Sub topic 10
Streaming tokens as they are generated
This chapter assumes you can send a chat request and read the response, as covered in earlier chapters. You should also be comfortable with Python, JSON, HTTP status codes, and environment variables. Examples use the chat-completions request shape. Field names differ between providers, so check your provider's documentation.
Why stream
A normal request waits until the model has finished generating the whole reply. A long answer can take many seconds, and the user sees nothing during that time.
With streaming, the server sends the reply in small pieces as the model produces them. Total generation time is about the same. What improves is the time to the first visible text, which makes an interface feel responsive.
Streaming helps in these cases:
- Chat interfaces where a person reads the text as it appears.
- Long outputs where you want to show progress or let the user cancel.
- Pipelines that can start work on partial output.
Streaming adds nothing when a program needs the complete reply before it can act, for example when it must parse a full JSON document. It also makes error handling and usage accounting more complicated, as the sections below describe.
How the wire format works
You turn streaming on by adding "stream": true to the request body. The server then keeps the HTTP connection open and sends the response as server-sent events (SSE). SSE is a simple text format. Each event is one or more lines, and events are separated by a blank line. For chat completions, each event is a single line that starts with data: followed by a JSON object called a chunk.
A stream looks like this:
data: {"choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]}
data: {"choices":[{"index":0,"delta":{"content":"One"},"finish_reason":null}]}
data: {"choices":[{"index":0,"delta":{"content":", two"},"finish_reason":null}]}
data: {"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
data: [DONE]Compare a chunk with a normal response:
| Aspect | Normal response | Streamed chunk |
|---|---|---|
| Text location | `choices[0].message.content` | `choices[0].delta.content` |
| Contents | The complete text | A fragment, often a few characters |
| `finish_reason` | Set once | `null` until the last content chunk |
| Role | In every message | Usually only in the first chunk |
| End of response | The HTTP body ends | A `data: [DONE]` line, then the connection closes |
The field is called delta because each chunk carries only the change since the previous one. Your program rebuilds the full text by appending fragments in order.
A minimal streaming client
The following program requests a streamed reply and prints each fragment as it arrives.
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,
}
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
print(choices[0]["delta"].get("content") or "", end="", flush=True)
print()Each part of this code addresses a specific problem:
stream=Trueinrequests.posttells the library not to download the whole body before returning. Without it, your code would block until the stream ended and you would lose the benefit.raise_for_status()runs before you read any events. Errors such as 401 or 429 that occur before generation starts arrive as a normal JSON error response, not as a stream.resp.encoding = "utf-8"matters because SSE responses often have no charset in the header. Without it,requestsmay guess a legacy encoding and corrupt non-ASCII text.- The
withblock closes the connection when the loop ends, including when an exception occurs. - Lines that do not start with
data:are skipped. SSE also allows comment lines that start with a colon, which some servers send as keep-alives. .get("choices", [])and theif not choicescheck handle chunks with an emptychoiceslist. Some providers send such a chunk at the end to carry usage data.delta.get("content") or ""handles chunks wherecontentis missing ornull, such as the first chunk and the final one.flush=Truepushes each fragment to the terminal at once. Without it, Python may buffer output and the text would appear in bursts.
Accumulating the full text, finish reason and usage
Printing is enough for a demo. A real application usually needs the complete text afterwards, to store it in conversation history, log it, or validate it. It also needs the finish reason to know whether the reply was cut off.
The next function collects the fragments and returns them with the finish reason. It also asks for token usage, which is not included in streams by default on this API shape.
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",
}
def stream_chat(messages, on_text=None):
payload = {
"model": os.environ["LLM_MODEL"],
"messages": messages,
"stream": True,
"stream_options": {"include_usage": True},
}
parts = []
finish_reason = None
usage = None
with requests.post(
URL, headers=HEADERS, json=payload, stream=True, timeout=(5, 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
data = line[len("data: "):]
if data == "[DONE]":
break
event = json.loads(data)
if event.get("usage"):
usage = event["usage"]
for choice in event.get("choices", []):
text = choice["delta"].get("content")
if text:
parts.append(text)
if on_text:
on_text(text)
if choice.get("finish_reason"):
finish_reason = choice["finish_reason"]
return "".join(parts), finish_reason, usage
text, reason, usage = stream_chat(
[{"role": "user", "content": "Name three primary colors."}],
on_text=lambda t: print(t, end="", flush=True),
)
print()
print("finish_reason:", reason)
print("usage:", usage)Key points about this function:
stream_optionswithinclude_usageis specific to this API shape. When it is supported, the usage object arrives in a final chunk whosechoiceslist is empty. Other providers report usage differently, or only when asked a different way. If your provider does not support the option,usagestaysNone.- A
finish_reasonoflengthmeans the reply hit the output token limit and is incomplete. Check for it exactly as you would for a non-streamed reply. - The
on_textcallback separates transport from display. The same function can feed a terminal, a web socket, or a log.
Failure modes specific to streaming
A streamed response can fail in ways a normal one cannot, because the HTTP status is sent before generation finishes.
Errors before the first chunk
Authentication errors, rate limits, and invalid parameters are returned before any event, with a non-200 status. raise_for_status() catches them. Your retry logic from the previous chapter applies unchanged: retry 429 and 5xx responses with backoff, and raise other 4xx errors.
Errors in the middle of a stream
Once the server has sent 200 OK, the status code cannot change. If something fails later, one of these happens:
- The connection drops.
requestsraisesChunkedEncodingErrororConnectionErrorinside your loop. - The read timeout expires because no data arrived.
requestsraisesReadTimeout. - The server sends an error object as an event, and then closes the stream.
- The stream ends without
[DONE]and without afinish_reason.
You cannot resume a stream from the middle with this API shape. The practical options are:
- Discard the partial text and retry the whole request. This is the simplest choice and the right default.
- Keep the partial text, add it as an assistant message, and ask the model to continue. This is more complex, may not continue cleanly, and costs extra tokens.
Whichever you choose, do not retry automatically after you have already shown partial text to a user without telling them. Repeated text on screen is confusing.
A check for an incomplete stream is cheap to add:
text, reason, usage = stream_chat(messages)
if reason is None:
raise RuntimeError("Stream ended without a finish reason; reply may be truncated")Timeouts mean something different
In requests, a timeout=60 value applies to the connection and to each wait for new data. It is not a limit on the total request time. This suits streaming, since the total duration depends on reply length. A tuple like (5, 60) sets separate connect and read timeouts. If you also need a hard cap on total time, you must track elapsed time yourself in the loop and close the response when it is exceeded.
Cancelling
To stop generation early, for example when a user clicks a stop button, leave the with block, or call resp.close(). Closing the connection signals the server to stop. Providers generally stop generating when the client disconnects, but billing details vary. Tokens generated before the server noticed the disconnect may still be charged, so check your provider's documentation.
Other considerations
- Tool calls and JSON. Streamed tool-call arguments and structured output arrive as fragments too. A fragment of JSON is not valid JSON, so concatenate all fragments and parse only after the stream ends. Do not call
json.loadson partial arguments. - Moderation and validation. If you filter or validate model output, streaming means users may see text before your check runs. For content that must be checked first, buffer the reply and release it after validation, or avoid streaming.
- Proxies and buffering. Some reverse proxies and load balancers buffer responses, which removes the streaming effect. If text arrives all at once in production but not on your laptop, check proxy buffering settings.
- Multiple choices. If you request more than one completion, chunks carry an
indexfield and fragments for different choices may interleave. Accumulate each index into its own buffer. - Chunk size. A chunk is not guaranteed to hold a whole word. Do not process the stream word by word without your own buffering.
- Per-chunk cost. Streaming does not change the token count or price of a reply. It only changes when you receive the text.
Exercise
A streaming client prints text correctly, but the final usage numbers are always None. The request already contains "stream": true. What is the most likely cause, and how would you check it?
Show answer
Token usage is usually not sent in streams unless requested. On this API shape you add "stream_options": {"include_usage": true}, and the usage then arrives in a final chunk with an empty choices list. Check that the client does not skip chunks with empty choices before reading usage, and confirm in your provider's documentation that the option exists, since other providers use different mechanisms.
Exercise
Midway through a long streamed reply, the connection drops and requests raises an exception. The user has already seen half the answer. Give two ways to recover and one risk of each.
Show answer
First, discard the partial text and resend the whole request. The risk is that the user sees the text restart or change, and you pay for the tokens again. Second, append the partial text as an assistant message and ask the model to continue. The risk is that the continuation may repeat or contradict the earlier part, and the extra request costs more input tokens. In both cases, never store the partial reply as a finished answer in the history.