Sub topic 8
Building the Full Message from Deltas
This chapter assumes you can read Python, know what a streamed chunk looks like (from the earlier chapters on SSE and delta events), and are comfortable with JSON. The examples use the OpenAI Chat Completions chunk format. Other providers use different field names, but the accumulation logic is the same.
Why you need an accumulator
A streamed response is a sequence of small fragments called deltas. A delta is the piece of new information in one chunk, not the whole message so far. Your UI can render each delta as it arrives. Your application usually needs the complete message too. You need it to save the conversation, send it back as history on the next turn, run a moderation check, or log the result.
Nothing in the stream gives you the full message. You build it yourself by merging each delta into a running state. That state is the accumulator.
What a chunk contains
In the Chat Completions format, each chunk is a JSON object. Fields appear at different points in the stream.
| Field | Where it appears | What to do with it |
|---|---|---|
| `choices[i].index` | Every chunk | Use it as the key for that choice's state. |
| `choices[i].delta.role` | Usually the first chunk only | Store it once. |
| `choices[i].delta.content` | Most chunks, sometimes `null` or missing | Append it when it is a non-empty string. |
| `choices[i].finish_reason` | `null` until the last chunk of that choice | Store it when it becomes non-null. |
| `usage` | Final chunk, only if you request it | Store it. |
For usage, OpenAI requires stream_options={"include_usage": True}. That final chunk has an empty choices list. Code that reads chunk.choices[0] without checking will crash on it.
A minimal accumulator
The function below works on already-parsed chunks (dictionaries). It keeps one state per choice index, so it also handles requests with n > 1. It collects content pieces in a list and joins them once at the end, which avoids repeated string copying on long outputs.
def accumulate(chunks):
"""Merge streamed chunks into complete messages and a usage record."""
states = {}
usage = None
for chunk in chunks:
if chunk.get("usage"):
usage = chunk["usage"]
for choice in chunk.get("choices", []):
state = states.setdefault(
choice["index"],
{"role": None, "parts": [], "finish_reason": None},
)
delta = choice.get("delta") or {}
if delta.get("role"):
state["role"] = delta["role"]
if delta.get("content"):
state["parts"].append(delta["content"])
if choice.get("finish_reason"):
state["finish_reason"] = choice["finish_reason"]
messages = {
index: {
"role": s["role"],
"content": "".join(s["parts"]),
"finish_reason": s["finish_reason"],
}
for index, s in states.items()
}
return messages, usage
chunks = [
{"choices": [{"index": 0, "delta": {"role": "assistant", "content": ""}, "finish_reason": None}]},
{"choices": [{"index": 0, "delta": {"content": "Hello"}, "finish_reason": None}]},
{"choices": [{"index": 0, "delta": {"content": ", world"}, "finish_reason": None}]},
{"choices": [{"index": 0, "delta": {"content": "!"}, "finish_reason": None}]},
{"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]},
{"choices": [], "usage": {"prompt_tokens": 9, "completion_tokens": 4, "total_tokens": 13}},
]
messages, usage = accumulate(chunks)
print(messages[0])
print(usage)Running it prints:
{'role': 'assistant', 'content': 'Hello, world!', 'finish_reason': 'stop'}
{'prompt_tokens': 9, 'completion_tokens': 4, 'total_tokens': 13}Three details in this code matter:
- The first chunk carries the role and an empty
content. The truthiness check skips it. - The
finish_reasonchunk has an emptydelta. Treating a missingcontentas an error would break here. - The usage chunk has no choices. The loop over
chunk.get("choices", [])does nothing for it.
The accumulation flow
Common errors
Appending `None`
Calling "".join(parts) fails if any part is None, and text += None raises a TypeError. Always test that the content is a non-empty string before appending.
Trimming whitespace
Tokens often begin with a space, such as " world". If you call .strip() on each delta, you get "Helloworld". Never alter a delta. Trim only the final message if you must.
Assuming one choice
Indexing choices[0] works for the common case and fails for n > 1. It also fails on the usage chunk. Keying state by index costs almost nothing and avoids both problems.
Splitting multi-byte characters
If you read raw bytes from the network, a chunk boundary can fall inside a UTF-8 character. Decoding each chunk separately then produces garbled text or an exception. Use an incremental decoder, which holds back incomplete bytes until the rest arrive:
import codecs
decoder = codecs.getincrementaldecoder("utf-8")()
raw = "héllo".encode("utf-8")
# The two-byte character "é" is cut after its first byte.
print(decoder.decode(raw[:2]) + "|" + decoder.decode(raw[2:]))This prints h|éllo. In the browser, TextDecoderStream does the same job. Most SDKs already handle it for you.
Treating a partial message as complete
If the stream ends without any chunk having a finish_reason, the connection dropped or the request failed. The text you hold is truncated. Check that finish_reason is set before you save the message as the assistant's turn.
Losing the text on error
If an exception interrupts the stream, the accumulator still holds everything received so far. Decide deliberately what to do with it. You can show it with a "response interrupted" marker, discard it, or keep it and let the user retry. Don't silently store it as a normal complete reply. The chapter on mid-stream errors covers this in more detail.
Keeping the UI and the accumulator in sync
Update the accumulator and the display from the same event, so they cannot drift apart. A simple pattern is to append each delta to the accumulator first, then pass that same delta to the renderer. If the renderer holds its own copy of the text, compare it with the accumulated string when the stream ends.
Summary of rules
- Key state by choice index, not by position in the list.
- Append only non-empty string content, and never modify a delta.
- Store
roleandfinish_reasonwhen they first appear. - Capture
usagefrom the final chunk, and expect it to have no choices. - Trust the message only after a
finish_reasonarrives and the stream closes.
Exercise
A stream ends normally, and your accumulator holds the text "The answer is 4" but finish_reason is still None and no usage chunk arrived. List two possible explanations and say whether you would save the text as a complete assistant message.
Show answer
Possible explanations: the connection was cut by a proxy or network failure before the final chunks arrived, or the client stopped reading early (for example, a cancel or a bug that breaks out of the loop on a [DONE]-like marker too soon). Another possibility is that you did not request usage, which would explain the missing usage chunk but not the missing finish reason. Because no finish reason was seen, you cannot tell whether the model finished, so you should not save the text as a complete message. Mark it as interrupted or retry the request.
Exercise
Why does the accumulator in this chapter use if delta.get("content"): instead of if "content" in delta:?
Show answer
The first chunk can have content set to an empty string, and some chunks have it set to null. Both are present as keys but contain nothing to append. The truthiness check skips empty strings and None, so the code never tries to append None to the parts list, and chunks with no content key are skipped as well.