DEV Community

Cover image for Your LLM Stream Can Fail After the 200. Test It With a Port and a Fake That Yields
Gabriel Anhaia
Gabriel Anhaia

Posted on Edited on AI-assisted

Your LLM Stream Can Fail After the 200. Test It With a Port and a Fake That Yields


Your chat endpoint has already sent 200 OK and forty tokens when the model says it is overloaded. Anthropic's error docs describe exactly this case: after a stream starts, the API has already returned a 200, so it sends an error as an error event, and the SDK doesn't retry the request. The status code can't change anymore. Whatever the browser sees next is up to your route handler.

So what does your handler do? If it iterates the SDK's stream directly, branches on SDK event types and formats SSE inline, you can only find out with a live model that happens to fail at the right moment. That test doesn't exist, so the branch ships untested.

The fix is a boundary. The stream becomes a port that yields your own Chunk type. The Anthropic SDK and the SSE formatting each sit behind an adapter, and a fake adapter yields a scripted sequence, including an exception on chunk two. The core never imports an SDK event class.

The port: a method that returns an AsyncIterator

The domain needs text pieces and a final token count from a model stream, plus a way to fail. In code that is two frozen dataclasses, an exception and a typing.Protocol.

# app/core.py
from collections.abc import AsyncIterator
from dataclasses import dataclass
from typing import Protocol

@dataclass(frozen=True)
class TextDelta:
    text: str

@dataclass(frozen=True)
class Usage:
    input_tokens: int
    output_tokens: int

Chunk = TextDelta | Usage

class ProviderError(Exception):
    def __init__(self, kind: str, message: str = "") -> None:
        super().__init__(message)
        self.kind = kind

class LLMStream(Protocol):
    def stream(self, prompt: str) -> AsyncIterator[Chunk]: ...
Enter fullscreen mode Exit fullscreen mode

Look at the protocol method: def, not async def. That isn't a typo. mypy's docs on asynchronous iterators call out the trap: an async def method with no yield in its body is typed as a coroutine that returns an iterator, Callable[[], Coroutine[Any, Any, AsyncIterator[int]]], not as a function that returns one. Every real adapter is an async generator (async def plus yield), and calling one hands back an AsyncIterator directly. Declaring the protocol with plain def matches what the adapters actually are.

The one piece of logic in the core is relay. It passes chunks through and enforces the contract every adapter has to meet: exactly one Usage, and it comes last.

async def relay(
    llm: LLMStream, prompt: str
) -> AsyncIterator[Chunk]:
    usage_seen = False
    async for chunk in llm.stream(prompt):
        if usage_seen:
            raise ProviderError("protocol", "chunk after usage")
        usage_seen = isinstance(chunk, Usage)
        yield chunk
    if not usage_seen:
        raise ProviderError("truncated", "no usage chunk")
Enter fullscreen mode Exit fullscreen mode

That last check pays for itself. A stream that ends without a usage chunk ended early, and the core can name that without knowing which provider was on the other end.

A hexagon with a small token conveyor inside, two plug-shaped adapters on the left feeding it and one pipe-shaped adapter on the right carrying tokens out
The core sees only Chunk. Provider adapters plug in on one side, the SSE adapter on the other.

Two provider adapters, two ways of reporting usage

The Anthropic Python SDK needs Python 3.10 or later. Its streaming helper yields SDK events, including a text event whose event.text is the delta, and after the stream is consumed, get_final_message() returns the accumulated message. On the wire, the usage in message_delta events is cumulative, which is one more reason to read it from the final message instead of adding up deltas.

# app/anthropic_adapter.py
from collections.abc import AsyncIterator

import anthropic
import httpx2

from app.core import Chunk, ProviderError, TextDelta, Usage

class AnthropicStream:
    def __init__(
        self,
        client: anthropic.AsyncAnthropic,
        model: str,
        max_tokens: int = 1024,
    ) -> None:
        self._client = client
        self._model = model
        self._max_tokens = max_tokens

    async def stream(self, prompt: str) -> AsyncIterator[Chunk]:
        try:
            async with self._client.messages.stream(
                model=self._model,
                max_tokens=self._max_tokens,
                messages=[{"role": "user", "content": prompt}],
            ) as events:
                async for event in events:
                    if event.type == "text":
                        yield TextDelta(event.text)
                final = await events.get_final_message()
        except anthropic.APIStatusError as err:
            kind = err.type or "api_error"
            raise ProviderError(kind, err.api_message or "") from err
        except anthropic.APIConnectionError as err:
            raise ProviderError("connection", str(err)) from err
        except httpx2.TransportError as err:
            raise ProviderError("dropped", str(err)) from err
        yield Usage(
            final.usage.input_tokens,
            final.usage.output_tokens,
        )
Enter fullscreen mode Exit fullscreen mode

Each except maps to a row in Anthropic's SDK error types table. An error event in a stream arrives as APIStatusError, and you branch on err.type (for example overloaded_error), not on the status code, because the status is the stream's 200 or missing. A failure before any response is APIConnectionError. A connection that drops or stalls mid-stream is httpx2.TransportError; the SDK sends requests with httpx2, an API-compatible fork of httpx. The adapter ignores every event type that isn't text, which is what the streaming docs ask for: new event types may be added, and your code should handle unknown ones gracefully.

