Sub topic 10
Streaming tokens as they are generated
This chapter assumes you can already send a non-streaming chat request and read choices[0].message.content. It also assumes you know what a response's finish_reason and usage fields are. Field names follow the chat-completions format, so check your provider's documentation for differences.
Why stream
A normal request returns only after the model has produced the whole reply. A long answer can take many seconds, and the user sees nothing until it finishes. With streaming, the server sends the text in small pieces as the model generates it. Total generation time stays about the same. What improves is the time to the first visible text, which is what makes a chat interface feel responsive.
You turn streaming on by adding "stream": true to the request body.
How the stream arrives
The server keeps the HTTP connection open and replies with the content type text/event-stream. This format is called server-sent events (SSE). Each event is a line that starts with data: and is followed by a JSON object. A blank line separates events. The last event is the literal text [DONE], which is not JSON.
Each JSON chunk has the same outer shape as a normal response, with one difference. Text lives in choices[0].delta instead of choices[0].message. A delta holds only the new fragment. The first chunk usually carries just the role. The finish_reason is null until the last content chunk, which often has an empty delta.
Reading a stream in Python
import json
import os
import requests
URL = "https://api.openai.com/v1/chat/completions"
HEADERS = {
"Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}",
"Content-Type": "application/json",
}
payload = {
"model": os.environ["LLM_MODEL"],
"messages": [{"role": "user", "content": "Count from one to five in words."}],
"stream": True,
}
parts = []
finish_reason = None
with requests.post(URL, headers=HEADERS, json=payload, stream=True, timeout=60) as resp:
resp.raise_for_status()
resp.encoding = "utf-8"
for line in resp.iter_lines(decode_unicode=True):
if not line or not line.startswith("data: "):
continue
chunk = line[len("data: "):]
if chunk == "[DONE]":
break
choices = json.loads(chunk).get("choices", [])
if not choices:
continue
text = choices[0]["delta"].get("content") or ""
finish_reason = choices[0].get("finish_reason") or finish_reason
parts.append(text)
print(text, end="", flush=True)
print()
print("finish_reason:", finish_reason)
full_text = "".join(parts)Several details matter here:
stream=Trueinrequests.poststops the library from downloading the whole body before returning.iter_linesyields one line at a time as data arrives.- Setting
resp.encodingavoids garbled characters, becauserequestsmay otherwise assume a legacy encoding fortext/event-stream. flush=Truemakes the text appear immediately instead of waiting in the output buffer.delta.get("content") or ""handles chunks wherecontentis missing ornull.- The
choicescheck skips chunks with an empty list. Some providers send such a chunk at the end to carry token usage.
What changes compared with a normal call
| Concern | Non-streaming | Streaming |
|---|---|---|
| Where the text is | `message.content` | Joined `delta.content` fragments |
| Token usage | Always in `usage` | Often absent unless you ask for it, for example with `stream_options` |
| Errors | Status code tells you | Status is already 200 once the stream starts |
| Timeout | Covers one wait | Applies to the gap between reads |
Common errors
- Parsing
[DONE]as JSON raises aJSONDecodeError. Check for it first. - Reading
delta["content"]directly raisesKeyErroron the role-only first chunk. - Showing partial text to a program that expects valid JSON fails. Parse structured output only after the stream ends.
- Forgetting that
usagemay be missing leads to wrong cost tracking.
Exercise
In the streaming loop, why is the code that builds the final reply written as parts.append(text) followed by "".join(parts) rather than relying on the last chunk?
Show answer
Each chunk's delta holds only a new fragment, not the text so far. The last chunk usually has an empty delta and only the finish reason. The full reply exists only if you collect every fragment and join them.