New Tool Radar

Local AI

How to Load an MLX Model from a Python Script and Get a First Reply

Call load and generate from the mlx-lm Python API to load a model once in a script and print a first reply.

Schematic diagram with three steps: import load and generate from mlx_lm in a Python script, load an MLX model by name, and print the generated reply.

The command line is fine for a one-off answer, but a script needs the Python API. The README’s Python API section shows the whole shape: import load and generate, load a model by its repository name, build a prompt, and call generate. This guide follows that example exactly.

Write the script

Install the package first (pip install mlx-lm), then save this as first_mlx.py. It uses the README’s own example model and prompt:

from mlx_lm import load, generate

model, tokenizer = load("mlx-community/Mistral-7B-Instruct-v0.3-4bit")
prompt = "Write a story about Einstein"
text = generate(model, tokenizer, prompt=prompt, verbose=True)
print(text)

load returns the model and its tokenizer together. The first run downloads the model from the Hugging Face Hub, so run it online. The README says you can call help(generate) in a Python session to see a description of all the arguments.

Run it and read the output

python first_mlx.py

With verbose=True the call prints generation statistics as well as the text. If you want a chat-style prompt instead of a plain string, the README builds the prompt with tokenizer.apply_chat_template over a list of {"role": "user", "content": ...} messages with add_generation_prompt=True — use that form when the model is an instruction-tuned chat model. See the separate guide on serving an MLX model as a local API server when you need other programs to call the model instead of a script.

Check What you should see If you do not see it
Model loads The script prints a reply to the prompt The model name is wrong, or the download failed — check the repo name on the Hugging Face Hub
Verbose output Generation statistics print alongside the text You left out verbose=True
Second run is faster The model loads from cache instead of downloading The cache was cleared, or a different model name was used

Expected result. We checked the mlx-lm README for the load and generate example, the Mistral example repo, verbose=True, the chat-template prompt form, and help(generate). We did not run the script, so the output above is UNTESTED.

Limits

The model downloads on first use, so the first run needs internet and disk space. generate returns the full text at once; for text that appears as it is produced, use stream_generate instead. This runs on Apple silicon only.

Sources

Sources checked 2026-11-28.

See all