OpenAI's Responses API streams differently. Text arrives as response.output_text.delta events, failures can arrive as an error event, and usage rides on the response.completed event. In the openai-python types, ResponseTextDeltaEvent carries delta: str, the error event carries code and message, and ResponseUsage has input_tokens and output_tokens.

# app/openai_adapter.py
from collections.abc import AsyncIterator

import openai

from app.core import Chunk, ProviderError, TextDelta, Usage

class OpenAIStream:
    def __init__(
        self, client: openai.AsyncOpenAI, model: str
    ) -> None:
        self._client = client
        self._model = model

    async def stream(self, prompt: str) -> AsyncIterator[Chunk]:
        try:
            events = await self._client.responses.create(
                model=self._model, input=prompt, stream=True
            )
            async for event in events:
                if event.type == "response.output_text.delta":
                    yield TextDelta(event.delta)
                elif event.type == "response.completed":
                    usage = event.response.usage
                    if usage is not None:
                        yield Usage(
                            usage.input_tokens,
                            usage.output_tokens,
                        )
                elif event.type == "error":
                    kind = event.code or "error"
                    raise ProviderError(kind, event.message)
        except openai.APIError as err:
            name = type(err).__name__
            raise ProviderError(name, str(err)) from err
Enter fullscreen mode Exit fullscreen mode

The openai-python README says all of its errors inherit from openai.APIError, and that during streaming, read timeouts raise APITimeoutError and other HTTPX failures raise APIConnectionError, so one except covers the transport. If the response fails or comes back incomplete, the stream ends with response.failed or response.incomplete instead of response.completed, so no Usage gets yielded and relay raises truncated. The adapter doesn't need its own branch for that.

None of that vocabulary reaches the core: both adapters hand back the same TextDelta and Usage.

The SSE adapter: FastAPI's EventSourceResponse

FastAPI has had SSE built in since 0.135.0: set response_class=EventSourceResponse, yield from the route, and yield ServerSentEvent objects when you want named events. The same page says it sends a keep-alive ping comment every 15 seconds when nothing else has gone out, and sets Cache-Control: no-cache and X-Accel-Buffering: no for you. SSE over POST is supported too, which a chat endpoint needs.

# app/web.py
import os
from collections.abc import AsyncIterable
from contextlib import asynccontextmanager
from dataclasses import asdict
from typing import Annotated

from anthropic import AsyncAnthropic
from fastapi import Depends, FastAPI, Request
from fastapi.sse import EventSourceResponse, ServerSentEvent
from pydantic import BaseModel, Field

from app.anthropic_adapter import AnthropicStream
from app.core import (
    LLMStream, ProviderError, TextDelta, Usage, relay,
)

@asynccontextmanager
async def lifespan(app: FastAPI):
    async with AsyncAnthropic() as client:
        model = os.environ["LLM_MODEL"]
        app.state.llm = AnthropicStream(client, model)
        yield

app = FastAPI(lifespan=lifespan)

class PromptIn(BaseModel):
    text: str = Field(min_length=1, max_length=8_000)

def get_llm(request: Request) -> LLMStream:
    return request.app.state.llm

@app.post("/chat", response_class=EventSourceResponse)
async def chat(
    body: PromptIn,
    llm: Annotated[LLMStream, Depends(get_llm)],
) -> AsyncIterable[ServerSentEvent]:
    try:
        async for chunk in relay(llm, body.text):
            match chunk:
                case TextDelta(text=text):
                    yield ServerSentEvent(
                        event="token", data={"text": text}
                    )
                case Usage() as usage:
                    yield ServerSentEvent(
                        event="usage", data=asdict(usage)
                    )
    except ProviderError as err:
        yield ServerSentEvent(
            event="error", data={"kind": err.kind}
        )
Enter fullscreen mode Exit fullscreen mode

The except ProviderError branch is the reason for the whole exercise. The 200 has already gone out, so the only honest thing left is a named error event the browser can listen for. It sends kind and nothing else, so the raw provider message never reaches the browser. An empty prompt never gets this far, because Pydantic's min_length rejects it with a 422 before any stream opens.

Switching to OpenAI is one line in lifespan: build an OpenAIStream instead. Nothing else changes, tests included. The one thing that moves is the kind string the browser gets, which follows each provider's error vocabulary.

The fake adapter and the tests that need it

The fake takes a script. Each item is either a chunk to yield or a ProviderError to raise at that point in the stream.

# app/fake.py
from collections.abc import AsyncIterator

from app.core import Chunk, ProviderError

class FakeLLM:
    def __init__(self, *script: Chunk | ProviderError) -> None:
        self.script = script
        self.prompts: list[str] = []

    async def stream(self, prompt: str) -> AsyncIterator[Chunk]:
        self.prompts.append(prompt)
        for item in self.script:
            if isinstance(item, ProviderError):
                raise item
            yield item
Enter fullscreen mode Exit fullscreen mode

