New Tool Radar

Local AI

How to Stream Generated Text Token by Token with the MLX LM Python API

Use stream_generate from mlx-lm so each piece of text prints as it is produced instead of waiting for the whole reply.

Schematic diagram with three steps: load an MLX model in Python, loop over stream_generate, and print each response piece as it arrives.

generate waits until the whole reply is finished before it returns anything, which feels slow for a long answer. The README’s Streaming section gives the alternative: stream_generate yields a generation response object for each piece, so you can print text as it arrives.

Write the streaming loop

Following the README example:

from mlx_lm import load, stream_generate

repo = "mlx-community/Mistral-7B-Instruct-v0.3-4bit"
model, tokenizer = load(repo)
prompt = "Write a story about Einstein"
messages = [{"role": "user", "content": prompt}]
prompt = tokenizer.apply_chat_template(
    messages, add_generation_prompt=True,
)
for response in stream_generate(model, tokenizer, prompt, max_tokens=512):
    print(response.text, end="", flush=True)
print()

Two details matter. First, each yielded item is a response object, so print response.text, not the object itself — older versions of the README printed the yielded item directly, and the current README prints response.text. Second, end="" and flush=True keep the pieces on one line and push them to the terminal immediately; without flush=True the output may sit buffered and appear in bursts.

When to stream, and when not to

Stream when a person is watching the answer appear, or when you want to show progress on a long generation. Keep generate when you need the complete text as one string to save or post-process. The README says both functions accept sampler and logits_processors, so sampling settings work the same in either form.

Check What you should see If you do not see it
Pieces appear live Text prints piece by piece before the reply finishes You called generate instead of stream_generate, or output is buffered — add flush=True
Full reply arrives The loop ends with the complete text printed max_tokens cut it off — raise max_tokens and try again
Response object You print response.text Printing the response object itself shows its fields, not the text

Expected result. We checked the mlx-lm README Streaming section for stream_generate yielding a generation response object and the loop printing response.text with end="" and flush=True, and the Sampling section for the shared sampler arguments. We did not run the script, so the behaviour above is UNTESTED.

Limits

Streaming only changes when you see the text, not what the model writes: the same prompt and sampler give the same reply as generate. max_tokens still caps the reply. This runs on Apple silicon only.

Sources

Sources checked 2026-11-28.

See all