03.3 Streaming Responses

Understand LLMsLesson 3 of 1328,383 words12 parts
Module 03 · 0 of 13 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13

Lesson 02.5 showed what streaming is and gave a five-line streaming loop for each provider. Those loops are enough for a demo and not enough for a product. A real streaming feature has to parse a wire format that proxies can break, route a dozen event types per provider, rebuild the final message (text, tool calls, reasoning, usage) from fragments, survive errors that arrive after the server has already said 200 OK, time out a stream that has gone silent without killing one that is merely thinking, stop paying when the user closes the tab, and get every token to a browser through your own backend without leaking the API key. This lesson does all of that, for OpenAI, Anthropic, Gemini and OpenRouter, with code you can run for free against a local model.

What you'll learn

  • When streaming is worth its complexity, and when it isn't
  • The Server-Sent Events (SSE) wire format from the WHATWG specification, the real bytes each provider sends, and how each stream ends
  • How to write and test your own SSE parser, and when you need one
  • Every provider's stream event taxonomy: OpenAI Responses semantic events, Chat Completions chunks, Anthropic content-block events, Gemini generate_content_stream chunks, Gemini Interactions step events, and OpenRouter's variations
  • The SDK stream helpers (responses.stream(), chat.completions.stream(), messages.stream(), send_message_stream()) versus raw iteration, and their traps
  • How to accumulate a correct final message yourself (multiple blocks, tool-call fragments, reasoning, finish reason, usage) and prove it matches the SDK's
  • Streaming reasoning, tool-call arguments, structured output (partial JSON), refusals and citations
  • Errors after HTTP 200: what each SDK raises, why SDKs don't retry streams (and the one exception, google-genai's automatic continuation of very long generations), streams that end with no error at all, and how to restart, continue or resume without showing duplicated text
  • Read timeouts versus total deadlines, keep-alives, closing streams so connections aren't leaked, and what cancellation does to your bill
  • Resumable streams: OpenAI background responses with starting_after, and Gemini Interactions with last_event_id
  • Async streaming on all four providers, and several streams at once
  • Streaming to a browser: FastAPI's native SSE, your own event protocol, EventSource versus fetch(), a minimal page, disconnect handling that cancels the upstream stream, and the proxy, buffering, auth and limit concerns of production
  • Measuring time to first token, time to first visible token, gaps between tokens and throughput with one reusable helper

What you don't need

  • An API key. Every part has something that runs for real without one: raw byte captures and SDK runs against a free local model, mock servers that replay each provider's documented error shapes, and a FastAPI app you drive from Python. The samples that need a hosted provider are marked, and the OpenAI and Anthropic ones have been run unchanged against the local stand-in. Gemini has no local stand-in: its samples are marked hosted-only and were not run.
  • JavaScript experience. The browser part has one 35-line page, commented line by line; everything else is Python.
  • Prior knowledge of SSE, asyncio or FastAPI beyond the basics. Each is explained where it's first used, with links to Module 01B for the general Python skills.

Setup

Use the llm-apis project from lesson 03.1, Part 4, which lessons 03.1 to 03.9 share (Python 3.11+). If you're starting fresh:

bash
uv init llm-apis --bare --python 3.13 && cd llm-apis    # --python matters: see lesson 03.1, 4.2
uv add openai anthropic google-genai python-dotenv \
       httpx pydantic fastapi uvicorn sse-starlette pytest
# or, without uv:
# pip install openai anthropic google-genai python-dotenv httpx \
#     pydantic fastapi uvicorn sse-starlette pytest

openai and anthropic bring their own HTTP library, httpx2, which the mock-server samples import (03.1, 4.5). Plain httpx is for the raw-byte samples and for google-genai. The lesson was written and tested with openai 3.42.1, anthropic 2.4.0 and google-genai 2.34.0 as of November 2026. The command above installs the newest releases, which for google-genai means 3.x: that no longer installs httpx with the SDK (so httpx is in the uv add line above) and changes the default HTTP library and Gemini API version, as 03.1, 4.5 explains.

Keys go in .env, as in 03.1, 3.4:

bash
OPENAI_API_KEY=...
ANTHROPIC_API_KEY=...
GEMINI_API_KEY=...
OPENROUTER_API_KEY=...

No keys? Install Ollama, run ollama pull qwen2.5:0.5b, and set up the local stand-in from 03.1, Part 12 (Ollama, for the OpenAI and Anthropic formats). Samples marked "local model" call it directly; samples marked "provider" run unchanged against it once you've set the *_BASE_URL variables that section describes. Gemini is the exception: Ollama doesn't speak Gemini's API (03.1, 12.4), so every google-genai sample in this lesson is marked hosted-only (it needs GEMINI_API_KEY) and was not run. The local model is tiny, so its answers are often odd or wrong: that doesn't matter here, because this lesson is about the mechanics of streams, which are the same whatever the model says.


What you must be able to do after this lesson#

  • Stream a response and print tokens as they arrive
  • Explain how Server-Sent Events carry a stream
  • Accumulate a streamed response into a final message
  • Handle an error that happens mid-stream
  • Set timeouts and cancel a stream
  • Measure time to first token

Why this matters for an AI engineer#

Streaming is the first feature of an LLM product that users notice, and the first one that breaks in production in ways that never showed up in a notebook:

You'll hear... You'll understand it after...
"Should this endpoint even stream?" 1.3 When not to stream
"It streams locally but arrives all at once in staging." 11.7 Production concerns
"The proxy is choking on : OPENROUTER PROCESSING." 2.4 Keep-alives and 2.5 Write your own SSE parser
"Usage is doubled for OpenRouter but fine for OpenAI." 3.6 OpenRouter
"We summed Claude's message_delta usage and overbilled ourselves." 3.3 Anthropic
"chunk.choices[0] throws IndexError on the last chunk." 3.2 Chat Completions
"The model's JSON is half-written: can we show it yet?" 6.3 Structured output as partial JSON
"We got a 200, then an overloaded_error, and the SDK didn't retry." Part 7: Errors inside a stream
"After a retry the user saw the first paragraph twice." 7.5 Restart, continue or resume
"The stream hung for ten minutes and nothing timed out." 8.1 A read timeout is the longest allowed silence
"We ran out of connections under load." 8.4 Close every stream
"Do we still pay if the user closes the tab?" 8.5 Cancelling a stream
"Can we reconnect to a stream after a network drop?" Part 9: Resumable streams
"Just use EventSource and put the prompt in the URL." 11.5 The browser side
"Time to first token is fine, but users say it feels slow." Part 12: Measuring streams

Part 1: Streaming as an engineering decision#

1.1 What changes when you set stream=True#

Lesson 02.5, Part 8 covered the idea: the model produces tokens one at a time anyway, so the API can send each piece as soon as it exists instead of waiting for the end, and you pay exactly the same per token. From the engineering side, one flag changes a surprising amount:

Non-streaming call Streaming call
Request POST with a JSON body The same request, plus stream: true (Gemini: a different URL, :streamGenerateContent?alt=sse)
Response headers Content-Type: application/json Content-Type: text/event-stream, sent before any text exists
Response body One JSON object, complete Many small events over seconds or minutes, then the connection closes
What your code gets back A finished response object An iterator of event objects you must consume, route and close
Where errors appear The HTTP status code The status code or an event in the middle of a 200 OK body (Part 7)
Where usage and the finish reason live In the response object In the last event, or one near it, and only if the stream finishes (7.6)
Timeouts that make sense "The whole call takes at most N seconds" "No more than N seconds of silence" plus an overall deadline (Part 8)
SDK retries Built in for 429s, 5xx and connection errors Only the request that opens the stream. Once events arrive, none (the exception: google-genai resumes long Gemini generations from a continuation token, 7.4, 4.5b)
Resource use The connection is free as soon as the body is read The connection stays checked out until you finish or close the stream (8.4)

1.2 When streaming pays off#

Stream when a human is waiting for the output, or when your code can act on early parts of it:

Situation Why streaming helps
Chat interfaces and assistants Users start reading after the time to first token instead of after the whole answer (02.5, 1.5). This is the main reason products stream
Long outputs (reports, code, documents) Progress is visible, and the user can stop a bad answer early, which also stops further output from being generated (8.5)
Reasoning models Thinking can take seconds or minutes before any answer text. A stream lets you show "thinking…" or a summary instead of a frozen screen (6.1)
Very long generations Some SDKs refuse to make long non-streaming calls at all. The anthropic SDK raises ValueError("Streaming is required for operations that may take longer than 10 minutes...") when max_tokens is large enough that its 10-minute default timeout could expire (above about 21,333 tokens with default settings; 4.4)
Pipelines that start work early A voice app can speak the first sentence while the rest is generated (Module 09); a UI can show the name of a tool being called before its arguments are complete (6.2)
Keeping idle connections alive A long silent request can be dropped by proxies or load balancers. A stream keeps bytes flowing (11.7)

1.3 When not to stream#

Streaming adds code paths, failure modes and tests. Don't pay for them when nothing benefits:

Situation Why not, and what to do instead
Backend jobs, no human waiting (classification, extraction, nightly summaries) Nobody sees the first token. Use a normal call, or the Batch APIs, which are much cheaper for work that can wait hours (03.9)
Short replies (a label, a yes/no, a one-line answer) The whole answer arrives in about the time to first token anyway. Streaming adds complexity for no visible gain
Structured output consumed by code Your code can't act on half an object. Wait for the complete JSON and validate it (03.4), unless you deliberately render partial objects in a UI (6.3)
Output that must be checked before anyone sees it Moderation, PII filtering or fact checks need the full text. If you show text as it arrives, you've shown it before you could check it. OpenAI's streaming guide warns that streaming "makes it more difficult to moderate the content", and that moderation scores requested with a generation "arrive after the full generated output is available" (Module 12)
Infrastructure that buffers Some serverless platforms, API gateways and CDNs collect the whole body before forwarding it. Streaming through them gives you all the complexity and none of the speed until you fix the buffering (11.7)
Strict request/response contracts If a downstream system expects one JSON response, give it one. You can still stream internally and return the assembled result (4.4 shows get_final_message(), which does exactly this)

What this means for you as an engineer: make streaming a per-endpoint decision, not a global default. User-facing chat: stream. Background extraction: don't. Long reports: stream, even if only to keep the connection alive.

1.4 The three layers of a stream#

Everything in this lesson sits at one of three layers. Knowing which layer a bug lives in saves hours:

flowchart LR
    P["Provider API"] -- "bytes: text/event-stream" --> L1
    subgraph app ["Your backend"]
        L1["Layer 1: SSE framing<br/>lines, fields, blank-line dispatch"] --> L2["Layer 2: provider events<br/>typed objects from the SDK"]
        L2 --> L3["Layer 3: your events<br/>delta, tool, usage, error, done"]
    end
    L3 -- "SSE you design" --> B["Browser or other client"]
  1. Layer 1, SSE framing. Bytes become events: lines, fields, blank lines. This layer knows nothing about LLMs. Proxies, buffering and hand-written parsers break here (Part 2).
  2. Layer 2, provider events. Each event's JSON becomes a typed object: response.output_text.delta, content_block_delta, a Gemini chunk. Each provider has its own taxonomy, and this is where most code lives (Parts 3 to 6).
  3. Layer 3, your events. What your own clients receive: a small, stable, provider-independent protocol that you design (11.2).

The SDKs handle layer 1 and give you layer 2. Your application owns layer 3. A common mistake is to skip layer 3 and forward provider events straight to the browser, which ties your front end to one provider's event names forever.


Part 2: The wire format: Server-Sent Events#

2.1 SSE in one page#

All four providers stream with Server-Sent Events (SSE), a format defined in the WHATWG HTML Living Standard ("9.2 Server-sent events"). It is deliberately simple: plain UTF-8 text, one field per line.

text
: this line is a comment                     <- starts with ":"; ignored (used as a keep-alive)
event: content_block_delta                   <- the event's type
id: 42                                       <- an ID the client can resume from
data: {"type": "content_block_delta", ...}   <- the payload
                                             <- a blank line: dispatch the event
data: first line                             <- an event with no "event:" line has type "message"
data: second line                            <- several data lines are joined with "\n"
                                             <- dispatch

The rules your code depends on:

Rule What the spec says Why it matters for LLM streams
Media type and encoding The MIME type is text/event-stream; the stream is always UTF-8 A different Content-Type usually means an error body (JSON) rather than a stream. Decode bytes incrementally, because a multi-byte character can be split across network chunks
Lines A line ends with CRLF, LF or CR. A leading byte order mark (BOM) is ignored Different servers use different line endings; sse-starlette sends CRLF, FastAPI sends LF
data: Appends its value to the event's data buffer; several data: lines are joined with a line feed Providers put one JSON object on one data: line. Your own server may send multi-line data
event: Sets the event type. Without it, the type is message Anthropic, OpenAI Responses and Interactions send event: lines; Chat Completions and Gemini generate_content don't
id: Sets the "last event ID". It persists until changed, and is ignored if it contains a NUL character Browsers send it back in a Last-Event-ID header when they reconnect (11.5)
retry: Sets the reconnection delay in milliseconds; ignored unless it is only ASCII digits Only matters to EventSource clients
Comments A line starting with : is ignored Used as keep-alives. The spec suggests one "every 15 seconds or so" to protect against proxies that drop idle connections
Dispatch A blank line ends the event. An event with no data is not dispatched. A final event without a trailing blank line is discarded A stream cut mid-event loses that event, which is correct: half a JSON object is useless
Optional space One space after the colon is removed (data: x and data:x are the same) Hand-written parsers that use line[6:] break on servers that omit the space

2.2 Try it: the raw bytes of the streaming APIs#

The SDKs hide these bytes. Seeing them once makes every later part easier. This sample uses httpx directly to send each provider's documented streaming request to the local stand-in (Ollama, which serves the OpenAI and Anthropic formats) and prints the first and last lines exactly as they arrive. repr() makes the blank separator lines visible; the long JSON lines are cut in the middle to fit.

It also saves every raw body into a captures/ folder next to the script, which the parser tests in 2.5 read. The script creates that folder itself, so keep s2_1_raw_capture.py, sse.py and test_sse.py together in one folder.

python
# s2_1_raw_capture.py: print the raw SSE bytes of three streaming APIs (local stand-in, no key)
from pathlib import Path

import httpx

# The captures go next to this script, where test_sse.py looks for them. Create the folder:
# open() will not, and without it the script fails with FileNotFoundError after the first API.
CAPTURES = Path(__file__).parent / "captures"
CAPTURES.mkdir(exist_ok=True)

PROMPT = "Name two primary colours."

# (label, url, headers, JSON body): each one is the provider's documented streaming request
REQUESTS = [
    ("OpenAI Chat Completions (Ollama)",
     "http://localhost:11434/v1/chat/completions",
     {"Authorization": "Bearer ollama"},
     {"model": "gpt-6-luna", "stream": True, "stream_options": {"include_usage": True},
      "max_tokens": 12, "messages": [{"role": "user", "content": PROMPT}]}),
    ("OpenAI Responses (Ollama)",
     "http://localhost:11434/v1/responses",
     {"Authorization": "Bearer ollama"},
     {"model": "gpt-6-luna", "stream": True, "max_output_tokens": 12, "input": PROMPT}),
    ("Anthropic Messages (Ollama)",
     "http://localhost:11434/v1/messages",
     {"x-api-key": "ollama", "anthropic-version": "2026-10-21"},
     {"model": "claude-haiku-5-5", "stream": True, "max_tokens": 12,
      "messages": [{"role": "user", "content": PROMPT}]}),
]


def show(line: str, width: int = 118) -> str:
    """repr() makes blank lines visible. Long lines keep their start and end, with the middle cut."""
    r = repr(line)
    return r if len(r) <= width else r[:62] + " … " + r[-(width - 65):]


with httpx.Client(timeout=httpx.Timeout(10.0, read=60.0)) as client:
    for label, url, headers, body in REQUESTS:
        print(f"===== {label}")
        # client.stream() keeps the connection open and lets us read the body as it arrives
        with client.stream("POST", url, headers=headers, json=body) as response:
            print(f"HTTP {response.status_code}  content-type: {response.headers.get('content-type')}")
            raw = b"".join(response.iter_raw())          # every byte, exactly as sent
        lines = raw.decode("utf-8").split("\n")
        for line in lines[:12]:
            print(show(line))
        print(f"... {len(lines)} lines, {len(raw)} bytes in total. Last 6 lines:")
        for line in lines[-6:]:
            print(show(line))
        safe = label.split(" (")[0].lower().replace(" ", "_")
        (CAPTURES / f"{safe}.sse").write_bytes(raw)   # saved for the parser tests in 2.5
Output · local model qwen2.5:0.5b via Ollama63 lines
===== OpenAI Chat Completions (Ollama)
HTTP 200  content-type: text/event-stream
'data: {"id":"chatcmpl-389","object":"chat.completion.chunk"," … "assistant","content":"Two"},"finish_reason":null}]}'
''
'data: {"id":"chatcmpl-389","object":"chat.completion.chunk"," … stant","content":" primary"},"finish_reason":null}]}'
''
'data: {"id":"chatcmpl-389","object":"chat.completion.chunk"," … istant","content":" colors"},"finish_reason":null}]}'
''
'data: {"id":"chatcmpl-389","object":"chat.completion.chunk"," … "assistant","content":" in"},"finish_reason":null}]}'
''
'data: {"id":"chatcmpl-389","object":"chat.completion.chunk"," … assistant","content":" the"},"finish_reason":null}]}'
''
'data: {"id":"chatcmpl-389","object":"chat.completion.chunk"," … istant","content":" visual"},"finish_reason":null}]}'
''
... 31 lines, 3209 bytes in total. Last 6 lines:
''
'data: {"id":"chatcmpl-389","object":"chat.completion.chunk"," … okens":34,"completion_tokens":12,"total_tokens":46}}'
''
'data: [DONE]'
''
''
===== OpenAI Responses (Ollama)
HTTP 200  content-type: text/event-stream
'event: response.created'
'data: {"response":{"background":false,"completed_at":null,"cr … null},"sequence_number":0,"type":"response.created"}'
''
'event: response.in_progress'
'data: {"response":{"background":false,"completed_at":null,"cr … },"sequence_number":1,"type":"response.in_progress"}'
''
'event: response.output_item.added'
'data: {"item":{"content":[],"id":"msg_207832","role":"assista … uence_number":2,"type":"response.output_item.added"}'
''
'event: response.content_part.added'
'data: {"content_index":0,"item_id":"msg_207832","output_index … ence_number":3,"type":"response.content_part.added"}'
''
... 61 lines, 6081 bytes in total. Last 6 lines:
'data: {"item":{"content":[{"annotations":[],"logprobs":[],"te … uence_number":18,"type":"response.output_item.done"}'
''
'event: response.completed'
'data: {"response":{"background":false,"completed_at":17938065 … }},"sequence_number":19,"type":"response.completed"}'
''
''
===== Anthropic Messages (Ollama)
HTTP 200  content-type: text/event-stream
'event: message_start'
'data: {"type":"message_start","message":{"id":"msg_4e073b5187 … t":[],"usage":{"input_tokens":7,"output_tokens":0}}}'
''
'event: content_block_start'
'data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}'
''
'event: content_block_delta'
'data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Two"}}'
''
'event: content_block_delta'
'data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":" primary"}}'
''
... 49 lines, 1914 bytes in total. Last 6 lines:
'data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"input_tokens":34,"output_tokens":12}}'
''
'event: message_stop'
'data: {"type":"message_stop"}'
''
''

What to notice:

  • Two framing styles. Chat Completions sends only data: lines; the event type is inside the JSON (or implied). Gemini's generate_content stream does the same according to Google's documentation, but it can't be captured here. Responses and Anthropic send an event: line before every data: line, and the JSON repeats the type in a "type" field.
  • Every event ends with a blank line (''), and the body ends with an extra one.
  • Chat Completions ends with data: [DONE], which is not JSON. A parser that calls json.loads() on every data: line crashes on it. The chunk before it has "choices":[] and the usage totals, because the request set stream_options.include_usage.
  • Responses and Anthropic end with a named terminal event (response.completed, message_stop) and no sentinel.
  • Gemini's generate_content stream has no terminal event. Its last chunk carries finishReason and usageMetadata, then the body simply ends (this is the documented behaviour listed in 2.3, not a capture).

Gemini has no local capture. Ollama doesn't speak Gemini's API, so this lesson can't capture Gemini's bytes. Google's documented Interactions stream looks like this (from the streaming guide, abridged):

text
event: interaction.created
data: {"interaction":{"id":"v1_...","status":"in_progress","object":"interaction","model":"gemini-3.8-flash"},"event_type":"interaction.created"}

event: step.start
data: {"index":1,"step":{"type":"model_output"},"event_type":"step.start"}

event: step.delta
data: {"index":1,"delta":{"text":"1, 2, 3, 4, 5, 6, ","type":"text"},"event_type":"step.delta"}

event: interaction.completed
data: {"interaction":{"id":"v1_...","status":"completed","usage":{"total_tokens":346, ...}},"event_type":"interaction.completed"}

event: done
data: [DONE]

2.3 How each stream ends#

A stream that stops without its documented ending was interrupted, even if no exception was raised. This table is the single most useful thing to remember from this part:

API Terminal event (success) Other endings After the terminal event
OpenAI Responses response.completed (carries the full Response, with status and usage) response.incomplete (cap reached: incomplete_details.reason), response.failed (response.error), or an error event The connection closes; no sentinel
OpenAI Chat Completions A chunk with finish_reason set; then, with include_usage, a chunk with choices: [] and usage — data: [DONE]
Anthropic Messages message_stop, after a message_delta carrying stop_reason and usage event: error at any point (7.2) The connection closes
Gemini generate_content The last chunk, whose candidate has a real finish_reason (and usage_metadata). CONTINUATION is not one: it means "ask again" (4.5b) A chunk whose JSON is {"error": {...}} The body ends. No terminal event or sentinel, so "the body ended" plus "a real finish reason was seen" is your only signal
Gemini Interactions interaction.completed (status and usage) error event; interaction.status_update with a non-running status event: done / data: [DONE] in Google's documented sample
OpenRouter Chat Completions Finish chunk, then a usage chunk that also has choices and repeats finish_reason A final chunk with a top-level error and finish_reason: "error" data: [DONE]
OpenRouter Responses / Messages As OpenAI Responses / as Anthropic response.failed / event: error As the format it copies

What this means for you as an engineer: when your loop ends, check that you saw the terminal event (or, for Gemini, a finish reason). If you didn't, treat the result as truncated: log it, don't save it as a complete answer, and decide whether to retry (7.5). Don't expect the SDKs to tell you: most helpers return a partial message without raising, which 7.3 demonstrates, and the accumulators of 5.3 are built to flag.

2.4 Keep-alives: comments, pings and empty events#

While a model queues or thinks, no text exists, but intermediaries such as proxies and load balancers drop connections that stay silent too long. Each provider fills the silence differently:

Provider Keep-alive on the wire What the SDK does with it
OpenAI (normal streams) None documented —
OpenAI (background streams) Events with type: "keepalive", which "use connection counters, not stored-event resume positions" Yielded to you like any other event, so skip them when tracking a cursor (Part 9)
Anthropic event: ping with data: {"type": "ping"}: a real event, not a comment, and it "might" appear any number of times The SDK drops ping events before you see them
Gemini None documented. interaction.status_update events can appear between steps Yielded
OpenRouter SSE comments: : OPENROUTER PROCESSING Ignored by any spec-compliant parser, including the openai SDK's. OpenRouter suggests you can "use it to improve UX", e.g. a loading indicator
Your own FastAPI server : ping comments every 15 s when idle (11.3) Ignored by browsers

2.5 Write your own SSE parser#

The SDKs parse SSE for you. You still need your own parser when you:

  • build a gateway or proxy that relays streams without loading an SDK per provider;
  • call a provider or self-hosted server that has no SDK, or an "OpenAI-compatible" endpoint whose stream the SDK chokes on;
  • consume your own SSE endpoint from Python (tests, other services), as 11.6 does;
  • want to record and replay streams in tests (03.10).

Here is a complete parser that follows the spec, in about 60 lines of logic. It is incremental: you feed it bytes in whatever pieces the network delivers, and it yields each event as soon as its blank line arrives.

python
# sse.py: a small, spec-following Server-Sent Events parser (WHATWG HTML, "event stream interpretation")
import codecs
from dataclasses import dataclass
from typing import Iterable, Iterator


@dataclass
class SSEEvent:
    event: str = "message"   # the spec's default event type when no "event:" line is sent
    data: str = ""           # all "data:" lines of the event, joined with "\n"
    id: str | None = None    # the last event ID seen so far (it persists across events)
    retry: int | None = None # reconnection delay in ms, if this event set one


class SSEParser:
    """Feed it bytes as they arrive; it yields complete events. Works for any chunk boundaries."""

    def __init__(self) -> None:
        # An incremental decoder copes with a multi-byte UTF-8 character split across two chunks
        self._decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
        self._buffer = ""
        self._first = True
        self._last_id: str | None = None
        self._reset()

    def _reset(self) -> None:
        self._event_type = ""
        self._data_lines: list[str] = []
        self._retry: int | None = None

    def feed(self, chunk: bytes) -> Iterator[SSEEvent]:
        text = self._decoder.decode(chunk)
        if self._first and text:
            text = text.removeprefix("")        # the spec says: ignore one leading BOM
            self._first = False
        self._buffer += text
        while True:
            # Lines end with \r\n, \n or \r. A lone \r at the end might be half of \r\n: wait for more.
            cut = min((i for i in (self._buffer.find("\r"), self._buffer.find("\n")) if i != -1), default=-1)
            if cut == -1 or (self._buffer[cut] == "\r" and cut == len(self._buffer) - 1):
                return
            line = self._buffer[:cut]
            step = 2 if self._buffer.startswith("\r\n", cut) else 1
            self._buffer = self._buffer[cut + step:]
            event = self._process_line(line)
            if event is not None:
                yield event

    def finish(self) -> Iterator[SSEEvent]:
        """Call once when the byte stream has ended: flush what the decoder and buffer still hold."""
        # final=True makes the decoder report a character cut off mid-sequence (errors="replace"
        # turns it into U+FFFD) instead of silently dropping its bytes. That fragment sits on a
        # line that never ended, so it is discarded below, but only because we looked at it.
        self._buffer += self._decoder.decode(b"", final=True)
        if self._buffer.endswith("\r"):                 # a lone CR at the very end is a complete line ending
            self._buffer += "\n"
        yield from self.feed(b"")

    def _process_line(self, line: str) -> SSEEvent | None:
        if line == "":                                  # a blank line dispatches the event
            return self._dispatch()
        if line.startswith(":"):                        # a comment: keep-alives such as ": ping"
            return None
        field, sep, value = line.partition(":")
        if sep and value.startswith(" "):               # one space after the colon is dropped
            value = value[1:]
        if field == "data":
            self._data_lines.append(value)
        elif field == "event":
            self._event_type = value
        elif field == "id":
            if "\0" not in value:                       # IDs containing NUL are ignored
                self._last_id = value
        elif field == "retry":
            if value.isascii() and value.isdigit():     # digits only, otherwise ignored
                self._retry = int(value)
        # any other field name is ignored, as the spec requires
        return None

    def _dispatch(self) -> SSEEvent | None:
        if not self._data_lines:                        # no data: reset and dispatch nothing
            self._reset()
            return None
        event = SSEEvent(event=self._event_type or "message", data="\n".join(self._data_lines),
                         id=self._last_id, retry=self._retry)
        self._reset()
        return event
    # At end of stream, an event that was never followed by a blank line is discarded (spec rule).


def iter_sse(chunks: Iterable[bytes]) -> Iterator[SSEEvent]:
    """Parse a whole byte stream, e.g. httpx's response.iter_bytes()."""
    parser = SSEParser()
    for chunk in chunks:
        yield from parser.feed(chunk)
    yield from parser.finish()                 # end of stream: flush the decoder and a trailing CR

iter_sse ends with parser.finish(), and that call matters. A stream that ends has no more bytes to wait for, so two things the parser was holding back must now be settled: a half-received multi-byte character (the decoder is flushed with final=True, which turns it into the replacement character U+FFFD instead of silently swallowing it) and a lone \r at the very end, which the spec treats as a complete line ending rather than "maybe half of \r\n". A cut-off line is still discarded, as the spec requires, but now because the parser looked at it and decided so. If you drive SSEParser yourself instead of through iter_sse, call finish() when the connection closes.

Now prove it works. The tests feed each input in deliberately awkward pieces (7 bytes, or 1 byte at a time), cover the end-of-stream cases, and include three of the raw captures from 2.2:

python
# test_sse.py: run with `uv run --with pytest pytest -q test_sse.py`
import json
from pathlib import Path

import pytest

from sse import SSEParser, iter_sse

CAPTURES = Path(__file__).parent / "captures"


def parse(raw: bytes, chunk_size: int = 7):
    """Feed the bytes in small, awkward pieces, the way a slow network delivers them."""
    chunks = [raw[i:i + chunk_size] for i in range(0, len(raw), chunk_size)]
    return list(iter_sse(chunks))


def test_comments_are_skipped():
    raw = b": OPENROUTER PROCESSING\n\ndata: {\"x\": 1}\n\n: ping\n\n"
    assert [e.data for e in parse(raw)] == ['{"x": 1}']


def test_multi_line_data_is_joined_with_newlines():
    raw = b"data: first line\ndata: second line\n\n"
    assert parse(raw)[0].data == "first line\nsecond line"


def test_event_id_and_retry_fields():
    raw = b"event: delta\nid: 42\nretry: 3000\ndata: hi\n\ndata: next\n\n"
    first, second = parse(raw)
    assert (first.event, first.id, first.retry, first.data) == ("delta", "42", 3000, "hi")
    assert (second.event, second.id) == ("message", "42")   # default type; the ID persists


def test_crlf_and_cr_line_endings():
    assert parse(b"data: a\r\n\r\ndata: b\r\rdata: c\n\n", chunk_size=1) == parse(
        b"data: a\n\ndata: b\n\ndata: c\n\n")


def test_utf8_character_split_across_chunks():
    raw = "data: café ☕\n\n".encode()
    assert parse(raw, chunk_size=1)[0].data == "café ☕"


def test_unfinished_event_at_end_of_stream_is_discarded():
    assert parse(b"data: complete\n\ndata: cut off mid-ev") == parse(b"data: complete\n\n")


def test_lone_cr_at_end_of_stream_ends_the_event():
    assert [e.data for e in parse(b"data: a\r\r")] == ["a"]       # a final CR with no LF after it is a complete line ending


def test_truncated_multibyte_character_at_end_of_stream():
    raw = "data: ok\n\ndata: café".encode()[:-1]                 # cut in the middle of the two-byte "é"
    parser = SSEParser()
    events = list(parser.feed(raw)) + list(parser.finish())
    assert [e.data for e in events] == ["ok"]                    # the cut-off event is discarded and nothing raises
    assert parser._buffer.endswith("caf\ufffd")                  # the half character was reported (U+FFFD), not silently lost


def test_done_sentinel_is_just_data():
    events = parse(b"data: {\"a\": 1}\n\ndata: [DONE]\n\n")
    assert events[-1].data == "[DONE]"       # the parser doesn't special-case it; your code must


@pytest.mark.parametrize("name, first_type, last_type", [
    ("openai_chat_completions", None, "[DONE]"),
    ("openai_responses", "response.created", "response.completed"),
    ("anthropic_messages", "message_start", "message_stop"),
])
def test_real_captures(name, first_type, last_type):
    events = parse((CAPTURES / f"{name}.sse").read_bytes())
    assert len(events) > 3
    if first_type:
        assert events[0].event == first_type or json.loads(events[0].data).get("type") == first_type
    if last_type == "[DONE]":
        assert events[-1].data == "[DONE]"
        assert json.loads(events[-2].data)["choices"] == []      # the usage chunk
    elif last_type:
        assert events[-1].event == last_type
    for e in events:                                               # every payload is valid JSON
        if e.data != "[DONE]":
            json.loads(e.data)

Run it from the folder that holds sse.py and captures/ (the one where you ran the capture script in 2.2), with uv run pytest -v test_sse.py. The test_real_captures cases fail with FileNotFoundError if you skip 2.2, because they replay the bytes it saved. Output:

text
test_sse.py::test_comments_are_skipped PASSED
test_sse.py::test_multi_line_data_is_joined_with_newlines PASSED
test_sse.py::test_event_id_and_retry_fields PASSED
test_sse.py::test_crlf_and_cr_line_endings PASSED
test_sse.py::test_utf8_character_split_across_chunks PASSED
test_sse.py::test_unfinished_event_at_end_of_stream_is_discarded PASSED
test_sse.py::test_lone_cr_at_end_of_stream_ends_the_event PASSED
test_sse.py::test_truncated_multibyte_character_at_end_of_stream PASSED
test_sse.py::test_done_sentinel_is_just_data PASSED
test_sse.py::test_real_captures[openai_chat_completions-None-[DONE]] PASSED
test_sse.py::test_real_captures[openai_responses-response.created-response.completed] PASSED
test_sse.py::test_real_captures[anthropic_messages-message_start-message_stop] PASSED
============================== 12 passed in 0.01s ==============================

2.6 Try it: your parser on a live stream#

The parser plus httpx is a complete streaming client: no SDK involved. This one talks to the stand-in's Anthropic-format endpoint and routes three event types; everything else is ignored on purpose, which is also how unknown future event types should be handled.

python
# s2_4_parser_live.py: your own parser on a live stream (Anthropic format, served by the local Ollama)
import json
import httpx
from sse import iter_sse

body = {"model": "claude-haiku-5-5", "max_tokens": 40, "stream": True,
        "messages": [{"role": "user", "content": "Say hello in French, Spanish and German."}]}
headers = {"x-api-key": "ollama", "anthropic-version": "2026-10-21"}

with httpx.Client(timeout=httpx.Timeout(10.0, read=60.0)) as client:
    with client.stream("POST", "http://localhost:11434/v1/messages", json=body, headers=headers) as r:
        r.raise_for_status()                       # a failure *before* the stream starts is a normal HTTP error
        for ev in iter_sse(r.iter_bytes()):
            payload = json.loads(ev.data)
            if ev.event == "content_block_delta" and payload["delta"]["type"] == "text_delta":
                print(payload["delta"]["text"], end="", flush=True)
            elif ev.event == "message_delta":
                print(f"\n[stop_reason={payload['delta']['stop_reason']} usage={payload['usage']}]")
            elif ev.event == "error":                # a failure *after* the 200: arrives as an event
                raise RuntimeError(payload["error"])
            # every other event type (message_start, ping, ...) is ignored on purpose

