Automate 3000+ Apps AI Support Chatbot Rent Cloud GPUs Smart Forms Free Rank In AI Search Track Your Rankings
Automate 3000+ Apps AI Support Chatbot
Free Email Marketing AI Data Analyst Funnels + Email Free AI Agent Workspace Build AI Apps No Code No-Code AI Agents
Home » Local AI Image Generation on Mac » Call a Local Image Model

How to Call a Local Image Model From a Script or an AI Assistant

A local image model on a Mac becomes a tool the moment you wrap it in something callable. The simplest wrapper is a short shell script around the mflux generate command, which any program or AI coding assistant with terminal access can run. For batches, a Python script loads the model once and generates many images. For an AI assistant that should call it as a proper tool, a small MCP server with 1 function does the job. All 3 run on your own machine with no API key and no cost per image.

Why Bother Wrapping It

So the hosted image APIs charge per image, somewhere around 1 to 8 cents each depending on the model and size, they need a key, and they see every prompt and picture. That is fine for 10 images. For 500 placeholder graphics, a batch of blog headers, or an assistant that makes an image whenever a task calls for one, a model on your own Mac costs nothing per call and never sends anything out.

The other reason is control. A hosted API changes models, prices and content rules when it wants to. A model file on your disk does the same thing next year that it does today. A local image tool basically means "I can call this 1000 times and nobody is counting".

Now where it flips, a hosted API is faster per image, needs no memory on your machine, and offers models too big to run locally. If you need 1 excellent image now and then, use the API. The local tool wins on volume, privacy and repeatability.

The Ready Made Version: sitepix

If you would sooner install this than build it, sitepix is a free MIT licensed tool that does everything on this page in 1 package. It is a command line tool with a thin MCP server on top, built on mflux, and it adds the parts a website needs: named sizes like hero and og, a resize and crop to the exact pixels, WebP output, and file names taken from the prompt. It also checks free memory before each run and runs 1 job at a time.

uv tool install git+https://github.com/AIAppsAPI/sitepix
sitepix setup
sitepix "a lighthouse on a rocky coast at dusk" --size hero -o ./images

# as an MCP tool for an AI assistant
claude mcp add sitepix -- sitepix serve

The rest of this page shows how each layer works, which is worth knowing whether you use that tool or write your own.

Before You Start: Save a Quantized Model

Everything below assumes mflux is installed, as in generating images with mflux. Do this 1 step first, because a tool gets called over and over and load time and memory matter more than they do for a single image:

mflux-save \
  --path "$HOME/models/z-image-turbo_8bit" \
  --model z-image-turbo \
  --quantize 8

From a saved 8 bit copy, a 1024 by 1024 image peaks at about 7.5 GB of memory in the mflux project's own measurements, against about 26 GB when the same model loads from the download cache. For something that runs next to your other work, that is the difference between not noticing it and the whole machine slowing down.

Level 1: A Shell Wrapper

This is the whole tool for a lot of uses. A script that takes a prompt and an output path and hides the flags:

#!/bin/zsh
# ~/bin/genimage  "prompt"  output.png  [width] [height]
prompt="$1"
out="${2:-$HOME/Pictures/generated/$(date +%Y%m%d-%H%M%S).png}"
width="${3:-1024}"
height="${4:-1024}"

mkdir -p "$(dirname "$out")"
mflux-generate-z-image-turbo \
  --model "$HOME/models/z-image-turbo_8bit" \
  --prompt "$prompt" \
  --width "$width" --height "$height" \
  --steps 9 \
  --output "$out" >&2

echo "$out"
chmod +x ~/bin/genimage
genimage "flat illustration of a lighthouse at dusk" ~/Desktop/lighthouse.png 1280 720

Two details make it behave well as a tool. The generator's own progress output is sent to the error stream, and the only thing printed on the normal output is the path of the finished file, so whatever called the script gets back exactly 1 clean line. And it creates the output folder itself, so a call never fails on a missing directory.

An AI coding assistant that can run terminal commands can use this as it is. Tell it once, in your project instructions, that genimage "prompt" path makes an image, and it will call it when a task needs one. No server, no protocol.

The weakness is that every call loads the model from disk, generates, and exits. For 1 image at a time that is fine. For 50 it is 50 loads.

Level 2: Python, With the Model Loaded Once

mflux has a Python interface, and the win is that the model stays in memory between images. This script uses inline dependencies, so uv sets up everything it needs on the first run:

#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = ["mflux"]
# ///
import sys
from pathlib import Path
from mflux.models.z_image import ZImageTurbo

prompts_file = Path(sys.argv[1])          # one prompt per line
out_dir = Path(sys.argv[2])
out_dir.mkdir(parents=True, exist_ok=True)

model = ZImageTurbo(quantize=8)            # loaded once

for i, prompt in enumerate(prompts_file.read_text().splitlines(), start=1):
    if not prompt.strip():
        continue
    image = model.generate_image(
        prompt=prompt,
        seed=i,
        num_inference_steps=9,
        width=1024,
        height=1024,
    )
    path = out_dir / f"{i:03d}.png"
    image.save(str(path))
    print(path)
