New Tool Radar

Local AI

How to Stream MLX Output Token by Token in Python

Stream a model's reply token by token in Python with mlx_lm.stream_generate, instead of waiting for the whole answer.

Schematic diagram with four steps: load the model, build the prompt with the chat template, loop over stream_generate printing each piece, then confirm the full reply is complete.

Waiting for a whole answer feels slow in an interactive app. mlx-lm’s stream_generate yields the reply piece by piece as the model produces it, so you can print tokens as they arrive — the way a chat window does.

Use stream_generate in a loop

Load the model and tokenizer, build the prompt with the chat template, then loop over stream_generate: each iteration yields a response object whose .text holds the new piece, which you print immediately with flush=True. Pass max_tokens=512 to cap the reply length.

from mlx_lm import load, stream_generate

model, tokenizer = load("mlx-community/Mistral-7B-Instruct-v0.3-4bit")
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()

Streaming changes when the text appears, not what the model says: the full reply is the same as a non-streaming call with the same settings. If your app buffers output, flush after each piece or the stream looks like a single block anyway.

Try it: four checks

Check What you should see If you do not see it
Model loads load() returns the model and tokenizer Check the model name spelling
Tokens arrive Text prints piece by piece Flush after each print
Full reply The joined pieces make a complete answer Compare with a non-streaming call
Max tokens respected The reply stops at max_tokens Raise it for longer answers

Expected result. We checked the mlx-lm README, which documents stream_generate yielding a generation response object, the max_tokens argument, and printing response.text with flush=True. We did not run the code on this machine.

Limits

This guide covers streaming in Python only. Streaming changes the display timing, not the model’s answer. We did not test any code ourselves.

Sources

See all