Sub topic 6
Reading delta events
This chapter assumes you can read Python and JSON, know how Server-Sent Events frame a stream (the previous chapters covered this), and have made a basic LLM API call. It covers what is inside each event after the SSE layer has handed you a data payload.
What a delta event is
A non-streaming response gives you one complete message. A streaming response gives you many small JSON objects, each describing only what changed since the last one. That change is the delta.
The SSE layer delivers each payload as a string. You decode it with json.loads, and the result is a chunk. Each chunk carries a small piece of the message and some metadata. You rebuild the full message by combining chunks in arrival order, which the next chapter covers. This chapter is about reading a single chunk correctly.
The shape of a chat completion chunk
The OpenAI Chat Completions format is widely copied by other providers and gateways, so this chapter uses it as the main example. A typical stream has four kinds of chunk.
- The opening chunk. Its
deltaholds"role": "assistant"and usually an emptycontent. It tells you a message has started. It contains no text. - Content chunks. Each
deltaholds"content": "...", a fragment of text. A fragment is often one token but can be several, or part of a word. Never assume it is a whole word. - The closing chunk. Its
deltais empty ({}) andfinish_reasonis set, for example"stop"or"length". Before this chunk,finish_reasonisnull. - An optional usage chunk. If you request it, the stream sends one more chunk with an empty
choiceslist and ausageobject. After that comes the[DONE]sentinel, which is not JSON.
Fields to read, and fields to ignore
Each chunk repeats metadata such as id, object, created, and model. These are the same on every chunk of one response, so you only need to store them once.
The fields that matter for reading are these:
| Field | Where | Meaning |
|---|---|---|
| `choices[i].index` | each chunk | Which candidate the delta belongs to. Only matters when you request more than one. |
| `choices[i].delta.role` | first chunk | The author of the message. |
| `choices[i].delta.content` | content chunks | A text fragment. May be missing, empty, or `null`. |
| `choices[i].finish_reason` | closing chunk | Why generation ended. `null` until then. |
| `usage` | last chunk, if requested | Token counts for the whole request. |
The key point is that every field is optional on any given chunk. A reader that indexes chunk["choices"][0]["delta"]["content"] directly will crash on the first chunk of some providers, on the closing chunk, and on the usage chunk.
A defensive reader
The following program reads a hand-written stream of payloads. It uses .get everywhere and handles an empty choices list, an empty delta, and a null content value. It runs as shown.
import json
payloads = [
'{"id":"c1","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]}',
'{"id":"c1","choices":[{"index":0,"delta":{"content":"Hel"},"finish_reason":null}]}',
'{"id":"c1","choices":[{"index":0,"delta":{"content":"lo"},"finish_reason":null}]}',
'{"id":"c1","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}',
'{"id":"c1","choices":[],"usage":{"prompt_tokens":12,"completion_tokens":2,"total_tokens":14}}',
"[DONE]",
]
def read_chunk(chunk):
"""Return (text, role, finish_reason, usage) for choice 0 of one chunk."""
text, role, finish = "", None, None
for choice in chunk.get("choices") or []:
if choice.get("index", 0) != 0:
continue
delta = choice.get("delta") or {}
text = delta.get("content") or ""
role = delta.get("role")
finish = choice.get("finish_reason")
return text, role, finish, chunk.get("usage")
for payload in payloads:
if payload == "[DONE]":
print("stream complete")
break
text, role, finish, usage = read_chunk(json.loads(payload))
print(repr(text), role, finish, usage)The output shows 'Hel' and 'lo' as text, 'stop' as the finish reason, and the usage dictionary on the final JSON chunk. The first chunk prints an empty string with the role assistant.
Asking for usage
By default, a streamed response does not report token usage. With the OpenAI SDK you ask for it through stream_options:
from openai import OpenAI
client = OpenAI()
stream = client.chat.completions.create(
model="MODEL_NAME",
messages=[{"role": "user", "content": "Say hello."}],
stream=True,
stream_options={"include_usage": True},
)
for chunk in stream:
if chunk.usage is not None:
print(chunk.usage.total_tokens)The usage chunk is the case that breaks code written as chunk.choices[0], because choices is empty. This is why the guard if chunk.choices appears in the earlier SDK example. Other providers differ here: some attach usage to the closing chunk instead, and some always include it.
Typed events in other providers
Not every provider uses one chunk shape. Anthropic's Messages API, for example, names each SSE event with an event: line and gives each type its own JSON structure.
| Event name | What it carries |
|---|---|
| `message_start` | Message metadata and initial usage. |
| `content_block_start` | The start of a block, such as text or a tool call. |
| `content_block_delta` | A fragment for one block, tagged with the block's `index`. |
| `content_block_stop` | The end of that block. |
| `message_delta` | Top-level changes such as `stop_reason` and updated usage. |
| `message_stop` | The end of the stream. |
The ideas match the first format. There is an opening event, fragments, a finish signal, and usage. The differences are that the event type is explicit, and a message is made of numbered blocks. For this reason, write your reader around a small internal event type, such as "text", "finish", and "usage". Convert each provider's chunks into those, and the rest of your application never sees provider details.
Edge cases to handle
- Unknown event types. Providers add new events over time. Ignore types you do not recognize instead of raising an error.
- Empty fragments. An empty
contentis normal. Do not treat it as the end of the stream. - Multiple choices. With
ngreater than 1, deltas for differentindexvalues interleave. Keep one buffer per index. - Partial Unicode. A fragment is always valid text after the SSE decoder, but one character can be split across network chunks before decoding. Decode bytes incrementally, which the parsing chapter explains.
- Non-text deltas. Fields such as
tool_callsor reasoning content appear in the samedeltaobject. A reader that only checkscontentwill silently skip them. Streamed tool calls are covered later.
Exercise
A stream's last JSON chunk has "choices": [] and a usage object. Your code does chunk["choices"][0]["delta"]["content"] and raises IndexError. Name two changes that fix it while still capturing the usage numbers.
Show answer
First, guard the choices access, for example by looping over chunk.get("choices") or [], so an empty list is skipped. Second, read chunk.get("usage") separately from the choice handling, and store it when it is not None. The guard stops the crash, and the separate usage read keeps the token counts.
Exercise
Why should you not use the first chunk's delta.content as the first piece of visible text, and what should you read from it instead?
Show answer
The first chunk usually carries an empty content and the role field. It signals that the message started, not text. Read role from it, and start appending text from the first chunk whose content is non-empty.