Sub topic 9
Normalizing streaming responses
This chapter assumes you have the neutral request type, the provider interface and the ProviderError class from the earlier chapters. You should also know what server-sent events are: a response body delivered as many small JSON events instead of one.
Why streaming needs its own normalization
A non-streaming call returns one ChatResponse. A streaming call returns a sequence of events, and each provider shapes those events differently.
| Detail | OpenAI-style | Anthropic-style |
|---|---|---|
| Text location | `choices[0].delta.content` | `content_block_delta` event, `delta.text` |
| Event kinds | One chunk shape | Several named event types |
| Input token count | Final chunk, if requested | `message_start` event |
| Output token count | Final chunk, if requested | `message_delta` event |
If call sites parse these shapes themselves, you are coupled to the provider again. The fix is the same as before: define a neutral type and let each adapter translate into it.
A neutral chunk type
Application code needs only three things from a stream: pieces of text, a signal that the stream is finished, and token usage at the end.
from dataclasses import dataclass
from typing import Iterator
@dataclass
class StreamChunk:
text: str = ""
done: bool = False
input_tokens: int | None = None
output_tokens: int | None = NoneAdd a second method to the provider interface. It returns an iterator of StreamChunk and never exposes raw events.
from typing import Protocol
class StreamingProvider(Protocol):
def stream(self, request: "ChatRequest") -> Iterator[StreamChunk]: ...Translating raw events
Each adapter owns one translation function. These two take already-decoded event dictionaries, so you can run them without network access. A real adapter would feed them the parsed lines of the HTTP response.
def normalize_openai(events):
usage = {}
for event in events:
for choice in event.get("choices", []):
text = choice.get("delta", {}).get("content")
if text:
yield StreamChunk(text=text)
if event.get("usage"):
usage = event["usage"]
yield StreamChunk(
done=True,
input_tokens=usage.get("prompt_tokens"),
output_tokens=usage.get("completion_tokens"),
)
def normalize_anthropic(events):
input_tokens = output_tokens = None
for event in events:
kind = event.get("type")
if kind == "message_start":
input_tokens = event["message"]["usage"]["input_tokens"]
elif kind == "content_block_delta":
text = event["delta"].get("text")
if text:
yield StreamChunk(text=text)
elif kind == "message_delta":
output_tokens = event["usage"]["output_tokens"]
yield StreamChunk(
done=True, input_tokens=input_tokens, output_tokens=output_tokens
)Both functions hold usage numbers until the stream ends and emit them once, in the final chunk. Callers then never need to know which event carried the counts. Now check that both produce the same output:
def collect(chunks):
chunks = list(chunks)
return "".join(c.text for c in chunks), chunks[-1]
openai_events = [
{"choices": [{"delta": {"role": "assistant"}}]},
{"choices": [{"delta": {"content": "Hel"}}]},
{"choices": [{"delta": {"content": "lo"}}]},
{"choices": [], "usage": {"prompt_tokens": 5, "completion_tokens": 2}},
]
anthropic_events = [
{"type": "message_start", "message": {"usage": {"input_tokens": 5}}},
{"type": "content_block_delta", "delta": {"text": "Hel"}},
{"type": "content_block_delta", "delta": {"text": "lo"}},
{"type": "message_delta", "usage": {"output_tokens": 2}},
]
a_text, a_last = collect(normalize_openai(openai_events))
b_text, b_last = collect(normalize_anthropic(anthropic_events))
assert a_text == b_text == "Hello"
assert a_last == b_lastCommon errors
- Assuming every event has text. The first OpenAI-style chunk above carries only a role. Skip events with no text instead of indexing into them.
- Treating the last chunk as text. The final chunk has
done=Trueand an emptytext. Checkdonebefore using it. - Raising raw SDK exceptions mid-stream. A connection can drop after output has started. Wrap those failures in
ProviderErrorinside the adapter. - Falling back after output began. If a stream fails after the first chunk, the user has already seen partial text. Switching providers would produce a second, different answer. Only fall back when the failure happens before the first chunk.
Exercise
A stream fails with a retryable ProviderError after three chunks have been yielded. Should completewithfallback-style logic try the next provider? Why or why not?
Show answer
No, not automatically. The caller has already received partial text, and a second provider would generate a different answer from the start. Fallback is safe only when the error occurs before any chunk is yielded. After that, surface the error or restart the whole response deliberately.