Sub topic 10
Handling streamed responses
This chapter assumes you can call the Ollama REST API with generate or chat (covered earlier), you know basic HTTP and JSON, and you can read short Python scripts.
Why streaming is the default
A model produces text one token at a time. If the server waited for the whole reply, you would see nothing for several seconds on a slow machine. Ollama instead sends each piece as soon as it exists. This is streaming, and it is on by default for both /api/generate and /api/chat. Setting "stream": false turns it off and returns one JSON object.
What the stream looks like
The body is newline-delimited JSON (NDJSON). Each line is a complete JSON object. For /api/chat, each object carries a fragment of the reply in message.content. The last object has "done": true and includes timing and token counts.
curl http://localhost:11434/api/chat -d '{
"model": "llama3.2",
"messages": [
{"role": "user", "content": "What is quantization?"}
]
}'Abbreviated output:
{"model":"llama3.2","message":{"role":"assistant","content":"Quant"},"done":false}
{"model":"llama3.2","message":{"role":"assistant","content":"ization"},"done":false}
{"model":"llama3.2","message":{"role":"assistant","content":""},"done":true,"done_reason":"stop"}Reading the stream in Python
Pass stream=True to requests and iterate over lines. Parse each line on its own. Do not try to parse the whole body as one JSON document, because it is not one.
import json
import requests
with requests.post(
"http://localhost:11434/api/chat",
json={
"model": "llama3.2",
"messages": [{"role": "user", "content": "Why is the sky blue?"}],
},
stream=True,
timeout=120,
) as resp:
resp.raise_for_status()
for line in resp.iter_lines():
if not line:
continue
chunk = json.loads(line)
print(chunk["message"]["content"], end="", flush=True)
if chunk.get("done"):
print()
breakflush=True makes text appear immediately instead of waiting for a full output buffer.
Common errors
- Parsing the whole body as JSON.
resp.json()fails on a stream with a "extra data" error. Either iterate over lines or set"stream": false. - Forgetting
stream=Trueinrequests. The library then downloads the full body before you can read it, so you lose the benefit of streaming. - Reading
responseon the chat endpoint./api/generateputs text inresponse./api/chatputs it inmessage.content. - Ignoring errors mid-stream. If the server fails after it has started sending, the HTTP status is already 200. Check each chunk for an
errorfield. - Dropping the last chunk. The final object holds statistics such as
eval_countandtotal_duration. Keep it if you need them.
When to turn streaming off
Disable streaming when a script only needs the finished text, such as a batch job or a structured-output call that you parse after completion. Keep it on for chat interfaces, where perceived speed matters more than code simplicity.
Exercise
Why does calling resp.json() on a streamed /api/chat response fail, and what are two ways to fix it?
Show answer
The body is several JSON objects, one per line, not a single JSON document, so the parser finds extra data after the first object. Fix it by iterating over the lines and calling json.loads on each one, or by sending "stream": false so the server returns a single object.
Exercise
In a streamed reply, how do you know the model has finished, and where do you find the full token counts?
Show answer
The last object has "done": true. That same final object contains the statistics, such as eval_count and total_duration.