Sub topic 10
Handling streamed responses
This chapter assumes you can send a request to the local Ollama server, as covered in the REST API chapter. You should also be comfortable with JSON and with reading a Python generator. The examples use requests and the openai package. Ollama must be running on localhost:11434 with llama3.2 pulled.
Why responses stream
A language model produces text one token at a time. A long answer on a laptop can take many seconds. If the server waited for the whole answer before replying, the user would see nothing until the end. Streaming sends each piece as soon as it exists, so a chat interface can show text as it is written.
For Ollama's native endpoints, /api/generate and /api/chat, streaming is the default. You must send "stream": false to get a single JSON object. The OpenAI-compatible /v1 endpoints follow the OpenAI convention instead, where streaming is off unless you ask for it.
The wire format: newline-delimited JSON
A streamed native response is newline-delimited JSON (NDJSON). Each line is a complete JSON object, and lines are separated by \n. The body as a whole is not one JSON document, so json.loads(resp.text) fails on it.
Here is the example from the REST API chapter, without "stream": false:
curl http://localhost:11434/api/chat -d '{
"model": "llama3.2",
"messages": [
{"role": "system", "content": "You answer in one short sentence."},
{"role": "user", "content": "What is quantization?"}
]
}'The output looks like this, shortened:
{"model":"llama3.2","created_at":"2026-11-27T12:57:20Z","message":{"role":"assistant","content":"Quant"},"done":false}
{"model":"llama3.2","created_at":"2026-11-27T12:57:20Z","message":{"role":"assistant","content":"ization"},"done":false}
{"model":"llama3.2","created_at":"2026-11-27T12:57:21Z","message":{"role":"assistant","content":""},"done":true,"done_reason":"stop","total_duration":1834000000,"load_duration":41000000,"prompt_eval_count":32,"prompt_eval_duration":210000000,"eval_count":27,"eval_duration":1540000000}Three details matter:
- Each chunk carries a fragment in
message.contentfor/api/chat. For/api/generatethe fragment is inresponse. - A fragment is not always a whole word. It can be part of a word, a space, or an empty string, so concatenate fragments exactly as received and do not trim them.
- The last object has
"done": true. It holds statistics, not new text. Its content is usually empty.
Reading a stream in Python
Pass stream=True to requests.post. Without it, requests downloads the whole body before returning, and you lose the benefit of streaming. Then use iter_lines(), which buffers network data and yields one complete line at a time. A JSON object can be split across TCP packets, so reading raw chunks and parsing each one is a common bug.
import json
import requests
URL = "http://localhost:11434/api/chat"
def stream_chat(messages, model="llama3.2"):
"""Yield each parsed chunk from a streamed chat request."""
payload = {"model": model, "messages": messages, "stream": True}
with requests.post(URL, json=payload, stream=True, timeout=(5, 120)) as resp:
resp.raise_for_status()
for line in resp.iter_lines():
if not line:
continue # skip keep-alive blank lines
chunk = json.loads(line)
if "error" in chunk:
raise RuntimeError(chunk["error"])
yield chunk
messages = [{"role": "user", "content": "Name three uses of a local LLM."}]
parts = []
final = {}
for chunk in stream_chat(messages):
text = chunk["message"]["content"]
print(text, end="", flush=True)
parts.append(text)
if chunk.get("done"):
final = chunk
print()
reply = "".join(parts)
if final.get("eval_duration"):
speed = final["eval_count"] / (final["eval_duration"] / 1e9)
print(f"{final['eval_count']} tokens at {speed:.1f} tokens/s")The code relies on four behaviors:
flush=Truemakes text appear immediately. Without it, Python may hold output in a buffer and the stream looks like a single burst.partscollects fragments so you can join them into the full reply afterwards.- The
timeout=(5, 120)tuple sets a 5-second connect timeout and a 120-second read timeout. The read timeout applies to the wait between bytes, not to the whole response, so a long answer is fine as long as tokens keep arriving. The first token can be slow while the model loads into memory, so keep the read value generous. - The
"error"check handles failures that happen after the HTTP status was already sent.
Errors in the middle of a stream
An HTTP 200 is sent when the response starts. If something fails later, such as running out of memory while generating, the server cannot change the status code. It sends a JSON line with an error field instead. Requests rejected before generation starts, such as asking for a model that is not installed, return an HTTP error status. raise_for_status() catches those.
A simple completeness check is to confirm that you saw a final chunk:
if not final:
raise RuntimeError("stream ended before the final chunk")Using the final chunk's statistics
The final object reports durations in nanoseconds and token counts:
| Field | Meaning |
|---|---|
| `done_reason` | Why generation stopped, for example `stop` (the model finished) or `length` (a token limit was reached) |
| `prompt_eval_count` | Tokens in the prompt that were processed |
| `prompt_eval_duration` | Time spent processing the prompt |
| `eval_count` | Tokens generated |
| `eval_duration` | Time spent generating |
| `load_duration` | Time spent loading the model into memory |
| `total_duration` | Whole request, including loading |
Dividing eval_count by eval_duration (converted to seconds) gives generation speed in tokens per second. This number is useful when you compare quantization levels or check whether a model is running on the CPU instead of the GPU. A large load_duration on the first request and a tiny one on the next shows the model staying in memory.
Keeping conversation history
A streamed reply is not saved by the server. To continue a chat, join the fragments and append the result to your messages list as an assistant turn:
messages.append({"role": "assistant", "content": reply})
messages.append({"role": "user", "content": "Expand on the second one."})If you skip this step, the next request has no memory of the previous answer. Because the history grows each turn, long chats eventually exceed the context window, as covered in the context chapter.
Streaming through the OpenAI-compatible endpoint
The /v1 endpoint uses server-sent events instead of NDJSON. The wire format is different, but the OpenAI client library hides it. Pass stream=True and iterate:
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
stream = client.chat.completions.create(
model="llama3.2",
messages=[{"role": "user", "content": "Give me one tip for writing clear commit messages."}],
stream=True,
)
for chunk in stream:
if not chunk.choices:
continue
piece = chunk.choices[0].delta.content
if piece:
print(piece, end="", flush=True)
print()The text is under choices[0].delta.content, not message.content. It can be None on the first and last chunks, so test it before printing. The stream ends with a data: [DONE] line, which the library handles for you.
Stopping early
To cancel a generation, close the connection. In the requests example, leaving the with block early (with break) closes the response. Ollama notices the closed connection and stops generating, which frees the GPU or CPU for other work. This is how a "Stop" button in a chat interface should work. Simply ignoring the remaining chunks while keeping the connection open does not stop the server.
When not to stream
Streaming adds code. Use "stream": false when you need the whole answer before doing anything with it, for example when you parse the reply as JSON or run a batch job with no user watching. For interactive output, streaming is almost always the better choice.
Exercise
A script calls /api/generate with stream enabled and runs json.loads(resp.text) on the whole body. It raises a JSON error. Why, and how do you fix it?
Show answer
A streamed body is NDJSON: many JSON objects, one per line, not one JSON document. Either set "stream": false to get a single object, or call requests.post with stream=True and parse each line from iter_lines() separately. For /api/generate, read the "response" field of each chunk and stop at the chunk where "done" is true.
Exercise
Your stream finished without any exception, but the last chunk you saw had "done": false. What happened, and what should your code do?
Show answer
The stream was cut short, for example because the server stopped or the connection dropped. The collected text is incomplete. Track whether a chunk with "done": true was received, and raise an error or retry if it was not.