Local Image Generation on Apple Silicon: A Practical Guide to mflux
The two most common elements in the universe are hydrogen and stupidity, Harlan Ellison
Generating high-quality images locally has historically required massive GPU resources and complex background server setups. However, with the advent of Apple Silicon and the MLX framework, state-of-the-art generative models are now accessible directly on your Mac.
This article provides a practical, no-nonsense guide to mflux, a lightweight Python library and CLI that runs models like FLUX.2 Klein and Z-Image Turbo natively on Apple Silicon. We will cover everything from navigating Hugging Face’s gated repositories and understanding disk requirements, to building a hardened Python wrapper for reliable automation and seamlessly integrating mflux into your OpenClaw autonomous agent workflows. Whether you are a developer building local AI tools or an enthusiast exploring on-device generation, this guide will help you avoid common pitfalls and get your local image pipeline running smoothly.
mflux — Local Image Generation from Python on Apple Silicon
mflux runs state-of-the-art generative image models — Z-Image-Turbo, FLUX.1-schnell, FLUX.2 Klein (4B and 9B), and a growing list including Krea 2, Ideogram 4, Qwen-Image, and FIBO 2 — natively on Apple Silicon via MLX. Because it is a Python library and CLI rather than a background server, your script blocks until the PNG is written to disk. There is no port to manage, no async polling loop, and no daemon to keep alive.
That synchronous model is mflux’s defining advantage for automation. It is also where most integration mistakes happen: treating a slow, memory-hungry, license-gated model download as if it were a fast, unconditional function call.
What mflux Actually Is
mflux is a line-by-line MLX port of several state-of-the-art generative image models from Hugging Face Diffusers and Transformers, implemented from scratch in MLX using only the tokenizers from Transformers. The design philosophy is deliberately minimal and explicit — “Karpathy style,” in the project’s own words — which means the CLI surface is large but predictable, and the Python API mirrors the CLI closely enough that you can move between them without relearning concepts.
Each model family gets its own CLI entry point: mflux-generate-flux2 for FLUX.2 Klein, mflux-generate-z-image-turbo for Z-Image Turbo, mflux-generate for FLUX.1, and so on. The Python API is organized by model under mflux.models.<family>, with variant classes such as Flux2Klein and ZImageTurbo.
For Python automation, this matters because you have two integration paths:
- Shell out to the CLI via subprocess.run — simple, isolated, and exactly synchronous.
- Import the Python API directly — more control over the model object, useful when you want to generate multiple images from one loaded model or manipulate latents.
2. Installation
# Install into your script's virtual environment
pip install mflux
# Or globally as a CLI tool
uv tool install mflux
# If you encounter the hf_transfer error — ValueError: Fast download using 'hf_transfer'
# is enabled but 'hf_transfer' package is not available — install with the extra included:
uv tool install mflux --with hf_transfer
# This enables faster model downloads from Hugging Face.
# Verify that the CLI entry points exist:
uv tool list
3. Model Access and Gated Repositories
There are two different gates
-
FLUX.1-schnell is gated on Hugging Face. You must open the model page, log in, and click Agree and access repository. The original draft covered this correctly.
-
FLUX.2 Klein 9B is also gated, but the mechanics are slightly different and the license is stricter. black-forest-labs/FLUX.2-klein-9B is set to gated: “auto” on Hugging Face, and the model page surfaces an “Agree and access repository” button for the FLUX Non-Commercial License Agreement and the Acceptable Use Policy. Clicking it grants access immediately — there is no manual review queue.
The critical detail: CLI token authentication alone gets a 403. Logging in with hf auth login is necessary but not sufficient. The browser-side agreement must be acknowledged separately. Even if hf auth whoami succeeds, the gated-repo error will persist until the license form has been submitted.
The error you will see.
If the license has not been accepted, mflux fails with:
Cannot access gated repo for url https://huggingface.co/black-forest-labs/FLUX.2-klein-base-9B/resolve/.../text_encoder/config.json
This is not an authentication failure. It is a terms-acceptance failure. The fix is a browser visit to the model page, not a new token.
Hugging Face login. Create a Read token at huggingface.co/settings/tokens, then:
hf auth login
Paste the token when prompted. Notice that login and license acceptance are independent steps.
Disk and download cost
The 9B model is large. On first invocation, mflux downloads roughly 20 files totaling about 30 GB, landing at around 32 GB in ~/.cache/huggingface/hub/models--black-forest-labs--FLUX.2-klein-9B/ after download. The 4B model is about half that, roughly 15 GB on disk. Budget at least 40 GB of free space before starting with the 9B variant.
The model cache location depends on version. Newer mflux uses platform-native caching via platformdirs, with macOS-idiomatic locations under ~/Library/Caches/mflux/, while Hugging Face downloads also land in the standard ~/.cache/huggingface hub directory.
4. The CLI: Flags That Actually Matter
The core flags
| Flag | Purpose | What to know |
|---|---|---|
--model |
Selects the model variant | Accepts predefined names (flux2-klein-9b, flux2-klein-4b), local paths, or full HF repos |
--quantize / -q |
Quantization level | 4 or 8; 8 is the recommended default for quality/memory balance |
--low-ram |
Reduce peak memory | Requests a memory-saving execution mode; it may run more slowly |
--steps |
Sets the number of image-generation sampling steps | The fast model is designed for few steps; the base model generally uses more |
--guidance |
Controls how strongly generation is guided by the prompt | The appropriate value depends on the model; higher is not always better |
--width / --height |
Set the image dimensions | 1280 × 720 is a 16:9 landscape image. Larger dimensions generally need more memory and time |
--seed |
Sets the random seed | Same seed + same settings produces pixel-identical output |
--output |
Sets the path and filename for the generated image | Use a new filename if you want to keep earlier results |
Scripts
These scripts ask mflux-generate-flux2 to create an image from a text prompt. The first uses the fast/distilled Klein 9B model; the second uses the non-distilled base 9B model. The settings differ because the two model variants are intended to use different sampling step counts and guidance strengths.
mflux-generate-flux2 \
--model flux2-klein-9b \
--quantize 8 \
--low-ram \
--steps 4 \
--guidance 1.0 \
--width 1280 \
--height 720 \
--seed 42 \
--prompt "your prompt" \
--output output.png
If you specifically want the base (non-distilled) 9B model and 50 steps:
mflux-generate-flux2 \
--model flux2-klein-base-9b \
--quantize 8 \
--low-ram \
--steps 50 \
--guidance 3.5 \
--width 1280 \
--height 720 \
--seed 42 \
--prompt "your prompt" \
--output output.png
5. A Hardened Python Wrapper
The original subprocess.run(cmd, check=True) is the right primitive, but it fails silently in ways that matter for automation: a gated-repo error raises CalledProcessError with a long stderr, and the caller has no structured way to distinguish “license not accepted” from “out of memory” from “model not found.”
Here is a more robust version:
# =====================================================================
# IMPORTS
# In Python, we "import" modules (toolkits) that give us extra abilities
# beyond basic math and text manipulation.
# =====================================================================
# 'subprocess' allows Python to run other programs on your computer,
# just like you would type commands into a Terminal or Command Prompt.
import subprocess
# 'shutil' stands for "shell utilities". It helps with file operations
# and finding out if certain programs are installed on your computer.
import shutil
# 'pathlib' is the modern Python toolkit for working with file and folder
# paths across different operating systems (Mac, Windows, Linux).
from pathlib import Path
# =====================================================================
# CUSTOM ERROR DEFINITION
# =====================================================================
# Here we create a custom error type called 'MfluxGenerationError'.
# By putting '(RuntimeError)' in parentheses, we tell Python that our
# new error is a specific category of a standard 'RuntimeError'.
# Making a custom error makes it easier to know *exactly* what went wrong later.
class MfluxGenerationError(RuntimeError):
# Triple quotes create a "docstring" – an official description of what
# this class or function does.
"""Raised when mflux fails, with the underlying stderr preserved."""
# 'pass' is a keyword that means "do nothing". We use it here because
# we don't need to add any special code to our custom error;
# inheriting behavior from 'RuntimeError' is enough.
pass
# =====================================================================
# MAIN FUNCTION DEFINITION
# =====================================================================
# 'def' starts a function definition named 'generate_image'.
# Inside the parentheses are the "parameters" (inputs) the function accepts.
#
# Notice the format: `parameter_name: data_type = default_value`
# - `: str`, `: int`, `: float`, `: bool` are "Type Hints". They tell the
# programmer what kind of data is expected (text, whole number, decimal, True/False).
# - `= "output.png"` is a default value. If you don't provide this input when
# calling the function, Python will automatically use this default.
def generate_image(
prompt: str, # Required: The text description of the image you want.
output_path: str = "output.png", # Optional: Where to save the image file.
model: str = "flux2-klein-9b", # Optional: Which AI model to use.
quantize: int = 8, # Optional: Compression level (8-bit saves memory).
low_ram: bool = True, # Optional: Whether to use low-memory mode (True/False).
steps: int = 4, # Optional: How many passes the AI takes to draw the image.
guidance: float = 1.0, # Optional: How strictly the AI follows your prompt (decimal).
width: int = 1280, # Optional: Image width in pixels.
height: int = 720, # Optional: Image height in pixels.
seed: int | None = 42, # Optional: A number to make randomness repeatable.
# `int | None` means it can be a whole number OR 'None' (empty).
) -> Path: # `-> Path` is a type hint saying this function will return a 'Path' object at the end.
# -----------------------------------------------------------------
# STEP 1: Check if the required tool is actually installed
# -----------------------------------------------------------------
# `shutil.which()` looks at your computer's "PATH" to see if the command "mflux-generate-flux2" exists.
# If it returns `None`, the program isn't installed (or can't be found).
if shutil.which("mflux-generate-flux2") is None:
# `raise` immediately stops the function and triggers our custom error
# with a helpful message telling the user how to fix the problem.
# Note: Python automatically joins strings that are next to each other on separate lines.
raise MfluxGenerationError(
"mflux-generate-flux2 not found on PATH. "
"Install with `uv tool install mflux` or `pip install mflux`."
)
# -----------------------------------------------------------------
# STEP 2: Build the terminal command as a Python list
# -----------------------------------------------------------------
# When using `subprocess` to run a terminal command, it wants the command
# broken up into a list of individual words (strings), inside square brackets `[]`.
#
# IMPORTANT: Terminal commands only understand text (strings). Because inputs
# like `quantize`, `steps`, and `width` are numbers (`int` or `float`), we must
# wrap them in `str()` to convert them into text before putting them in the list.
cmd = [
"mflux-generate-flux2",
"--model", model,
"--quantize", str(quantize),
"--steps", str(steps),
"--guidance", str(guidance),
"--width", str(width),
"--height", str(height),
"--prompt", prompt,
"--output", output_path,
]
# If `low_ram` is True, we need to add the "--low-ram" flag to our command list.
if low_ram:
# `.insert(3, ...)` puts "--low-ram" at position 3 in the list (right after `model`).
# Remember, Python (as many other programming languages) counts list positions starting from 0!
# Position 0: "mflux-generate-flux2", 1: "--model", 2: model, 3: "--low-ram"
cmd.insert(3, "--low-ram")
# If the user provided a `seed` (meaning it is not `None`), we add it to the command.
if seed is not None:
# `.extend()` adds multiple items to the very end of our `cmd` list.
cmd.extend(["--seed", str(seed)])
# -----------------------------------------------------------------
# STEP 3: Run the command and watch out for errors
# -----------------------------------------------------------------
# `try:` starts an error-handling block. Python will attempt to run the code
# inside the `try` block. If it crashes, instead of stopping the whole program,
# Python jumps down to the `except` block to handle the crash gracefully.
try:
# `subprocess.run()` actually executes our command list in the background.
# - `cmd`: The list of command words we have already built.
# - `check=True`: Tells Python to **automatically trigger an error** (`CalledProcessError`)
# if the command fails (returns a non-zero exit code).
# - `capture_output=True`: Tells Python to record whatever text the program prints out,
# so we can read its error messages if it fails.
# - `text=True`: Tells Python to decode that recorded output as normal readable text
# (strings) instead of raw computer bytes.
subprocess.run(cmd, check=True, capture_output=True, text=True)
# If `subprocess.run` fails (because of `check=True`), Python catches the
# `CalledProcessError` here and names the error object `exc` (short for exception)
# so we can inspect it.
except subprocess.CalledProcessError as exc:
# Command-line programs print normal messages to `stdout` (standard output)
# and error messages to `stderr` (standard error).
# Here, we grab the error text from `exc.stderr`.
# The `or ""` is a safety trick (defensive programming): if `exc.stderr` is `None` (empty),
# it falls back to an empty string `""` so our text searches below don't crash.
stderr = exc.stderr or ""
# --- Error Diagnosis 1: Hugging Face Permission Issue ---
# We check if the phrase "Cannot access gated repo" is in the error text,
# OR if the word "gated" is in a lowercase version (`.lower()`) of the error text.
if "Cannot access gated repo" in stderr or "gated" in stderr.lower():
# An 'f-string' (`f"..."`) lets us insert variables directly into text
# using curly braces, like `{model}`.
# `from exc` attaches the original technical error to our friendly custom error,
# preserving the full history of what went wrong for debugging.
raise MfluxGenerationError(
f"Model '{model}' is gated on Hugging Face. "
"Open the model page in a browser, log in, and click "
"'Agree and access repository'. Then run `hf auth login`. "
"Token login alone does not satisfy the gate."
) from exc
# --- Error Diagnosis 2: Not Enough Computer Memory (RAM/VRAM) ---
# We check if the error message complains about "memory".
if "out of memory" in stderr.lower() or "memory" in stderr.lower():
raise MfluxGenerationError(
"mflux ran out of memory. Try --quantize 4, --low-ram, "
"--vae-tiling, a smaller model (4B), or a smaller resolution."
) from exc
# --- Error Diagnosis 3: Anything else ---
# If it failed for some other unknown reason, we raise our custom error
# and show the program's exit code (`exc.returncode`) along with the
# last 2000 characters of the error message (`stderr[-2000:]`).
# Slicing with `[-2000:]` prevents dumping a massive wall of text to the screen.
raise MfluxGenerationError(
f"mflux failed with exit code {exc.returncode}:\n{stderr[-2000:]}"
) from exc
# -----------------------------------------------------------------
# STEP 4: Verify the output file actually exists and isn't broken
# -----------------------------------------------------------------
# Convert the text string `output_path` (e.g., "output.png") into a
# smart `Path` object, which has built-in tools for checking files.
out = Path(output_path)
# Sometimes a command-line tool claims it succeeded, but silently failed to
# write the file. Here we double-check two things:
# 1. `not out.exists()`: Did the file fail to appear on the hard drive?
# 2. `out.stat().st_size == 0`: Does the file exist, but its size is 0 bytes (empty)?
if not out.exists() or out.stat().st_size == 0:
raise MfluxGenerationError(
f"mflux exited successfully but '{output_path}' is missing or empty."
)
# -----------------------------------------------------------------
# STEP 5: Success! Return the result
# -----------------------------------------------------------------
# Everything worked! Send the `Path` object pointing to the new image
# back to whatever part of the program called this function.
return out
6. The Python API Alternative
If you are generating multiple images in one process, loading the model once and calling generate_image repeatedly is faster than shelling out each time.
In our previous code, we have used subprocess.run() to run a terminal command. Programmers call this “shelling out” (asking the operating system’s command shell to run an outside program).
AI models are huge—often several gigabytes in size.
- Shelling out (our previous code): Imagine hiring a chef to make a pancake. The chef comes to your house, unpacks all their heavy pots and pans, makes one pancake, washes up, packs everything back into their car, and leaves. If you want 5 pancakes, they have to unpack and pack up 5 separate times. That wastes a ton of time!
- Loading the model once in Python (The code below): Instead of using the terminal command, you bring the AI directly inside your Python script. The chef comes over, unpacks their heavy kitchen gear once (loading the gigabytes of AI data into your computer’s memory), and can now flip 5 pancakes in a row instantly.
Example 1: Using the “Z-Image Turbo” Model
Here is the first snippet:
# =====================================================================
# 1. IMPORTING THE AI BLUEPRINT
# =====================================================================
# Instead of running a terminal command, we reach directly inside the
# 'mflux' Python library that is installed on your computer.
# Notice the dots (.): You can think of them like folders!
# Inside 'mflux' -> go to 'models' -> go to 'z_image' -> and grab 'ZImageTurbo'.
from mflux.models.z_image import ZImageTurbo
# =====================================================================
# 2. LOADING THE MODEL INTO MEMORY (Unpacking the kitchen!)
# =====================================================================
# 'ZImageTurbo' is a Class (a blueprint for an AI generator).
# By putting parentheses () after it, we build a working copy of it and
# store it in a variable named 'model'.
#
# NOTE: This single line takes a few seconds to run because Python is
# moving gigabytes of AI brainpower from your hard drive into your RAM.
# 'quantize=8' compresses the AI to 8-bit so it uses less memory.
model = ZImageTurbo(quantize=8)
# =====================================================================
# 3. GENERATING THE IMAGE
# =====================================================================
# Now that 'model' is loaded and ready, we ask it to do an action by
# typing a dot (.) and calling its built-in function: '.generate_image()'.
#
# Notice we don't have to convert numbers like 42 or 1280 into text with str()
# like we did in the terminal version! Python functions happily accept real numbers.
image = model.generate_image(
prompt="A puffin standing on a cliff", # What you want the AI to draw.
seed=42, # The starting random number (for repeatable results).
num_inference_steps=9, # How many passes the AI takes to refine the image
# (Notice this was called "--steps" in the terminal).
width=1280, # Width in pixels.
height=500, # Height in pixels.
)
# At this exact moment, the picture is finished! However, it only exists inside
# the variable 'image' in your computer's temporary memory (RAM). It is not a file yet.
# =====================================================================
# 4. SAVING TO YOUR HARD DRIVE
# =====================================================================
# Now we tell the 'image' variable to save itself onto your hard drive
# as a real file named "puffin.png".
image.save("puffin.png")
Example 2: Using the “FLUX.2 Klein” Model
Some AI models come in multiple sizes (for example, a smaller 4-Billion parameter brain vs. a larger 9-Billion parameter brain). Because of this, Flux2Klein requires one extra step: you have to hand it a Configuration object so it knows which version of itself to load.
# =====================================================================
# 1. IMPORTS
# =====================================================================
# First, we import 'ModelConfig', which is a menu of settings for different models.
from mflux.models.common.config import ModelConfig
# Next, we import the 'Flux2Klein' AI blueprint itself.
from mflux.models.flux2.variants import Flux2Klein
# =====================================================================
# 2. CONFIGURING AND LOADING THE MODEL
# =====================================================================
# Just like before, this step loads the heavy AI into your computer's memory.
# However, Flux2Klein needs two pieces of information to start up:
# 1. 'model_config': We use ModelConfig.flux2_klein_9b() to select the "9-Billion" size variant.
# 2. 'quantize=8': We tell it to compress the model to 8-bit to save RAM.
model = Flux2Klein(
model_config=ModelConfig.flux2_klein_9b(),
quantize=8,
)
# =====================================================================
# 3. GENERATING THE IMAGE
# =====================================================================
# Once loaded, generating the image works the exact same way as ZImageTurbo!
# We call 'model.generate_image()' and store the resulting picture in 'image'.
image = model.generate_image(
prompt="A cinematic wide shot of a Galilean shoreline at dawn",
seed=42,
num_inference_steps=4, # Flux2 Klein is super fast and only needs 4 steps!
width=1280,
height=720,
)
# =====================================================================
# 4. SAVING TO YOUR HARD DRIVE
# =====================================================================
# Write the image from temporary memory onto your hard drive as "output.png".
image.save("output.png")
The exact import paths and constructor signatures have shifted across mflux versions. For production automation, the CLI wrapper is more stable across upgrades; the Python API is faster for batches but more sensitive to version drift. A reasonable rule: use the CLI for one-off generation and the Python API for loops where model load time dominates.
Bonus: How do you actually generate multiple images fast?
To show you why the paragraph said this method is faster for multiple images, here is what it looks like to generate three images in a row. Notice that we only load model once at the top:
from mflux.models.z_image import ZImageTurbo
# 1. Load the heavy model ONCE (Slow - takes several seconds)
model = ZImageTurbo(quantize=8)
# 2. Make Image #1 (Fast!)
img1 = model.generate_image(prompt="A red apple", seed=1, num_inference_steps=9, width=512, height=512)
img1.save("apple.png")
# 3. Make Image #2 immediately without reloading the model (Fast!)
img2 = model.generate_image(prompt="A yellow banana", seed=2, num_inference_steps=9, width=512, height=512)
img2.save("banana.png")
# 4. Make Image #3 immediately without reloading the model (Fast!)
img3 = model.generate_image(prompt="A purple grape", seed=3, num_inference_steps=9, width=512, height=512)
img3.save("grape.png")
7. Integration with OpenClaw
mflux is a natural fit for OpenClaw because it is fully local: no API key, no rate limit, no prompt leaving the machine.
- Fully Local (On-Device): Normally, when you ask an AI (like ChatGPT or Midjourney) to make a picture, your request is sent over the internet to a giant supercomputer owned by a company. “Local” means your own computer does 100% of the brainwork right at your desk.
- No API Key: An API key is like a digital password and credit card linked together that companies give you so they can charge you per image. Because your computer does the work, you don’t need an account or a password.
- No Rate Limit: Cloud companies often say, “Stop! You can only make 10 images per hour.” On your own computer, you can make as many as you want, 24/7.
- No prompt leaving the machine: Complete privacy. Nobody on the internet can see what you are typing or generating.
- Apache 2.0: This is a software license that basically means “100% free to use for personal or commercial projects with no strings attached.”
- Requirements (Apple Silicon M1+, RAM, Quantization): mflux was specially built for modern Mac computers (which use Apple’s M1, M2, M3, or M4 chips). RAM is your computer’s short-term working desk space. A bigger desk (16 GB) is best, an 8 GB desk works if you “quantize” (shrink/compress) the AI model so it fits on the smaller desk.
There is an existing OpenClaw skill that wraps it. The skill defaults to FLUX.2 Klein 4B (fastest, Apache 2.0) and exposes Z-Image Turbo as the higher-quality option, with all processing on-device. Requirements are an Apple Silicon Mac (M1 or later), Python 3.10+, and macOS 13.5+; 16 GB RAM recommended, 8 GB workable with quantization.
The trade-off versus OpenRouter free models is the usual local-vs-cloud one.
- Using OpenRouter (Cloud): You don’t need a powerful Mac, and you don’t have to download huge files. Downside: They limit how many images you can make per day, and on free plans, they might read and save your prompts to train their future AIs.
- Using mflux (Local): Unlimited free images and total privacy. Downside: You must own a modern Mac, and the very first time you run it, it has to download the AI brain from the internet—which is a massive file (10 to 20+ Gigabytes!). After the first time, it stays saved on your hard drive.
# You type this into your Mac's Terminal app (not inside Python).
# It tells the 'openclaw' program to download and install the 'mflux'
# skill created by the user '@pjain'.
openclaw skills install @pjain/mflux
# The code is shown below
code ~/macOS/claude/skills/mflux/scripts/generate_image.py
# Installs mflux as a command-line tool.
uv tool install --upgrade --prerelease allow mflux
# It checks that the directory containing that command is on my shell’s PATH. The message says it already is.
uv tool update-shell
... Executable directory /Users/nmaximo7/.local/bin is already in PATH
# Test it
python generate_image.py "Generate a banana driving a car"
For a daily devotional workflow, mflux is attractive precisely because the image step is synchronous and local — the agent outputs the command, the subprocess blocks, the PNG appears, and the next step proceeds. There is no async placeholder to manage and no provider that can rate-limit you mid-prayer.
- Synchronous (“The subprocess blocks”): Imagine putting bread in your toaster. You stand there and wait (“block” yourself from doing anything else) for 60 seconds, the toast pops up, you butter it, and you eat. It is simple, predictable, and step-by-step. That is how mflux works here: Python asks for the image, freezes and waits patiently until the image is 100% finished, and then moves to the next line of code.
- Asynchronous (“Async placeholder”): Imagine ordering pizza delivery from a busy restaurant (the Cloud). They give you a paper receipt (“an async placeholder”), and your code has to keep checking the front door every 10 seconds asking, “Is the picture here yet? How about now?” Even worse, the restaurant might suddenly say, “Sorry, we are too busy today, order canceled!” (“rate-limited mid-prayer”). Local and synchronous avoids all that headache.
# =====================================================================
# IMPORTS
# =====================================================================
# 'subprocess' lets Python run terminal commands behind the scenes.
import subprocess
import sys
# 'Path' helps Python understand and work with files on your hard drive.
from pathlib import Path
# =====================================================================
# THE IMAGE GENERATION FUNCTION
# =====================================================================
# Here we create our function. Unlike the previous script,
# this one only asks for TWO inputs:
# 1. 'prompt': What you want to draw (Required text string).
# 2. 'output_path': What to name the saved file (Optional, defaults to "output.png").
# `-> Path` means when the function finishes, it will hand back the file's Path.
def generate_image(prompt: str, output_path: str = "output.png") -> Path:
resolved_path = Path(output_path).expanduser()
# Here we build the terminal command as a list of words in square brackets [].
# Notice that all the numbers ("8", "50", "3.5", "1280", "720") are already
# inside quotation marks! Because they are hardcoded as text strings right
# from the start, we don't need to use `str()` to convert them like before.
cmd = [
"mflux-generate-flux2", # The program we are calling
"--model",
"flux2-klein-base-9b", # We are using the "base" 9-Billion model (higher quality, slower)
"--quantize",
"8", # Shrink the model to 8-bit so it uses less Mac memory (RAM)
"--low-ram", # Turn on extra memory-saving tricks
"--steps",
"50", # Take 50 passes to draw the image (Base models need ~50 steps; fast models need ~4)
"--guidance",
"3.5", # Follow the prompt pretty closely (3.5 is standard for Base models)
"--width",
"1280", # 1280 pixels wide
"--height",
"720", # 16:9 # 720 pixels tall (1280x720 is standard widescreen TV shape, known as 16:9)
"--prompt",
prompt, # Plug in the 'prompt' variable that was passed into the function
"--output",
str(resolved_path),
]
# This is the "Synchronous / Blocking" step mentioned in the article!
# Python runs the command and PAUSES right here on this line until the
# image is completely finished generating (which might take a minute or two).
# `check=True` means: "If mflux crashes, stop the Python script immediately and show an error."
subprocess.run(cmd, check=True)
# Once `subprocess.run` finishes unpausing, the file is ready on your hard drive!
# We wrap the filename in a `Path()` object and return it.
return Path(output_path)
# =====================================================================
# THE "START BUTTON" (Main Execution Block)
# =====================================================================
# Up until this point, Python has only *memorized* how `generate_image` works,
# like reading a recipe without actually cooking it.
#
# `if __name__ == "__main__":` is a famous Python phrase.
# In plain English, it asks: "Did the user run THIS file directly?"
# - If YES (you ran this file): It runs the indented code below (starts cooking!).
# - If NO (another Python file imported this file just to borrow the `generate_image`
# function): It skips the code below so it doesn't accidentally generate a picture of Jesus
# when another script just wanted to borrow the tool.
if __name__ == "__main__":
# sys.argv[0] is always the name of the script itself ("generate_image.py")
# sys.argv[1] catches the FIRST thing in quotes after the script ("Image of Jesus as a shepherd")
# sys.argv[2] catches the SECOND thing in quotes ("~/Downloads/output.png")
user_prompt = sys.argv[1]
save_location = sys.argv[2]
# Pass them right into the function we learned earlier!
generate_image(prompt=user_prompt, output_path=save_location)
You may get Cannot access gated repo for url https://huggingface.co/black-forest-labs/FLUX.2-klein-base-9B/resolve/32773329fbe7e81a90ef971740e8ba4b0364ecf3/text_encoder/config.json. Like schnell, black-forest-labs/FLUX.2-klein-base-9B is gated on Hugging Face—accept its license once on HF
This is the skill and the call is simply /mflux “Image of Jesus as a shepherd". When you type it into OpenClaw, a 4-step chain reaction happens behind the scenes:
- You type the command: Using /mflux tells OpenClaw: “Hey! Go open the instruction binder labeled mflux and read SKILL.md.”.
- OpenClaw reads the SKILL.md file: OpenClaw reads the English sentences in the file you just shared. At the bottom, it sees the rule: “When the user requests an image, run…”
- OpenClaw fills in the blank: OpenClaw takes your words (“Image of Jesus as a shepherd”) and swaps them into the placeholder (“USER’S IMAGE PROMPT”).
- OpenClaw runs the Python script from earlier: OpenClaw opens your Mac’s Terminal in the background and runs:
python ~/macOS/skills/mflux/generate_image.py "Image of Jesus as a shepherd" "~/Downloads/output.png". Wait a minute or two, and poof—output.png appears in your Mac’s Downloads folder!
---
description: Local image generation using Apple MLX via mflux — FLUX.2 Klein 4B (fast, Apache 2.0) and Z-Image Turbo (quality) models
---
# =====================================================================
# 1. THE "INDEX CARD" (YAML Frontmatter)
# =====================================================================
# Notice the three dashes (---) above and below the description?
# In Markdown files, putting three dashes at the very top creates a
# "Frontmatter" block (think of it like the label on the outside of a folder).
#
# OpenClaw might have 50 different skills installed. Instead of reading 50 huge
# files every time you chat with it, OpenClaw just scans these short 1-sentence
# labels between the `---` dashes to know what skills it has available!
# (Quick Jargon Note: "Apple MLX" is special software invented by Apple engineers
# specifically to make AI run super fast on M1/M2/M3/M4 Mac chips!)
# =====================================================================
# 2. THE DOCUMENT HEADINGS
# =====================================================================
# In a Markdown (.md) file, two hashtags (##) mean "Make this a Big Bold Heading".
# It helps the AI understand how the document is organized.
## SKILL.md — mflux
## Name
# This tells OpenClaw the exact name of the skill so that when you type
# `/mflux`, it knows this is the right file.
mflux
# =====================================================================
# 3. THE BACKGROUND KNOWLEDGE FOR THE AI
# =====================================================================
## Description
# This paragraph gives the AI context about the tool.
# Why does the AI need to know this? Because if you ask OpenClaw a question like,
# "Hey, if I make an image, is it private?" or "Which models can you use?",
# the AI reads this paragraph and can answer you accurately!
#
# Quick Jargon Notes on "4B" and "6B":
# - "4B" means 4 Billion parameters (think of parameters like microscopic brain connections).
# 4 Billion is smaller and faster.
# - "6B" means 6 Billion parameters. Slightly larger brain = higher quality art!
Generate images locally using Apple Silicon via the mflux MLX implementation. Supports FLUX.2-klein-4B (default, fastest 4-step generation, Apache 2.0 licensed) and Z-Image-Turbo (6B, highest quality). All processing is on-device — no cloud, no API keys, no data leaving your Mac.
# =====================================================================
# 4. THE DIRECT ORDER (The Most Important Part!)
# =====================================================================
# Here, we literally just talk to the AI in plain English and tell it what
# terminal command to type when you ask for a picture:
When the user requests an image, run:
python ~/macOS/skills/mflux/generate_image.py "USER'S IMAGE PROMPT" "~/Downloads/output.png"