Output (local model qwen2.5:0.5b via Ollama; a hosted model's text would differ, and would know German):

text
Bonjour (French)
¡Hola! (Spanish)
Dobson (German)
[stop_reason=end_turn usage={'input_tokens': 38, 'output_tokens': 17}]

What this means for you as an engineer: the SDKs are the right default, but SSE itself is small enough to own. When a stream misbehaves, capture the raw bytes (2.2) and run them through a parser you trust; you'll know in a minute whether the problem is the framing (layer 1) or the events (layer 2).


Part 3: Every provider's stream events#

Reference

Each provider turns the same generation into a different sequence of events. This part gives you, for each API: a table of the events that matter (names, payload fields, order), a sequence diagram, and a real run against the local stand-in that prints every event with its arrival time. 3.7 puts them side by side; 3.8 shows what hosted models add.

3.1 OpenAI Responses: semantic events#

The Responses API sends semantic events: every event has a type saying exactly what happened, and a sequence_number that increases by one with every event in the response. Think of the response as a tree (the response contains output items, which contain content parts, which receive text deltas), and the events as "this node was added", "this node grew", "this node is done".

Family Event type Key payload fields Notes
Lifecycle response.created response (a full Response, status: "in_progress", no output yet) Always first. Holds the id you need to retrieve or resume it
response.queued response Background responses waiting to start (Part 9)
response.in_progress response
Output items response.output_item.added / .done output_index, item (a message, function_call, reasoning, tool call...) One pair per item. .done carries the finished item
Content parts response.content_part.added / .done item_id, output_index, content_index, part (output_text or refusal) Inside message items
Text response.output_text.delta delta (the new text), item_id, output_index, content_index, logprobs The events you render
response.output_text.done text (the whole text of that part)
response.output_text.annotation.added annotation, annotation_index Citations, e.g. from web or file search (6.4)
Refusal response.refusal.delta / .done delta / refusal A refusal is its own content part, not text (6.4)
Function calls response.function_call_arguments.delta delta (a fragment of the JSON arguments), item_id, output_index The call's name and call_id came earlier, in output_item.added (6.2)
response.function_call_arguments.done arguments (the complete JSON string) Parse here, not before
Reasoning response.reasoning_summary_part.added / .done, response.reasoning_summary_text.delta / .done delta, summary_index, item_id Only if you asked for reasoning.summary (6.1)
response.reasoning_text.delta / .done delta, content_index Full reasoning text, for models that expose it
Built-in tools response.web_search_call.*, response.file_search_call.*, response.code_interpreter_call*, response.image_generation_call.*, response.mcp_*, response.custom_tool_call_input.*, response.shell_call_* Progress of each tool Show progress in a UI if you use these tools; otherwise ignore
Endings response.completed response (final status, all output, usage) Success
response.incomplete response with incomplete_details.reason (e.g. "max_output_tokens") Truncated: check it (02.5, 4.6)
response.failed response with error (code, message) The model failed after the stream began
Errors error code, message, param Can arrive mid-stream (7.2)

OpenAI's streaming guide names four events as the minimum to handle for text: response.created, response.output_text.delta, response.completed and error. A production handler also needs response.incomplete and response.failed.

sequenceDiagram
    participant App as Your code
    participant API as OpenAI Responses API
    App->>API: POST /v1/responses with stream true
    API-->>App: response.created (seq 0)
    API-->>App: response.in_progress (seq 1)
    Note over App,API: one block per output item, reasoning first if requested
    API-->>App: response.output_item.added (reasoning)
    API-->>App: response.reasoning_summary_text.delta ...
    API-->>App: response.output_item.done (reasoning)
    API-->>App: response.output_item.added (message)
    API-->>App: response.content_part.added
    API-->>App: response.output_text.delta ... (many)
    API-->>App: response.output_text.done
    API-->>App: response.content_part.done
    API-->>App: response.output_item.done (message)
    API-->>App: response.completed, carrying status and usage
    Note over App,API: or response.incomplete / response.failed, and an error event can appear

Try it free. Every event of a short answer, with arrival times:

python
# s3_1_responses_events.py: every Responses API stream event, with timing (local model, no key)
import time
from openai import OpenAI

client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")   # the local stand-in

start = time.perf_counter()
stream = client.responses.create(
    model="gpt-6-luna",
    input="Name two primary colours.",
    max_output_tokens=16,
    stream=True,
)
with stream:                                       # closes the HTTP connection even if we break early
    for event in stream:
        ms = (time.perf_counter() - start) * 1000
        summary = ""
        if event.type == "response.output_text.delta":
            summary = repr(event.delta)
        elif event.type in ("response.created", "response.in_progress", "response.completed",
                            "response.incomplete", "response.failed"):
            r = event.response
            summary = f"status={r.status}" + (f" usage=in:{r.usage.input_tokens}/out:{r.usage.output_tokens}"
                                              if r.usage else "")
        elif event.type in ("response.output_item.added", "response.output_item.done"):
            summary = f"item={event.item.type} id={event.item.id}"
        elif event.type == "response.output_text.done":
            summary = f"text={event.text!r}"
        print(f"{ms:6.0f} ms  #{event.sequence_number:<3} {event.type:<34} {summary}")

Output (local model qwen2.5:0.5b via Ollama; a hosted model's text, timing and token counts would differ):

text
   198 ms  #0   response.created                   status=in_progress
   198 ms  #1   response.in_progress               status=in_progress
   198 ms  #2   response.output_item.added         item=message id=msg_58125
   198 ms  #3   response.content_part.added        
   198 ms  #4   response.output_text.delta         'Two'
   198 ms  #5   response.output_text.delta         ' primary'
   198 ms  #6   response.output_text.delta         ' colors'
   198 ms  #7   response.output_text.delta         ' in'
   198 ms  #8   response.output_text.delta         ' the'
   199 ms  #9   response.output_text.delta         ' color'
   204 ms  #10  response.output_text.delta         ' wheel'
   209 ms  #11  response.output_text.delta         ' are'
   214 ms  #12  response.output_text.delta         ' blue'
   219 ms  #13  response.output_text.delta         ' and'
   224 ms  #14  response.output_text.delta         ' red'
   230 ms  #15  response.output_text.delta         '.'
   235 ms  #16  response.output_text.delta         ' Blue'
   239 ms  #17  response.output_text.delta         ' is'
   244 ms  #18  response.output_text.delta         ' represented'
   249 ms  #19  response.output_text.delta         ' by'
   249 ms  #20  response.output_text.done          text='Two primary colors in the color wheel are blue and red. Blue is represented by'
   249 ms  #21  response.content_part.done         
   250 ms  #22  response.output_item.done          item=message id=msg_58125
   351 ms  #23  response.completed                 status=completed usage=in:34/out:16

Twenty-four events for sixteen tokens of text (fifteen words): four of setup, one per text delta, three of teardown and the terminal event. sequence_number runs 0 to 23 with no gaps, which is what makes resuming possible (Part 9).

stream_options.include_obfuscation. Both OpenAI APIs accept stream_options={"include_obfuscation": False}. Verified against the SDK's own documentation for the parameter and the API reference: by default OpenAI adds random characters in an obfuscation field on streaming delta events (and on Chat Completions chunks) "to normalize payload sizes as a mitigation to certain side-channel attacks". The attack it addresses: even through TLS, an observer who sees the size of each encrypted packet learns the length of each token, and published research ("What Was Your Prompt? A Remote Keylogging Attack on AI Assistants", Weiss et al., 2024) showed that token lengths alone can leak much of a response. Padding hides the lengths. Setting it to false saves a little bandwidth; OpenAI suggests that only "if you trust the network links between your application and the OpenAI API". Leave it on unless you've measured a problem. Two practical notes:

  • The obfuscation field isn't declared on the openai 3.42.1 SDK's Responses event models, so you'll find it in event.model_extra if you look. It carries no information; never log it or forward it.
  • When you stream to a browser over the internet, the same side channel exists on your own connection (11.7).

3.2 OpenAI Chat Completions: chunks#

Chat Completions streams chunks: every data: line is a chat.completion.chunk object shaped like a tiny completion, whose choices[i].delta holds only what's new.

Field In which chunks Meaning
id, created, model, system_fingerprint Every chunk (same values)
choices[i].index Every chunk with choices Which choice this delta belongs to (n > 1 gives several)
choices[i].delta.role The first chunk (OpenAI) "assistant"
choices[i].delta.content Text chunks The new text, possibly "" or None
choices[i].delta.refusal Refusal chunks New refusal text (6.4)
choices[i].delta.tool_calls[j] Tool-call chunks index (which call), then id, type and function.name on the call's first fragment, and function.arguments fragments after (6.2)
choices[i].finish_reason One chunk per choice, near the end stop, length, tool_calls, content_filter (02.5, 4.5)
usage Only the extra last chunk, if you set stream_options={"include_usage": True}; null on all others Token totals for the whole request
choices [] (empty) in that usage chunk The API reference: the choices list "can also be empty for the last chunk if you set stream_options: {"include_usage": true}"
obfuscation Every chunk unless disabled Padding (3.1)
sequenceDiagram
    participant App as Your code
    participant API as Chat Completions API
    App->>API: POST /v1/chat/completions, stream true, include_usage true
    API-->>App: data: chunk, delta.role = assistant
    API-->>App: data: chunk, delta.content = "Red" (or delta.tool_calls fragments)
    API-->>App: data: chunk, delta.content = " and blue"
    API-->>App: data: chunk, finish_reason = stop
    API-->>App: data: chunk, choices = [ ], usage = totals
    API-->>App: data: [DONE]

Try it free:

python
# s3_2_chat_chunks.py: Chat Completions chunks, including the usage chunk (local model, no key)
import time
from openai import OpenAI

client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")

start = time.perf_counter()
stream = client.chat.completions.create(
    model="gpt-6-luna",
    messages=[{"role": "user", "content": "Name two primary colours."}],
    max_tokens=8,               # Ollama honours max_tokens; OpenAI's newer name is max_completion_tokens
    stream=True,
    stream_options={"include_usage": True},   # ask for one extra, final chunk that carries usage
)
with stream:
    for chunk in stream:
        ms = (time.perf_counter() - start) * 1000
        if not chunk.choices:                  # the usage chunk: choices is an EMPTY list
            print(f"{ms:6.0f} ms  choices=[]  usage={chunk.usage}")
            continue
        choice = chunk.choices[0]
        print(f"{ms:6.0f} ms  delta.role={choice.delta.role!s:<9} delta.content={choice.delta.content!r:<12} "
              f"finish_reason={choice.finish_reason}  usage={chunk.usage}")
Output · local model qwen2.5:0.5b via Ollama10 lines
   158 ms  delta.role=assistant delta.content='Two'        finish_reason=None  usage=None
   163 ms  delta.role=assistant delta.content=' primary'   finish_reason=None  usage=None
   169 ms  delta.role=assistant delta.content=' colors'    finish_reason=None  usage=None
   176 ms  delta.role=assistant delta.content=' are'       finish_reason=None  usage=None
   182 ms  delta.role=assistant delta.content=' red'       finish_reason=None  usage=None
   189 ms  delta.role=assistant delta.content=' and'       finish_reason=None  usage=None
   195 ms  delta.role=assistant delta.content=' blue'      finish_reason=None  usage=None
   202 ms  delta.role=assistant delta.content='.'          finish_reason=None  usage=None
   202 ms  delta.role=assistant delta.content=''           finish_reason=length  usage=None
   202 ms  choices=[]  usage=CompletionUsage(completion_tokens=8, prompt_tokens=34, total_tokens=42, completion_tokens_details=None, prompt_tokens_details=None)

3.3 Anthropic Messages: content-block events#

Anthropic's stream mirrors the structure of a Message: the message starts, then each content block (text, thinking, tool use...) starts, grows and stops, then the message's top-level fields change, then the message stops.

Event Payload Notes
message_start message: a Message with empty content, stop_reason: null, initial usage (input tokens) Always first
content_block_start index, content_block ({"type": "text", "text": ""}, {"type": "thinking", ...}, {"type": "tool_use", "id", "name", "input": {}}, server tool blocks...) index is the block's position in the final content array
content_block_delta index, delta (see below) One or more per block
content_block_stop index The block is complete
message_delta delta.stop_reason, delta.stop_sequence, usage "One or more" of these. The usage is cumulative
message_stop — Always last on success
ping — "Any number" of them, anywhere
error error.type, error.message Can arrive mid-stream, e.g. overloaded_error (7.2)

The delta inside content_block_delta has its own type:

Delta type Field In blocks of type Notes
text_delta text text The answer text
input_json_delta partial_json tool_use (and server tool blocks) Fragments of the input JSON. Anthropic: "the deltas are partial JSON strings, whereas the final tool_use.input is always an object" (6.2)
thinking_delta thinking thinking Thinking text; an empty string when thinking is hidden (6.1)
signature_delta signature thinking Sent "just before the content_block_stop event"; needed when you pass thinking back (02.8, 8.2)
citations_delta citation text "Each delta contains a single citation to add to the citations list on the current text content block" (6.4)
sequenceDiagram
    participant App as Your code
    participant API as Anthropic Messages API
    App->>API: POST /v1/messages with stream true
    API-->>App: message_start (Message with empty content, initial usage)
    loop for each content block (thinking, text, tool_use...)
        API-->>App: content_block_start (index, block type)
        API-->>App: content_block_delta ... (text_delta, input_json_delta, thinking_delta...)
        API-->>App: content_block_stop (index)
    end
    API-->>App: message_delta (stop_reason, CUMULATIVE usage)
    API-->>App: message_stop
    Note over App,API: ping and error events can arrive at any point

Try it free. With stream=True the SDK gives you these raw events (minus ping, which it drops):

python
# s3_3_anthropic_events.py: every raw Messages stream event, with timing (local model, no key)
import time
import anthropic

client = anthropic.Anthropic(base_url="http://localhost:11434", api_key="ollama")   # the local stand-in

start = time.perf_counter()
stream = client.messages.create(
    model="claude-haiku-5-5",
    max_tokens=12,
    messages=[{"role": "user", "content": "Name two primary colours."}],
    stream=True,                                   # raw events, no accumulation
)
with stream:
    for event in stream:
        ms = (time.perf_counter() - start) * 1000
        match event.type:
            case "message_start":
                summary = f"id={event.message.id} usage={event.message.usage.input_tokens} in"
            case "content_block_start":
                summary = f"index={event.index} block={event.content_block.type}"
            case "content_block_delta":
                d = event.delta
                summary = f"index={event.index} {d.type} " + (repr(d.text) if d.type == "text_delta" else "")
            case "content_block_stop":
                summary = f"index={event.index}"
            case "message_delta":
                summary = (f"stop_reason={event.delta.stop_reason} "
                           f"usage(cumulative)=out:{event.usage.output_tokens}")
            case _:
                summary = ""                       # message_stop, and any type added in future
        print(f"{ms:6.0f} ms  {event.type:<20} {summary}")
Output · local model qwen2.5:0.5b via Ollama17 lines
   144 ms  message_start        id=msg_cd74a7fc5c5134c1adf5a4b7 usage=7 in
   144 ms  content_block_start  index=0 block=text
   144 ms  content_block_delta  index=0 text_delta 'Two'
   145 ms  content_block_delta  index=0 text_delta ' of'
   152 ms  content_block_delta  index=0 text_delta ' the'
   158 ms  content_block_delta  index=0 text_delta ' most'
   165 ms  content_block_delta  index=0 text_delta ' widely'
   172 ms  content_block_delta  index=0 text_delta ' used'
   178 ms  content_block_delta  index=0 text_delta ' and'
   185 ms  content_block_delta  index=0 text_delta ' recognizable'
   191 ms  content_block_delta  index=0 text_delta ' primary'
   198 ms  content_block_delta  index=0 text_delta ' colors'
   204 ms  content_block_delta  index=0 text_delta ' in'
   211 ms  content_block_delta  index=0 text_delta ' color'
   211 ms  content_block_stop   index=0
   211 ms  message_delta        stop_reason=max_tokens usage(cumulative)=out:12
   211 ms  message_stop

Two more things you'll meet on hosted Claude models: a fallback content block "at each model boundary" during server-side fallback responses, which arrives as a content_block_start and content_block_stop pair "with no deltas in between", and a stop_details object on the final message explaining a refusal (6.4). Both are reasons to route on block types rather than assume "block 0 is the text".

3.4 Gemini generate_content_stream: whole responses as chunks#

Gemini's original streaming API has no event types at all. client.models.generate_content_stream(...) yields a sequence of complete GenerateContentResponse objects, each holding only the new content. Every convenience you know from a non-streaming response works on each chunk: chunk.text, chunk.candidates[0].content.parts, chunk.function_calls.

What Where in each chunk Notes
New text chunk.text, or the text of each part in chunk.candidates[0].content.parts chunk.text is None for chunks with no text parts
Thought summaries Parts with part.thought == True Only with ThinkingConfig(include_thoughts=True) (6.1)
Function calls Parts with part.function_call Each call arrives whole, in one chunk on the Gemini API (see below)
Finish reason chunk.candidates[0].finish_reason None until the last chunk, then e.g. FinishReason.STOP or FinishReason.MAX_TOKENS. A third kind exists, FinishReason.CONTINUATION: "stopped at the per-request token limit, generation not yet complete". It is not an ending, and by default the SDK hides it and asks again for you (4.6 covers the machinery, and 4.5b shows it)
Usage chunk.usage_metadata An optional field of every GenerateContentResponse. Google's reference doesn't promise which chunks carry it, so keep the latest non-empty value and never sum across chunks. The SDK's own source agrees: within one request "each chunk's usage_metadata is the server's running total", so the latest replaces the earlier ones. (Across continuation hops the SDK sums for you, 4.5b.)
Safety and blocking candidates[0].safety_ratings, prompt_feedback A blocked prompt can produce a chunk with prompt_feedback.block_reason and no candidates
Structured output chunk.parsed Always None while streaming: buffer the text and validate it yourself (6.3)
sequenceDiagram
    participant App as Your code
    participant API as Gemini generateContent
    App->>API: POST models/MODEL:streamGenerateContent?alt=sse
    API-->>App: data: GenerateContentResponse (parts with text)
    API-->>App: data: GenerateContentResponse (parts with text) ...
    API-->>App: data: GenerateContentResponse (finishReason, usageMetadata)
    Note over App,API: no terminator event, the response body simply ends

Hosted-only sample (needs a Gemini key):

python
# s3_4_gemini_chunks.py: generate_content_stream chunks, with timing (hosted Gemini API)
import time
from google import genai
from google.genai import types

client = genai.Client()     # reads GEMINI_API_KEY from the environment

start = time.perf_counter()
for chunk in client.models.generate_content_stream(
    model="gemini-3.8-flash",
    contents="Name two primary colours.",
    config=types.GenerateContentConfig(max_output_tokens=12),
):
    ms = (time.perf_counter() - start) * 1000
    cand = chunk.candidates[0] if chunk.candidates else None
    # Each chunk is a complete GenerateContentResponse object, not a "delta" type
    print(f"{ms:6.0f} ms  {type(chunk).__name__}  text={chunk.text!r:<12} "
          f"finish_reason={cand.finish_reason if cand else None}  "
          f"usage_metadata={'yes' if chunk.usage_metadata else 'None'}")

Function-call arguments don't stream on the Gemini API. The SDK has fields for incremental arguments (FunctionCallingConfig.stream_function_call_arguments, FunctionCall.partial_args and will_continue), but their own docstrings in google-genai 2.34.0 say "This field is not supported in Gemini API" (they are Vertex AI features), and Google's Interactions migration guide confirms that with generateContent, "streaming function calls arrived complete in a single chunk". If you need streamed arguments from Gemini, use Interactions (3.5).

3.5 Gemini Interactions: step events#

The Interactions API streams step events, a design Google calls "symmetric": text, thinking and tool calls all flow through the same step.start → step.delta → step.stop cycle. When you stream with the SDK, you route on event.event_type (not event.type), and each step.delta has a delta.type.

event_type Payload Notes
interaction.created interaction (id, model, status: "in_progress") Save the id: you need it to resume or cancel
interaction.status_update interaction_id, status, sometimes usage "May appear between steps"
step.start index, step (its type: model_output, thought, function_call, server tool steps...) For function_call, the step already has id, name and empty arguments
step.delta index, delta (a type plus data) One or more per step
step.stop index, optionally usage and step_usage (documented for the Antigravity agent) The step is complete
interaction.completed interaction with final status and usage; no steps "Sent when the interaction is finished". In foreground long generations it can come once per continuation hop (9.3)
error error (message, code) Mid-stream failures, e.g. gateway_timeout

The common delta types:

delta.type Fields In steps of type
text text model_output
image, audio, video, document data, mime_type... model_output
thought_summary content (text or image summary) thought, only with thinking_summaries enabled
thought_signature signature thought, "the last delta before step.stop"
arguments_delta arguments (a JSON fragment) function_call: "Must be accumulated across deltas"
text_annotation_delta annotations Citations on text
Tool-specific (google_search_call, code_execution_result, ...) Varies Server-side tool steps

google-genai 2.34.0 knows 26 delta types (3.9); events it doesn't recognize come back as UnknownInteractionSSEEvent (with event_type="UNKNOWN" and the raw payload) instead of raising, which is the "log and skip" behaviour Google asks for. Every event can also carry an event_id, the resume token used in 9.3.

sequenceDiagram
    participant App as Your code
    participant API as Gemini Interactions API
    App->>API: POST /v1beta/interactions?alt=sse with stream true
    API-->>App: interaction.created (id, status in_progress)
    API-->>App: interaction.status_update (may appear between steps)
    loop for each step (thought, model_output, function_call...)
        API-->>App: step.start (index, step type)
        API-->>App: step.delta ... (text, thought_summary, thought_signature, arguments_delta)
        API-->>App: step.stop (index)
    end
    API-->>App: interaction.completed (status, usage)
    API-->>App: event done, data [DONE]
    Note over App,API: an error event can arrive instead, every event can carry an event_id

Hosted-only sample (needs a Gemini key):

python
# s3_5_interactions_events.py: Interactions API stream events, with timing (hosted Gemini API)
import time
from google import genai

client = genai.Client()     # reads GEMINI_API_KEY from the environment

start = time.perf_counter()
stream = client.interactions.create(
    model="gemini-3.8-flash",
    input="Name two primary colours.",
    generation_config={"max_output_tokens": 12},
    stream=True,
)
with stream:
    for event in stream:
        ms = (time.perf_counter() - start) * 1000
        match event.event_type:                        # Interactions uses event_type, not type
            case "step.start":
                summary = f"index={event.index} step={event.step.type}"
            case "step.delta":
                d = event.delta
                summary = f"index={event.index} {d.type} " + (repr(d.text) if d.type == "text" else "")
            case "step.stop":
                summary = f"index={event.index}"
            case "interaction.created" | "interaction.completed":
                summary = f"status={event.interaction.status} usage={event.interaction.usage}"
            case "interaction.status_update":
                summary = f"status={event.status}"
            case "error":
                summary = f"error={event.error}"
            case _:
                summary = f"(unknown event, skipped) {event!r:.60}"   # log and skip, as Google advises
        print(f"{ms:6.0f} ms  {event.event_type:<22} {summary}")

3.6 OpenRouter: Chat Completions chunks with extras#

OpenRouter's primary API is Chat Completions, so its stream is the chunk format of 3.2, parsed by the same openai SDK. The differences are small and each one breaks naive code:

Difference OpenAI OpenRouter
Keep-alives None : OPENROUTER PROCESSING comment lines while the request is queued or the provider is slow (2.4)
When usage is sent Only with stream_options.include_usage Always. OpenRouter's usage-accounting page (as of November 2026): stream_options: { include_usage: true } is "deprecated and [has] no effect"; usage is "always included automatically"
The usage chunk's choices [] Not empty: it repeats the last delta and finish_reason. So "the terminal finish_reason appears twice", and OpenRouter tells clients to treat the usage chunk "as an accounting frame rather than a second terminal event"
Extra fields — provider at the top level, native_finish_reason on each choice, cost and cost_details in usage, reasoning in delta.reasoning / delta.reasoning_details; all arrive in model_extra with the openai SDK (03.7 owns the cost fields)
Mid-stream errors — A final chunk with a top-level error and finish_reason: "error" (7.2)
Generation ID x-request-id header X-Generation-Id response header on all endpoints, plus the chunk id (gen-...)
sequenceDiagram
    participant App as Your code
    participant OR as OpenRouter
    participant Up as Upstream provider
    App->>OR: POST /api/v1/chat/completions with stream true
    OR->>Up: route the request
    OR-->>App: : OPENROUTER PROCESSING (comment, while queued)
    Up-->>OR: tokens
    OR-->>App: data: chunk, delta.content ...
    OR-->>App: data: chunk, finish_reason = stop
    OR-->>App: data: chunk, choices NOT empty, finish_reason again, usage incl. cost
    OR-->>App: data: [DONE]

OpenRouter's Responses endpoint (/api/v1/responses) streams OpenAI's semantic events, with usage in response.completed, and its Messages endpoint (/api/v1/messages) streams Anthropic's events, with usage in message_delta. The same handler code you write for OpenAI and Anthropic works on them.

The local stand-in can't produce OpenRouter's quirks, so this sample serves a mock stream (layer 3) built from the shapes in OpenRouter's streaming docs, and runs the real openai SDK on it:

python
# s3_6_openrouter_mock.py: OpenRouter's stream shape, served by a MOCK transport (no network, no key).
# The fixture copies the shapes in OpenRouter's streaming docs: keep-alive comments, and a final
# usage chunk whose `choices` is NOT empty (unlike OpenAI's).
import json
import httpx2
from openai import OpenAI


def chunk(choices: list, **extra) -> bytes:
    body = {"id": "gen-abc123", "object": "chat.completion.chunk", "created": 1793750000,
            "model": "anthropic/claude-haiku-5.5", "provider": "Anthropic", "choices": choices, **extra}
    return f"data: {json.dumps(body)}\n\n".encode()


def delta(text: str, finish: str | None = None) -> dict:
    return {"index": 0, "delta": {"role": "assistant", "content": text},
            "finish_reason": finish, "native_finish_reason": finish}


FIXTURE = b"".join([
    b": OPENROUTER PROCESSING\n\n",                          # keep-alive comment while the provider queues
    b": OPENROUTER PROCESSING\n\n",
    chunk([delta("Red and")]),
    chunk([delta(" blue.")]),
    chunk([delta("", "stop")]),                              # finish_reason, first time
    chunk([delta("", "stop")], usage={                       # usage chunk: choices repeats finish_reason
        "prompt_tokens": 14, "completion_tokens": 5, "total_tokens": 19, "cost": 0.0000395}),
    b"data: [DONE]\n\n",
])


def handler(request: httpx2.Request) -> httpx2.Response:
    return httpx2.Response(200, headers={"content-type": "text/event-stream"}, content=FIXTURE)


client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key="sk-test",
                http_client=httpx2.Client(transport=httpx2.MockTransport(handler)))

stream = client.chat.completions.create(
    model="anthropic/claude-haiku-5.5",
    messages=[{"role": "user", "content": "Name two primary colours."}],
    stream=True,
)
text, finish_reasons, usage = [], [], None
with stream:
    for c in stream:
        if c.usage is not None:          # check usage on EVERY chunk, independent of choices
            usage = c.usage
        if c.choices:                    # guard: OpenAI's usage chunk has no choices at all
            ch = c.choices[0]
            text.append(ch.delta.content or "")
            if ch.finish_reason:
                finish_reasons.append(ch.finish_reason)

print("text:", "".join(text))
print("finish_reason seen", len(finish_reasons), "times:", finish_reasons)
print("usage:", usage.prompt_tokens, "in /", usage.completion_tokens, "out | cost (model_extra):",
      usage.model_extra.get("cost") if usage and usage.model_extra else None)
Output3 lines
text: Red and blue.
finish_reason seen 2 times: ['stop', 'stop']
usage: 14 in / 5 out | cost (model_extra): 3.95e-05

3.7 The same stream on every provider#

OpenAI Responses OpenAI Chat Completions Anthropic Gemini generate_content Gemini Interactions OpenRouter (Chat)
Event type lives in event: line and type (implied: every line is a chunk) event: line and type (implied) event: line and event_type (implied)
Text delta response.output_text.delta → delta choices[0].delta.content content_block_delta + text_delta → text chunk.text step.delta + text → text as Chat
Tool-argument delta response.function_call_arguments.delta delta.tool_calls[j].function.arguments input_json_delta → partial_json none: calls arrive whole arguments_delta → arguments as Chat
Reasoning delta response.reasoning_summary_text.delta none thinking_delta (on Claude 5.x the default is an empty one, 6.1) parts with thought=True thought_summary delta.reasoning_details (documented), delta.reasoning (observed)
Finish reason response.status + incomplete_details in the terminal event choices[0].finish_reason message_delta.delta.stop_reason candidates[0].finish_reason on the last chunk (CONTINUATION is not a final one) interaction.status in interaction.completed finish_reason (twice) + native_finish_reason
Usage response.usage in the terminal event last chunk, opt-in message_start (input) then message_delta (cumulative) usage_metadata, keep the latest interaction.usage in interaction.completed usage chunk, always
End of stream terminal event [DONE] message_stop body ends interaction.completed, then [DONE] [DONE]
Keep-alive keepalive (background) — ping — — : comments
Ordering / resume sequence_number — — — event_id —

3.8 The full event list from hosted models#

The stand-in never thinks, so it never emits reasoning events. This provider sample (layer 4) asks each hosted API a small reasoning question with reasoning output turned on, and prints the sequence of event types with repeats collapsed, so you can see the real shape of a reasoning stream:

python
# s3_8_hosted_events.py: the full event sequence from each hosted provider, with reasoning on.
# Needs keys in .env: OPENAI_API_KEY, ANTHROPIC_API_KEY, GEMINI_API_KEY, OPENROUTER_API_KEY
import os

import anthropic
from dotenv import load_dotenv
from google import genai
from google.genai import types
from openai import OpenAI

load_dotenv()
PROMPT = "Is 391 a prime number? Answer in one sentence."


def collapse(names: list[str]) -> str:
    """['a', 'b', 'b', 'b'] -> 'a, b ×3': repeated deltas collapsed so the shape is visible."""
    out: list[list] = []
    for n in names:
        if out and out[-1][0] == n:
            out[-1][1] += 1
        else:
            out.append([n, 1])
    return "\n  ".join(f"{n} ×{c}" if c > 1 else n for n, c in out)


# OpenAI Responses, with a reasoning summary so reasoning events are streamed
openai_client = OpenAI()
names = []
with openai_client.responses.create(model="gpt-6-luna", input=PROMPT, stream=True,
                                    reasoning={"effort": "low", "summary": "auto"}) as stream:
    for event in stream:
        names.append(event.type)
        if event.type == "response.completed" and event.response.usage:
            u = event.response.usage
            names.append(f"(usage: {u.input_tokens} in, {u.output_tokens} out, "
                         f"{u.output_tokens_details.reasoning_tokens} reasoning)")
print("OpenAI Responses:\n  " + collapse(names))

# Anthropic, with adaptive thinking whose summary is streamed
claude = anthropic.Anthropic()
names = []
with claude.messages.create(model="claude-haiku-5-5", max_tokens=4_000, stream=True,
                            thinking={"type": "adaptive", "display": "summarized"},
                            messages=[{"role": "user", "content": PROMPT}]) as stream:
    for event in stream:
        if event.type == "content_block_start":
            names.append(f"content_block_start({event.content_block.type})")
        elif event.type == "content_block_delta":
            names.append(f"content_block_delta({event.delta.type})")
        elif event.type == "message_delta":
            names.append(f"message_delta(stop_reason={event.delta.stop_reason}, "
                         f"output_tokens={event.usage.output_tokens})")
        else:
            names.append(event.type)
print("Anthropic:\n  " + collapse(names))

# Gemini generate_content_stream, with thought summaries included
gemini = genai.Client()
names = []
for chunk in gemini.models.generate_content_stream(
    model="gemini-3.8-flash", contents=PROMPT,
    config=types.GenerateContentConfig(thinking_config=types.ThinkingConfig(include_thoughts=True)),
):
    parts = chunk.candidates[0].content.parts if chunk.candidates and chunk.candidates[0].content else None
    kinds = sorted({"thought" if p.thought else "text" for p in parts or [] if p.text})
    finish = chunk.candidates[0].finish_reason if chunk.candidates else None
    names.append(f"chunk(parts={'+'.join(kinds) or '-'}"
                 + (f", finish_reason={finish}" if finish else "")
                 + (f", usage_metadata.candidates_token_count={chunk.usage_metadata.candidates_token_count}"
                    if chunk.usage_metadata and finish else "") + ")")
print("Gemini generate_content:\n  " + collapse(names))

# Gemini Interactions, with thought summaries
names = []
with gemini.interactions.create(model="gemini-3.8-flash", input=PROMPT, stream=True,
                                generation_config={"thinking_summaries": "auto"}) as stream:
    for event in stream:
        if event.event_type == "step.start":
            names.append(f"step.start({event.step.type})")
        elif event.event_type == "step.delta":
            names.append(f"step.delta({event.delta.type})")
        elif event.event_type == "interaction.completed":
            u = event.interaction.usage
            names.append(f"interaction.completed(usage: {u.total_output_tokens if u else '?'} out, "
                         f"{u.total_thought_tokens if u else '?'} thought)")
        else:
            names.append(event.event_type)
print("Gemini Interactions:\n  " + collapse(names))

# OpenRouter Chat Completions (attribution headers identify your app on OpenRouter)
openrouter = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=os.environ["OPENROUTER_API_KEY"],
                    default_headers={"HTTP-Referer": "https://example.com", "X-OpenRouter-Title": "Streaming lesson"})
names = []
# `reasoning` is an OpenRouter-only request field, so it goes in extra_body. Anthropic models reason
# through OpenRouter ONLY when you send it ("effort" or "max_tokens"); without it you get no reasoning chunks.
with openrouter.chat.completions.create(model="anthropic/claude-haiku-5.5", stream=True,
                                        messages=[{"role": "user", "content": PROMPT}],
                                        extra_body={"reasoning": {"effort": "low"}}) as stream:
    for c in stream:
        if c.choices:
            d = c.choices[0].delta
            extra = d.model_extra or {}                   # OpenRouter-only fields land in model_extra
            # documented: delta.reasoning_details. A plain delta.reasoning string is observed, not documented
            kind = ("content" if d.content else
                    "reasoning" if extra.get("reasoning") or extra.get("reasoning_details") else "empty")
            names.append(f"chunk(delta={kind}" + (f", finish_reason={c.choices[0].finish_reason}"
                                                  if c.choices[0].finish_reason else "")
                         + (f", usage={c.usage.completion_tokens} out" if c.usage else "") + ")")
print("OpenRouter Chat Completions:\n  " + collapse(names))
Example output · illustrative48 lines
OpenAI Responses:
  response.created
  response.in_progress
  response.output_item.added
  response.reasoning_summary_part.added
  response.reasoning_summary_text.delta ×9
  response.reasoning_summary_text.done
  response.reasoning_summary_part.done
  response.output_item.done
  response.output_item.added
  response.content_part.added
  response.output_text.delta ×17
  response.output_text.done
  response.content_part.done
  response.output_item.done
  response.completed
  (usage: 19 in, 212 out, 176 reasoning)
Anthropic:
  message_start
  content_block_start(thinking)
  content_block_delta(thinking_delta) ×6
  content_block_delta(signature_delta)
  content_block_stop
  content_block_start(text)
  content_block_delta(text_delta) ×5
  content_block_stop
  message_delta(stop_reason=end_turn, output_tokens=187)
  message_stop
Gemini generate_content:
  chunk(parts=thought) ×3
  chunk(parts=text) ×2
  chunk(parts=text, finish_reason=FinishReason.STOP, usage_metadata.candidates_token_count=21)
Gemini Interactions:
  interaction.created
  interaction.status_update
  step.start(thought)
  step.delta(thought_summary) ×3
  step.delta(thought_signature)
  step.stop
  step.start(model_output)
  step.delta(text) ×3
  step.stop
  interaction.completed(usage: 21 out, 233 thought)
OpenRouter Chat Completions:
  chunk(delta=reasoning) ×11
  chunk(delta=content) ×6
  chunk(delta=empty, finish_reason=stop)
  chunk(delta=empty, finish_reason=stop, usage=203 out)

How to read it (the OpenRouter call sends extra_body={"reasoning": {"effort": "low"}}: on Anthropic models OpenRouter only reasons when you send its unified reasoning object, so without it that last block would show no reasoning chunks at all. OpenRouter documents the streamed reasoning as choices[].delta.reasoning_details; a plain delta.reasoning string is something the sample's detection also checks because it has been observed, but it isn't documented): every reasoning stream starts with thinking (or a placeholder for it), and the visible answer comes last. On OpenAI that's a separate reasoning output item before the message item; on Claude a thinking block (index 0) before the text block; on Gemini thought parts or a thought step before the output; on OpenRouter reasoning deltas before content deltas. The counts (how many deltas, how many tokens) vary from run to run.

3.9 List the event types your SDK knows#

Event lists grow with every release. Instead of trusting a table (including the ones above), ask the SDK you have installed. This needs no network:

python
# s3_0_event_catalogue.py: list every stream event type the installed SDKs know about (no network)
import textwrap
import typing

from anthropic.types import RawContentBlockDelta, RawMessageStreamEvent
from google.genai._gaos.types.interactions import interactionsseevent, stepdeltadata  # generated sub-SDK. PRIVATE path: may move in any release, so pin google-genai (2.34.0 here)
from openai.types.responses import ResponseStreamEvent


def literal_types(union, field: str = "type") -> list[str]:
    """Read the Literal value of `field` from every model in a (possibly annotated) union."""
    args = typing.get_args(union)
    if args and typing.get_origin(args[0]) is typing.Union:   # Annotated[Union[...], ...]
        args = typing.get_args(args[0])
    names = []
    for model in args:
        ann = model.model_fields[field].annotation
        while typing.get_args(ann) and not isinstance(typing.get_args(ann)[0], str):
            ann = typing.get_args(ann)[0]                      # unwrap Annotated[Literal[...], ...]
        names.append(typing.get_args(ann)[0])
    return sorted(names)


openai_events = literal_types(ResponseStreamEvent)
print(f"openai 3.42.1, Responses stream: {len(openai_events)} event types")
families: dict[str, int] = {}
for name in openai_events:
    family = name.split(".")[1] if "." in name else name
    families[family] = families.get(family, 0) + 1
print(textwrap.fill(", ".join(f"{k}={v}" for k, v in sorted(families.items())), 96,
                    initial_indent="  by family: ", subsequent_indent="    "))
print("anthropic 2.4.0, Messages stream:", literal_types(RawMessageStreamEvent))
print("  content_block_delta types:", literal_types(RawContentBlockDelta))
print("google-genai 2.34.0, Interactions stream:", sorted(interactionsseevent._INTERACTION_SSE_EVENT_VARIANTS))
print(textwrap.fill(", ".join(sorted(stepdeltadata._STEP_DELTA_DATA_VARIANTS)), 96,
                    initial_indent=f"  step.delta types ({len(stepdeltadata._STEP_DELTA_DATA_VARIANTS)}): ",
                    subsequent_indent="    "))
