Sub topic 9
Normalizing streaming responses
This chapter assumes you have read the earlier chapters on neutral request and response types, the ChatProvider interface, adapters, and error normalization. You should be comfortable with Python generators and with the idea of server-sent events (SSE), where an HTTP response stays open and the server sends small messages as they are ready.
Why streaming needs its own design
A non-streaming call returns one ChatResponse. A streaming call returns many small pieces over time, and each provider cuts and labels those pieces differently. If application code reads provider events directly, every provider's event vocabulary leaks into the user interface code. The fix is the same as for requests: define one neutral event type and make each adapter translate into it.
Streaming also adds problems that non-streaming calls don't have:
- Text, token counts, and the stop reason arrive in different events.
- Some events carry no text at all (pings, role announcements, block markers).
- A call can fail after output has already been shown to the user.
How streams differ between providers
The table compares two common wire formats. The shapes are simplified, but the structure matches what the real services send.
| Concern | OpenAI-style chat stream | Anthropic-style message stream |
|---|---|---|
| Text location | `choices[0].delta.content` | `content_block_delta` event, `delta.text` |
| Start of stream | A delta with only `role` | `message_start` event |
| Stop reason | `finish_reason` on the last choice (`stop`, `length`) | `message_delta` event, `stop_reason` (`end_turn`, `max_tokens`) |
| Input token count | A final chunk with `usage`, if requested | Inside `message_start` |
| Output token count | Same final `usage` chunk | `message_delta` event, `usage` |
| Keep-alive | Comment lines or empty deltas | `ping` events |
| Error mid-stream | Connection drop or error payload | `error` event |
No two columns line up. The OpenAI-style stream reports usage after the stop reason, in a chunk that has no choices. The Anthropic-style stream splits usage across two events at opposite ends of the stream.
A neutral chunk type
Keep the neutral type small. Each chunk can carry text, a stop reason, and token counts. Any field a chunk doesn't have stays empty. Callers then need one loop and no knowledge of event kinds.
from dataclasses import dataclass
from typing import Iterable, Iterator, Protocol
class ProviderError(Exception):
def __init__(self, message: str, retryable: bool):
super().__init__(message)
self.retryable = retryable
@dataclass
class Message:
role: str
content: str
@dataclass
class ChatRequest:
model: str
messages: list[Message]
max_tokens: int = 512
temperature: float | None = None
@dataclass
class ChatResponse:
text: str
model: str
input_tokens: int | None = None
output_tokens: int | None = None
@dataclass
class StreamChunk:
text: str = ""
finish_reason: str | None = None # "stop", "length" or "other"
input_tokens: int | None = None
output_tokens: int | None = None
class StreamingProvider(Protocol):
def stream(self, request: ChatRequest) -> Iterator[StreamChunk]: ...
FINISH_REASONS = {
"stop": "stop",
"end_turn": "stop",
"length": "length",
"max_tokens": "length",
}
def normalize_finish(raw: str | None) -> str:
return FINISH_REASONS.get(raw, "other")Two design choices matter here.
- Chunks carry deltas, not running totals. Each chunk holds only the new text. Providers that send the whole text so far must be converted by the adapter, because mixing the two conventions makes callers double-print text.
- The stop reason is a small closed vocabulary. Code that decides whether to continue a truncated answer needs to test
"length". It should not need to know that one provider saysmax_tokensand another sayslength. Unknown values map to"other"so a new provider value never crashes the caller.
Writing the two adapter translators
Each adapter has two layers. The transport layer opens the HTTP stream and parses SSE lines into dictionaries. The translator turns those dictionaries into StreamChunk objects. Keeping the translator a pure function over an iterable of dictionaries lets you test it with no network, using recorded events.
def openai_events_to_chunks(events: Iterable[dict]) -> Iterator[StreamChunk]:
for event in events:
usage = event.get("usage")
if usage:
yield StreamChunk(
input_tokens=usage["prompt_tokens"],
output_tokens=usage["completion_tokens"],
)
for choice in event.get("choices", []):
text = choice.get("delta", {}).get("content") or ""
raw = choice.get("finish_reason")
if text or raw:
reason = normalize_finish(raw) if raw else None
yield StreamChunk(text=text, finish_reason=reason)
def anthropic_events_to_chunks(events: Iterable[dict]) -> Iterator[StreamChunk]:
input_tokens = None
for event in events:
kind = event["type"]
if kind == "message_start":
input_tokens = event["message"]["usage"]["input_tokens"]
elif kind == "content_block_delta":
delta = event["delta"]
if delta.get("type") == "text_delta":
yield StreamChunk(text=delta["text"])
elif kind == "message_delta":
yield StreamChunk(
finish_reason=normalize_finish(event["delta"].get("stop_reason")),
input_tokens=input_tokens,
output_tokens=event["usage"]["output_tokens"],
)
elif kind == "error":
err = event["error"]
raise ProviderError(
err["message"], retryable=err["type"] == "overloaded_error"
)
# ping, content_block_start, message_stop and similar events are droppedThe Anthropic translator keeps one local variable, input_tokens, from the first event and emits it later. This is typical: the translator is allowed to hold state so the output stream is simpler than the input stream. Events with no neutral meaning are dropped on purpose.
Assembling a full response from a stream
Many callers want the complete text and don't need incremental output. A single helper that folds chunks into a ChatResponse lets the same adapter code serve both cases. A provider can then implement only stream, and the non-streaming path can reuse it.
def collect(chunks: Iterable[StreamChunk], model: str) -> ChatResponse:
parts: list[str] = []
input_tokens = output_tokens = None
for chunk in chunks:
parts.append(chunk.text)
if chunk.input_tokens is not None:
input_tokens = chunk.input_tokens
if chunk.output_tokens is not None:
output_tokens = chunk.output_tokens
return ChatResponse("".join(parts), model, input_tokens, output_tokens)
openai_events = [
{"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": 5, "completion_tokens": 2}},
]
anthropic_events = [
{"type": "message_start", "message": {"usage": {"input_tokens": 5}}},
{"type": "ping"},
{"type": "content_block_delta", "delta": {"type": "text_delta", "text": "Hel"}},
{"type": "content_block_delta", "delta": {"type": "text_delta", "text": "lo"}},
{
"type": "message_delta",
"delta": {"stop_reason": "end_turn"},
"usage": {"output_tokens": 2},
},
{"type": "message_stop"},
]
a = collect(openai_events_to_chunks(openai_events), "m1")
b = collect(anthropic_events_to_chunks(anthropic_events), "m2")
assert (a.text, a.input_tokens, a.output_tokens) == ("Hello", 5, 2)
assert (b.text, b.input_tokens, b.output_tokens) == ("Hello", 5, 2)Two very different event sequences produce the same text and the same token counts. That equality is the property to test whenever you add a provider.
Errors during a stream
Error normalization applies to streams too, with one added difficulty: a stream can fail at two different moments.
- Before the first chunk. The connection is refused, the key is wrong, or the rate limit is hit. No output has been shown, so retrying or falling back is safe.
- After some chunks. The connection drops partway through an answer. The user may already have seen half a sentence. A different provider would start a new answer from the beginning, with different wording.
Your fallback rule should treat these cases differently. The function below switches providers only if the failure happens before any chunk is produced. Errors after the first chunk propagate to the caller, who decides whether to show the partial text, discard it, or restart.
def stream_with_fallback(
providers: list[StreamingProvider], request: ChatRequest
) -> Iterator[StreamChunk]:
last_error: ProviderError | None = None
for provider in providers:
try:
stream = provider.stream(request)
first = next(stream, None)
except ProviderError as err:
if not err.retryable:
raise
last_error = err
continue
if first is not None:
yield first
yield from stream
return
raise last_error or ValueError("no providers configured")A generator doesn't run until someone asks for its first value, so provider errors surface at the next(stream, None) call. That is why both the call and the first read sit inside the try.
Testing streams with a scripted provider
A scripted provider replays fixed chunks and can raise an error at a chosen point. This checks both the happy path and the two failure moments without any network access.
class ScriptedProvider:
def __init__(self, pieces: list[str], error: ProviderError | None = None):
self.pieces = pieces
self.error = error
def stream(self, request: ChatRequest) -> Iterator[StreamChunk]:
for piece in self.pieces:
yield StreamChunk(text=piece)
if self.error:
raise self.error
request = ChatRequest("any", [Message("user", "hi")])
down = ScriptedProvider([], ProviderError("overloaded", retryable=True))
healthy = ScriptedProvider(["Hel", "lo"])
# Failure before the first chunk: fall back to the next provider.
text = "".join(c.text for c in stream_with_fallback([down, healthy], request))
assert text == "Hello"
# Failure after the first chunk: the error reaches the caller.
broken = ScriptedProvider(["Hel"], ProviderError("dropped", retryable=True))
seen = []
try:
for chunk in stream_with_fallback([broken, healthy], request):
seen.append(chunk.text)
except ProviderError:
pass
assert seen == ["Hel"]What the normalization cannot hide
Some differences survive the adapter.
- Chunk size and timing. One provider may send a word per event and another a few characters. Don't assume one chunk is a word, and don't build features such as typing animation that rely on chunk size.
- Usage availability. Some APIs only send token counts if you ask for them in the request, and some never send them while streaming. Fields stay
Nonein those cases. Code that bills by token must handleNone. - Partial structured data. Tool-call arguments often stream as fragments of JSON text, and you can't parse them until the stream ends. Handling these needs a separate event type, which the tool-call chapter covers.
- Cancellation. Closing the stream early stops the output, but whether the provider still bills for the unread tokens varies. Make your adapter close the underlying HTTP response when the consumer stops iterating.
- Content filtering. A provider may end a stream early with a safety-related stop reason. Mapping it to
"other"keeps callers simple but loses the detail. Log the raw value in the adapter.
Exercise
A third provider streams the whole answer so far in each event, for example "Hel", then "Hello", then "Hello world", instead of only the new text. How should its adapter keep StreamChunk consistent with the other two, and what state does the translator need?
Show answer
The translator must emit only the new suffix of each event. It keeps the text it has already emitted, for example seen. For each event it yields event_text[len(seen):] as the chunk text, then sets seen = event_text. This keeps the neutral convention that chunks are deltas, so the collect function and any user interface loop work unchanged. The translator should also check that event_text starts with seen. If it doesn't, the provider rewrote earlier text, and the adapter should raise a non-retryable ProviderError instead of emitting a wrong delta.