Sub topic 8
Building the full message from deltas
This chapter assumes you can read Python and JSON, know what a token is, and have seen a streamed response arrive as a series of events. Here you turn those events into one finished message.
What a delta is
A streamed response does not contain the full text in any single event. Each event carries a small piece, called a delta. The full message is the sum of every delta in order. Your code owns that sum, so you keep a buffer and append to it as events arrive.
In an OpenAI-style chat stream, each chunk looks like this:
{"choices": [{"index": 0, "delta": {"content": "Hel"}, "finish_reason": null}]}The first chunk often carries only {"role": "assistant"} with no content. The last content chunk carries an empty delta and a non-null finish_reason. If you treat every delta as if it has text, you will crash or print None.
Accumulating text
The rule is simple: append only when content is present, and never assume the order of keys or the presence of a field.
def accumulate(chunks):
"""Build a message from OpenAI-style chunk dictionaries."""
parts = []
finish_reason = None
usage = None
for chunk in chunks:
if chunk.get("usage"):
usage = chunk["usage"]
for choice in chunk.get("choices", []):
delta = choice.get("delta", {})
if delta.get("content"):
parts.append(delta["content"])
if choice.get("finish_reason"):
finish_reason = choice["finish_reason"]
return {"text": "".join(parts), "finish_reason": finish_reason, "usage": usage}
chunks = [
{"choices": [{"delta": {"role": "assistant"}, "finish_reason": None}]},
{"choices": [{"delta": {"content": "Hel"}, "finish_reason": None}]},
{"choices": [{"delta": {"content": "lo"}, "finish_reason": None}]},
{"choices": [{"delta": {}, "finish_reason": "stop"}]},
{"choices": [], "usage": {"prompt_tokens": 9, "completion_tokens": 2}},
]
print(accumulate(chunks))The output is:
{'text': 'Hello', 'finish_reason': 'stop', 'usage': {'prompt_tokens': 9, 'completion_tokens': 2}}Collect the pieces in a list and join once at the end. Repeated += on a long string works, but a list avoids copying the text on every event.
Details that trip people up
- Usage arrives last, if at all. Many APIs send token counts only in a final chunk, and some only when you request them. That final chunk can have an empty
choiceslist, so guard against indexingchoices[0]. - The finish reason is not in the text. Values such as
stop(the model ended naturally) andlength(it hit the token limit) tell you whether the message is complete. Store it with the message. - Display the buffer, not the delta. If the UI re-renders, render the accumulated text. Rendering only the latest delta loses everything before it.
- Keep what you have on failure. If the connection drops, the buffer holds a partial message. Decide whether to show it, mark it as incomplete, or discard it. Do not present it as finished when no finish reason arrived.
The flow
Exercise
A stream ends, and your buffer holds a sentence cut off mid-word. The last chunk you received had finish_reason: null, and no usage chunk arrived. What does this tell you, and what should the UI do?
Show answer
The stream ended without a finish reason, so the message is incomplete. The connection was probably dropped or an error occurred. The UI should keep the partial text but mark it as incomplete, for example with a warning and a retry option, rather than showing it as a finished answer.