Output17 lines
openai 3.42.1, Responses stream: 59 event types
  by family: audio=4, code_interpreter_call=3, code_interpreter_call_code=2, compaction=1,
    completed=1, content_part=2, created=1, custom_tool_call_input=2, error=1, failed=1,
    file_search_call=3, function_call_arguments=2, image_generation_call=4, in_progress=1,
    incomplete=1, mcp_call=3, mcp_call_arguments=2, mcp_list_tools=3, output_item=2,
    output_text=3, queued=1, reasoning_summary_part=2, reasoning_summary_text=2,
    reasoning_text=2, refusal=2, shell_call_command=3, shell_call_output_content=2,
    web_search_call=3
anthropic 2.4.0, Messages stream: ['content_block_delta', 'content_block_start', 'content_block_stop', 'message_delta', 'message_start', 'message_stop']
  content_block_delta types: ['citations_delta', 'input_json_delta', 'signature_delta', 'text_delta', 'thinking_delta']
google-genai 2.34.0, Interactions stream: ['error', 'interaction.completed', 'interaction.created', 'interaction.status_update', 'step.delta', 'step.start', 'step.stop']
  step.delta types (26): arguments_delta, audio, code_execution_call, code_execution_result,
    document, file_search_call, file_search_result, function_result, google_maps_call,
    google_maps_result, google_search_call, google_search_result, image, mcp_server_tool_call,
    mcp_server_tool_result, processing_call, processing_result, retrieval_call,
    retrieval_result, text, text_annotation_delta, thought_signature, thought_summary,
    url_context_call, url_context_result, video

Two things this reveals. First, the 59 OpenAI types are mostly tool progress events; a text-and-tools application routes about fifteen of them. Second, ping and error are not in the anthropic SDK's event union at all: the SDK handles both below the level you see, by dropping pings and raising errors as exceptions (7.3).

What this means for you as an engineer: write each provider's event handler as a match on the type string with a default branch that ignores (and perhaps counts) unknown types. Re-run the catalogue when you upgrade an SDK, and diff it against the last one; new types are new features you may want to render.


Part 4: SDK stream helpers vs raw iteration#

4.1 Two ways to stream with each SDK#

Every SDK offers a raw stream (an iterator of provider events, exactly as in Part 3) and most offer a helper: a context manager that consumes the same events, accumulates the final message for you, and adds convenience events and methods.

SDK Raw iteration Helper What the helper adds
openai (Responses) client.responses.create(..., stream=True) with client.responses.stream(...) as stream: snapshot on text and argument deltas, get_final_response(), until_done(), text_format= parsing, resuming with response_id= + starting_after=
openai (Chat Completions) client.chat.completions.create(..., stream=True) with client.chat.completions.stream(...) as stream: Typed events (content.delta, tool_calls.function.arguments.delta, refusal.delta...), partial parsing of response_format and strict tools, get_final_completion()
anthropic client.messages.create(..., stream=True) with client.messages.stream(...) as stream: text_stream, synthetic text / input_json / thinking / signature / citation events with snapshots, current_message_snapshot, get_final_message(), get_final_text(), until_done(), output_format= parsing
google-genai (generate_content) client.models.generate_content_stream(...) chat.send_message_stream(...) on a client.chats session History recorded for you after the stream finishes. There is no accumulation helper: you join the chunks yourself. Both resume long generations by themselves (automatic continuation, 4.5b)
google-genai (Interactions) client.interactions.create(..., stream=True) — (the raw stream is the API) Automatic continuation across long-generation hops (4.6)

The async versions are the same methods on AsyncOpenAI, AsyncAnthropic and client.aio (Part 10).

4.2 OpenAI: responses.stream()#

python
with client.responses.stream(model=..., input=..., text_format=MyModel) as stream:
    for event in stream:        # the raw event types, some with extra fields
        ...
    response = stream.get_final_response()   # a ParsedResponse: .output_text, .output_parsed, .usage

The helper yields the same event types as raw iteration, but response.output_text.delta and response.function_call_arguments.delta gain a snapshot (everything so far), and response.output_text.done gains parsed when you pass text_format=. Leaving the with block closes the HTTP response; until_done() consumes the rest of the stream without your loop; close() stops early.

Part B of the next sample, and several later ones, need a stream the stand-in can't produce. They use this small module of mock helpers (layer 3): an httpx2 client whose every request is answered with an SSE body you choose, so the real SDK parses a fixture you wrote:

python
# mockkit.py: helpers for the MOCK stream demos (fixtures only; nothing here talks to a provider)
import json
from collections.abc import Sequence

import httpx2


def sse_body(events: Sequence[tuple[str | None, dict | str]]) -> bytes:
    out = []
    for name, data in events:
        line = data if isinstance(data, str) else json.dumps(data)
        out.append((f"event: {name}\n" if name else "") + f"data: {line}\n\n")
    return "".join(out).encode()


def mock_client_transport(events: Sequence[tuple[str | None, dict | str]]) -> httpx2.Client:
    """An httpx2 client (for the openai/anthropic SDKs) whose every request gets this SSE body."""
    body = sse_body(events)
    return httpx2.Client(transport=httpx2.MockTransport(
        lambda request: httpx2.Response(200, headers={"content-type": "text/event-stream"}, content=body)))


def claude_message_start(input_tokens: int = 40) -> tuple[str, dict]:
    return ("message_start", {"type": "message_start", "message": {
        "id": "msg_1", "type": "message", "role": "assistant", "content": [], "model": "claude-opus-5-5",
        "stop_reason": None, "stop_sequence": None, "usage": {"input_tokens": input_tokens, "output_tokens": 1}}})


def claude_block(index: int, block: dict, deltas: list[dict]) -> list[tuple[str, dict]]:
    return ([("content_block_start", {"type": "content_block_start", "index": index, "content_block": block})]
            + [("content_block_delta", {"type": "content_block_delta", "index": index, "delta": d}) for d in deltas]
            + [("content_block_stop", {"type": "content_block_stop", "index": index})])


def claude_end(stop_reason: str, output_tokens: int) -> list[tuple[str, dict]]:
    return [("message_delta", {"type": "message_delta", "delta": {"stop_reason": stop_reason, "stop_sequence": None},
                               "usage": {"output_tokens": output_tokens}}),
            ("message_stop", {"type": "message_stop"})]
python
# s4_2_responses_helper.py: the openai Responses stream helper.
# Part A runs against the local model; part B uses a MOCK stream that ends in response.incomplete.
from openai import OpenAI

from mockkit import mock_client_transport

local = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
with local.responses.stream(model="gpt-6-luna", input="Name two primary colours.", max_output_tokens=12) as stream:
    for event in stream:
        if event.type == "response.output_text.delta":     # helper version adds .snapshot (text so far)
            print(f"delta={event.delta!r:<12} snapshot={event.snapshot!r}")
    final = stream.get_final_response()                    # a full Response, as non-streaming would give
print("output_text:", repr(final.output_text), "| status:", final.status, "| usage out:",
      final.usage.output_tokens if final.usage else None)

# Part B: a response cut off by max_output_tokens ends with response.incomplete, not .completed
RESP = {"id": "resp_1", "object": "response", "created_at": 1, "model": "gpt-6-luna", "output": [],
        "parallel_tool_calls": True, "tool_choice": "auto", "tools": []}
EVENTS = [("response.created", {"type": "response.created", "sequence_number": 0,
                                "response": {**RESP, "status": "in_progress"}}),
          ("response.incomplete", {"type": "response.incomplete", "sequence_number": 1,
                                   "response": {**RESP, "status": "incomplete",
                                                "incomplete_details": {"reason": "max_output_tokens"}}})]
mocked = OpenAI(api_key="sk-test", http_client=mock_client_transport(EVENTS))
with mocked.responses.stream(model="gpt-6-luna", input="Write an essay.", max_output_tokens=5) as stream:
    terminal = None
    for event in stream:
        if event.type in ("response.completed", "response.incomplete", "response.failed"):
            terminal = event                               # keep the terminal event yourself
    try:
        stream.get_final_response()
    except RuntimeError as e:
        print("get_final_response() raised:", e)
print("so read the terminal event instead:", terminal.type if terminal else None,
      terminal.response.incomplete_details if terminal else None)
Output · part A: local model qwen2.5:0.5b via Ollama; part B: mock server15 lines
delta='Two'        snapshot='Two'
delta=' primary'   snapshot='Two primary'
delta=' colors'    snapshot='Two primary colors'
delta=' in'        snapshot='Two primary colors in'
delta=' the'       snapshot='Two primary colors in the'
delta=' color'     snapshot='Two primary colors in the color'
delta=' spectrum'  snapshot='Two primary colors in the color spectrum'
delta=' are'       snapshot='Two primary colors in the color spectrum are'
delta=' red'       snapshot='Two primary colors in the color spectrum are red'
delta=' and'       snapshot='Two primary colors in the color spectrum are red and'
delta=' blue'      snapshot='Two primary colors in the color spectrum are red and blue'
delta='.'          snapshot='Two primary colors in the color spectrum are red and blue.'
output_text: 'Two primary colors in the color spectrum are red and blue.' | status: completed | usage out: 12
get_final_response() raised: Didn't receive a `response.completed` event.
so read the terminal event instead: response.incomplete IncompleteDetails(reason='max_output_tokens')

4.3 OpenAI: chat.completions.stream()#

The Chat Completions helper is different in kind: it yields its own event types, built from the chunks.

Helper event Fields Fires when
chunk chunk, snapshot Every raw chunk (so you can still see them)
content.delta / content.done delta, snapshot, parsed / content, parsed Text arrives / ends
refusal.delta / refusal.done delta, snapshot / refusal Refusal text
tool_calls.function.arguments.delta / .done name, index, arguments, parsed_arguments, arguments_delta Tool-call fragments / end of a call
logprobs.content.delta / .done, logprobs.refusal.* If you requested logprobs