A player-piano roll punched with a short row of holes and one torn gap in the middle, feeding into a small testing bench under a magnifier
The fake plays a scripted stream, including the tear halfway through.

pytest needs no async plugin here. The core tests drive relay with asyncio.run, and the route tests go through FastAPI's sync TestClient. Overrides follow the pattern in FastAPI's testing-dependencies docs: set a key in app.dependency_overrides and reset it to {} afterwards. The client is built without a with block, which FastAPI's docs reserve for tests that need the lifespan to run, so these tests don't need a real Anthropic client or LLM_MODEL.

# tests/test_stream.py
import asyncio
import json

import pytest
from fastapi.testclient import TestClient

from app.core import ProviderError, TextDelta, Usage, relay
from app.fake import FakeLLM
from app.web import app, get_llm

def collect(llm: FakeLLM) -> list:
    async def run() -> list:
        return [c async for c in relay(llm, "hi")]
    return asyncio.run(run())

def parse_sse(body: str) -> list[tuple]:
    events = []
    for block in body.replace("\r\n", "\n").split("\n\n"):
        fields: dict[str, str] = {}
        for line in block.split("\n"):
            name, _, value = line.partition(":")
            if name:
                fields[name] = value.removeprefix(" ")
        if "data" in fields:
            data = json.loads(fields["data"])
            events.append((fields.get("event"), data))
    return events

@pytest.fixture
def post_chat():
    def run(fake: FakeLLM):
        app.dependency_overrides[get_llm] = lambda: fake
        return TestClient(app).post("/chat", json={"text": "hi"})
    yield run
    app.dependency_overrides = {}
Enter fullscreen mode Exit fullscreen mode

parse_sse splits on blank lines and reads name: value fields, so it doesn't care which order FastAPI writes event: and data: in, and it skips comment lines such as keep-alive pings (their field name is empty). The tests go in the same file, below the helpers.

def test_relay_keeps_order_and_ends_on_usage():
    fake = FakeLLM(TextDelta("Hel"), TextDelta("lo"), Usage(5, 2))
    assert collect(fake) == [
        TextDelta("Hel"), TextDelta("lo"), Usage(5, 2),
    ]
    assert fake.prompts == ["hi"]

def test_stream_without_usage_is_truncated():
    with pytest.raises(ProviderError) as err:
        collect(FakeLLM(TextDelta("Hel")))
    assert err.value.kind == "truncated"

def test_chunk_after_usage_is_rejected():
    fake = FakeLLM(Usage(5, 2), TextDelta("late"))
    with pytest.raises(ProviderError) as err:
        collect(fake)
    assert err.value.kind == "protocol"

def test_sse_carries_tokens_then_usage(post_chat):
    fake = FakeLLM(TextDelta("Hel"), TextDelta("lo"), Usage(5, 2))
    resp = post_chat(fake)
    assert resp.status_code == 200
    assert parse_sse(resp.text) == [
        ("token", {"text": "Hel"}),
        ("token", {"text": "lo"}),
        ("usage", {"input_tokens": 5, "output_tokens": 2}),
    ]

def test_error_halfway_becomes_error_event(post_chat):
    fake = FakeLLM(
        TextDelta("Hel"),
        ProviderError("overloaded_error", "Overloaded"),
    )
    resp = post_chat(fake)
    assert resp.status_code == 200
    assert parse_sse(resp.text) == [
        ("token", {"text": "Hel"}),
        ("error", {"kind": "overloaded_error"}),
    ]
Enter fullscreen mode Exit fullscreen mode

The last test is the one you couldn't write before: a token arrives, the provider fails, the status is still 200, and the client gets a named error event with no raw message attached.

A test that keeps the SDKs out of the core

Boundaries rot one convenient import at a time. A short test makes this one mechanical:

# tests/test_boundary.py
import ast
from pathlib import Path

BANNED = {"anthropic", "openai", "fastapi", "httpx2"}

def test_core_imports_no_sdk():
    tree = ast.parse(Path("app/core.py").read_text())
    roots = set()
    for node in ast.walk(tree):
        if isinstance(node, ast.Import):
            roots |= {a.name.split(".")[0] for a in node.names}
        elif isinstance(node, ast.ImportFrom) and node.module:
            roots.add(node.module.split(".")[0])
    assert not roots & BANNED
Enter fullscreen mode Exit fullscreen mode

Run everything from the project root with python -m pytest, which puts the current directory on sys.path so import app resolves (add an empty app/__init__.py). Install with pip install "fastapi>=0.135" uvicorn httpx anthropic openai pytest; httpx is what TestClient runs on. I haven't run this suite myself. None of these tests talk to a live provider, and nothing in the suite needs one.


If this was useful

The move in this post (keep the model behind a port, let the core see only your own types, test the edges with a fake adapter) is the design idea behind Hexagonal Architecture in Python. The book isn't about LLMs: it builds one async FastAPI and SQLAlchemy 2 service five ways (Hexagonal, Clean, Onion, layered and vertical slice) and measures how each holds up, which is where the habit of drawing the boundary first comes from. Every listing runs from the free companion repo on GitHub, so you can read the code before you decide.

Hexagonal Architecture in Python by Gabriel Anhaia

Top comments (0)