Sub topic 6
Reading delta events
This chapter assumes you can read JSON and Python, and that you already know how to pull the data: payloads out of an SSE stream. Here you will learn what those payloads contain.
What a delta event is
A streamed response is a sequence of small JSON objects. Each one describes only the change since the previous one, which is called a delta. In the OpenAI Chat Completions format, each payload is a chat.completion.chunk object. The new text is in choices[0].delta, not in choices[0].message.
A typical stream looks like this:
{"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]}
{"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"Hel"},"finish_reason":null}]}
{"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"lo"},"finish_reason":null}]}
{"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}The shape of the stream
The chunks fall into three groups.
| Position | What `delta` holds | `finish_reason` |
|---|---|---|
| First chunk | `role`, often with empty `content` | `null` |
| Middle chunks | A piece of `content` | `null` |
| Last chunk | Empty `{}` | `"stop"`, `"length"`, and so on |
Some providers add one more chunk after the last one. It has an empty choices list and a usage object, which is why code must not assume choices[0] exists.
Reading deltas defensively
A delta can omit any field, so read each one with a default. The function below turns decoded chunks into text pieces:
import json
def iter_text(payloads):
"""Yield text pieces from chat.completion.chunk JSON strings."""
for payload in payloads:
if payload == "[DONE]":
return
chunk = json.loads(payload)
if not chunk.get("choices"):
continue # for example, a final usage-only chunk
delta = chunk["choices"][0].get("delta", {})
content = delta.get("content")
if content: # skips None and ""
yield content
payloads = [
'{"choices":[{"delta":{"role":"assistant","content":""},"finish_reason":null}]}',
'{"choices":[{"delta":{"content":"Hel"},"finish_reason":null}]}',
'{"choices":[{"delta":{"content":"lo"},"finish_reason":null}]}',
'{"choices":[{"delta":{},"finish_reason":"stop"}]}',
'{"choices":[],"usage":{"prompt_tokens":9,"completion_tokens":2}}',
"[DONE]",
]
print("".join(iter_text(payloads))) # HelloRun it and it prints Hello. The role-only chunk, the finish chunk, and the usage chunk all pass through without errors.
Common errors
- Indexing
choices[0]without checking. Usage-only chunks have an empty list, so this raisesIndexError. - Treating
[DONE]as JSON. It is a plain sentinel string, sojson.loadsfails on it. - Printing
None. Chunks with a role or a finish reason havecontentset toNoneor missing. Check for a value first. - Trimming whitespace. Pieces such as
" is"carry their own leading spaces. Concatenate them exactly as received. - Assuming one token per chunk. A chunk may contain several tokens or a partial word. Do not count chunks as tokens.
Other providers use different event shapes. Anthropic, for example, sends named events such as content_block_delta. The idea is the same: read the event type, then extract the incremental piece.
Exercise
A chunk arrives with "choices": [] and a usage object. Why does chunk["choices"][0]["delta"] fail on it, and how does the code above avoid the failure?
Show answer
The choices list is empty, so index 0 does not exist and Python raises IndexError. The code checks chunk.get("choices") and skips the chunk when the list is empty.