uv run batch.py prompts.txt ./out

Keep in mind what staying loaded costs. With the model held in memory the footprint is the full weight size, about 11 GB for Z-Image Turbo at 8 bit, not the 7.5 GB of a single command line run that frees parts of the model as it goes. On a 16 GB Mac, the 1 shot shell wrapper is the safer design. On 32 GB and up, keeping it loaded is the faster one.

Level 3: An MCP Server for an AI Assistant

MCP, the Model Context Protocol, is the standard way to give an AI assistant a tool with a name, a description and typed inputs. Instead of the assistant guessing at a shell command, it sees a function called generate_image and calls it properly. The Python MCP library makes a server short. This uses version 2 of the library, where the server class is named MCPServer. Older examples import FastMCP from mcp.server.fastmcp, which is the same thing under its version 1 name and no longer exists in version 2:

#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.11"
# dependencies = ["mflux", "mcp>=2"]
# ///
import time
from pathlib import Path
from mcp.server.mcpserver import MCPServer
from mflux.models.z_image import ZImageTurbo

OUT_DIR = Path.home() / "Pictures" / "generated"
OUT_DIR.mkdir(parents=True, exist_ok=True)

mcp = MCPServer("local-image")
_model = None

def get_model():
    global _model
    if _model is None:
        _model = ZImageTurbo(quantize=8)   # load on first use, then keep
    return _model

@mcp.tool()
def generate_image(prompt: str, width: int = 1024, height: int = 1024, seed: int = 0) -> str:
    """Generate an image from a text prompt with a local model. Returns the saved file path."""
    width = max(256, min(width, 1536))
    height = max(256, min(height, 1536))
    image = get_model().generate_image(
        prompt=prompt,
        seed=seed or int(time.time()),
        num_inference_steps=9,
        width=width,
        height=height,
    )
    path = OUT_DIR / f"{time.strftime('%Y%m%d-%H%M%S')}.png"
    image.save(str(path))
    return str(path)

if __name__ == "__main__":
    mcp.run()

Register it with the assistant. For Claude Code that is 1 command, and other assistants that support MCP take the same command in their own config file:

claude mcp add local-image -- uv run /Users/you/tools/image_server.py

After that the assistant has a tool it can call on its own judgment. Ask it to build a landing page and it can generate the hero image, save it into the project, and reference it in the HTML, without you leaving the conversation.

Some design choices in that server are deliberate. The tool returns a file path, not the image data, because a path is tiny and the assistant can then move or reference the file, while a full image would flood its working memory. The model loads on the first call instead of at startup, so the server costs nothing until it is used. And the docstring matters more than it looks, it is what the assistant reads to decide when and how to call the tool, so write it plainly.

If you would sooner not write one, there are community projects that put a server in front of mflux, including one that offers an MCP tool and an endpoint in the same shape as the OpenAI image API, so existing code written for that API can be pointed at your Mac. Check any such project's current state and read its code before running it, since it will be executing on your machine.

The ComfyUI Route

If your generation is a multi step ComfyUI workflow, ComfyUI is already a server. The same local address that serves its interface accepts jobs over HTTP. Export a workflow in API format from the interface, then post it:

curl -s -X POST http://127.0.0.1:8188/prompt \
  -H "Content-Type: application/json" \
  -d "{\"prompt\": $(cat workflow_api.json)}"

The response carries an id for the queued job, and the output lands in ComfyUI's output folder. To change the prompt per call, your script edits the text field of the right node in the JSON before posting. It is more plumbing than the mflux routes, and it is the way to automate anything that needs a graph, such as generate then upscale then animate. Setup is in ComfyUI on Mac.

Limits Worth Setting

Cap the size and steps. An assistant asked for "a huge detailed image" may request 4096 by 4096, which will take forever or run the Mac out of memory. Clamp the inputs in code, as the server above does.

One job at a time. Two generations at once do not run twice as fast, they fight for the same memory. If several things can call the tool, queue them.

One output folder. Write everything to a known place, and clear it out now and then. A tool called in a loop fills a disk quietly.

Keep it local. Bind any server to 127.0.0.1 and do not expose it to the network or the internet. An open image endpoint is free compute for whoever finds it.

Mind what else is running. If a large language model is loaded on the same Mac, add its memory to the image model's before deciding whether to keep the image model loaded. On a 64 GB machine both usually fit. Check with sysctl vm.swapusage after a few calls, and if swap is growing, switch to the load per call design.

Adding Your Own LoRA

A tool that makes generic images is useful. One that makes images in your brand's style or of your product is more so. The command line wrapper takes it as 2 more flags, --lora-paths and --lora-scales, and from then on every call comes out in your style. Training that LoRA on the same Mac is covered in how to train a LoRA on a Mac.

Start with the shell wrapper. It takes 5 minutes, it works with anything that can run a command, and it loads nothing when idle. Move to the Python loop when you need batches, and to an MCP server when you want an AI assistant to call it as a real tool.