Streaming Responses from the Ollama API
By default, Ollama streams its answer: instead of one big response it sends many small JSON objects, one per chunk of generated text, so users see words appear immediately. This post explains the format and shows how to read it in curl and Python.
Why stream?
A local model might take ten seconds to write a long answer. If your app waits for the whole thing, the screen is blank for ten seconds. Streaming shows the first words after the model finishes reading the prompt, which makes the app feel responsive even when total time is the same.
The wire format
With streaming on, the response body is newline-delimited JSON (often called NDJSON): each line is a complete JSON object. Run this and watch the lines arrive:
curl http://localhost:11434/api/generate -d '{
"model": "llama3.2",
"prompt": "Count from one to five in words."
}'
You will see lines like these, shortened here:
{"model":"llama3.2","created_at":"...","response":"One","done":false}
{"model":"llama3.2","created_at":"...","response":",","done":false}
{"model":"llama3.2","created_at":"...","response":" two","done":false}
{"model":"llama3.2","created_at":"...","response":"","done":true,"eval_count":23}
Each non-final line carries a small piece of text in response. The last line has done set to true and includes the statistics, such as token counts and durations. Concatenate the pieces to build the full answer. For /api/chat the text is in message.content on each line instead.
Reading the stream in Python
This script uses the requests library (install with pip install requests). It reads line by line and prints text as it arrives:
import json
import requests
payload = {
"model": "llama3.2",
"messages": [{"role": "user", "content": "Explain TCP in three sentences."}],
"stream": True,
}
with requests.post("http://localhost:11434/api/chat", json=payload, stream=True) as resp:
resp.raise_for_status()
full = []
for line in resp.iter_lines():
if not line:
continue
chunk = json.loads(line)
text = chunk["message"]["content"]
full.append(text)
print(text, end="", flush=True)
if chunk.get("done"):
break
print()
print("characters:", len("".join(full)))
The key parts are stream=True in requests, which stops it buffering the whole body, and flush=True in print, which makes the terminal show each piece at once. Run it and the answer types itself out.
Streaming with the official Python library
If you install the ollama package, streaming is shorter:
import ollama
stream = ollama.chat(
model="llama3.2",
messages=[{"role": "user", "content": "Name three sorting algorithms."}],
stream=True,
)
for chunk in stream:
print(chunk["message"]["content"], end="", flush=True)
print()
Setting stream=True makes the call return an iterator of chunks instead of one response.
Common problems
- Output appears all at once. Something in between is buffering. Use
stream=Truein requests, and disable proxy buffering in Nginx (post 82). - JSON errors on partial lines. Parse whole lines only; do not split the byte stream at arbitrary points.
- Missing statistics. They are only on the final line, so read until
doneis true. - Cancelling. Closing the connection stops the request, and the server stops generating.
How streaming relates to latency
It helps to separate two delays. The first is the time to first token, which is how long the model takes to read your prompt and produce the first piece of text. The second is the rate after that, in tokens per second. Streaming does not change either number, but it changes what the user perceives. A long prompt, such as a pasted document, makes the first delay large even on a fast machine, and nothing appears until it ends. A short prompt on the same machine starts almost at once. When you measure your setup, record both numbers separately, because different fixes improve each of them.
Handling errors mid-stream
Sometimes the connection drops or the server runs out of memory halfway through an answer. Because the HTTP status code is sent before the body, a stream that starts well can still end badly. Treat the absence of a final line with done set to true as a failure, keep what you received so far, and decide whether to retry or show a partial answer with a warning. Wrapping the loop in a try block and checking for the final marker takes only a few lines and prevents silent truncation in production.
Asynchronous clients
If your application uses asyncio, use the library's async client so that waiting for tokens does not block other work. The ollama Python package provides an AsyncClient class whose chat method can be awaited with stream=True and iterated with async for. The idea is identical to the synchronous example, and it is the right shape for web servers that handle many users at once, as shown in post 45.
When not to stream
For batch jobs, JSON parsing and scripts that need the full text before continuing, "stream": false is simpler. Use streaming for anything a human watches. OpenAI-compatible endpoints stream differently, using server-sent events, which post 18 and post 45 show.
Comments
No comments yet. Have a question or a tip? Be the first to share it.