Its standout feature, verified in the 3.42.1 source: with response_format=YourPydanticModel, every content.delta carries parsed, a partial parse of the JSON so far (done with the jiter library's partial mode), and for strict function tools every arguments delta carries parsed_arguments the same way. 6.3 uses it. It also raises LengthFinishReasonError or ContentFilterFinishReasonError from inside the loop when a parseable response stops with finish_reason length or content_filter, so wrap the loop, not just the call.

4.4 Anthropic: messages.stream()#

python
with client.messages.stream(model=..., max_tokens=..., messages=...) as stream:
    for text in stream.text_stream:     # just the text deltas
        ...
    message = stream.get_final_message()

What it gives you:

Member What it does
for event in stream The raw events plus synthetic ones: text (with text and snapshot), input_json (with partial_json and a parsed snapshot of the tool input so far), thinking, signature, citation; message_stop and content_block_stop carry the finished message or block
stream.text_stream An iterator of text deltas only (the same events, filtered)
stream.current_message_snapshot The Message accumulated so far, at any point in the loop
stream.get_final_message() Consumes the rest of the stream and returns the complete Message, identical in shape to messages.create()'s result
stream.get_final_text() Consumes the stream and joins the text blocks; raises RuntimeError if the message has no text block (e.g. only tool_use)
stream.until_done() Consumes the stream, discarding events
stream.close(), stream.request_id, stream.response Close early; the request ID for support tickets; the raw HTTP response (headers)
python
# s4_4_anthropic_helper.py: what the anthropic messages.stream() helper gives you (local model, no key)
import anthropic

client = anthropic.Anthropic(base_url="http://localhost:11434", api_key="ollama")
MODEL = "claude-haiku-5-5"
MESSAGES: list[anthropic.types.MessageParam] = [{"role": "user", "content": "Name two primary colours."}]

with client.messages.stream(model=MODEL, max_tokens=30, messages=MESSAGES) as stream:
    for i, text in enumerate(stream.text_stream):          # only the text, as it arrives
        if i == 3:                                         # peek at the message built so far
            snap = stream.current_message_snapshot
            # Pick the text block by TYPE, never content[0]: on hosted Claude 5.x models block 0 is usually a
            # (hidden) thinking block, because thinking is on by default there.
            so_far = next((b.text for b in snap.content if b.type == "text"), "")
            print(f"\n[snapshot after 4 deltas: {so_far!r}, stop_reason={snap.stop_reason}]")
        print(text, end="", flush=True)
    message = stream.get_final_message()                   # the complete Message
print(f"\nstop_reason={message.stop_reason} usage={message.usage.input_tokens} in/{message.usage.output_tokens} out")

with client.messages.stream(model=MODEL, max_tokens=30, messages=MESSAGES) as stream:          # no per-event work needed?
    print("get_final_text():", repr(stream.get_final_text()))   # consumes the stream, joins text blocks
Output · local model qwen2.5:0.5b via Ollama5 lines
Two primary colors
[snapshot after 4 deltas: 'Two primary colors in', stop_reason=None]
 in the rainbow are red and blue. These colors can be combined to create various shades of other colors, but they are typically used as
stop_reason=max_tokens usage=34 in/30 out
get_final_text(): 'Two of the most important and widely recognized colors in visual arts and design are:\n\n1. Red: This color is often associated with passion, energy,'

The first stream shows the snapshot growing while text arrives; the second uses the helper purely for convenience, getting a whole answer through a stream. That second form is what Anthropic recommends for large max_tokens values, and it is the way round the SDK's "Streaming is required for operations that may take longer than 10 minutes" error: the 2.4.0 SDK estimates a non-streaming call's duration as 3600 × max_tokens ÷ 128000 seconds and refuses if that exceeds its 10-minute default timeout (passing stream=True or an explicit timeout disables the check).

4.5 Gemini: generate_content_stream and send_message_stream#

google-genai has no accumulating helper for generate_content: the chunks are already complete response objects, and you join what you need (5.3). Its chat sessions do stream:

python
chat = client.chats.create(model="gemini-3.8-flash")
for chunk in chat.send_message_stream("Hello"):
    print(chunk.text or "", end="")

Lesson 03.2, Part 8 covers client.chats as a history store. What matters for streaming is when the history is written:

python
# s4_5_gemini_chat_stream.py: chats.send_message_stream records history only after the stream ends
from collections.abc import Generator
from contextlib import closing
from typing import cast

from google import genai
from google.genai import types

client = genai.Client(http_options=types.HttpOptions(timeout=30_000))   # reads GEMINI_API_KEY; ms: google-genai has NO default timeout (8.1)
chat = client.chats.create(model="gemini-3.8-flash", config=types.GenerateContentConfig(max_output_tokens=20))

for chunk in chat.send_message_stream("My name is Asha. Say hello to me."):
    print(chunk.text or "", end="", flush=True)
history = chat.get_history()
print(f"\nafter a full stream: {len(history)} history entries, roles={[c.role for c in history][:4]}...")

# send_message_stream is a generator: breaking out of a `for` does not close it. closing() calls .close()
# on every exit path, so the connection goes back to the pool (8.4) instead of hanging the next request.
with closing(cast(Generator, chat.send_message_stream("Now count to twenty."))) as stream:   # cast: it IS a generator
    for i, chunk in enumerate(stream):
        if i == 2:
            break                                          # the user pressed Stop
print(f"after stopping early: {len(chat.get_history())} entries (unchanged: the turn was not recorded)")

Three behaviours of google-genai 2.34.0, read from its source (not observed in a run, since the sample is hosted-only):

  • The turn is recorded only when the stream is fully consumed. send_message_stream collects the chunks and calls record_history after its loop. If the user stops the stream (your loop breaks, or the request is cancelled), neither the user's message nor the partial answer is added. That is usually what you want for a "Stop" button, but if you want the partial answer kept, save it yourself.
  • Close the generator when you stop early. send_message_stream returns a generator, and break alone does not close it. The sample wraps the loop in contextlib.closing(...), so .close() runs on every exit path and the connection returns to the pool. 8.4 explains why: an abandoned generator can hang the next request on a one-connection pool, and google-genai has no default timeout, which is why the client here sets HttpOptions(timeout=...) (milliseconds).
  • Each chunk becomes its own model entry. After a full stream the history is one user entry followed by one Content(role="model") entry per chunk, not one merged reply. When you persist or display history, join consecutive model entries.

4.5b Gemini generate_content_stream: automatic continuation#

This is the main place where an SDK does retry inside a stream (Interactions has a twin of it, 4.6), so it needs its own section. In google-genai 2.34.0, generate_content_stream and chats.send_message_stream have long-decode continuation, on by default. Very long generations are produced in "hops" (separate HTTP requests). When a hop stops at its per-request token limit, the server says so and hands back an opaque token, and the SDK sends the same request again carrying that token, so you see one stream. Four names matter (all introspected in 2.34.0):

Name Where Meaning
FinishReason.CONTINUATION candidate.finish_reason "Token generation stopped because the response reached the per-request token limit, but generation is not yet complete." Not an ending
continuation_token candidate.continuation_token (bytes) An opaque checkpoint the server issues "when finish_reason is CONTINUATION", and, per the SDK source, at checkpoints inside a long hop
continuation_token GenerateContentConfig Send it back to continue a previous response
automatic_continuation GenerateContentConfig "Defaults to true." The SDK sends the request again with the response's token "until the model finishes. Timeouts, retries and billing apply to each request. Set to false to turn this off."

What the SDK does, read from StreamContinuation in google/genai/_extra_utils.py:

  • A hop ends with CONTINUATION and a token: the SDK clears that intermediate finish reason (you see None), starts the next request with the token, and keeps yielding chunks until a real finish reason arrives.
  • The connection drops, or the body ends early, after a checkpoint token arrived: the SDK resumes from the latest token, silently. You see no exception. This is why "no SDK retries a stream" is not quite true.
  • The hop died before it produced a token of its own and before any content: the SDK retries from the token that hop started with, at most MAX_STREAM_RECONNECTS_WITHOUT_PROGRESS = 3 times in a row, then raises the original error.
  • A request the server rejects before streaming anything (an HTTP error status, or an error as the very first event) is raised at once. Backing off and retrying those is HttpOptions.retry_options (03.8).
  • Usage is merged for you. Within one hop, "each chunk's usage_metadata is the server's running total", so the latest replaces the earlier ones. Across hops the SDK sums, so each yielded chunk carries the usage of all earlier hops plus its own. Add nothing yourself. Prompt tokens are counted again on every hop, because each hop re-sends the prompt and what was generated so far (Google's long-decode guide says "You pay for every token in every hop").

Short answers never meet any of this: no token, nothing to resume, and the lesson's rule holds. A drop in a short answer is yours to handle. This mock (layer 3: a real google-genai client on an httpx.MockTransport serving SSE bodies and dropping connections on cue) shows each case; the token fields follow the SDK's own types:

python
# s4_5b_gemini_continuation.py: google-genai 2.34.0 resumes a broken generate_content_stream by itself
# when the server has sent a continuation token. The server here is a MOCK (httpx.MockTransport):
# the token fields follow the SDK's own types (Candidate.continuation_token, FinishReason.CONTINUATION).
import base64
import json

import httpx
from google import genai
from google.genai import types


def token(name: str) -> str:
    return base64.b64encode(name.encode()).decode()      # the wire carries the opaque token as base64


def chunk(text: str, *, finish: str | None = None, tok: str | None = None, out: int | None = None) -> bytes:
    cand: dict = {"content": {"role": "model", "parts": [{"text": text}]}, "index": 0}
    if finish:
        cand["finishReason"] = finish
    if tok:
        cand["continuationToken"] = token(tok)
    body: dict = {"candidates": [cand]}
    if out is not None:                                   # the server's running total for THIS request
        body["usageMetadata"] = {"promptTokenCount": 10, "candidatesTokenCount": out}
    return f"data: {json.dumps(body)}\n\n".encode()


class Drop(httpx.ReadError):                              # stands in for a proxy resetting the connection
    pass


class Body(httpx.SyncByteStream):
    """A response body that yields `parts`, then (optionally) fails like a dropped connection."""

    def __init__(self, parts: list[bytes], drop_after: bool):
        self.parts, self.drop_after = parts, drop_after

    def __iter__(self):
        yield from self.parts
        if self.drop_after:
            raise Drop("connection reset by peer")


def sent_token(request_body: dict) -> str | None:
    """Find the continuation token the SDK put in a request (wherever it placed it)."""
    text = json.dumps(request_body)
    return "ckpt-1" if token("ckpt-1") in text else None


def run(label: str, hops: list[tuple[list[bytes], bool]], config: types.GenerateContentConfig | None = None):
    """`hops` is one (chunks, drop_after) entry per HTTP request the mock server will answer.
    The last entry answers every further request."""
    requests: list[dict] = []

    def handler(request: httpx.Request) -> httpx.Response:
        requests.append(json.loads(request.content))
        parts, drop = hops[min(len(requests), len(hops)) - 1]
        return httpx.Response(200, headers={"content-type": "text/event-stream"}, stream=Body(parts, drop))

    client = genai.Client(api_key="sk-test", http_options=types.HttpOptions(
        httpx_client=httpx.Client(transport=httpx.MockTransport(handler))))
    print(label)
    seen: list[str] = []
    try:
        for c in client.models.generate_content_stream(model="gemini-3.8-flash", contents="Tell me about otters.",
                                                       config=config):
            cand = c.candidates[0] if c.candidates else None
            seen.append(f"{c.text!r}/{cand.finish_reason.name if cand and cand.finish_reason else None}")
            if c.usage_metadata:
                seen[-1] += f"/out={c.usage_metadata.candidates_token_count}"
        outcome = "no exception"
    except Exception as e:  # noqa: BLE001
        outcome = f"raised {type(e).__name__}" + (" (an httpx.ReadError)" if isinstance(e, httpx.ReadError) else "")
    print(f"  chunks (text/finish_reason): {seen}")
    print(f"  {outcome}; HTTP requests: {len(requests)}; token sent per request: "
          f"{[sent_token(r) for r in requests]}")
    return requests


# 1. Default settings: a drop after a checkpoint is resumed silently
run("1. Drop after a checkpoint token (automatic_continuation is on by default)",
    [([chunk("Otters hold ", tok="ckpt-1")], True),
     ([chunk("hands.", finish="STOP", out=3)], False)])

# 2. The same drop on a short answer: the server never issued a token, so nothing can be resumed
run("2. Drop with no token (a short answer)",
    [([chunk("Otters hold ")], True)])

# 3. A hop that ends with CONTINUATION: the SDK chains the next hop and hides the intermediate finish reason
run("3. Hop ends with finish_reason=CONTINUATION (default: the SDK chains the hops)",
    [([chunk("Part one. ", finish="CONTINUATION", tok="ckpt-1", out=8)], False),
     ([chunk("Part two.", finish="STOP", out=5)], False)])

# 4. The same, with automatic continuation switched off: you see CONTINUATION and must act on it
reqs = run("4. Same, with automatic_continuation=False",
           [([chunk("Part one. ", finish="CONTINUATION", tok="ckpt-1", out=8)], False),
            ([chunk("Part two.", finish="STOP", out=5)], False)],
           types.GenerateContentConfig(automatic_continuation=False))

# 5. Switched off, you carry the token yourself: pass it back in the config and keep the same request
print("5. Manual loop with automatic_continuation=False")
chunks_by_request = iter([[chunk("Part one. ", finish="CONTINUATION", tok="ckpt-1", out=8)],
                          [chunk("Part two.", finish="STOP", out=5)]])
client = genai.Client(api_key="sk-test", http_options=types.HttpOptions(httpx_client=httpx.Client(
    transport=httpx.MockTransport(lambda r: httpx.Response(
        200, headers={"content-type": "text/event-stream"}, stream=Body(next(chunks_by_request), False))))))
answer, resume_from, hops = "", None, 0
while True:
    hops += 1
    cfg = types.GenerateContentConfig(automatic_continuation=False, continuation_token=resume_from)
    finish = None
    for c in client.models.generate_content_stream(model="gemini-3.8-flash", contents="Tell me about otters.",
                                                   config=cfg):
        answer += c.text or ""
        cand = c.candidates[0] if c.candidates else None
        if cand and cand.finish_reason:
            finish, resume_from = cand.finish_reason, cand.continuation_token
    if finish != types.FinishReason.CONTINUATION:          # STOP, MAX_TOKENS, SAFETY...: really finished
        break
print(f"  {hops} hops, answer={answer!r}, final finish_reason={finish.name if finish else None}")

# 6. The give-up limit: the connection keeps dying before any new text or token arrives
run("6. Repeated drops with no progress (the SDK gives up after 3 reconnects)",
    [([chunk("Otters hold ", tok="ckpt-1")], True),
     ([], True)])

# 7. A drop AFTER text that followed the checkpoint: the SDK still resumes from the checkpoint
run("7. Text after the last checkpoint, then a drop (the SDK has no duplicate guard here)",
    [([chunk("Otters hold ", tok="ckpt-1"), chunk("paws and ")], True),
     ([chunk("hands.", finish="STOP", out=3)], False)])
Output20 lines
1. Drop after a checkpoint token (automatic_continuation is on by default)
  chunks (text/finish_reason): ["'Otters hold '/None", "'hands.'/STOP/out=3"]
  no exception; HTTP requests: 2; token sent per request: [None, 'ckpt-1']
2. Drop with no token (a short answer)
  chunks (text/finish_reason): ["'Otters hold '/None"]
  raised Drop (an httpx.ReadError); HTTP requests: 1; token sent per request: [None]
3. Hop ends with finish_reason=CONTINUATION (default: the SDK chains the hops)
  chunks (text/finish_reason): ["'Part one. '/None/out=8", "'Part two.'/STOP/out=13"]
  no exception; HTTP requests: 2; token sent per request: [None, 'ckpt-1']
4. Same, with automatic_continuation=False
  chunks (text/finish_reason): ["'Part one. '/CONTINUATION/out=8"]
  no exception; HTTP requests: 1; token sent per request: [None]
5. Manual loop with automatic_continuation=False
  2 hops, answer='Part one. Part two.', final finish_reason=STOP
6. Repeated drops with no progress (the SDK gives up after 3 reconnects)
  chunks (text/finish_reason): ["'Otters hold '/None"]
  raised Drop (an httpx.ReadError); HTTP requests: 5; token sent per request: [None, 'ckpt-1', 'ckpt-1', 'ckpt-1', 'ckpt-1']
7. Text after the last checkpoint, then a drop (the SDK has no duplicate guard here)
  chunks (text/finish_reason): ["'Otters hold '/None", "'paws and '/None", "'hands.'/STOP/out=3"]
  no exception; HTTP requests: 2; token sent per request: [None, 'ckpt-1']

Read it case by case:

  1. A drop after a checkpoint is invisible. Two HTTP requests, no exception, and the second request carried the token.
  2. The same drop without a token raises the transport error (httpx.ReadError here), after one request. This is the common case, and the situation of 7.5.
  3. A CONTINUATION hop is chained for you: the first chunk's finish reason reads None, not CONTINUATION, and the usage in the last chunk is 13: the two hops' 8 + 5 already added.
  4. With automatic_continuation=False you see CONTINUATION and the stream simply ends. Nothing is wrong, but nothing is finished.
  5. Then the loop is yours: pass continuation_token back (keep the same model, contents and config) until the finish reason is a real one.
  6. There is a give-up limit: one request, one resume from the token, then three more tries that made no progress: five requests, then the error.
  7. There is no duplicate guard on this path. The text that followed the last checkpoint ('paws and ') was already yielded to your loop when the connection dropped, yet the SDK resumed from the checkpoint. The SDK's own comment on the Interactions twin of this code says why that is risky: resuming "would re-generate (and duplicate) any output yielded since" the checkpoint. The Interactions stream refuses to do it and raises ContinuationInterruptedError instead (4.6); generate_content_stream in 2.34.0 does not. Whether a hosted server ever sends text after a checkpoint inside a hop is not documented for generate_content (Google's long-decode guide describes checkpoint chunks of about 5,000 tokens, which would make it rare); so if exact text matters, turn automatic continuation off and run the manual loop of case 5, which cannot duplicate.

What this means for you as an engineer:

  • Treat CONTINUATION as non-terminal in any accumulator or finish-reason mapping (5.3 does: complete stays False, and the token is kept in continuation_token).
  • Don't stack your own restart-and-reset on top without knowing the SDK may already have resumed. Your code only ever sees what the SDK gave up on: an exception, or a stream that ended. At that point 7.5 applies.
  • Count cost from the SDK's merged usage, and expect the input side of a very long generation to be larger than the prompt: every hop pays for the context again.
  • Turn it off (GenerateContentConfig(automatic_continuation=False)) when you want your own retry policy, a hard cost cap per request, or the strictest no-duplicates guarantee.

4.6 Gemini Interactions: create(stream=True)#

The Interactions stream is the raw event stream of 3.5; there is no separate helper. One SDK behaviour matters, though: automatic continuation (the generate_content_stream twin is 4.5b). Very long generations are produced in "hops" (Google's long-decode guide gives a per-request cap of 64K tokens when streaming), and with automatic_continuation (on by default in google-genai 2.34.0) the SDK chains the hops into one stream. Its docstring spells out the consequences:

  • "Each intermediate hop ends with an interaction.completed event whose event.interaction.status is 'requires_continuation', followed by interaction.created for the next hop", so check status != "requires_continuation" before treating interaction.completed as the end.
  • "event.interaction.usage on streamed events reflects only that hop rather than cumulative usage across hops": sum the final usage of each hop.
  • A numeric timeout= on the call "bounds the whole call (all continuation hops together)".
  • If a connection drops at a checkpoint before any new deltas arrived, the SDK reconnects for you. If the stream already yielded deltas after the latest checkpoint, it raises google.genai.errors.ContinuationInterruptedError instead, "to avoid duplicate output" (long-decode guide). The error carries the continuation_token (and the interaction ID) so you can resume yourself. The generate_content_stream version of the same machinery, 4.5b, has no such guard.

Short answers never hit this. Long reports and long reasoning can.

4.7 Choosing helper or raw#

Use the helper when... Use raw iteration when...
You want the final message too (almost always) You forward events and never need the final object (a pure relay)
You want text_stream / snapshot convenience Memory matters (very long outputs, thousands of concurrent streams)
You use text_format=, response_format= or output_format= parsing You need to see every event exactly as sent, e.g. for logging or replay
You must control exactly where exceptions can occur

Either way: always use the with form (or async with), and always handle the terminal event yourself rather than relying on get_final_*() to tell you something went wrong. They won't: when the body ends with no terminal event, messages.stream().get_final_message() returns a Message with stop_reason=None and chat.completions.stream().get_final_completion() returns finish_reason=None, both with the partial text and no exception (7.3, case 7). Check stop_reason / finish_reason yourself, or use the accumulators of 5.3, whose result(strict=True) raises. Only responses.stream().get_final_response() raises on its own.


Part 5: Accumulating the final message yourself#

5.1 Why you'd do it#

The helpers accumulate for you, so why write your own? Because sooner or later you'll stream in a place where the helper isn't available or isn't enough:

  • A relay or gateway that forwards events to clients (Part 11) still has to log the final answer, its usage and its finish reason, and to save the assistant turn to the conversation store (03.2, Part 5).
  • A provider-agnostic layer needs one result type for four event formats (03.11).
  • OpenRouter and other compatible endpoints add fields the helpers don't know about.
  • Raw iteration (for memory or control, 4.7) gives you no final object at all.
  • Interrupted streams: when a stream dies, the helper's get_final_*() raises or returns nothing, but your own accumulator still holds everything received so far, which is what you need to continue or log (7.5).

5.2 What a correct accumulator keeps#

Piece The trap The correct handling
Text Several text blocks or items (Claude can interleave text and tool calls; Responses can return several message items) Key text by block index / output_index, keep the order
Tool calls Arguments arrive as JSON fragments; with parallel calls, fragments of different calls interleave by index Concatenate fragment strings per call; parse JSON once, after the call is complete. Keep the call's id / call_id, sent only on the first fragment
Empty arguments A tool with no parameters may stream no argument fragments at all Treat "" as {}
Reasoning Thinking blocks, summaries and signatures must be kept to pass reasoning back (02.8, 8.2). On Claude 5.x the thinking text is empty by default but the block and its signature still matter (6.1) Keep thinking text and signatures; route them separately from answer text. The accumulators keep Anthropic thinking / redacted_thinking blocks with their signatures, OpenAI reasoning items and Gemini thought_signature values
Finish reason and the terminal event Arrives at the end; OpenRouter repeats it. Gemini may send CONTINUATION, which is not an ending (4.5b). Helpers don't raise when the body simply ends (7.3, case 7) Overwrite, don't append. Track whether the terminal event arrived (complete). complete == False means "interrupted": result(strict=True) raises StreamInterrupted
Usage Chat Completions: only on the opt-in last chunk (and OpenRouter's has choices). Anthropic: cumulative in message_delta, and a docs-shaped fixture may carry no usage at all. Gemini: optional on each chunk, a running total Check every event; replace with the latest value; never sum. None at the end means "unknown", not zero (7.6). Keep the extras too: cached input, cache-write and reasoning tokens, which 03.7's cost tracker needs (usage_details). The input count is stored as raw_input because it is the provider's own number (see the note under 5.3)
Refusals and errors Refusal text is its own delta on both OpenAI APIs; Responses yields error and response.failed as ordinary events Keep them in refusal and error, not in the answer text
Unknown events New event and delta types appear Ignore them; never raise

5.3 The accumulators#

One module, four accumulators, one result type. Each has add(event) for every event and result() at the end. result() never raises on an interrupted stream: it returns a Final whose complete is False, so you can still log what arrived. result(strict=True) raises StreamInterrupted (with the partial Final in e.partial) when you'd rather fail loudly. A tool call whose arguments are not valid JSON (cut off) gets arguments=None and a note in problems. complete means "the provider's terminal event arrived", not "it succeeded": check finish_reason and error too.

python
# accumulate.py: build the final message from raw stream events yourself, for each API.
# Each accumulator has .add(event) for every event and .result() once the stream has ended.
# A stream that ends WITHOUT its terminal event is never silent here: .result() returns a Final
# with complete=False, and .result(strict=True) raises StreamInterrupted (carrying what was received).
# Token names: `raw_input` is the provider's own input count, NOT the module's `input`. It includes cached tokens
# on OpenAI and Gemini and excludes them on Anthropic. Cached and written counts sit in `usage_details`. To price a
# call, convert with cost_calc.from_* (lesson 03.7, 3.1), which gives uncached input / cached / written.
import json
from dataclasses import dataclass, field
from typing import Any


def _extra() -> Any:
    """Fields that carry detail beyond the core comparison (text, tools, finish reason, usage)."""
    return field(default_factory=list, compare=False)


@dataclass
class Final:
    # --- the core: what 5.4 compares against each SDK's own result
    text: list[str] = field(default_factory=list)          # one entry per text block / item, in order
    tool_calls: list[dict] = field(default_factory=list)   # {"id", "name", "arguments": dict | None}
    reasoning: list[str] = field(default_factory=list)     # thinking / summaries, if any were streamed
    finish_reason: str | None = None                       # None means: the stream never finished
    usage: dict[str, int] | None = None                    # {"raw_input", "output"}; None means unknown (not zero!)
    # --- the rest: what a production accumulator also keeps
    complete: bool = field(default=False, compare=False)   # the provider's terminal event arrived
    usage_details: dict[str, int] = field(default_factory=dict, compare=False)  # cached / cache-write / reasoning tokens
    thinking_blocks: list[dict] = _extra()   # Anthropic thinking and redacted_thinking blocks, WITH signatures
    reasoning_items: list[dict] = _extra()   # OpenAI Responses reasoning items (id, summary, encrypted_content)
    thought_signatures: list[bytes] = _extra()  # Gemini thought_signature values, in part order
    refusal: list[str] = _extra()            # refusal text (OpenAI Chat and Responses)
    error: dict | None = field(default=None, compare=False)   # an `error` event or a failed response
    problems: list[str] = _extra()           # e.g. tool arguments that are not valid JSON
    continuation_token: bytes | None = field(default=None, compare=False)  # Gemini: ask again with this

    def require_complete(self) -> "Final":
        """Raise if the stream ended without its terminal event; otherwise return self."""
        if not self.complete:
            raise StreamInterrupted(self)
        return self


class StreamInterrupted(Exception):
    """The stream ended without a terminal event. `.partial` holds everything received so far."""

    def __init__(self, partial: Final) -> None:
        got = sum(len(t) for t in partial.text)
        super().__init__(f"stream ended without a terminal event (received {got} characters of text, "
                         f"{len(partial.tool_calls)} tool call(s), finish_reason={partial.finish_reason!r})")
        self.partial = partial


def parse_args(raw: str) -> dict:
    """Tool arguments are only parseable once complete. An empty string means 'no arguments'."""
    return json.loads(raw) if raw.strip() else {}


def _tool_call(call_id: str | None, name: str | None, raw: str, problems: list[str]) -> dict:
    """Parse one call's arguments. Invalid JSON (a cut-off call) becomes None plus a problem note."""
    try:
        args: dict | None = parse_args(raw)
    except json.JSONDecodeError:
        args = None
        problems.append(f"tool call {name!r} ({call_id}): arguments are not valid JSON: {raw[:60]!r}")
    return {"id": call_id, "name": name, "arguments": args}


def _finish(final: Final, strict: bool) -> Final:
    return final.require_complete() if strict else final


class ChatAccumulator:
    """OpenAI Chat Completions, and OpenRouter (same chunks; its usage chunk also has choices)."""

    def __init__(self) -> None:
        self.content: list[str] = []
        self.refusal: list[str] = []
        self.calls: dict[int, dict[str, Any]] = {}          # keyed by tool_calls[].index
        self.finish_reason: str | None = None
        self.usage: dict[str, int] | None = None
        self.details: dict[str, int] = {}

    def add(self, chunk) -> None:
        u = chunk.usage
        if u is not None:                                   # check on every chunk, whatever `choices` holds
            self.usage = {"raw_input": u.prompt_tokens, "output": u.completion_tokens}
            if u.prompt_tokens_details and u.prompt_tokens_details.cached_tokens is not None:
                self.details["cached_input"] = u.prompt_tokens_details.cached_tokens
            if u.completion_tokens_details and u.completion_tokens_details.reasoning_tokens is not None:
                self.details["reasoning"] = u.completion_tokens_details.reasoning_tokens
        if not chunk.choices:                               # OpenAI's usage chunk: choices == []
            return
        choice = chunk.choices[0]                           # n=1; with n>1, key everything by choice.index
        if choice.delta.content:
            self.content.append(choice.delta.content)
        if choice.delta.refusal:
            self.refusal.append(choice.delta.refusal)
        for tc in choice.delta.tool_calls or []:
            call = self.calls.setdefault(tc.index, {"id": None, "name": "", "arguments": ""})
            if tc.id:
                call["id"] = tc.id                          # sent once, on the call's first fragment
            if tc.function and tc.function.name:
                call["name"] += tc.function.name
            if tc.function and tc.function.arguments:
                call["arguments"] += tc.function.arguments  # JSON text, in pieces
        if choice.finish_reason:
            self.finish_reason = choice.finish_reason       # OpenRouter repeats it; same value, harmless

    def result(self, strict: bool = False) -> Final:
        problems: list[str] = []
        calls = [_tool_call(c["id"], c["name"], c["arguments"], problems) for _, c in sorted(self.calls.items())]
        return _finish(Final(text=["".join(self.content)] if self.content else [], tool_calls=calls,
                             finish_reason=self.finish_reason, usage=self.usage,
                             complete=self.finish_reason is not None,   # the last content chunk has one
                             usage_details=self.details, refusal=["".join(self.refusal)] if self.refusal else [],
                             problems=problems), strict)


class ResponsesAccumulator:
    """OpenAI Responses API (and OpenRouter's Responses endpoint).
    Feed it the stream from the START: indexes come from output_item.added. To resume after a cursor
    (9.2), keep this object (or its state) alongside the cursor: a fresh one has never seen the items."""

    def __init__(self) -> None:
        self.items: dict[int, dict[str, Any]] = {}          # keyed by output_index
        self.reasoning_items: list[dict] = []
        self.finish_reason: str | None = None
        self.usage: dict[str, int] | None = None
        self.details: dict[str, int] = {}
        self.error: dict | None = None
        self.terminal = False

    def add(self, event) -> None:
        t = event.type
        if t == "response.output_item.added":
            item = event.item
            self.items[event.output_index] = {"type": item.type, "text": "", "arguments": "", "refusal": "",
                                              "call_id": getattr(item, "call_id", None),
                                              "name": getattr(item, "name", None), "reasoning": ""}
        elif t == "response.output_text.delta":
            self.items[event.output_index]["text"] += event.delta
        elif t == "response.refusal.delta":
            self.items[event.output_index]["refusal"] += event.delta
        elif t == "response.function_call_arguments.delta":
            self.items[event.output_index]["arguments"] += event.delta
        elif t == "response.reasoning_summary_text.delta":
            self.items[event.output_index]["reasoning"] += event.delta
        elif t == "response.output_item.done" and event.item.type == "reasoning":
            # the finished item carries what you pass back: id, summary, encrypted_content (if requested)
            self.reasoning_items.append(event.item.model_dump(exclude_none=True))
        elif t == "error":                                  # yielded, not raised: the caller must look
            self.error = {"code": event.code, "message": event.message}
        elif t in ("response.completed", "response.incomplete", "response.failed"):
            self.terminal = True
            r = event.response
            # status is "completed" / "incomplete" / "failed"; incomplete_details says why
            self.finish_reason = r.status if t != "response.incomplete" else \
                f"incomplete:{r.incomplete_details.reason if r.incomplete_details else '?'}"
            if r.error:
                self.error = {"code": r.error.code, "message": r.error.message}
            if r.usage:
                self.usage = {"raw_input": r.usage.input_tokens, "output": r.usage.output_tokens}
                if r.usage.input_tokens_details:
                    self.details["cached_input"] = r.usage.input_tokens_details.cached_tokens
                if r.usage.output_tokens_details:
                    self.details["reasoning"] = r.usage.output_tokens_details.reasoning_tokens
        # everything else (created, in_progress, content_part.*, *.done, keepalive, new types) is ignored

    def result(self, strict: bool = False) -> Final:
        items = [self.items[i] for i in sorted(self.items)]
        problems: list[str] = []
        calls = [_tool_call(i["call_id"], i["name"], i["arguments"], problems)
                 for i in items if i["type"] == "function_call"]
        return _finish(Final(text=[i["text"] for i in items if i["type"] == "message"], tool_calls=calls,
                             reasoning=[i["reasoning"] for i in items if i["type"] == "reasoning" and i["reasoning"]],
                             finish_reason=self.finish_reason, usage=self.usage, complete=self.terminal,
                             usage_details=self.details, reasoning_items=self.reasoning_items,
                             refusal=[i["refusal"] for i in items if i["refusal"]], error=self.error,
                             problems=problems), strict)


class AnthropicAccumulator:
    """Anthropic Messages raw events (stream=True, or the raw events inside messages.stream())."""

    def __init__(self) -> None:
        self.blocks: dict[int, dict[str, Any]] = {}         # keyed by content block index
        self.finish_reason: str | None = None
        self.usage: dict[str, int] | None = None
        self.details: dict[str, int] = {}
        self.terminal = False

    def _usage(self, u) -> None:
        """message_start and message_delta usage are CUMULATIVE; either may lack `usage` in docs examples."""
        if u is None:
            return
        self.usage = dict(self.usage or {})
        for ours, theirs in (("raw_input", "input_tokens"), ("output", "output_tokens")):
            value = getattr(u, theirs, None)
            if value is not None:
                self.usage[ours] = value                    # replace, never add
        for ours, theirs in (("cached_input", "cache_read_input_tokens"), ("cache_write", "cache_creation_input_tokens")):
            value = getattr(u, theirs, None)
            if value is not None:
                self.details[ours] = value

    def add(self, event) -> None:
        t = event.type
        if t == "message_start":
            self._usage(getattr(event.message, "usage", None))
        elif t == "content_block_start":
            b = event.content_block
            self.blocks[event.index] = {"type": b.type, "text": "", "json": "", "thinking": "", "signature": None,
                                        "data": getattr(b, "data", None),            # redacted_thinking payload
                                        "id": getattr(b, "id", None), "name": getattr(b, "name", None)}
        elif t == "content_block_delta":
            block, d = self.blocks[event.index], event.delta
            if d.type == "text_delta":
                block["text"] += d.text
            elif d.type == "input_json_delta":
                block["json"] += d.partial_json             # partial JSON: parse once, at the end
            elif d.type == "thinking_delta":
                block["thinking"] += d.thinking             # empty when thinking is hidden (display "omitted")
            elif d.type == "signature_delta":
                block["signature"] = d.signature            # one delta, just before the block stops
            # citations_delta: kept by real code, skipped in this sketch
        elif t == "message_delta":
            self.finish_reason = event.delta.stop_reason
            self._usage(getattr(event, "usage", None))
        elif t == "message_stop":
            self.terminal = True
        # ping, content_block_stop and unknown future types need nothing here

    def result(self, strict: bool = False) -> Final:
        blocks = [self.blocks[i] for i in sorted(self.blocks)]
        problems: list[str] = []
        calls = [_tool_call(b["id"], b["name"], b["json"], problems) for b in blocks if b["type"] == "tool_use"]
        thinking = [{"type": "thinking", "thinking": b["thinking"], "signature": b["signature"]}
                    for b in blocks if b["type"] == "thinking"]
        thinking += [{"type": "redacted_thinking", "data": b["data"]} for b in blocks if b["type"] == "redacted_thinking"]
        return _finish(Final(text=[b["text"] for b in blocks if b["type"] == "text"], tool_calls=calls,
                             reasoning=[b["thinking"] for b in blocks if b["type"] == "thinking" and b["thinking"]],
                             finish_reason=self.finish_reason, usage=self.usage, complete=self.terminal,
                             usage_details=self.details, thinking_blocks=thinking, problems=problems), strict)


class GeminiAccumulator:
    """google-genai generate_content_stream: every chunk is a whole GenerateContentResponse.
    A finish_reason of CONTINUATION is NOT terminal: it means "ask again with continuation_token".
    The SDK hides it by default (automatic_continuation); you only see it if you switch that off."""

    def __init__(self) -> None:
        self.text: list[str] = []
        self.thoughts: list[str] = []
        self.calls: list[dict] = []
        self.signatures: list[bytes] = []
        self.finish_reason: str | None = None
        self.usage: dict[str, int] | None = None
        self.details: dict[str, int] = {}
        self.token: bytes | None = None
        self.terminal = False

    def add(self, chunk) -> None:
        u = chunk.usage_metadata
        if u:                                               # a running total: take the latest, don't sum
            self.usage = {"raw_input": u.prompt_token_count or 0, "output": u.candidates_token_count or 0}
            if u.cached_content_token_count is not None:
                self.details["cached_input"] = u.cached_content_token_count
            if u.thoughts_token_count is not None:
                self.details["reasoning"] = u.thoughts_token_count
        if chunk.prompt_feedback and chunk.prompt_feedback.block_reason:   # prompt blocked: no candidates at all
            self.finish_reason = f"PROMPT_BLOCKED:{chunk.prompt_feedback.block_reason.name}"
            self.terminal = True
        if not chunk.candidates:
            return
        cand = chunk.candidates[0]
        for part in (cand.content.parts if cand.content and cand.content.parts else []):
            if part.thought_signature:                      # needed to pass thinking back (02.8, 8.2)
                self.signatures.append(part.thought_signature)
            if part.function_call:                          # arrives whole, in a single chunk
                self.calls.append({"id": part.function_call.id, "name": part.function_call.name,
                                   "arguments": dict(part.function_call.args or {})})
            elif part.text and part.thought:
                self.thoughts.append(part.text)
            elif part.text:
                self.text.append(part.text)
        if cand.continuation_token:
            self.token = cand.continuation_token
        if cand.finish_reason:
            self.finish_reason = cand.finish_reason.name     # FinishReason.STOP -> "STOP"
            self.terminal = self.finish_reason != "CONTINUATION"

    def result(self, strict: bool = False) -> Final:
        return _finish(Final(text=["".join(self.text)] if self.text else [], tool_calls=self.calls,
                             reasoning=["".join(self.thoughts)] if self.thoughts else [],
                             finish_reason=self.finish_reason, usage=self.usage, complete=self.terminal,
                             usage_details=self.details, thought_signatures=self.signatures,
                             continuation_token=self.token), strict)

5.4 Try it: compare with each SDK's own result#

The test of an accumulator is whether it produces what the SDK produces from the same events. This sample feeds every event to both, on the stand-in (Ollama, so the three OpenAI and Anthropic paths; Gemini has no local stand-in and its accumulator is checked against a mock in 5.5), using a prompt that makes the small model call a tool twice (when it cooperates) so multi-call accumulation is exercised (on whole, unfragmented arguments; see the caveat below the output):

  • Chat Completions: the SDK's own ChatCompletionStreamState, fed the same chunks (it's what chat.completions.stream() uses internally);
  • Responses: responses.stream()'s get_final_response();
  • Anthropic: messages.stream()'s get_final_message().
python
# s5_4_compare.py: hand-built final messages vs each SDK's own accumulation (local stand-in, no key)
import anthropic
from openai import OpenAI
from openai.lib.streaming.chat import ChatCompletionStreamState
from openai.types.chat import ChatCompletionFunctionToolParam

from accumulate import AnthropicAccumulator, ChatAccumulator, Final, ResponsesAccumulator, parse_args

ASK = "What's the weather in Paris and in Tokyo, in celsius? Use the tool."
PARAMS = {"type": "object", "properties": {"city": {"type": "string"},
          "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}}, "required": ["city", "unit"]}
oa = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")


def check(label: str, mine: Final, sdk: Final) -> None:
    assert mine == sdk, f"{label}: MISMATCH\n mine={mine}\n sdk ={sdk}"
    assert mine.complete, f"{label}: the terminal event never arrived"     # the new flag (not in the SDKs' results)
    print(f"{label:<18} match ✓  text={[t[:30] for t in mine.text]} "
          f"tools={[(c['name'], c['arguments']) for c in mine.tool_calls]} "
          f"finish={mine.finish_reason} usage={mine.usage}")


# 1. Chat Completions: compare with the SDK's ChatCompletionStreamState fed the very same chunks
chat_tools: list[ChatCompletionFunctionToolParam] = [{"type": "function", "function": {"name": "get_weather", "parameters": PARAMS}}]
mine, state = ChatAccumulator(), ChatCompletionStreamState()
with oa.chat.completions.create(model="gpt-6-luna", messages=[{"role": "user", "content": ASK}],
                                tools=chat_tools, stream=True, stream_options={"include_usage": True}) as s:
    for chunk in s:
        mine.add(chunk)
        state.handle_chunk(chunk)
done = state.get_final_completion()
msg = done.choices[0].message
check("chat completions", mine.result(), Final(
    text=[msg.content] if msg.content else [],
    tool_calls=[{"id": t.id, "name": t.function.name, "arguments": parse_args(t.function.arguments)}
                for t in msg.tool_calls or [] if t.type == "function"],
    finish_reason=done.choices[0].finish_reason,
    usage={"raw_input": done.usage.prompt_tokens, "output": done.usage.completion_tokens} if done.usage else None))

# 2. Responses: compare with responses.stream()'s get_final_response()
#    (text only here: Ollama 0.32.5 gives a text item and a tool call the same output_index,
#    which the SDK rightly rejects. Part 6 streams Responses tool calls from a mock instead.)
mine2 = ResponsesAccumulator()
with oa.responses.stream(model="gpt-6-luna", input="Name two primary colours.", max_output_tokens=20) as s:
    for event in s:                                    # helper events are raw events plus `snapshot` fields
        mine2.add(event)
    r = s.get_final_response()
check("responses", mine2.result(), Final(
    text=[c.text for o in r.output if o.type == "message" for c in o.content if c.type == "output_text"],
    tool_calls=[{"id": o.call_id, "name": o.name, "arguments": parse_args(o.arguments)}
                for o in r.output if o.type == "function_call"],
    finish_reason=r.status, usage={"raw_input": r.usage.input_tokens, "output": r.usage.output_tokens}))

# 3. Anthropic: compare with messages.stream()'s get_final_message()
claude = anthropic.Anthropic(base_url="http://localhost:11434", api_key="ollama")
mine3 = AnthropicAccumulator()
with claude.messages.stream(model="claude-haiku-5-5", max_tokens=300, messages=[{"role": "user", "content": ASK}],
                            tools=[{"name": "get_weather", "input_schema": PARAMS}]) as s:
    for event in s:                                    # raw events + helper events (text, input_json, ...)
        mine3.add(event)
    m = s.get_final_message()
check("anthropic", mine3.result(), Final(
    text=[b.text for b in m.content if b.type == "text"],
    tool_calls=[{"id": b.id, "name": b.name, "arguments": b.input} for b in m.content if b.type == "tool_use"],
    finish_reason=m.stop_reason, usage={"raw_input": m.usage.input_tokens, "output": m.usage.output_tokens}))

Output (local model qwen2.5:0.5b via Ollama; a hosted model would call the tool reliably). The comparison also asserts complete, the new flag the SDKs' own results don't have:

text
chat completions   match ✓  text=[] tools=[('get_weather', {'city': 'Paris', 'unit': 'celsius'}), ('get_weather', {'city': 'Tokyo', 'unit': 'celsius'})] finish=tool_calls usage={'raw_input': 173, 'output': 55}
responses          match ✓  text=['The most common and well-known'] tools=[] finish=completed usage={'raw_input': 34, 'output': 20}
anthropic          match ✓  text=[] tools=[('get_weather', {'city': 'Paris', 'unit': 'celsius'}), ('get_weather', {'city': 'Tokyo', 'unit': 'celsius'})] finish=tool_use usage={'raw_input': 173, 'output': 55}

All three match, including two tool calls on Chat Completions and Anthropic. But read the caveat: Ollama streams each call's arguments as one fragment (a stand-in quirk, not what hosted providers do), so this run proves matching on unfragmented calls. 5.5 proves the hard case. The small model is erratic: on some runs it answers the weather question in text instead, and both sides still agree.

5.5 Try it: fragmented, interleaved tool calls from a mock#

The stand-in can't produce the hard case, so this mock (layer 3) can: the pattern from OpenAI's function-calling guide and Anthropic's streaming guide, through the real SDKs, with each accumulator checked against the SDK's own result:

  • Chat Completions: two calls whose argument fragments interleave by index (ids and names only on each call's first fragment), then a finish chunk, then a usage chunk with choices: [] and cached tokens.
  • Responses: two function_call items whose argument deltas interleave by output_index, compared with responses.stream()'s get_final_response().
  • Anthropic: a hidden thinking block with a signature, two tool calls in pieces, and a third with no parameters (an empty fragment), compared with messages.stream()'s get_final_message().
  • Anthropic fixture shaped like the docs examples, with no usage anywhere: the accumulator reports usage=None instead of crashing. (The SDK's own messages.stream() helper raises AttributeError on that fixture, which is worth knowing when you write test fixtures: include usage.)
  • Gemini: a thought summary, text, a function call carrying a thought_signature, and a hop that ends with CONTINUATION (automatic continuation switched off): complete stays False, and the token is kept.
python
# s5_5_fragments_mock.py: the accumulators on FRAGMENTED, INTERLEAVED tool calls. Every server is a MOCK
# (the stand-in streams each call's arguments as one piece, so it can't show this). The fragment patterns
# follow OpenAI's function-calling guide and Anthropic's streaming guide. Real SDKs parse every event.
import base64
import json

import anthropic
import httpx
from google import genai
from google.genai import types
from openai import OpenAI
from openai.lib.streaming.chat import ChatCompletionStreamState

from accumulate import (AnthropicAccumulator, ChatAccumulator, Final, GeminiAccumulator, ResponsesAccumulator,
                        StreamInterrupted, parse_args)
from mockkit import claude_block, claude_end, mock_client_transport


def check(label: str, mine: Final, sdk: Final) -> None:
    assert mine == sdk, f"{label}: MISMATCH\n mine={mine}\n sdk ={sdk}"
    print(f"{label:<18} match ✓  complete={mine.complete} finish={mine.finish_reason} usage={mine.usage} "
          f"details={mine.usage_details}")
    for c in mine.tool_calls:
        print(f"{'':<18}   {c['id']}  {c['name']}({json.dumps(c['arguments'])})")


# 1. Chat Completions: two calls interleaved by `index`; id and name only on each call's FIRST fragment
def chunk(tool_calls=None, finish=None, **extra) -> dict:
    delta = {"tool_calls": tool_calls} if tool_calls else {}
    return {"id": "chatcmpl-1", "object": "chat.completion.chunk", "created": 1, "model": "gpt-6-luna",
            "choices": [{"index": 0, "delta": delta, "finish_reason": finish}], **extra}


def frag(index: int, text: str, **first) -> dict:
    return {"index": index, "function": {"arguments": text, **({"name": first["name"]} if "name" in first else {})},
            **({"id": first["id"], "type": "function"} if "id" in first else {})}


CHAT = [chunk([frag(0, "", id="call_a", name="get_weather")]),
        chunk([frag(1, "", id="call_b", name="get_weather")]),
        chunk([frag(0, '{"ci')]), chunk([frag(1, '{"ci')]),
        chunk([frag(0, 'ty":"Par')]), chunk([frag(1, 'ty":"Tok')]),
        chunk([frag(1, 'yo","unit":"celsius"}')]), chunk([frag(0, 'is","unit":"celsius"}')]),
        chunk(finish="tool_calls"),
        {"id": "chatcmpl-1", "object": "chat.completion.chunk", "created": 1, "model": "gpt-6-luna", "choices": [],
         "usage": {"prompt_tokens": 150, "completion_tokens": 40, "total_tokens": 190,
                   "prompt_tokens_details": {"cached_tokens": 128},
                   "completion_tokens_details": {"reasoning_tokens": 0}}}]
oa = OpenAI(api_key="sk-test", http_client=mock_client_transport([(None, c) for c in CHAT] + [(None, "[DONE]")]))
mine, state = ChatAccumulator(), ChatCompletionStreamState()
with oa.chat.completions.create(model="gpt-6-luna", messages=[{"role": "user", "content": "Weather?"}],
                                stream=True, stream_options={"include_usage": True}) as s:
    for c in s:
        mine.add(c)
        state.handle_chunk(c)
done = state.get_final_completion()
msg = done.choices[0].message
check("chat completions", mine.result(strict=True), Final(
    text=[msg.content] if msg.content else [],
    tool_calls=[{"id": t.id, "name": t.function.name, "arguments": parse_args(t.function.arguments)}
                for t in msg.tool_calls or [] if t.type == "function"],
    finish_reason=done.choices[0].finish_reason,
    usage={"raw_input": done.usage.prompt_tokens, "output": done.usage.completion_tokens} if done.usage else None))

# 2. Responses: two function_call items whose argument deltas interleave by output_index
CALLS = [("fc_a", "call_a", ["", '{"ci', 'ty":"Par', 'is","unit":"celsius"}']),
         ("fc_b", "call_b", ["", '{"ci', 'ty":"Tok', 'yo","unit":"celsius"}'])]
RESP = {"id": "resp_1", "object": "response", "created_at": 1, "model": "gpt-6-luna", "parallel_tool_calls": True,
        "tool_choice": "auto", "tools": []}
seq = iter(range(100))
ev: list[tuple[str, dict]] = [("response.created", {"type": "response.created", "sequence_number": next(seq),
                                                     "response": {**RESP, "status": "in_progress", "output": []}})]
for i, (item_id, call_id, _) in enumerate(CALLS):
    ev.append(("response.output_item.added", {"type": "response.output_item.added", "output_index": i,
               "sequence_number": next(seq), "item": {"type": "function_call", "id": item_id, "call_id": call_id,
                                                      "name": "get_weather", "arguments": "", "status": "in_progress"}}))
for k in range(1, 4):                                      # fragment k of call 0, then fragment k of call 1
    for i, (item_id, _, fragments) in enumerate(CALLS):
        ev.append(("response.function_call_arguments.delta", {"type": "response.function_call_arguments.delta",
                   "item_id": item_id, "output_index": i, "delta": fragments[k], "sequence_number": next(seq)}))
for i, (item_id, call_id, fragments) in enumerate(CALLS):
    ev.append(("response.function_call_arguments.done", {"type": "response.function_call_arguments.done",
               "item_id": item_id, "output_index": i, "arguments": "".join(fragments), "name": "get_weather",
               "sequence_number": next(seq)}))
done_items = [{"type": "function_call", "id": i, "call_id": c, "name": "get_weather", "arguments": "".join(f),
               "status": "completed"} for i, c, f in CALLS]
ev.append(("response.completed", {"type": "response.completed", "sequence_number": next(seq), "response": {
    **RESP, "status": "completed", "output": done_items,
    "usage": {"input_tokens": 150, "output_tokens": 40, "total_tokens": 190,
              "input_tokens_details": {"cached_tokens": 128}, "output_tokens_details": {"reasoning_tokens": 12}}}}))
oa2 = OpenAI(api_key="sk-test", http_client=mock_client_transport(ev))
mine2 = ResponsesAccumulator()
with oa2.responses.stream(model="gpt-6-luna", input="Weather?") as s:
    for e in s:
        mine2.add(e)
    r = s.get_final_response()
check("responses", mine2.result(strict=True), Final(
    text=[], tool_calls=[{"id": o.call_id, "name": o.name, "arguments": parse_args(o.arguments)}
                         for o in r.output if o.type == "function_call"],
    finish_reason=r.status, usage={"raw_input": r.usage.input_tokens, "output": r.usage.output_tokens}))

# 3. Anthropic: a (hidden) thinking block with a signature, two tool calls in pieces, one with NO arguments
frag_a, frag_b = ['', '{"ci', 'ty":"Par', 'is","unit":"celsius"}'], ['{"', 'city":"Tokyo","unit":', '"celsius"}']
events = ([("message_start", {"type": "message_start", "message": {
    "id": "msg_1", "type": "message", "role": "assistant", "content": [], "model": "claude-haiku-5-5",
    "stop_reason": None, "stop_sequence": None,
    "usage": {"input_tokens": 50, "output_tokens": 1, "cache_read_input_tokens": 1024,
              "cache_creation_input_tokens": 0}}})]
          + claude_block(0, {"type": "thinking", "thinking": "", "signature": ""},
                         [{"type": "thinking_delta", "thinking": ""},
                          {"type": "signature_delta", "signature": "EqQBCgIYAhIM..."}])
          + claude_block(1, {"type": "tool_use", "id": "toolu_a", "name": "get_weather", "input": {}},
                         [{"type": "input_json_delta", "partial_json": f} for f in frag_a])
          + claude_block(2, {"type": "tool_use", "id": "toolu_b", "name": "get_weather", "input": {}},
                         [{"type": "input_json_delta", "partial_json": f} for f in frag_b])
          + claude_block(3, {"type": "tool_use", "id": "toolu_c", "name": "get_time", "input": {}},
                         [{"type": "input_json_delta", "partial_json": ""}])   # no parameters: an empty fragment
          + claude_end("tool_use", 60))
claude = anthropic.Anthropic(api_key="sk-test", http_client=mock_client_transport(events))
mine3 = AnthropicAccumulator()
with claude.messages.stream(model="claude-haiku-5-5", max_tokens=200,
                            messages=[{"role": "user", "content": "Weather and time?"}]) as s:
    for e in s:
        mine3.add(e)
    m = s.get_final_message()
check("anthropic", mine3.result(strict=True), Final(
    text=[b.text for b in m.content if b.type == "text"],
    tool_calls=[{"id": b.id, "name": b.name, "arguments": b.input} for b in m.content if b.type == "tool_use"],
    finish_reason=m.stop_reason, usage={"raw_input": m.usage.input_tokens, "output": m.usage.output_tokens}))
print("kept for passing back:", mine3.result().thinking_blocks)

# 4. An Anthropic fixture shaped like the DOCS examples: no `usage` on message_start, none on message_delta.
#    The accumulator must not crash on a missing field: usage is simply unknown (None), never invented.
bare_start = ("message_start", {"type": "message_start", "message": {
    "id": "msg_2", "type": "message", "role": "assistant", "content": [], "model": "claude-haiku-5-5",
    "stop_reason": None, "stop_sequence": None}})
bare_end = [("message_delta", {"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence": None}}),
            ("message_stop", {"type": "message_stop"})]
BARE = [bare_start] + claude_block(0, {"type": "text", "text": ""}, [{"type": "text_delta", "text": "Hi"}]) + bare_end
claude2 = anthropic.Anthropic(api_key="sk-test", http_client=mock_client_transport(BARE))
mine4 = AnthropicAccumulator()
with claude2.messages.create(model="claude-haiku-5-5", max_tokens=20, stream=True,    # raw events
                             messages=[{"role": "user", "content": "Hi"}]) as raw:
    for e in raw:
        mine4.add(e)
print("anthropic, no usage:", mine4.result(strict=True).usage, "| complete =", mine4.result().complete)
try:                                                       # the SDK's own helper does not survive this fixture
    with claude2.messages.stream(model="claude-haiku-5-5", max_tokens=20,
                                 messages=[{"role": "user", "content": "Hi"}]) as helper:
        helper.get_final_message()
except AttributeError as e:
    print("  messages.stream() on the same fixture raised AttributeError:", e)

# 5. Gemini: thought summary + signature, text, a function call, then a hop that ends with CONTINUATION.
#    automatic_continuation=False shows you the raw finish reason, which is NOT a terminal event.
def part(**kw) -> dict:
    return {"content": {"role": "model", "parts": [kw]}, "index": 0}


GEMINI = [{"candidates": [part(text="Checking the units. ", thought=True)]},
          {"candidates": [part(text="Paris is ")]},
          {"candidates": [part(functionCall={"name": "get_weather", "args": {"city": "Paris"}},
                               thoughtSignature=base64.b64encode(b"sig-1").decode())]},
          {"candidates": [{**part(text="mild."), "finishReason": "CONTINUATION",
                           "continuationToken": base64.b64encode(b"ckpt-1").decode()}],
           "usageMetadata": {"promptTokenCount": 30, "candidatesTokenCount": 12, "thoughtsTokenCount": 5,
                             "cachedContentTokenCount": 16}}]
body = "".join(f"data: {json.dumps(c)}\n\n" for c in GEMINI).encode()
gem = genai.Client(api_key="sk-test", http_options=types.HttpOptions(httpx_client=httpx.Client(
    transport=httpx.MockTransport(lambda r: httpx.Response(200, headers={"content-type": "text/event-stream"},
                                                           content=body)))))
mine5 = GeminiAccumulator()
for c in gem.models.generate_content_stream(model="gemini-3.8-flash", contents="Weather in Paris?",
                                            config=types.GenerateContentConfig(automatic_continuation=False)):
    mine5.add(c)
r5 = mine5.result()
print("gemini:", r5.text, r5.reasoning, r5.tool_calls, f"finish={r5.finish_reason} complete={r5.complete}")
print("       usage", r5.usage, r5.usage_details, "| signatures", r5.thought_signatures,
      "| continuation_token", r5.continuation_token)
try:
    mine5.result(strict=True)
except StreamInterrupted as e:
    print("       strict=True raised StreamInterrupted:", e)
Output16 lines
chat completions   match ✓  complete=True finish=tool_calls usage={'raw_input': 150, 'output': 40} details={'cached_input': 128, 'reasoning': 0}
                     call_a  get_weather({"city": "Paris", "unit": "celsius"})
                     call_b  get_weather({"city": "Tokyo", "unit": "celsius"})
responses          match ✓  complete=True finish=completed usage={'raw_input': 150, 'output': 40} details={'cached_input': 128, 'reasoning': 12}
                     call_a  get_weather({"city": "Paris", "unit": "celsius"})
                     call_b  get_weather({"city": "Tokyo", "unit": "celsius"})
anthropic          match ✓  complete=True finish=tool_use usage={'raw_input': 50, 'output': 60} details={'cached_input': 1024, 'cache_write': 0}
                     toolu_a  get_weather({"city": "Paris", "unit": "celsius"})
                     toolu_b  get_weather({"city": "Tokyo", "unit": "celsius"})
                     toolu_c  get_time({})
kept for passing back: [{'type': 'thinking', 'thinking': '', 'signature': 'EqQBCgIYAhIM...'}]
anthropic, no usage: None | complete = True
  messages.stream() on the same fixture raised AttributeError: 'NoneType' object has no attribute 'output_tokens'
gemini: ['Paris is mild.'] ['Checking the units. '] [{'id': None, 'name': 'get_weather', 'arguments': {'city': 'Paris'}}] finish=CONTINUATION complete=False
       usage {'raw_input': 30, 'output': 12} {'cached_input': 16, 'reasoning': 5} | signatures [b'sig-1'] | continuation_token b'ckpt-1'
       strict=True raised StreamInterrupted: stream ended without a terminal event (received 14 characters of text, 1 tool call(s), finish_reason='CONTINUATION')

Every match ✓ is an equality assertion against the SDK, so the interleaving, the empty-arguments case and the usage handling are all proven rather than described. Note details=: cached-input, cache-write and reasoning tokens are kept next to the two core numbers (the chat-completions fixture's raw_input of 150 already includes its 128 cached tokens; the Anthropic fixture's raw_input of 50 does not include its 1,024), and kept for passing back shows the (empty, signed) thinking block that hosted Claude sends by default.


Part 6: Streaming reasoning, tool calls, structured output and refusals#

Deep-dive

6.1 Reasoning arrives first#

Lesson 02.8, 5.8 covered the concept and the per-provider table: on a reasoning model the stream starts with thinking (or a placeholder for hidden thinking), and the answer text comes after it. The engineering consequences:

Provider Turn reasoning output on What arrives first Gotcha
OpenAI (Responses) reasoning={"summary": "auto"} A reasoning output item with response.reasoning_summary_text.delta events Without summary, nothing at all arrives during thinking: just a pause before the first output_text.delta
Anthropic Already on for Claude 5 and later models. To see the text: thinking={"type": "adaptive", "display": "summarized"} A thinking block (index 0) with thinking_delta events, then one signature_delta. With no display set, the default is "omitted": the block still opens and closes, carrying "a thinking_delta with an empty thinking string and then a single signature_delta" Code that assumes the answer is block 0 breaks, and a timer that treats the first thinking event as "content" reports the wrong time to first token (see the callout below)
Gemini generate_content ThinkingConfig(include_thoughts=True) Parts with part.thought == True chunk.text excludes thought parts, so a thought-only chunk looks empty
Gemini Interactions generation_config={"thinking_summaries": "auto"} A thought step with thought_summary deltas and a final thought_signature
OpenRouter reasoning request object (02.8, 3.4) delta.reasoning / delta.reasoning_details in the chunks, in model_extra With exclude: true, no reasoning fields

The local model doesn't think, so this sample uses a mock stream (layer 3, built with mockkit.py from 4.2) with exactly the event pattern Anthropic's docs give for hidden thinking, and runs it through the real helper and the accumulator from 5.3:

python
# s6_1_thinking_mock.py: a Claude stream that thinks first, with hidden thinking (display="omitted").
# That is the DEFAULT on Claude 5.x models, so a hosted stream with no `thinking` parameter looks like this.
# MOCK server: the event pattern follows Anthropic's streaming docs ("Thinking delta").
import anthropic

from accumulate import AnthropicAccumulator
from mockkit import claude_block, claude_end, claude_message_start, mock_client_transport

EVENTS = ([claude_message_start()]
          + claude_block(0, {"type": "thinking", "thinking": "", "signature": ""},
                         [{"type": "thinking_delta", "thinking": ""},          # empty: thinking is hidden
                          {"type": "signature_delta", "signature": "EqQBCgIYAhIM1gbcDa9GJwZA..."}])
          + [("ping", {"type": "ping"})]                                       # pings may come anywhere
          + claude_block(1, {"type": "text", "text": ""},
                         [{"type": "text_delta", "text": "No: 391 = 17 × 23."}])
          + claude_end("end_turn", 230))

client = anthropic.Anthropic(api_key="sk-test", http_client=mock_client_transport(EVENTS))
acc = AnthropicAccumulator()
with client.messages.stream(model="claude-opus-5-5", max_tokens=16_000,
                            messages=[{"role": "user", "content": "Is 391 prime?"}]) as stream:
    for event in stream:
        acc.add(event)
        label = event.type
        if event.type == "content_block_start":
            label += f" ({event.content_block.type})"
        elif event.type == "content_block_delta":
            label += f" ({event.delta.type})"
        print(" ", label)                               # note: no "ping" line, the SDK drops pings
    final = stream.get_final_message()

print("blocks:", [b.type for b in final.content], "| thinking text:", repr(final.content[0].thinking)
      if final.content[0].type == "thinking" else None)
result = acc.result(strict=True)
print("accumulator text:", result.text, "| reasoning text:", result.reasoning, "| complete:", result.complete)
print("kept to pass back:", result.thinking_blocks)    # empty text, but the signature is what the API needs
Output16 lines
  message_start
  content_block_start (thinking)
  content_block_delta (thinking_delta)
  thinking
  content_block_delta (signature_delta)
  signature
  content_block_stop
  content_block_start (text)
  content_block_delta (text_delta)
  text
  content_block_stop
  message_delta
  message_stop
blocks: ['thinking', 'text'] | thinking text: ''
accumulator text: ['No: 391 = 17 × 23.'] | reasoning text: [] | complete: True
kept to pass back: [{'type': 'thinking', 'thinking': '', 'signature': 'EqQBCgIYAhIM1gbcDa9GJwZA...'}]

The helper adds its own thinking and signature events after the raw deltas; the ping in the fixture never reaches your loop. The accumulator correctly reports no reasoning text (it was hidden), still puts the answer in the right place because it keys blocks by index and type rather than assuming the text is block 0, and keeps the empty block with its signature in thinking_blocks, ready to be passed back.

What this means for your UI: route reasoning and answer events to different places (a collapsible "thinking" panel and the answer area); start a "thinking…" indicator on the first reasoning event, or on a timer if reasoning is hidden; and measure the time to the first answer token separately (Part 12). Hiding thinking shortens the wait for visible text a little; it doesn't reduce what you pay (02.8, 5.1).

6.2 Tool-call arguments arrive as JSON fragments#

When a model calls a tool in a stream, the tool's name arrives first and its arguments arrive as pieces of a JSON string, which are not valid JSON until the last piece. Lesson 03.5 owns the tool round trip (executing the call and sending the result back); this section is only about receiving the call from a stream.

Provider Name and ID arrive in Argument fragments Complete arguments
OpenAI Responses response.output_item.added (item.name, item.call_id) response.function_call_arguments.delta → delta response.function_call_arguments.done → arguments, and response.output_item.done
OpenAI Chat Completions The call's first delta.tool_calls[j] fragment (id, function.name) delta.tool_calls[j].function.arguments, matched by index When finish_reason is tool_calls
Anthropic content_block_start with a tool_use block (id, name, input: {}) input_json_delta → partial_json content_block_stop (parse then)
Gemini generate_content — None: each function_call part arrives complete in one chunk on the Gemini API (3.4) That chunk
Gemini Interactions step.start with a function_call step (id, name) arguments_delta → arguments step.stop; the interaction ends with status requires_action
OpenRouter As Chat Completions As Chat Completions As Chat Completions

Anthropic adds two details. By default the API buffers each parameter and validates it before streaming it, and current models emit "one complete key and value property from input at a time", so "there might be delays between streaming events while the model is working". For large inputs (a whole file as an argument), setting "eager_input_streaming": true on a tool definition turns on fine-grained tool streaming: fragments arrive "without server-side buffering or JSON validation", sooner and in bigger pieces, with the warning that "you might receive partial or invalid JSON", so guard the parse. OpenRouter turns this on for you: its provider-routing docs say that for every streamed request (stream: true) that includes user-defined tools, OpenRouter sets eager_input_streaming: true on each tool it sends to Anthropic. So on the OpenRouter route to Claude, partial or invalid JSON is more likely than on Anthropic's own API, and the guard is not optional (03.5, 11.2).

This mock (layer 3) replays the fragment pattern from OpenAI's function-calling guide through both the OpenAI raw stream and the Anthropic helper, and shows what each partial string parses to:

python
# s6_2_tool_args_mock.py: tool-call arguments arrive as JSON *fragments*. The server is a MOCK that
# replays the fragment pattern from OpenAI's function-calling guide and Anthropic's streaming guide.
import json

import anthropic
import httpx2
import pydantic_core
from openai import OpenAI

FRAGMENTS = ['{"', 'location', '":"', 'Paris', ',', ' France', '"}']   # as in OpenAI's docs example


def sse(events: list[tuple[str, dict]]) -> httpx2.MockTransport:
    body = b"".join(f"event: {n}\ndata: {json.dumps(d)}\n\n".encode() for n, d in events)
    return httpx2.MockTransport(lambda req: httpx2.Response(
        200, headers={"content-type": "text/event-stream"}, content=body))


def show(buffer: str) -> str:
    try:
        json.loads(buffer)
        strict = "valid JSON"
    except json.JSONDecodeError:
        strict = "json.loads fails"
    partial = pydantic_core.from_json(buffer, allow_partial="trailing-strings") if buffer else None
    return f"{buffer!r:<32} {strict:<17} partial parse: {partial}"


# --- OpenAI Responses: response.function_call_arguments.delta / .done
item = {"type": "function_call", "id": "fc_1", "call_id": "call_1", "name": "get_weather", "arguments": "",
        "status": "in_progress"}
events = [("response.output_item.added", {"type": "response.output_item.added", "output_index": 0,
           "item": item, "sequence_number": 2})]
events += [("response.function_call_arguments.delta", {"type": "response.function_call_arguments.delta",
            "item_id": "fc_1", "output_index": 0, "delta": f, "sequence_number": 3 + i})
           for i, f in enumerate(FRAGMENTS)]
events.append(("response.function_call_arguments.done", {"type": "response.function_call_arguments.done",
               "item_id": "fc_1", "output_index": 0, "arguments": "".join(FRAGMENTS), "sequence_number": 10,
               "name": "get_weather"}))
client = OpenAI(api_key="sk-test", http_client=httpx2.Client(transport=sse(events)))
print("OpenAI Responses")
buffer = ""
with client.responses.create(model="gpt-6-luna", input="Weather in Paris?", stream=True) as stream:
    for event in stream:
        if event.type == "response.function_call_arguments.delta":
            buffer += event.delta
            print("  delta ", show(buffer))
        elif event.type == "response.function_call_arguments.done":
            args = json.loads(event.arguments)             # parse ONCE, from the complete string
            print("  done   arguments =", args)

# --- Anthropic: input_json_delta inside a tool_use block
a_events = [("message_start", {"type": "message_start", "message": {"id": "msg_1", "type": "message",
             "role": "assistant", "content": [], "model": "claude-haiku-5-5", "stop_reason": None,
             "stop_sequence": None, "usage": {"input_tokens": 50, "output_tokens": 1}}}),
            ("content_block_start", {"type": "content_block_start", "index": 0, "content_block": {
             "type": "tool_use", "id": "toolu_1", "name": "get_weather", "input": {}}})]
a_events += [("content_block_delta", {"type": "content_block_delta", "index": 0,
              "delta": {"type": "input_json_delta", "partial_json": f}}) for f in FRAGMENTS]
a_events += [("content_block_stop", {"type": "content_block_stop", "index": 0}),
             ("message_delta", {"type": "message_delta", "delta": {"stop_reason": "tool_use",
              "stop_sequence": None}, "usage": {"output_tokens": 20}}),
             ("message_stop", {"type": "message_stop"})]
claude = anthropic.Anthropic(api_key="sk-test", http_client=httpx2.Client(transport=sse(a_events)))
print("Anthropic (messages.stream helper)")
with claude.messages.stream(model="claude-haiku-5-5", max_tokens=100,
                            messages=[{"role": "user", "content": "Weather in Paris?"}]) as stream:
    for event in stream:
        if event.type == "input_json":                    # helper event: the SDK's own partial parse
            print(f"  input_json partial_json={event.partial_json!r:<12} snapshot={event.snapshot}")
    final = stream.get_final_message()
block = final.content[0]
print("  final tool_use input =", block.input if block.type == "tool_use" else None,
      "| stop_reason =", final.stop_reason)
Output18 lines
OpenAI Responses
  delta  '{"'                             json.loads fails  partial parse: {}
  delta  '{"location'                     json.loads fails  partial parse: {}
  delta  '{"location":"'                  json.loads fails  partial parse: {'location': ''}
  delta  '{"location":"Paris'             json.loads fails  partial parse: {'location': 'Paris'}
  delta  '{"location":"Paris,'            json.loads fails  partial parse: {'location': 'Paris,'}
  delta  '{"location":"Paris, France'     json.loads fails  partial parse: {'location': 'Paris, France'}
  delta  '{"location":"Paris, France"}'   valid JSON        partial parse: {'location': 'Paris, France'}
  done   arguments = {'location': 'Paris, France'}
Anthropic (messages.stream helper)
  input_json partial_json='{"'         snapshot={}
  input_json partial_json='location'   snapshot={}
  input_json partial_json='":"'        snapshot={}
  input_json partial_json='Paris'      snapshot={}
  input_json partial_json=','          snapshot={}
  input_json partial_json=' France'    snapshot={}
  input_json partial_json='"}'         snapshot={'location': 'Paris, France'}
  final tool_use input = {'location': 'Paris, France'} | stop_reason = tool_use

What it shows:

  • json.loads() fails on every fragment but the last. Parse once, from the complete string (the .done event, content_block_stop, or the end of the stream).
  • A partial JSON parser can show a draft early. pydantic_core.from_json(..., allow_partial="trailing-strings") keeps an unfinished string ('Paris,'), which is good for a live preview and bad for decisions: a half-received city name is the wrong city. The Anthropic helper's snapshot uses the stricter mode, which drops incomplete strings, so it stays {} until "Paris, France" is complete.
  • Never execute a tool on partial arguments. Show "Calling get_weather…" as soon as the name arrives; run the function only after the arguments are complete and validated.

6.3 Structured output as partial JSON#

Structured output (lesson 03.4) and streaming pull in opposite directions: the schema guarantees a valid object at the end, and the stream gives you an invalid prefix of it at every moment before that. There are two honest options. Either wait for the end (most backend code), or render partial objects in a UI and validate strictly once complete.

Provider Streaming structured output Partial parsing for you?
OpenAI Chat Completions chat.completions.stream(response_format=Model) Yes: content.delta events carry parsed (a partial dict); get_final_completion().choices[0].message.parsed is the validated model
OpenAI Responses responses.stream(text_format=Model) No: text deltas are raw JSON text; parsed appears only on response.output_text.done, and get_final_response().output_parsed at the end
Anthropic messages.stream(output_format=Model) No: validated at content_block_stop, available as parsed_output on the final message's text block
Gemini generate_content response_json_schema= (Google's recommended field) or response_schema= (the convenience that fills .parsed), with response_mime_type="application/json" (03.4, 3.4) No: chunk.parsed is always None while streaming; join chunk.text and validate
Gemini Interactions response_format= No: join the text deltas and validate
OpenRouter As Chat Completions, with the same openai helper Yes, through the helper

Because providers generate keys in schema order (OpenAI: "outputs will be produced in the same order as the ordering of keys in the schema"), you can design a schema for streaming: put what the user wants to see first (a title, a summary) before the long lists.

This section has two samples. The first runs against the stand-in and uses the Chat Completions helper's built-in partial parsing. The second is your own partial parsing for Gemini, with Pydantic doing the work; it is hosted-only:

python
# s6_3_structured_stream.py: render a structured answer while it streams (local stand-in, no key)
from openai import OpenAI
from pydantic import BaseModel


class City(BaseModel):                     # the strict schema the final answer must satisfy
    name: str
    country: str
    landmarks: list[str]


# Chat Completions helper: the SDK partially parses the JSON for you on every content.delta
client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
with client.chat.completions.stream(
    model="gpt-6-luna",
    messages=[{"role": "user", "content": "Describe Paris as JSON with three landmarks."}],
    response_format=City,
    max_tokens=120,
) as stream:
    seen = None
    for event in stream:
        if event.type == "content.delta" and event.parsed != seen:
            seen = event.parsed
            print("chat draft :", seen)                # a dict that grows; strings may be cut short
    final = stream.get_final_completion().choices[0].message.parsed   # a validated City, or None
print("chat final :", repr(final), "\n")

Output (local model qwen2.5:0.5b via Ollama; a hosted model would name real landmarks):

text
chat draft : {}
chat draft : {'name': 'Paris'}
chat draft : {'name': 'Paris', 'country': 'France'}
chat draft : {'name': 'Paris', 'country': 'France', 'landmarks': []}
chat draft : {'name': 'Paris', 'country': 'France', 'landmarks': ['Eiffel Tower']}
chat draft : {'name': 'Paris', 'country': 'France', 'landmarks': ['Eiffel Tower', 'Louvre Museum']}
chat draft : {'name': 'Paris', 'country': 'France', 'landmarks': ['Eiffel Tower', 'Louvre Museum', 'Arc de Triomphe']}
chat final : City(name='Paris', country='France', landmarks=['Eiffel Tower', 'Louvre Museum', 'Arc de Triomphe']) 
python
# s6_3_structured_stream_gemini.py: partial parsing for a Gemini stream (hosted Gemini API)
from typing_extensions import NotRequired, TypedDict   # pydantic needs this TypedDict on Python < 3.12

import pydantic_core
from google import genai
from google.genai import types
from pydantic import BaseModel, TypeAdapter


class City(BaseModel):                     # the strict schema the final answer must satisfy
    name: str
    country: str
    landmarks: list[str]


class PartialCity(TypedDict):              # the same shape with every key optional, for drafts
    name: NotRequired[str]
    country: NotRequired[str]
    landmarks: NotRequired[list[str]]


draft_adapter = TypeAdapter(PartialCity)

# Gemini: chunk.parsed is None while streaming, so buffer the text and parse it yourself
gemini = genai.Client()     # reads GEMINI_API_KEY from the environment
buffer, last_draft = "", None
for chunk in gemini.models.generate_content_stream(
    model="gemini-3.8-flash",
    contents="Describe Paris as JSON with three landmarks.",
    config=types.GenerateContentConfig(response_mime_type="application/json", response_schema=City,
                                       max_output_tokens=120),
):
    assert chunk.parsed is None                       # never filled in a stream
    buffer += chunk.text or ""
    if not buffer.strip():
        continue
    # "trailing-strings" keeps a half-finished string; the TypedDict tolerates missing keys
    draft = draft_adapter.validate_python(pydantic_core.from_json(buffer, allow_partial="trailing-strings"))
    if draft != last_draft and len(draft.get("landmarks", [])) != len((last_draft or {}).get("landmarks", [])):
        print("gemini draft:", draft)                 # print only when a new landmark appears
    last_draft = draft
try:
    print("gemini final:", repr(City.model_validate_json(buffer)))   # strict validation, once, at the end
except Exception as e:
    print("gemini final: invalid ->", type(e).__name__)

The pattern to copy is the Gemini sample above: one strict model (City) for the final result, and one lenient shape (a TypedDict with every key NotRequired) for drafts, filled by pydantic_core.from_json(buffer, allow_partial="trailing-strings"). Pydantic's own TypeAdapter.validate_json(..., experimental_allow_partial=...) works too, but in Pydantic 2.14 it rejects a BaseModel whose required fields haven't arrived yet, which is why the draft type has optional keys. Expect '' entries in the drafts: that's the start of a landmark whose text hasn't arrived. Render drafts as drafts (greyed out, no buttons), and only enable actions on the validated final object.

python
# s6_3b_truncated_json_mock.py: structured output cut off by max_tokens, mid-stream.
# MOCK server: a Claude stream whose JSON text stops half-way, then stop_reason "max_tokens".
import anthropic
import pydantic
from pydantic import BaseModel

from mockkit import claude_block, claude_end, claude_message_start, mock_client_transport


class City(BaseModel):
    name: str
    country: str
    landmarks: list[str]


EVENTS = ([claude_message_start()]
          + claude_block(0, {"type": "text", "text": ""},
                         [{"type": "text_delta", "text": '{"name": "Paris", "country": "Fra'}])
          + claude_end("max_tokens", 16))
client = anthropic.Anthropic(api_key="sk-test", http_client=mock_client_transport(EVENTS))
request = dict(model="claude-haiku-5-5", max_tokens=16, messages=[{"role": "user", "content": "Paris as JSON"}])

# A. With output_format, the helper validates at content_block_stop, i.e. BEFORE message_delta
try:
    with client.messages.stream(**request, output_format=City) as stream:
        for _ in stream:
            pass
except pydantic.ValidationError as e:
    print("A. raised inside the loop:", type(e).__name__, "| stop_reason known yet?",
          stream.current_message_snapshot.stop_reason)

# B. Robust: read to the end first, then decide using stop_reason
with client.messages.stream(**request) as stream:
    final = stream.get_final_message()
text = "".join(b.text for b in final.content if b.type == "text")
if final.stop_reason == "max_tokens":
    print(f"B. truncated after {final.usage.output_tokens} tokens: {text!r} -> raise max_tokens and retry")
else:
    print("B. parsed:", City.model_validate_json(text))
Output2 lines
A. raised inside the loop: ValidationError | stop_reason known yet? None
B. truncated after 16 tokens: '{"name": "Paris", "country": "Fra' -> raise max_tokens and retry

In A, the helper validates at content_block_stop and raises, and the snapshot's stop_reason is still None because message_delta hasn't been read. B reads to the end first and decides with the stop reason. The OpenAI Chat Completions helper takes the opposite approach: it raises LengthFinishReasonError itself when a response_format request finishes with length (4.3). 03.4 owns what to do next (raise the limit, simplify the schema, retry).

6.4 Refusals and citations#

Refusals. A model can decline mid-stream, and each provider signals it differently:

Provider How a refusal streams
OpenAI Responses A content part of type refusal, streamed with response.refusal.delta / response.refusal.done instead of output_text events
OpenAI Chat Completions delta.refusal instead of delta.content; chat.completions.stream() emits refusal.delta / refusal.done
Anthropic Text may already have streamed when message_delta arrives with stop_reason: "refusal", which the API reference describes as "when streaming classifiers intervene to handle potential policy violations"; the final message's stop_details can give a category
Gemini finish_reason such as SAFETY on the last chunk, or a prompt blocked up front (prompt_feedback.block_reason, no candidates)
OpenRouter The upstream model's behaviour, with finish_reason normalized (content_filter) and the original in native_finish_reason; moderation blocks before the stream are HTTP 403 (03.8)

A mock of the first and the third:

python
# s6_4_refusal_mock.py: refusals in a stream. MOCK servers replaying documented shapes:
# OpenAI's response.refusal.delta / .done events, and a Claude stream ending with stop_reason "refusal".
import anthropic
from openai import OpenAI

from mockkit import claude_block, claude_end, claude_message_start, mock_client_transport

# OpenAI: the refusal is its own content part (type "refusal"), streamed with its own events
item = {"id": "msg_1", "type": "message", "role": "assistant", "status": "in_progress", "content": []}
OPENAI = [
    ("response.output_item.added", {"type": "response.output_item.added", "output_index": 0, "item": item,
                                    "sequence_number": 1}),
    ("response.content_part.added", {"type": "response.content_part.added", "item_id": "msg_1", "output_index": 0,
     "content_index": 0, "part": {"type": "refusal", "refusal": ""}, "sequence_number": 2}),
    ("response.refusal.delta", {"type": "response.refusal.delta", "item_id": "msg_1", "output_index": 0,
     "content_index": 0, "delta": "I can't help with that.", "sequence_number": 3}),
    ("response.refusal.done", {"type": "response.refusal.done", "item_id": "msg_1", "output_index": 0,
     "content_index": 0, "refusal": "I can't help with that.", "sequence_number": 4}),
]
client = OpenAI(api_key="sk-test", http_client=mock_client_transport(OPENAI))
with client.responses.create(model="gpt-6-luna", input="(something disallowed)", stream=True) as stream:
    for event in stream:
        if event.type == "response.output_text.delta":
            print("answer text:", event.delta)
        elif event.type == "response.refusal.delta":     # route to a refusal UI, not the answer
            print("refusal    :", event.delta)

# Claude: text may already have streamed when stop_reason "refusal" arrives at the very end
CLAUDE = ([claude_message_start()]
          + claude_block(0, {"type": "text", "text": ""}, [{"type": "text_delta", "text": "Here is how to "}])
          + claude_end("refusal", 5))
claude = anthropic.Anthropic(api_key="sk-test", http_client=mock_client_transport(CLAUDE))
shown = ""
with claude.messages.stream(model="claude-haiku-5-5", max_tokens=100,
                            messages=[{"role": "user", "content": "(something disallowed)"}]) as stream:
    for text in stream.text_stream:
        shown += text
    final = stream.get_final_message()
if final.stop_reason == "refusal":
    print(f"claude     : stop_reason=refusal after showing {shown!r} -> replace it with a refusal message")
Output2 lines
refusal    : I can't help with that.
claude     : stop_reason=refusal after showing 'Here is how to ' -> replace it with a refusal message

The Claude case is the one that needs UI work: the user has already seen "Here is how to ", and the stream then says it was refused. Your front end needs a way to replace what's on screen, not just append to it; the reset event of 7.5 serves both cases. Detecting refusals in general is covered in 02.10, 14.3.

Citations stream as their own events, attached to the text they support: Anthropic sends citations_delta with one citation each, OpenAI Responses sends response.output_text.annotation.added, Interactions has text_annotation_delta, and Gemini generate_content attaches grounding_metadata to the candidate. The safe UI pattern is to stream the text, collect citations as they arrive, and render the markers or a source list when the block finishes, so a citation never points at text that isn't on screen yet. Lesson 03.6 covers citations on documents.


Part 7: Errors inside a stream#

Lesson 03.8 owns the error taxonomy, the exception classes and retry policy. This part covers what is specific to streams: errors that arrive after the server has committed to 200 OK.

7.1 Before and after the 200#

A streaming response sends its status line and headers before any text exists. Whatever goes wrong after that point can't change the status code, so it has to travel inside the stream, or the connection simply drops.

sequenceDiagram
    participant App as Your code
    participant API as Provider
    App->>API: request with stream true
    alt fails before the stream starts
        API-->>App: HTTP 429 / 500 / 529 with a JSON error body
        Note over App: SDK raises a status error and its built-in retries apply
    else fails after HTTP 200 was sent
        API-->>App: HTTP 200, text/event-stream
        API-->>App: deltas ...
        API-->>App: an error event (or the connection just drops)
        Note over App: no retry by the SDK, the user has already seen partial text
    end
Error before the stream starts Error after the 200
How it arrives HTTP status (400, 401, 429, 500, 529...) with a JSON error body An error event or chunk in the body, a terminal event with a failed status, or a dropped connection
What the user has seen Nothing Possibly a lot of text
SDK behaviour Raises the usual status exception; built-in retries apply to 408, 409, 429 and 5xx (03.1, 7.4) Raises or yields, depending on SDK and API (below); not retried (one Gemini exception, 7.4)
Failover Gateways (e.g. OpenRouter) can try another provider OpenRouter: "Failover to another provider stops once the 200 is committed"

OpenRouter's docs add a subtle point that applies everywhere: "Once the provider has returned response headers, the 200 OK status is committed even if no token has been produced yet." The error can be the first and only event in the stream, so "treat a 200 carrying an error chunk with no content as a failure, not a success".

7.2 Each provider's mid-stream error#

Provider Mid-stream error on the wire What the SDK does with it
OpenAI Responses An error event (code, message, param), and/or a terminal response.failed whose response.error has code and message Yields both as ordinary events. Nothing is raised: your loop must check
OpenAI Chat Completions A chunk whose JSON has a top-level error. Handled by the SDK; OpenAI's Chat reference does not document this shape Raises openai.APIError (the openai decoder raises for any data: JSON with an "error" key)
Anthropic event: error with {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}; Anthropic says an overloaded_error "would normally correspond to an HTTP 529 in a non-streaming context" Raises anthropic.APIStatusError with status_code == 200 (the HTTP status, which was fine) and the error in e.body; not the OverloadedError subclass you'd get for a real 529
Gemini generate_content A chunk whose JSON is {"error": {"code": ..., "message": ..., "status": ...}}. Handled by the SDK; Google's streamGenerateContent page does not document error chunks Raises google.genai.errors.ClientError or ServerError, chosen by the code in the JSON. If a continuation token had arrived, the SDK may resume instead (4.5b)
Gemini Interactions An error event with error.code and error.message (e.g. "gateway_timeout") Yields it as an ErrorEvent
OpenRouter Chat Completions A final chunk with a top-level error and choices[0].finish_reason: "error" Raises openai.APIError (same decoder), so finish_reason: "error" never reaches your code through the SDK
OpenRouter Responses response.failed, with error_type at the top level of response; it may also send an error event ("handling both is safe") Yields, as OpenAI Responses. Upstream token-limit errors become response.incomplete instead
Any provider The connection drops (network failure, proxy timeout, server restart), or the body just ends with no terminal event A drop raises a connection error (APIConnectionError in openai/anthropic, an httpx error in google-genai), or a timeout error (Part 8). A clean end of body raises nothing in most helpers (case 7 below)

7.3 Try it: what each SDK raises#

A mock server per case (layer 3), each replaying the documented error shape after a first delta, plus one contrast case where the error happens before the stream (case 6), plus the case with no error at all: the body just ends after one delta, with no terminal event (case 7). Every SDK is the real one, and case 7 also runs the accumulators of 5.3:

python
# s7_2_midstream_errors.py: what each SDK does when an error arrives AFTER the HTTP 200.
# Every server here is a MOCK transport replaying the error shapes from each provider's docs.
import json

import anthropic
import httpx
import httpx2
from google import genai
from google.genai import types
from openai import OpenAI

from accumulate import AnthropicAccumulator, ChatAccumulator, GeminiAccumulator, ResponsesAccumulator, StreamInterrupted

attempts = {"count": 0}


def sse_transport(body: bytes, module=httpx2):
    """A mock server that always answers 200 + text/event-stream with `body`, and counts requests."""
    def handler(request):
        attempts["count"] += 1
        return module.Response(200, headers={"content-type": "text/event-stream"}, content=body)
    return module.MockTransport(handler)


def ev(name: str | None, data: dict | str) -> bytes:
    line = data if isinstance(data, str) else json.dumps(data)
    return (f"event: {name}\n" if name else "").encode() + f"data: {line}\n\n".encode()


def report(label: str, run) -> None:
    attempts["count"] = 0
    print(label)
    text: list[str] = []
    try:
        run(text)
        outcome = "no exception"
    except Exception as e:  # noqa: BLE001 (we want to see exactly what is raised)
        package = {"anthropic": "anthropic", "openai": "openai", "google": "google.genai.errors"}
        outcome = f"raised {package[type(e).__module__.split('.')[0]]}.{type(e).__name__}"
        if hasattr(e, "status_code"):
            outcome += f" (status_code={e.status_code})"
    print(f"  text received: {''.join(text)!r}\n  {outcome}, HTTP attempts: {attempts['count']}")


# 1. Anthropic: an `event: error` in the middle of the stream (shape from the streaming docs)
ANTHROPIC = b"".join([
    ev("message_start", {"type": "message_start", "message": {"id": "msg_1", "type": "message", "role": "assistant",
       "content": [], "model": "claude-haiku-5-5", "stop_reason": None, "stop_sequence": None,
       "usage": {"input_tokens": 12, "output_tokens": 1}}}),
    ev("content_block_start", {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}),
    ev("content_block_delta", {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": "Red and"}}),
    ev("error", {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}),
])


def run_anthropic(text: list[str]) -> None:
    client = anthropic.Anthropic(api_key="sk-test", http_client=httpx2.Client(transport=sse_transport(ANTHROPIC)))
    try:
        with client.messages.stream(model="claude-haiku-5-5", max_tokens=50,
                                    messages=[{"role": "user", "content": "Colours?"}]) as stream:
            for t in stream.text_stream:
                text.append(t)
    except anthropic.APIStatusError as e:
        print(f"  (anthropic) is OverloadedError? {isinstance(e, anthropic.OverloadedError)} | body={e.body}")
        raise


# 2. OpenRouter Chat Completions: a final chunk with a top-level `error` and finish_reason "error"
def chunk(content: str, finish: str | None = None, **extra) -> dict:
    return {"id": "gen-1", "object": "chat.completion.chunk", "created": 1, "model": "openai/gpt-6-luna",
            "choices": [{"index": 0, "delta": {"content": content}, "finish_reason": finish}], **extra}


OPENROUTER = b"".join([
    b": OPENROUTER PROCESSING\n\n",
    ev(None, chunk("Red and")),
    ev(None, chunk("", "error", error={"code": "server_error", "message": "Provider disconnected unexpectedly"})),
    ev(None, "[DONE]"),
])


def run_openrouter(text: list[str]) -> None:
    client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key="sk-test",
                    http_client=httpx2.Client(transport=sse_transport(OPENROUTER)))
    with client.chat.completions.create(model="openai/gpt-6-luna", stream=True,
                                        messages=[{"role": "user", "content": "Colours?"}]) as stream:
        for c in stream:
            if c.choices:
                text.append(c.choices[0].delta.content or "")
                if c.choices[0].finish_reason == "error":     # never reached: the SDK raises first
                    print("  saw finish_reason='error'")


# 3. OpenAI Responses: `error` and `response.failed` are ordinary events (shapes from the API reference)
RESPONSES = b"".join([
    ev("response.output_text.delta", {"type": "response.output_text.delta", "item_id": "msg_1", "output_index": 0,
       "content_index": 0, "delta": "Red and", "logprobs": [], "sequence_number": 4}),
    ev("error", {"type": "error", "code": "server_error", "message": "Something went wrong", "param": None,
       "sequence_number": 5}),
    ev("response.failed", {"type": "response.failed", "sequence_number": 6, "response": {
       "id": "resp_1", "object": "response", "created_at": 1, "status": "failed", "model": "gpt-6-luna",
       "output": [], "error": {"code": "server_error", "message": "The model failed to generate a response."},
       "parallel_tool_calls": True, "tool_choice": "auto", "tools": []}}),
])


def run_responses(text: list[str]) -> None:
    client = OpenAI(api_key="sk-test", http_client=httpx2.Client(transport=sse_transport(RESPONSES)))
    with client.responses.create(model="gpt-6-luna", input="Colours?", stream=True) as stream:
        for event in stream:
            if event.type == "response.output_text.delta":
                text.append(event.delta)
            elif event.type == "error":                       # yielded, not raised: YOU must check
                print(f"  (openai) got an `error` event: code={event.code} message={event.message!r}")
            elif event.type == "response.failed":             # the terminal event of a failed response
                print(f"  (openai) got response.failed: status={event.response.status} error={event.response.error}")


# 4. Gemini Interactions: an `error` event (shape from the Interactions streaming guide)
INTERACTIONS = b"".join([
    ev("step.start", {"index": 0, "step": {"type": "model_output"}, "event_type": "step.start"}),
    ev("step.delta", {"index": 0, "delta": {"type": "text", "text": "Red and"}, "event_type": "step.delta"}),
    ev("error", {"error": {"message": "Deadline expired before operation could complete.", "code": "gateway_timeout"},
       "event_type": "error"}),
])


def run_interactions(text: list[str]) -> None:
    client = genai.Client(api_key="sk-test", http_options=types.HttpOptions(
        httpx_client=httpx.Client(transport=sse_transport(INTERACTIONS, httpx))))
    with client.interactions.create(model="gemini-3.8-flash", input="Colours?", stream=True) as stream:
        for event in stream:
            if event.event_type == "step.delta" and event.delta.type == "text":
                text.append(event.delta.text)
            elif event.event_type == "error":                 # also yielded, not raised
                print(f"  (genai) got an `error` event: {event.error}")


# 5. Gemini generate_content_stream: a chunk whose JSON is {"error": {...}}
GEMINI = b"".join([
    ev(None, {"candidates": [{"content": {"parts": [{"text": "Red and"}], "role": "model"}, "index": 0}]}),
    ev(None, {"error": {"code": 503, "message": "The model is overloaded.", "status": "UNAVAILABLE"}}),
])


def run_gemini(text: list[str]) -> None:
    client = genai.Client(api_key="sk-test", http_options=types.HttpOptions(
        httpx_client=httpx.Client(transport=sse_transport(GEMINI, httpx))))
    for c in client.models.generate_content_stream(model="gemini-3.8-flash", contents="Colours?"):
        text.append(c.text or "")


# 6. For contrast: Anthropic fails BEFORE the stream starts (HTTP 529), then succeeds
ANTHROPIC_OK = ANTHROPIC.replace(
    ev("error", {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}),
    ev("content_block_stop", {"type": "content_block_stop", "index": 0})
    + ev("message_delta", {"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence": None},
                           "usage": {"output_tokens": 3}})
    + ev("message_stop", {"type": "message_stop"}))


def run_anthropic_529_then_ok(text: list[str]) -> None:
    def handler(request: httpx2.Request) -> httpx2.Response:
        attempts["count"] += 1
        if attempts["count"] == 1:                            # a normal HTTP error, no stream yet
            return httpx2.Response(529, json={"type": "error", "error": {"type": "overloaded_error",
                                                                         "message": "Overloaded"}})
        return httpx2.Response(200, headers={"content-type": "text/event-stream"}, content=ANTHROPIC_OK)
    client = anthropic.Anthropic(api_key="sk-test", http_client=httpx2.Client(transport=httpx2.MockTransport(handler)))
    with client.messages.stream(model="claude-haiku-5-5", max_tokens=50,
                                messages=[{"role": "user", "content": "Colours?"}]) as stream:
        for t in stream.text_stream:
            text.append(t)


for label, fn in [("1. Anthropic event: error", run_anthropic),
                  ("2. OpenRouter error chunk", run_openrouter),
                  ("3. OpenAI Responses error event", run_responses),
                  ("4. Gemini Interactions error event", run_interactions),
                  ("5. Gemini generate_content error chunk", run_gemini),
                  ("6. Anthropic HTTP 529 before the stream, then OK", run_anthropic_529_then_ok)]:
    report(label, fn)


# 7. NO error event at all: the body just ends after one delta (a proxy or load balancer closed the
#    connection cleanly). Nothing is raised by most helpers: only the missing terminal event tells you.
print("7. Clean end of body after one delta, no terminal event (a proxy closed the connection)")
CUT_ANTHROPIC = b"".join(ANTHROPIC.split(b"event: error")[:1])           # case 1's body, cut before the error
CUT_CHAT = ev(None, chunk("Red and"))                                     # no finish chunk, no [DONE]
RESP_SKELETON = {"id": "resp_1", "object": "response", "created_at": 1, "status": "in_progress", "model": "gpt-6-luna",
                 "output": [], "parallel_tool_calls": True, "tool_choice": "auto", "tools": []}
CUT_RESPONSES = b"".join([
    ev("response.created", {"type": "response.created", "sequence_number": 0, "response": RESP_SKELETON}),
    ev("response.output_item.added", {"type": "response.output_item.added", "output_index": 0, "sequence_number": 1,
       "item": {"type": "message", "id": "msg_1", "role": "assistant", "status": "in_progress", "content": []}}),
    ev("response.content_part.added", {"type": "response.content_part.added", "item_id": "msg_1", "output_index": 0,
       "content_index": 0, "sequence_number": 2, "part": {"type": "output_text", "text": "", "annotations": []}}),
    ev("response.output_text.delta", {"type": "response.output_text.delta", "item_id": "msg_1", "output_index": 0,
       "content_index": 0, "delta": "Red and", "logprobs": [], "sequence_number": 3})])
CUT_GEMINI = ev(None, {"candidates": [{"content": {"parts": [{"text": "Red and"}], "role": "model"}, "index": 0}]})

claude = anthropic.Anthropic(api_key="sk-test", http_client=httpx2.Client(transport=sse_transport(CUT_ANTHROPIC)))
with claude.messages.stream(model="claude-haiku-5-5", max_tokens=50, messages=[{"role": "user", "content": "Colours?"}]) as st:
    msg = st.get_final_message()
print(f"  anthropic messages.stream().get_final_message(): no exception, stop_reason={msg.stop_reason}, "
      f"usage.output_tokens={msg.usage.output_tokens} (the placeholder from message_start), "
      f"text={msg.content[0].text if msg.content[0].type == 'text' else None!r}")

oa = OpenAI(api_key="sk-test", http_client=httpx2.Client(transport=sse_transport(CUT_CHAT)))
with oa.chat.completions.stream(model="gpt-6-luna", messages=[{"role": "user", "content": "Colours?"}]) as st:
    completion = st.get_final_completion()
print(f"  openai chat.completions.stream().get_final_completion(): no exception, "
      f"finish_reason={completion.choices[0].finish_reason}, text={completion.choices[0].message.content!r}")

oa = OpenAI(api_key="sk-test", http_client=httpx2.Client(transport=sse_transport(CUT_RESPONSES)))
acc, text7 = ResponsesAccumulator(), []
with oa.responses.create(model="gpt-6-luna", input="Colours?", stream=True) as st:      # a raw loop
    for event in st:
        acc.add(event)
        if event.type == "response.output_text.delta":
            text7.append(event.delta)
print(f"  openai responses.create(stream=True) raw loop: no exception, text={''.join(text7)!r}")
try:
    with oa.responses.stream(model="gpt-6-luna", input="Colours?") as st:
        st.get_final_response()
except RuntimeError as e:
    print(f"  openai responses.stream().get_final_response(): raised RuntimeError({str(e)!r})   <- the only one")

gem = genai.Client(api_key="sk-test", http_options=types.HttpOptions(
    httpx_client=httpx.Client(transport=sse_transport(CUT_GEMINI, httpx))))
gacc = GeminiAccumulator()
for c in gem.models.generate_content_stream(model="gemini-3.8-flash", contents="Colours?"):
    gacc.add(c)
print(f"  google-genai generate_content_stream (no token, so nothing to resume): no exception, "
      f"text={gacc.text}, finish_reason={gacc.finish_reason}")

# The fix is yours: the accumulators from 5.3 flag it, and strict mode raises with the partial result attached
claude = anthropic.Anthropic(api_key="sk-test", http_client=httpx2.Client(transport=sse_transport(CUT_ANTHROPIC)))
aacc = AnthropicAccumulator()
with claude.messages.create(model="claude-haiku-5-5", max_tokens=50, stream=True,
                            messages=[{"role": "user", "content": "Colours?"}]) as st:
    for event in st:
        aacc.add(event)
cacc = ChatAccumulator()
oa_chat = OpenAI(api_key="sk-test", http_client=httpx2.Client(transport=sse_transport(CUT_CHAT)))
with oa_chat.chat.completions.create(model="gpt-6-luna", stream=True,
                                     messages=[{"role": "user", "content": "Colours?"}]) as st:
    for c in st:
        cacc.add(c)
for name, accumulator in [("ChatAccumulator", cacc), ("AnthropicAccumulator", aacc),
                          ("ResponsesAccumulator", acc), ("GeminiAccumulator", gacc)]:
    final = accumulator.result()
    print(f"  {name}.result(): complete={final.complete}, finish_reason={final.finish_reason}, text={final.text}")
    try:
        accumulator.result(strict=True)
    except StreamInterrupted as e:
        print(f"    result(strict=True) raised StreamInterrupted: {e} | e.partial.text={e.partial.text}")
Output36 lines
1. Anthropic event: error
  (anthropic) is OverloadedError? False | body={'type': 'error', 'error': {'type': 'overloaded_error', 'message': 'Overloaded'}}
  text received: 'Red and'
  raised anthropic.APIStatusError (status_code=200), HTTP attempts: 1
2. OpenRouter error chunk
  text received: 'Red and'
  raised openai.APIError, HTTP attempts: 1
3. OpenAI Responses error event
  (openai) got an `error` event: code=server_error message='Something went wrong'
  (openai) got response.failed: status=failed error=ResponseError(code='server_error', message='The model failed to generate a response.', misalignment=None, param=None, type=None)
  text received: 'Red and'
  no exception, HTTP attempts: 1
4. Gemini Interactions error event
  (genai) got an `error` event: code='gateway_timeout' message='Deadline expired before operation could complete.'
  text received: 'Red and'
  no exception, HTTP attempts: 1
5. Gemini generate_content error chunk
  text received: 'Red and'
  raised google.genai.errors.ServerError, HTTP attempts: 1
6. Anthropic HTTP 529 before the stream, then OK
  text received: 'Red and'
  no exception, HTTP attempts: 2
7. Clean end of body after one delta, no terminal event (a proxy closed the connection)
  anthropic messages.stream().get_final_message(): no exception, stop_reason=None, usage.output_tokens=1 (the placeholder from message_start), text='Red and'
  openai chat.completions.stream().get_final_completion(): no exception, finish_reason=None, text='Red and'
  openai responses.create(stream=True) raw loop: no exception, text='Red and'
  openai responses.stream().get_final_response(): raised RuntimeError("Didn't receive a `response.completed` event.")   <- the only one
  google-genai generate_content_stream (no token, so nothing to resume): no exception, text=['Red and'], finish_reason=None
  ChatAccumulator.result(): complete=False, finish_reason=None, text=['Red and']
    result(strict=True) raised StreamInterrupted: stream ended without a terminal event (received 7 characters of text, 0 tool call(s), finish_reason=None) | e.partial.text=['Red and']
  AnthropicAccumulator.result(): complete=False, finish_reason=None, text=['Red and']
    result(strict=True) raised StreamInterrupted: stream ended without a terminal event (received 7 characters of text, 0 tool call(s), finish_reason=None) | e.partial.text=['Red and']
  ResponsesAccumulator.result(): complete=False, finish_reason=None, text=['Red and']
    result(strict=True) raised StreamInterrupted: stream ended without a terminal event (received 7 characters of text, 0 tool call(s), finish_reason=None) | e.partial.text=['Red and']
  GeminiAccumulator.result(): complete=False, finish_reason=None, text=['Red and']
    result(strict=True) raised StreamInterrupted: stream ended without a terminal event (received 7 characters of text, 0 tool call(s), finish_reason=None) | e.partial.text=['Red and']

Read it in four groups:

  • Raised (cases 1, 2, 5): Anthropic, Chat Completions/OpenRouter and Gemini generate_content turn mid-stream errors into exceptions. Note the Anthropic class: APIStatusError with status_code=200, not OverloadedError. A handler written as except anthropic.OverloadedError: never catches a streamed overload; check e.body["error"]["type"] instead.
  • Yielded (cases 3, 4): OpenAI Responses and Gemini Interactions hand you the error as an event and end the loop normally. Code that only handles text deltas finishes "successfully" with half an answer.
  • Retried (case 6 only): the same overload before the stream started was retried by the SDK and the user never knew. Every mid-stream case shows HTTP attempts: 1.
  • Silent (case 7): the body ends cleanly after Red and, with no error and no terminal event, as when a proxy or load balancer closes the connection. messages.stream().get_final_message() returns a Message with stop_reason=None and usage.output_tokens=1 (the placeholder from message_start). chat.completions.stream().get_final_completion() returns finish_reason=None. A raw Responses loop, a raw Chat loop and Gemini's generate_content_stream just stop. Only responses.stream().get_final_response() raises (RuntimeError). So a truncated answer looks like a successful short one unless your code checks the finish reason or the terminal event. The accumulators flag it: result().complete is False, and result(strict=True) raises StreamInterrupted with the partial result attached (e.partial), which is exactly what 7.5 needs to decide what to do next.

7.4 SDKs don't retry streams#

None of the SDKs retries a stream in general. Once events have started arriving, anything that goes wrong while you iterate goes straight to you, and they're right not to: the SDK can't know what you've already shown, saved or acted on, and a silent retry would produce a different answer (generation isn't deterministic: 02.5, Part 7) glued onto the old one. In openai and anthropic the retry loop wraps only the request that opens the stream, which is why every mid-stream case above shows one HTTP attempt.

One exception, verified in the source: google-genai 2.34.0 resumes generate_content_stream (and chats.send_message_stream) from a server-issued continuation token, and its Interactions stream from continuation hops. The token exists only for very long generations, so short answers have nothing to resume from and the rule above applies to them (4.5b shows both sides with a mock, and how to turn it off). So the accurate statement is: SDK retries cover only the request that opens the stream, except Gemini's long-generation continuation. Either way the retry decision for everything else is yours, and it's an application decision, not a transport one.

7.5 Restart, continue or resume without duplicating text#

When a stream fails part-way, there are four strategies. Which one you can use depends on the provider and on what the user has seen. "Seen" means anything you have forwarded to a client that renders it: answer text, reasoning or thinking text, and tool progress such as a "Calling get_weather…" badge. It does not mean "the first answer token". A stream that has shown a thinking panel but no answer text yet has already put something on the screen, and a silent restart would show that panel twice. Events that draw nothing (a ping, message_start, the empty thinking_delta of hidden thinking, a usage frame) don't count. So the second question in the flowchart is simply "Has anything been shown?":

flowchart TD
    E["Stream failed mid-way,<br/>or ended with no terminal event"] --> Q1{"Is the error retryable?<br/>overloaded, server error,<br/>connection or read timeout,<br/>or a clean end with no terminal event"}
    Q1 -- no --> F["Send an error event to the client<br/>log usage as unknown"]
    Q1 -- yes --> Q2{"Can the provider resume?<br/>OpenAI background + stream<br/>Interactions background"}
    Q2 -- yes --> R["Resume from the last cursor<br/>sequence_number or event_id"]
    Q2 -- no --> Q3{"Has anything been shown?<br/>answer text, reasoning or tool progress<br/>forwarded to the client"}
    Q3 -- no --> S["Restart silently"]
    Q3 -- yes --> T["Restart and send a reset event<br/>that clears everything shown,<br/>or ask the model to continue<br/>from the partial text"]
Strategy How Duplicates? Cost When
Resume Reconnect to the same generation from a cursor None: you get only the events after the cursor No extra tokens OpenAI background responses, Gemini Interactions background mode (Part 9). google-genai also does it for you on long generations (4.5b)
Restart silently Send the request again None, if nothing was shown yet (no text, no reasoning, no tool progress) Input tokens again, plus whatever was generated before the failure The error came before the first event you forwarded
Restart and reset Send the request again; tell the client to clear everything it showed first (answer, reasoning panel, tool badges) None on screen (the old content is replaced), though the answer may differ As above Something was shown; you want a clean, complete answer
Continue Send a new request containing the partial answer and an instruction to continue None, if the model complies Input tokens for the conversation plus the partial answer Long text answers where restarting would waste a lot; text only, not tool calls or thinking

Here is restart-and-reset for Claude, against a mock server whose first attempt fails after two deltas. The function yields your events (layer 3 of 1.4), including reset, and sets shown for text, non-empty reasoning and tool-start events alike:

python
# s7_5_restart.py: recover from a mid-stream error without showing the user duplicated text.
# The server is a MOCK: attempt 1 fails after two deltas (Anthropic `event: error`), attempt 2 succeeds.
import json
import time
from collections.abc import Iterator

import anthropic
import httpx2


def ev(name: str, data: dict) -> bytes:
    return f"event: {name}\ndata: {json.dumps(data)}\n\n".encode()


def anthropic_sse(deltas: list[str], fail: bool) -> bytes:
    out = [ev("message_start", {"type": "message_start", "message": {
        "id": "msg_1", "type": "message", "role": "assistant", "content": [], "model": "claude-haiku-5-5",
        "stop_reason": None, "stop_sequence": None, "usage": {"input_tokens": 20, "output_tokens": 1}}}),
        ev("content_block_start", {"type": "content_block_start", "index": 0,
                                   "content_block": {"type": "text", "text": ""}})]
    out += [ev("content_block_delta", {"type": "content_block_delta", "index": 0,
                                       "delta": {"type": "text_delta", "text": d}}) for d in deltas]
    if fail:
        out.append(ev("error", {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}))
    else:
        out += [ev("content_block_stop", {"type": "content_block_stop", "index": 0}),
                ev("message_delta", {"type": "message_delta", "delta": {"stop_reason": "end_turn",
                   "stop_sequence": None}, "usage": {"output_tokens": 9}}),
                ev("message_stop", {"type": "message_stop"})]
    return b"".join(out)


requests_seen: list[dict] = []


def handler(request: httpx2.Request) -> httpx2.Response:
    requests_seen.append(json.loads(request.content))
    first = len(requests_seen) == 1
    deltas = ["The sky is ", "blue because "] if first else (
        ["The sky is ", "blue because ", "air scatters ", "blue light most."])
    return httpx2.Response(200, headers={"content-type": "text/event-stream"},
                           content=anthropic_sse(deltas, fail=first))


client = anthropic.Anthropic(api_key="sk-test", http_client=httpx2.Client(transport=httpx2.MockTransport(handler)))

# Mid-stream failures worth retrying: overloaded/api errors in the stream, and dropped connections
RETRYABLE_STREAM_ERRORS = {"overloaded_error", "api_error", "connection"}


def stream_error_type(e: Exception) -> str:
    if isinstance(e, anthropic.APIConnectionError):    # includes APITimeoutError
        return "connection"
    body = getattr(e, "body", None)                    # mid-stream: {"type": "error", "error": {"type": ...}}
    return body.get("error", {}).get("type", "unknown") if isinstance(body, dict) else "unknown"


def stream_with_restart(messages: list[dict], max_attempts: int = 3) -> Iterator[dict]:
    """Yields app-level events. On a retryable mid-stream error it starts again and emits
    a `reset` event first, so the UI clears EVERYTHING it showed (answer, reasoning, tool badges)."""
    for attempt in range(1, max_attempts + 1):
        shown = False                                  # "shown" = ANYTHING we forwarded to the client
        try:
            with client.messages.stream(model="claude-haiku-5-5", max_tokens=200, messages=messages) as stream:
                for event in stream:                   # helper events: text, thinking, content_block_start...
                    if event.type == "text":
                        out = {"type": "delta", "text": event.text}
                    elif event.type == "thinking" and event.thinking:   # empty = hidden thinking: nothing to show
                        out = {"type": "reasoning", "text": event.thinking}
                    elif event.type == "content_block_start" and event.content_block.type == "tool_use":
                        out = {"type": "tool", "name": event.content_block.name}   # a "Calling ..." badge
                    else:
                        continue                       # ping-like or bookkeeping events: the user sees nothing
                    shown = True                       # a reasoning panel or tool badge counts, not just answer text
                    yield out
                final = stream.get_final_message()
            yield {"type": "done", "stop_reason": final.stop_reason, "output_tokens": final.usage.output_tokens}
            return
        except (anthropic.APIStatusError, anthropic.APIConnectionError) as e:
            error_type = stream_error_type(e)
            retryable = error_type in RETRYABLE_STREAM_ERRORS
            if not retryable or attempt == max_attempts:
                yield {"type": "error", "message": str(e), "retryable": retryable}
                return
            if shown:
                yield {"type": "reset", "reason": error_type, "attempt": attempt + 1}
            time.sleep(0.5 * attempt)                  # a short backoff; 03.8 covers jitter properly


screen = ""                                            # what the user would see
for event in stream_with_restart([{"role": "user", "content": "Why is the sky blue? One sentence."}]):
    if event["type"] == "delta":
        screen += event["text"]
    elif event["type"] == "reset":
        screen = ""                                    # clear the partial answer
    print(f"{event['type']:<6} {json.dumps({k: v for k, v in event.items() if k != 'type'})}")
print(f"\nfinal screen: {screen!r}\nHTTP requests made: {len(requests_seen)}")
Output11 lines
delta  {"text": "The sky is "}
delta  {"text": "blue because "}
reset  {"reason": "overloaded_error", "attempt": 2}
delta  {"text": "The sky is "}
delta  {"text": "blue because "}
delta  {"text": "air scatters "}
delta  {"text": "blue light most."}
done   {"stop_reason": "end_turn", "output_tokens": 9}

final screen: 'The sky is blue because air scatters blue light most.'
HTTP requests made: 2

The user saw "The sky is blue because ", then the screen cleared and the full answer streamed. Without the reset event the screen would read "The sky is blue because The sky is blue because air scatters...". The same reset event handles a refusal that arrives after text (6.4).

For continue, Anthropic's error-recovery guidance for Claude 4.6 and later is: capture the partial response, then "construct a continuation request" with "a user message containing the partial response and an instruction to continue", and gives the template "Your previous response was interrupted and ended with [previous_response]. Continue from where you left off." So the partial text goes inside a user message. Putting it in an assistant turn is the older pattern, documented for Claude 4.5 and earlier ("the partial assistant response as the beginning of a new assistant message"), and it isn't what Anthropic documents for current models. The sample below builds the documented request first, and the legacy form second, labelled as such. Building the requests needs no network:

python
# s7_5b_continuation.py: build a "continue from where you stopped" request (no network).
# Anthropic's error-recovery guidance for Claude 4.6 and later: put the partial response INSIDE a user
# message with an instruction to continue (its template: "Your previous response was interrupted and
# ended with [previous_response]. Continue from where you left off."). The quotes around the partial text
# are our addition, so the trailing space and the sentence's full stop stay unambiguous.
import json


def continuation_messages(messages: list[dict], partial_text: str) -> list[dict]:
    """The original conversation + one user message carrying what the user already saw."""
    return messages + [{"role": "user", "content":
                        f'Your previous response was interrupted and ended with "{partial_text}". '
                        "Continue from where you left off."}]


def legacy_continuation_messages(messages: list[dict], partial_text: str) -> list[dict]:
    """The Claude 4.5-and-earlier pattern: the partial answer as an ASSISTANT turn for the model to extend.
    Not what Anthropic documents for current models, and a request that ENDS with an assistant turn is
    rejected by current Claude and Gemini models (03.2, 4.2), so this one needs a follow-up user turn."""
    return messages + [{"role": "assistant", "content": partial_text.rstrip()},
                       {"role": "user", "content": "Your previous response was interrupted. Continue "
                                                   "exactly from where you left off."}]


original = [{"role": "user", "content": "Why is the sky blue? One sentence."}]
shown_so_far = "The sky is blue because "          # note the trailing space: the UI already has it on screen
print("Documented form (Claude 4.6 and later):")
print(json.dumps(continuation_messages(original, shown_so_far), indent=2))
print("\nLegacy form (4.5 and earlier; rstrip() drops the trailing space the UI must then restore):")
print(json.dumps(legacy_continuation_messages(original, shown_so_far), indent=2))
# The UI keeps `shown_so_far` on screen and APPENDS the new stream to it.
Output27 lines
Documented form (Claude 4.6 and later):
[
  {
    "role": "user",
    "content": "Why is the sky blue? One sentence."
  },
  {
    "role": "user",
    "content": "Your previous response was interrupted and ended with \"The sky is blue because \". Continue from where you left off."
  }
]

Legacy form (4.5 and earlier; rstrip() drops the trailing space the UI must then restore):
[
  {
    "role": "user",
    "content": "Why is the sky blue? One sentence."
  },
  {
    "role": "assistant",
    "content": "The sky is blue because"
  },
  {
    "role": "user",
    "content": "Your previous response was interrupted. Continue exactly from where you left off."
  }
]

Note that the documented form keeps the trailing space of the partial text (inside the quotes), while the legacy form's rstrip() drops it, so a UI that appends the new stream to the old text must restore the space.

Anthropic adds that "tool use and thinking blocks cannot be partially recovered. You can resume streaming from the most recent text block." Expect some rough joins (a missing space, a repeated word) with continuation; it trades polish for not regenerating a long answer.

7.6 Usage when a stream breaks#

A broken stream usually never delivers its usage: Chat Completions puts it in the last chunk ("If the stream is interrupted, you may not receive the final usage chunk"), Anthropic in message_delta, Responses and Interactions in the terminal event. But the provider still did the work, and may bill for it (8.5).

Rule Why
Log usage as unknown (null), never as 0 Zero says "free"; your cost dashboards and budgets would undercount exactly the failed requests (03.7)
Log what you do know: input size (counted or estimated), the number of deltas and characters received, elapsed time, the outcome (error, client disconnected, timeout) Lets you estimate cost later, and spot patterns (one model failing more often)
On OpenRouter, look the request up afterwards: GET /api/v1/generation?id=... reports the generation's real usage, total_cost and a cancelled flag The one provider where after-the-fact usage for a broken stream is easy to get
On Anthropic, message_start already carried the input token count Even a stream that dies before message_delta tells you its input size

The FastAPI app in 11.4 logs exactly this way: usage=unknown when the client disconnects.


Part 8: Timeouts, keep-alives and cancellation#

8.1 A read timeout is the longest allowed silence#

HTTP clients have several timeouts (connect, write, pool and read), and 03.8 covers them all. For streams, one matters most, and it's widely misunderstood: the read timeout is not "how long the whole response may take". In httpx and httpx2 it is the longest the client will wait for the next bytes. nginx documents its proxy timeout the same way: it "is set only between two successive read operations, not for the transmission of the whole response". Every byte that arrives (a delta, a ping, a comment) resets the clock.

That has two consequences:

  • A thinking model may send nothing for a long time before its first answer token, and a long tool argument may pause between keys (6.2). A read timeout shorter than the longest silence kills healthy streams.
  • A stream that keeps sending keep-alives never hits the read timeout, even if no text ever comes. Only a total deadline, which you add yourself, bounds the whole thing.
SDK Default (as of November 2026) Where the read timeout comes from
openai 3.42.1 600 s, connect 5 s timeout= on the client or per request: a number (all phases) or httpx2.Timeout(total, read=...)
anthropic 2.4.0 600 s, connect 5 s The same
google-genai 2.34.0 None: no timeout at all unless you set one HttpOptions(timeout=...) in milliseconds, passed to httpx as one number, so it limits each phase (in effect, the silence between reads), not the total
google-genai Interactions As above, per hop A numeric timeout= on interactions.create "bounds the whole call (all continuation hops together)"

For a total deadline, Python 3.11+ has asyncio.timeout(): wrap the whole stream (opening it and consuming it) and it raises TimeoutError when the time is up, cancelling whatever is running inside. In synchronous code, check elapsed time inside the loop and break (the with block then closes the stream).

8.2 Try it: read timeouts, pings and a total deadline#

To control the silence exactly, this sample runs a tiny fake server (layer 3, a local fixture, not a provider): it streams two Chat Completions chunks, goes quiet for 3 seconds (optionally sending : ping comments every half second), then finishes.

python
# fake_sse_server.py: a tiny local HTTP server that streams Chat Completions chunks with a deliberate
# stall in the middle. Used by the timeout demos. Not a real provider: it only replays a fixture.
import asyncio
import json


def chunk(text: str, finish: str | None = None) -> bytes:
    body = {"id": "chatcmpl-fake", "object": "chat.completion.chunk", "created": 1, "model": "gpt-6-luna",
            "choices": [{"index": 0, "delta": {"content": text}, "finish_reason": finish}]}
    return f"data: {json.dumps(body)}\n\n".encode()


async def handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
    head = (await reader.readuntil(b"\r\n\r\n")).decode()
    length = int(next((l.split(":")[1] for l in head.split("\r\n") if l.lower().startswith("content-length")), 0))
    await reader.readexactly(length)                     # the JSON request body (ignored)
    path = head.split(" ")[1]
    stall = 3.0                                          # seconds of silence mid-stream
    pings = "pings" in path                              # /pings/v1/...: send ": ping" comments while stalled
    writer.write(b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\nconnection: close\r\n\r\n")
    try:
        for word in ["Red", " and"]:
            writer.write(chunk(word)); await writer.drain(); await asyncio.sleep(0.1)
        waited = 0.0
        while waited < stall:                            # the "model is thinking" gap
            await asyncio.sleep(0.5); waited += 0.5
            if pings:
                writer.write(b": ping\n\n"); await writer.drain()
        for word in [" blue."]:
            writer.write(chunk(word)); await writer.drain()
        writer.write(chunk("", "stop") + b"data: [DONE]\n\n"); await writer.drain()
    except (ConnectionResetError, BrokenPipeError):
        pass                                             # the client gave up: that's the point of the demo
    finally:
        writer.close()


async def serve(port: int = 8765) -> asyncio.Server:
    return await asyncio.start_server(handle, "127.0.0.1", port)

The client side tries four timeout set-ups against it, with the real openai SDK:

python
# s8_1_timeouts.py: read timeout (max gap between bytes) vs a total deadline.
# The server is a local FAKE (fake_sse_server.py): two chunks, 3 s of silence, then the rest.
import asyncio
import time

import httpx2
from openai import APITimeoutError, AsyncOpenAI

from fake_sse_server import serve


async def consume(client: AsyncOpenAI, label: str, deadline: float | None = None) -> None:
    start = time.perf_counter()
    text = ""
    try:
        async with asyncio.timeout(deadline):            # None means "no total deadline"
            stream = await client.chat.completions.create(
                model="gpt-6-luna", messages=[{"role": "user", "content": "Colours?"}], stream=True)
            async with stream:                           # closes the connection on any exit
                async for c in stream:
                    if c.choices:
                        text += c.choices[0].delta.content or ""
        outcome = "completed"
    except APITimeoutError:
        outcome = "APITimeoutError (read timeout: no bytes for too long)"
    except TimeoutError:
        outcome = "TimeoutError (our total deadline)"
    print(f"{label:<46} {time.perf_counter() - start:4.1f} s  {outcome:<52} text={text!r}")


async def main() -> None:
    server = await serve()
    # max_retries=0 so the SDK's own retry of the initial request doesn't hide what happens
    def client(path: str, read: float) -> AsyncOpenAI:
        return AsyncOpenAI(base_url=f"http://127.0.0.1:8765/{path}/v1", api_key="sk-test", max_retries=0,
                           timeout=httpx2.Timeout(30.0, read=read))
    await consume(client("plain", read=10.0), "read timeout 10 s")
    await consume(client("plain", read=1.0), "read timeout 1 s")
    await consume(client("pings", read=1.0), "read timeout 1 s, server sends pings")
    await consume(client("pings", read=1.0), "read 1 s + pings + total deadline 2 s", deadline=2.0)
    server.close()

asyncio.run(main())
Output4 lines
read timeout 10 s                               3.2 s  completed                                            text='Red and blue.'
read timeout 1 s                                1.1 s  APITimeoutError (read timeout: no bytes for too long) text='Red and'
read timeout 1 s, server sends pings            3.2 s  completed                                            text='Red and blue.'
read 1 s + pings + total deadline 2 s           2.0 s  TimeoutError (our total deadline)                    text='Red and'
  1. A 10-second read timeout survives the 3-second silence.
  2. A 1-second read timeout fires mid-stream with APITimeoutError, after the first words had arrived.
  3. The same 1-second read timeout never fires when the server sends pings, because each ping is bytes on the wire. The stream completes.
  4. Only the total deadline stops a stream that is alive but too slow.

What this means for you as an engineer: set the read timeout to a little more than the longest silence you expect for that model and setting. Fast non-reasoning chat: tens of seconds. Reasoning models with hidden thinking: minutes (Google's long-decode guide tells you to "set HTTP read timeouts to 15 to 20 minutes per stream" for its longest generations). Then add a total deadline that matches the product: what is the longest a user, or a job, should wait for this feature?

8.3 Long thinking gaps#

The silent phase of a reasoning model is where most stream timeouts in production come from, and each layer between the model and the user has its own idle limit:

Layer Idle limit Kept alive by
Provider → your server Your SDK's read timeout The provider's own keep-alives: Anthropic ping, OpenRouter comments, OpenAI background keepalive events; reasoning summary events if you request them
Proxies, load balancers For example nginx's proxy_read_timeout (default 60 s) and AWS Application Load Balancers' idle timeout (default 60 s, configurable from 1 to 4000 s), as of November 2026 Your server sending bytes to the client (heartbeats, 11.7)
Your server → browser The browser rarely times out, but every proxy in between does Heartbeats

Two practical rules follow. Request reasoning summaries when you stream to users: they give the user something to look at and keep bytes flowing (6.1). And make your own server send a heartbeat comment at least every 15 seconds, whatever the provider does; FastAPI does it for you (11.3).

8.4 Close every stream#

A stream holds an HTTP connection from the client's connection pool until it is closed (03.1, 7.5). Reading a stream to the end closes it. Stopping early does not, unless you close it:

SDK Close properly with
openai with client.responses.create(..., stream=True) as stream: (or with client.responses.stream(...)), or stream.close(); async: async with, or await stream.close()
anthropic with client.messages.stream(...) as stream: or with client.messages.create(..., stream=True) as stream:; stream.close() / await stream.close()
google-genai Interactions with client.interactions.create(..., stream=True) as stream:; stream.close() / await stream.close()
google-genai generate_content_stream A generator: run it to the end, or call .close() on it if you break out early (async: await gen.aclose()). In our test with a one-connection pool, an abandoned generator that was still referenced made the next request wait until we killed the process: with no default timeout there's nothing to stop the wait

This sample makes the leak visible by giving the client a pool of one connection, then stopping each stream after three words. Against the stand-in:

python
# s8_3_leak.py: an unclosed stream keeps its HTTP connection checked out (local model, no key)
import time

import httpx2
from openai import APITimeoutError, OpenAI

# A pool with ONE connection makes the leak visible at once. Real pools are bigger, so in
# production the same bug shows up later, under load, as mysterious timeouts.
client = OpenAI(
    base_url="http://localhost:11434/v1", api_key="ollama", max_retries=0,
    http_client=httpx2.Client(limits=httpx2.Limits(max_connections=1),
                              timeout=httpx2.Timeout(60.0, pool=2.0)),   # wait at most 2 s for a free connection
)


def first_words(close_properly: bool) -> str:
    stream = client.responses.create(model="gpt-6-luna", input="Count to twenty.", stream=True)
    words = []
    if close_properly:
        with stream:                                   # leaving the block closes the response
            for event in stream:
                if event.type == "response.output_text.delta":
                    words.append(event.delta)
                    if len(words) == 3:
                        break
    else:
        for event in stream:                           # BUG: break without closing the stream
            if event.type == "response.output_text.delta":
                words.append(event.delta)
                if len(words) == 3:
                    break
    return "".join(words)


for close_properly in (True, False):
    print(f"--- close_properly={close_properly}")
    for i in range(1, 4):
        start = time.perf_counter()
        try:
            print(f"request {i}: {first_words(close_properly)!r:<16} ({time.perf_counter() - start:.1f} s)")
        except APITimeoutError as e:
            print(f"request {i}: {type(e).__name__} after {time.perf_counter() - start:.1f} s "
                  f"(cause: {type(e.__cause__).__name__})")
Output · local model qwen2.5:0.5b via Ollama8 lines
--- close_properly=True
request 1: 'Sure! Here'     (0.2 s)
request 2: 'Sure! Let'      (0.1 s)
request 3: 'Sure! Here'     (0.1 s)
--- close_properly=False
request 1: 'Sure! Here'     (0.1 s)
request 2: APITimeoutError after 2.0 s (cause: PoolTimeout)
request 3: APITimeoutError after 2.0 s (cause: PoolTimeout)

With the with block, every request reuses the one connection. Without it, the first request's connection is never returned, and every later request waits 2 seconds for a free connection and fails with a PoolTimeout, even after the leaking function has returned and its stream variable is gone. (Python's garbage collector may eventually close it, but not when you need it.) With the default pool size the same bug shows up only under load, as unexplained timeouts, which is why it is so hard to diagnose in production.

8.5 Cancelling a stream, and what you still pay for#

Closing a stream early is how you cancel a generation: when the HTTP connection closes, the provider can stop generating. Whether it does, and what you're billed, is provider-specific, and mostly undocumented by the first-party providers:

Provider How to cancel What the docs say about billing (as of November 2026)
OpenAI Close the stream. For background responses, client.responses.cancel(id) (03.9) The background-mode guide says "To cancel a synchronous response, terminate the connection". No page states how tokens generated before the disconnect are billed
Anthropic Close the stream Not documented. There is no cancel endpoint for Messages
Gemini Close the stream. For background interactions, client.interactions.cancel(id=...) For Interactions: "Cancelled and failed interactions: You pay for all work completed before the interaction ends", and a cancelled interaction's usage shows "the billed tokens". Nothing documented for generate_content
OpenRouter Close the stream "For supported providers, this immediately stops model processing and billing." Supported includes OpenAI, Azure, Anthropic, Fireworks, DeepInfra, Together, xAI, DeepSeek and others; not supported includes AWS Bedrock, Groq, Google and Google AI Studio, Mistral and others. "For non-streaming requests or unsupported providers, the model will continue processing and you will be billed for the complete response"

What to assume in your own cost model: you pay for the input tokens of every request that reached the model, and for output generated until the provider noticed the disconnect. Cancelling stops the cost from growing; it doesn't refund what was already produced. Check your provider's usage dashboard or usage API after a test with deliberate cancellations, and treat cancellation as a cost limiter, not a refund (03.7).


Part 9: Resumable streams#

Deep-dive

A normal stream lives and dies with its HTTP connection: if the connection drops, the generation is gone (or keeps running somewhere you can't reach). Two APIs decouple the generation from the connection, so a client can reconnect to the same generation and receive only what it missed. Background mode itself (polling, cancelling, webhooks, when to use it) belongs to lesson 03.9; this part is only about re-attaching to the stream.

9.1 OpenAI: background responses with a cursor#

OpenAI's background-mode guide: "You can create a background Response and start streaming events from it right away. This may be helpful if you expect the client to drop the stream and want the option of picking it back up later. To do this, create a Response with both background and stream set to true. You will want to keep track of a 'cursor' corresponding to the sequence_number you receive in each streaming event."

sequenceDiagram
    participant App as Your code
    participant API as OpenAI Responses API
    App->>API: POST /v1/responses, background true, stream true
    API-->>App: response.created (id resp_42, seq 0)
    API-->>App: events up to seq 7
    API--xApp: connection drops
    Note over API: the response keeps running on the server
    App->>API: GET /v1/responses/resp_42?stream=true&starting_after=7
    API-->>App: events from seq 8
    API-->>App: response.completed

The rules, all from that guide (as of November 2026):

  • Both flags, at creation. "You can only start a new stream from a background response if you created it with stream=true."
  • The cursor is sequence_number. Resume with GET /v1/responses/{id}?stream=true&starting_after=N, which is client.responses.retrieve(id, stream=True, starting_after=N) in the SDK.
  • Skip keepalive events when updating the cursor: "Keepalives use connection counters, not stored-event resume positions."
  • Latency: "the time to first token you receive from a background response is higher than what you receive from a synchronous one".
  • Retention: background responses are stored so they can be polled; with store=false or Zero Data Retention, "response data is temporarily stored to disk for roughly 10 minutes" (03.2, 7.5 covers retention).

Here's the provider sample (layer 4): it simulates a dropped connection after about 60 characters, then resumes.

python
# s9_1_background_resume.py: a background response you can re-attach to after a disconnect.
# Needs OPENAI_API_KEY in .env. Background mode itself (polling, cancel, webhooks) is lesson 03.9.
from dotenv import load_dotenv
from openai import APIConnectionError, OpenAI

load_dotenv()
client = OpenAI()

text, cursor, response_id = "", -1, None
try:
    with client.responses.create(model="gpt-6-luna", input="Write four sentences about otters.",
                                 background=True, stream=True) as stream:   # both flags: resumable
        for event in stream:
            if event.type == "keepalive":             # keepalives don't advance the cursor
                continue
            cursor = event.sequence_number            # persist this somewhere durable in real code
            if event.type == "response.created":
                response_id = event.response.id
            elif event.type == "response.output_text.delta":
                text += event.delta
                if len(text) > 60:                    # simulate a dropped connection mid-answer
                    print(f"[dropping the connection after sequence_number {cursor}]")
                    break
except APIConnectionError as e:                       # a real network failure lands here
    print(f"[connection lost: {e}]")

if response_id is None:
    raise SystemExit("never got response.created: nothing to resume, start a new request")

# The response kept running on OpenAI's side. Ask only for the events after our cursor.
with client.responses.retrieve(response_id, stream=True, starting_after=cursor) as resumed:
    for event in resumed:
        if event.type == "keepalive":
            continue
        cursor = event.sequence_number
        if event.type == "response.output_text.delta":
            text += event.delta
        elif (event.type == "response.completed" or event.type == "response.incomplete"
              or event.type == "response.failed"):
            print(f"[{event.type} at sequence_number {cursor}; status={event.response.status}]")
print(text)
Example output · illustrative3 lines
[dropping the connection after sequence_number 19]
[response.completed at sequence_number 71; status=completed]
Otters are semi-aquatic mammals found on every continent except Australia and Antarctica. Sea otters hold hands while they sleep so they don't drift apart, a habit called rafting. They have the densest fur of any animal, with up to a million hairs per square inch. Many otters use stones as tools to crack open shellfish.

Against the stand-in, the first half runs (Ollama accepts background and streams), and the resume fails with openai.NotFoundError (404), because Ollama stores no responses: this one is not supported locally. The mock in the next section shows the reconnect logic working end to end.

9.2 Try it: resume after a dropped connection#

A mock server (layer 3) whose first stream breaks after sequence_number 7, and which replays stored events on GET. It shows the two SDK ways to resume:

python
# s9_1b_resume_mock.py: resume a background response after the connection drops.
# MOCK server: POST /responses streams events 0-5 and then breaks the connection; GET
# /responses/{id}?stream=true&starting_after=N replays the stored events after N.
import json

import httpx2
from openai import APIConnectionError, OpenAI

TEXT = ["Otters ", "hold ", "hands ", "while ", "they ", "sleep."]
RESP = {"id": "resp_42", "object": "response", "created_at": 1, "model": "gpt-6-luna", "output": [],
        "parallel_tool_calls": True, "tool_choice": "auto", "tools": [], "background": True}
PART = {"type": "output_text", "text": "", "annotations": [], "logprobs": []}
DONE_ITEM = {"id": "msg_1", "type": "message", "role": "assistant", "status": "completed",
             "content": [{**PART, "text": "".join(TEXT)}]}
EVENTS = ([{"type": "response.created", "response": {**RESP, "status": "queued"}},
           {"type": "response.in_progress", "response": {**RESP, "status": "in_progress"}},
           {"type": "response.output_item.added", "output_index": 0,
            "item": {**DONE_ITEM, "status": "in_progress", "content": []}},
           {"type": "response.content_part.added", "item_id": "msg_1", "output_index": 0, "content_index": 0,
            "part": PART}]
          + [{"type": "response.output_text.delta", "item_id": "msg_1", "output_index": 0, "content_index": 0,
              "delta": t, "logprobs": []} for t in TEXT]
          + [{"type": "response.output_text.done", "item_id": "msg_1", "output_index": 0, "content_index": 0,
              "text": "".join(TEXT), "logprobs": []},
             {"type": "response.output_item.done", "output_index": 0, "item": DONE_ITEM},
             {"type": "response.completed", "response": {**RESP, "status": "completed", "output": [DONE_ITEM],
              "usage": {"input_tokens": 12, "output_tokens": 6, "total_tokens": 18,
                        "input_tokens_details": {"cached_tokens": 0},
                        "output_tokens_details": {"reasoning_tokens": 0}}}}])
for n, e in enumerate(EVENTS):
    e["sequence_number"] = n


def sse(events: list[dict]) -> bytes:
    return b"".join(f"event: {e['type']}\ndata: {json.dumps(e)}\n\n".encode() for e in events)


class DroppedConnection(httpx2.SyncByteStream):
    """Sends some bytes, then fails like a network cut would."""
    def __init__(self, body: bytes) -> None:
        self.body = body

    def __iter__(self):
        yield self.body
        raise httpx2.ReadError("connection reset by peer")


def handler(request: httpx2.Request) -> httpx2.Response:
    print(f"  server: {request.method} {request.url.path}?{request.url.query.decode()}")
    headers = {"content-type": "text/event-stream"}
    if request.method == "POST":                          # the first stream dies after event #7
        return httpx2.Response(200, headers=headers, stream=DroppedConnection(sse(EVENTS[:8])))
    after = int(request.url.params.get("starting_after", -1))
    keepalive = {"type": "keepalive", "sequence_number": 0}   # background streams can include these
    return httpx2.Response(200, headers=headers, content=sse(EVENTS[after + 1:after + 2] + [keepalive] + EVENTS[after + 2:]))


client = OpenAI(api_key="sk-test", max_retries=0,
                http_client=httpx2.Client(transport=httpx2.MockTransport(handler)))

text, cursor, response_id = "", -1, None
try:
    with client.responses.create(model="gpt-6-luna", input="Tell me an otter fact.",
                                 background=True, stream=True) as stream:
        for event in stream:
            cursor = event.sequence_number              # remember how far we got
            if event.type == "response.created":
                response_id = event.response.id
            elif event.type == "response.output_text.delta":
                text += event.delta
except APIConnectionError as e:
    print(f"  client: {type(e).__name__} after sequence_number {cursor}; text so far {text!r}")

assert response_id is not None
seen_text, seen_cursor = text, cursor

# Option 1: ask the server for only the events after the cursor, and keep accumulating yourself
with client.responses.retrieve(response_id, stream=True, starting_after=cursor) as resumed:
    for event in resumed:
        if event.type == "keepalive":                    # not a stored event: don't move the cursor
            continue
        cursor = event.sequence_number
        if event.type == "response.output_text.delta":
            text += event.delta
print(f"  option 1 final text: {text!r} (cursor now {cursor})")

# Option 2: the helper replays the WHOLE stream to rebuild its snapshot, and yields only new events
with client.responses.stream(response_id=response_id, starting_after=seen_cursor) as resumed:
    new = [e.delta for e in resumed if e.type == "response.output_text.delta"]
    final = resumed.get_final_response()
print(f"  option 2 new deltas: {new} | get_final_response().output_text={final.output_text!r}")
Output6 lines
  server: POST /v1/responses?
  client: APIConnectionError after sequence_number 7; text so far 'Otters hold hands while '
  server: GET /v1/responses/resp_42?starting_after=7&stream=true
  option 1 final text: 'Otters hold hands while they sleep.' (cursor now 12)
  server: GET /v1/responses/resp_42?stream=true
  option 2 new deltas: ['they ', 'sleep.'] | get_final_response().output_text='Otters hold hands while they sleep.'

The two options behave differently, and the SDK source explains why:

client.responses.retrieve(id, stream=True, starting_after=N) client.responses.stream(response_id=id, starting_after=N)
What it requests Only the events after N (starting_after=7 is sent) The whole stream from the start (no starting_after on the wire)
What it yields Raw events after N Helper events after N: it filters locally, after rebuilding its snapshot from every event
Final object None: keep accumulating with your own accumulator (5.3), the same one you used before the drop (see below) get_final_response() works, because the helper saw everything
Cost Least data Re-downloads everything already received

Both deliver exactly the missing text, with no duplicates. Pick retrieve when you already have your own accumulator, and the helper when you want the final Response object.

9.3 Gemini Interactions: last_event_id#

Interactions created with background=True keep running on Google's side and can be streamed again: "If a network interruption disconnects a stream, streaming can resume from the last received event. Each delta contains a unique event_id in its payload. Passing this ID as last_event_id resumes the stream from that event." In the SDK that's client.interactions.get(id=..., stream=True, last_event_id=...).

From Google's background-execution and long-decode guides:

  • Save the interaction ID from interaction.created, and every event_id: one "can arrive on interaction.status_update events, not only on text deltas".
  • Read to the end after reconnecting, before checking the status: "The server replays missed events, even after the interaction completes."
  • Background interactions need store (the default); store=false "can't be combined with background".
  • Long streams pause at checkpoints ("After the first 32K tokens, the stream sends output in chunks of about 5,000 tokens at each checkpoint. Pauses between chunks are normal"), which is another reason for generous read timeouts.

The provider sample (layer 4):

python
# s9_2_interactions_resume.py: resume a background Interactions stream from the last event_id.
# Needs GEMINI_API_KEY in .env.
from dotenv import load_dotenv
from google import genai

load_dotenv()
client = genai.Client()

text, last_event_id, interaction_id = "", None, None
stream = client.interactions.create(model="gemini-3.8-flash", input="Write four sentences about otters.",
                                    background=True, stream=True)    # background needs store (the default)
with stream:
    for event in stream:
        event_id = getattr(event, "event_id", None)  # resume tokens arrive on many event types
        if event_id:
            last_event_id = event_id
        if event.event_type == "interaction.created":
            interaction_id = event.interaction.id
        elif event.event_type == "step.delta" and event.delta.type == "text":
            text += event.delta.text
            if len(text) > 60:
                print(f"[dropping the connection; last_event_id saved: {last_event_id is not None}]")
                break

assert interaction_id is not None
with client.interactions.get(id=interaction_id, stream=True, last_event_id=last_event_id) as resumed:
    for event in resumed:                           # read to the end before checking the status
        if event.event_type == "step.delta" and event.delta.type == "text":
            text += event.delta.text
        elif event.event_type == "interaction.completed":
            print(f"[completed: status={event.interaction.status}]")
print(text)
Example output · illustrative3 lines
[dropping the connection; last_event_id saved: True]
[completed: status=completed]
Otters are playful, semi-aquatic mammals in the weasel family. Sea otters often float on their backs and hold paws while sleeping so they don't drift apart. Their extremely dense fur traps air and keeps them warm in cold water. Some otters even use rocks as tools to open shells.

9.4 Everyone else: no resume#

API Resumable? What to do instead
OpenAI Responses (normal) No Restart, or create with background=True, stream=True if resumption matters
OpenAI Chat Completions No Restart or continue (7.5)
Anthropic Messages No: there's no stored stream to reconnect to Restart, or continue from the partial text, as Anthropic's error-recovery guidance describes
Gemini generate_content Only through the SDK's automatic continuation, for long generations (continuation_token; 4.5b). There is no cursor you can hold or reconnect with yourself For anything else, restart or continue, or use Interactions in background mode
OpenRouter (all three endpoints) No: its Responses API is stateless (store: true gets a 400) Restart or continue

Resumable streams and your own resumable SSE endpoint are different things: the browser's EventSource sends Last-Event-ID when it reconnects to your server (11.5), and your server can honour it only if it buffered the events, or if the upstream provider itself is resumable as above.


Part 10: Async streaming#

Deep-dive

A web server that streams to many users at once can't block a thread per stream while it waits for the next event. Async clients let one process wait on hundreds of streams. Lesson 03.9 owns async clients in general and bounded concurrency (semaphores, rate-aware throughput); this part covers what is specific to streams.

10.1 The async form of each SDK#

SDK Raw stream Helper Close
openai stream = await client.responses.create(..., stream=True), then async for event in stream async with client.responses.stream(...) as stream: async with stream: or await stream.close()
anthropic stream = await client.messages.create(..., stream=True) async with client.messages.stream(...) as stream: then async for text in stream.text_stream The same
google-genai async for chunk in await client.aio.models.generate_content_stream(...) (note the await) chat = client.aio.chats.create(...); async for chunk in await chat.send_message_stream(...) await gen.aclose() if you stop early; await client.aio.aclose() when done with the client
google-genai Interactions stream = await client.aio.interactions.create(..., stream=True) — async with stream:
OpenRouter As openai, with AsyncOpenAI(base_url="https://openrouter.ai/api/v1", ...) As openai As openai

The OpenAI and Anthropic forms, streaming at once against the stand-in:

python
# s10_1_async_all.py: the async streaming form of the OpenAI and Anthropic SDKs, both running at once (local stand-in)
import asyncio
import time

import anthropic
from openai import AsyncOpenAI

PROMPT = "Name one primary colour. One word."
openai_client = AsyncOpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
claude = anthropic.AsyncAnthropic(base_url="http://localhost:11434", api_key="ollama")
START = time.perf_counter()


def log(label: str, text: str) -> None:
    print(f"{time.perf_counter() - START:5.2f} s  {label:<22} {text!r}")


async def openai_responses() -> None:
    stream = await openai_client.responses.create(model="gpt-6-luna", input=PROMPT, stream=True,
                                                  max_output_tokens=8)
    async with stream:
        async for event in stream:
            if event.type == "response.output_text.delta":
                log("openai responses", event.delta)


async def anthropic_messages() -> None:
    async with claude.messages.stream(model="claude-haiku-5-5", max_tokens=8,
                                      messages=[{"role": "user", "content": PROMPT}]) as stream:
        async for text in stream.text_stream:
            log("anthropic", text)


async def main() -> None:
    async with asyncio.TaskGroup() as tg:             # like Promise.all, but cancels siblings on failure
        for coro in (openai_responses(), anthropic_messages()):
            tg.create_task(coro)
    await openai_client.close(); await claude.close()

asyncio.run(main())

Output (local model qwen2.5:0.5b via Ollama; illustrative: carried over from a run that also had Gemini tasks, not re-measured, so timings and interleaving will differ; a hosted run interleaves according to each provider's speed):

text
 0.31 s  openai responses       'Red'
 0.32 s  anthropic              'Red'
 0.42 s  anthropic              '.'

The two Gemini forms follow the same pattern, in a TaskGroup of their own. They are hosted-only, because Gemini has no local stand-in:

python
# s10_1_async_gemini.py: the async streaming forms of google-genai (hosted Gemini API)
import asyncio

from google import genai
from google.genai import types

PROMPT = "Name one primary colour. One word."
gemini = genai.Client()     # reads GEMINI_API_KEY from the environment


async def gemini_generate_content() -> None:
    # note the `await` before the call: it returns an async iterator
    async for chunk in await gemini.aio.models.generate_content_stream(
            model="gemini-3.8-flash", contents=PROMPT,
            config=types.GenerateContentConfig(max_output_tokens=8)):
        if chunk.text:
            print("gemini generate", repr(chunk.text))


async def gemini_interactions() -> None:
    stream = await gemini.aio.interactions.create(model="gemini-3.8-flash", input=PROMPT, stream=True,
                                                  generation_config={"max_output_tokens": 8})
    async with stream:
        async for event in stream:
            if event.event_type == "step.delta" and event.delta.type == "text":
                print("gemini interactions", repr(event.delta.text))


async def main() -> None:
    async with asyncio.TaskGroup() as tg:
        for coro in (gemini_generate_content(), gemini_interactions()):
            tg.create_task(coro)
    await gemini.aio.aclose()

asyncio.run(main())

10.2 Several streams at once#

Common reasons to run streams concurrently: comparing models side by side, answering several sub-questions in parallel, or streaming a draft from a fast model while a slower one works. The pattern is a fan-in: each stream task puts its events on one asyncio.Queue, and one consumer reads them in arrival order:

python
# s10_2_three_prompts.py: stream three prompts at once and merge their events (local model, no key)
import asyncio
import time

from openai import AsyncOpenAI

PROMPTS = {"A": "List three fruits.", "B": "List three planets.", "C": "List three metals."}


async def stream_one(client: AsyncOpenAI, label: str, prompt: str, out: asyncio.Queue) -> None:
    start = time.perf_counter()
    stream = await client.responses.create(model="gpt-6-luna", input=prompt, stream=True, max_output_tokens=6)
    async with stream:
        async for event in stream:
            if event.type == "response.output_text.delta":
                await out.put((label, event.delta))
            elif event.type == "response.completed":
                usage = event.response.usage
                await out.put((label, f"[done in {time.perf_counter() - start:.2f} s, "
                                      f"{usage.output_tokens if usage else '?'} tokens]"))


async def main() -> None:
    queue: asyncio.Queue = asyncio.Queue()             # one place where all streams' events land, in arrival order
    async with AsyncOpenAI(base_url="http://localhost:11434/v1", api_key="ollama") as client:
        start = time.perf_counter()
        async with asyncio.TaskGroup() as tg:
            for label, prompt in PROMPTS.items():
                tg.create_task(stream_one(client, label, prompt, queue))
            # drain the queue while the tasks run; stop when all three said "done"
            done = 0
            while done < len(PROMPTS):
                label, text = await queue.get()
                done += text.startswith("[done")
                print(f"{time.perf_counter() - start:5.2f} s  {label}: {text!r}")
        print(f"all three finished in {time.perf_counter() - start:.2f} s")

asyncio.run(main())

Output (local model qwen2.5:0.5b via Ollama; illustrative: carried over from a run that also had Gemini tasks, not re-measured, so timings and interleaving will differ):

text
 0.21 s  B: 'Sure'
 0.21 s  B: '!'
 0.21 s  B: ' Here'
 0.21 s  B: ' are'
 0.21 s  B: ' the'
 0.21 s  B: ' names'
 0.31 s  B: '[done in 0.29 s, 6 tokens]'
 0.31 s  A: 'Sure'
 0.31 s  A: '!'
 0.31 s  A: ' Here'
 0.31 s  A: "'s"
 0.31 s  A: ' my'
 0.31 s  A: ' answer'
 0.31 s  A: '[done in 0.31 s, 6 tokens]'
 0.31 s  C: 'Three'
 0.31 s  C: ' common'
 0.31 s  C: ' metals'
 0.31 s  C: ' are'
 0.31 s  C: ' copper'
 0.31 s  C: ','
 0.31 s  C: '[done in 0.29 s, 6 tokens]'
all three finished in 0.31 s

The three requests ran together and all finished in about the time of one. On this tiny local model each answer is produced almost instantly, so they arrive one after another; against hosted APIs, events from the three streams interleave over the seconds each answer takes. Either way the consumer doesn't care: every event is labelled with its stream.

What this means for you as an engineer:

  • Label every event with its stream ("A", a request ID, a model name), and finish only when every stream has reported done or failed.
  • Bound the concurrency. Three streams is fine; three hundred from one user is a rate-limit incident. Use a semaphore or a per-user limit (03.9, and 11.4 for a per-user cap on an endpoint).
  • Never block the event loop inside a stream loop. A synchronous call (a sync SDK client, time.sleep, a slow database write) inside async for freezes every stream in the process. Use the async clients throughout, and await asyncio.to_thread(...) for unavoidable blocking work.

Part 11: Streaming to a browser#

Deep-dive

Most streams end up on a screen. This part builds the whole path: a FastAPI endpoint that streams from a provider, your own event protocol, a minimal browser page, disconnect handling that stops the provider, and the production concerns that decide whether any of it works behind real infrastructure. How the streamed answer should look and feel (typing effects, scroll behaviour, failure states) is UX design, covered in Module 13A.

11.1 The architecture: the key stays on your server#

flowchart LR
    subgraph client ["Browser"]
        UI["Page: fetch() + ReadableStream<br/>parses your SSE events"]
    end
    subgraph server ["Your backend (FastAPI)"]
        AUTH["Auth + per-user limit<br/>(before the stream starts)"] --> GEN["SSE generator<br/>maps provider events to your events"]
        GEN --> LOG["Usage and outcome log"]
    end
    subgraph provider ["Provider"]
        LLM["Streaming API"]
    end
    UI -- "POST /chat/stream<br/>Authorization header" --> AUTH
    GEN -- "SDK stream, API key" --> LLM
    LLM -- "provider events" --> GEN
    GEN -- "delta, usage, error, done" --> UI

The browser never talks to the provider. It calls your endpoint with your authentication; your server holds the API key, calls the provider, and relays a cleaned-up stream. Lesson 03.1, 3.5 explains why a key in front-end code is a key published to the world. Your server in the middle is also where everything else on this page lives: authentication, per-user limits, logging usage, mapping provider events to your own protocol, and stopping the provider when the user leaves.

11.2 Design your own event protocol#

Don't forward provider events to the browser. If your front end parses response.output_text.delta, switching to Claude means rewriting the front end; if it parses Anthropic's events, it must also understand ping, signatures and cumulative usage. Define a small protocol of your own, named SSE events with JSON data, and translate on the server:

Event Data Sent when
delta {"text": "..."} Answer text arrives
reasoning {"text": "..."} A reasoning summary arrives (optional: only if you show it)
tool {"name": "...", "arguments": "..."} A tool call is complete (or {"name"} alone when it starts, to show progress)
usage {"input_tokens": n, "output_tokens": n} The provider reported usage. You may choose not to expose it to end users
reset {"reason": "..."} The client must clear the partial answer (a restart or refusal, 7.5)
error {"message": "...", "retryable": true} Something failed. A safe message: never provider internals, keys or stack traces
done {"status": "completed", "reason": null} The stream finished; the client can enable "send" again

Give every event an id (an increasing number) so a client can tell you where it got to, and version the protocol (a v field or a path like /v1/chat/stream) before you have users on two app versions. The protocol is the contract between your back end and front end; 03.11 builds the provider side of it as a reusable layer.

11.3 Serving SSE from FastAPI#

FastAPI has built-in SSE support: "Added in FastAPI 0.135.0", verified here on 0.162.0. You import EventSourceResponse and ServerSentEvent from fastapi.sse, set response_class=EventSourceResponse on a path operation, and yield items. The documented behaviour, all confirmed against the 0.162.0 source:

Feature Behaviour
ServerSentEvent(data=...) data "is always encoded as JSON", Pydantic models included
ServerSentEvent(raw_data=...) Sent as-is, "useful for sending pre-formatted text, log lines, or special 'sentinel' values like [DONE]". data and raw_data "are mutually exclusive"
event=, id=, retry=, comment= The SSE fields. id and event must be single lines; retry is milliseconds
Yielding a plain object (dict, model) Sent as a JSON data: field with no event name
Keep-alive A : ping comment "every 15 seconds when there hasn't been any message" (_PING_INTERVAL = 15.0 in the source)
Headers Cache-Control: no-cache and X-Accel-Buffering: no, set for you
Methods "SSE works with any HTTP method, not just GET", so POST bodies work
Last-Event-ID Read it as a Header() parameter; resuming is up to your code

This layer-1 sample serves the same small stream three ways, FastAPI native, plain StreamingResponse, and sse-starlette 3.6.0, and prints exactly what each puts on the wire. httpx's ASGITransport calls the apps in-process, with no network:

python
# s11_3_sse_servers.py: what three ways of serving SSE from Python put on the wire (no network:
# httpx's ASGITransport calls the apps in-process).
import asyncio
from collections.abc import AsyncIterator

import httpx
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from fastapi.sse import EventSourceResponse, ServerSentEvent
from sse_starlette import EventSourceResponse as StarletteSSE

app = FastAPI()


@app.get("/native", response_class=EventSourceResponse)        # FastAPI >= 0.135
async def native() -> AsyncIterator[ServerSentEvent]:
    yield ServerSentEvent(comment="stream opened")
    yield ServerSentEvent(data={"text": "Hi"}, event="delta", id="1", retry=3000)   # data -> JSON
    await asyncio.sleep(15.5)                                    # idle long enough for an automatic ping
    yield ServerSentEvent(data="two\nlines", event="delta", id="2")          # JSON: the newline is escaped
    yield ServerSentEvent(raw_data="two\nlines", event="note")               # raw: one data: line per line
    yield ServerSentEvent(raw_data="[DONE]", event="done")      # raw_data is sent as-is


@app.get("/plain")
async def plain() -> StreamingResponse:
    async def body() -> AsyncIterator[str]:                     # you format every byte yourself
        yield 'event: delta\nid: 1\ndata: {"text": "Hi"}\n\n'
        yield "data: [DONE]\n\n"
    return StreamingResponse(body(), media_type="text/event-stream",
                             headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})


@app.get("/sse-starlette")
async def starlette_sse() -> StarletteSSE:
    async def body() -> AsyncIterator[dict]:
        yield {"event": "delta", "id": "1", "data": '{"text": "Hi"}'}   # data must already be a string
        yield {"data": "[DONE]"}
    return StarletteSSE(body(), ping=15)


async def main() -> None:
    async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as client:
        for path in ("/native", "/plain", "/sse-starlette"):
            r = await client.get(path)
            headers = {k: v for k, v in r.headers.items() if k in ("content-type", "cache-control",
                                                                   "x-accel-buffering", "connection")}
            print(f"===== {path}  {headers}")
            print(r.text.replace("\r\n", "␍␊\n"), end="")           # make CRLF line endings visible

asyncio.run(main())

Output (it takes about 16 seconds, because the native endpoint idles long enough to trigger a real ping):

text
===== /native  {'content-type': 'text/event-stream; charset=utf-8', 'cache-control': 'no-cache', 'x-accel-buffering': 'no'}
: stream opened

event: delta
data: {"text": "Hi"}
id: 1
retry: 3000

: ping

event: delta
data: "two\nlines"
id: 2

event: note
data: two
data: lines

event: done
data: [DONE]

===== /plain  {'cache-control': 'no-cache', 'x-accel-buffering': 'no', 'content-type': 'text/event-stream; charset=utf-8'}
event: delta
id: 1
data: {"text": "Hi"}

data: [DONE]

===== /sse-starlette  {'cache-control': 'no-store', 'connection': 'keep-alive', 'x-accel-buffering': 'no', 'content-type': 'text/event-stream; charset=utf-8'}
id: 1␍␊
event: delta␍␊
data: {"text": "Hi"}␍␊
␍␊
data: [DONE]␍␊
␍␊
FastAPI native (fastapi.sse) StreamingResponse sse-starlette 3.6.0
Formatting Done for you; data JSON-encoded, raw_data split into one data: line per line You write every byte Done for you; data must already be a string
Line endings LF Whatever you write CRLF by default (sep= changes it)
Keep-alive : ping after 15 s idle None: you add it Ping every 15 s by default (ping=)
Headers Cache-Control: no-cache, X-Accel-Buffering: no Only what you set Cache-Control: no-store, Connection: keep-alive, X-Accel-Buffering: no
Disconnect handling The generator is cancelled (11.6) Starlette's default behaviour Detects disconnects and cancels the generator; extra hooks (client_close_handler_callable, send_timeout, shutdown handling)
Best for New FastAPI apps Full control, or non-FastAPI Starlette code Older FastAPI versions, or its extra hooks

11.4 The streaming endpoint#

The full app: a POST endpoint that authenticates the user, caps their concurrent streams, streams from the provider with AsyncOpenAI (the Responses API, pointed at the stand-in through OPENAI_BASE_URL), translates events into the protocol of 11.2, cancels the provider stream if the client disconnects, and logs one line with the outcome and usage for every request. It also serves the page of 11.5.

python
# chat_app.py: stream an LLM answer to a browser over SSE, with your own event protocol.
# Run: OPENAI_BASE_URL=http://localhost:11434/v1 OPENAI_API_KEY=ollama uv run uvicorn chat_app:app
import asyncio
import logging
import os
import time
from collections import defaultdict
from collections.abc import AsyncIterator
from pathlib import Path
from typing import Annotated

from fastapi import Depends, FastAPI, Header, HTTPException
from fastapi.responses import HTMLResponse
from fastapi.sse import EventSourceResponse, ServerSentEvent
from openai import APIError, AsyncOpenAI
from pydantic import BaseModel, Field

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
log = logging.getLogger("chat")

app = FastAPI()
llm = AsyncOpenAI()            # one client for the whole app; the key stays on the server
MODEL = os.environ.get("CHAT_MODEL", "gpt-6-luna")
# Demo auth: map bearer tokens to user IDs. Use your real session or JWT check here.
TOKENS = {"demo-token-alice": "alice", "demo-token-bob": "bob"}
MAX_STREAMS_PER_USER = 2
active_streams: dict[str, int] = defaultdict(int)   # per process; use Redis or similar across workers


class ChatRequest(BaseModel):
    message: str = Field(min_length=1, max_length=4_000)


def current_user(authorization: Annotated[str | None, Header()] = None) -> str:
    """Runs BEFORE the stream starts, so failures are real HTTP 401s, not events inside a 200."""
    token = (authorization or "").removeprefix("Bearer ").strip()
    if token not in TOKENS:
        raise HTTPException(401, "missing or invalid token")
    return TOKENS[token]


async def stream_slot(user: Annotated[str, Depends(current_user)]) -> AsyncIterator[str]:
    """Caps concurrent streams per user. The code after `yield` runs when the stream has ended."""
    if active_streams[user] >= MAX_STREAMS_PER_USER:
        raise HTTPException(429, "too many open streams", headers={"Retry-After": "5"})
    active_streams[user] += 1
    try:
        yield user
    finally:
        active_streams[user] -= 1


@app.get("/", response_class=HTMLResponse)
async def page() -> str:
    return (Path(__file__).parent / "page.html").read_text()


@app.post("/chat/stream", response_class=EventSourceResponse)
async def chat_stream(body: ChatRequest, user: Annotated[str, Depends(stream_slot)]
                      ) -> AsyncIterator[ServerSentEvent]:
    seq = 0

    def event(kind: str, **data) -> ServerSentEvent:
        nonlocal seq
        seq += 1                                   # an id per event, in case you add resume later
        return ServerSentEvent(event=kind, data=data, id=str(seq))

    start, deltas, usage = time.perf_counter(), 0, None
    outcome, response_id, terminal_seen = "unknown", None, False
    try:
        stream = await llm.responses.create(model=MODEL, input=body.message, max_output_tokens=300,
                                            stream=True)
        async with stream:                         # leaving this block closes the upstream connection
            async for ev in stream:
                if ev.type == "response.created":
                    response_id = ev.response.id   # for the log line: a support ticket needs this ID
                elif ev.type == "response.output_text.delta":
                    deltas += 1
                    yield event("delta", text=ev.delta)
                elif ev.type == "response.reasoning_summary_text.delta":
                    yield event("reasoning", text=ev.delta)
                elif ev.type == "response.output_item.done" and ev.item.type == "function_call":
                    yield event("tool", name=ev.item.name, arguments=ev.item.arguments)
                elif ev.type in ("response.completed", "response.incomplete", "response.failed"):
                    terminal_seen = True
                    r = ev.response
                    if r.usage:
                        usage = {"input_tokens": r.usage.input_tokens, "output_tokens": r.usage.output_tokens}
                        yield event("usage", **usage)
                    if ev.type == "response.failed":
                        outcome = "failed"
                        yield event("error", message="The model failed to answer.", retryable=True)
                    else:
                        outcome = r.status
                        reason = r.incomplete_details.reason if r.incomplete_details else None
                        yield event("done", status=r.status, reason=reason)
                elif ev.type == "error":
                    outcome = "error"
                    yield event("error", message="The model stream failed.", retryable=True)
        if not terminal_seen and outcome == "unknown":   # the body ended with no terminal event (7.3, case 7)
            outcome = "interrupted"
            yield event("error", message="The answer was cut off.", retryable=True)
    except asyncio.CancelledError:
        outcome = "client disconnected"            # the browser went away: stop paying for tokens
        log.warning("user=%s disconnected after %d deltas; upstream stream closed", user, deltas)
        raise                                      # always re-raise CancelledError
    except APIError as e:
        outcome = "upstream error"
        log.error("user=%s upstream error: %s", user, e)
        yield event("error", message="The model service is unavailable.", retryable=True)  # no internals
    finally:
        # Log usage once per request. Unknown is not zero: a cut stream may have been billed anyway.
        log.info("user=%s response_id=%s outcome=%s seconds=%.2f deltas=%d usage=%s", user, response_id, outcome,
                 time.perf_counter() - start, deltas, usage or "unknown")

The design decisions, one by one:

  • Auth and limits are dependencies, not code inside the generator. By the time the generator body runs, the 200 OK and text/event-stream headers may already be on their way, so an error there can only be an error event. current_user and stream_slot run before the response starts, so a bad token is a real 401 and an over-limit user a real 429 with Retry-After, which the browser can handle with a plain status check.
  • stream_slot holds the slot for the whole stream. In FastAPI 0.162.0, a dependency's code after yield runs when the streaming response has finished (the SSE machinery is tied to the request's exit stack, as its source comments explain), so finally: active_streams[user] -= 1 releases the slot when the stream ends, fails or is cancelled.
  • async with stream: is what closes the provider connection on every exit path, including cancellation.
  • except asyncio.CancelledError: ... raise. When the client disconnects, the server cancels the generator; the CancelledError passes through async with (closing the upstream stream) into our handler, which logs and re-raises. Swallowing CancelledError breaks cancellation for everything above you.
  • Errors become safe events. A provider APIError mid-stream is logged with details on the server and sent to the client as a generic message.
  • The finally logs exactly once per request, with usage=unknown when the stream never reported it (7.6). 03.7 turns these lines into costs once the counts are converted to its convention (here input_tokens is OpenAI's own field, which includes cached tokens; see 3.1); 03.10 covers structured logging.
  • It notices a stream that just ends. terminal_seen is set only by response.completed, .incomplete or .failed. If the loop finishes without one, the outcome is interrupted and the client gets a retryable error event instead of silence (7.3, case 7: a proxy closing the connection otherwise looks like a short answer).
  • The log line carries the provider's response ID (from response.created), so a support ticket or a provider's dashboard can find the exact request (03.8 covers request IDs).
  • One client for the app. llm = AsyncOpenAI() is created once at import and shared by every request (03.1, 7.5).

11.5 The browser side: EventSource vs fetch()#

Browsers have a built-in SSE client, EventSource, and it is the wrong tool for most LLM endpoints:

EventSource fetch() + ReadableStream
HTTP method GET only Any (POST with a JSON body)
Custom headers (Authorization) None. Only cookies, and cross-origin cookies only with withCredentials: true Any
Request body None: everything goes in the URL JSON body
Parsing Built in, spec-compliant Yours (a few lines, or a library such as eventsource-parser)
Reconnect Automatic, sending Last-Event-ID; a server can stop it with HTTP 204 Yours to write, if you want it
Non-200 or wrong Content-Type The spec says the browser must "fail the connection": you get an error event with no status code or body You read response.status and the error body
Cancel source.close() AbortController.abort()
Connection limit over HTTP/1.1 MDN: "the limit is per browser and set to a very low number (6)" per domain, across all tabs The same per-domain limit applies to every HTTP/1.1 request, so serve streams over HTTP/2

The page served by chat_app.py, about 30 lines of HTML and JavaScript (the one non-Python listing in this module). It POSTs with a bearer token, reads the body as a stream, splits it into events at blank lines, and handles three of our event types; the Stop button aborts the request, which is what triggers the server-side cancellation of 11.6:

html
<!doctype html><meta charset="utf-8"><title>Streaming chat</title>
<textarea id="q">Why is the sky blue? Two sentences.</textarea>
<button id="go">Ask</button> <button id="stop">Stop</button> <pre id="out"></pre>
<script>
let controller;                                   // lets the Stop button abort the request
go.onclick = async () => {
  controller = new AbortController(); out.textContent = "";
  const res = await fetch("/chat/stream", {       // POST + headers: two things EventSource can't do
    method: "POST", signal: controller.signal,
    // DEMO ONLY: a real app gets this token from your login session, never a hard-coded string
    headers: {"Content-Type": "application/json", "Authorization": "Bearer demo-token-alice"},
    body: JSON.stringify({message: q.value}),
  });
  if (!res.ok) { out.textContent = `HTTP ${res.status}`; return; }   // 401, 429... before any event
  const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
  let buf = "";
  for (;;) {
    const {value, done} = await reader.read(); if (done) break;
    buf += value.replaceAll("\r\n", "\n");
    for (let i; (i = buf.indexOf("\n\n")) >= 0; buf = buf.slice(i + 2)) {   // blank line = end of event
      let type = "message", data = "";
      for (const line of buf.slice(0, i).split("\n")) {   // ":" lines (pings) match neither branch
        if (line.startsWith("event:")) type = line.slice(6).trim();
        else if (line.startsWith("data:")) data += line.slice(5).trim();  // our server sends one JSON line
      }
      if (!data) continue;
      const msg = JSON.parse(data);
      if (type === "delta") out.textContent += msg.text;
      else if (type === "error") out.textContent += `\n[error: ${msg.message}]`;
      else if (type === "done") out.textContent += `\n[${msg.status}]`;
    }
  }
};
stop.onclick = () => controller?.abort();         // drops the connection; the server cancels upstream
</script>

Note the comment above the Authorization header: the hard-coded token is demo only, exactly the pattern 11.1 warns against. A real page gets a short-lived token or a session cookie from your login flow, never a string in the source.

Run it with OPENAI_BASE_URL=http://localhost:11434/v1 OPENAI_API_KEY=ollama uv run uvicorn chat_app:app --port 8001 from the folder holding chat_app.py and page.html, and open http://127.0.0.1:8001/. (Against a hosted provider, drop the two variables and keep your real key in .env, loaded with load_dotenv() at the top of chat_app.py.)

11.6 Try it: drive the endpoint, then disconnect#

The cancellation chain this section proves:

sequenceDiagram
    participant B as Browser
    participant S as Your FastAPI app
    participant P as Provider
    B->>S: POST /chat/stream
    S->>P: stream request
    P-->>S: deltas
    S-->>B: event delta ...
    B--xS: user presses Stop, connection closed
    Note over S: the server notices the disconnect, the generator gets CancelledError
    S->>P: leaving async with closes the upstream connection
    Note over P: generation stops (billing for tokens already made is provider-specific)
    S->>S: log outcome = client disconnected, usage = unknown

This test starts the real app under uvicorn (pointed at the local model), then acts as four browsers using httpx.AsyncClient and the SSE parser from 2.5: no token; a full stream; a stream it abandons after three deltas, exactly like a user pressing Stop; and three simultaneous streams for one user. At the end it prints the server's log.

python
# s11_6_client_test.py: drive chat_app.py like a browser would, with httpx.AsyncClient.
# It starts the real app (uvicorn) against the local model, then reads its server log.
import asyncio
import os
import subprocess
import sys
import time

import httpx

from sse import SSEParser

BASE = "http://127.0.0.1:8001"
AUTH = {"Authorization": "Bearer demo-token-alice"}


async def read_events(client: httpx.AsyncClient, message: str, stop_after_deltas: int | None = None) -> None:
    parser = SSEParser()
    deltas = 0
    async with client.stream("POST", f"{BASE}/chat/stream", json={"message": message}, headers=AUTH) as r:
        print(f"HTTP {r.status_code} {r.headers['content-type']} | cache-control={r.headers.get('cache-control')}"
              f" | x-accel-buffering={r.headers.get('x-accel-buffering')}")
        async for chunk in r.aiter_bytes():
            for ev in parser.feed(chunk):
                print(f"  id={ev.id:<3} event={ev.event:<6} data={ev.data}")
                deltas += ev.event == "delta"
                if stop_after_deltas and deltas >= stop_after_deltas:
                    print("  -- client closes the connection --")
                    return                              # leaving `async with` drops the connection


async def main() -> None:
    async with httpx.AsyncClient(timeout=httpx.Timeout(10.0, read=60.0)) as client:
        print("1. no token:")
        r = await client.post(f"{BASE}/chat/stream", json={"message": "hi"})
        print(f"HTTP {r.status_code} {r.json()}")
        print("2. a full stream:")
        await read_events(client, "Name two primary colours. One short sentence.")
        print("3. disconnect after 3 deltas:")
        await read_events(client, "Count slowly from one to fifty in words.", stop_after_deltas=3)
        await asyncio.sleep(0.5)                        # give the server a moment to log
        print("4. three streams at once for one user (limit is 2):")
        results = await asyncio.gather(*[client.post(f"{BASE}/chat/stream", headers=AUTH,
                                         json={"message": "Write a haiku."}) for _ in range(3)])
        print("  statuses:", sorted(r.status_code for r in results))


env = {**os.environ, "OPENAI_BASE_URL": "http://localhost:11434/v1", "OPENAI_API_KEY": "ollama"}
server = subprocess.Popen([sys.executable, "-m", "uvicorn", "chat_app:app", "--port", "8001", "--log-level",
                           "warning"], env=env, stderr=subprocess.PIPE, text=True)
try:
    for _ in range(50):                                 # wait until the server accepts connections
        try:
            httpx.get(BASE + "/", timeout=0.2); break
        except httpx.TransportError:
            time.sleep(0.2)
    asyncio.run(main())
finally:
    time.sleep(0.5)
    server.terminate()
    server_log = server.communicate(timeout=5)[1]
    print("server log:")
    for line in server_log.splitlines():
        if "user=" in line:                             # our app's lines (its format has no logger name to match)
            print("  " + line.split(" ", 2)[2])         # drop the timestamp ("2026-11-08 12:00:00,123 ")
Output · local model qwen2.5:0.5b via Ollama28 lines
1. no token:
HTTP 401 {'detail': 'missing or invalid token'}
2. a full stream:
HTTP 200 text/event-stream; charset=utf-8 | cache-control=no-cache | x-accel-buffering=no
  id=1   event=delta  data={"text": "Red"}
  id=2   event=delta  data={"text": " and"}
  id=3   event=delta  data={"text": " Blue"}
  id=4   event=delta  data={"text": " are"}
  id=5   event=delta  data={"text": " two"}
  id=6   event=delta  data={"text": " primary"}
  id=7   event=delta  data={"text": " colors"}
  id=8   event=delta  data={"text": "."}
  id=9   event=usage  data={"input_tokens": 38, "output_tokens": 9}
  id=10  event=done   data={"status": "completed", "reason": null}
3. disconnect after 3 deltas:
HTTP 200 text/event-stream; charset=utf-8 | cache-control=no-cache | x-accel-buffering=no
  id=1   event=delta  data={"text": "One"}
  id=2   event=delta  data={"text": ","}
  id=3   event=delta  data={"text": " two"}
  -- client closes the connection --
4. three streams at once for one user (limit is 2):
  statuses: [200, 200, 429]
server log:
  INFO user=alice response_id=resp_944769 outcome=completed seconds=1.06 deltas=8 usage={'input_tokens': 38, 'output_tokens': 9}
  WARNING user=alice disconnected after 3 deltas; upstream stream closed
  INFO user=alice response_id=resp_552467 outcome=client disconnected seconds=0.80 deltas=3 usage=unknown
  INFO user=alice response_id=resp_804057 outcome=completed seconds=1.12 deltas=19 usage={'input_tokens': 34, 'output_tokens': 20}
  INFO user=alice response_id=resp_643181 outcome=completed seconds=1.29 deltas=21 usage={'input_tokens': 34, 'output_tokens': 22}

Everything the design promised is visible:

  1. No token: a real 401 with a JSON error, before any stream.
  2. A full stream: the FastAPI headers, our own events with increasing ids, usage then done. The provider's two dozen event types never reach the client.
  3. The disconnect. The client read three deltas and closed the connection; the server logged disconnected after 3 deltas; upstream stream closed and outcome=client disconnected ... usage=unknown. The CancelledError reached the generator, async with closed the provider stream, and the provider stopped generating for a user who had left.
  4. Two streams at once were allowed and the third got 429.

11.7 Production concerns#

A stream that works on localhost can arrive all at once, be cut after 60 seconds, or keep billing after the user leaves, once real infrastructure is in the way. Check each of these before launch:

Concern What goes wrong What to do
Reverse-proxy buffering nginx (and others) buffer the body, so the user sees nothing and then everything Send X-Accel-Buffering: no (FastAPI does), or set proxy_buffering off; for the stream location
Compression Gzip middleware buffers to compress efficiently Starlette's GZipMiddleware (1.10) excludes text/event-stream by default; check any other compression layer (CDN, proxy)
CDNs and API gateways Some buffer, cache or cap response duration Disable caching for stream routes (the Cache-Control: no-cache header helps), check the platform's streaming support and maximum response time
Idle timeouts Proxies and load balancers close silent connections: nginx's proxy_read_timeout and AWS ALB's idle timeout both default to 60 s (as of November 2026) Heartbeats more often than the shortest idle timeout in the chain (FastAPI: every 15 s), and raise the timeouts for stream routes
Serverless platforms Some don't stream responses at all, or cap execution time Check streaming support before you choose the platform
Disconnects The user leaves; the provider keeps generating and billing async with upstream + re-raise CancelledError (11.4); verify with a log line
Authentication EventSource can't send headers, tempting tokens in URLs fetch() + Authorization, or cookies, or short-lived single-use stream tokens; check auth before the stream starts
CORS (a front end on another origin) A page on app.example.com calling api.example.com is blocked by the browser unless your server opts in. The Authorization header is not CORS-safelisted, so every such fetch() first sends an OPTIONS preflight. EventSource sends cookies cross-origin only with withCredentials: true (and it can't send Authorization at all) Add FastAPI's CORSMiddleware with an explicit allow_origins list (not * when credentials are involved), allow_headers=["Authorization", "Content-Type"] and allow_credentials=True if you use cookies; use credentials: "include" in fetch(). Test the preflight, not just the stream
Per-user limits One user opens 50 tabs; your provider rate limit is shared by everyone A concurrency cap per user (429 before the stream), plus rate limits, in shared storage across workers
Total duration A stuck stream holds a worker and a provider connection forever A total deadline (asyncio.timeout, 8.1) and a sensible output cap
Usage logging Cancelled and failed streams are invisible in cost reports One log line per request with outcome and usage-or-unknown (7.6)
Graceful shutdown A deploy kills every open stream mid-sentence Drain: stop accepting new streams and let open ones finish (sse-starlette has shutdown hooks; most process managers have a grace period)
HTTP/1.1 connection limit Six concurrent connections per domain per browser, across tabs Serve over HTTP/2
Side channels Token-length leaks through packet sizes on your connection too (3.1) For sensitive apps, batch deltas into larger, padded events

11.8 WebSockets and other transports#

SSE is one-way: the server talks, the client listens. That suits a text answer. WebSockets give a two-way channel over one long-lived connection, which pays off when the client also streams to the server (audio from a microphone, live edits) or when one connection carries many interleaved conversations. The costs are a different protocol through proxies and load balancers, your own message framing, reconnection logic and authentication (browsers can't set headers on a WebSocket either). Some providers offer WebSocket APIs: OpenAI has a WebSocket mode for the Responses API "with incremental inputs via previous_response_id", and realtime voice APIs are WebSocket- or WebRTC-based (Module 09). For "send a prompt, stream back an answer" between your server and a browser, SSE over fetch() remains the simpler, more robust default.


Part 12: Measuring streams#

12.1 What to measure#

Lesson 02.5, 1.5 defined the metrics: time to first token, output tokens per second, time per output token and end-to-end latency. Streams give you the timestamps to measure them, plus two that matter more to users:

Metric Measured from your stream as Why it matters
Time to first token (TTFT) Request sent → first event with content (text or reasoning; an empty thinking delta is a placeholder, not content) Queueing, prefill (the model reading your whole prompt in one parallel pass, 02.5, 1.2) and network: the provider's responsiveness
Time to first visible token (TTFVT) Request sent → first answer text delta What the user experiences. On reasoning models it includes thinking time, and can be seconds longer than TTFT
Inter-delta gaps (p50, p95, max) Time between consecutive visible deltas Smoothness. A good median with a bad maximum is a visible freeze in the middle of an answer
Total time Request sent → stream ends End-to-end latency, and your cost of holding the connection
Output tokens per second Output tokens from the final usage ÷ (total − TTFT) Decode speed. Use the token count from usage, not the number of events: one event can carry several tokens

Two caveats when you compare numbers. First, these are event times, not token times: providers batch tokens into events differently (Gemini's chunks are often much larger than Claude's deltas), so inter-delta gaps compare smoothness, not raw speed. Second, output tokens include hidden reasoning, so when thinking is hidden, "tokens per second" computed from the first visible token looks absurdly high (see the claude omitted line in 12.3). Report TTFVT and total time to product people; keep TPS for capacity planning.

12.2 A reusable stream timer#

One small helper works with any SDK: call content() on any reasoning or text event, visible() on answer text, and finish(output_tokens) at the end.

python
# stream_metrics.py: measure any stream: time to first event, time to first VISIBLE token,
# gaps between visible deltas, total time and output tokens per second.
import statistics
import time
from dataclasses import dataclass


@dataclass
class StreamMetrics:
    ttft_s: float | None           # first event with any content (thinking included)
    ttfvt_s: float | None          # first text the user can read
    total_s: float
    visible_deltas: int
    gap_p50_ms: float | None       # gaps between visible deltas ("inter-token latency", per event)
    gap_p95_ms: float | None
    gap_max_ms: float | None       # the longest freeze the user saw
    output_tokens: int | None      # from the final usage; None if the stream never delivered it
    output_tps: float | None       # output tokens / (total - ttft)

    def line(self) -> str:
        def f(x, unit=""):
            return "n/a" if x is None else f"{x:.2f}{unit}" if isinstance(x, float) else f"{x}{unit}"
        return (f"TTFT {f(self.ttft_s, 's')} | first visible {f(self.ttfvt_s, 's')} | total {f(self.total_s, 's')}"
                f" | {self.visible_deltas} deltas, gaps p50 {f(self.gap_p50_ms, 'ms')} p95 {f(self.gap_p95_ms, 'ms')}"
                f" max {f(self.gap_max_ms, 'ms')} | {f(self.output_tokens)} tokens, {f(self.output_tps)} tok/s")


class StreamTimer:
    """Call .content() on any content event, .visible() on answer text, .finish() at the end."""

    def __init__(self) -> None:
        self.start = time.perf_counter()
        self.first_content: float | None = None
        self.visible_times: list[float] = []

    def content(self) -> None:
        if self.first_content is None:
            self.first_content = time.perf_counter()

    def visible(self) -> None:
        self.content()                 # visible text is content too
        self.visible_times.append(time.perf_counter())

    def finish(self, output_tokens: int | None) -> StreamMetrics:
        end = time.perf_counter()
        gaps = [(b - a) * 1000 for a, b in zip(self.visible_times, self.visible_times[1:])]
        ttft = self.first_content - self.start if self.first_content else None
        decode = end - self.first_content if self.first_content else None
        return StreamMetrics(
            ttft_s=ttft,
            ttfvt_s=self.visible_times[0] - self.start if self.visible_times else None,
            total_s=end - self.start,
            visible_deltas=len(self.visible_times),
            gap_p50_ms=statistics.median(gaps) if gaps else None,
            gap_p95_ms=statistics.quantiles(gaps, n=20)[-1] if len(gaps) >= 2 else None,
            gap_max_ms=max(gaps) if gaps else None,
            output_tokens=output_tokens,
            output_tps=output_tokens / decode if output_tokens and decode else None,
        )

The same helper on three of the four APIs (OpenAI Responses, Anthropic and Chat Completions), against the stand-in. Gemini has no local stand-in, so its timing is in the hosted sample of 12.3:

python
# s12_2_measure_local.py: the same StreamTimer on three APIs (local stand-in, no key)
import anthropic
from openai import OpenAI

from stream_metrics import StreamTimer

PROMPT = "Explain in three sentences what a CPU does."
oa = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
claude = anthropic.Anthropic(base_url="http://localhost:11434", api_key="ollama")

# OpenAI Responses
timer, tokens = StreamTimer(), None
with oa.responses.create(model="gpt-6-luna", input=PROMPT, max_output_tokens=120, stream=True) as s:
    for ev in s:
        if ev.type == "response.reasoning_summary_text.delta":
            timer.content()
        elif ev.type == "response.output_text.delta":
            timer.visible()
        elif ev.type in ("response.completed", "response.incomplete") and ev.response.usage:
            tokens = ev.response.usage.output_tokens
print("openai    ", timer.finish(tokens).line())

# Anthropic
timer = StreamTimer()
with claude.messages.stream(model="claude-haiku-5-5", max_tokens=120,
                            messages=[{"role": "user", "content": PROMPT}]) as s:
    for ev in s:
        if ev.type == "thinking" and ev.thinking:          # hidden thinking streams EMPTY deltas: not content
            timer.content()
        elif ev.type == "text":
            timer.visible()
    tokens = s.get_final_message().usage.output_tokens
print("anthropic ", timer.finish(tokens).line())

# OpenRouter-style Chat Completions (the openai SDK with another base_url)
timer, tokens = StreamTimer(), None
with oa.chat.completions.create(model="openai/gpt-6-luna", messages=[{"role": "user", "content": PROMPT}],
                                max_tokens=120, stream=True, stream_options={"include_usage": True}) as s:
    for c in s:
        if c.usage:
            tokens = c.usage.completion_tokens
        if c.choices and c.choices[0].delta.content:
            timer.visible()
print("chat      ", timer.finish(tokens).line())

Output (local model qwen2.5:0.5b via Ollama; hosted latencies are higher and more variable):

text
openai     TTFT 0.15s | first visible 0.15s | total 0.65s | 97 deltas, gaps p50 4.35ms p95 4.74ms max 5.14ms | 98 tokens, 194.97 tok/s
anthropic  TTFT 0.09s | first visible 0.09s | total 0.42s | 73 deltas, gaps p50 4.40ms p95 5.16ms max 5.49ms | 74 tokens, 228.05 tok/s
chat       TTFT 0.11s | first visible 0.11s | total 0.41s | 66 deltas, gaps p50 4.45ms p95 4.95ms max 5.44ms | 67 tokens, 225.20 tok/s

Locally there's no reasoning, so TTFT and first visible token are the same, and the gaps are a few milliseconds. The Anthropic branch tests ev.thinking, not just ev.type == "thinking": on hosted Claude 5.x models thinking is on and hidden by default (6.1), so the stream starts with an empty thinking delta that must not stop the TTFT clock. When a stream reports no token count, the helper prints n/a tokens and "unknown" throughput rather than computing a fake one, the same rule as 7.6.

12.3 The same timer on hosted reasoning models#

Where the timer earns its place is on reasoning models, where the two "first token" times split apart. This provider sample (layer 4) runs one small reasoning question with different reasoning settings:

python
# s12_3_measure_hosted.py: thinking vs visible-text latency on hosted reasoning models.
# Needs OPENAI_API_KEY, ANTHROPIC_API_KEY and GEMINI_API_KEY in .env. stream_metrics.py is in 12.2.
import anthropic
from dotenv import load_dotenv
from google import genai
from google.genai import types
from openai import OpenAI

from stream_metrics import StreamTimer

load_dotenv()
openai_client, claude, gemini = OpenAI(), anthropic.Anthropic(), genai.Client()   # create once, reuse
PROMPT = "A bat and a ball cost $1.10 together. The bat costs $1.00 more than the ball. Ball price?"

for effort in ("none", "medium"):
    timer, tokens = StreamTimer(), None
    with openai_client.responses.create(model="gpt-6-luna", input=PROMPT, stream=True,
                                   reasoning={"effort": effort, "summary": "auto"}) as s:
        for ev in s:
            if ev.type == "response.reasoning_summary_text.delta":
                timer.content()
            elif ev.type == "response.output_text.delta":
                timer.visible()
            elif ev.type == "response.completed" and ev.response.usage:
                tokens = ev.response.usage.output_tokens
    print(f"openai effort={effort:<7}", timer.finish(tokens).line())

for display in ("summarized", "omitted"):
    timer = StreamTimer()
    with claude.messages.stream(
            model="claude-haiku-5-5", max_tokens=8_000, messages=[{"role": "user", "content": PROMPT}],
            thinking={"type": "adaptive", "display": display}) as s:
        for ev in s:
            if ev.type == "thinking" and ev.thinking:     # empty when display="omitted"
                timer.content()
            elif ev.type == "text":
                timer.visible()
        tokens = s.get_final_message().usage.output_tokens
    print(f"claude {display:<10}  ", timer.finish(tokens).line())

timer, tokens = StreamTimer(), None
for chunk in gemini.models.generate_content_stream(
        model="gemini-3.8-flash", contents=PROMPT,
        config=types.GenerateContentConfig(thinking_config=types.ThinkingConfig(include_thoughts=True))):
    cand = chunk.candidates[0] if chunk.candidates else None
    for part in (cand.content.parts or []) if cand and cand.content else []:
        if part.text and part.thought:
            timer.content()
        elif part.text:
            timer.visible()
    if chunk.usage_metadata and chunk.usage_metadata.candidates_token_count:
        # candidates_token_count excludes thinking; add thoughts_token_count for all output tokens
        tokens = chunk.usage_metadata.candidates_token_count + (chunk.usage_metadata.thoughts_token_count or 0)
print("gemini thoughts=on    ", timer.finish(tokens).line())
Example output · illustrative5 lines
openai effort=none    TTFT 0.52s | first visible 0.52s | total 1.31s | 38 deltas, gaps p50 14.80ms p95 41.20ms max 63.10ms | 41 tokens, 51.90 tok/s
openai effort=medium  TTFT 2.94s | first visible 4.87s | total 5.62s | 36 deltas, gaps p50 15.30ms p95 38.70ms max 71.40ms | 298 tokens, 111.19 tok/s
claude summarized   TTFT 1.12s | first visible 3.41s | total 4.05s | 31 deltas, gaps p50 19.60ms p95 52.10ms max 66.30ms | 233 tokens, 79.52 tok/s
claude omitted      TTFT 2.96s | first visible 2.96s | total 3.58s | 29 deltas, gaps p50 18.90ms p95 49.80ms max 61.20ms | 226 tokens, 364.52 tok/s
gemini thoughts=on     TTFT 1.85s | first visible 3.02s | total 3.47s | 4 deltas, gaps p50 141.30ms p95 196.20ms max 203.40ms | 271 tokens, 167.28 tok/s

How to read it:

  • effort=none: no thinking, so TTFT = first visible, and few output tokens.
  • effort=medium with summaries: the summary starts streaming at ~3 s (TTFT), but the answer starts at ~4.9 s (TTFVT). A dashboard showing only TTFT would claim this is fine; the user waited almost five seconds for the first word of the answer.
  • Claude summarized vs omitted (omitted is what you get when you set no display at all, on Haiku 5.5 and the other Claude 5.x models): with summaries the user sees thinking from ~1.1 s; with thinking hidden there's nothing to see until the answer at ~3 s (TTFT = TTFVT because empty thinking deltas don't count as content). The output-token count barely changes, because you pay for thinking either way (02.8, 5.1), and the throughput figure for omitted is inflated for exactly that reason.
  • Gemini: few, large chunks, so few gaps, each long. Smoothness at the UI depends on how you render big chunks (Module 13A's concern).
  • Gemini's candidates_token_count excludes thinking, so the sample adds thoughts_token_count to get all output tokens.

What this means for you as an engineer: put TTFVT, the p95 and maximum gaps, total time, and the outcome on every streaming request's log line, broken down by model and reasoning setting. Set alerts on TTFVT, not TTFT. When someone asks "is it faster?", compare distributions over many requests, not one run (03.10 for logging, Module 11A for dashboards).


Common misconceptions#

Misconception Reality
"Streaming makes the model faster." Generation takes the same time and costs the same. Streaming changes when the user starts reading (1.1)
"Every SSE data: line is JSON." Chat Completions ends with data: [DONE], Interactions with data: [DONE] after an event: done, and comment lines (: OPENROUTER PROCESSING) aren't data at all (2.3)
"If the HTTP status is 200, the stream succeeded." Errors after the headers arrive inside the stream, or as a dropped connection; some SDKs raise them, others yield them as events (7.2)
"The SDK will retry a failed stream." SDK retries cover only the request that opens the stream (Gemini's long-generation continuation is the exception: google-genai resumes from a continuation_token, 4.5b). Any other mid-stream failure is yours to handle (7.4)
"If the stream ended without an error, it finished." Most helpers return a partial message with stop_reason=None / finish_reason=None and raise nothing. Check for the terminal event (7.3, case 7)
"Claude only hides its thinking when I ask it to." On Claude 5.x models thinking is on and display defaults to "omitted": every stream starts with an empty thinking block (6.1)
"except anthropic.OverloadedError catches overloads." Not streamed ones: a mid-stream overloaded_error raises APIStatusError with status_code=200 (7.3)
"Add up the usage you see in the stream." Anthropic's message_delta usage is cumulative and OpenRouter may repeat fields; always take the latest value, never sum (5.2)
"The usage chunk has no choices." True for OpenAI; OpenRouter's usage chunk has choices and repeats finish_reason (3.6)
"A read timeout limits how long the stream can take." It limits the gap between bytes; keep-alives reset it. Add a total deadline yourself (8.2)
"Breaking out of the loop stops the stream." It stops your loop. Only closing the stream (a with block) returns the connection and lets the provider stop (8.4)
"Closing the stream means we don't pay." You pay for the input and for whatever was generated before the provider noticed; only OpenRouter documents which providers stop billing immediately (8.5)
"Parse tool arguments as they stream." Fragments aren't valid JSON until the end. Preview with a partial parser if you like; execute only on the complete, validated arguments (6.2)
"Use EventSource, it's built for SSE." It can't POST or send an Authorization header, which leads people to put prompts and keys in URLs. Use fetch() (11.5)
"Forward the provider's events to the front end." That ties your UI to one provider's event names and leaks internals. Define your own small protocol (11.2)
"TTFT tells us how fast the app feels." On reasoning models the first visible token can come seconds later. Measure both (Part 12)

Key takeaways#

  • Stream when a human is waiting or when your code can act on early output; don't stream backend jobs, short replies or output that must be checked first.
  • SSE is simple: data:, event:, id:, retry:, comments starting with :, and a blank line to dispatch. Know each provider's ending, and treat a stream without it as interrupted.
  • Each API has its own taxonomy: Responses semantic events with sequence_number; Chat Completions chunks with an opt-in usage chunk whose choices is empty; Anthropic content-block events with cumulative usage; Gemini chunks that are whole responses; Interactions step events with event_id; OpenRouter chunks with comments and a usage chunk that has choices.
  • Route on event type, ignore unknown types, guard chunk.choices, read usage from every event and keep the latest value.
  • Helpers (responses.stream(), chat.completions.stream(), messages.stream()) give snapshots and final objects, but can raise mid-loop, and get_final_response() fails on incomplete responses: keep the terminal event yourself.
  • Accumulate by block or item index; join tool-argument fragments and parse once; keep reasoning and signatures; record finish reason and usage, with None meaning unknown.
  • Reasoning comes first; tool arguments arrive as JSON fragments (not at all on Gemini generate_content); structured output can be shown as partial objects but must be validated at the end; refusals can arrive after text, so your UI needs a reset.
  • Errors after 200 OK are raised by some SDKs and yielded by others, and are not retried (the one exception is google-genai's automatic continuation of very long Gemini generations). A body that just ends raises nothing in most helpers: check the terminal event. Choose between resume, silent restart, restart-and-reset and continue, and count anything you forwarded (text, reasoning, tool progress) as "shown".
  • A read timeout is the longest silence; add a total deadline. Close every stream with with/async with. Cancelling limits cost; it doesn't refund it.
  • OpenAI background responses (starting_after) and Gemini background interactions (last_event_id) can be resumed; nothing else can.
  • In a browser app, the key stays on your server; auth and limits run before the stream; your own event protocol goes to the client over fetch(); disconnects must cancel the upstream stream; heartbeats and disabled buffering keep proxies out of the way.
  • Measure time to first visible token, gaps and total time, not just TTFT.

Terms introduced in this lesson#

Term One-line definition
Server-Sent Events (SSE) A one-way, text-based streaming format over HTTP (text/event-stream) made of data:, event:, id: and retry: fields separated by blank lines
Event dispatch The SSE rule that a blank line ends an event and hands it to the client
SSE comment / keep-alive A line starting with : that clients ignore, sent to keep idle connections open
[DONE] sentinel The non-JSON data: [DONE] line that ends Chat Completions (and some other) streams
Terminal event The event that marks a successful end of a stream: response.completed, message_stop, interaction.completed...
Semantic events OpenAI Responses' streaming style: typed events per change to the response tree, numbered by sequence_number
Stream chunk Chat Completions' streaming unit: a small completion object whose delta holds only the new content
Usage chunk The extra final Chat Completions chunk carrying token usage (choices empty on OpenAI, not on OpenRouter)
Content-block events Anthropic's streaming style: content_block_start / _delta / _stop per block inside message_start … message_stop
Cumulative usage Usage figures that are running totals (Anthropic message_delta), to be replaced, never added
Step events Gemini Interactions' streaming style: step.start / step.delta / step.stop per step
Stream helper An SDK wrapper (responses.stream(), messages.stream()...) that accumulates the final message and adds convenience events
Snapshot The helper's accumulated state so far, attached to delta events or available mid-stream
Stream accumulator Code that rebuilds the final message (text, tool calls, reasoning, finish reason, usage) from stream events
Partial JSON parsing Parsing an incomplete JSON prefix into a best-effort object, for previews of streamed structured output or tool arguments
Mid-stream error An error that arrives inside a stream after 200 OK has been sent
Restart-and-reset Recovering from a mid-stream failure by retrying and telling the client to clear what it already showed
Continuation request A new request that includes the partial answer and asks the model to continue from it. For Claude 4.6 and later the partial answer goes inside a user message
Automatic continuation google-genai's default behaviour of chaining long-generation "hops" and resuming a dropped stream from a continuation_token; FinishReason.CONTINUATION is not an ending
Continuation token An opaque checkpoint the Gemini server issues during very long generations; sending it back continues the generation
Resumable stream A stream you can reconnect to after a disconnect, receiving only missed events (OpenAI background + starting_after, Interactions + last_event_id)
Stream cursor The last sequence_number or event_id received, used to resume
Read timeout (streaming) The longest silence allowed between received bytes; reset by every byte, including keep-alives
Total deadline A limit on a whole operation's duration, e.g. asyncio.timeout(), independent of read timeouts
Connection leak A stream left unclosed, holding a pooled connection until the pool is exhausted
Stream obfuscation OpenAI's random padding on stream events (include_obfuscation) that hides token lengths from network observers
Fan-in Merging events from several concurrent streams into one ordered queue
Event protocol The small set of typed events your own server sends to its clients, independent of any provider
EventSource The browser's built-in SSE client: GET only, no custom headers, automatic reconnect with Last-Event-ID
Last-Event-ID The header a reconnecting EventSource sends with the last id: it received
Response buffering (proxy) A proxy collecting a response before forwarding it, which breaks streaming; disabled with X-Accel-Buffering: no on nginx
Heartbeat A periodic keep-alive your server sends so proxies don't drop the stream and dead clients are detected
Time to first visible token (TTFVT) Time from request to the first answer text the user can read, after any thinking
Inter-delta gap The time between consecutive visible deltas; its maximum is the longest freeze the user sees
Fine-grained tool streaming Anthropic's eager_input_streaming tool option: tool input streams without server-side buffering or validation

All terms are also collected in the glossary.


Exercises#

All of these run against the free local stand-in unless marked. Gemini has no local stand-in, so nothing here asks you to run a Gemini sample.

  1. Raw bytes (2.2): add "stream_options": {"include_usage": False} to the Chat Completions request in s2_1_raw_capture.py. What disappears from the end of the stream?
  2. Parser (2.5): add tests to test_sse.py for a leading BOM, for data: with no space after the colon, for an id: containing a NUL character, and for retry: 10s (which must be ignored). Fix the parser if any fail.
  3. Event routing (3.1, 3.3): extend s3_1_responses_events.py and s3_3_anthropic_events.py with a counter of event types, and print the counts at the end. Which types appear exactly once in every stream?
  4. OpenRouter trap (3.6): change s3_6_openrouter_mock.py's loop to read usage only when chunk.choices is empty (OpenAI-style code). What does it report? Now write the version that works on both OpenAI and OpenRouter shapes, and test it against both a mock of each.
  5. Accumulator (5.3, 5.5): extend AnthropicAccumulator to keep citations_delta and stop_sequence. Write a mock (using mockkit.py) that exercises them, and compare against the SDK helper's final object as s5_5_fragments_mock.py does. Then add a fragmented, interleaved Responses refusal to the same file.
  6. Partial structured output (6.3): add a summary: str field to City, placed first, and watch the drafts. Then move it last. Which order is better for a UI, and why does order matter?
  7. Mid-stream errors (7.3): s7_2_midstream_errors.py case 7 shows a stream that stops after one delta for four SDK paths. Now do the same for OpenRouter Chat Completions with a body that carries : OPENROUTER PROCESSING comments and one delta, then ends. Use ChatAccumulator to report "interrupted", and decide what your app does: restart, continue or give up?
  8. Restart (7.5): change stream_with_restart so it emits no reset when nothing had been shown yet, and makes the mock fail twice. Then switch it to the continuation strategy using continuation_messages and compare the final screen text.
  9. Timeouts (8.2): in fake_sse_server.py, make the stall 20 seconds with pings. Make the client give up after 5 seconds of no text, even while pings keep arriving. (Hint: no timeout setting can do this, because pings reset the read timeout; track the time of the last text delta yourself.)
  10. Leaks (8.4): run s8_3_leak.py with max_connections=3. After how many leaking requests does the first PoolTimeout appear?
  11. Browser (11.6): add a reasoning and a reset handler to page.html, and an error path to chat_app.py for an incomplete response with reason max_output_tokens. Then set MAX_STREAMS_PER_USER = 1 and open the page in two tabs.
  12. Measuring (12.2): run s12_2_measure_local.py five times and report the median and spread of each metric. Which metric is most stable? (Provider, with a key: run s12_3_measure_hosted.py with effort set to low and high and compare TTFVT.)
  13. Async restart (11.4, 7.5): port stream_with_restart to AsyncAnthropic (async with, async for, await asyncio.sleep) and use it inside an endpoint like chat_app.py (or adapt the app to the Anthropic API). Add the reset event to page.html, and prove with the mock of 7.5 that the screen ends with one clean answer. Why does the synchronous version freeze other users' streams?
  14. Resumable endpoint (11.4, 9.4): keep the last 200 events of each stream in a ring buffer keyed by stream ID, and make the endpoint honour Last-Event-ID (the header a reconnecting EventSource sends) by replaying events after that ID. What do you do when the ID has already fallen out of the buffer? (9.4 names the gap; this closes it for your own endpoint.)
Hints and what you should see
  1. Without include_usage, the choices: [] chunk with the totals disappears: the stream ends with the chunk that has finish_reason, then data: [DONE]. (Gemini's REST API is different: alt=sse is what asks for SSE framing. Without it, Google's API returns the stream as one growing JSON array ([{...}, then {...} and so on) instead of data: lines, so your SSE parser would find no events. That can't be tried locally.)

  2. Add these four cases to test_sse.py. All four pass with the parser in 2.5, which is the point of writing the parser against the spec:

    python
    def test_leading_bom_is_ignored():
        assert parse("\ufeffdata: x\n\n".encode())[0].data == "x"
    
    
    def test_data_without_a_space_after_the_colon():
        assert parse(b"data:x\n\n")[0].data == "x"
    
    
    def test_id_with_nul_is_ignored():
        assert parse(b"id: 1\x002\ndata: a\n\n")[0].id is None     # no earlier ID, so it stays None
    
    
    def test_retry_must_be_digits_only():
        assert parse(b"retry: 10s\ndata: a\n\n")[0].retry is None

    A BOM in the middle of a stream is not ignored (only a leading one is): the line then has an unknown field name, and the spec says to skip it.

  3. Count event.type with collections.Counter. In a single-text-block answer, these appear exactly once: for Responses response.created, response.in_progress, response.output_item.added/.done, response.content_part.added/.done, response.output_text.done and response.completed (the delta type is the only repeated one). For Anthropic: message_start, content_block_start, content_block_stop, message_delta and message_stop, with content_block_delta repeated and ping never visible (the SDK drops it).

  4. Reading usage only when choices is empty never fires on OpenRouter, because its usage chunk has a non-empty choices list: usage stays None, and the sample's last print line fails with AttributeError ('NoneType' object has no attribute 'prompt_tokens'). The version that works everywhere checks chunk.usage is not None on every chunk, independent of choices, and guards chunk.choices separately. To test it against the OpenAI shape, write a second fixture whose last chunk has "choices": [] and the usage object; both fixtures should print the same totals.

  5. Follow s5_5_fragments_mock.py: citations_delta is {"type": "citations_delta", "citation": {...}} on a text block, so keep a list per block and add it to the block's dict. stop_sequence arrives in message_delta.delta. The SDK helper's final message exposes block.citations and message.stop_sequence to compare against. For the Responses refusal, ResponsesAccumulator already routes response.refusal.delta into the item's refusal field by output_index: build two refusal items whose deltas interleave and assert that final.refusal holds both strings in item order.

  6. With summary first, the first draft that appears already contains the summary, and the rest fills in below it. With summary last, the draft shows the name, country and landmarks first, and the summary appears only at the end. For a UI, put what the reader wants first at the front: providers generate keys in schema order (6.3), so the order of fields is the order of arrival.

  7. The mock body is b": OPENROUTER PROCESSING\n\n" plus one chunk("Red and") and nothing else (no finish chunk, no [DONE]). The openai SDK raises nothing; ChatAccumulator.result() gives complete=False, finish_reason=None, text=['Red and']. Decision: the user has already seen text, so the choices are restart and reset (cheap for a short answer) or continue (worth it only for a long partial answer). Give up and show a retryable error if the second attempt also fails (7.5).

  8. With nothing shown before the failure, no reset should appear: only delta events from the successful attempt. With max_attempts=3, a mock that fails twice succeeds on the third request (HTTP requests made: 3); fail three times and you get the error event. For the continuation version, the final screen is shown_so_far plus whatever the model produces next, often with a rough join (a missing space or a repeated word), whereas restart-and-reset gives a clean answer at the price of regenerating everything.

  9. asyncio.timeout can be moved: async with asyncio.timeout(5) as cm: and, on every text delta, cm.reschedule(asyncio.get_running_loop().time() + 5). Pings then keep the connection alive but never move the deadline, so the client gives up about 5 seconds after the last text (about 5.2 s into the run with this server). The alternative is to store time.monotonic() at each text delta and break when the gap exceeds 5 seconds, checking it on every event, including pings.

  10. Set max_connections=3 in httpx2.Limits(...) and change range(1, 4) to range(1, 6), so each run makes five requests. Each leaked request holds one connection for good, so requests 1, 2 and 3 succeed and request 4 is the first to fail with PoolTimeout after the 2-second pool wait (with max_connections=1 it was request 2). The rule: the first failure comes at request max_connections + 1.

  11. In the page: else if (type === "reasoning") reasoning.textContent += msg.text; (add a second <pre id="reasoning">), and else if (type === "reset") out.textContent = "";. In chat_app.py, inside the response.incomplete branch, when reason == "max_output_tokens", yield event("error", message="The answer was cut off by the length limit.", retryable=False) before the done event (or instead of it). With MAX_STREAMS_PER_USER = 1, the second tab, which uses the same demo token, shows HTTP 429 while the first is still streaming, and works again once the first finishes.

  12. Expect the inter-delta gaps (p50, p95) to be the steadiest numbers on a local model, since they are a few milliseconds each. TTFT and total time vary most, especially on the first run, when the model may still be loading. Report the median of five runs and the min and max, not the mean. With a key: effort="high" should push TTFVT later than "low" and raise the output-token count (reasoning tokens are output tokens); check the direction on your own runs rather than assuming a size.

  13. Replace client.messages.stream with async with AsyncAnthropic(...).messages.stream(...), for with async for, and time.sleep with await asyncio.sleep. Make the generator async def and consume it with async for in the endpoint. The synchronous version freezes other users because FastAPI runs the async def endpoint on the single event-loop thread: a blocking time.sleep (or a blocking SDK read) stops every coroutine from being scheduled until it returns, so all other streams stall during the backoff.

  14. Generation must outlive the connection for this to work: run the provider stream in its own asyncio.Task that writes (id, event) pairs into a collections.deque(maxlen=200) per stream ID, and let each HTTP request read from the buffer. That conflicts with "cancel upstream on disconnect" (8.5), so cancel the task only after an idle period with no reader. Read Last-Event-ID with Header(alias="last-event-id"), and replay events whose id is greater. If the oldest buffered ID is more than one above the requested one, events were lost: a gap cannot be repaired by replaying: send a reset event and restart the generation (or tell the client to start a new request).


Check yourself#

  1. Name four things that change in your code when you switch from a normal call to a streaming call.
  2. Give three situations where you should not stream, and what to do instead.
  3. In SSE, what does a blank line do? What happens to a final event that isn't followed by one?
  4. How does each of these streams end: Chat Completions, Responses, Anthropic, Gemini generate_content?
  5. Why does chunk.choices[0] crash on the last chunk of an OpenAI Chat Completions stream, and why does the obvious fix misbehave on OpenRouter?
  6. Anthropic sends two message_delta events with output_tokens 40 and then 95. How many output tokens did the response use?
  7. What does stream_options.include_obfuscation do, and when might you turn it off?
  8. Why should you parse tool-call arguments only when the call is complete? What can you safely show earlier?
  9. Your messages.stream(output_format=...) loop raises a Pydantic ValidationError and the snapshot's stop_reason is None. What probably happened, and how do you handle it robustly?
  10. A Claude stream fails with overloaded_error after 200 words. What exception does the SDK raise, with what status_code, and will the SDK retry it?
  11. Which two APIs can resume a dropped stream, and what is the cursor for each? Which other SDK path can resume without a cursor of yours, and when?
  12. Your read timeout is 30 seconds, yet a stream ran for 25 minutes without producing text. How is that possible, and how do you prevent it?
  13. Why is break inside for event in stream: dangerous without a with block?
  14. Why shouldn't an LLM chat endpoint use EventSource, and what's wrong with the usual workaround?
  15. Why do authentication and the per-user limit run in FastAPI dependencies instead of inside the streaming generator?
  16. What has to happen, step by step, for a user's Stop button to stop the provider from generating?
  17. A dashboard shows TTFT of 0.6 s for a reasoning model, but users complain it's slow. What should you measure instead?
  18. A Claude stream's body ends after 200 words with no error, and get_final_message() returns normally. How do you find out whether the answer is complete?

Further resources#


← 03.2 — Messages, Roles and Conversation State | Module 03 overview | 03.4 — Structured Output →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close