Stream the Reply as It Is Written
A language model writes its reply a few tokens at a time, but a normal call hands the program nothing until the last token is written. Streaming changes that: the server sends each new piece of the reply as soon as it exists, and the program can show it straight away. This page explains what arrives in a stream, how a program joins the pieces into a whole reply (tool calls and token usage included), and what to do when a stream stops halfway.
The first words and the whole reply
Two times matter when a person waits for a reply. The time to the first token is how long a request takes to start returning content. The time to the whole reply is how long it takes until the last word is written. Without streaming, the two are the same for the person waiting: the program receives the reply in one piece, so the screen stays empty until the model has finished.
With streaming, the program prints each piece as it arrives, and the person starts reading while the model is still writing. The model does not write any faster: the whole reply takes about as long as before. What changes is what the person sees in the meantime, text that grows instead of a blank screen.
reply shown (%) against time (not to scale)
- streamed
- one response at the end
The chart shows the shape, not a measurement: both lines end at the same moment, but one of them has something to read from early on. Two limits stay. The first words still wait for any work the model does before it answers, such as thinking before it writes or asking for a tool. And a program that must check the text before a person sees it has to hold back enough of it to run that check, which delays what it shows.
True or false?
Streaming makes the model finish its reply sooner.
False. The model writes at the same pace. Streaming only lets the program show the first pieces before the last one is written.
A streamed reply can still start late when the model reasons or asks for a tool before it answers.
True. The first visible words come only after that work, so streaming cannot show text that has not been written yet.
Chunks, deltas and one open response
A streamed call is still one HTTP request with one response. The difference is that the server keeps the response open and writes to it as the reply grows. What it writes is plain text in a format called server-sent events (SSE), and the response says so with the type text/event-stream. The text is a series of small messages, the events. Each event is a line that starts with data:, and an empty line after it marks its end.
- language model
- program
- one HTTP response, kept open (text/event-stream)
In Chat Completions, a request asks for a stream with stream=True. With the openai Python client, the call then returns a stream object instead of a finished completion, and a plain for chunk in stream: loop reads it.
Each event carries one chunk: a JSON object of type chat.completion.chunk. All the chunks of one reply share the same id. A chunk looks much like a full response, with one difference in its choices. A full response has a message in each choice, holding the whole reply. A chunk has a delta there instead, holding only the part that is new since the previous chunk. A shortened stream looks like this as the server sends it:
data: {"id":"chatcmpl-1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]}
data: {"id":"chatcmpl-1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"Your order"},"finish_reason":null}]}
data: {"id":"chatcmpl-1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":" has shipped."},"finish_reason":null}]}
data: {"id":"chatcmpl-1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
data: [DONE]The first chunk usually carries only the role. The chunks after it carry pieces of text in delta.content, and the last one carries no text but a finish_reason. Then the server sends data: [DONE], and the client stops reading and closes the response. The client parses the events itself, so a program sees only chunk objects, never the data: lines. A piece is often a single token, but one event can hold several, so a program never counts chunks to count tokens.
True or false?
A streamed reply is fetched with many small HTTP requests, one per chunk.
False. It is one request and one response. The server keeps that response open and writes each chunk to it as an event.
A chunk holds only the new part of the reply, not everything written so far.
True. That is why it is called a delta: the program has to keep the earlier pieces itself.
Joining the pieces into the reply
Since every chunk brings only what is new, the program builds the full text itself: it prints each piece as it arrives and keeps it in a list, then joins the list when the stream ends. Two details shape the loop. Every field of a delta is optional, so delta.content is None in chunks that carry no text, such as the last one. And the finish reason is None on every chunk except the one that ends the reply.
stream = client.chat.completions.create(
model=model,
messages=messages,
stream=True,
)
parts = []
finish_reason = None
for chunk in stream:
if not chunk.choices:
continue
choice = chunk.choices[0]
piece = choice.delta.content or ""
print(piece, end="", flush=True)
parts.append(piece)
if choice.finish_reason:
finish_reason = choice.finish_reason
print()
reply = "".join(parts)print normally ends with a newline and may hold text back until it has a full line. end="" keeps the pieces on one line, and flush=True sends each piece to the terminal at once, which is the point of streaming. The check if not chunk.choices skips a chunk that carries no choice at all; the section on usage below shows where one comes from. Here is how the text grows over the stream shown earlier:
| Chunk | delta.content | finish_reason | Text so far |
|---|---|---|---|
| 1 | "" | None | (empty) |
| 2 | "Your order" | None | Your order |
| 3 | " has shipped." | None | Your order has shipped. |
| 4 | None | "stop" | Your order has shipped. |
The finish reason takes the same values as in a full response: stop when the model ended on its own, length when the reply hit its token cap, tool_calls when the model asks for tools, content_filter when the provider withheld content. A stream raises no error for a reply cut off at its cap: it simply ends. So the program checks the finish reason after the loop, before it treats the joined text as complete. By then the person has already read the cut-off text, so all the program can do is tell them the reply stopped early.
True or false?
In a stream, the code can read the text of a chunk with chunk.choices[0].message.content.
False. Streamed choices have a delta, not a message. Only a full completion has message.
A streamed reply that stops at its token cap ends with the finish reason length, just like a full response.
True. The values are the same. The stream simply ends, so the program has to check the finish reason itself.
Tool calls arrive in pieces too
When the model asks for a tool in a streamed reply, the tool call comes in pieces as well. Each chunk may carry a list in delta.tool_calls, and each item in that list is a fragment of one call. A turn can hold several calls, so every fragment has an index that says which call it belongs to: 0 for the first call of the turn, 1 for the second. The index is the only field present on every fragment. The call's id and function name usually come once, with its first fragment. The arguments, a JSON text, are spread over the fragments that follow.
| Chunk | index | id | name | arguments piece | finish_reason |
|---|---|---|---|---|---|
| 1 | 0 | call_7 | lookup_order | "" | None |
| 2 | 0 | None | None | {"order | None |
| 3 | 0 | None | None | _id": "A | None |
| 4 | 0 | None | None | 1042"} | None |
| 5 | "tool_calls" |
None of the argument pieces is valid JSON on its own: {"order cannot be parsed, and neither can the first three pieces together. So the program collects the fragments by index, joining the strings, and runs nothing until the call is whole. A call is whole when a fragment with another index starts the next call, or when the finish reason tool_calls arrives. Waiting for the finish reason is the simplest safe rule, and it covers several calls in one turn as well.
calls = {}
finish_reason = None
for chunk in stream:
if not chunk.choices:
continue
choice = chunk.choices[0]
for piece in choice.delta.tool_calls or []:
call = calls.setdefault(
piece.index, {"id": "", "name": "", "arguments": ""}
)
if piece.id:
call["id"] = piece.id
if piece.function and piece.function.name:
call["name"] += piece.function.name
if piece.function and piece.function.arguments:
call["arguments"] += piece.function.arguments
if choice.finish_reason:
finish_reason = choice.finish_reason
if finish_reason == "tool_calls":
for index in sorted(calls):
arguments = json.loads(calls[index]["arguments"])Once joined, each entry has what a non-streamed tool call has: an id, a name and the arguments as JSON text, so it is handled the same way. The arguments are still generated text. json.loads can fail on them like on any other model output, and they are validated before the tool runs.
How finely a provider splits a call varies: some send the arguments in one fragment, others in many. Joining by index until the finish reason works in both cases. The client also has a helper, client.chat.completions.stream(...), that does this joining and reports when each call's arguments are complete.
True or false?
As soon as the tool name arrives in a stream, the program has everything it needs to run the tool.
False. The arguments are still arriving as fragments of JSON text, which cannot be parsed until the call is complete.
Fragments of different tool calls are told apart by their index.
True. The index is the only field present on every fragment; the id and the name usually come only once.
Token usage in a final chunk
A full response reports its token usage along with the reply. A stream, by default, reports none. To get it, the request adds stream_options={"include_usage": True}. The server then sends one more chunk after the chunk with the finish reason and before data: [DONE]. That chunk has usage with the input and output token counts for the whole request, and its choices list is always empty. Every other chunk has usage set to None.
stream = client.chat.completions.create(
model=model,
messages=messages,
stream=True,
stream_options={"include_usage": True},
)
usage = None
for chunk in stream:
if chunk.usage:
usage = chunk.usage
if not chunk.choices:
continue
piece = chunk.choices[0].delta.content or ""
print(piece, end="", flush=True)The empty choices list is why the loop checks for choices before it reads chunk.choices[0]: on the usage chunk, that index would raise an IndexError. It also means the finish reason is not on the very last chunk, but on the one before it. Many compatible endpoints accept stream_options, but not every one does, so a program that relies on it checks that its endpoint supports it.
Because usage arrives last, it is the first thing lost when a stream is cut. If the stream breaks, the usage chunk may never come, and the program does not learn how many tokens the request used, even though the tokens written before the break were generated.
True or false?
With include_usage set, the last chunk of a stream carries both the finish reason and the usage.
False. The finish reason comes on the chunk before. The usage chunk comes after it, with an empty choices list.
When a stream breaks in the middle
A stream can fail after it has started: the connection drops, a read times out, or the server sends an error event in place of the next chunk. By then the response had a success status, and part of the reply is already on the screen.
- no finish reason, no usage
The openai client turns these failures into its own exceptions while the loop reads the stream. A read that times out raises APITimeoutError. Another failure of the connection raises APIConnectionError, and APITimeoutError is a kind of APIConnectionError. An error event inside the stream raises APIError, the base class of all the client's errors. That error has no status code, because the HTTP status had already arrived as a success.
The client does not retry here. Its automatic retries cover only the start of the request, up to the moment a successful status arrives, so a failure before the first chunk can still be retried on its own. Once the stream is being read, a retry would mean asking for the whole reply again, and the pieces the program already received and showed would be generated a second time. So the exception reaches the program's loop, and the program decides what to do.
parts = []
finish_reason = None
try:
for chunk in stream:
if not chunk.choices:
continue
choice = chunk.choices[0]
piece = choice.delta.content or ""
print(piece, end="", flush=True)
parts.append(piece)
if choice.finish_reason:
finish_reason = choice.finish_reason
except openai.APIError as error:
print(f"\n[the reply stopped early: {error}]")
print()
partial = "".join(parts)
complete = finish_reason == "stop"Catching APIError catches all three failures. A stream can also simply end early with no exception at all; then the loop just stops. In every case the sign is the same: no finish reason arrived, so the joined text is incomplete. Checking the finish reason after the loop catches all of them, the exception included.
What comes next is a decision for the program, and the text already shown limits it:
- Keep the partial text, marked as incomplete, so the person knows the reply stopped and is not mistaken for a full answer.
- Discard it from anything the program stores or sends on, such as the conversation history, while telling the person it failed.
- Ask again, by sending the same request once more. The model writes the whole reply from the start, and it may say something different, so the program clears or separates the broken text before the new one appears, and the new request uses tokens again.
True or false?
When a stream breaks halfway, the client sends the request again and continues the reply where it stopped.
False. Reading a stream is never retried automatically, and a new request would generate the whole reply again, not continue it.
A stream that ends without a finish reason should be treated as incomplete, even if no exception was raised.
True. The finish reason is the signal that the reply ended. Without it, the program cannot know the text is whole.