03.10 Logging, Debugging and Testing LLM Code
When an ordinary function misbehaves, you set a breakpoint and step through it. When an LLM-powered feature misbehaves, there is nothing to step into: the "function" is a model on someone else's servers, it may answer differently each time, and each experiment costs money. What you can inspect is everything around the model: the exact request you sent, the exact response that came back, the retries and timings in between, and the code that parsed the result. This lesson teaches you to make that code observable (you can see what happened), debuggable (you can reproduce and explain a bad call) and testable (you can prove it works without a network, a key or a bill). It uses all four providers (OpenAI, Anthropic, Gemini and OpenRouter), and almost everything in it runs for free on your machine, because the techniques it teaches are the same ones this module uses to verify its own code without API keys.
What you'll learn
- Why "what did we actually send?" is the first question for almost every LLM bug, and four ways to answer it: the SDKs' debug logs, HTTP event hooks with fail-closed secret redaction, raw responses, and a wire capture that builds the request without sending it
- A debugging checklist for LLM API bugs (wrong model, missing system instruction, truncated history, dropped reasoning items, mis-threaded tool results, a stale SDK, silently ignored parameters, cache misses, unchecked finish reasons), each linked to the lesson that owns the fix
- Structured logging of every call: which fields to log (request IDs, model requested and served, API family, latency, time to first token, token counts in one convention across providers, cost, finish reason, retries, error class, feature, hashed user, prompt version, SDK version), what never to log by default, content logging behind a flag with redaction and sampling, correlation IDs, JSON logs with the standard
loggingmodule (andstructlog), and reusable wrappers for sync, async and streamed calls - The SDKs' built-in OpenTelemetry spans (Anthropic's
open_telemetryoption) and what the OpenTelemetry GenAI conventions are - How to reproduce a problem: storing the exact failing request, replaying it, running it N times because LLM behaviour is probabilistic, and logging the model version that actually served the call
- How to design code for testability: injected clients, pure functions for prompts and parsing, a
Protocolfor "something that completes a chat", and clients that are never built at import time - The testing toolbox from fastest to most realistic: unit tests, fake clients, mock transports under the real SDKs, record/replay cassettes, request snapshots, contract tests against a local stand-in, and live smoke tests with a spending cap
- The
respxtrap: why a "mocked"openaioranthropictest can silently call the real network now that both SDKs usehttpx2, and a guard that makes it impossible - Testing streams, retries and timeouts without waiting, structured output and tool calls (valid, invalid, refused and truncated fixtures, plus property-based tests with
hypothesis) - Static checks: letting
pyrightormypycatch misspelt SDK parameters before a request is ever sent - CI without keys (what runs on every push and what runs on a schedule, a GitHub Actions sketch, secrets in CI) and cost-safe development habits, including a disk cache for development
What you don't need
- Any API key. Every part runs without one: mock servers, recorded responses and a free local model (Ollama, for the OpenAI and Anthropic formats) stand in for the providers, and the two samples that call real APIs skip themselves when no key is set. Gemini has no local stand-in, so the Gemini samples are hosted-only or use mocks. Where a sample needs a key, it says so.
- Prior experience with
pytest. A one-paragraph refresher is in Part 7, and Module 01B teaches it properly. - Knowledge of how to judge whether an answer is good. That is evaluation, and it belongs to Module 10A. This lesson tests the code, not the model's wisdom.
Setup
You need Python 3.11+ (google-genai requires it) and uv. Unlike lessons 03.1 to 03.9, which share the llm-apis project, this lesson and 03.11 each start their own package in a new folder, so run uv init even if you already have llm-apis. If you've never created a project, lesson 03.1, Part 4 walks through it. The short version:
uv init llm-testing --bare --python 3.13 && cd llm-testing # --python matters: see lesson 03.1, 4.2
uv add openai anthropic google-genai python-dotenv tenacity structlog pydantic pyyaml httpx
uv add --dev pytest pytest-asyncio pytest-socket pytest-recording respx hypothesis pyright opentelemetry-sdk fastapi
# or, without uv: pip install the same package namesThe commands name the packages without versions, so you get the newest releases. The versions this lesson's samples were run with (the latest on PyPI when the module was written, November 2026) are openai 3.42.1, anthropic 2.4.0, google-genai 2.34.0, tenacity 9.1.4, pytest 9.2.0, pytest-asyncio 1.4.1.post1, pytest-socket 0.8.1, pytest-recording 0.14.1 (which brings vcrpy 9.4.2), respx 0.23.1, hypothesis 6.170.14, structlog 26.1.0, opentelemetry-sdk 1.45.2, pyright 1.1.414, fastapi 0.162.0 (only 4.4 uses it; its TestClient needs httpx, which is in the uv add line above: see the note below), pydantic 2.14.3 and pyyaml 6.0.3 (03.7's price table reads YAML). A newer major version of any of them may change a name or a default, so check its changelog if a sample does not match; the lockfile records exactly what you got, as 03.1 explains.
Keep the modules and numbered sample scripts in the project root and the test files in tests/ (1.4 shows the layout). The tests import the modules by name (from redact import ...), and uv run pytest does not put the project root on the import path by itself, so create a pytest.ini now with just these two lines (7.9 grows it into the full file):
[pytest]
pythonpath = .Real keys are optional. If you have them, put them in a .env file (never commit it, see 03.1, 3.4):
OPENAI_API_KEY=...
ANTHROPIC_API_KEY=...
GEMINI_API_KEY=...
OPENROUTER_API_KEY=...No keys? Install Ollama, run ollama pull qwen2.5:0.5b, and follow 03.1, Part 12. The "local model" samples here point the SDKs at http://localhost:11434. Gemini has no local stand-in (Ollama doesn't speak Gemini's API: 03.1, 12.4), so the Gemini samples are marked hosted-only and were not run; where this lesson needs Gemini behaviour without a key, it uses a mock. The default model names are gpt-6-luna, claude-haiku-5-5 and gemini-3.8-flash; Ollama answers to the first two because of ollama cp aliases, as 03.1 explains.
What you must be able to do after this lesson#
- Inspect the exact request and response of a failing call
- Follow a debugging checklist for LLM API bugs
- Log every call in a structured way
- Reproduce a problem
- Write tests for LLM code without real calls
- Run tests in CI without keys
- Test retries and streaming without waiting
Why this matters for an AI engineer#
LLM features fail in ways that are hard to see and expensive to guess about. The skills here turn "it's being weird" into a diagnosis.
| You'll hear... | You'll understand it after... |
|---|---|
| "The answers got worse after the deploy. Did the model change?" | 3.3 Compare two requests, 5.4 Which model actually answered |
| "What exactly did we send to the API?" | Part 2: Seeing what you sent and received |
| "Turn on debug logging." (and then a prompt shows up in the logs) | 2.1 The SDKs' own debug logs, 4.5 Content in logs |
| "Our test passed, but it called the real API." | 7.4 The respx trap |
| "Support wants the request ID." | 4.1 What to log, 4.4 Correlation IDs |
| "Can we reproduce that bad answer?" | Part 5: Reproducing a problem |
| "How do we unit-test code that calls an LLM?" | Part 6 and Part 7 |
| "The retry test takes 30 seconds." | Part 9: Testing retries and timeouts without waiting |
| "Snapshot tests keep failing because the model's wording changes." | 7.6 Snapshot the request, not the answer |
| "Record the API responses and replay them in CI." | 7.5 Record and replay |
| "Our CI has no API keys. What can it test?" | Part 12: CI without keys |
| "Dev used $40 of credits over a weekend." | Part 13: Cost-safe development habits |
| "pyright caught a typo in a parameter." | Part 11: Static checks |
| "Log the prompt too, just temporarily." | 4.5 Content in logs |
Part 1: Debugging LLM code starts with the request#
1.1 The first question: what did we actually send?#
Most "the model is acting strangely" reports turn out not to be about the model. Between your intention and the provider's server there are many places for the request to differ from what you believe you sent:
- the system prompt is empty because a config value didn't load in production;
- the history was trimmed too aggressively, so the model "forgot" the user's name;
- a model alias now points to a newer snapshot;
- a parameter was silently ignored (or, on Claude's current API version, rejected);
- a tool result was attached to the wrong tool call;
- the SDK is two versions behind the docs you read.
In every one of these, the model behaved correctly for the request it received. That's good news, because requests are just JSON, and JSON can be captured, diffed and tested. So the habit this lesson builds is simple: before you suspect the model, look at the request (Part 2), then at the response and the code that handled it (Parts 3 and 4).
1.2 What makes LLM code harder to debug and test#
| Difference | What it does to debugging and testing |
|---|---|
| Non-deterministic output (02.5, Part 7) | Asserting an exact answer is a flaky test. Test the shape of what comes back and the request you sent, and reproduce problems by running them N times (Part 5) |
| Every experiment costs money | Tests and debugging sessions need cheap models, hard output caps, spending limits and caches (Part 13) |
| Calls are slow (seconds, sometimes minutes) | Retry and timeout tests must not really wait (Part 9) |
| Failures arrive inside successful responses (03.8, Part 10) | "No exception" is not "it worked". Log the finish reason and test refusal and truncation fixtures (Parts 4, 7 and 10) |
| Parameters can be silently ignored | A local server or a different model may accept a parameter and do nothing. A passing run proves less than it looks (Part 7.7) |
| The inputs are sensitive | Prompts hold personal data, secrets and business content. The log you write to debug today is a data-protection problem next year (Part 4) |
| Providers change under you | Aliases move, defaults change, SDK versions shift. Log versions; lock them; run a small live check on a schedule (Parts 5.4 and 7.8) |
1.3 What this lesson covers, and what it leaves to later modules#
There are three different questions people mean by "testing an LLM application", and different modules own them:
- Is my code right? Does it build the request I think it builds, parse every shape of response, retry correctly, and survive refusals and truncation? That's this lesson: unit tests, fakes, mocks, recordings, snapshots, contract tests and live smoke tests.
- Is the model's output good? Is it accurate, helpful, on-brand, safe? That needs datasets, metrics and judges: Module 10A: Evaluation.
- What is happening in production? Traces, dashboards, alerts, cost analytics, prompt versioning and deployment pipelines: Modules 11A to 11C. This lesson ends where those platforms begin, at a well-structured log line and a few OpenTelemetry spans.
flowchart LR
subgraph here ["This lesson: is the CODE right?"]
direction TB
U["1 Unit tests<br/>pure functions"] --> F["2 Fake clients<br/>scripted ChatModel"]
F --> M["3 Mock transports<br/>real SDK, fake network"]
M --> R["4 Record / replay<br/>cassettes"]
R --> S["5 Snapshots<br/>of requests"]
S --> C["6 Contract tests<br/>local stand-in"]
C --> L["7 Live smoke tests<br/>real APIs, tiny"]
end
subgraph m10 ["Module 10A: is the ANSWER good?"]
E["Evals, datasets, judges"]
end
subgraph m11 ["Modules 11A to 11C: what happens in PRODUCTION?"]
O["Tracing platforms, dashboards, CI/CD for prompts"]
end
L -.->|"quality questions"| E
L -.->|"live traffic"| OTwo neighbours deserve a mention. Personal data in prompts and logs, prompt injection and key leaks are Module 12's subjects; this lesson shows the logging side (what to keep out, how to redact) and links there for the rest. And per-call error handling, retries and timeouts are lesson 03.8; here you learn to test them.
1.4 The project you'll build#
Every sample in this lesson belongs to one small project, so the parts fit together. Its job is a plausible one: triage a customer-support ticket (is it about billing, a bug, how-to, or something else, and is it urgent?) by asking a model for a tiny JSON answer. The prompt is deliberately dull, because the point is the engineering around it.
llm-testing/
├── pyproject.toml # dependencies (Setup above)
├── pytest.ini # markers, --disable-socket, asyncio mode (7.7, 7.8)
├── pyrightconfig.json # the type checker's settings (11.3)
├── cost_calc.py prices.py prices_fake_local.yaml # copied from lesson 03.7 (3.6, 4.3): one Usage shape, FAKE local prices
├── chat_types.py # Completion, the ChatModel Protocol, the trace-ID variable (1.5)
├── adapters.py # one thin class per SDK, all returning Completion (1.5)
├── triage.py triage_strategies.py # the business code under test; its test generators (3.4, Part 6, 10)
├── llm_log.py llm_log_async.py # structured call logs (sync, async, streams) (Part 4)
├── fixtures_inline.py # a scripted Completion for samples that need no client (4.6)
├── wire_log.py redact.py # HTTP event hooks with fail-closed redaction; the shared scrubber (Part 2)
├── wire_capture.py request_diff.py request_summary.py captured_adapters.py # (Part 2, 3)
├── repro.py # save and replay the exact failing request (Part 5)
├── streamer.py # stream a reply and time it (Part 8)
├── toolargs.py # tool-call argument checks (Part 10)
├── check_response.py # copied from lesson 03.8, 10.2 (Part 10)
├── devcache.py # a development response cache (Part 13)
├── s2_1_debug_openai.py ... s13_dev_cache.py # the numbered demo scripts: the file name is the first line of each listing
└── tests/
├── conftest.py fakes.py fixtures.py mocks.py sse_fixtures.py snapshot.py # test helpers
└── test_*.py # one file per technique (Parts 5 to 10, 12)Every listing in this lesson starts with a comment giving the file name to save it as, and the exercises refer to files by those names. Two things are not written here, because lessons 03.7 and 03.8 own them: cost_calc.py and prices.py (03.7, 3.6 and 4.3), with a small price file whose rates are fake (prices_fake_local.yaml, listed in 03.7, 5.3), and check_response.py (03.8, 10.2). Copy them next to the other files. triage.py is listed in 3.4, where a sample first imports it, and explained in Part 6.
1.5 The code we'll instrument: one Completion, four adapters#
Logs, tests and reproductions all need something concrete to point at. The project has one very small abstraction, which lesson 03.11 later grows into a full provider-agnostic client. Business code asks a ChatModel for a Completion; a thin adapter per API family translates the SDK's response into that Completion. Save these as chat_types.py and adapters.py:
# chat_types.py
"""chat_types.py: the small interface the rest of the app depends on (lesson 03.11 grows it into a full client)."""
from __future__ import annotations
import uuid
from contextvars import ContextVar
from dataclasses import dataclass
from typing import Literal, Protocol, TypedDict
from cost_calc import Usage # lesson 03.7 (3.1): the module's one usage shape
# One id per request through your own system. Adapters send it to the provider where a header allows,
# and the log wrapper writes it on every line, so one search finds everything about a request.
trace_id_var: ContextVar[str | None] = ContextVar("trace_id", default=None)
def new_trace_id() -> str:
return uuid.uuid4().hex
class Message(TypedDict):
role: Literal["user", "assistant"]
content: str
@dataclass
class Completion:
text: str
outcome: Literal["ok", "truncated", "refused"] # what the model's answer is worth to the app
finish_reason: str | None # the provider's own word, kept for logs
model: str | None # the model that actually served the call (may differ from the alias asked for)
request_id: str | None # the provider's id: the first thing support asks for
# Token counts follow the module convention (lesson 03.7, 3.1), whatever the provider's raw fields mean.
# `usage` is None when the provider did not report any: unknown is never zero.
usage: Usage | None = None
attempts: int = 1 # HTTP attempts the SDK made (1 = no retries)
cost_usd: float | None = None # filled by the logging wrapper when it has a price function
# The log record's token fields. They are views of `usage`, so the log and the cost maths cannot disagree.
@property
def uncached_input_tokens(self) -> int | None: # billed at the plain input rate (NOT the provider's raw field)
return self.usage.input if self.usage else None
@property
def cached_input_tokens(self) -> int | None: # input served from the cache (cache reads)
return self.usage.cached_input if self.usage else None
@property
def cache_write_tokens(self) -> int | None: # input written to the cache, all lifetimes added up
return sum(self.usage.cache_writes.values()) if self.usage else None
@property
def output_tokens(self) -> int | None: # visible text PLUS reasoning/thinking tokens
return self.usage.output if self.usage else None
@property
def reasoning_tokens(self) -> int | None: # informational: already inside output_tokens
return self.usage.reasoning if self.usage else None
@property
def total_input_tokens(self) -> int | None: # every prompt token: uncached + cached + written
return self.usage.total_input if self.usage else None
class ChatModel(Protocol):
"""Anything that answers a chat. Business code depends on this, never on an SDK class."""
def complete(self, system: str, messages: list[Message], *, max_tokens: int,
user: str | None = None) -> Completion: ...
class AsyncChatModel(Protocol):
"""The same seam for async code (03.9): `await chat.complete(...)`."""
async def complete(self, system: str, messages: list[Message], *, max_tokens: int,
user: str | None = None) -> Completion: ...Three details matter for everything that follows. First, None means "the provider didn't say", never 0: a log or a cost report that turns missing usage into zero makes your numbers lie in exactly the cases you most need to see. Second, the token fields follow the module's convention, not each provider's. The providers disagree about what their input number means (OpenAI, Gemini and OpenRouter include cached tokens in it; Anthropic leaves them out), so Completion carries a 03.7 Usage object, built by that lesson's cost_calc.from_* functions, and exposes it as flat fields: uncached_input_tokens (billed at the plain input rate), cached_input_tokens, cache_write_tokens, total_input_tokens (the sum of those three) and output_tokens, which includes reasoning tokens (reasoning_tokens is informational, a part of it). One rule, one place: this lesson never re-implements the arithmetic, it calls 03.7. Third, outcome captures the three things your application needs to know about a 200 OK answer (usable, cut off, refused), while finish_reason keeps the provider's own word for the log. Lesson 03.8, Part 10 covers the full catalogue of "success that isn't"; the adapters implement the common cases.
# adapters.py
"""adapters.py: one thin class per SDK, each returning the same Completion.
The client is INJECTED, so tests can hand in a client with a mock transport (lesson 03.10).
Token counts are read by lesson 03.7's cost_calc.from_* functions, so every provider's usage ends up
in the module's one convention: input = UNCACHED input, plus cached and cache-write counts."""
from __future__ import annotations
import logging
from collections.abc import Callable
import anthropic
import openai
from anthropic import Anthropic
from anthropic.types import Message as ClaudeMessage
from anthropic.types import MessageParam
from google import genai
from google.genai import types
from openai import AsyncOpenAI, OpenAI
from openai.types.chat import ChatCompletion, ChatCompletionMessageParam
from openai.types.responses import EasyInputMessageParam, Response
import cost_calc
from chat_types import Completion, Message, trace_id_var
log = logging.getLogger("llm.adapters")
def _usage(read: Callable[[], cost_calc.Usage]) -> cost_calc.Usage | None:
"""cost_calc raises ValueError when a response has no usage (or a tier it can't price). That is
'unknown', and unknown is never zero: the Completion gets usage=None and the log says null."""
try:
return read()
except ValueError as exc:
log.warning("usage unknown: %s", exc)
return None
def _chat_messages(system: str, messages: list[Message]) -> list[ChatCompletionMessageParam]:
"""Our two-role messages as Chat Completions messages. The explicit branches keep pyright happy."""
out: list[ChatCompletionMessageParam] = [{"role": "system", "content": system}]
for m in messages:
out.append({"role": "user", "content": m["content"]} if m["role"] == "user"
else {"role": "assistant", "content": m["content"]})
return out
def _claude_messages(messages: list[Message]) -> list[MessageParam]:
return [{"role": "user", "content": m["content"]} if m["role"] == "user"
else {"role": "assistant", "content": m["content"]} for m in messages]
# --- response -> Completion: pure functions, so streams and tests can reuse them -------------------------------
def completion_from_responses(r: Response, *, request_id: str | None, attempts: int = 1) -> Completion:
refusal = any(part.type == "refusal" for item in r.output if item.type == "message" for part in item.content)
reason = r.incomplete_details.reason if r.incomplete_details else None
outcome = "refused" if refusal else "truncated" if r.status == "incomplete" else "ok"
return Completion(
text=r.output_text, outcome=outcome, finish_reason=f"{r.status}:{reason}" if reason else r.status,
model=r.model, request_id=request_id, attempts=attempts,
usage=_usage(lambda: cost_calc.from_openai_response(r)))
def completion_from_chat(r: ChatCompletion, *, request_id: str | None, attempts: int = 1,
openrouter: bool = False) -> Completion:
choice = r.choices[0]
outcome = "refused" if choice.message.refusal else "truncated" if choice.finish_reason == "length" else "ok"
read = cost_calc.from_openrouter if openrouter else cost_calc.from_openai_chat
return Completion(
text=choice.message.content or "", outcome=outcome, finish_reason=choice.finish_reason, model=r.model,
request_id=request_id, attempts=attempts, usage=_usage(lambda: read(r)))
def completion_from_claude(m: ClaudeMessage, *, request_id: str | None, attempts: int = 1) -> Completion:
text = "".join(b.text for b in m.content if b.type == "text") # skip thinking blocks
outcome = "refused" if m.stop_reason == "refusal" else "truncated" if m.stop_reason == "max_tokens" else "ok"
return Completion(text=text, outcome=outcome, finish_reason=m.stop_reason, model=m.model, request_id=request_id,
attempts=attempts, usage=_usage(lambda: cost_calc.from_anthropic(m)))
def completion_from_gemini(r: types.GenerateContentResponse, *, model: str) -> Completion:
cand = r.candidates[0] if r.candidates else None
finish = cand.finish_reason.value if cand and cand.finish_reason else None
blocked = bool(r.prompt_feedback and r.prompt_feedback.block_reason) or finish in {"SAFETY", "PROHIBITED_CONTENT"}
outcome = "refused" if blocked else "truncated" if finish == "MAX_TOKENS" else "ok"
return Completion(text=r.text or "", outcome=outcome, finish_reason=finish, model=r.model_version,
request_id=r.response_id, usage=_usage(lambda: cost_calc.from_gemini(r, model)))
# --- the adapters ----------------------------------------------------------------------------------------------
class OpenAIResponsesChat:
"""OpenAI Responses API. Also serves Ollama's /v1 endpoint, which speaks the same format."""
def __init__(self, client: OpenAI, model: str) -> None:
self.client, self.model = client, model
def complete(self, system: str, messages: list[Message], *, max_tokens: int, user: str | None = None) -> Completion:
trace = trace_id_var.get()
raw = self.client.responses.with_raw_response.create(
model=self.model, instructions=system,
input=[EasyInputMessageParam(role=m["role"], content=m["content"]) for m in messages],
max_output_tokens=max_tokens, safety_identifier=user or openai.omit,
# OpenAI echoes nothing back, but support can match this id against their own logs
extra_headers={"X-Client-Request-Id": trace} if trace else {})
return completion_from_responses(raw.parse(), request_id=raw.request_id, attempts=raw.retries_taken + 1)
class AsyncOpenAIResponsesChat:
"""The same adapter for AsyncOpenAI: `await chat.complete(...)`. It satisfies AsyncChatModel (lesson 03.9 builds on it)."""
def __init__(self, client: AsyncOpenAI, model: str) -> None:
self.client, self.model = client, model
async def complete(self, system: str, messages: list[Message], *, max_tokens: int, user: str | None = None) -> Completion:
trace = trace_id_var.get()
raw = await self.client.responses.with_raw_response.create(
model=self.model, instructions=system,
input=[EasyInputMessageParam(role=m["role"], content=m["content"]) for m in messages],
max_output_tokens=max_tokens, safety_identifier=user or openai.omit,
extra_headers={"X-Client-Request-Id": trace} if trace else {})
return completion_from_responses(raw.parse(), request_id=raw.request_id, attempts=raw.retries_taken + 1)
class ChatCompletionsChat:
"""Chat Completions: OpenAI itself, OpenRouter (base_url=https://openrouter.ai/api/v1), Ollama, and more."""
def __init__(self, client: OpenAI, model: str, *, openrouter: bool = False) -> None:
self.client, self.model, self.openrouter = client, model, openrouter
def complete(self, system: str, messages: list[Message], *, max_tokens: int, user: str | None = None) -> Completion:
raw = self.client.chat.completions.with_raw_response.create(
model=self.model,
messages=_chat_messages(system, messages),
max_completion_tokens=openai.omit if self.openrouter else max_tokens,
max_tokens=max_tokens if self.openrouter else openai.omit, # OpenRouter's documented name
# OpenAI: `user` is deprecated in favour of `safety_identifier`. OpenRouter still reads `user` (up to 128 characters)
safety_identifier=openai.omit if self.openrouter else (user or openai.omit),
user=(user or openai.omit) if self.openrouter else openai.omit)
# OpenRouter keeps its own generation id in a header; OpenAI uses x-request-id
request_id = raw.headers.get("x-generation-id") if self.openrouter else raw.request_id
return completion_from_chat(raw.parse(), request_id=request_id, attempts=raw.retries_taken + 1,
openrouter=self.openrouter)
class AnthropicChat:
def __init__(self, client: Anthropic, model: str) -> None:
self.client, self.model = client, model
def complete(self, system: str, messages: list[Message], *, max_tokens: int, user: str | None = None) -> Completion:
raw = self.client.messages.with_raw_response.create(
model=self.model, system=system, max_tokens=max_tokens,
messages=_claude_messages(messages),
metadata={"user_id": user} if user else anthropic.omit) # an opaque id, never an email
return completion_from_claude(raw.parse(), request_id=raw.request_id, attempts=raw.retries_taken + 1)
class GeminiChat:
"""Gemini generate_content. (The Interactions API has a different shape: lesson 03.1.)"""
def __init__(self, client: genai.Client, model: str) -> None:
self.client, self.model = client, model
def complete(self, system: str, messages: list[Message], *, max_tokens: int, user: str | None = None) -> Completion:
contents = [types.Content(role="model" if m["role"] == "assistant" else "user",
parts=[types.Part(text=m["content"])]) for m in messages]
r = self.client.models.generate_content(
model=self.model, contents=contents,
config=types.GenerateContentConfig(
system_instruction=system, max_output_tokens=max_tokens,
# Google's documented key for end-user ids; label values are at most 63 characters (03.2, 9.1)
labels={"safety_identifier": user[:63]} if user else None))
return completion_from_gemini(r, model=self.model)Where each Completion field comes from, as of November 2026 (the shapes are the ones in lesson 03.1, Part 8; 03.7 explains the usage buckets and the one conversion rule, total_input = uncached + cached + written):
Completion field |
OpenAI Responses | Chat Completions (OpenAI, OpenRouter) | Anthropic Messages | Gemini generate_content |
|---|---|---|---|---|
text |
response.output_text |
choices[0].message.content |
the text blocks of content |
response.text |
| refused | a refusal part inside a message output item |
choices[0].message.refusal |
stop_reason == "refusal" |
a blocked prompt (prompt_feedback.block_reason) or finish reason SAFETY / PROHIBITED_CONTENT |
| truncated | status == "incomplete" (reason max_output_tokens) |
finish_reason == "length" |
stop_reason == "max_tokens" |
finish reason MAX_TOKENS |
model (served) |
response.model |
response.model |
message.model |
response.model_version |
request_id |
x-request-id header |
x-request-id (OpenAI) or x-generation-id (OpenRouter) |
request-id header |
none: the closest is response.response_id |
| raw usage fields | usage.input_tokens (includes cached and written), output_tokens (includes reasoning) |
usage.prompt_tokens (includes cached and written), completion_tokens (includes reasoning) |
usage.input_tokens (excludes cache reads and writes), cache_read_input_tokens, cache_creation_input_tokens, output_tokens (includes thinking) |
usage_metadata.prompt_token_count (includes cached), cached_content_token_count, candidates_token_count (excludes thoughts), thoughts_token_count |
uncached_input_tokens |
input_tokens - cached - written |
prompt_tokens - cached - written |
input_tokens as is |
prompt_token_count - cached (plus tool-use prompt tokens) |
output_tokens |
output_tokens |
completion_tokens |
output_tokens |
candidates_token_count + thoughts_token_count |
attempts |
raw.retries_taken + 1 |
raw.retries_taken + 1 |
raw.retries_taken + 1 |
1: models.* doesn't retry unless you configure it (03.8, 5.2) |
reasoning_tokens (informational) |
output_tokens_details.reasoning_tokens |
completion_tokens_details.reasoning_tokens |
output_tokens_details.thinking_tokens when the response includes it; otherwise inside output_tokens and not broken out |
thoughts_token_count |
A few choices in the adapters are worth explaining:
- The client is a constructor argument. The adapter never builds an SDK client. That one decision is what makes every test technique in Parts 7 to 10 possible (Part 6).
with_raw_responsegives both the parsed object and the HTTP details (request ID, retry count) in one call (03.1, 8.5). Thecompletion_from_*functions turn a parsed response into aCompletion, so a streamed call (4.9) reuses them with the stream's final message. Gemini's Interactions API needs different code and is left out here.useris already hashed by the time an adapter sees it (Part 4 does the hashing, with the provider-facing purpose"llm-abuse-v1"from 03.2, 10.3; the value in your log line uses a different purpose, so the two can't be matched). OpenAI (Responses and Chat Completions) receives it assafety_identifier; theuserfield is deprecated there. Anthropic gets it asmetadata.user_id, OpenRouter asuser, and Geminigenerate_contentaslabels["safety_identifier"], truncated to 63 characters (03.2, 9.1).- The
X-Client-Request-Idheader is sent to OpenAI when your code has set a trace ID (Part 4.4). - No sampling parameters, per the module conventions (02.5, Part 6).
- Retries stay with the SDK. The clients you inject decide
max_retries, so tests can set it to0or1and production can choose its own policy (03.8, 5.5). - The explicit
if role == "user"branches in the message helpers look fussy, but the SDKs' message parameters areTypedDictunions, and a type checker (Part 11) only accepts a literal"user"or"assistant"it can see.
Part 2: Seeing what you sent and received#
There are five ways to look at an LLM call, from the cheapest to the most exact. Use the cheapest one that answers your question.
| Tool | You get | Costs you | Safe to leave on in production? |
|---|---|---|---|
| SDK debug logs (2.1) | Request line, status, request ID, retry decisions; with Anthropic, the whole request body too | One environment variable | openai: mostly. anthropic: no (it logs your prompt) |
| Python loggers (2.2) | The same, switchable per library from code | A few lines of logging config |
The HTTP-library INFO line, yes |
| HTTP event hooks (2.3) | Every attempt's method, URL, redacted headers, body size and hash, response status and rate-limit headers, all as data | About 100 lines (wire_log.py) |
Yes, with the default (no body), if the redaction stays under test: a hook log is only as safe as its allow-list |
| Raw responses (2.4) | The response headers and status, per call | A different method call | Yes |
| Wire capture (2.5) | The exact request the SDK would send, as an object, with nothing sent | A mock transport | It's for tests and debugging, not for production |
2.1 The SDKs' own debug logs#
openai and anthropic read an environment variable when the package is imported and, if it's set, turn on their own logger. Set it before the process starts (setting it after import openai does nothing):
| SDK | Variable | Values | What it enables |
|---|---|---|---|
openai |
OPENAI_LOG |
debug, info, warning, error, critical |
The openai logger only |
anthropic |
ANTHROPIC_LOG |
debug, info |
The anthropic logger and the httpx2 logger |
google-genai |
none | Nothing: use the logging module (2.2) |
Try it on the free local model. The two scripts are the whole programs; the only difference from normal code is how you run them:
# s2_1_debug_openai.py
"""Run with OPENAI_LOG=debug to see the openai SDK's own debug log. Targets the free local model."""
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama") # local stand-in, no real key
response = client.responses.create(model="gpt-6-luna", input="Say hi in two words.", max_output_tokens=10)
print("text:", response.output_text)OPENAI_LOG=debug uv run python s2_1_debug_openai.py[2026-11-04 11:29:15 - openai._base_client:606 - DEBUG] Building HTTP request: method=POST retries_taken=0
[2026-11-04 11:29:15 - openai._base_client:1179 - DEBUG] Sending HTTP Request: POST
[2026-11-04 11:29:15 - openai._base_client:1220 - DEBUG] HTTP Response: POST 200
[2026-11-04 11:29:15 - openai._base_client:1225 - DEBUG] request_id: None
text: Hello, how are you?Four lines, and they're informative: this was attempt zero (retries_taken=0), the method, the status, and the request ID, which is None because Ollama sends none (a hosted OpenAI response would show its x-request-id value here). Notice what's missing: no URL, no headers, no body. That is deliberate. The SDK's source says its switch doesn't turn on the HTTP library's logger, because those "may include complete URLs", and leaves that choice to the application. The SDK also installs a filter that replaces api-key, authorization and x-amz-security-token with <redacted> in any log record that carries headers.
Now the same for Anthropic:
# s2_1_debug_anthropic.py
"""Run with ANTHROPIC_LOG=debug to see the anthropic SDK's own debug log. Targets the free local model."""
import anthropic
client = anthropic.Anthropic(base_url="http://localhost:11434", api_key="ollama") # local stand-in
message = client.messages.create(model="claude-haiku-5-5", max_tokens=10,
messages=[{"role": "user", "content": "Say hi in two words."}])
print("text:", message.content[0].text if message.content[0].type == "text" else "")ANTHROPIC_LOG=debug uv run python s2_1_debug_anthropic.py[2026-11-04 11:29:16 - anthropic._base_client:602 - DEBUG] Request options: {'method': 'post', 'url': '/v1/messages', 'headers': {}, 'timeout': {'connect': 5.0, 'read': 600, 'write': 600, 'pool': 600}, 'files': None, 'idempotency_key': 'stainless-python-retry-6fb194c1-30a0-41de-97cb-0a4d90ef24ac', 'span_name': 'anthropic.messages.create', 'span_route': '/v1/messages', 'span_attributes': <function Messages.create.<locals>.<lambda> at 0x108a9f920>, 'content': None, 'json_data': {'max_tokens': 10, 'messages': [{'role': 'user', 'content': 'Say hi in two words.'}], 'model': 'claude-haiku-5-5'}}
[2026-11-04 11:29:16 - anthropic._base_client:1432 - DEBUG] Sending HTTP Request: POST http://localhost:11434/v1/messages
[2026-11-04 11:29:16 - httpx2:1084 - INFO] HTTP Request: POST http://localhost:11434/v1/messages "HTTP/1.1 200 OK"
[2026-11-04 11:29:16 - anthropic._base_client:1455 - DEBUG] HTTP Response: POST http://localhost:11434/v1/messages "200 OK" Headers({'content-type': 'application/json', 'date': 'Wed, 04 Nov 2026 05:59:16 GMT', 'content-length': '219'})
[2026-11-04 11:29:16 - anthropic._base_client:1463 - DEBUG] request_id: None
[2026-11-04 11:29:16 - anthropic._base_client:1464 - DEBUG] workspace_id: None
text: Hi there!This one shows far more, which is useful and dangerous in equal measure. (Ignore the odd-looking <function Messages.create.<locals>.<lambda> at 0x...> and span_name entries: they are SDK internals, and the exact memory address will differ on your machine.) You see the full URL, the effective timeouts (connect: 5.0, read: 600), the response headers, and the request and workspace IDs (None locally). And look at the first line: 'json_data': {... 'messages': [{'role': 'user', 'content': 'Say hi in two words.'}] ...}. At debug level the Anthropic SDK logs your entire request body, which means every prompt, every document you attached and every piece of personal data in them.
Debug logs also explain what the SDK is doing behind your back, which is exactly what you need when a call takes too long. This script sets the same logger from code and points the SDK at a mock server that answers 429 and then 200:
# s2_1c_debug_retries.py
"""The SDKs' debug logs explain their RETRY decisions. A MOCK server answers 429, then 200.
(Same effect as OPENAI_LOG=debug / ANTHROPIC_LOG=debug, but set from code so the sample is self-contained.)"""
import logging
import sys
import httpx2
import openai
logging.basicConfig(stream=sys.stdout, level=logging.WARNING, format="%(name)s %(levelname)s %(message)s")
logging.getLogger("openai").setLevel(logging.DEBUG)
replies = iter([httpx2.Response(429, json={"error": {"message": "Rate limit reached", "type": "rate_limit_error"}},
headers={"retry-after-ms": "5", "x-request-id": "req_a"}),
httpx2.Response(200, json={"id": "resp_1", "object": "response", "status": "completed", "model": "gpt-6-luna",
"output": []}, headers={"x-request-id": "req_b"})])
client = openai.OpenAI(api_key="sk-test", max_retries=2,
http_client=httpx2.Client(transport=httpx2.MockTransport(lambda request: next(replies))))
print("--- openai: a 429, then a 200 ---")
client.responses.create(model="gpt-6-luna", input="Hi")--- openai: a 429, then a 200 ---
openai._base_client DEBUG Building HTTP request: method=POST retries_taken=0
openai._base_client DEBUG Sending HTTP Request: POST
openai._base_client DEBUG HTTP Response: POST 429
openai._base_client DEBUG request_id: req_a
openai._base_client DEBUG Encountered an HTTP status error: 429
openai._base_client DEBUG Retrying due to status code 429
openai._base_client DEBUG 2 retries left
openai._base_client INFO Retrying request in 0.005000 seconds (retry 1 of 2)
openai._base_client DEBUG Building HTTP request: method=POST retries_taken=1
openai._base_client DEBUG Sending HTTP Request: POST
openai._base_client DEBUG HTTP Response: POST 200
openai._base_client DEBUG request_id: req_bRead it top to bottom: the first attempt got a 429, the SDK decided "Retrying due to status code 429", waited the 5 ms the server asked for through retry-after-ms (03.8, 5.1), and retries_taken=1 shows the second attempt. Each attempt has its own request_id (req_a, then req_b), so when you report a problem you can say which attempt failed. If someone tells you "the API takes 30 seconds", these lines show whether that's one slow call or three fast failures with waits between them.
2.2 Python's logging loggers#
All three SDKs use the standard library logging module, so you can control them from code. These are the logger names that matter, verified in the versions named in Setup:
| Logger | Whose | What it logs |
|---|---|---|
openai (and openai._base_client) |
openai |
Request building, sending, status, request ID, retry decisions |
anthropic (and anthropic._base_client) |
anthropic |
The same, plus request options including the body (see above) |
httpx2 |
the HTTP library under openai and anthropic |
One INFO line per request: HTTP Request: POST <url> "HTTP/1.1 200 OK" |
httpx |
the HTTP library under google-genai |
The same INFO line |
httpcore2, httpcore |
the layer below each | Connection and TLS events at DEBUG (very noisy; for network problems only) |
google_genai and its children (google_genai.models, google_genai._api_client, ...) |
google-genai |
Mostly INFO messages about automatic function calling, plus rare DEBUG messages |
Turn on what you need, and leave the rest quiet:
# s2_2_logging_loggers.py
"""Turn on SDK and HTTP-library loggers with the standard logging module (no env vars).
Runs openai against the free local stand-in (Ollama). google-genai is imported only so that its
loggers are registered: Gemini has no local stand-in, so no Gemini call is made here."""
import logging
import sys
from google import genai # noqa: F401 (imported so the google_genai loggers exist)
from openai import OpenAI
logging.basicConfig(stream=sys.stdout, level=logging.WARNING, # everything else stays quiet
format="%(levelname)-5s %(name)s: %(message)s")
for name in ("openai", "httpx2", "google_genai", "httpx"): # the loggers worth knowing
logging.getLogger(name).setLevel(logging.DEBUG)
print("--- openai (Responses) ---")
oai = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
oai.responses.create(model="gpt-6-luna", input="Hi", max_output_tokens=5)
print("--- loggers that exist after these calls ---")
print(sorted(n for n in logging.root.manager.loggerDict
if n.split(".")[0] in {"openai", "anthropic", "httpx", "httpx2", "httpcore", "httpcore2", "google_genai"}))Output (local model qwen2.5:0.5b via Ollama; illustrative: the logger list was carried over from a run that also imported the Gemini SDK and was not re-run):
--- openai (Responses) ---
DEBUG openai._base_client: Building HTTP request: method=POST retries_taken=0
DEBUG openai._base_client: Sending HTTP Request: POST
INFO httpx2: HTTP Request: POST http://localhost:11434/v1/responses "HTTP/1.1 200 OK"
DEBUG openai._base_client: HTTP Response: POST 200
DEBUG openai._base_client: request_id: None
--- loggers that exist after these calls ---
['google_genai', 'google_genai._api_client', 'google_genai._common', 'google_genai._transformers', 'google_genai.batches', 'google_genai.caches', 'google_genai.chats', 'google_genai.documents', 'google_genai.files', 'google_genai.filesearchstores', 'google_genai.live', 'google_genai.live_music', 'google_genai.models', 'google_genai.operations', 'google_genai.tokens', 'google_genai.tunings', 'google_genai.types', 'httpcore', 'httpcore.connection', 'httpcore.http11', 'httpcore.proxy', 'httpcore2', 'httpcore2.connection', 'httpcore2.http11', 'httpcore2.proxy', 'httpx', 'httpx2', 'openai', 'openai._base_client', 'openai._legacy_response', 'openai._response', 'openai.lib', 'openai.lib.parsing', 'openai.resources', 'openai.resources.responses', 'openai.resources.responses.responses']What to notice:
- The
httpx2/httpxINFO line is the cheapest "what URL did we call?" tool that works for all three SDKs. It prints the full URL, so make sure URLs in your setup never contain secrets (old Gemini REST examples put the key in?key=; the SDK now sendsx-goog-api-keyas a header). google-genaihas little to say on its own. Its INFO messages are mostly about automatic function calling (03.5), unrelated to your request, and the Gemini call isn't in this local sample (no stand-in). For Gemini, the HTTP-library logger (httpx) and event hooks (next) are the real tools.- The last line lists the loggers that existed after these calls, so you can see the namespace for yourself.
logging.root.manager.loggerDictis the quickest way to answer "what can I turn on?" for any library. httpcoreandhttpcore2are for network debugging only. At DEBUG they log every connection step, which is the right tool for "is it DNS, TLS or the proxy?" and the wrong tool for anything else.
2.3 HTTP event hooks: the wire as data, with secrets redacted#
Debug logs are text written by someone else. An event hook is a function you register on the HTTP client; it receives every request just before it's sent and every response just after it arrives, as objects, so you decide what to log and what to hide. Hooks run for each HTTP attempt, retries included, which makes them the best place to count attempts and see per-attempt status codes.
Both httpx and httpx2 support event_hooks={"request": [...], "response": [...]}. All three SDKs let you hand them a configured client, and each has a way to keep its own defaults (timeouts, connection limits, redirects) while you add the hooks:
| SDK | How to attach hooks | Why this form |
|---|---|---|
openai |
OpenAI(http_client=openai.DefaultHttpx2Client(event_hooks=...)) |
DefaultHttpx2Client keeps the SDK's defaults |
anthropic |
Anthropic(http_client=anthropic.DefaultHttpxClient(event_hooks=...)) |
Despite the name, it builds an httpx2 client in 2.x |
google-genai |
HttpOptions(client_args={"event_hooks": ...}) |
client_args are passed to the httpx.Client the SDK builds, so its defaults stay (in 3.x the client it builds is an httpx2 one; hooks work the same way) |
The scrubbing itself lives in one small module that this part and Part 4 share, redact.py. It needs only re, so save it now even though its personal-data patterns matter most once we log content in 4.5. redact_secrets() knows credential shapes — safe to run on headers, URLs and free text — and redact_text() adds emails, card and phone numbers for free text such as prompts and replies.
# redact.py
"""redact.py: best-effort scrubbing of text before it reaches a log. A safety net, not a guarantee (Module 12).
Two layers: redact_secrets() for credential shapes (safe to run on headers and URLs too) and redact_text(),
which adds personal data (emails, cards, phone numbers) for free text such as prompts and replies."""
import re
# Credential shapes. Each prefix is a vendor's convention as of November 2026: keep this list under test.
SECRET_PATTERNS: list[tuple[str, re.Pattern[str]]] = [
("JWT", re.compile(r"\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}")), # three base64url parts
("API_KEY", re.compile(
r"(?<![A-Za-z0-9_-])(?:"
r"sk-(?:ant-|or-v1-|or-|proj-)?[A-Za-z0-9_-]{16,}" # OpenAI, Anthropic, OpenRouter
r"|AIza[0-9A-Za-z_-]{30,}" # Google API keys (Gemini)
r"|ya29\.[A-Za-z0-9_-]{20,}" # Google OAuth access tokens
r"|gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{30,}" # GitHub tokens
r"|xai-[A-Za-z0-9]{20,}" # xAI
r"|gsk_[A-Za-z0-9]{20,}" # Groq
r"|hf_[A-Za-z0-9]{20,}" # Hugging Face
r"|(?:AKIA|ASIA)[0-9A-Z]{16}" # AWS access key IDs
r")")),
("BEARER", re.compile(r"(?i)\bbearer\s+[A-Za-z0-9._\-]{12,}")),
]
# "password: hunter2", "api_key=...", '"token": "..."': keep the name, hide the value.
SECRET_KV = re.compile(r"""(?i)\b(password|passwd|secret|api[_-]?key|access[_-]?token|token)(["']?\s*[:=]\s*["']?)(?!<redacted>|\[[A-Z_]+\])([^\s"',;&]{4,})""")
PII_PATTERNS: list[tuple[str, re.Pattern[str]]] = [
("EMAIL", re.compile(r"\b[\w.+-]+@[\w-]+(?:\.[\w-]+)+\b")),
("SSN", re.compile(r"\b\d{3}-\d{2}-\d{4}\b")), # US social security number shape
("CARD", re.compile(r"\b\d(?:[ -]?\d){12,18}\b")), # long digit runs: card numbers, account numbers
]
# Phone numbers: either "+<country code> ..." or digit groups SEPARATED by spaces or dashes. A bare run of digits
# (an order number) is not a phone number, and a date such as 2026-10-01 has groups too short to match.
PHONE = re.compile(r"(?<![\w.:/+-])(?:\+\d{1,3}[ .-]?(?:\(\d{1,5}\)[ .-]?)?\d{2,5}(?:[ .-]?\d{2,5}){1,3}"
r"|\(?\d{3,5}\)?[ -]\d{3,4}[ -]\d{3,5}(?:[ -]\d{1,4})?)(?![\w-])")
def _phone(m: re.Match[str]) -> str:
return "[PHONE]" if 8 <= sum(c.isdigit() for c in m.group()) <= 15 else m.group()
def redact_secrets(text: str) -> str:
"""Replace anything shaped like a credential. Safe for headers, URLs and any other string."""
for label, pattern in SECRET_PATTERNS:
text = pattern.sub(f"[{label}]", text)
return SECRET_KV.sub(lambda m: f"{m.group(1)}{m.group(2)}[SECRET]", text)
def find_secrets(text: str) -> list[str]:
"""Which credential shapes appear in `text`? Used to lint files (cassettes) that must contain none."""
found = [label for label, pattern in SECRET_PATTERNS if pattern.search(text)]
return found + (["SECRET_KV"] if SECRET_KV.search(text) else [])
def redact_text(text: str) -> str:
"""Replace credentials, emails, card and phone numbers with a [LABEL] marker."""
text = redact_secrets(text)
for label, pattern in PII_PATTERNS:
text = pattern.sub(f"[{label}]", text)
return PHONE.sub(_phone, text)Here is the reusable piece, wire_log.py. Read its helper functions first: they are the redaction, and the design decision that matters most is in the first comment: redaction fails closed. A deny-list ("hide authorization and x-api-key") leaks every credential header it hasn't heard of, and gateways and proxies invent new ones constantly (x-portkey-api-key, helicone-auth, ocp-apim-subscription-key). So the code does the opposite: a header's value is shown only if the header is on a short allow-list of harmless ones; everything else is <redacted>, known or not.
# wire_log.py
"""wire_log.py: log every HTTP request and response an LLM SDK makes, with secrets redacted.
Works with httpx2 (openai 3.x, anthropic 2.x) and httpx (google-genai), through event hooks.
Redaction FAILS CLOSED: a header is shown only if it is on an allow-list, and a URL keeps only allow-listed
query parameters. A credential in a header nobody has heard of (a gateway's x-portkey-api-key) is hidden anyway."""
import hashlib
import json
import logging
import re
from typing import Any
from urllib.parse import parse_qsl, quote, urlsplit, urlunsplit
import httpx
import httpx2
from redact import redact_secrets, redact_text
log = logging.getLogger("wire")
# Request headers whose VALUES are safe to log (lower-case: HTTP header names are case-insensitive).
# Everything not listed here is shown as <redacted>, so a new credential header can't leak by being unknown.
SAFE_HEADERS = {"accept", "accept-encoding", "connection", "content-type", "content-length", "host", "user-agent",
"anthropic-version", "anthropic-beta", "openai-beta", "x-client-request-id", "x-request-id",
"http-referer", "x-title", "x-goog-api-client"}
SAFE_HEADER_PREFIXES = ("x-stainless-",) # the OpenAI and Anthropic SDKs' own telemetry: retry count, timeout...
SAFE_QUERY = {"alt", "api-version", "api_version"} # everything else in a query string is hidden (?key=, ?token=, ...)
# Transport and SDK-telemetry headers that rarely matter when debugging (pass drop=set() to see them)
NOISE = {"host", "accept-encoding", "connection", "x-stainless-lang", "x-stainless-os", "x-stainless-arch",
"x-stainless-runtime", "x-stainless-runtime-version", "x-stainless-async", "x-goog-api-client"}
# Response headers worth keeping: request IDs, timing, rate limits, retry hints
KEEP_RESPONSE = ("request-id", "x-request-id", "x-generation-id", "openai-processing-ms",
"retry-after", "retry-after-ms", "x-should-retry", "content-type")
KEEP_RESPONSE_PREFIXES = ("x-ratelimit-", "anthropic-ratelimit-")
_SCHEME = re.compile(r"(?i)^(bearer|basic|token|digest)\s")
_NOT_READ = (httpx.RequestNotRead, httpx2.RequestNotRead) # a streamed body: multipart file uploads
def _safe(name: str) -> bool:
return name in SAFE_HEADERS or name.startswith(SAFE_HEADER_PREFIXES)
def redact_headers(headers: Any, drop: set[str] | frozenset[str] = frozenset()) -> dict[str, str]:
"""A plain dict copy: allow-listed headers keep their value, everything else becomes <redacted>.
The authentication scheme word is kept, so 'no auth header' and 'a header I hid' stay distinguishable."""
out = {}
for name, value in headers.items():
lname = name.lower()
if lname in drop:
continue
if _safe(lname):
value = redact_secrets(value) # belt and braces: a key pasted into a safe header
else:
scheme = _SCHEME.match(value)
value = f"{scheme.group(1)} <redacted>" if scheme else "<redacted>"
out[lname] = value
return out
def redact_url(url: Any) -> str:
"""Hides userinfo (https://user:pass@host) and every query value except allow-listed ones, keeps empty
parameters, and removes anything key-shaped from the path too."""
parts = urlsplit(str(url))
userinfo, _, hostinfo = parts.netloc.rpartition("@")
netloc = f"<redacted>@{hostinfo}" if userinfo else hostinfo
query = "&".join(f"{k}={quote(v) if k.lower() in SAFE_QUERY else '<redacted>'}"
for k, v in parse_qsl(parts.query, keep_blank_values=True))
return redact_secrets(urlunsplit(parts._replace(netloc=netloc, query=query)))
def body_summary(content: bytes | None, show_body: bool, max_chars: int, *, declared_length: str | None = None) -> dict[str, Any]:
"""By default: size and a fingerprint, never the content. With show_body: a REDACTED, truncated preview
(still sensitive: regexes miss things). content=None means a streamed body (a file upload) we must not read."""
if content is None:
return {"bytes": int(declared_length) if declared_length and declared_length.isdigit() else None, "stream": True}
summary: dict[str, Any] = {"bytes": len(content), "sha256": hashlib.sha256(content).hexdigest()[:12]}
if show_body:
text = redact_text(content.decode("utf-8", errors="replace")) # redact BEFORE cutting, so a cut can't split a secret
summary["preview"] = text if len(text) <= max_chars else text[:max_chars] + f"...(+{len(text) - max_chars} chars)"
return summary
def _body_of(request: Any) -> bytes | None:
try:
return request.content
except _NOT_READ:
return None
def make_event_hooks(*, show_body: bool = False, max_chars: int = 300,
drop: set[str] | frozenset[str] = NOISE) -> dict[str, list[Any]]:
"""event_hooks for httpx2.Client or httpx.Client. Hooks see each HTTP attempt, retries included.
A hook must never break the request it observes, so each body is wrapped: a failure is logged and swallowed."""
def on_request(request: Any) -> None:
try:
log.debug(json.dumps({"event": "http_request", "method": request.method, "url": redact_url(request.url),
"headers": redact_headers(request.headers, drop),
"body": body_summary(_body_of(request), show_body, max_chars,
declared_length=request.headers.get("content-length"))}))
except Exception:
log.exception("wire request hook failed")
def on_response(response: Any) -> None:
# The body hasn't been read yet (it may be a stream), so log status and headers only.
try:
kept = {k.lower(): redact_secrets(v) for k, v in response.headers.items()
if k.lower() in KEEP_RESPONSE or k.lower().startswith(KEEP_RESPONSE_PREFIXES)}
log.debug(json.dumps({"event": "http_response", "status": response.status_code,
"url": redact_url(response.request.url),
"retry_count": response.request.headers.get("x-stainless-retry-count"),
"headers": kept}))
except Exception:
log.exception("wire response hook failed")
return {"request": [on_request], "response": [on_response]}
def make_async_event_hooks(**kwargs: Any) -> dict[str, list[Any]]:
"""The same hooks for async clients: `async def` wrappers around the plain functions above, because an
async httpx client awaits its hooks (a plain function there fails at the first request)."""
def wrap(hook: Any) -> Any:
async def async_hook(arg: Any) -> None:
hook(arg)
return async_hook
return {event: [wrap(h) for h in hooks] for event, hooks in make_event_hooks(**kwargs).items()}The design decisions, each of which prevents a real incident:
- Headers are allow-listed, case-insensitively.
SAFE_HEADERS(content type,anthropic-version,x-client-request-id, and the SDKs' ownx-stainless-*telemetry) keep their value; every other header becomes<redacted>, keeping only an authentication scheme word such asBearer. The function copies the headers into a plain dict and never mutates or logs the original object. Even an allowed header's value goes throughredact_secrets, in case someone pastes a key into auser-agent. - URLs are allow-listed too. The userinfo part (
https://user:pass@host) is replaced, and so is every query value except a short list (alt,api-version);?key=,?apikey=,?api-key=,?token=and a cloud signature such asX-Amz-Signatureall disappear without being named, and key-shaped text anywhere in the path is removed. - The body is summarized, not logged: its size and the first 12 hex characters of its SHA-256. Two requests with the same hash carried the same bytes, so you can tell "same prompt" from "different prompt" without storing either.
show_body=Trueadds a preview, but it is redacted and then truncated (in that order, so a cut can't split a key), and it is still sensitive: it exists for one debugging session on your laptop. - A file upload has no body to read. A multipart request (
files.create, a Gemini file upload) streams its body, and readingrequest.contenton it raisesRequestNotRead. A hook that did that would break every upload in the application, sobody_summarylogs{"bytes": <the content-length header>, "stream": true}for such a request and leaves the stream alone. - A hook must never take a request down. Each hook body is wrapped: if redaction or logging itself raises, the error is logged and the request carries on. (4.10 preaches this; the hooks follow it.)
- The response hook logs only status and a short allow-list of headers (request IDs,
retry-after,x-should-retry, rate-limit headers). It can't read the body, because the body may be a stream that hasn't arrived yet and reading it would break streaming. - Noise headers are dropped by default (
x-stainless-os,accept-encoding, ...). Passdrop=set()to see everything.
The tests in tests/test_wire_log.py are what make "fail closed" a fact rather than a hope. Every secret in them is assembled at run time from an obviously fake body (the word EXAMPLE repeated, plus the real vendor prefix), so no real or realistic credential is stored in the file, yet each has the shape and length a vendor's key has:
# tests/test_wire_log.py
"""The event hooks sit on the hot path of EVERY request and handle credentials, so they get the strictest tests:
they must hide what they don't recognize, must never break a request (file uploads!), and must work on async clients.
Every secret value here is assembled at run time from an obviously fake body (see test_redact.py)."""
from __future__ import annotations
import io
import json
import logging
import httpx2
import openai
import pytest
import wire_log
from wire_log import body_summary, make_async_event_hooks, make_event_hooks, redact_headers, redact_url
FAKE = "EXAMPLE" * 6
OPENAI_KEY = "sk-" + "proj-" + FAKE
FILE_REPLY = {"id": "file-1", "object": "file", "bytes": 3, "created_at": 1, "filename": "a.txt", "purpose": "user_data"}
def test_unknown_credential_headers_are_hidden_because_they_are_not_on_the_allow_list() -> None:
headers = {"Authorization": f"Bearer {OPENAI_KEY}", "x-litellm-api-key": OPENAI_KEY, "x-portkey-api-key": FAKE,
"helicone-auth": f"Bearer {FAKE}", "ocp-apim-subscription-key": FAKE, "x-custom-token": FAKE,
"Content-Type": "application/json", "anthropic-version": "2026-10-21", "x-stainless-retry-count": "0"}
out = redact_headers(headers)
assert out["authorization"] == "Bearer <redacted>" and out["helicone-auth"] == "Bearer <redacted>" # scheme word kept
for name in ("x-litellm-api-key", "x-portkey-api-key", "ocp-apim-subscription-key", "x-custom-token"):
assert out[name] == "<redacted>", name
assert out["content-type"] == "application/json" and out["anthropic-version"] == "2026-10-21"
assert out["x-stainless-retry-count"] == "0" # allow-listed families keep their values
assert FAKE not in json.dumps(out)
def test_a_key_pasted_into_an_allowed_header_is_still_caught() -> None:
assert OPENAI_KEY not in redact_headers({"user-agent": f"my-app/1.0 {OPENAI_KEY}"})["user-agent"]
@pytest.mark.parametrize("url, expected", [
("https://api.example.test/v1/x?key=SECRET&alt=sse", "https://api.example.test/v1/x?key=<redacted>&alt=sse"),
("https://api.example.test/v1/x?apikey=SECRET", "https://api.example.test/v1/x?apikey=<redacted>"),
("https://api.example.test/v1/x?api-key=SECRET&token=SECRET2", "https://api.example.test/v1/x?api-key=<redacted>&token=<redacted>"),
("https://s3.example.test/f?X-Amz-Signature=SECRET", "https://s3.example.test/f?X-Amz-Signature=<redacted>"),
("https://alice:SECRET@api.example.test/v1", "https://<redacted>@api.example.test/v1"),
("https://api.example.test/v1/x?empty=&other", "https://api.example.test/v1/x?empty=<redacted>&other=<redacted>"),
])
def test_urls_hide_userinfo_and_every_query_value_not_on_the_allow_list(url: str, expected: str) -> None:
assert redact_url(url) == expected
assert "SECRET" not in redact_url(url)
def test_a_key_shaped_string_in_the_path_is_removed_too() -> None:
assert OPENAI_KEY not in redact_url(f"https://api.example.test/bot/{OPENAI_KEY}/send")
def test_the_body_preview_is_redacted_and_the_default_has_no_preview() -> None:
body = json.dumps({"input": f"my key is {OPENAI_KEY}, mail jane@example.com"}).encode()
preview = body_summary(body, True, 300)["preview"]
assert OPENAI_KEY not in preview and "jane@example.com" not in preview and "[API_KEY]" in preview
assert "preview" not in body_summary(body, False, 300)
# --- the hooks on a real SDK client ---------------------------------------------------------------------------------
def client_with(hooks: dict, handler) -> openai.OpenAI: # type: ignore[no-untyped-def]
return openai.OpenAI(api_key=OPENAI_KEY, max_retries=0, http_client=openai.DefaultHttpx2Client(
transport=httpx2.MockTransport(handler), event_hooks=hooks))
def wire_lines(caplog: pytest.LogCaptureFixture) -> list[dict]:
return [json.loads(r.getMessage()) for r in caplog.records if r.name == "wire" and r.levelno == logging.DEBUG]
def test_a_multipart_file_upload_is_not_broken_by_the_hooks(caplog: pytest.LogCaptureFixture) -> None:
"""The bug this pins: request.content raises RequestNotRead for a streamed body, and the hook took the call down."""
caplog.set_level(logging.DEBUG, logger="wire")
seen: list[bytes] = []
def handler(request: httpx2.Request) -> httpx2.Response:
seen.append(request.read()) # the server DOES receive the whole upload
return httpx2.Response(200, json=FILE_REPLY)
client = client_with(make_event_hooks(show_body=True), handler)
f = client.files.create(file=("a.txt", io.BytesIO(b"abc")), purpose="user_data")
assert f.id == "file-1" and b"abc" in seen[0]
request_line = next(x for x in wire_lines(caplog) if x["event"] == "http_request")
assert request_line["body"]["stream"] is True and "preview" not in request_line["body"] # logged as "a stream", unread
assert request_line["body"]["bytes"] and "authorization" in request_line["headers"]
def test_a_hook_that_raises_is_logged_and_never_breaks_the_request(monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture) -> None:
def explode(*a, **k): # type: ignore[no-untyped-def]
raise RuntimeError("redaction bug")
monkeypatch.setattr(wire_log, "redact_headers", explode)
client = client_with(make_event_hooks(), lambda r: httpx2.Response(200, json=FILE_REPLY))
assert client.files.retrieve("file-1").id == "file-1" # the call still succeeds
assert any("wire request hook failed" in r.getMessage() for r in caplog.records)
@pytest.mark.asyncio
async def test_async_hooks_run_on_an_async_client(caplog: pytest.LogCaptureFixture) -> None:
caplog.set_level(logging.DEBUG, logger="wire")
async def handler(request: httpx2.Request) -> httpx2.Response:
return httpx2.Response(200, json=FILE_REPLY, headers={"x-request-id": "req_async"})
client = openai.AsyncOpenAI(api_key=OPENAI_KEY, max_retries=0, http_client=openai.DefaultAsyncHttpx2Client(
transport=httpx2.MockTransport(handler), event_hooks=make_async_event_hooks()))
await client.files.retrieve("file-1")
events = [x["event"] for x in wire_lines(caplog)]
assert events == ["http_request", "http_response"]
assert OPENAI_KEY not in caplog.text============================= test session starts ==============================
collected 13 items
tests/test_wire_log.py::test_unknown_credential_headers_are_hidden_because_they_are_not_on_the_allow_list PASSED [ 7%]
tests/test_wire_log.py::test_a_key_pasted_into_an_allowed_header_is_still_caught PASSED [ 15%]
tests/test_wire_log.py::test_urls_hide_userinfo_and_every_query_value_not_on_the_allow_list[https://api.example.test/v1/x?key=SECRET&alt=sse-https://api.example.test/v1/x?key=<redacted>&alt=sse] PASSED [ 23%]
tests/test_wire_log.py::test_urls_hide_userinfo_and_every_query_value_not_on_the_allow_list[https://api.example.test/v1/x?apikey=SECRET-https://api.example.test/v1/x?apikey=<redacted>] PASSED [ 30%]
tests/test_wire_log.py::test_urls_hide_userinfo_and_every_query_value_not_on_the_allow_list[https://api.example.test/v1/x?api-key=SECRET&token=SECRET2-https://api.example.test/v1/x?api-key=<redacted>&token=<redacted>] PASSED [ 38%]
tests/test_wire_log.py::test_urls_hide_userinfo_and_every_query_value_not_on_the_allow_list[https://s3.example.test/f?X-Amz-Signature=SECRET-https://s3.example.test/f?X-Amz-Signature=<redacted>] PASSED [ 46%]
tests/test_wire_log.py::test_urls_hide_userinfo_and_every_query_value_not_on_the_allow_list[https://alice:SECRET@api.example.test/v1-https://<redacted>@api.example.test/v1] PASSED [ 53%]
tests/test_wire_log.py::test_urls_hide_userinfo_and_every_query_value_not_on_the_allow_list[https://api.example.test/v1/x?empty=&other-https://api.example.test/v1/x?empty=<redacted>&other=<redacted>] PASSED [ 61%]
tests/test_wire_log.py::test_a_key_shaped_string_in_the_path_is_removed_too PASSED [ 69%]
tests/test_wire_log.py::test_the_body_preview_is_redacted_and_the_default_has_no_preview PASSED [ 76%]
tests/test_wire_log.py::test_a_multipart_file_upload_is_not_broken_by_the_hooks PASSED [ 84%]
tests/test_wire_log.py::test_a_hook_that_raises_is_logged_and_never_breaks_the_request PASSED [ 92%]
tests/test_wire_log.py::test_async_hooks_run_on_an_async_client PASSED [100%]
============================== 13 passed in 0.19s ==============================The multipart test is the one to remember. It builds a real OpenAI client with the hooks attached, uploads a file through files.create, and checks three things: the call succeeds, the server received the whole upload, and the log line says "stream": true instead of showing a body. Before the fix the same call raised RequestNotRead out of the hook. test_a_hook_that_raises_is_logged_and_never_breaks_the_request forces the redaction to raise and checks that the request still succeeds.
Wire it up for the openai and anthropic SDKs and watch it work:
# s2_3_event_hooks.py
"""Log the wire for the openai and anthropic SDKs with event hooks and redaction, against the free local stand-in."""
import logging
import sys
import anthropic
import openai
from wire_log import make_event_hooks
logging.basicConfig(stream=sys.stdout, level=logging.WARNING, format="%(name)s %(message)s")
logging.getLogger("wire").setLevel(logging.DEBUG)
# openai: DefaultHttpx2Client keeps the SDK's own defaults (timeouts, connection limits) and adds our hooks
oai = openai.OpenAI(base_url="http://localhost:11434/v1", api_key="ollama-local-not-a-key",
http_client=openai.DefaultHttpx2Client(event_hooks=make_event_hooks(show_body=True)))
oai.responses.create(model="gpt-6-luna", input="Hi", max_output_tokens=5)
# anthropic: the same idea; its default-preserving class is called DefaultHttpxClient but builds an httpx2 client
claude = anthropic.Anthropic(base_url="http://localhost:11434", api_key="ollama-local-not-a-key",
http_client=anthropic.DefaultHttpxClient(event_hooks=make_event_hooks()))
claude.messages.create(model="claude-haiku-5-5", max_tokens=5, messages=[{"role": "user", "content": "Hi"}])wire {"event": "http_request", "method": "POST", "url": "http://localhost:11434/v1/responses", "headers": {"authorization": "Bearer <redacted>", "accept": "application/json", "content-type": "application/json", "user-agent": "OpenAI/Python 3.42.1", "x-stainless-package-version": "3.42.1", "x-stainless-retry-count": "0", "x-stainless-read-timeout": "600", "content-length": "57"}, "body": {"bytes": 57, "sha256": "c92b1775a471", "preview": "{\"model\":\"gpt-6-luna\",\"input\":\"Hi\",\"max_output_tokens\":5}"}}
wire {"event": "http_response", "status": 200, "url": "http://localhost:11434/v1/responses", "retry_count": "0", "headers": {"content-type": "application/json"}}
wire {"event": "http_request", "method": "POST", "url": "http://localhost:11434/v1/messages", "headers": {"x-stainless-timeout": "600", "x-stainless-retry-count": "0", "x-stainless-read-timeout": "600", "accept": "application/json", "content-type": "application/json", "user-agent": "Anthropic/Python 2.4.0", "x-stainless-package-version": "2.4.0", "authorization": "Bearer <redacted>", "anthropic-version": "2026-10-21", "content-length": "87"}, "body": {"bytes": 87, "sha256": "cbc456ef4774"}}
wire {"event": "http_response", "status": 200, "url": "http://localhost:11434/v1/messages", "retry_count": "0", "headers": {"content-type": "application/json"}}Look at the authorization value: Bearer <redacted>. The calls used dummy local keys; with a real key the output would be identical, which is the point. Also look at what the headers tell you for free: user-agent: OpenAI/Python 3.42.1 (the SDK version actually running), anthropic-version: 2026-10-21, x-stainless-retry-count: 0 (which attempt), x-stainless-read-timeout: 600 (the timeout in force) and the exact URL. For the first call the preview shows the JSON body the SDK actually serialized: {"model":"gpt-6-luna","input":"Hi","max_output_tokens":5}.
google-genai takes the same hooks through client_args, which are passed to the httpx.Client the SDK builds, so its defaults stay. That form is hosted-only:
# s2_3_event_hooks_gemini.py: the same hooks on google-genai (hosted Gemini API)
import logging
import sys
from google import genai
from google.genai import types
from wire_log import make_event_hooks
logging.basicConfig(stream=sys.stdout, level=logging.WARNING, format="%(name)s %(message)s")
logging.getLogger("wire").setLevel(logging.DEBUG)
gem = genai.Client(http_options=types.HttpOptions(client_args={"event_hooks": make_event_hooks()})) # GEMINI_API_KEY
gem.models.generate_content(model="gemini-3.8-flash", contents="Hi",
config=types.GenerateContentConfig(max_output_tokens=5))2.4 Raw responses and middleware#
Hooks see raw HTTP. When you only need the response's headers next to the parsed object, the SDKs already provide that (03.1, 8.5). Here they are as debugging tools:
openaiandanthropic:client.responses.with_raw_response.create(...)returns a wrapper with.parse()(the normal object),.headers,.status_code,.elapsed,.retries_taken,.request_id, and.http_request(the request that was sent).with_streaming_responsegives you the headers before the body, as a context manager.google-genai: everyGenerateContentResponsecarriessdk_http_responsewith the response headers.anthropicalso offers middleware: a function that wraps each HTTP attempt and can inspect or change the request and the response. It runs inside the SDK's retry loop, so it sees every attempt.
# s2_4_raw_and_middleware.py
"""Debugging data the SDKs already have: with_raw_response (openai, anthropic) and anthropic middleware.
Part A runs against the free local model; part B uses a MOCK server (a 529, then a 200)."""
from typing import Any
import anthropic
import httpx2
from anthropic import APIRequest, APIResponse, CallNext
from openai import OpenAI
# --- Part A: the raw response wraps the parsed object with HTTP details ---------------------------
local = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
raw = local.responses.with_raw_response.create(model="gpt-6-luna", input="Hi", max_output_tokens=5)
resp = raw.parse() # the normal Response object
print("status:", raw.status_code, "| elapsed:", f"{raw.elapsed.total_seconds():.2f}s",
"| retries_taken:", raw.retries_taken, "| request_id:", raw.request_id)
print("sent:", raw.http_request.method, raw.http_request.url, "| body bytes:", len(raw.http_request.content))
print("model asked vs served:", "gpt-6-luna", "->", resp.model, "| status:", resp.status)
# --- Part B: middleware sees every attempt, including the ones the SDK retries -------------------
attempts = 0
def log_attempts(request: APIRequest, call_next: CallNext) -> APIResponse[Any]:
global attempts
attempts += 1 # middleware runs inside the SDK's retry loop
response = call_next(request) # one HTTP attempt (4xx/5xx come back too)
print(f" middleware: {request.method.upper()} {request.url} attempt {attempts} -> {response.status_code}"
f" request-id={response.headers.get('request-id')}")
return response
MSG = {"id": "msg_1", "type": "message", "role": "assistant", "model": "claude-haiku-5-5",
"content": [{"type": "text", "text": "Hi!"}], "stop_reason": "end_turn", "stop_sequence": None,
"usage": {"input_tokens": 8, "output_tokens": 3}}
replies = iter([
httpx2.Response(529, json={"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}},
headers={"request-id": "req_mock_1", "retry-after-ms": "10"}), # retry after 10 ms
httpx2.Response(200, json=MSG, headers={"request-id": "req_mock_2"}),
])
mock = httpx2.Client(transport=httpx2.MockTransport(lambda request: next(replies)))
claude = anthropic.Anthropic(api_key="sk-ant-test", http_client=mock, max_retries=2, middleware=[log_attempts])
raw_msg = claude.messages.with_raw_response.create(model="claude-haiku-5-5", max_tokens=50,
messages=[{"role": "user", "content": "Hi"}])
print("final:", raw_msg.status_code, "| retries_taken:", raw_msg.retries_taken,
"| _request_id:", raw_msg.parse()._request_id)status: 200 | elapsed: 0.15s | retries_taken: 0 | request_id: None
sent: POST http://localhost:11434/v1/responses | body bytes: 57
model asked vs served: gpt-6-luna -> gpt-6-luna | status: completed
middleware: POST /v1/messages attempt 1 -> 529 request-id=req_mock_1
middleware: POST /v1/messages attempt 2 -> 200 request-id=req_mock_2
final: 200 | retries_taken: 1 | _request_id: req_mock_2Part A shows what the raw response knows: status 200, the elapsed time, retries_taken: 0, the request that was actually sent (POST .../v1/responses, 57 bytes) and the model you asked for next to the model the response says served it (identical here; hosted aliases often differ, see 5.4). Part B is a mock server that answers 529 (Anthropic's "overloaded") and then 200. The middleware printed both attempts, each with its own request-id, and the final call reports retries_taken: 1 and _request_id: req_mock_2, the ID of the successful attempt. When you open a support ticket about a failed call, the failed attempt's ID (req_mock_1) is the one they need, which is why logging per attempt (hooks or middleware) beats logging only the final result.
Two more raw-access patterns, from a different mock server:
# s2_5_raw_gemini_streaming.py
"""More ways to see the HTTP layer. Servers are MOCKS returning documented header names with made-up values.
A: google-genai keeps response headers in sdk_http_response. B: openai/anthropic raw streaming responses."""
import httpx
import httpx2
from google import genai
from google.genai import types
from openai import OpenAI
# A) Gemini: headers and body of the HTTP response ride along on the parsed object
BODY = {"responseId": "Fh4kZ-example", "modelVersion": "gemini-3.8-flash-001",
"candidates": [{"content": {"role": "model", "parts": [{"text": "Hello!"}]}, "finishReason": "STOP"}]}
gem = genai.Client(api_key="gemini-test", http_options=types.HttpOptions(httpx_client=httpx.Client(
transport=httpx.MockTransport(lambda r: httpx.Response(200, json=BODY, headers={"server-timing": "gfet4t7; dur=412"})))))
r = gem.models.generate_content(model="gemini-3.8-flash", contents="Hi")
http = r.sdk_http_response
print("gemini : response_id =", r.response_id, "| model_version =", r.model_version)
print(" headers =", dict(http.headers) if http and http.headers else None)
# B) openai: with_streaming_response gives the headers BEFORE you read the body (useful to log the request id early)
SSE = (b'event: response.completed\ndata: {"type":"response.completed","sequence_number":0,"response":'
b'{"id":"resp_1","object":"response","status":"completed","model":"gpt-6-luna","output":[]}}\n\n')
oai = OpenAI(api_key="sk-test", http_client=httpx2.Client(transport=httpx2.MockTransport(
lambda r: httpx2.Response(200, content=SSE, headers={"content-type": "text/event-stream", "x-request-id": "req_stream_1"}))))
with oai.responses.with_streaming_response.create(model="gpt-6-luna", input="Hi", stream=True) as resp:
print("openai : headers arrive first -> x-request-id =", resp.headers["x-request-id"], "| request_id attr =", resp.request_id)
events = [line for line in resp.iter_lines() if line.startswith("event:")]
print(" then the body:", events)gemini : response_id = Fh4kZ-example | model_version = gemini-3.8-flash-001
headers = {'server-timing': 'gfet4t7; dur=412', 'content-length': '162', 'content-type': 'application/json'}
openai : headers arrive first -> x-request-id = req_stream_1 | request_id attr = req_stream_1
then the body: ['event: response.completed']- Gemini's
sdk_http_response.headersholds whatever HTTP headers came back. Gemini has no request-ID header documented, soresponse_idis the identifier to log (03.1, 8.6). with_streaming_responsehands you thex-request-idbefore any of the body is read. For a long stream, that means you can log the ID as soon as the connection opens, so a stream that later dies still leaves a trace you can give to support (03.3).
2.5 Wire capture: the request, without sending it#
The most precise answer to "what did we send?" is the request itself, built by the real SDK, with a transport that never sends it. Lesson 03.1, 1.3 introduced the trick to show that the four APIs are "just HTTP". Here it becomes a reusable debugging and testing tool: wire_capture.py wraps it in a class that records the request, redacts its credentials, and then stops the call.
# wire_capture.py
"""wire_capture.py: build the exact HTTP request an SDK would send, without sending it (a dry run).
Use it to debug "what did we actually send?", to diff two requests, and for payload snapshot tests."""
import json
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any, NoReturn
import httpx
import httpx2
from wire_log import redact_headers, redact_url
@dataclass
class Captured:
method: str
url: str
headers: dict[str, str] # credentials already redacted
body: Any # parsed JSON (or None)
class _Stop(Exception):
"""Raised by the capturing transport so the request never goes anywhere."""
class WireCapture:
"""Hand .httpx2_client() to openai/anthropic (with max_retries=0) or .httpx_client() to google-genai."""
def __init__(self) -> None:
self.requests: list[Captured] = []
def _record(self, request: Any) -> NoReturn:
body = json.loads(request.content) if request.content else None
self.requests.append(Captured(request.method, redact_url(request.url), redact_headers(request.headers), body))
raise _Stop()
def httpx2_client(self) -> httpx2.Client:
return httpx2.Client(transport=httpx2.MockTransport(self._record))
def httpx_client(self) -> httpx.Client:
return httpx.Client(transport=httpx.MockTransport(self._record))
def run(self, call: Callable[[], Any]) -> Captured:
"""Run one SDK call; return the request it built. The SDK raises a connection error: expected."""
before = len(self.requests)
try:
call()
except Exception: # noqa: BLE001 - the SDK wraps _Stop in its own error type
pass
if len(self.requests) != before + 1:
raise AssertionError(f"expected exactly 1 HTTP request, saw {len(self.requests) - before} "
"(did you leave SDK retries on? use max_retries=0)")
return self.requests[-1]How it works:
WireCapture.httpx2_client()returns anhttpx2.ClientwhoseMockTransporthandler records the request and then raises a private_Stopexception. The SDK wraps that in its own connection error, andrun()swallows it. So no response is ever needed, and nothing can be sent anywhere.max_retries=0is required (run()checks it): with retries on, the SDK would "retry" the failed attempt and record several requests.httpx_client()is the same forgoogle-genai, which takes anhttpx.Client(03.1, 4.5).- The recorded
Capturedobject holds the method, URL, already-redacted headers and the parsed JSON body, which is what you diff, snapshot or assert on.
Part 3: A debugging checklist for LLM API bugs#
When an LLM feature misbehaves, resist the urge to rewrite the prompt. Prompt-tweaking is the most expensive way to debug, and it only helps if the prompt was the problem. Work through the request first.
3.1 The checklist#
Go roughly top to bottom: the early rows are the most common and the cheapest to check. Every row names the lesson that owns the fix, so this table doubles as an index.
| # | Suspect | Typical symptom | How to check | Fix lives in |
|---|---|---|---|---|
| 1 | Wrong model, or an alias that moved | Quality, format or latency changed with no code change | Compare model_requested with model_resolved in the log (4.1, 5.4) |
02.9, Part 8, 03.1, 9.3 |
| 2 | Wrong API family or API version | A parameter is rejected (a 400), or silently has no effect |
Wire capture: which URL and which field names were used? (2.5) | 03.1, Part 9, 03.2, Part 9 |
| 3 | A missing or empty system instruction | The model ignores your rules, or "forgets its role" | system_chars in the request summary is 0 (3.4); a config value didn't load |
03.2, Part 2 |
| 4 | Instructions in the wrong place | The instruction exists but has little effect (e.g. in a user turn, or in a field the API doesn't use) | The captured body: is the text under instructions / system / systemInstruction, or buried in messages? |
03.2, Part 1 |
| 5 | Trimmed or truncated history | The model "forgets" earlier turns, repeats questions | turns and the role pattern in the summary; total_input_tokens much lower than expected |
02.7, Part 4, 03.2, Part 5 |
| 6 | Server-side state not applied | A chained conversation answers as if it were the first turn | Is previous_response_id / previous_interaction_id really in the captured body? Did the stored object expire or get deleted? |
03.2, Part 7 |
| 7 | Dropped reasoning items, thinking blocks or thought signatures | A 400 mentioning thinking blocks or signatures; tool use gets worse mid-conversation |
Does the replayed history contain every reasoning item exactly as received? | 02.8, 8.2, 03.2 |
| 8 | Wrong tool-result threading | A 400 about unmatched tool calls, or the model repeats a call |
Do the IDs of the results match the IDs of the calls, in the right message shape? | 03.5, 5.3, Part 9 |
| 9 | A stale or mismatched SDK | Docs show a parameter your SDK doesn't have; behaviour differs between machines | Print versions (diagnose.py, 3.5); compare the lockfile |
03.1, 4.4, 9.4 |
| 10 | A parameter silently ignored or rejected | You set it and nothing changes, or a 400 appears after a model or API-version upgrade |
Request summary: is it in the body at all? Type-check (Part 11); check the provider support matrix | 02.5, Part 6, 03.2, 9.2 |
| 11 | An output cap that is too small | Cut-off or empty text; reasoning models spend the whole budget thinking | finish_reason is a length stop; output_tokens equals the cap |
02.5, 4.6, 03.8, Part 10 |
| 12 | An unchecked finish reason | "It returned 200 but the answer is wrong or missing": refusals, blocks, pause_turn |
outcome != "ok" in the log; was it checked in code? |
03.8, 10.2 |
| 13 | A cache miss | Cost and latency jump; cached_input_tokens is 0 |
The prompt_sha256 of the stable prefix changed (a timestamp or a user ID early in the prompt?) |
03.7, 10.3 |
| 14 | A wrong base URL, stray environment variable or proxy | Calls go to the wrong place; works on one machine only | diagnose.py (3.5); the httpx2 INFO log line (2.2) |
03.1, 7.2 |
| 15 | Hidden retries | Calls "randomly" take 3x longer; bills higher than expected | attempts > 1 in the log; per-attempt hook output |
03.8, Part 5 |
| 16 | Timeouts too short or too long | Failures on long outputs; users staring at spinners | latency_ms distribution; the timeout in x-stainless-read-timeout |
03.8, Part 6 |
| 17 | A stream accumulated wrongly | Garbled or duplicated text, missing tool arguments | Compare your accumulation with the SDK's final message (Part 8) | 03.3, Part 5 |
| 18 | Structured output that doesn't validate | Parse errors, missing keys | Store the raw text next to the parse error | 03.4, Part 6 |
| 19 | Media that is too big or the wrong type | 400 or 413 on requests with images or PDFs |
bytes in the hook log; the size and media types in the body |
03.6, Part 9 |
| 20 | A local stand-in hiding the problem | Passes locally, fails on the hosted API | The stand-in ignores many parameters; see its known gaps (03.1, 12.6) and 7.7 | here |
3.2 The triage flow#
The checklist is a reference; this is the order to apply it in.
flowchart TD
A["Bad answer or error reported"] --> B{"Do you have the<br/>request ID and trace ID?"}
B -->|"no"| B1["Add structured logging first<br/>Part 4"]
B -->|"yes"| C["Find the log line:<br/>model, finish reason, usage, attempts"]
C --> D{"Outcome not ok?<br/>truncated, refused, error"}
D -->|"yes"| D1["Fix handling:<br/>03.8 check_response"]
D -->|"no"| E["Get the exact request:<br/>stored case or wire capture"]
E --> F["Compare it with the request<br/>you THOUGHT you sent"]
F --> G{"Differences?"}
G -->|"yes"| G1["Bug is in your code or config:<br/>walk the checklist, Part 3"]
G -->|"no"| H["Replay it N times<br/>Part 5"]
H --> I{"Same behaviour<br/>every time?"}
I -->|"yes"| I1["Deterministic cause:<br/>prompt, model version, parameters"]
I -->|"sometimes"| I2["Variance:<br/>measure the rate, then Module 10A"]Two rules keep you honest. Change one thing at a time: if you edit the prompt, the model and a parameter together, you'll never know which one mattered. And keep the evidence before you fix: save the failing request (Part 5) before you change anything, or you'll be unable to prove the fix worked.
3.3 Try it: "it works on my machine", compare two requests#
A classic: the feature is fine in development and poor in production. The code is identical; the configuration differs. Instead of reading both configs and guessing, build the request in each environment (without sending it) and diff the two bodies.
First, the diff helper, request_diff.py. It turns two JSON bodies into a list of path-based differences:
# request_diff.py
"""request_diff.py: list every difference between two JSON request bodies, as paths."""
from typing import Any
def diff(a: Any, b: Any, path: str = "$") -> list[str]:
if isinstance(a, dict) and isinstance(b, dict):
out: list[str] = []
for key in sorted(set(a) | set(b)):
if key not in b:
out.append(f"{path}.{key}: only in A ({_short(a[key])})")
elif key not in a:
out.append(f"{path}.{key}: only in B ({_short(b[key])})")
else:
out += diff(a[key], b[key], f"{path}.{key}")
return out
if isinstance(a, list) and isinstance(b, list):
out = [f"{path}: {len(a)} items in A, {len(b)} in B"] if len(a) != len(b) else []
for i, (x, y) in enumerate(zip(a, b)):
out += diff(x, y, f"{path}[{i}]")
return out
return [] if a == b else [f"{path}: {_short(a)} -> {_short(b)}"]
def _short(value: Any, limit: int = 40) -> str:
text = repr(value)
return text if len(text) <= limit else text[:limit] + "..."Now the scenario. build_and_send is the "code under suspicion": it trims history and picks a system prompt from config. The dev and prod dictionaries stand for what each environment loaded (production lost its system prompt, say because an environment variable was missing, and uses a cheaper model with a tighter cap):
# s3_3_request_diff.py
"""'It works on my machine': capture the request each environment builds (no network) and diff them."""
from typing import Any
from openai import OpenAI
from request_diff import diff
from wire_capture import WireCapture
HISTORY = [{"role": "user" if i % 2 == 0 else "assistant", "content": f"turn {i}"} for i in range(12)]
def build_and_send(client: OpenAI, config: dict, question: str) -> None:
"""The code under suspicion: what it sends depends on config it reads at runtime."""
kept = HISTORY[-config["history_turns"]:] # trims history to a configured size
kwargs = {"instructions": config["system_prompt"]} if config.get("system_prompt") else {}
messages: list[Any] = [*kept, {"role": "user", "content": question}]
client.responses.create(model=config["model"], input=messages,
max_output_tokens=config["max_output_tokens"], **kwargs)
dev = {"model": "gpt-6.1-terra", "system_prompt": "You are a support agent for Acme.", "history_turns": 12,
"max_output_tokens": 2000}
prod = {"model": "gpt-6-luna", "system_prompt": "", "history_turns": 2, # e.g. an env var missing in prod
"max_output_tokens": 200}
cap = WireCapture()
client = OpenAI(api_key="sk-test", max_retries=0, http_client=cap.httpx2_client()) # fake key; nothing is sent
a = cap.run(lambda: build_and_send(client, dev, "Where is my order?"))
b = cap.run(lambda: build_and_send(client, prod, "Where is my order?"))
print("A = dev, B = prod")
for line in diff(a.body, b.body):
print(" ", line)A = dev, B = prod
$.input: 13 items in A, 3 in B
$.input[0].content: 'turn 0' -> 'turn 10'
$.input[1].content: 'turn 1' -> 'turn 11'
$.input[2].content: 'turn 2' -> 'Where is my order?'
$.instructions: only in A ('You are a support agent for Acme.')
$.max_output_tokens: 2000 -> 200
$.model: 'gpt-6.1-terra' -> 'gpt-6-luna'Seven lines of differences (after the header), and the bug is obvious. Production sends instructions as nothing (only in A), keeps only two turns of history (3 items instead of 13: look at input[0] being turn 10 rather than turn 0), caps output at 200 instead of 2,000 tokens and uses a smaller model. Any one of those could explain "worse answers", and a person reading two config files might spot one. The diff shows all four, and it ran with a fake key and no network. In a real incident, diff the stored production request (Part 5) against a request built locally from the same inputs.
3.4 Read a request at a glance#
For the questions on rows 2 to 5 and 10 of the checklist, you want a summary, not 4 KB of JSON. request_summary.py extracts the facts from a captured body for the five wire formats of this module (OpenAI Responses, Chat Completions in its OpenAI and OpenRouter variants, Anthropic Messages, Gemini generateContent), whichever provider made it:
# request_summary.py
"""request_summary.py: the facts you check first when an answer is wrong, read from a captured request body.
Handles the five wire formats of Module 03: Responses, Chat Completions (OpenAI and OpenRouter), Messages, generateContent."""
from typing import Any
from urllib.parse import urlsplit
from wire_capture import Captured
OUTPUT_CAPS = ("max_output_tokens", "max_completion_tokens", "max_tokens")
SAMPLING = ("temperature", "top_p", "top_k", "seed", "presence_penalty", "frequency_penalty")
def _text_of(content: Any) -> str:
return content if isinstance(content, str) else "".join(str(p.get("text", "")) for p in content if isinstance(p, dict))
def summarize_request(sent: Captured) -> dict[str, Any]:
body: dict[str, Any] = sent.body or {}
gen: dict[str, Any] = body.get("generationConfig", {})
turns = body.get("input") or body.get("messages") or body.get("contents") or []
turns = [turns] if isinstance(turns, str) else turns
system = body.get("instructions") or body.get("system") or ""
if not system and "systemInstruction" in body:
system = "".join(p.get("text", "") for p in body["systemInstruction"].get("parts", []))
roles = []
for t in turns:
role = t.get("role", "user") if isinstance(t, dict) else "user"
if role == "system" and isinstance(t, dict): # Chat Completions keeps the system prompt in messages
system = system or _text_of(t.get("content", ""))
else:
roles.append({"model": "assistant"}.get(role, role))
cap = next(((k, body[k]) for k in OUTPUT_CAPS if k in body), None) or (
("generationConfig.maxOutputTokens", gen["maxOutputTokens"]) if "maxOutputTokens" in gen else None)
return {"endpoint": urlsplit(sent.url).path.rsplit("/", 1)[-1], "model": body.get("model") or urlsplit(sent.url).path.split("/")[-1].split(":")[0],
"system_chars": len(_text_of(system)), "turns": len(roles), "roles": "".join(r[0] for r in roles),
"output_cap": cap, "sampling": {k: v for k, v in {**body, **gen}.items() if k in SAMPLING} or None,
"tools": len(body.get("tools", [])), "stream": bool(body.get("stream")), "user": body.get("user") or body.get("safety_identifier")
or (body.get("metadata") or {}).get("user_id") or (body.get("labels") or {}).get("safety_identifier")}Run it on the request each adapter builds for the same ticket, with the same history and the same user. The sample needs a function to call, and it is the project's business code, triage.py: a prompt, a parser, two rules and one thin function that asks a ChatModel. Save it now. Part 6 explains why it is shaped this way, so for the moment you only need to know that triage_ticket(chat, text, history=..., user=...) builds the request and calls chat.complete(...):
# triage.py
"""triage.py: the 'business code' under test. Three pure functions and one thin function that talks to a ChatModel."""
from __future__ import annotations
import json
import re
from dataclasses import dataclass
from chat_types import ChatModel, Message
FENCE = "`" * 3 # three backticks: the Markdown code fence that models wrap JSON in
PROMPT_VERSION = "triage-v3"
SYSTEM = ('You triage customer-support tickets. Reply with JSON only, no prose: '
'{"category": "billing" | "bug" | "how_to" | "other", "urgent": true | false}')
CATEGORIES = {"billing", "bug", "how_to", "other"}
MAX_HISTORY_TURNS = 6
class TriageParseError(ValueError):
"""The model answered, but not with the JSON we asked for."""
@dataclass(frozen=True)
class Triage:
category: str
urgent: bool
needs_human: bool = False
reason: str | None = None # why a human is needed, for the log
def build_messages(ticket: str, history: list[Message] | None = None) -> list[Message]:
"""Pure: keeps the last few turns of history, then the new ticket. No network, no clock, no globals."""
kept = (history or [])[-MAX_HISTORY_TURNS:]
return [*kept, {"role": "user", "content": ticket.strip()}]
def parse_triage(text: str) -> Triage:
"""Pure: accepts bare JSON or JSON inside a Markdown code fence, which models add even when told not to."""
body = re.sub(rf"^{FENCE}(?:json)?\s*|\s*{FENCE}$", "", text.strip())
try:
data = json.loads(body)
category, urgent = data["category"], data["urgent"]
# RecursionError: json.loads on absurdly nested input ("[[[[...") raises it, not JSONDecodeError
except (json.JSONDecodeError, KeyError, TypeError, RecursionError) as exc:
raise TriageParseError(f"not the expected JSON: {text[:60]!r}") from exc
# isinstance FIRST: a list or dict is valid JSON, and `[] in CATEGORIES` raises TypeError (unhashable)
if not isinstance(category, str) or category not in CATEGORIES or not isinstance(urgent, bool):
raise TriageParseError(f"unexpected values: category={category!r} urgent={urgent!r}")
return Triage(category, urgent)
def apply_rules(result: Triage, ticket: str) -> Triage:
"""Pure business rule: an outage is always urgent, whatever the model said."""
if "outage" in ticket.lower() and not result.urgent:
return Triage(result.category, True, result.needs_human, result.reason)
return result
def triage_ticket(chat: ChatModel, ticket: str, *, history: list[Message] | None = None,
user: str | None = None) -> Triage:
"""The only function that touches the model. It depends on the ChatModel protocol, not on an SDK."""
c = chat.complete(SYSTEM, build_messages(ticket, history), max_tokens=200, user=user)
if c.outcome != "ok": # refused or truncated: never parse half an answer
return Triage("other", False, needs_human=True, reason=c.outcome)
try:
return apply_rules(parse_triage(c.text), ticket)
except TriageParseError as exc:
return Triage("other", False, needs_human=True, reason=str(exc))captured_adapters.py wires each adapter to a capturing client; here it is, because the snapshot tests in Part 7 reuse it:
# captured_adapters.py
"""captured_adapters.py: every adapter wired to a client that CAPTURES its request instead of sending it."""
from __future__ import annotations
from typing import Any
import anthropic
from google import genai
from google.genai import types
from openai import OpenAI
from adapters import AnthropicChat, ChatCompletionsChat, GeminiChat, OpenAIResponsesChat
from wire_capture import WireCapture
NAMES = ["openai_responses", "openai_chat", "openrouter_chat", "anthropic", "gemini"]
def build_capturing(name: str, cap: WireCapture) -> Any:
"""Each adapter around a client that CAPTURES the request instead of sending it (no retries, so exactly one)."""
if name == "openai_responses":
return OpenAIResponsesChat(OpenAI(api_key="sk-test", max_retries=0, http_client=cap.httpx2_client()), "gpt-6-luna")
if name == "openai_chat":
return ChatCompletionsChat(OpenAI(api_key="sk-test", max_retries=0, http_client=cap.httpx2_client()), "gpt-6-luna")
if name == "openrouter_chat":
return ChatCompletionsChat(OpenAI(api_key="sk-or-test", base_url="https://openrouter.ai/api/v1", max_retries=0,
http_client=cap.httpx2_client()), "openai/gpt-6-luna", openrouter=True)
if name == "anthropic":
return AnthropicChat(anthropic.Anthropic(api_key="sk-ant-test", max_retries=0, http_client=cap.httpx2_client()),
"claude-haiku-5-5")
return GeminiChat(genai.Client(api_key="gemini-test", http_options=types.HttpOptions(httpx_client=cap.httpx_client())),
"gemini-3.8-flash")# s3_5_request_summary.py
"""One-line summaries of the request each adapter builds, for all four providers, without sending anything."""
from typing import Any
from captured_adapters import NAMES, build_capturing
from request_summary import summarize_request
from triage import triage_ticket
from wire_capture import WireCapture
HISTORY: list[Any] = [{"role": "user", "content": "My invoice looks wrong"},
{"role": "assistant", "content": '{"category": "billing", "urgent": false}'}]
for name in NAMES:
cap = WireCapture()
chat = build_capturing(name, cap)
sent = cap.run(lambda: triage_ticket(chat, "I was charged twice", history=HISTORY, user="u-hash"))
s = summarize_request(sent)
print(f"{name:<16} {s['endpoint']:<35} model={s['model']:<18} system={s['system_chars']:>3} chars "
f"turns={s['turns']} ({s['roles']}) cap={s['output_cap']} sampling={s['sampling']} user={s['user']}")openai_responses responses model=gpt-6-luna system=145 chars turns=3 (uau) cap=('max_output_tokens', 200) sampling=None user=u-hash
openai_chat completions model=gpt-6-luna system=145 chars turns=3 (uau) cap=('max_completion_tokens', 200) sampling=None user=u-hash
openrouter_chat completions model=openai/gpt-6-luna system=145 chars turns=3 (uau) cap=('max_tokens', 200) sampling=None user=u-hash
anthropic messages model=claude-haiku-5-5 system=145 chars turns=3 (uau) cap=('max_tokens', 200) sampling=None user=u-hash
gemini gemini-3.8-flash:generateContent model=gemini-3.8-flash system=145 chars turns=3 (uau) cap=('generationConfig.maxOutputTokens', 200) sampling=None user=u-hashOne screen answers the early checklist rows for all four providers (five adapters): the endpoint, the model, system=145 chars (so the instruction is present), turns=3 (uau) (user, assistant, user: the history survived and alternates), the output cap and what each provider calls it (max_output_tokens, max_completion_tokens, max_tokens, generationConfig.maxOutputTokens), no sampling parameters, and the hashed user, which every provider receives under its own name: safety_identifier (OpenAI), user (OpenRouter), metadata.user_id (Anthropic) and labels.safety_identifier (Gemini; 03.2, 9.1). If production's summary shows system=0 chars or turns=1, you've found rows 3 or 5 in about ten seconds.
3.5 Check the environment: versions, base URLs and stray variables#
Some bugs aren't in the request at all. A stray OPENAI_BASE_URL in a shell profile sends your "OpenAI" calls to a local server; HTTPS_PROXY sends them through a corporate proxy; a second GOOGLE_API_KEY takes precedence over your GEMINI_API_KEY (03.1, 7.2). diagnose.py prints the facts, and it's built so you can paste its output into a bug report: it says whether each key is set and never prints a key.
# s3_4_diagnose.py
"""diagnose.py: which SDK versions, settings and endpoints is this process really using?
Prints whether each key is set, never its value. Paste the output into a bug report."""
import os
import platform
from importlib.metadata import PackageNotFoundError, version
from urllib.parse import urlsplit, urlunsplit
from dotenv import load_dotenv
load_dotenv()
print("python", platform.python_version())
for pkg in ("openai", "anthropic", "google-genai", "httpx2", "httpx"):
try:
print(f" {pkg:<13}", version(pkg))
except PackageNotFoundError:
print(f" {pkg:<13}", "not installed")
# Environment variables the SDKs read on their own (a stray one silently changes where calls go)
WATCH = ["OPENAI_API_KEY", "OPENAI_BASE_URL", "OPENAI_ORG_ID", "OPENAI_PROJECT_ID", "OPENAI_LOG",
"ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL", "ANTHROPIC_PROFILE", "ANTHROPIC_LOG",
"ANTHROPIC_OPEN_TELEMETRY", "GEMINI_API_KEY", "GOOGLE_API_KEY", "GOOGLE_GEMINI_BASE_URL",
"GOOGLE_GENAI_USE_VERTEXAI", "GOOGLE_CLOUD_PROJECT", "OPENROUTER_API_KEY",
"HTTPS_PROXY", "HTTP_PROXY", "SSL_CERT_FILE"]
SECRET = ("KEY", "TOKEN")
def strip_userinfo(value: str) -> str:
"""Proxy URLs often look like http://user:password@host:3128. Show the host, never the password."""
parts = urlsplit(value)
return urlunsplit(parts._replace(netloc=parts.hostname + (f":{parts.port}" if parts.port else ""))) if parts.password or parts.username else value
for name in WATCH:
value = os.environ.get(name)
if value is None:
continue
shown = "set" if name.endswith(SECRET) else strip_userinfo(value) # never print a credential
print(f" env {name}={shown}")
# Where would a default client send requests? (No request is made.)
from anthropic import Anthropic # noqa: E402
from google import genai # noqa: E402
from openai import OpenAI # noqa: E402
print("openai base_url:", OpenAI(api_key=os.environ.get("OPENAI_API_KEY", "unset")).base_url)
print("anthropic base_url:", Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY", "unset")).base_url)
gem = genai.Client(api_key=os.environ.get("GEMINI_API_KEY", "unset"))
print("gemini base_url:", gem._api_client._http_options.base_url, # private attribute: diagnostics only
"| vertexai:", gem.vertexai)On a clean machine:
python 3.13.14
openai 3.42.1
anthropic 2.4.0
google-genai 2.34.0
httpx2 2.16.0
httpx 0.28.1
openai base_url: https://api.openai.com/v1/
anthropic base_url: https://api.anthropic.com
gemini base_url: https://generativelanguage.googleapis.com/ | vertexai: FalseWith a few things set (a fake OPENAI_API_KEY, a base URL pointing at the local model, ANTHROPIC_LOG=debug, and a proxy URL that includes a password):
python 3.13.14
openai 3.42.1
anthropic 2.4.0
google-genai 2.34.0
httpx2 2.16.0
httpx 0.28.1
env OPENAI_API_KEY=set
env OPENAI_BASE_URL=http://localhost:11434/v1
env ANTHROPIC_LOG=debug
env HTTPS_PROXY=http://proxy.corp.example:3128
openai base_url: http://localhost:11434/v1/
anthropic base_url: https://api.anthropic.com
gemini base_url: https://generativelanguage.googleapis.com/ | vertexai: FalseThe key shows as set, the proxy's alice:s3cret@ userinfo is gone, and the OpenAI line base_url: http://localhost:11434/v1/ immediately explains why calls from this shell never reach OpenAI. The proxy line matters because both SDKs' default HTTP clients honour HTTPS_PROXY and HTTP_PROXY (trust_env=True, which we checked in the pinned versions). The script reads one private attribute (gem._api_client._http_options.base_url) because the google-genai client doesn't expose its base URL publicly. That's fine for a diagnostic script and not for production code.
3.6 More habits that save hours#
- Make a minimal reproduction. Remove history turns, tools and options one at a time from the failing request until the problem disappears; the last thing you removed is involved. Do this on a replay (Part 5), not by editing the live feature.
- Compare against a known-good request. Keep one captured request that works as a snapshot (7.6); diff the failing one against it.
- Try the same body from outside your code. Replaying the stored body with
curlorhttpx2(Part 5) separates "my SDK usage" from "the provider's behaviour". - Ask the provider with the request ID. When you've shown the request is right and the behaviour is wrong, the ID of the failing attempt is what their support needs (03.8, Part 12). The ID is also how you find the provider's own record of the call: OpenAI's dashboard has a logs view you can search by request ID, the Anthropic Console has a usage and logs section, and OpenRouter's activity page lists generations, which you can also fetch with
GET /api/v1/generation?id=(03.7, 9.3). Menu names change, so search the console for "logs" or "activity"; what stays the same is that you paste the ID. - Use a proxy when you must see TLS traffic from a process you can't change. A tool such as
mitmproxycan sit between your app and the provider and record everything. Forhttpx2clients, trust its certificate by settingSSL_CERT_FILE, as the certificate note in 03.1, 4.5 explains. (Not run here; it needs installing and configuring a CA on your machine.) For code you control, hooks (2.3) do the same job with redaction built in.
Part 4: Structured logging of every call#
Debug logs (Part 2) are for you, once, at your desk. Structured logs are for the system, always: one machine-readable record per model call, with the same fields every time, so you can later ask questions such as "which feature's p95 latency doubled on Tuesday?", "how many calls were retried?" or "which model snapshot actually served the bad answers?".
4.1 What to log, and what not to#
One call, one record. These are the fields worth having, and what each answers:
| Field | Answers | Where it comes from |
|---|---|---|
trace_id |
"Show me everything that happened for this user request" | Your code (4.4) |
request_id |
"What do we tell the provider's support?" | The response: x-request-id, request-id, x-generation-id, or Gemini's response_id (1.5) |
provider, api |
"Responses or Chat Completions? Which family?" | Your adapter |
model_requested, model_resolved |
"Did an alias move?" | Your config; the response's model / model_version |
latency_ms, ttft_ms |
"Is it slow, and is it the model or the network?" | Your clock. ttft_ms (time to first token) only for streams (4.9) |
attempts |
"Were retries hiding failures?" | A hook counter or retries_taken |
uncached_input_tokens, cached_input_tokens, cache_write_tokens, total_input_tokens, output_tokens, reasoning_tokens |
"What did it consume? Is caching working? What did the context cost?" | The response's usage, converted to the module convention by 03.7's cost_calc.from_* (below). Log all of them: you can't reconstruct a missing one later |
cost_usd |
"What did this call cost?" | Computed by 03.7's cost_calc.price() from the same usage; null when unknown |
finish_reason, outcome |
"Did it finish, get cut off, or refuse?" | The response (03.8, Part 10) |
error_class, error_status |
"What failed, and with which HTTP status?" | The exception |
feature (or route) |
"Which product feature made this call?" | Set at the call site, never guessed later |
user |
"Is one user driving the traffic or the errors?" | A keyed hash of the user ID, never the raw ID or email |
prompt_version |
"Did the template change?" | A constant you bump when you edit the prompt |
prompt_sha256 |
"Is this the same prompt as before?" | A short hash of the system and user text: compares prompts without storing them |
input_chars, max_tokens |
"How big was the request, and what cap was set?" | The request |
sdk |
"Which SDK version was running?" | importlib.metadata.version(...) |
env |
"Prod, staging, or a laptop?" | Configuration |
The token fields mean the same thing for every provider. The raw numbers don't: OpenAI's input_tokens and Gemini's prompt_token_count include cached tokens, Anthropic's input_tokens excludes them, and Gemini's candidates_token_count excludes thinking while the others include it. A dashboard that grouped by "input tokens" across providers would mix three meanings. So the log follows the convention of 03.7, 3.1: uncached_input_tokens is what is billed at the plain input rate, cached_input_tokens and cache_write_tokens are separate, total_input_tokens is the sum of the three (the size of the prompt), and output_tokens includes reasoning, with reasoning_tokens as an informational part of it. The adapters get these from cost_calc.from_*, which is the one place that conversion lives, so a cache-heavy call looks the same in the log whichever provider served it (the test in 7.3 checks exactly that).
What not to log by default:
| Don't log | Why | Instead |
|---|---|---|
| Prompts and responses | They hold personal data, trade secrets, credentials people paste into chats, and anything a tool returned. Log retention is long and access is wide | A hash, a length, and a flag-controlled, redacted, sampled excerpt (4.5) |
| API keys, auth headers, cookies | An obvious leak, but it happens through "log the request" helpers | Show only allow-listed headers (2.3) |
| Raw user IDs, emails | Logs are read by more people than the database is | A keyed hash |
| Tool arguments and results | They often contain exactly what the user asked about: addresses, account numbers | Log the tool name and a size or hash |
| Provider error messages, unfiltered | A 400 message can quote part of your input back at you |
Log the class, the status and the error type / code; treat the free-text message as content |
| Images, PDFs, base64 blobs | Megabytes per line, and a copy of the user's file, metadata included (03.6) | Size, media type and a hash |
4.2 JSON logs with the standard logging module#
You don't need a logging framework. The standard library produces JSON Lines (one JSON object per line, the format log pipelines read best) with a small formatter. llm_log.py has these parts: the formatter, the config (with the hashing key), a CallLogger that builds and writes the record, and the LoggedChat wrapper that logs every call made through any ChatModel. It builds on the Completion and adapters of 1.5, on cost_calc and prices from 03.7, and on redact.py from 2.3. The async and streaming wrappers are in 4.9; they reuse CallLogger, so every kind of call writes the same line.
# llm_log.py
"""llm_log.py: one structured JSON line per model call, with content off by default (lesson 03.10).
Token fields follow the module convention of lesson 03.7 (3.1): `uncached_input_tokens` is billed at the plain input
rate, cached reads and cache writes have their own fields, and `output_tokens` already includes reasoning."""
from __future__ import annotations
import hashlib
import hmac
import json
import logging
import os
import random
import secrets
import time
from collections.abc import Callable
from contextvars import ContextVar
from dataclasses import dataclass, field
from datetime import datetime, timezone
from importlib.metadata import version
from typing import Any
import cost_calc
from chat_types import ChatModel, Completion, Message, new_trace_id, trace_id_var
from prices import PriceTable
from redact import redact_text
log = logging.getLogger("llm.calls")
class JsonFormatter(logging.Formatter):
"""Turns a record carrying `fields` into one JSON object per line (JSON Lines)."""
def __init__(self, indent: int | None = None) -> None:
super().__init__()
self.indent = indent # None in production (one line); 2 for reading in a terminal
def format(self, record: logging.LogRecord) -> str:
payload = {"ts": datetime.fromtimestamp(record.created, timezone.utc).isoformat(timespec="milliseconds"),
"level": record.levelname, "event": record.getMessage(), **getattr(record, "fields", {})}
return json.dumps(payload, default=str, ensure_ascii=False, indent=self.indent)
@dataclass
class LogConfig:
env: str = "dev"
log_content: bool = False # the flag: prompts and replies stay out of logs unless this is on
content_sample_rate: float = 0.0 # or log content for this fraction of calls (0.01 = 1 in 100)
max_content_chars: int = 500
# The secret for the keyed user hash. NO default: pass it, or set USER_ID_PEPPER (from your secret store, like an API key;
# the same variable as lesson 03.2, 10.3).
hash_key: bytes | None = field(default=None, repr=False)
rng: Callable[[], float] = random.random # injectable, so tests are deterministic
_key: bytes = field(init=False, repr=False, default=b"")
def __post_init__(self) -> None:
key = self.hash_key or os.environ.get("USER_ID_PEPPER", "").encode()
if not key:
if self.env != "dev": # fail closed: a missing key must stop the service, not weaken the hash
raise ValueError(f"env={self.env!r} needs a secret hash key: pass hash_key= or set USER_ID_PEPPER")
key = secrets.token_bytes(32) # dev: random per process. Hashes won't match across restarts; nothing is guessable
self._key = key
@property
def key(self) -> bytes:
return self._key
LOG_PURPOSE = "logs-v1" # the ID written to YOUR logs
PROVIDER_PURPOSE = "llm-abuse-v1" # the ID sent to the provider (lesson 03.2, 10.3). Different purpose = unlinkable IDs
def hash_user(user_id: str, key: bytes, purpose: str = LOG_PURPOSE) -> str:
"""The keyed hash of lesson 03.2, 10.3: HMAC-SHA256 over "purpose:user_id". Stable per user and purpose, but nobody can
rebuild it from a list of emails without the key, and the log ID can't be matched to the ID a provider holds.
16 hex characters = 64 bits: enough to correlate one user's calls, not collision-proof across billions of users."""
return hmac.new(key, f"{purpose}:{user_id}".encode(), hashlib.sha256).hexdigest()[:16]
_attempts: ContextVar[int] = ContextVar("http_attempts", default=0)
def count_attempts() -> dict[str, list[Any]]:
"""event_hooks for the SDK's HTTP client: counts every HTTP attempt, retries included (sync clients)."""
def on_request(request: Any) -> None:
_attempts.set(_attempts.get() + 1)
return {"request": [on_request]}
def count_attempts_async() -> dict[str, list[Any]]:
"""The same counter for async clients (AsyncOpenAI, AsyncAnthropic): an async client awaits its hooks."""
async def on_request(request: Any) -> None:
_attempts.set(_attempts.get() + 1)
return {"request": [on_request]}
def price_with(table: PriceTable) -> Callable[[Completion], float | None]:
"""A `price=` function built on lesson 03.7: Completion.usage is already a cost_calc.Usage, so this is one line."""
def price(c: Completion) -> float | None:
return None if c.usage is None else round(cost_calc.price(c.usage, table).usd, 10) # tidy float noise
return price
def usage_from_record(rec: dict[str, Any], *, write_ttl: str | None = None) -> cost_calc.Usage:
"""Rebuild a cost_calc.Usage from one logged line, to (re)price old logs with a newer price table.
The log keeps ONE cache-write total, but prices differ by lifetime (Anthropic 5m vs 1h), so say which one applies.
Not in the line, so not rebuilt: the service tier, batch, regional and search counts."""
if rec.get("uncached_input_tokens") is None:
raise ValueError("this record has no usage (the call failed, or the provider sent none)")
written = rec.get("cache_write_tokens") or 0
if written and write_ttl is None:
raise ValueError("this call wrote to the cache: pass write_ttl= ('5m', '1h', '30m'... as in your price table)")
return cost_calc.Usage(
provider=rec["provider"], model=rec["model_requested"], # the alias: it is the key in your price table
input=rec["uncached_input_tokens"], cached_input=rec.get("cached_input_tokens") or 0,
cache_writes={write_ttl: written} if written and write_ttl else {},
output=rec.get("output_tokens") or 0, reasoning=rec.get("reasoning_tokens") or 0)
class CallLogger:
"""Builds and writes the record. LoggedChat (sync), ALoggedChat and logged_stream (async) all use it,
so every kind of call produces the same line."""
def __init__(self, *, provider: str, api: str, model: str, feature: str, sdk_package: str,
cfg: LogConfig | None = None, price: Callable[[Completion], float | None] | None = None,
clock: Callable[[], float] = time.perf_counter) -> None:
self.provider, self.api, self.model, self.feature = provider, api, model, feature
self.cfg, self.price, self.clock = cfg or LogConfig(), price, clock
self.sdk = f"{sdk_package}=={version(sdk_package)}"
def start(self, system: str, messages: list[Message], *, max_tokens: int, user: str | None,
prompt_version: str | None) -> PendingCall:
trace = trace_id_var.get() or new_trace_id()
_attempts.set(0)
prompt_text = "\n".join(m["content"] for m in messages)
user_hash = hash_user(user, self.cfg.key) if user else None # for the log line
provider_user = hash_user(user, self.cfg.key, PROVIDER_PURPOSE) if user else None # for the provider
record: dict[str, Any] = {
"trace_id": trace, "env": self.cfg.env, "feature": self.feature, "provider": self.provider, "api": self.api,
"model_requested": self.model, "sdk": self.sdk, "prompt_version": prompt_version, "user": user_hash,
"max_tokens": max_tokens, "input_chars": len(system) + len(prompt_text),
# a fingerprint, not the content: equal hashes mean "the same prompt" (spot accidental changes, cache misses)
"prompt_sha256": hashlib.sha256((system + "\x00" + prompt_text).encode()).hexdigest()[:12]}
return PendingCall(self, record, prompt_text, trace, provider_user, started=self.clock())
class PendingCall:
"""One call in flight. Call finish() exactly once, with the Completion or the exception."""
def __init__(self, owner: CallLogger, record: dict[str, Any], prompt_text: str, trace: str,
provider_user: str | None, started: float) -> None:
self.owner, self.record, self.prompt_text = owner, record, prompt_text
self.trace, self.provider_user, self.started = trace, provider_user, started
def finish(self, c: Completion | None = None, exc: BaseException | None = None, *,
ttft_ms: int | None = None, chunks: int | None = None) -> None:
owner, record = self.owner, self.record
latency = round((owner.clock() - self.started) * 1000)
if exc is not None:
record |= {"latency_ms": latency, "ttft_ms": ttft_ms, "attempts": _attempts.get() or None,
"outcome": "error", "error_class": type(exc).__name__,
"error_status": getattr(exc, "status_code", None), "request_id": getattr(exc, "request_id", None)}
if chunks is not None:
record["chunks"] = chunks # a stream that broke: how much had arrived
log.error("llm_call", extra={"fields": record})
return
if c is None: # a stream that ended without a final message: usage unknown
c = Completion(text="", outcome="ok", finish_reason=None, model=None, request_id=None)
record["outcome_note"] = "stream ended without a final message"
record |= {
"latency_ms": latency, "ttft_ms": ttft_ms, # ttft_ms is None for non-streaming calls
"attempts": _attempts.get() or c.attempts, "outcome": c.outcome, "finish_reason": c.finish_reason,
"request_id": c.request_id, "model_resolved": c.model,
"uncached_input_tokens": c.uncached_input_tokens, "cached_input_tokens": c.cached_input_tokens,
"cache_write_tokens": c.cache_write_tokens, "total_input_tokens": c.total_input_tokens,
"output_tokens": c.output_tokens, "reasoning_tokens": c.reasoning_tokens}
if chunks is not None:
record["chunks"] = chunks
try:
c.cost_usd = owner.price(c) if owner.price else None
except Exception: # accounting must never break the user's request
log.exception("price function failed")
c.cost_usd = None
record["cost_usd"] = c.cost_usd # None = unknown, never 0
cfg = owner.cfg
if cfg.log_content or cfg.rng() < cfg.content_sample_rate:
cut = cfg.max_content_chars
record["content"] = {"prompt": redact_text(self.prompt_text)[:cut], "reply": redact_text(c.text)[:cut]}
degraded = c.outcome != "ok" or record["attempts"] > 1
log.log(logging.WARNING if degraded else logging.INFO, "llm_call", extra={"fields": record})
class LoggedChat:
"""Wraps any ChatModel and writes one JSON line per call: success, soft failure or exception."""
def __init__(self, inner: ChatModel, *, provider: str, api: str, model: str, feature: str,
sdk_package: str, cfg: LogConfig | None = None,
price: Callable[[Completion], float | None] | None = None,
clock: Callable[[], float] = time.perf_counter) -> None:
self.inner = inner
self.logger = CallLogger(provider=provider, api=api, model=model, feature=feature,
sdk_package=sdk_package, cfg=cfg, price=price, clock=clock)
def complete(self, system: str, messages: list[Message], *, max_tokens: int, user: str | None = None,
prompt_version: str | None = None) -> Completion:
call = self.logger.start(system, messages, max_tokens=max_tokens, user=user, prompt_version=prompt_version)
token = trace_id_var.set(call.trace)
try:
c = self.inner.complete(system, messages, max_tokens=max_tokens, user=call.provider_user)
except Exception as exc:
call.finish(exc=exc)
raise
finally:
trace_id_var.reset(token)
call.finish(c)
return cHere is the path one call takes through the layers, and where each piece of information is produced:
sequenceDiagram
participant App as Your code
participant Log as LoggedChat wrapper
participant Ad as Adapter
participant SDK as SDK client
participant Hook as HTTP event hooks
participant API as Provider API
App->>Log: complete(system, messages)
Note over Log: sets trace_id, starts the clock
Log->>Ad: complete(system, messages, user hash)
Ad->>SDK: responses.with_raw_response.create(...)
loop each HTTP attempt, retries included
SDK->>Hook: request hook (headers redacted)
Hook->>API: HTTP request
API-->>Hook: HTTP response
Hook-->>SDK: response hook (status, request id)
end
SDK-->>Ad: parsed object plus raw headers
Ad-->>Log: Completion (usage, model served, request id)
Note over Log: one JSON line: no content unless flagged
Log-->>App: CompletionHow it works, and why it's built this way:
- A wrapper, not a decorator on every call site.
LoggedChat(inner, ...)is itself aChatModel, so business code can't tell the difference, and tests can use the unwrapped adapter. Logging is composition, not an edit to each call. - One record per call, written in every outcome. Success writes an
INFOline, a soft failure (outcome != "ok") or a retried call writesWARNING, an exception writesERRORand then re-raises. The user's request never changes behaviour because of logging. - Missing values stay
null.ttft_ms(for non-streaming calls), the token fields andcost_usdarenullwhen unknown, because zero would claim something false. - Pricing can't break a request, and it is one line.
Completion.usageis already a 03.7cost_calc.Usage, soprice=price_with(PriceTable.load("prices.yaml"))prices every call with 03.7'scost_calc.price(), and this lesson doesn't re-teach cost maths. If the price function raises (a new model missing from the table), the wrapper logs that and recordscost_usd: null, like 03.7's tracker. To re-price old log lines with a newer table,usage_from_record(line, write_ttl="5m")turns a line back into aUsage: the field names map one to one, and the line keeps a single cache-write total, so you must say which lifetime it was (forgetting is an error, not a guess). - The attempt count comes from an HTTP hook,
count_attempts(), which increments a counter for every request the client sends. That's the only way to know how many attempts failed calls made, because SDK exceptions don't carry a retry count. Pass it asevent_hookswhen you build the client (count_attempts_async()for async clients, 4.9). - Everything time-related and random is injectable (
clock,rng), so tests are exact (Part 9). - The user ID is hashed twice, with two purposes.
hash_user(user, key)(purpose"logs-v1") is the value written to the log line. The adapter receives a different value,hash_user(user, key, "llm-abuse-v1"), which is what the provider gets as its abuse-tracking ID (1.5). This is the keyed hash of 03.2, 10.3 with its purpose string, so a provider's abuse report can't be matched to your logs by anyone who has both. The 16-hex truncation is for short log lines; the secret is the sameUSER_ID_PEPPERvariable. - The hash key (
hash_key) is a secret like an API key, and it has no default. Pass it, or setUSER_ID_PEPPERfrom your secret store. Withenv="dev"and no key,LogConfigmakes a random one for the process (so the hashes are not comparable across restarts, and nothing is guessable); with any otherenvand no key it raises at construction, so a forgotten secret stops the service instead of quietly turning the keyed hash into a hash with a public key. The key is also kept out of the config'srepr, so it can't land in a log by accident. 03.7's tracker has the same weakness in its development fallback (USER_ID_PEPPER): don't rely on it outside development.
4.3 Try it: a real call, a retried call and a failed call#
This script wires the logger to a real call on the free local model, then to two mock servers: a 429 followed by a 200 (to show retries in the log), and a 401 (to show the error line). It pretty-prints the JSON with indent=2 so you can read it; in production you'd leave the indent off and get one line per call. The prompt contains a fake email address and a fake key-shaped string on purpose, to exercise the redaction. The price function is 03.7's cost_calc.price() over its fake local price table (prices_fake_local.yaml: $1 per million input tokens and $5 per million output), not real prices. The script sets USER_ID_PEPPER itself, because the hash key has no default.
# s4_2_json_log.py
"""One structured JSON line per call: a real call to the free local model, then two MOCK servers
(a 429 followed by a 200, and a 401 that raises). Prompts contain fake PII to show the redaction."""
import logging
import os
import secrets
import sys
import httpx2
import openai
from openai import OpenAI
from adapters import OpenAIResponsesChat
from chat_types import Message, new_trace_id, trace_id_var
from llm_log import JsonFormatter, LoggedChat, LogConfig, count_attempts, price_with
from prices import PriceTable
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(JsonFormatter(indent=2)) # indent only for reading; production: one line
logging.getLogger("llm.calls").addHandler(handler)
logging.getLogger("llm.calls").setLevel(logging.INFO)
os.environ.setdefault("USER_ID_PEPPER", secrets.token_hex(16)) # the keyed-hash secret. In production: your secret store
FAKE_PRICE = price_with(PriceTable.load("prices_fake_local.yaml")) # FAKE rates (03.7): $1 per million input, $5 output
PROMPT: list[Message] = [{"role": "user", "content": "Mail jane.doe@example.com, my key is sk-test-1234567890abcdefghij"}]
# 1) Real call to the local stand-in (Ollama): no request id comes back from Ollama, so request_id is null
local = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama", max_retries=0,
http_client=openai.DefaultHttpx2Client(event_hooks=count_attempts()))
chat = LoggedChat(OpenAIResponsesChat(local, "gpt-6-luna"), provider="openai", api="responses", model="gpt-6-luna",
feature="demo", sdk_package="openai", cfg=LogConfig(env="dev", log_content=True), price=FAKE_PRICE)
trace_id_var.set(new_trace_id()) # e.g. set per HTTP request by your web framework
chat.complete("Be brief.", PROMPT, max_tokens=20, user="user-42@example.com", prompt_version="demo-v1")
# 2) MOCK server: a 429 first, then a 200 with request ids. The SDK retries once; the log line says so.
BODY = {"id": "resp_1", "object": "response", "status": "completed", "model": "gpt-6-luna-2026-10-01",
"output": [{"type": "message", "id": "msg_1", "role": "assistant", "status": "completed",
"content": [{"type": "output_text", "text": "Done.", "annotations": []}]}],
"usage": {"input_tokens": 30, "output_tokens": 3, "total_tokens": 33,
"input_tokens_details": {"cached_tokens": 0}, "output_tokens_details": {"reasoning_tokens": 0}}}
replies = iter([httpx2.Response(429, json={"error": {"message": "Rate limit reached", "type": "rate_limit_error"}},
headers={"retry-after-ms": "5", "x-request-id": "req_a"}),
httpx2.Response(200, json=BODY, headers={"x-request-id": "req_b"})])
mock = OpenAI(api_key="sk-test", max_retries=2, http_client=openai.DefaultHttpx2Client(
transport=httpx2.MockTransport(lambda r: next(replies)), event_hooks=count_attempts()))
trace_id_var.set(None)
LoggedChat(OpenAIResponsesChat(mock, "gpt-6-luna"), provider="openai", api="responses", model="gpt-6-luna",
feature="demo", sdk_package="openai", price=FAKE_PRICE).complete(
"Be brief.", PROMPT, max_tokens=20, user="user-42@example.com", prompt_version="demo-v1")
# 3) MOCK server: a 401. The exception still propagates, and one error line is logged first.
bad = OpenAI(api_key="sk-test", max_retries=2, http_client=openai.DefaultHttpx2Client(
transport=httpx2.MockTransport(lambda r: httpx2.Response(
401, json={"error": {"message": "Incorrect API key provided", "type": "invalid_request_error"}},
headers={"x-request-id": "req_c"})), event_hooks=count_attempts()))
try:
LoggedChat(OpenAIResponsesChat(bad, "gpt-6-luna"), provider="openai", api="responses", model="gpt-6-luna",
feature="demo", sdk_package="openai").complete("Be brief.", PROMPT, max_tokens=20)
except openai.AuthenticationError as e:
print("raised:", type(e).__name__)Output (call 1 uses the local model qwen2.5:0.5b via Ollama; calls 2 and 3 are mock servers):
{
"ts": "2026-11-04T15:20:07.857+00:00",
"level": "INFO",
"event": "llm_call",
"trace_id": "804176950a71419b93f27bbdb0572bf1",
"env": "dev",
"feature": "demo",
"provider": "openai",
"api": "responses",
"model_requested": "gpt-6-luna",
"sdk": "openai==3.42.1",
"prompt_version": "demo-v1",
"user": "2c277138abd996ae",
"max_tokens": 20,
"input_chars": 74,
"prompt_sha256": "829a7e932866",
"latency_ms": 234,
"ttft_ms": null,
"attempts": 1,
"outcome": "ok",
"finish_reason": "completed",
"request_id": null,
"model_resolved": "gpt-6-luna",
"uncached_input_tokens": 41,
"cached_input_tokens": 0,
"cache_write_tokens": 0,
"total_input_tokens": 41,
"output_tokens": 20,
"reasoning_tokens": 0,
"cost_usd": 0.000141,
"content": {
"prompt": "Mail [EMAIL], my key is [API_KEY]",
"reply": "Send mail to [EMAIL] with your key: sk-test-12345"
}
}
{
"ts": "2026-11-04T15:20:07.867+00:00",
"level": "WARNING",
"event": "llm_call",
"trace_id": "7c270411a72f48008e3f30a310c21448",
"env": "dev",
"feature": "demo",
"provider": "openai",
"api": "responses",
"model_requested": "gpt-6-luna",
"sdk": "openai==3.42.1",
"prompt_version": "demo-v1",
"user": "2c277138abd996ae",
"max_tokens": 20,
"input_chars": 74,
"prompt_sha256": "829a7e932866",
"latency_ms": 8,
"ttft_ms": null,
"attempts": 2,
"outcome": "ok",
"finish_reason": "completed",
"request_id": "req_b",
"model_resolved": "gpt-6-luna-2026-10-01",
"uncached_input_tokens": 30,
"cached_input_tokens": 0,
"cache_write_tokens": 0,
"total_input_tokens": 30,
"output_tokens": 3,
"reasoning_tokens": 0,
"cost_usd": 4.5e-05
}
{
"ts": "2026-11-04T15:20:07.867+00:00",
"level": "ERROR",
"event": "llm_call",
"trace_id": "289c88a65e064df09781b78f39d11060",
"env": "dev",
"feature": "demo",
"provider": "openai",
"api": "responses",
"model_requested": "gpt-6-luna",
"sdk": "openai==3.42.1",
"prompt_version": null,
"user": null,
"max_tokens": 20,
"input_chars": 74,
"prompt_sha256": "829a7e932866",
"latency_ms": 0,
"ttft_ms": null,
"attempts": 1,
"outcome": "error",
"error_class": "AuthenticationError",
"error_status": 401,
"request_id": "req_c"
}
raised: AuthenticationErrorRead the three records as a debugging session would:
- The local call.
request_idisnullbecause Ollama sends none.model_resolvedequals the requested alias because the local server echoes it back.cached_input_tokens: 0,cache_write_tokens: 0andreasoning_tokens: 0are real numbers from the local server, andtotal_input_tokensequalsuncached_input_tokens(41) because nothing was cached.cost_usdis 41 × $1 + 20 × $5 = $141 per million, which is0.000141.contentis present only because this call setlog_content=True, and the prompt was redacted before it was written:Mail [EMAIL], my key is [API_KEY]. Thereplyis whatever the tiny model wrote; replies are redacted too, because models do echo parts of their prompts, and redaction can miss them (4.5). - The retried call.
levelisWARNINGandattemptsis2: the first attempt got the 429 and the SDK retried.latency_msis small only because this is a mock.request_idisreq_b, the ID of the successful attempt, andmodel_resolvedisgpt-6-luna-2026-10-01whilemodel_requestedis the aliasgpt-6-luna: this is exactly the field that tells you an alias moved. Bothuserfields are the same 16 characters across calls 1 and 2 (stable per user) and unrelated to the email.prompt_sha256is829a7e932866in both, so you can see these were the same prompt. - The failed call.
levelisERROR,outcomeiserror,error_classisAuthenticationError,error_statusis401, andrequest_idisreq_c, taken from the exception, so a call that never produced a response still leaves an ID for support. There's no usage because there was no response. The exception still propagated (raised: AuthenticationError).
4.4 Correlation IDs: one ID from your code to the provider#
Two IDs matter for one call. The provider's request ID comes back (you log it so support can find the call). Your trace ID goes out with the call and into every log line (so you can find all the work for one user request). Where each travels:
| Provider | Your ID goes in | The provider's ID comes back in | Notes (as of November 2026) |
|---|---|---|---|
| OpenAI | The X-Client-Request-Id request header (opt-in; ASCII, at most 512 characters, or the request fails with a 400) |
x-request-id response header; response._request_id |
metadata and safety_identifier (a hashed user) are separate request fields |
| Anthropic | No client-request-ID header is documented. metadata.user_id carries an opaque user identifier, not a trace |
request-id response header; message._request_id; also request_id in error bodies; anthropic-organization-id and anthropic-workspace-id headers |
Don't put names, emails or phone numbers in user_id |
| Gemini | A request labels object (Cloud label rules). The SDK accepts and sends labels for generate_content; whether your tier honours them isn't something the SDK can tell you, so verify before relying on it |
No request-ID header is documented: log response.response_id |
Keep your own trace ID in your logs as the primary key |
| OpenRouter | user, session_id (or the x-session-id header), and a free-form trace object that OpenRouter's Broadcast feature forwards to your observability destinations |
X-Generation-Id response header, then GET /api/v1/generation?id=... |
Send session_id and trace through extra_body= with the openai SDK (03.1, 6.6) |
The size limits for these fields (metadata pairs, user and label lengths) change and belong to 03.2, 9.1, which keeps the table. The IDs are also how you find the provider's own record of a call: see the pointer in 3.6.
The pattern that works for all four: generate (or accept) one trace ID per user request, keep it in a ContextVar, put it on every log line, and send it to any provider that has a field for it. chat_types.py already defines trace_id_var. LoggedChat reads it (or creates one) and the OpenAI adapter sends it as X-Client-Request-Id. The place to set it is the edge of your system, once per incoming request. Here is a FastAPI middleware, driven in-process by TestClient so it needs no server and no model:
# s4_4_trace_middleware.py
"""Set the trace ID once per web request, and every log line below it carries it. FastAPI's TestClient drives the app
in-process (no server, no network); the model is a scripted fake, so this runs anywhere."""
import logging
import sys
from fastapi import FastAPI, Request
from fastapi.testclient import TestClient
from chat_types import Completion, new_trace_id, trace_id_var
from cost_calc import Usage
from llm_log import JsonFormatter, LoggedChat
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(JsonFormatter())
logging.getLogger("llm.calls").addHandler(handler)
logging.getLogger("llm.calls").setLevel(logging.INFO)
class ScriptedChat: # stands in for a real adapter
def complete(self, system, messages, *, max_tokens, user=None): # type: ignore[no-untyped-def]
return Completion(text="ok", outcome="ok", finish_reason="stop", model="gpt-6-luna-2026-10-01",
request_id="req_8f2c51d0a7",
usage=Usage(provider="openai", model="gpt-6-luna", input=40, output=2))
chat = LoggedChat(ScriptedChat(), provider="openai", api="responses", model="gpt-6-luna", feature="triage",
sdk_package="openai")
app = FastAPI()
@app.middleware("http")
async def trace_ids(request: Request, call_next): # type: ignore[no-untyped-def]
# Reuse the caller's ID (a gateway or front-end may have set one), otherwise make one. Validate it: it is user input.
incoming = request.headers.get("x-request-id", "")
trace = incoming if incoming.isascii() and 8 <= len(incoming) <= 64 and incoming.replace("-", "").isalnum() else new_trace_id()
token = trace_id_var.set(trace)
try:
response = await call_next(request)
finally:
trace_id_var.reset(token)
response.headers["x-request-id"] = trace # hand it back, so users can quote it in a bug report
return response
@app.post("/triage")
def triage(ticket: dict) -> dict:
chat.complete("Triage.", [{"role": "user", "content": ticket["text"]}], max_tokens=50)
return {"ok": True}
client = TestClient(app)
r = client.post("/triage", json={"text": "I was charged twice"}, headers={"x-request-id": "front-end-7f3a91c2"})
print("response header x-request-id:", r.headers["x-request-id"])
r = client.post("/triage", json={"text": "hello"}, headers={"x-request-id": "not valid!! <script>"})
print("bad incoming id replaced by:", r.headers["x-request-id"]){"ts": "2026-11-04T15:19:29.202+00:00", "level": "INFO", "event": "llm_call", "trace_id": "front-end-7f3a91c2", "env": "dev", "feature": "triage", "provider": "openai", "api": "responses", "model_requested": "gpt-6-luna", "sdk": "openai==3.42.1", "prompt_version": null, "user": null, "max_tokens": 50, "input_chars": 26, "prompt_sha256": "55635c2c84a0", "latency_ms": 0, "ttft_ms": null, "attempts": 1, "outcome": "ok", "finish_reason": "stop", "request_id": "req_8f2c51d0a7", "model_resolved": "gpt-6-luna-2026-10-01", "uncached_input_tokens": 40, "cached_input_tokens": 0, "cache_write_tokens": 0, "total_input_tokens": 40, "output_tokens": 2, "reasoning_tokens": 0, "cost_usd": null}
response header x-request-id: front-end-7f3a91c2
{"ts": "2026-11-04T15:19:29.205+00:00", "level": "INFO", "event": "llm_call", "trace_id": "cc8e253cec6045609defeb83c3b1f70a", "env": "dev", "feature": "triage", "provider": "openai", "api": "responses", "model_requested": "gpt-6-luna", "sdk": "openai==3.42.1", "prompt_version": null, "user": null, "max_tokens": 50, "input_chars": 12, "prompt_sha256": "64e712c869c9", "latency_ms": 0, "ttft_ms": null, "attempts": 1, "outcome": "ok", "finish_reason": "stop", "request_id": "req_8f2c51d0a7", "model_resolved": "gpt-6-luna-2026-10-01", "uncached_input_tokens": 40, "cached_input_tokens": 0, "cache_write_tokens": 0, "total_input_tokens": 40, "output_tokens": 2, "reasoning_tokens": 0, "cost_usd": null}
bad incoming id replaced by: cc8e253cec6045609defeb83c3b1f70aThree things to copy from this. The middleware accepts the caller's ID (so a front-end or gateway ID follows the request through) but validates it, because a header is user input: the second request sent not valid!! <script> and got a fresh ID instead. It returns the ID in the response, so a user's bug report can quote it. And the log line inside the endpoint carries the same trace_id with no code at the call site knowing about it, because a ContextVar follows the request through sync endpoints (which FastAPI runs in a thread pool) and async code alike.
4.5 Content in logs: flag, redact, sample#
Sometimes you do need the words: a user reports a bad answer, and the hash can't tell you what the model said. The safe design makes content logging an explicit, narrow decision:
- Off by default, controlled by
LogConfig.log_content. Production runs with it off. - Sampled when on.
content_sample_rate=0.01logs content for about 1 call in 100, enough to eyeball quality and spot problems without keeping a copy of everything. - Redacted before it's written. Run the text through a scrubber for the patterns that must never be kept: keys, tokens, emails, card and phone numbers.
- Truncated (
max_content_chars), so a pasted novel can't become a megabyte of log. - Stored where access is controlled and retention is short, which is a deployment decision for Module 11C and a policy decision for Module 12.
redact.py — listed in 2.3, where wire_log.py first needed it — has two layers. redact_secrets() knows credential shapes (it is safe to run on headers and URLs as well as free text), and redact_text() adds personal data for free text such as prompts and replies. Content logging is where the second layer earns its keep, and its limits matter here.
The credential list covers the four main LLM key shapes (OpenAI sk-proj-, Anthropic sk-ant-, OpenRouter sk-or-v1-, Gemini AIza) and the ones that turn up in prompts and logs when a developer pastes a shell history or an error: GitHub (ghp_, github_pat_), xAI (xai-), Groq (gsk_), Hugging Face (hf_), AWS access key IDs (AKIA), Google OAuth tokens (ya29.), JWTs (three base64url parts), anything after the word Bearer, and password: ... / api_key=... pairs (the name is kept, the value hidden). Vendors add prefixes, so each shape has a test: tests/test_redact.py builds one string per vendor at run time from the real prefix and an obviously fake body ("EXAMPLE" * 8), so no real or realistic secret is stored in the repository, and checks that each one disappears from the middle of a sentence. A list like this is never finished; the test is how you notice a gap.
Here is that test file. It needs only redact.py and pytest:
# tests/test_redact.py
"""One test per credential shape in redact.py. Every secret is assembled at run time from a real vendor prefix and an
obviously fake body, so no real or realistic credential is stored in the repository."""
import pytest
from redact import find_secrets, redact_secrets, redact_text
FAKE = "EXAMPLE" * 8 # 56 characters: long enough for every shape, impossible to mistake for a key
SHAPES = {
"openai": "sk-" + "proj-" + FAKE,
"anthropic": "sk-" + "ant-" + FAKE,
"openrouter": "sk-" + "or-v1-" + FAKE,
"gemini": "AI" + "za" + FAKE,
"google_oauth": "ya29" + "." + FAKE,
"github": "gh" + "p_" + FAKE[:36],
"github_pat": "github_" + "pat_" + FAKE,
"xai": "xai" + "-" + FAKE,
"groq": "gsk" + "_" + FAKE,
"huggingface": "hf" + "_" + FAKE,
"aws": "AK" + "IA" + FAKE[:16],
"jwt": "ey" + "J" + FAKE[:12] + "." + FAKE[:12] + "." + FAKE[:12],
"bearer": "Bearer " + FAKE[:20],
}
@pytest.mark.parametrize("name, secret", list(SHAPES.items()))
def test_every_credential_shape_disappears_from_the_middle_of_a_sentence(name: str, secret: str) -> None:
out = redact_text(f"before {secret} after")
assert "EXAMPLE" not in out, name
assert out.startswith("before [") and out.endswith("] after"), out
def test_name_value_pairs_keep_the_name_and_hide_the_value() -> None:
out = redact_secrets('password: hunter2xyz and "api_key": "abc12345"')
assert "hunter2xyz" not in out and "abc12345" not in out
assert "password: [SECRET]" in out
def test_find_secrets_names_the_shapes_it_found() -> None:
assert find_secrets("nothing to see here") == []
assert find_secrets("key " + SHAPES["openai"]) == ["API_KEY"]
def test_identifiers_and_dates_are_left_alone() -> None:
text = "model gpt-6-luna-2026-10-01 request_id req_8f2c51d0a7 on 2026-10-01, order 12345678901"
assert redact_text(text) == textRun it with uv run pytest tests/test_redact.py -v; with the thirteen shapes above, the file collects 16 tests (not run under this lesson's no-key rules, so there is no pasted output). When a vendor introduces a new prefix, the order is: add a line to SHAPES, watch the test fail, then add the pattern to redact.py.
It's a safety net. Run it against some samples before you trust it, and look at what it gets wrong (the credentials in this file are fakes assembled in code):
# s4_6_redact_limits.py
"""What regex redaction catches, and what it gets wrong. Run it before you trust a redactor with real traffic.
Every credential below is a FAKE assembled here from a vendor prefix and an obviously fake body: no real secret is stored."""
from redact import redact_text
FAKE = "EXAMPLE" * 8
SAMPLES = [
"Contact jane.doe@example.com or +1 (415) 555-0100", # caught
"my key is sk-ant-api03-abcdefghijklmnop", # caught (a fake: too short to be a real key)
"card 4242 4242 4242 4242", # caught
"pushed with " + "gh" + "p_" + FAKE[:36], # caught: a GitHub token shape, built in code
"Authorization: Bearer " + FAKE[:20], # caught: whatever follows the word Bearer
"model gpt-6-luna-2026-10-01 returned request_id req_8f2c51d0a7", # structured data: must NOT be touched
"born 1990-04-12, order 12345678901", # a date and an 11-digit number: left alone
"tracking number 1234567890123", # over-redacted: 13 digits look like a card
"Sk-test-123456789", # a partly echoed key: missed
"reach me at jane dot doe at example dot com", # obfuscated email: missed
"my name is Jane Doe and I live at 12 Baker Street", # names and addresses: no regex can find these
]
for text in SAMPLES:
print(f"{text!r}\n -> {redact_text(text)!r}")'Contact jane.doe@example.com or +1 (415) 555-0100'
-> 'Contact [EMAIL] or [PHONE]'
'my key is sk-ant-api03-abcdefghijklmnop'
-> 'my key is [API_KEY]'
'card 4242 4242 4242 4242'
-> 'card [CARD]'
'pushed with ghp_EXAMPLEEXAMPLEEXAMPLEEXAMPLEEXAMPLEE'
-> 'pushed with [API_KEY]'
'Authorization: Bearer EXAMPLEEXAMPLEEXAMPL'
-> 'Authorization: [BEARER]'
'model gpt-6-luna-2026-10-01 returned request_id req_8f2c51d0a7'
-> 'model gpt-6-luna-2026-10-01 returned request_id req_8f2c51d0a7'
'born 1990-04-12, order 12345678901'
-> 'born 1990-04-12, order 12345678901'
'tracking number 1234567890123'
-> 'tracking number [CARD]'
'Sk-test-123456789'
-> 'Sk-test-123456789'
'reach me at jane dot doe at example dot com'
-> 'reach me at jane dot doe at example dot com'
'my name is Jane Doe and I live at 12 Baker Street'
-> 'my name is Jane Doe and I live at 12 Baker Street'The first five samples are caught, including a GitHub token built in code and anything after Bearer. The next two are false positives that a naive phone-number pattern gets wrong and this one avoids: a loose pattern rewrites the date inside a model name (gpt-6-luna-2026-10-01 becomes gpt-6-luna-[PHONE]) and every date and long number in free text (1990-04-12, an order number, an SSN). Here a phone number must start with + and a country code, or be digit groups separated by spaces or dashes; an ISO date has groups too short to match, an order number has no separators, and a US social security number has its own [SSN] marker. A redactor applied to every field would still be a risk to the identifiers you log for debugging, which is why LoggedChat applies it only to the content excerpt, and the structlog sample below applies it only to named free-text fields. The remaining samples show what is still wrong: a 13-digit tracking number looks like a card (over-redaction, harmless but surprising); a partly echoed, case-changed key (Sk-test-...) is missed, and although re.IGNORECASE would fix the casing (one flag), a key cut short in the middle of an echo has no shape left to match; an obfuscated email is missed; and so is a name and street address, which no regular expression can find.
So the honest summary is: regex redaction reduces risk; it doesn't remove it. Real PII detection (named-entity recognition, allow-lists of known-safe fields, tokenization, human review of samples) is Module 12's subject. In the meantime, treat any log with content as sensitive data, whether or not it was "redacted".
4.6 The same thing with structlog#
structlog is a popular alternative that makes structured logging the default style (log.info("llm_call", model=..., tokens=...)), with processors that run on every event and bound context that follows the request. Use it if your team already does; otherwise the standard library above is enough. The mapping is direct: ContextVar binding becomes bind_contextvars, the formatter becomes the JSONRenderer, and redaction becomes a processor that guarantees no call site can forget it:
# s4_5_structlog.py
"""The same call log with structlog (optional): context binding and a redaction processor in the pipeline.
A fake price and a MOCK model: this sample only shows the logging mechanics."""
import re
import structlog
from structlog.contextvars import bind_contextvars, clear_contextvars, merge_contextvars
from fixtures_inline import FAKE_COMPLETION
from redact import redact_text
WORDS = {"key", "apikey", "token", "secret", "cookie", "password", "passwd", "credential", "credentials"} # whole words of a key name
FREE_TEXT = {"note", "prompt", "reply", "error_message"} # only these get regex redaction: it would mangle ids and dates
def scrub(logger, method_name, event_dict): # type: ignore[no-untyped-def]
"""A processor runs on every event, so one place guarantees that no call site can log a credential."""
for key in list(event_dict):
if any(w in WORDS or w.startswith("auth") for w in re.split(r"[_\-\s.]+", key.lower())):
event_dict[key] = "<redacted>"
elif key in FREE_TEXT and isinstance(event_dict[key], str):
event_dict[key] = redact_text(event_dict[key])
return event_dict
structlog.configure(processors=[merge_contextvars, structlog.processors.add_log_level, scrub,
structlog.processors.TimeStamper(fmt="iso", utc=True), structlog.processors.JSONRenderer()])
log = structlog.get_logger("llm.calls")
bind_contextvars(trace_id="9f2c1ab04d", feature="triage", env="dev") # every later line carries these
c = FAKE_COMPLETION
log.info("llm_call", provider="openai", model_requested="gpt-6-luna", model_resolved=c.model, request_id=c.request_id,
uncached_input_tokens=c.uncached_input_tokens, output_tokens=c.output_tokens, outcome=c.outcome,
note="user wrote to jane@example.com", authorization="Bearer sk-live-do-not-log") # both get scrubbed
clear_contextvars()# fixtures_inline.py
from chat_types import Completion
from cost_calc import Usage
FAKE_COMPLETION = Completion(text="ok", outcome="ok", finish_reason="completed", model="gpt-6-luna-2026-10-01",
request_id="req_8f2c51d0a7",
usage=Usage(provider="openai", model="gpt-6-luna", input=42, output=11)){"provider": "openai", "model_requested": "gpt-6-luna", "model_resolved": "gpt-6-luna-2026-10-01", "request_id": "req_8f2c51d0a7", "uncached_input_tokens": 42, "output_tokens": 11, "outcome": "ok", "note": "user wrote to [EMAIL]", "authorization": "<redacted>", "event": "llm_call", "env": "dev", "feature": "triage", "trace_id": "9f2c1ab04d", "level": "info", "timestamp": "2026-11-04T15:26:32.711500Z"}The authorization value became <redacted> and the email in the free-text note field became [EMAIL]. The processor matches the words of a key name (split on _, - and .) against a list (key, token, secret, cookie, password, credential, and anything starting with auth), so x-portkey-api-key or refresh_token is hidden without being listed. Matching whole words matters: a plain substring test for token would also hide output_tokens, the count you log to watch cost (an easy mistake to make). It is still a block-list on field names, so keep call sites to the fixed fields of 4.1. The context bound at the top (trace_id, feature, env) appears on the line though the log.info call didn't pass it. model_resolved is untouched, because FREE_TEXT limits regex redaction to named fields (the lesson of the previous section).
4.7 The SDKs' built-in OpenTelemetry spans#
OpenTelemetry (OTel) is the vendor-neutral standard for traces, metrics and logs, and the telemetry that Module 11A builds production observability on. A span records one operation (here, one API call) with a start, an end and attributes. Its GenAI semantic conventions define standard attribute names for LLM calls: gen_ai.provider.name, gen_ai.operation.name, gen_ai.request.model, gen_ai.response.model, gen_ai.response.id, gen_ai.response.finish_reasons, token usage under gen_ai.usage.* (input_tokens, output_tokens, and the newer cache_read.input_tokens, cache_write.input_tokens and reasoning.output_tokens; the cache-write attribute was spelled cache_creation.input_tokens in the older, now deprecated definition in the core semantic-conventions repository, and some instrumentation packages still emit that spelling, so check which one yours writes; Module 11A.1, section 3.2 has the details), and, as opt-in attributes because they hold content, gen_ai.input.messages, gen_ai.output.messages and gen_ai.system_instructions. As of November 2026 the conventions are marked Development (not yet stable), so names can still change, and they now live in their own repository, semantic-conventions-genai, which the old pages on opentelemetry.io point to. Check the exact attribute names there before you build dashboards on them.
What the three SDKs do on their own:
| SDK | Built-in OpenTelemetry? |
|---|---|
anthropic 2.4.0 |
Yes. It depends on opentelemetry-api and emits one span per API call whenever your application has registered a tracer provider. The open_telemetry= constructor option controls it. Anthropic's docs list the feature as beta |
openai 3.42.1 |
No. Nothing in the package imports OpenTelemetry |
google-genai 2.34.0 |
No. Nothing in the package imports OpenTelemetry |
For openai and google-genai, tracing comes from instrumentation you add yourself (HTTP-client instrumentation, or a third-party package; check that whatever you pick supports httpx2 for openai, since much instrumentation patches httpx). For all three, the structured log of 4.2 already gives you most of what a trace would, and Module 11A shows how to send both to a platform.
The anthropic option, verified in the installed SDK: open_telemetry takes False (no spans), or a dictionary with tracer_provider, propagation (whether to send the trace context in request headers; default True), conversation_id and traces (enabled, content_mode of "metadata_only" (the default) or "content", and max_content_bytes, default 750,000). Environment variables set the same things for a client whose option is unset: ANTHROPIC_OPEN_TELEMETRY=false to disable, ANTHROPIC_OPEN_TELEMETRY_TRACES_CONTENT_MODE=content, ANTHROPIC_OPEN_TELEMETRY_TRACES_MAX_CONTENT_BYTES and ANTHROPIC_OPEN_TELEMETRY_PROPAGATION=false. A client given the option, even {}, ignores those variables. This script collects the spans in memory (a mock server answers) in both content modes:
# s4_7_otel.py
"""anthropic 2.x emits OpenTelemetry spans by itself. This script collects them in memory (a MOCK server answers),
once with the default metadata_only mode and once with content_mode="content"."""
import anthropic
import httpx2
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
MESSAGE = {"id": "msg_1", "type": "message", "role": "assistant", "model": "claude-haiku-5-5-20261015",
"content": [{"type": "text", "text": "Hello!"}], "stop_reason": "end_turn", "stop_sequence": None,
"usage": {"input_tokens": 12, "output_tokens": 3, "cache_read_input_tokens": 0}}
mock = lambda: httpx2.Client(transport=httpx2.MockTransport(
lambda request: httpx2.Response(200, json=MESSAGE, headers={"request-id": "req_011Cotel"})))
for mode in ("metadata_only", "content"):
exporter = InMemorySpanExporter()
provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(exporter)) # a real app would add an OTLP exporter here
client = anthropic.Anthropic(api_key="sk-ant-test", http_client=mock(),
open_telemetry={"tracer_provider": provider, "traces": {"content_mode": mode}})
client.messages.create(model="claude-haiku-5-5", max_tokens=50,
messages=[{"role": "user", "content": "Say hello"}])
(span,) = exporter.get_finished_spans()
print(f"--- content_mode={mode!r}: span {span.name!r} ---")
for key, value in sorted((span.attributes or {}).items()):
print(f" {key} = {str(value)[:70]}")
print("--- resolved option ---")
print(client.open_telemetry["traces"])--- content_mode='metadata_only': span 'anthropic.messages.create' ---
anthropic.message.stop_reason = end_turn
anthropic.request.id = req_011Cotel
gen_ai.operation.name = chat
gen_ai.provider.name = anthropic
gen_ai.request.max_tokens = 50
gen_ai.request.model = claude-haiku-5-5
gen_ai.response.id = msg_1
gen_ai.response.model = claude-haiku-5-5-20261015
gen_ai.usage.cache_read.input_tokens = 0
gen_ai.usage.input_tokens = 12
gen_ai.usage.output_tokens = 3
http.request.method = POST
http.response.status_code = 200
http.route = /v1/messages
server.address = api.anthropic.com
server.port = 443
url.full = https://api.anthropic.com/v1/messages
url.path = /v1/messages
url.scheme = https
--- content_mode='content': span 'anthropic.messages.create' ---
anthropic.message.stop_reason = end_turn
anthropic.request.id = req_011Cotel
gen_ai.input.messages = [{"role":"user","parts":[{"type":"text","content":"Say hello"}]}]
gen_ai.operation.name = chat
gen_ai.output.messages = [{"role":"assistant","parts":[{"type":"text","content":"Hello!"}]}]
gen_ai.provider.name = anthropic
gen_ai.request.max_tokens = 50
gen_ai.request.model = claude-haiku-5-5
gen_ai.response.id = msg_1
gen_ai.response.model = claude-haiku-5-5-20261015
gen_ai.usage.cache_read.input_tokens = 0
gen_ai.usage.input_tokens = 12
gen_ai.usage.output_tokens = 3
http.request.method = POST
http.response.status_code = 200
http.route = /v1/messages
server.address = api.anthropic.com
server.port = 443
url.full = https://api.anthropic.com/v1/messages
url.path = /v1/messages
url.scheme = https
--- resolved option ---
{'enabled': True, 'content_mode': 'content', 'max_content_bytes': 750000}In metadata_only mode the span has the model asked and served, token usage including cache reads, the stop reason, the HTTP status and URL, and Anthropic's request ID (anthropic.request.id): everything in your JSON log, as standard attributes, with no prompt. Switch to content and two more attributes appear, gen_ai.input.messages and gen_ai.output.messages, holding the prompt and the reply. Everything said in 4.1 and 4.5 applies to them: content mode puts prompts into your tracing backend. Leave it at metadata_only unless you've decided otherwise on purpose. (The span is named anthropic.messages.create by this SDK; the OTel conventions suggest names built from the operation, so expect backends to key on the gen_ai.* attributes instead.)
4.8 Putting the logger in front of a real client#
The wrapper composes with everything else in this module. In production code the wiring looks like this (a sketch of the shape; the same objects run in the samples above):
# app wiring (sketch). Build clients ONCE at start-up, not at import time and not per request (see 6.3 and lesson 03.1, 7.5).
import logging, os
import openai
from adapters import OpenAIResponsesChat
from llm_log import JsonFormatter, LoggedChat, LogConfig, count_attempts
handler = logging.StreamHandler() # stdout/stderr: let the platform ship it
handler.setFormatter(JsonFormatter())
logging.getLogger("llm.calls").addHandler(handler)
logging.getLogger("llm.calls").setLevel(logging.INFO)
client = openai.OpenAI(max_retries=2, timeout=30, # key comes from OPENAI_API_KEY
http_client=openai.DefaultHttpx2Client(event_hooks=count_attempts()))
chat = LoggedChat(OpenAIResponsesChat(client, os.environ.get("TRIAGE_MODEL", "gpt-6-luna")),
provider="openai", api="responses", model="gpt-6-luna", feature="triage",
sdk_package="openai", cfg=LogConfig(env=os.environ.get("APP_ENV", "dev"))) # outside dev, USER_ID_PEPPER must be set or this raisesThis block is a sketch, not a run sample: it needs a key and builds a real client. Its parts are each run for real elsewhere in this lesson, and the LoggedChat over a mock-backed client is what Parts 7 and 9 test.
4.9 Streams and the ttft_ms field#
Most production code is async, and much of it streams. Two things from the sections above don't carry over by themselves: the attempt-counting hook (a sync function fails on an async client, 2.3) and ttft_ms (always null in LoggedChat, because it wraps a non-streaming call). A streamed call also has two extra numbers: time to first token (TTFT, how long the user stares at nothing; 02.5, 1.5) and the total duration. Lesson 03.3, Part 12 owns what to measure about streams, including the gaps between chunks that make "slow" feel slow; here is how to get the numbers into the same log line as every other call.
llm_log_async.py builds on the CallLogger of 4.2, so the line is identical and the schema test passes for all three kinds of call. It also uses StreamTimer from Part 8 (copy streamer.py from 8.1 first), which takes the clock as a parameter so a test can assert exact values:
# llm_log_async.py
"""llm_log_async.py: the same call log for async code and for streams (lesson 03.10, 4.9).
Both build on CallLogger from llm_log.py, so a streamed call writes the SAME line as a plain one, with a real ttft_ms."""
from __future__ import annotations
import time
from collections.abc import AsyncIterator, Callable
from contextlib import asynccontextmanager
from chat_types import AsyncChatModel, Completion, Message, trace_id_var
from llm_log import CallLogger, LogConfig
from streamer import StreamTimer
class ALoggedChat:
"""Wraps any AsyncChatModel. Same fields, same rules as LoggedChat; `await chat.complete(...)`."""
def __init__(self, inner: AsyncChatModel, *, provider: str, api: str, model: str, feature: str,
sdk_package: str, cfg: LogConfig | None = None,
price: Callable[[Completion], float | None] | None = None,
clock: Callable[[], float] = time.perf_counter) -> None:
self.inner = inner
self.logger = CallLogger(provider=provider, api=api, model=model, feature=feature,
sdk_package=sdk_package, cfg=cfg, price=price, clock=clock)
async def complete(self, system: str, messages: list[Message], *, max_tokens: int, user: str | None = None,
prompt_version: str | None = None) -> Completion:
call = self.logger.start(system, messages, max_tokens=max_tokens, user=user, prompt_version=prompt_version)
token = trace_id_var.set(call.trace) # a ContextVar set here follows this task, and only this task
try:
c = await self.inner.complete(system, messages, max_tokens=max_tokens, user=call.provider_user)
except Exception as exc:
call.finish(exc=exc)
raise
finally:
trace_id_var.reset(token)
call.finish(c)
return c
class StreamLog:
"""What the caller touches inside `async with logged_stream(...)`: feed it every text delta, and hand it the
SDK's final message (as a Completion) when the stream is done, so the record carries real usage."""
def __init__(self, timer: StreamTimer) -> None:
self.timer = timer
self.completion: Completion | None = None
def on_delta(self, text: str) -> None:
self.timer.on_delta(text)
def done(self, completion: Completion) -> None:
self.completion = completion
@asynccontextmanager
async def logged_stream(logger: CallLogger, system: str, messages: list[Message], *, max_tokens: int,
user: str | None = None, prompt_version: str | None = None) -> AsyncIterator[StreamLog]:
"""Writes ONE record when the stream ends, whichever way it ends: finished, broken part-way, or cancelled
(a disconnected client). A broken stream logs ttft_ms and chunks (how far it got) with usage unknown, never 0."""
call = logger.start(system, messages, max_tokens=max_tokens, user=user, prompt_version=prompt_version)
token = trace_id_var.set(call.trace)
handle = StreamLog(StreamTimer(logger.clock)) # the timer starts now: ttft_ms counts from the request
try:
yield handle
except BaseException as exc: # BaseException on purpose: CancelledError must be logged too
call.finish(exc=exc, ttft_ms=handle.timer.stats.ttft_ms, chunks=handle.timer.stats.chunks)
raise
else:
call.finish(handle.completion, ttft_ms=handle.timer.stats.ttft_ms, chunks=handle.timer.stats.chunks)
finally:
trace_id_var.reset(token)count_attempts_async()(inllm_log.py) is the same counter with anasync defhook. The counter lives in aContextVar, which follows anasynciotask, so two calls running at once withasyncio.gathercount their own attempts and keep their own trace IDs.ALoggedChatwraps anyAsyncChatModel(the async twin of theProtocolinchat_types.py;AsyncOpenAIResponsesChatinadapters.pyis the async adapter). Same fields, same rules,await chat.complete(...).logged_streamis an async context manager that writes one record when the stream ends, whichever way it ends: finished (with the usage from the SDK's final message), broken part-way (anERRORline withttft_msandchunks, so you can see how far it got, and the usage stays unknown, never0, as 03.3, 7.6 explains), or cancelled because the client disconnected. It catchesBaseExceptionon purpose, becauseasyncio.CancelledErroris not anException, and it re-raises after logging. Swallowing it would leave your task running and your tokens billing (8.2).- TTFT is measured from the request. The timer starts when
logged_streamis entered andttft_msis set by the first text delta you pass toon_delta.
Here it is against the free local model, one plain async call and one streamed call. The ttft_ms in the second line is a real measurement against the stand-in; a hosted model will show its own number:
# s4_9_async_stream_log.py
"""The call log for async code and for streams, against the free local model: one plain async call, then a streamed one.
Both write the SAME JSON line as LoggedChat; the streamed line has a real ttft_ms and chunks."""
import asyncio
import logging
import os
import secrets
import sys
import anthropic
import openai
from adapters import AsyncOpenAIResponsesChat, completion_from_claude
from llm_log import CallLogger, JsonFormatter, count_attempts_async, price_with
from llm_log_async import ALoggedChat, logged_stream
from prices import PriceTable
os.environ.setdefault("USER_ID_PEPPER", secrets.token_hex(16)) # the keyed-hash secret (your secret store, in production)
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(JsonFormatter(indent=2))
logging.getLogger("llm.calls").addHandler(handler)
logging.getLogger("llm.calls").setLevel(logging.INFO)
PRICE = price_with(PriceTable.load("prices_fake_local.yaml")) # FAKE rates (03.7)
MESSAGES = [{"role": "user", "content": "Why is the sky blue?"}]
async def main() -> None:
# 1) async, not streamed: async hooks count the attempts, ALoggedChat writes the line
oai = openai.AsyncOpenAI(base_url="http://localhost:11434/v1", api_key="ollama", max_retries=0,
http_client=openai.DefaultAsyncHttpx2Client(event_hooks=count_attempts_async()))
chat = ALoggedChat(AsyncOpenAIResponsesChat(oai, "gpt-6-luna"), provider="openai", api="responses",
model="gpt-6-luna", feature="demo", sdk_package="openai", price=PRICE)
await chat.complete("Answer in one sentence.", MESSAGES, max_tokens=20) # type: ignore[arg-type]
# 2) streamed: feed every delta to the log, hand it the SDK's final message at the end
claude = anthropic.AsyncAnthropic(base_url="http://localhost:11434", api_key="ollama", max_retries=0)
logger = CallLogger(provider="anthropic", api="messages", model="claude-haiku-5-5", feature="demo",
sdk_package="anthropic", price=PRICE)
async with logged_stream(logger, "Answer in one sentence.", MESSAGES, max_tokens=200) as log: # type: ignore[arg-type]
async with claude.messages.stream(model="claude-haiku-5-5", max_tokens=200, system="Answer in one sentence.",
messages=[{"role": "user", "content": "Why is the sky blue?"}]) as stream:
async for text in stream.text_stream:
log.on_delta(text) # the first call starts the TTFT clock reading
final = await stream.get_final_message()
log.done(completion_from_claude(final, request_id=stream.response.headers.get("request-id")))
asyncio.run(main()){
"ts": "2026-11-04T15:20:06.708+00:00",
"level": "INFO",
"event": "llm_call",
"trace_id": "91e674261d9d4a8bbbc64566d9f17e54",
"env": "dev",
"feature": "demo",
"provider": "openai",
"api": "responses",
"model_requested": "gpt-6-luna",
"sdk": "openai==3.42.1",
"prompt_version": null,
"user": null,
"max_tokens": 20,
"input_chars": 43,
"prompt_sha256": "ff6db064bf3d",
"latency_ms": 264,
"ttft_ms": null,
"attempts": 1,
"outcome": "ok",
"finish_reason": "completed",
"request_id": null,
"model_resolved": "gpt-6-luna",
"uncached_input_tokens": 24,
"cached_input_tokens": 0,
"cache_write_tokens": 0,
"total_input_tokens": 24,
"output_tokens": 20,
"reasoning_tokens": 0,
"cost_usd": 0.000124
}
{
"ts": "2026-11-04T15:20:06.940+00:00",
"level": "INFO",
"event": "llm_call",
"trace_id": "f6f80a9e133047a6a665cf11579851b1",
"env": "dev",
"feature": "demo",
"provider": "anthropic",
"api": "messages",
"model_requested": "claude-haiku-5-5",
"sdk": "anthropic==2.4.0",
"prompt_version": null,
"user": null,
"max_tokens": 200,
"input_chars": 43,
"prompt_sha256": "ff6db064bf3d",
"latency_ms": 231,
"ttft_ms": 95,
"attempts": 1,
"outcome": "ok",
"finish_reason": "end_turn",
"request_id": null,
"model_resolved": "claude-haiku-5-5",
"uncached_input_tokens": 24,
"cached_input_tokens": 0,
"cache_write_tokens": 0,
"total_input_tokens": 24,
"output_tokens": 31,
"reasoning_tokens": 0,
"chunks": 30,
"cost_usd": 0.000179
}The two lines have the same fields. The streamed one has ttft_ms and chunks filled in, and its usage and cost come from completion_from_claude(final), the same function the sync adapter uses. Its tests run with the fake clock and the SSE fixtures of Part 8, with no network and no sleeping:
| Test | What it pins down |
|---|---|
test_async_wrapper_counts_attempts_with_async_hooks |
A 429 then a 200 on an AsyncOpenAI client logs attempts: 2 and a WARNING |
test_concurrent_calls_keep_their_own_trace_ids_and_attempt_counts |
Two calls under asyncio.gather, one retried: attempts 1 and 2, different trace IDs, nothing left in the context variable |
test_a_stream_logs_one_line_with_a_real_ttft_and_real_usage |
A scripted clock gives ttft_ms == 250 and latency_ms == 900 exactly, and the usage is the SDK's final message |
test_a_stream_that_breaks_still_logs_how_far_it_got |
A mid-stream error event raises APIStatusError, and the line has ttft_ms, chunks == 2 and no usage fields |
test_a_cancelled_stream_is_logged_and_the_cancellation_is_not_swallowed |
Cancelling the task logs CancelledError and still raises it |
============================= test session starts ==============================
collected 5 items
tests/test_llm_log_async.py::test_async_wrapper_counts_attempts_with_async_hooks PASSED [ 20%]
tests/test_llm_log_async.py::test_concurrent_calls_keep_their_own_trace_ids_and_attempt_counts PASSED [ 40%]
tests/test_llm_log_async.py::test_a_stream_logs_one_line_with_a_real_ttft_and_real_usage PASSED [ 60%]
tests/test_llm_log_async.py::test_a_stream_that_breaks_still_logs_how_far_it_got PASSED [ 80%]
tests/test_llm_log_async.py::test_a_cancelled_stream_is_logged_and_the_cancellation_is_not_swallowed PASSED [100%]
============================== 5 passed in 0.66s ===============================Writing these five tests from the table is exercise 19.
4.10 Logging pitfalls#
- Logging inside the request path that can fail. A log call that raises (a non-serializable value, a full disk) mustn't take the request down with it. The formatter uses
default=str, the pricing is guarded, and any custom field should be too. - Unbounded fields. Error messages, tool results and content can be huge. Truncate at write time.
- High-cardinality labels. Fields such as
trace_idandrequest_idare for search, not for metric dimensions: don't turn them into metric labels in a metrics system. - Clock arithmetic with the wrong clock. Durations come from a monotonic clock (
time.perf_counter), never from subtracting wall-clock timestamps, which can jump. - Logging only the final answer of a retried call. Per-attempt request IDs are in hooks (2.3) or the debug log; the structured line records the attempts count and the last request ID.
- Forgetting async. A
ContextVarfollows anasynciotask, but a thread you start yourself doesn't inherit it automatically. Copy the context (contextvars.copy_context().run(...)) when you hand work to threads that you manage.
Part 5: Reproducing a problem#
Deep-dive
A user reports a bad answer on Tuesday. On Wednesday you open the code, run it with a similar question, and it works. Without the original request you can't tell whether the bug is fixed, was never there, or only shows up sometimes. Reproduction means getting back the exact input, running it again, and measuring.
5.1 Keep the exact request behind a flagged call#
You don't need to store every request (that's the content-logging problem of 4.5, at full scale). Store the exact request only when something marks the call as worth investigating:
- an exception or an
outcomeother thanok(refusal, truncation); - a validation failure in your own parser (the model's JSON didn't parse);
- a user action: a thumbs-down, a "report this answer" button, an agent's correction;
- a random sample of a small fraction of normal calls, if you need a baseline.
What goes in the file, and what must not:
| Keep | Why |
|---|---|
| The exact body the SDK serialized: method, URL (with its query values and userinfo redacted), JSON | It's the one thing that reproduces the call. Capture it at the HTTP layer (a hook), not by re-assembling it from your variables, because the SDK may add or reshape fields |
trace_id and the provider's request_id |
To connect the case to the logs and to support |
model_resolved and the SDK versions |
To know what to pin when you replay |
| The reason it was saved, and the time | Triage and retention |
| Never headers, keys or cookies, and nothing from a request that has no JSON body (a file upload) | A case file is a document people will open and share. Replay supplies a fresh key from the environment |
5.2 repro.py: save, load, replay, repeat#
# repro.py
"""repro.py: keep the request behind a bad answer, replay it later, and run it N times.
The stored body contains your users' prompts: treat the folder like the database it is (access, retention).
Nothing here stores a credential, and replay() refuses to send one to a host you did not list."""
from __future__ import annotations
import json
import os
import re
import shlex
import time
from collections import Counter
from contextvars import ContextVar
from datetime import datetime, timezone
from importlib.metadata import version
from pathlib import Path
from typing import Any
from urllib.parse import urlsplit
import httpx
import httpx2
from wire_log import redact_url
_last: ContextVar[dict[str, Any] | None] = ContextVar("last_request", default=None)
# Where a replay may send your key. Local servers and the four providers; add your gateway, nothing else.
ALLOWED_HOSTS = frozenset({"api.openai.com", "api.anthropic.com", "generativelanguage.googleapis.com",
"openrouter.ai", "localhost", "127.0.0.1"})
class ReplayRefused(Exception):
"""The case file names a host that is not on the allow-list: replaying it would send your key there."""
def capture_last_request() -> dict[str, list[Any]]:
"""event_hooks for the SDK's HTTP client: remember the method, URL and JSON body of the latest request.
A request with no JSON body (a multipart file upload, whose body is a stream) is not stored at all."""
def on_request(request: Any) -> None:
try:
text = request.content.decode("utf-8")
json.loads(text)
except (httpx.RequestNotRead, httpx2.RequestNotRead, UnicodeDecodeError, ValueError):
_last.set(None) # forget the previous request too: never save a stale one
return
_last.set({"method": request.method, "url": redact_url(request.url), "body": text})
return {"request": [on_request]}
class ReproStore:
def __init__(self, directory: str | Path, keep_days: float = 7) -> None:
self.dir, self.keep_days = Path(directory), keep_days
self.dir.mkdir(mode=0o700, parents=True, exist_ok=True) # owner only, from the first moment
def save(self, *, reason: str, trace_id: str, provider: str, **meta: Any) -> Path | None:
sent = _last.get()
if sent is None:
return None
case = {"created": datetime.now(timezone.utc).isoformat(timespec="seconds"), "reason": reason,
"trace_id": trace_id, "provider": provider, **sent, "body": json.loads(sent["body"]),
"sdk_versions": {p: version(p) for p in ("openai", "anthropic", "google-genai")}, **meta}
# No headers are stored, and the URL's query values and userinfo are redacted (wire_log.redact_url).
# Replay supplies a fresh key from the environment. trace_id comes from outside: keep only safe characters.
safe_id = re.sub(r"[^A-Za-z0-9]", "", trace_id)[:8] or "noid"
path = self.dir / f"{datetime.now(timezone.utc):%Y%m%dT%H%M%S}_{safe_id}.json"
# O_EXCL: never overwrite or follow a planted file. Mode 0o600 is set when the file is CREATED, so there is
# no moment when it is readable by others (write_text() then chmod() has that moment).
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(fd, "w", encoding="utf-8") as f:
f.write(json.dumps(case, indent=2, ensure_ascii=False))
return path
def purge(self) -> list[str]:
"""Delete cases older than keep_days. Run it from a scheduled job, not only 'when someone remembers'."""
cutoff = time.time() - self.keep_days * 86_400
gone = [p.name for p in self.dir.glob("*.json") if p.stat().st_mtime < cutoff]
for name in gone:
(self.dir / name).unlink()
return gone
def load_case(path: str | Path) -> dict[str, Any]:
return json.loads(Path(path).read_text())
def replay(case: dict[str, Any], headers: dict[str, str], *, times: int = 1, timeout: float = 60,
allowed_hosts: frozenset[str] = ALLOWED_HOSTS) -> list[dict[str, Any]]:
"""Send the stored JSON again, `times` times. The SDK is not involved: this is the raw request.
It is the same JSON value, not the same bytes (spacing and key order may differ; servers ignore both).
`headers` carries your key, so the host is checked BEFORE anything is sent: a case file is data
from disk, and an edited or foreign one must not be able to point your key at someone else's server."""
url = urlsplit(case["url"])
if url.scheme not in ("http", "https") or url.hostname not in allowed_hosts:
raise ReplayRefused(f"{url.hostname!r} is not an allowed host: refusing to send credentials there")
results = []
with httpx2.Client(timeout=timeout, follow_redirects=False) as http: # a redirect could leave the allowed host
for _ in range(times):
response = http.request(case["method"], case["url"], json=case["body"], headers=headers)
results.append({"status": response.status_code, "json": response.json()})
return results
def summarize(results: list[dict[str, Any]], pick: Any) -> Counter[str]:
"""Count how often each distinct outcome appeared. `pick` turns one response JSON into a short label."""
return Counter(pick(r["json"]) if r["status"] == 200 else f"HTTP {r['status']}" for r in results)
def local_headers() -> dict[str, str]:
"""For hosted APIs build this from os.environ at replay time; never save it next to the case."""
return {"authorization": f"Bearer {os.environ.get('OPENAI_API_KEY', 'ollama')}"}
def to_curl(case: dict[str, Any], *, auth: str = "Authorization: Bearer", key_env: str = "OPENAI_API_KEY") -> str:
"""The stored request as a curl command, to try it outside Python. The key stays in YOUR shell variable.
The header is in DOUBLE quotes so the shell expands $VAR when you run it: inside single quotes the variable
would be sent as the literal text '$OPENAI_API_KEY' and every call would be a 401."""
if not key_env.isidentifier() or not re.fullmatch(r"[A-Za-z0-9-]+:( Bearer)?", auth):
raise ValueError("key_env must be a plain variable name and auth a header name such as 'x-api-key:'")
return (f"curl -sS -X {case['method']} {shlex.quote(case['url'])} -H \"{auth} ${{{key_env}}}\" "
f"-H 'content-type: application/json' -d {shlex.quote(json.dumps(case['body']))}")The pieces:
capture_last_request()is an event hook (2.3) that remembers the latest request's method, redacted URL and body in aContextVar. It stores nothing for a request without a JSON body: a multipart upload (files.create) has a streamed body whose.contentraisesRequestNotRead, so the hook catches that, forgets the previous request too (a stale one must never be saved by mistake) and returns. Attach it to the client alongside the other hooks.ReproStore.save(...)writes one JSON file per flagged call, containing the body but no headers (so no credentials can leak into it). The permissions are right from the first byte: the file is created withos.open(..., O_EXCL, 0o600)and the folder with0o700. The obvious alternative,write_text()followed bychmod(), leaves the file readable at the process's default (usually0644) for a moment, and a file that already existed (a planted symlink) would be followed;O_EXCLrefuses both. Thetrace_idends up in the file name and comes from outside, so only its letters and digits are used.purge()deletes cases older thankeep_days; run it from a scheduled job.replay(case, headers, times=N)sends the stored JSON again without the SDK, using whatever auth headers you supply at replay time. Going around the SDK is deliberate: it separates "my SDK usage" from "the provider's behaviour". To test the SDK path, pass the stored body's fields to the SDK call instead. Two honest limits: it sends the same JSON value, not the same bytes (spacing and key order may differ, which servers ignore), and because the stored URL is redacted it can't replay a request whose key lived in the URL (old Gemini REST examples), which is intended. And it refuses to send your key to a host you haven't listed: a case file is data from disk, and an edited or foreign one would otherwise turnreplayinto a way to post yourAuthorizationheader to someone else's server.ALLOWED_HOSTSholds the four providers and localhost; the check happens before anything is sent, a look-alike such asapi.openai.com.attacker.exampledoes not pass, and redirects are not followed.to_curl(case)renders the case as acurlcommand that reads the key from${OPENAI_API_KEY}(or the variable you name withkey_env=, withauth="x-api-key:"for Anthropic), for trying the request from outside Python, or for pasting into a support ticket after you've scrubbed the content. The header is in double quotes on purpose. The easy mistake is single quotes: the shell then never expands the variable and curl sends the literal textBearer $OPENAI_API_KEY(a401on every call), and a test that only looks for the substring$OPENAI_API_KEYpasses on the broken command. The test below runs the command in a real shell against a local server and checks the header that arrives.summarize(results, pick)counts distinct outcomes, which is the next section's point.
5.3 Try it: reproduce a "bad answer" and run it many times#
The script calls the free local model once (the user_reported_bad_answer flag stands for a thumbs-down in your UI), saves the case, then replays it eight times and counts the distinct outcomes. Because the model is a tiny local one, the numbers belong to it. The technique is the same on a hosted model.
# s5_1_reproduce.py
"""Reproduce a bad answer: save the exact request when a call is flagged, replay it 8 times, compare the outcomes.
Runs against the free local model, so the distribution is the small model's, not a hosted model's."""
import tempfile
import time
import openai
from openai import OpenAI
from adapters import OpenAIResponsesChat
from chat_types import new_trace_id, trace_id_var
from repro import ReproStore, capture_last_request, load_case, local_headers, replay, summarize, to_curl
store = ReproStore(tempfile.mkdtemp(prefix="repro_"), keep_days=7)
client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama", max_retries=0,
http_client=openai.DefaultHttpx2Client(event_hooks=capture_last_request()))
chat = OpenAIResponsesChat(client, "gpt-6-luna")
trace = new_trace_id()
trace_id_var.set(trace)
c = chat.complete("Answer in one sentence.", [{"role": "user", "content": "Why is the sky blue?"}], max_tokens=12)
print("outcome:", c.outcome, "| finish_reason:", c.finish_reason, "| text:", repr(c.text))
user_reported_bad_answer = True # e.g. the user clicked "thumbs down" in your UI
if user_reported_bad_answer or c.outcome != "ok": # a flagged call: keep the evidence
path = store.save(reason="user_reported" if user_reported_bad_answer else c.outcome, trace_id=trace, provider="openai", model_resolved=c.model, request_id=c.request_id)
assert path is not None
case = load_case(path)
print("saved:", path.name, "| keys:", sorted(case))
print("stored body:", case["body"])
print("same request as curl:", to_curl(case))
started = time.perf_counter()
results = replay(case, local_headers(), times=8)
pick = lambda j: f"{j['status']}: {j['output'][0]['content'][0]['text'][:30]!r}" # label = status + start of text
for label, n in summarize(results, pick).most_common():
print(f" {n}x {label}")
print(f"8 replays took {time.perf_counter() - started:.1f}s")outcome: ok | finish_reason: completed | text: 'The sky appears blue because of the scattering and absorption of light'
saved: 20261104T151930_bfaa721a.json | keys: ['body', 'created', 'method', 'model_resolved', 'provider', 'reason', 'request_id', 'sdk_versions', 'trace_id', 'url']
stored body: {'model': 'gpt-6-luna', 'input': [{'role': 'user', 'content': 'Why is the sky blue?'}], 'instructions': 'Answer in one sentence.', 'max_output_tokens': 12}
same request as curl: curl -sS -X POST http://localhost:11434/v1/responses -H "Authorization: Bearer ${OPENAI_API_KEY}" -H 'content-type: application/json' -d '{"model": "gpt-6-luna", "input": [{"role": "user", "content": "Why is the sky blue?"}], "instructions": "Answer in one sentence.", "max_output_tokens": 12}'
3x completed: 'The sky appears blue due to sc'
1x completed: 'The sky being blue is due to t'
1x completed: 'The sky is blue because it con'
1x completed: "The Earth's atmosphere allows "
1x completed: 'The sky appears blue because o'
1x completed: 'The sky appears blue because i'
8 replays took 1.1sLook at the stored body: it is the exact JSON that went over the wire, with instructions, the user turn and the output cap, and the file has no headers. The curl line shows the same request without Python, using ${OPENAI_API_KEY} rather than a key, in double quotes so your shell fills it in when you run it. Then the point of the exercise: eight replays of one identical request gave several different answers. The model is not deterministic, so "I ran it once and it was fine" proves very little.
5.4 The model that actually answered#
When replays show a change over time (fine last month, worse this month), the first suspect is the model identity. Aliases such as gpt-6-luna or claude-haiku-5-5 can move to a newer snapshot; the response says which snapshot actually answered (response.model, message.model, model_version for Gemini), and the structured log of Part 4 records it as model_resolved, next to model_requested. In the retried-call record of 4.3, you saw an alias (gpt-6-luna) resolve to a dated snapshot (gpt-6-luna-2026-10-01). That one field answers "did the model change?" without any guesswork.
What to do with it:
- Log it on every call (done), and alert when a
model_resolvedvalue you've never seen appears. - Pin a dated snapshot where reproducibility matters more than automatic improvements, and move deliberately, with the regression suite running before you do. Lesson 02.10, 19.3 covers pinning and migrations, and 02.9, Part 8 the lifecycle of aliases, snapshots and retirements.
- Remember the three kinds of version (03.1, Part 9): the API version (Anthropic's
anthropic-version), the model version (the snapshot) and the SDK version. A regression can come from any of the three, and the log should say which were in play: that's what themodel_resolved,sdkand the request's headers in your case file are for. - On OpenRouter, "the model" is also a route. The same
vendor/modelID can be served by different upstream providers, and a fallback can switch models mid-flight. Look the call up with the generation ID (03.7, 9.3) to see which provider answered.
5.5 Why reproduction is probabilistic, and how many runs are enough#
Lesson 02.5, Part 7 explains why identical requests can give different answers, and why most current frontier models give you little or no control over it (no temperature, and seed support varies). Don't plan around forcing determinism. Plan around measuring a rate.
If a failure happens with probability p on each run, the number of runs needed to see it at least once with 95% confidence is about 3 / p:
Failure rate p |
Runs to see it at least once (95%) | Chance that 10 clean runs happen anyway |
|---|---|---|
| 50% | 5 | 0.1% |
| 20% | 14 | 11% |
| 10% | 29 | 35% |
| 5% | 59 | 60% |
| 1% | 299 | 90% |
(Computed as ceil(ln 0.05 / ln(1 - p)) and (1 - p)^10.) The consequences are practical:
- "I ran it five times and it's fine" doesn't show that a 10% problem is fixed: five clean runs happen 59% of the time even when the bug is still there.
- After a fix, re-run the same stored case enough times to have a fair chance of seeing the original rate, and compare rates before and after, not single outcomes.
- Rare failures (1% or less) can't be chased by hand. That's the point where you build a dataset and an evaluation, which is Module 10A's job. This lesson gets you the evidence to know you need one.
- Costs add up: 30 replays of a long prompt on a large model isn't free. Use the cheap-model habits of Part 13 first (reproduce on the small model if the problem also appears there), and remember output caps apply to replays too.
5.6 Testing the store itself#
A store of user prompts, and a replay that sends credentials, deserve tests of their safety properties: no credential in the file (including one in the URL), owner-only permissions that don't depend on a later chmod (the test sets the loosest possible umask and makes Path.chmod fail), a hostile trace ID that can't choose the file's location, a file upload that is neither a crash nor a stored case, a purge that removes only old cases, a replay that refuses a foreign host before sending anything, and a curl command that really sends the key. Those last two need a socket, so they carry the enable_socket marker and talk to a tiny HTTP server on 127.0.0.1, which records the headers it receives. Every key in the file is assembled at run time from an obviously fake body, so no secret is stored in it:
# tests/test_repro.py
"""The reproduction store is code that handles user content and sends credentials, so test its safety properties:
no key in the file, owner-only permissions from the first byte, hooks that survive file uploads, a replay that
refuses foreign hosts, and a curl command that REALLY sends the key (checked against a local mock server)."""
from __future__ import annotations
import io
import json
import os
import shutil
import stat
import subprocess
import threading
import time
from contextlib import contextmanager
from http.server import BaseHTTPRequestHandler, HTTPServer
from pathlib import Path
import httpx2
import openai
import pytest
from repro import ReplayRefused, ReproStore, _last, capture_last_request, load_case, replay, to_curl
FAKE_KEY = "fake-key-" + "EXAMPLE" * 3 # assembled here, obviously fake
def send_one(body: dict, url: str = "https://api.example.test/v1/responses") -> None:
"""A request through a client with the capture hook; the mock server answers {}."""
client = httpx2.Client(transport=httpx2.MockTransport(lambda r: httpx2.Response(200, json={})),
event_hooks=capture_last_request())
client.post(url, json=body, headers={"authorization": f"Bearer {FAKE_KEY}"})
def test_saved_case_has_the_body_but_never_a_credential(tmp_path: Path) -> None:
send_one({"model": "gpt-6-luna", "input": "hi"})
path = ReproStore(tmp_path).save(reason="user_reported", trace_id="abc12345xyz", provider="openai")
assert path is not None
text = path.read_text()
assert FAKE_KEY not in text and "authorization" not in text.lower()
assert load_case(path)["body"] == {"model": "gpt-6-luna", "input": "hi"}
def test_a_key_in_the_url_never_reaches_the_file(tmp_path: Path) -> None:
"""The very pattern 2.2 warns about (?key=...): the URL is redacted before it is stored."""
send_one({"input": "hi"}, url=f"https://api.example.test/v1/models/m:generateContent?key={FAKE_KEY}&alt=sse")
path = ReproStore(tmp_path).save(reason="r", trace_id="t" * 8, provider="gemini")
assert path is not None and FAKE_KEY not in path.read_text()
assert load_case(path)["url"].endswith("?key=<redacted>&alt=sse")
def test_case_files_are_owner_only_and_never_depend_on_a_later_chmod(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(Path, "chmod", lambda *a, **k: (_ for _ in ()).throw(AssertionError("save() must not need chmod")))
old_umask = os.umask(0) # the loosest umask: only the mode passed to os.open can protect us
try:
send_one({"input": "x"})
store = ReproStore(tmp_path / "cases")
path = store.save(reason="r", trace_id="t" * 8, provider="openai")
finally:
os.umask(old_umask)
assert path is not None and stat.S_IMODE(path.stat().st_mode) == 0o600
assert stat.S_IMODE(store.dir.stat().st_mode) == 0o700
def test_a_hostile_trace_id_cannot_choose_where_the_file_goes(tmp_path: Path) -> None:
send_one({"input": "x"})
path = ReproStore(tmp_path).save(reason="r", trace_id="../../etc/passwd", provider="openai")
assert path is not None and path.parent == tmp_path and ".." not in path.name
def test_a_multipart_upload_is_neither_a_crash_nor_a_stored_case(tmp_path: Path) -> None:
"""files.create() has a streamed body: reading request.content raised RequestNotRead inside the hook."""
send_one({"stale": "request"}) # something from earlier must not be saved by mistake
client = openai.OpenAI(api_key=FAKE_KEY, max_retries=0, http_client=openai.DefaultHttpx2Client(
transport=httpx2.MockTransport(lambda r: (r.read(), httpx2.Response(200, json={
"id": "file-1", "object": "file", "bytes": 3, "created_at": 1, "filename": "a.txt", "purpose": "user_data"}))[1]),
event_hooks=capture_last_request()))
assert client.files.create(file=("a.txt", io.BytesIO(b"abc")), purpose="user_data").id == "file-1"
assert ReproStore(tmp_path).save(reason="r", trace_id="t" * 8, provider="openai") is None
def test_purge_removes_only_old_cases(tmp_path: Path) -> None:
store = ReproStore(tmp_path, keep_days=7)
old, new = tmp_path / "old.json", tmp_path / "new.json"
old.write_text("{}")
new.write_text("{}")
ten_days_ago = time.time() - 10 * 86_400
os.utime(old, (ten_days_ago, ten_days_ago))
assert store.purge() == ["old.json"] and new.exists() and not old.exists()
def test_nothing_captured_means_nothing_saved(tmp_path: Path) -> None:
_last.set(None)
assert ReproStore(tmp_path).save(reason="r", trace_id="t" * 8, provider="openai") is None
# --- replay and curl, against a REAL local HTTP server (the loopback socket is allowed by the enable_socket marker) ------
@contextmanager
def local_server(): # type: ignore[no-untyped-def]
"""A tiny server on 127.0.0.1 that records the headers and body of every request and answers {"ok": true}."""
received: list[dict] = []
class Handler(BaseHTTPRequestHandler):
def do_POST(self) -> None:
body = self.rfile.read(int(self.headers.get("content-length", 0)))
received.append({"headers": {k.lower(): v for k, v in self.headers.items()}, "body": body})
payload = b'{"ok": true}'
self.send_response(200)
self.send_header("content-type", "application/json")
self.send_header("content-length", str(len(payload)))
self.end_headers()
self.wfile.write(payload)
def log_message(self, *args) -> None: # type: ignore[no-untyped-def]
pass
server = HTTPServer(("127.0.0.1", 0), Handler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
yield f"http://127.0.0.1:{server.server_port}", received
finally:
server.shutdown()
server.server_close()
@pytest.mark.enable_socket
@pytest.mark.skipif(shutil.which("curl") is None, reason="curl is not installed")
@pytest.mark.parametrize("auth, key_env, header", [
("Authorization: Bearer", "OPENAI_API_KEY", "authorization"),
("x-api-key:", "ANTHROPIC_API_KEY", "x-api-key"),
])
def test_the_curl_command_really_sends_the_key_from_your_shell_variable(auth: str, key_env: str, header: str) -> None:
"""The bug this pins: a single-quoted header sent the literal text '$OPENAI_API_KEY' and every call was a 401.
Here the command is run by a real shell and a real curl, and the server reports the header it received."""
with local_server() as (base, received):
case = {"method": "POST", "url": f"{base}/v1/responses", "body": {"input": "it's \"quoted\""}}
command = to_curl(case, auth=auth, key_env=key_env)
assert FAKE_KEY not in command # the command holds a variable NAME, never the key
done = subprocess.run(["sh", "-c", command], env={"PATH": os.environ["PATH"], key_env: FAKE_KEY},
capture_output=True, text=True, timeout=20)
assert done.returncode == 0 and json.loads(done.stdout) == {"ok": True}
sent = received[0]
assert sent["headers"][header] == (f"Bearer {FAKE_KEY}" if header == "authorization" else FAKE_KEY)
assert json.loads(sent["body"]) == case["body"] # and the body survived the shell quoting
def test_to_curl_refuses_a_header_it_cannot_quote_safely() -> None:
with pytest.raises(ValueError):
to_curl({"method": "POST", "url": "http://x", "body": {}}, key_env='KEY"; rm -rf ~; echo "')
@pytest.mark.enable_socket
def test_replay_sends_the_same_json_with_the_key_you_supply_now() -> None:
with local_server() as (base, received):
case = {"method": "POST", "url": f"{base}/v1/responses", "body": {"model": "m", "input": "hi"}}
assert replay(case, {"authorization": f"Bearer {FAKE_KEY}"}, times=2)[0]["json"] == {"ok": True}
assert len(received) == 2 and json.loads(received[0]["body"]) == case["body"]
assert received[0]["headers"]["authorization"] == f"Bearer {FAKE_KEY}"
def test_replay_refuses_a_host_that_is_not_on_the_allow_list_before_sending_anything() -> None:
"""A case file is data from disk. An edited one must not be able to point your key at somebody else's server.
No socket is opened here: the test runs under --disable-socket, so a send would fail with SocketBlockedError."""
case = {"method": "POST", "url": "https://collector.attacker.example/v1/responses", "body": {}}
with pytest.raises(ReplayRefused, match="not an allowed host"):
replay(case, {"authorization": f"Bearer {FAKE_KEY}"})
with pytest.raises(ReplayRefused):
replay({**case, "url": "file:///etc/passwd"}, {})
with pytest.raises(ReplayRefused): # a look-alike must not pass a naive "endswith" check
replay({**case, "url": "https://api.openai.com.attacker.example/v1"}, {})============================= test session starts ==============================
collected 12 items
tests/test_repro.py::test_saved_case_has_the_body_but_never_a_credential PASSED [ 8%]
tests/test_repro.py::test_a_key_in_the_url_never_reaches_the_file PASSED [ 16%]
tests/test_repro.py::test_case_files_are_owner_only_and_never_depend_on_a_later_chmod PASSED [ 25%]
tests/test_repro.py::test_a_hostile_trace_id_cannot_choose_where_the_file_goes PASSED [ 33%]
tests/test_repro.py::test_a_multipart_upload_is_neither_a_crash_nor_a_stored_case PASSED [ 41%]
tests/test_repro.py::test_purge_removes_only_old_cases PASSED [ 50%]
tests/test_repro.py::test_nothing_captured_means_nothing_saved PASSED [ 58%]
tests/test_repro.py::test_the_curl_command_really_sends_the_key_from_your_shell_variable[Authorization: Bearer-OPENAI_API_KEY-authorization] PASSED [ 66%]
tests/test_repro.py::test_the_curl_command_really_sends_the_key_from_your_shell_variable[x-api-key:-ANTHROPIC_API_KEY-x-api-key] PASSED [ 75%]
tests/test_repro.py::test_to_curl_refuses_a_header_it_cannot_quote_safely PASSED [ 83%]
tests/test_repro.py::test_replay_sends_the_same_json_with_the_key_you_supply_now PASSED [ 91%]
tests/test_repro.py::test_replay_refuses_a_host_that_is_not_on_the_allow_list_before_sending_anything PASSED [100%]
============================== 12 passed in 1.32s ==============================Part 6: Designing code for testability#
You can bolt logging onto any code, but you can only test code that was built to be tested. Most quickstarts aren't:
# The shape of most tutorials (don't copy this)
from openai import OpenAI
client = OpenAI() # built when the module is imported
def triage(ticket: str) -> str:
r = client.responses.create(model="gpt-6-luna", input=f"Triage this ticket as JSON: {ticket}")
return r.output_text.split("\x60\x60\x60")[1] # fragile fence-stripping, plus prompt and call in one functionThree things make that hard to test. The client is a hidden global, so a test can't swap it. The prompt, the network call and the parsing are one block, so you can't test the parsing without a model. And importing the module already needs a key. Each has a cheap fix.
6.1 Three rules#
Rule 1: inject the client (or a thin interface). Business code receives the thing that talks to the model as a parameter. It never constructs it. In this lesson that thing is a ChatModel: anything with a complete(system, messages, *, max_tokens, user) method that returns a Completion (1.5). A real adapter, a logging wrapper around it, a scripted fake and a mock-backed adapter all satisfy it.
Rule 2: keep prompt building, response parsing and business rules as pure functions. A pure function gives the same output for the same input and touches nothing outside itself: no network, no clock, no global state. Pure functions are the cheapest tests there are (microseconds, no setup), and they're where most logic bugs live.
Rule 3: use a Protocol for the seam. A typing.Protocol describes a shape ("has a complete method like this") without requiring inheritance. Your fakes and test doubles don't need to import or subclass anything, and a type checker verifies that they fit.
All three are visible in triage.py, the business code under test in this lesson, which you saved in 3.4 (the listing is there, because the first sample that needs it comes first). Re-read it now with the three rules in mind.
Read it as three layers:
| Layer | Functions | Touches the network? | How it's tested |
|---|---|---|---|
| Pure core | build_messages, parse_triage, apply_rules |
No | Unit tests with plain inputs (7.1), including property-based tests (Part 10) |
| Thin shell | triage_ticket(chat, ...) |
Only through the injected chat |
A fake ChatModel that returns scripted Completions (7.2) |
| Adapters | OpenAIResponsesChat and friends (1.5) |
Yes, through the injected SDK client | The real SDK over a mock transport (7.3) |
Two design choices deserve a comment. First, triage_ticket turns a refusal or a truncated answer into a result the caller can act on (needs_human=True, with a reason) instead of parsing half an answer or raising; deciding that is business logic, so it's tested at the fake-client level without any HTTP. Second, parse_triage accepts a JSON object inside a Markdown code fence (three backticks, optionally followed by json), because models add one even when told not to, and it raises one specific exception (TriageParseError) for everything else. The one-exception rule is what lets Part 10 check, by property-based testing, that no input can crash it in an unexpected way. ("Check", not "prove": a property test searches, it doesn't exhaust. A naive version of this parser has a hole, {"category": []} (a list is valid JSON, but [] in CATEGORIES raises TypeError), that a generator of arbitrary JSON finds in a fraction of a second, which is why the validation here tests isinstance(category, str) before the membership test, and why 10.2 shows the failure.)
6.2 Don't build clients at import time#
The tutorial shape above constructs a client when the module loads. That breaks tests, CI and teammates' first checkouts, because the SDKs don't agree on what happens when the key is missing. This script removes the keys from the environment, then tries to construct each client:
# s6_2_import_time_clients.py
"""Why clients must not be built at import time: with no key in the environment, what does each SDK do?"""
import os
for name in ("OPENAI_API_KEY", "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "GEMINI_API_KEY", "GOOGLE_API_KEY"):
os.environ.pop(name, None) # simulate a CI runner or a teammate's fresh checkout
import anthropic
from google import genai
from openai import OpenAI
for label, make in [("OpenAI()", OpenAI), ("anthropic.Anthropic()", anthropic.Anthropic), ("genai.Client()", genai.Client)]:
try:
make()
print(f"{label:<24} constructed without a key (it fails later, at the first request)")
except Exception as e: # noqa: BLE001
print(f"{label:<24} raises at construction: {type(e).__name__}: {str(e)[:70]}")
# The fix: build the client on first use, once. Importing this file needs no key; only the first call does.
import functools
@functools.cache
def get_openai() -> OpenAI:
return OpenAI()
print("\nlazy factory defined: importing it needed no key")
try:
get_openai()
except Exception as e: # noqa: BLE001
print("first use fails clearly, at the call site:", type(e).__name__)
os.environ["OPENAI_API_KEY"] = "sk-test"
print("after the key exists:", type(get_openai()).__name__, "| same object next time:", get_openai() is get_openai())OpenAI() raises at construction: OpenAIError: Missing credentials. Please pass an `api_key`, `workload_identity`, `a
anthropic.Anthropic() constructed without a key (it fails later, at the first request)
genai.Client() raises at construction: ValueError: No API key was provided. Please pass a valid API key. Learn how to cre
lazy factory defined: importing it needed no key
first use fails clearly, at the call site: OpenAIError
after the key exists: OpenAI | same object next time: TrueOpenAI() and genai.Client() raise at construction when no key is found; anthropic.Anthropic() doesn't (it fails at the first request instead). So a module-level client = OpenAI() makes import yourmodule crash on any machine without OPENAI_API_KEY: including the CI runner that is supposed to run your key-free tests. The bottom half of the script shows the fix: a small factory, built on first use and then cached. The failure now happens at the call site with a clear message, importing needs nothing, and tests never call the factory because they inject their own client.
Related pitfalls:
- Don't construct a client per request either. Clients own a connection pool; creating one per call throws that away (03.1, 7.5). Build one at start-up (in a FastAPI lifespan handler, a
get_chat()factory, or your application object) and pass it down. load_dotenv()belongs in the application entry point, not in library modules. A module that loads.envas a side effect of being imported can make a test pick up your real keys.- Tests must not depend on the developer's shell. Use
monkeypatch.delenv("OPENAI_API_KEY", raising=False)where a test relies on the key being absent, and pass keys explicitly (api_key="sk-test") where it only needs a client.
6.3 Time, randomness and IDs are dependencies too#
Anything that makes a function return something different on each run is a dependency, and the same technique applies: pass it in. This lesson's code already does it:
| Dependency | How it's injected | What it lets a test do |
|---|---|---|
| The clock | LoggedChat(clock=...), StreamTimer(clock=...) |
Assert latency_ms == 250 exactly (7.1, Part 8) |
| Randomness | LogConfig(rng=...) |
Make content sampling deterministic |
| Sleeping | tenacity's sleep= argument; 03.8's reliable_call(sleep=...) |
Run a 30-second backoff in zero seconds (Part 9) |
| The client | Constructor argument | Everything in Part 7 |
| IDs | The trace_id_var context variable |
Set a known trace ID before the call |
The default values (time.perf_counter, random.random) mean production code never mentions them.
6.4 What this seam is not#
The ChatModel here has one method, because that's all the examples need. It deliberately leaves out streaming, tools, structured output, multimodal parts, reasoning controls and the Interactions API. Real provider-agnostic clients grow those carefully, and they're the subject of 03.11: "when to abstract and when not to" is a real design question, and an abstraction that tries to cover everything tends to leak. The advice for now is narrower: put a seam where your tests need one, keep it as small as the code that crosses it, and keep provider-specific features (a cache breakpoint, a grounding tool) on the provider-specific side.
Part 7: The testing toolbox, from fastest to most realistic#
There are seven ways to test code that calls an LLM. They differ in how much of the real world is in the loop, and so in speed, cost and what they can catch. Use many of the fast ones and few of the slow ones.
| # | Technique | What is real | What is fake | Runs | Catches | Misses |
|---|---|---|---|---|---|---|
| 1 | Unit tests (7.1) | Your pure functions | Everything else is absent | Every save | Logic bugs in prompts, parsers, rules, converters, cost maths | Anything about SDKs or providers |
| 2 | Fake clients (7.2) | Your business code | The model (a scripted ChatModel) |
Every save | Wrong handling of refusals, truncation, errors; wrong request-building inputs | Bugs in adapters and SDK usage |
| 3 | Mock transports (7.3, 7.4) | The real SDK: request building, retries, parsing, exceptions | The network and the server | Every push | Wrong parameters, retry behaviour, response parsing, exception types | Whether the provider accepts the request; fixtures that drifted from reality |
| 4 | Record/replay (7.5) | Recorded real responses | Replayed, no network | Every push | The same as 3, with more realistic bodies | Anything that changed since the recording |
| 5 | Request snapshots (7.6) | The exact request the SDK builds | The reply | Every push | Accidental prompt or parameter changes, visible in review | Whether the request is good |
| 6 | Contract tests against a stand-in (7.7) | A real HTTP server speaking the wire format | A small local model | On demand, nightly | The code works end to end through a real socket and parser | Hosted-model behaviour and parameters the stand-in ignores |
| 7 | Live smoke tests (7.8) | Everything | Nothing | On a schedule | The provider changed, your key broke, an alias vanished | Nothing it covers is faked; it only covers a little |
7.1 Level 1: pure unit tests#
Start with the tests that need nothing. The functions from Part 6 (build_messages, parse_triage, apply_rules), the user-hash helper and the redactor are all pure, so a test is a few lines. The file below contains levels 1 and 2 together; this section covers the first half.
# tests/test_unit_and_fakes.py
"""Level 1 and 2 of the toolbox: pure unit tests, then tests that use a fake ChatModel. No HTTP anywhere."""
from typing import Any
import pytest
import redact
from chat_types import Completion
from fakes import FakeChat, ok, refused, truncated
from llm_log import hash_user
from triage import FENCE, Triage, TriageParseError, apply_rules, build_messages, parse_triage, triage_ticket
# --- Level 1: pure functions ---------------------------------------------------------------------
def test_build_messages_keeps_only_recent_history() -> None:
history: list[Any] = [{"role": "user" if i % 2 == 0 else "assistant", "content": f"turn {i}"} for i in range(10)]
messages = build_messages(" new ticket ", history)
assert len(messages) == 7 # six kept turns + the new ticket
assert messages[0]["content"] == "turn 4"
assert messages[-1] == {"role": "user", "content": "new ticket"} # whitespace trimmed
@pytest.mark.parametrize("text, expected", [
('{"category": "billing", "urgent": false}', Triage("billing", False)),
pytest.param(f'{FENCE}json\n{{"category": "bug", "urgent": true}}\n{FENCE}', Triage("bug", True), id="fenced"),
(' {"category": "how_to", "urgent": false} ', Triage("how_to", False)),
])
def test_parse_triage_accepts(text: str, expected: Triage) -> None:
assert parse_triage(text) == expected
@pytest.mark.parametrize("text", [
"Sure! Here is the JSON: {}", "", "[]", '{"category": "weather", "urgent": false}',
'{"category": "bug", "urgent": "yes"}', '{"category": "bug"}',
'{"category": [], "urgent": true}', '{"category": {}, "urgent": true}', # valid JSON, unhashable values: once a crash
])
def test_parse_triage_rejects(text: str) -> None:
with pytest.raises(TriageParseError):
parse_triage(text)
def test_outage_is_always_urgent() -> None:
assert apply_rules(Triage("bug", False), "Total OUTAGE in eu-west").urgent is True
assert apply_rules(Triage("bug", False), "button is blue").urgent is False
def test_user_hash_is_stable_keyed_and_not_the_raw_id() -> None:
a = hash_user("jane@example.com", b"key-1")
assert a == hash_user("jane@example.com", b"key-1")
assert a != hash_user("jane@example.com", b"key-2")
assert "jane" not in a and len(a) == 16
assert a != hash_user("jane@example.com", b"key-1", "llm-abuse-v1") # another purpose gives an unlinkable ID
def test_redaction_catches_common_secrets() -> None:
text = "mail jane@example.com card 4242 4242 4242 4242 key sk-ant-api03-abcdefghijklmnop" # a fake key shape
assert redact.redact_text(text) == "mail [EMAIL] card [CARD] key [API_KEY]"
# --- Level 2: a fake client, scripted per test ---------------------------------------------------
def test_happy_path_sends_the_expected_request() -> None:
chat = FakeChat(ok('{"category": "billing", "urgent": false}'))
assert triage_ticket(chat, "I was charged twice", user="u1") == Triage("billing", False)
call = chat.calls[0]
assert call["max_tokens"] == 200 and call["user"] == "u1"
assert call["messages"][-1]["content"] == "I was charged twice"
@pytest.mark.parametrize("completion, reason", [(refused(), "refused"), (truncated('{"category": "bu'), "truncated")])
def test_refusal_and_truncation_go_to_a_human_and_are_never_parsed(completion: Completion, reason: str) -> None:
result = triage_ticket(FakeChat(completion), "anything")
assert result.needs_human and result.reason == reason
def test_malformed_json_goes_to_a_human() -> None:
result = triage_ticket(FakeChat(ok("Sure! Here you go: {category: bug}")), "anything")
assert result.needs_human and "not the expected JSON" in (result.reason or "")
def test_provider_errors_are_not_swallowed() -> None:
with pytest.raises(TimeoutError):
triage_ticket(FakeChat(TimeoutError("provider timed out")), "anything")
def test_a_fake_that_is_called_too_often_fails_loudly() -> None:
chat = FakeChat(ok('{"category": "bug", "urgent": false}'))
triage_ticket(chat, "one")
with pytest.raises(AssertionError, match="more times than the test scripted"):
triage_ticket(chat, "two")Save tests/fakes.py from 7.2 first (the file imports it; it is short), then run it:
uv run pytest tests/test_unit_and_fakes.py -v============================= test session starts ==============================
collected 21 items
tests/test_unit_and_fakes.py::test_build_messages_keeps_only_recent_history PASSED [ 4%]
tests/test_unit_and_fakes.py::test_parse_triage_accepts[{"category": "billing", "urgent": false}-expected0] PASSED [ 9%]
tests/test_unit_and_fakes.py::test_parse_triage_accepts[fenced] PASSED [ 14%]
tests/test_unit_and_fakes.py::test_parse_triage_accepts[ {"category": "how_to", "urgent": false} -expected2] PASSED [ 19%]
tests/test_unit_and_fakes.py::test_parse_triage_rejects[Sure! Here is the JSON: {}] PASSED [ 23%]
tests/test_unit_and_fakes.py::test_parse_triage_rejects[] PASSED [ 28%]
tests/test_unit_and_fakes.py::test_parse_triage_rejects[[]] PASSED [ 33%]
tests/test_unit_and_fakes.py::test_parse_triage_rejects[{"category": "weather", "urgent": false}] PASSED [ 38%]
tests/test_unit_and_fakes.py::test_parse_triage_rejects[{"category": "bug", "urgent": "yes"}] PASSED [ 42%]
tests/test_unit_and_fakes.py::test_parse_triage_rejects[{"category": "bug"}] PASSED [ 47%]
tests/test_unit_and_fakes.py::test_parse_triage_rejects[{"category": [], "urgent": true}] PASSED [ 52%]
tests/test_unit_and_fakes.py::test_parse_triage_rejects[{"category": {}, "urgent": true}] PASSED [ 57%]
tests/test_unit_and_fakes.py::test_outage_is_always_urgent PASSED [ 61%]
tests/test_unit_and_fakes.py::test_user_hash_is_stable_keyed_and_not_the_raw_id PASSED [ 66%]
tests/test_unit_and_fakes.py::test_redaction_catches_common_secrets PASSED [ 71%]
tests/test_unit_and_fakes.py::test_happy_path_sends_the_expected_request PASSED [ 76%]
tests/test_unit_and_fakes.py::test_refusal_and_truncation_go_to_a_human_and_are_never_parsed[completion0-refused] PASSED [ 80%]
tests/test_unit_and_fakes.py::test_refusal_and_truncation_go_to_a_human_and_are_never_parsed[completion1-truncated] PASSED [ 85%]
tests/test_unit_and_fakes.py::test_malformed_json_goes_to_a_human PASSED [ 90%]
tests/test_unit_and_fakes.py::test_provider_errors_are_not_swallowed PASSED [ 95%]
tests/test_unit_and_fakes.py::test_a_fake_that_is_called_too_often_fails_loudly PASSED [100%]
============================== 21 passed in 0.90s ==============================Things to notice in the tests:
- Parametrize the parser. Three accepted shapes (bare JSON, a Markdown code fence, padding) and eight rejected ones (chatty prose, empty string, a list, an unknown category, a string where a boolean belongs, a missing key, and a list and an object where the category should be: valid JSON that once crashed the parser, see 10.2). Every time production shows you a new weird model output, add one line to a list like this. That's how a parser's test suite becomes the memory of everything that went wrong.
- The business rule has its own test (
outageis always urgent), independent of any model. - Security-relevant helpers are tested too. The user hash must be stable, depend on the key, and not contain the raw ID; the redactor must catch the patterns it claims to.
This suite found a real bug while this lesson was written. The first version of the card-number pattern in redact.py swallowed the space after the number, and the test failed:
F [100%]
=================================== FAILURES ===================================
____________________ test_redaction_catches_common_secrets _____________________
def test_redaction_catches_common_secrets() -> None:
text = "mail jane@example.com card 4242 4242 4242 4242 key sk-ant-api03-abcdefghijklmnop"
> assert redact.redact_text(text) == "mail [EMAIL] card [CARD] key [API_KEY]"
E AssertionError: assert 'mail [EMAIL]...key [API_KEY]' == 'mail [EMAIL]...key [API_KEY]'
E
E - mail [EMAIL] card [CARD] key [API_KEY]
E ? -
E + mail [EMAIL] card [CARD]key [API_KEY]
tests/test_unit_and_fakes.py:54: AssertionError
=========================== short test summary info ============================
FAILED tests/test_unit_and_fakes.py::test_redaction_catches_common_secrets - ...
1 failed, 18 deselected in 0.08sThe ? marker line points at the difference: [CARD]key instead of [CARD] key. The fix was one regular expression (\b\d(?:[ -]?\d){12,18}\b), and the redact.py listed in 2.3 has the fixed pattern (its CARD entry). Without the test, the redactor would have silently glued words together in every log line.
7.2 Level 2: fake clients#
A fake client is a hand-written ChatModel that returns what the test tells it to. It lets you test everything above the adapter, including the cases that are awkward or expensive to get from a real model: a refusal, a truncated answer, a malformed reply, a timeout.
# tests/fakes.py
"""fakes.py: a scripted ChatModel. No HTTP, no SDK: the fastest test double there is."""
from __future__ import annotations
from chat_types import Completion, Message
class FakeChat:
"""Returns (or raises) the scripted items in order, and remembers every call it received."""
def __init__(self, *script: Completion | Exception) -> None:
self.script = list(script)
self.calls: list[dict] = []
def complete(self, system: str, messages: list[Message], *, max_tokens: int, user: str | None = None) -> Completion:
self.calls.append({"system": system, "messages": messages, "max_tokens": max_tokens, "user": user})
if not self.script:
raise AssertionError("FakeChat was called more times than the test scripted")
item = self.script.pop(0)
if isinstance(item, Exception):
raise item
return item
def ok(text: str) -> Completion:
return Completion(text=text, outcome="ok", finish_reason="stop", model="fake-model", request_id="req_fake")
def truncated(text: str) -> Completion:
return Completion(text=text, outcome="truncated", finish_reason="length", model="fake-model", request_id="req_fake")
def refused() -> Completion:
return Completion(text="I can't help with that.", outcome="refused", finish_reason="refusal",
model="fake-model", request_id="req_fake")FakeChat(*script) returns or raises its scripted items in order, and records every call so the test can assert on what it was given. Three habits make it a good fake:
- It fails loudly when over-called. A test that scripted one reply and triggers two calls gets an
AssertionError, so a retry loop that retries forever, or a double call, can't pass by accident (test_a_fake_that_is_called_too_often_fails_loudly). - It records the arguments.
test_happy_path_sends_the_expected_requestchecks the output cap, the user and the last message, which is how you catch "the ticket text wasn't passed to the model" with no HTTP involved. - It can raise as well as return. Putting an
Exceptionin the script tests that provider errors aren't swallowed (test_provider_errors_are_not_swallowed).
The second half of the file (below the "Level 2" comment) uses it. The three outcome tests are the point: a refusal and a truncated answer both end in needs_human=True with a reason, and the malformed-JSON case does too, so no failure mode ever crashes the ticket flow or sends half an answer to a parser.
What fakes can't tell you is whether your adapter works. For that you need the real SDK in the loop.
7.3 Level 3: mock transports under the real SDK#
A mock transport replaces only the lowest layer, the code that sends bytes over the network. Everything above it is the real SDK: it builds the real request, applies its own retry logic, parses the response into its real classes and raises its real exceptions. That makes this the most valuable layer for the code in adapters.py. Lesson 03.1, 1.3 introduced the idea; 03.8, 3.6 used it for errors.
Which transport object to use depends on the SDK's HTTP library (03.1, 4.5):
| SDK | Inject with | Transport and response classes |
|---|---|---|
openai, anthropic |
http_client=httpx2.Client(transport=...) |
httpx2.MockTransport, httpx2.Response |
google-genai |
HttpOptions(httpx_client=httpx.Client(transport=...)) (an httpx2.Client is also accepted) |
httpx.MockTransport, httpx.Response (with google-genai 3.x, httpx is no longer installed with the SDK: uv add httpx, or pass an httpx2.Client and httpx2 classes) |
The helpers: first the fixtures, which are the response bodies the "server" returns. They follow the shapes in each provider's API reference, with made-up IDs, counts and header values. Each provider gets five scenarios: success, refusal, truncation, a 429, and cache_heavy: one logical call, as that provider reports it, with a warm cache and some reasoning (100 prompt tokens in all, 60 of them read from the cache; 40 output tokens in all, 15 of them reasoning). The raw numbers differ per provider, because the providers disagree about what "input" means (4.1); the comments in fixtures.py say how.
# tests/fixtures.py
"""fixtures.py: provider response bodies for MOCK servers. Shapes copied from each provider's API reference;
ids, counts and header values are made up. Refresh them from real captures once you have keys."""
from typing import Any
TRIAGE_JSON = '{"category": "billing", "urgent": false}'
Reply = tuple[int, dict[str, Any], dict[str, str]] # (status, JSON body, headers)
# --- OpenAI Responses -------------------------------------------------------------------------------
def _responses(text: str | None, *, status: str = "completed", refusal: str | None = None,
incomplete: str | None = None, usage: dict[str, Any] | None = None) -> dict[str, Any]:
part = ({"type": "refusal", "refusal": refusal} if refusal
else {"type": "output_text", "text": text or "", "annotations": []})
return {"id": "resp_1", "object": "response", "status": status, "model": "gpt-6-luna-2026-10-01",
"incomplete_details": {"reason": incomplete} if incomplete else None,
"output": [{"type": "message", "id": "msg_1", "role": "assistant", "status": "completed",
"content": [part]}],
"usage": usage or {"input_tokens": 42, "output_tokens": 11, "total_tokens": 53,
"input_tokens_details": {"cached_tokens": 0}, "output_tokens_details": {"reasoning_tokens": 0}}}
# --- OpenAI / OpenRouter Chat Completions -----------------------------------------------------------
def _chat(content: str | None, finish: str = "stop", refusal: str | None = None, model: str = "gpt-6-luna-2026-10-01",
usage: dict[str, Any] | None = None) -> dict[str, Any]:
return {"id": "chatcmpl-1", "object": "chat.completion", "created": 1793000000, "model": model,
"choices": [{"index": 0, "finish_reason": finish,
"message": {"role": "assistant", "content": content, "refusal": refusal}}],
"usage": usage or {"prompt_tokens": 42, "completion_tokens": 11, "total_tokens": 53,
"prompt_tokens_details": {"cached_tokens": 0}, "completion_tokens_details": {"reasoning_tokens": 0}}}
# --- Anthropic Messages -----------------------------------------------------------------------------
def _claude(text: str, stop: str, usage: dict[str, Any] | None = None) -> dict[str, Any]:
return {"id": "msg_1", "type": "message", "role": "assistant", "model": "claude-haiku-5-5-20261015",
"content": [{"type": "text", "text": text}], "stop_reason": stop, "stop_sequence": None,
"usage": usage or {"input_tokens": 42, "output_tokens": 11, "cache_read_input_tokens": 0,
"cache_creation_input_tokens": 0}}
# --- Gemini generateContent -------------------------------------------------------------------------
def _gemini(text: str, finish: str, usage: dict[str, Any] | None = None) -> dict[str, Any]:
return {"responseId": "resp-gem-1", "modelVersion": "gemini-3.8-flash-001",
"candidates": [{"content": {"role": "model", "parts": [{"text": text}]}, "finishReason": finish}],
"usageMetadata": usage or {"promptTokenCount": 42, "candidatesTokenCount": 11, "totalTokenCount": 53}}
# --- the SAME call as each provider reports it, with a warm cache and some reasoning (lesson 03.7, 3.1) -----------------
# Every provider describes one logical call: 100 prompt tokens in all (60 read from the cache), 40 output tokens in all
# (15 of them reasoning). What differs is the RAW numbers, which is why the log must not copy them through.
CACHE_HEAVY: dict[str, dict[str, Any]] = {
# input_tokens INCLUDES cached and written tokens; output_tokens includes reasoning
"openai_responses": {"input_tokens": 100, "output_tokens": 40, "total_tokens": 140,
"input_tokens_details": {"cached_tokens": 60, "cache_write_tokens": 10},
"output_tokens_details": {"reasoning_tokens": 15}},
"openai_chat": {"prompt_tokens": 100, "completion_tokens": 40, "total_tokens": 140,
"prompt_tokens_details": {"cached_tokens": 60, "cache_write_tokens": 10},
"completion_tokens_details": {"reasoning_tokens": 15}},
# prompt_tokens includes cached and written ones, like OpenAI's
"openrouter_chat": {"prompt_tokens": 100, "completion_tokens": 40, "total_tokens": 140,
"prompt_tokens_details": {"cached_tokens": 60, "cache_write_tokens": 10},
"completion_tokens_details": {"reasoning_tokens": 15}},
# input_tokens EXCLUDES cache reads and writes (only the tokens after the last breakpoint); thinking is inside output_tokens
"anthropic": {"input_tokens": 30, "output_tokens": 40, "cache_read_input_tokens": 60,
"cache_creation_input_tokens": 10,
"cache_creation": {"ephemeral_5m_input_tokens": 10, "ephemeral_1h_input_tokens": 0},
"output_tokens_details": {"thinking_tokens": 15}},
# promptTokenCount INCLUDES cached tokens; candidatesTokenCount EXCLUDES thoughts, which are counted separately
"gemini": {"promptTokenCount": 100, "cachedContentTokenCount": 60, "candidatesTokenCount": 25,
"thoughtsTokenCount": 15, "totalTokenCount": 140},
}
OPENAI_H = {"x-request-id": "req_openai_1"}
SCENARIOS: dict[str, dict[str, Reply]] = {
"openai_responses": {
"ok": (200, _responses(TRIAGE_JSON), OPENAI_H),
"refused": (200, _responses(None, refusal="I can't help with that."), OPENAI_H),
"cache_heavy": (200, _responses(TRIAGE_JSON, usage=CACHE_HEAVY["openai_responses"]), OPENAI_H),
"truncated": (200, _responses('{"category": "bil', status="incomplete", incomplete="max_output_tokens"), OPENAI_H),
"rate_limited": (429, {"error": {"message": "Rate limit reached", "type": "rate_limit_error", "param": None,
"code": "rate_limit_exceeded"}}, {**OPENAI_H, "retry-after-ms": "5"})},
"openai_chat": {
"ok": (200, _chat(TRIAGE_JSON), OPENAI_H),
"refused": (200, _chat(None, "stop", "I can't help with that."), OPENAI_H),
"cache_heavy": (200, _chat(TRIAGE_JSON, usage=CACHE_HEAVY["openai_chat"]), OPENAI_H),
"truncated": (200, _chat('{"category": "bil', "length"), OPENAI_H),
"rate_limited": (429, {"error": {"message": "Rate limit reached", "type": "rate_limit_error", "param": None,
"code": "rate_limit_exceeded"}}, {**OPENAI_H, "retry-after-ms": "5"})},
"openrouter_chat": {
"ok": (200, _chat(TRIAGE_JSON, model="openai/gpt-6-luna"), {"x-generation-id": "gen-or-1"}),
"refused": (200, _chat(None, "stop", "I can't help with that.", "openai/gpt-6-luna"), {"x-generation-id": "gen-or-1"}),
"cache_heavy": (200, _chat(TRIAGE_JSON, model="openai/gpt-6-luna", usage=CACHE_HEAVY["openrouter_chat"]), {"x-generation-id": "gen-or-1"}),
"truncated": (200, _chat('{"category": "bil', "length", None, "openai/gpt-6-luna"), {"x-generation-id": "gen-or-1"}),
"rate_limited": (429, {"error": {"code": 429, "message": "Rate limit exceeded"}}, {"retry-after-ms": "5"})},
"anthropic": {
"ok": (200, _claude(TRIAGE_JSON, "end_turn"), {"request-id": "req_011Cexample"}),
"refused": (200, _claude("I can't help with that.", "refusal"), {"request-id": "req_011Cexample"}),
"cache_heavy": (200, _claude(TRIAGE_JSON, "end_turn", CACHE_HEAVY["anthropic"]), {"request-id": "req_011Cexample"}),
"truncated": (200, _claude('{"category": "bil', "max_tokens"), {"request-id": "req_011Cexample"}),
"rate_limited": (429, {"type": "error", "error": {"type": "rate_limit_error", "message": "Rate limited"},
"request_id": "req_011Cerr"}, {"request-id": "req_011Cerr", "retry-after-ms": "5"})},
"gemini": {
"ok": (200, _gemini(TRIAGE_JSON, "STOP"), {}),
"refused": (200, _gemini("", "SAFETY"), {}),
"cache_heavy": (200, _gemini(TRIAGE_JSON, "STOP", CACHE_HEAVY["gemini"]), {}),
"truncated": (200, _gemini('{"category": "bil', "MAX_TOKENS"), {}),
"rate_limited": (429, {"error": {"code": 429, "status": "RESOURCE_EXHAUSTED", "message": "Quota exceeded"}}, {})},
}Then mocks.py, which builds a real SDK client around a Script:
# tests/mocks.py
"""mocks.py: real SDK clients whose network layer is a Python script. Everything above the transport is the real SDK:
request building, retries, parsing, exceptions."""
from __future__ import annotations
import json
from dataclasses import dataclass
from typing import Any
import anthropic
import httpx
import httpx2
import openai
from google import genai
from google.genai import types
from fixtures import Reply
@dataclass
class Seen:
method: str
url: str
headers: dict[str, str]
body: Any
class Script:
"""Answers requests with the given replies, in order. A request beyond the script raises, so a test can never
pass by accident on an unexpected extra call."""
def __init__(self, *replies: Reply) -> None:
self.replies = list(replies)
self.seen: list[Seen] = []
def handler(self, http: Any) -> Any: # http is the module: httpx2 or httpx
def handle(request: Any) -> Any:
self.seen.append(Seen(request.method, str(request.url), dict(request.headers),
json.loads(request.content) if request.content else None))
if not self.replies:
raise AssertionError(f"unexpected request #{len(self.seen)}: {request.method} {request.url}")
status, body, headers = self.replies.pop(0)
return http.Response(status, json=body, headers=headers)
return handle
def openai_client(script: Script, *, base_url: str | None = None, max_retries: int = 0) -> openai.OpenAI:
transport = httpx2.MockTransport(script.handler(httpx2)) # openai 3.x and anthropic 2.x use httpx2
return openai.OpenAI(api_key="sk-test", base_url=base_url, max_retries=max_retries,
http_client=httpx2.Client(transport=transport))
def anthropic_client(script: Script, *, max_retries: int = 0) -> anthropic.Anthropic:
transport = httpx2.MockTransport(script.handler(httpx2))
return anthropic.Anthropic(api_key="sk-ant-test", max_retries=max_retries,
http_client=httpx2.Client(transport=transport))
def gemini_client(script: Script, *, attempts: int | None = None) -> genai.Client:
"""google-genai's models.* calls do not retry unless asked: attempts=N means N TOTAL attempts."""
retry = types.HttpRetryOptions(attempts=attempts, initial_delay=0.001, jitter=0) if attempts else None
transport = httpx.MockTransport(script.handler(httpx))
return genai.Client(api_key="gemini-test", http_options=types.HttpOptions(
httpx_client=httpx.Client(transport=transport), retry_options=retry))A Script is an ordered list of replies. It records each request it sees, and if a request arrives with no reply left it raises, which is the "transport that fails on unexpected calls" guard. Combined with max_retries=0 (or an explicit number), a test knows exactly how many requests may happen. Now the tests, which run the same scenarios against all five adapters (OpenAI Responses, OpenAI Chat Completions, OpenRouter Chat Completions, Anthropic and Gemini):
# tests/test_mock_transport.py
"""Level 3: the REAL SDKs over a MOCK network. Success, 429-then-success, refusal and truncation, for every adapter."""
from __future__ import annotations
from typing import Any, Callable
import pytest
from adapters import AnthropicChat, ChatCompletionsChat, GeminiChat, OpenAIResponsesChat
from chat_types import Completion, trace_id_var
from fixtures import SCENARIOS
from mocks import Script, anthropic_client, gemini_client, openai_client
MESSAGES: list[Any] = [{"role": "user", "content": "I was charged twice"}]
# name -> function building an adapter around a mock-backed client; retries=1 means "allow one retry"
Build = Callable[[Script, int], Any]
BUILDERS: dict[str, Build] = {
"openai_responses": lambda s, retries: OpenAIResponsesChat(openai_client(s, max_retries=retries), "gpt-6-luna"),
"openai_chat": lambda s, retries: ChatCompletionsChat(openai_client(s, max_retries=retries), "gpt-6-luna"),
"openrouter_chat": lambda s, retries: ChatCompletionsChat(
openai_client(s, base_url="https://openrouter.ai/api/v1", max_retries=retries), "openai/gpt-6-luna", openrouter=True),
"anthropic": lambda s, retries: AnthropicChat(anthropic_client(s, max_retries=retries), "claude-haiku-5-5"),
"gemini": lambda s, retries: GeminiChat(gemini_client(s, attempts=retries + 1 if retries else None), "gemini-3.8-flash"),
}
ADAPTERS = list(BUILDERS)
def run(adapter: str, *replies: Any, retries: int = 0) -> tuple[Completion, Script]:
script = Script(*replies)
return BUILDERS[adapter](script, retries).complete("Triage.", MESSAGES, max_tokens=200), script
@pytest.mark.parametrize("adapter", ADAPTERS)
def test_success_fills_every_field(adapter: str) -> None:
c, script = run(adapter, SCENARIOS[adapter]["ok"])
assert (c.outcome, c.text) == ("ok", '{"category": "billing", "urgent": false}')
assert (c.uncached_input_tokens, c.output_tokens) == (42, 11)
assert c.model and c.model != "gpt-6-luna" # the SERVED model, not the alias we asked for
assert c.request_id # support will ask for this
assert c.attempts == 1 and len(script.seen) == 1
# The same logical call, as each provider reports it: 100 prompt tokens in all (60 from the cache), 40 output tokens in all
# (15 of them reasoning). The Completion must say the same thing for every provider (lesson 03.7, 3.1).
EXPECTED = { # uncached input, cache writes: the raw `input` fields differ (OpenAI/OpenRouter and Gemini include cached tokens)
"openai_responses": (30, 10), "openai_chat": (30, 10), "openrouter_chat": (30, 10), "anthropic": (30, 10),
"gemini": (40, 0)} # Gemini reports no cache writes: 100 - 60 cached = 40
@pytest.mark.parametrize("adapter", ADAPTERS)
def test_usage_follows_the_module_convention_whatever_the_provider_reports(adapter: str) -> None:
c, _ = run(adapter, SCENARIOS[adapter]["cache_heavy"])
uncached, written = EXPECTED[adapter]
assert (c.uncached_input_tokens, c.cache_write_tokens) == (uncached, written)
assert c.cached_input_tokens == 60
assert c.total_input_tokens == 100 # uncached + cached + written: the same for all five
assert c.output_tokens == 40 # reasoning INCLUDED, even where the raw field excludes it
assert c.reasoning_tokens == 15 # informational: already inside output_tokens
@pytest.mark.parametrize("adapter", ADAPTERS)
def test_429_then_success_is_retried(adapter: str) -> None:
c, script = run(adapter, SCENARIOS[adapter]["rate_limited"], SCENARIOS[adapter]["ok"], retries=1)
assert c.outcome == "ok" and len(script.seen) == 2
if adapter != "gemini": # openai/anthropic SDKs say which attempt this is
assert [s.headers["x-stainless-retry-count"] for s in script.seen] == ["0", "1"]
assert c.attempts == 2
@pytest.mark.parametrize("adapter", ADAPTERS)
def test_refusal_is_an_outcome_not_an_exception(adapter: str) -> None:
c, _ = run(adapter, SCENARIOS[adapter]["refused"])
assert c.outcome == "refused"
@pytest.mark.parametrize("adapter", ADAPTERS)
def test_truncation_is_an_outcome_not_an_exception(adapter: str) -> None:
c, _ = run(adapter, SCENARIOS[adapter]["truncated"])
assert c.outcome == "truncated" and c.text.startswith('{"category"')
def test_openai_sends_our_trace_id_as_x_client_request_id() -> None:
script = Script(SCENARIOS["openai_responses"]["ok"])
trace_id_var.set("trace-123")
try:
OpenAIResponsesChat(openai_client(script), "gpt-6-luna").complete("Triage.", MESSAGES, max_tokens=50)
finally:
trace_id_var.set(None)
assert script.seen[0].headers["x-client-request-id"] == "trace-123"
def test_default_retries_would_make_this_test_slow_so_tests_set_max_retries_explicitly() -> None:
c = OpenAIResponsesChat(openai_client(Script(SCENARIOS["openai_responses"]["rate_limited"]), max_retries=0), "gpt-6-luna")
import openai
with pytest.raises(openai.RateLimitError) as info:
c.complete("Triage.", MESSAGES, max_tokens=50)
assert info.value.request_id == "req_openai_1"============================= test session starts ==============================
collected 27 items
tests/test_mock_transport.py::test_success_fills_every_field[openai_responses] PASSED [ 3%]
tests/test_mock_transport.py::test_success_fills_every_field[openai_chat] PASSED [ 7%]
tests/test_mock_transport.py::test_success_fills_every_field[openrouter_chat] PASSED [ 11%]
tests/test_mock_transport.py::test_success_fills_every_field[anthropic] PASSED [ 14%]
tests/test_mock_transport.py::test_success_fills_every_field[gemini] PASSED [ 18%]
tests/test_mock_transport.py::test_usage_follows_the_module_convention_whatever_the_provider_reports[openai_responses] PASSED [ 22%]
tests/test_mock_transport.py::test_usage_follows_the_module_convention_whatever_the_provider_reports[openai_chat] PASSED [ 25%]
tests/test_mock_transport.py::test_usage_follows_the_module_convention_whatever_the_provider_reports[openrouter_chat] PASSED [ 29%]
tests/test_mock_transport.py::test_usage_follows_the_module_convention_whatever_the_provider_reports[anthropic] PASSED [ 33%]
tests/test_mock_transport.py::test_usage_follows_the_module_convention_whatever_the_provider_reports[gemini] PASSED [ 37%]
tests/test_mock_transport.py::test_429_then_success_is_retried[openai_responses] PASSED [ 40%]
tests/test_mock_transport.py::test_429_then_success_is_retried[openai_chat] PASSED [ 44%]
tests/test_mock_transport.py::test_429_then_success_is_retried[openrouter_chat] PASSED [ 48%]
tests/test_mock_transport.py::test_429_then_success_is_retried[anthropic] PASSED [ 51%]
tests/test_mock_transport.py::test_429_then_success_is_retried[gemini] PASSED [ 55%]
tests/test_mock_transport.py::test_refusal_is_an_outcome_not_an_exception[openai_responses] PASSED [ 59%]
tests/test_mock_transport.py::test_refusal_is_an_outcome_not_an_exception[openai_chat] PASSED [ 62%]
tests/test_mock_transport.py::test_refusal_is_an_outcome_not_an_exception[openrouter_chat] PASSED [ 66%]
tests/test_mock_transport.py::test_refusal_is_an_outcome_not_an_exception[anthropic] PASSED [ 70%]
tests/test_mock_transport.py::test_refusal_is_an_outcome_not_an_exception[gemini] PASSED [ 74%]
tests/test_mock_transport.py::test_truncation_is_an_outcome_not_an_exception[openai_responses] PASSED [ 77%]
tests/test_mock_transport.py::test_truncation_is_an_outcome_not_an_exception[openai_chat] PASSED [ 81%]
tests/test_mock_transport.py::test_truncation_is_an_outcome_not_an_exception[openrouter_chat] PASSED [ 85%]
tests/test_mock_transport.py::test_truncation_is_an_outcome_not_an_exception[anthropic] PASSED [ 88%]
tests/test_mock_transport.py::test_truncation_is_an_outcome_not_an_exception[gemini] PASSED [ 92%]
tests/test_mock_transport.py::test_openai_sends_our_trace_id_as_x_client_request_id PASSED [ 96%]
tests/test_mock_transport.py::test_default_retries_would_make_this_test_slow_so_tests_set_max_retries_explicitly PASSED [100%]
============================== 27 passed in 0.73s ==============================Twenty-seven tests, about a second. What each group proves:
test_usage_follows_the_module_convention_whatever_the_provider_reportsis the parity test for the token fields. It feeds each adapter thecache_heavyreply and asserts the same facts from all five:total_input_tokens == 100,cached_input_tokens == 60,output_tokens == 40(reasoning included even where the raw field excludes it) andreasoning_tokens == 15; the uncached input is 30 for the four providers that report cache writes (10 written) and 40 for Gemini (100 minus 60 cached, no writes). If an SDK orcost_calcchanges what a field means, this fails.test_success_fills_every_fieldchecks that each SDK's real response object is read correctly: text, token counts, the served model (different from the alias that was requested), the request ID, and one attempt. If an SDK renames a field, this fails.test_429_then_success_is_retriedscripts a429then a200and checks the SDK retried once. Foropenaiandanthropicit also checks thex-stainless-retry-countheader on the two requests (0then1), which is how you assert "it retried" without timing anything. Gemini is configured withHttpRetryOptions(attempts=2, ...), becausemodels.*calls make one attempt unless you ask for more (03.8, 5.2). The 5 msretry-after-mshints in the fixtures are what keep the SDKs from waiting half a second.test_refusal...andtest_truncation...check the two "successful" responses that aren't (200with a refusal;200cut off by the output cap) becomeoutcomevalues instead of text that looks fine.test_openai_sends_our_trace_id...inspects the request the SDK sent: theX-Client-Request-Idheader equals the trace ID in the context variable.- The last test shows the error path: with
max_retries=0a429surfaces asopenai.RateLimitError, carrying the request ID.
7.4 The respx trap: mocks that silently do nothing#
respx and pytest-httpx are the popular way to mock httpx. They work by patching httpx. Since openai 3.0.0 and anthropic 2.x, those SDKs use httpx2, a different library with its own classes, so the patch doesn't reach them. Worse, nothing tells you: the test "mocks" a route, the SDK ignores the mock, and the call goes to the real network (or fails to connect, if you're lucky). Many tutorials and Stack Overflow answers still show the old pattern.
This script proves it safely. The base URL ends in .invalid, a top-level domain reserved so that it can never resolve, so if a request escapes the mock it fails instead of reaching anyone:
# s7_4_respx_trap.py
"""The respx trap: respx patches httpx only. openai 3.x and anthropic 2.x use httpx2, so their 'mocked' calls
really try to reach the network. The base_url below can never resolve (the .invalid TLD is reserved by RFC 6761),
so this script is safe: if a request escapes the mock, it fails instead of reaching anyone."""
import os
import anthropic
import httpx
import openai
import respx
from google import genai
from google.genai import types
HOST = "https://llm-api.invalid"
print("GOOGLE_GENAI_HTTP_CLIENT =", os.environ.get("GOOGLE_GENAI_HTTP_CLIENT", "(unset)"))
with respx.mock(assert_all_called=False) as router:
oai_route = router.post(f"{HOST}/v1/responses").mock(return_value=httpx.Response(200, json={"id": "x", "output": []}))
ant_route = router.post(f"{HOST}/v1/messages").mock(return_value=httpx.Response(200, json={"content": []}))
gem_route = router.post(f"{HOST}/v1beta/models/gemini-3.8-flash:generateContent").mock(
return_value=httpx.Response(200, json={"candidates": [{"content": {"role": "model", "parts": [{"text": "mocked"}]},
"finishReason": "STOP"}]}))
try:
openai.OpenAI(api_key="sk-test", base_url=f"{HOST}/v1", max_retries=0).responses.create(model="gpt-6-luna", input="hi")
except openai.APIConnectionError as e:
print(f"openai : {type(e).__name__} (cause: {type(e.__cause__).__name__}), respx route called: {oai_route.called}")
try:
anthropic.Anthropic(api_key="sk-ant-test", base_url=HOST, max_retries=0).messages.create(
model="claude-haiku-5-5", max_tokens=10, messages=[{"role": "user", "content": "hi"}])
except anthropic.APIConnectionError as e:
print(f"anthropic : {type(e).__name__} (cause: {type(e.__cause__).__name__}), respx route called: {ant_route.called}")
gem = genai.Client(api_key="gemini-test", http_options=types.HttpOptions(base_url=HOST))
try:
reply = gem.models.generate_content(model="gemini-3.8-flash", contents="hi")
print(f"google-genai: answered {reply.text!r}, respx route called: {gem_route.called}")
except Exception as e: # noqa: BLE001
print(f"google-genai: {type(e).__name__}, respx route called: {gem_route.called}")GOOGLE_GENAI_HTTP_CLIENT = (unset)
openai : APIConnectionError (cause: ConnectError), respx route called: False
anthropic : APIConnectionError (cause: ConnectError), respx route called: False
google-genai: answered 'mocked', respx route called: Trueopenai and anthropic both fail to connect (ConnectError), and the respx route was never called (respx route called: False). Only google-genai 2.34.0, which still defaults to httpx, gets the mocked answer. With google-genai 3.x this third line changes too: 3.0.0 (6 November 2026) uses httpx2 by default, so respx stops intercepting Gemini as well, and the same ConnectError appears. Now the same script with the environment variable that switches Gemini's default HTTP library:
GOOGLE_GENAI_HTTP_CLIENT=httpx2 uv run python s7_4_respx_trap.pyGOOGLE_GENAI_HTTP_CLIENT = httpx2
openai : APIConnectionError (cause: ConnectError), respx route called: False
anthropic : APIConnectionError (cause: ConnectError), respx route called: False
google-genai: ConnectError, respx route called: FalseNow google-genai is also un-mocked. pytest-httpx behaves the same way as respx (it also patches httpx): in a check with the versions named in Setup, a mocked openai call raised APIConnectionError and pytest-httpx reported at teardown that the response it had registered was never requested.
The defences, from strongest to weakest:
- Block the network for the whole test run.
pytest-socket's--disable-socketmakes any test that tries to open a socket fail immediately, whichever HTTP library or mock tool it uses. This is the strongest guard, because it doesn't depend on knowing which library the SDK uses.pytest.ini(7.9) turns it on for every test and only the tests markedstand_inorliveare exempt. - Inject the client, with the right transport:
http_client=httpx2.Client(transport=httpx2.MockTransport(...))foropenaiandanthropic(7.3). Don't rely on global patching. - Make the transport fail on unexpected requests.
Scriptraises when it runs out of replies. - Assert on the mock. A test that registers a mock should check it was used (
route.called,len(script.seen)). A mock nobody called is a test that tests nothing.
The guard in action:
# tests/test_network_guard.py
"""The guard against 'mocked' tests that really use the network. pytest.ini passes --disable-socket (pytest-socket),
so ANY test that reaches for a socket fails, whichever HTTP library or mock tool it uses."""
import httpx
import openai
import pytest
import respx
from pytest_socket import SocketBlockedError
def test_respx_does_not_mock_openai_but_the_socket_guard_catches_it() -> None:
with respx.mock(assert_all_called=False) as router:
route = router.post("https://llm-api.invalid/v1/responses").mock(return_value=httpx.Response(200, json={}))
client = openai.OpenAI(api_key="sk-test", base_url="https://llm-api.invalid/v1", max_retries=0)
# Without the guard this would be an APIConnectionError (the host never resolves) or, with a real host,
# a real request. With it, the test fails at once with a clear error:
with pytest.raises(SocketBlockedError):
client.responses.create(model="gpt-6-luna", input="hi")
assert route.called is False # respx never saw the request
def test_an_unmocked_default_client_cannot_reach_the_internet() -> None:
client = openai.OpenAI(api_key="sk-test", max_retries=0) # default base_url: the real api.openai.com
with pytest.raises(SocketBlockedError):
client.responses.create(model="gpt-6-luna", input="hi")============================= test session starts ==============================
collected 2 items
tests/test_network_guard.py::test_respx_does_not_mock_openai_but_the_socket_guard_catches_it PASSED [ 50%]
tests/test_network_guard.py::test_an_unmocked_default_client_cannot_reach_the_internet PASSED [100%]
============================== 2 passed in 0.21s ===============================With --disable-socket, the respx-mocked openai call doesn't quietly try the network: the first time the SDK's HTTP library opens a socket, pytest-socket raises SocketBlockedError, and the test fails at once with a message saying what happened. The second test shows the same thing for a client with no mock at all: the default OpenAI() pointed at api.openai.com. In a project with this guard, "a test hit the real API" is a failing test, not a surprise on the invoice.
7.5 Record and replay (cassettes)#
Hand-written fixtures drift. Record/replay avoids that: run the test once against a real server, save every request/response pair in a file (a cassette), and from then on replay the cassette with no network. The fixtures are real because they were real.
As of November 2026, the standard Python tool, vcrpy (used through the pytest-recording plugin), supports httpx2. This was checked in the versions named in Setup: vcrpy 9.4.2 patches httpx2's transports alongside httpx's, and cassettes recorded and replayed correctly for the openai and anthropic SDKs, including a streaming call. (google-genai was not recorded here: Gemini has no local stand-in, and recording needs a Gemini key.) So you don't need to write your own record/replay transport, though Part 13 shows how little code one takes. (Only 9.4.2 was tested. If you pin a different vcrpy, confirm that replay really works with --block-network before you trust it: a cassette test that quietly bypasses its cassette is another version of the respx trap in 7.4.)
flowchart LR
subgraph rec ["Record (rare, with a stand-in or a key)"]
T1["pytest --record-mode=once<br/>--force-enable-socket"] --> N["Real network"]
N --> W["Scrub secrets<br/>write cassette .yaml"]
end
W --> G["Review and commit<br/>the cassette"]
subgraph rep ["Replay (every push, no network)"]
T2["pytest --block-network"] --> P["Match request:<br/>method, URL, body"]
P -->|"match"| OK["Recorded response"]
P -->|"no match"| X["CannotOverwriteExistingCassette<br/>request changed: review the diff"]
end
G --> T2The setup is one fixture in conftest.py (shown in full in 7.9). Its vcr_config is where secret scrubbing lives, and where you decide what counts as "the same request". Scrubbing is by allow-list, for the same reason as in 2.3: filter_headers is a deny-list that only touches request headers, so a Set-Cookie, an openai-organization ID or a gateway's x-litellm-key-spend in a response would sail into the committed file, along with the recording machine's fingerprints (x-stainless-os: MacOS, x-stainless-arch: arm64, the Python version in user-agent). So only listed headers are kept, in both directions:
KEEP_REQUEST_HEADERS = {"content-type", "accept", "anthropic-version"}
KEEP_RESPONSE_HEADERS = {"content-type", "x-request-id", "request-id", "x-generation-id", "retry-after", "retry-after-ms"}
@pytest.fixture(scope="module")
def vcr_config() -> dict:
return {
"before_record_request": scrub_request, # keeps only KEEP_REQUEST_HEADERS; redact_url() on the URI (?key=...)
"before_record_response": scrub_response, # keeps only KEEP_RESPONSE_HEADERS and the rate-limit families
"match_on": ["method", "uri", "body"], # include the body: if the prompt changes, the replay MISSES
"decode_compressed_response": True, # readable text in the file, not gzip bytes
}And the tests are ordinary tests marked @pytest.mark.vcr:
# tests/test_record_replay.py
"""Record/replay with vcrpy + pytest-recording. vcrpy 9.4 patches httpx2, so openai and anthropic cassettes work.
Record once against the stand-in (or the real API), commit the cassette, replay forever with no network.
Gemini has no local stand-in, so a Gemini cassette can only be recorded with a hosted key (not shown here):
record: pytest --force-enable-socket --record-mode=once tests/test_record_replay.py
replay: pytest --block-network tests/test_record_replay.py"""
import os
import anthropic
import openai
import pytest
from adapters import AnthropicChat, OpenAIResponsesChat
from chat_types import Completion
MESSAGES = [{"role": "user", "content": "Reply with the single word: ready"}]
def key(name: str) -> str:
"""A replay never needs a real key, so use the environment's only if it is NOT empty: CI sets keys to ""
("explicitly empty"), and the SDKs raise at construction for an empty string."""
return os.environ.get(name) or "replay-only"
def check(c: Completion) -> None:
# Assert SHAPES. A replay returns the recorded words, but the test must also pass when you re-record them.
assert isinstance(c.text, str) and c.outcome in {"ok", "truncated"}
assert isinstance(c.uncached_input_tokens, int) and c.model
@pytest.mark.vcr
def test_openai_responses_replay() -> None:
client = openai.OpenAI(base_url="http://localhost:11434/v1", api_key=key("OPENAI_API_KEY"), max_retries=0)
check(OpenAIResponsesChat(client, "gpt-6-luna").complete("Be brief.", MESSAGES, max_tokens=20)) # type: ignore[arg-type]
@pytest.mark.vcr
def test_anthropic_messages_replay() -> None:
client = anthropic.Anthropic(base_url="http://localhost:11434", api_key=key("ANTHROPIC_API_KEY"), max_retries=0)
check(AnthropicChat(client, "claude-haiku-5-5").complete("Be brief.", MESSAGES, max_tokens=20)) # type: ignore[arg-type]
Record once (this run needs the network, so it overrides --disable-socket; here it recorded against the local stand-in, and with keys and a hosted model you'd do the same):
uv run pytest --force-enable-socket --record-mode=once tests/test_record_replay.pyReplay, which is the normal run (--block-network is pytest-recording's own guard, in addition to --disable-socket):
uv run pytest --block-network tests/test_record_replay.py============================= test session starts ==============================
collected 2 items
tests/test_record_replay.py::test_openai_responses_replay PASSED [ 50%]
tests/test_record_replay.py::test_anthropic_messages_replay PASSED [100%]
============================== 2 passed in 0.71s ===============================A replay never needs a real key, and it must not care what the environment holds. Part 12's no-keys job sets every key variable to the empty string ("explicitly empty"), and the SDKs raise at construction for an empty key (OpenAIError: Missing credentials, ValueError: No API key was provided). The obvious os.environ.get("OPENAI_API_KEY", "replay-only") returns "" when the variable exists but is empty, and that job would be red. The key() helper therefore uses os.environ.get(name) or "replay-only". The same run with all four variables empty:
============================= test session starts ==============================
collected 2 items
tests/test_record_replay.py::test_openai_responses_replay PASSED [ 50%]
tests/test_record_replay.py::test_anthropic_messages_replay PASSED [100%]
============================== 2 passed in 0.68s ===============================What the cassette looks like inside, for the first test (trimmed to the parts that matter). Two headers survive in the request and one in the response; the key, the host, the SDK's version and the machine's details are not in the file at all:
interactions:
- request:
body: '{"model":"gpt-6-luna","input":[{"role":"user","content":"Reply with the
single word: ready"}],"instructions":"Be brief.","max_output_tokens":20}'
headers:
accept:
- application/json
content-type:
- application/json
method: POST
uri: http://localhost:11434/v1/responses
response:
body:
string: '{"id":"resp_335059","object":"response", ... "usage":{"input_tokens":23, ...}}'
headers:
content-type:
- application/json
status:
code: 200
message: OK
version: 1"A search of the cassettes for the key found nothing" is weak evidence on its own (the key used while recording may have been a dummy), so a test does the looking. tests/test_cassettes.py is a cassette lint: it fails if a cassette contains a key-shaped string (it reuses the patterns of redact.py), a cookie, an organization or project ID, a machine fingerprint, any header outside the allow-lists, or the value of any *_API_KEY, *_MASTER_KEY or *_TOKEN variable in the environment of whoever runs the test. The last check is the strong one: record with your real variables set, and the lint proves none of them reached the file. A lint that has never failed is a guess, so its last test feeds it a deliberately dirty cassette (all values obviously fake) and checks that every kind of problem is reported:
# tests/test_cassettes.py
"""A cassette lint: the committed cassettes are read by strangers, so a test (not a person's memory) checks them.
It looks for the things that have actually leaked from cassettes elsewhere: key-shaped strings, the value of any key
in YOUR environment, cookies, organization IDs, and fingerprints of the machine that recorded them."""
from __future__ import annotations
import os
from pathlib import Path
import pytest
import yaml
from conftest import KEEP_REQUEST_HEADERS, KEEP_RESPONSE_HEADERS, KEEP_RESPONSE_PREFIXES
from redact import find_secrets
CASSETTES = sorted(Path(__file__).parent.glob("cassettes/**/*.yaml"))
# Fragments that mean "this came from the provider's account or the recording machine", wherever they appear
FORBIDDEN = ("cookie", "organization", "cf-ray", "x-stainless-", "user-agent", "x-litellm-", "arm64", "macos", "gl-python")
def problems(text: str) -> list[str]:
"""Everything wrong with one cassette's text (an empty list means clean)."""
found = [f"key-shaped string ({label})" for label in find_secrets(text)]
found += [f"forbidden fragment {word!r}" for word in FORBIDDEN if word in text.lower()]
for name, value in os.environ.items(): # the strongest check: a value from the environment of whoever recorded it
if name.endswith(("_API_KEY", "_MASTER_KEY", "_TOKEN", "_SECRET")) and len(value) >= 8 and value in text:
found.append(f"the value of ${name}")
for interaction in yaml.safe_load(text)["interactions"]: # and the allow-list really held
found += [f"request header {h!r}" for h in interaction["request"]["headers"] if h not in KEEP_REQUEST_HEADERS]
found += [f"response header {h!r}" for h in interaction["response"]["headers"]
if h not in KEEP_RESPONSE_HEADERS and not h.startswith(KEEP_RESPONSE_PREFIXES)]
return found
def test_there_are_cassettes_to_lint() -> None:
assert CASSETTES, "no cassettes found: a lint that checks nothing passes forever"
@pytest.mark.parametrize("path", CASSETTES, ids=lambda p: p.stem)
def test_cassette_holds_no_secret_account_id_or_machine_fingerprint(path: Path) -> None:
assert problems(path.read_text()) == []
def test_the_lint_itself_catches_what_it_claims_to(monkeypatch: pytest.MonkeyPatch) -> None:
"""A lint that has never failed is a guess. This feeds it a deliberately dirty cassette (all values obviously fake)."""
monkeypatch.setenv("MY_SERVICE_API_KEY", "value-from-the-recorders-environment")
dirty = f"""
interactions:
- request:
headers:
x-stainless-os: [MacOS]
authorization: ["Bearer {"sk-" + "proj-" + "EXAMPLE" * 5}"]
body: 'the key was value-from-the-recorders-environment'
response:
headers:
set-cookie: ["__cf_bm=abc"]
openai-organization: ["org-example"]
"""
found = " | ".join(problems(dirty))
for expected in ("key-shaped string", "$MY_SERVICE_API_KEY", "'set-cookie'", "'openai-organization'",
"'x-stainless-os'", "'authorization'", "forbidden fragment 'cookie'"):
assert expected in found, expected============================= test session starts ==============================
collected 4 items
tests/test_cassettes.py::test_there_are_cassettes_to_lint PASSED [ 25%]
tests/test_cassettes.py::test_cassette_holds_no_secret_account_id_or_machine_fingerprint[test_anthropic_messages_replay] PASSED [ 50%]
tests/test_cassettes.py::test_cassette_holds_no_secret_account_id_or_machine_fingerprint[test_openai_responses_replay] PASSED [ 75%]
tests/test_cassettes.py::test_the_lint_itself_catches_what_it_claims_to PASSED [100%]
============================== 4 passed in 0.05s ===============================Say plainly what no scrubber can promise: record with a throwaway key in a dedicated project, never with customer data, and read the file before you commit it. The lint catches what it knows to look for.
And what happens when the code's request changes, here the system prompt going from Be brief. to Be very brief.. Because body is in match_on, replay has nothing to match, and vcrpy raises CannotOverwriteExistingCassetteException and says why (the layout of the message differs between vcrpy versions; this is the shape to expect):
vcr.errors.CannotOverwriteExistingCassetteException: Can't play back this request: no recorded interaction matches it (the closest differ in body).
record_mode 'none' doesn't record new requests.
POST http://localhost:11434/v1/responses
body: {"model":"gpt-6-luna","input":[{"role":"user","content":"Reply with the single word: ready"}],"instructions":"Be very brief.","max_output_tokens":20}
Cassette: tests/cassettes/test_record_replay/test_openai_responses_replay.yaml
record_mode: none
match_on: method, uri, body
interactions: 1 recorded, 0 played
Closest recorded requests:
1. POST http://localhost:11434/v1/responses
body differs:
--- recorded
+++ this request
@@ -7,3 +7,3 @@
],
- "instructions": "Be brief.",
+ "instructions": "Be very brief.",
"max_output_tokens": 20,
How to fix:
* If the request changed on purpose, record it again: run once with
record_mode='new_episodes' to add it to the cassette, or record_mode='all'
with drop_unused_requests=True to re-record the cassette from scratch [1].
* If the difference changes on every run (a timestamp, a random ID), make
matching ignore it: loosen match_on, or normalize the request with
before_record_request [2].
[1] https://vcrpy.readthedocs.io/en/latest/usage.html#record-modes
[2] https://vcrpy.readthedocs.io/en/latest/configuration.html#request-matchingThat diff is the feature. A cassette test fails when the request changes, and shows the change, so a prompt edit can't slip through unnoticed. If the change was intended, re-record.
Practical rules for cassettes:
- Treat a cassette like code and like data. It's committed and reviewed, and it contains real response bodies and your prompts. Read it before committing, and never record with real customer data.
- Scrub by allow-list, in both directions. A header that isn't on the list isn't recorded. If a provider returns IDs or personal data in the body, scrub that in
before_record_responsetoo, and let the lint look for it. - Match on the body. Without it, a replay returns the old answer to a new prompt and the test passes while testing nothing.
- Assert shapes. A replayed answer is a frozen sentence; when you re-record, the words change, so the test must pass either way (
check()in the sample). - Re-record on a schedule. Cassettes go stale as providers change. Re-recording a handful periodically (
--record-mode=rewritewith live keys in a CI job that opens a pull request with the diff) is how fixtures are "refreshed from real captures". - Record modes.
pytest-recordingoffersnone(replay only; the default, and the safe one for CI),once(record if the cassette doesn't exist yet),new_episodes(also record requests the cassette hasn't seen),all(record everything again, appending) andrewrite(delete the cassette and record it again). The list comes frompytest --help; check it for your version.
7.6 Snapshot the request, not the answer#
A snapshot test saves the output of a function the first time it runs and fails if the output ever changes. Applied to a model's answer it's a flaky test; applied to the request your code builds, it's one of the best tests in this lesson, because the request is deterministic and it is exactly what changes when someone edits a prompt template, a default parameter or a history-trimming rule.
# tests/snapshot.py
"""snapshot.py: a short snapshot helper. Snapshot the REQUEST your code builds, never the model's reply."""
import difflib
import json
import os
from pathlib import Path
from typing import Any
SNAPSHOT_DIR = Path(__file__).parent / "snapshots"
def assert_matches_snapshot(name: str, data: Any) -> None:
"""First run on a laptop (or UPDATE_SNAPSHOTS=1) writes the file; later runs compare and show a unified diff.
In CI (the CI variable is set) a MISSING snapshot is a failure: a file somebody forgot to `git add` would
otherwise be created on the runner and the test would pass while checking nothing."""
path = SNAPSHOT_DIR / f"{name}.json"
actual = json.dumps(data, indent=2, sort_keys=True, ensure_ascii=False) + "\n"
updating = os.environ.get("UPDATE_SNAPSHOTS") == "1"
if not path.exists() and os.environ.get("CI") and not updating:
raise AssertionError(f"snapshot {path.name} is missing in CI: run the test locally and commit the file")
if updating or not path.exists():
SNAPSHOT_DIR.mkdir(exist_ok=True)
path.write_text(actual)
return
expected = path.read_text()
if actual != expected:
diff = "".join(difflib.unified_diff(expected.splitlines(True), actual.splitlines(True),
f"snapshot/{name}", "actual", n=2))
raise AssertionError(f"request changed (rerun with UPDATE_SNAPSHOTS=1 if intended):\n{diff}")# tests/test_snapshot.py
"""Level 5: snapshot tests of the request each adapter builds. A prompt or parameter change shows up as a diff in review."""
from __future__ import annotations
from pathlib import Path
from typing import Any
import pytest
import snapshot
from captured_adapters import NAMES, build_capturing
from snapshot import assert_matches_snapshot
from triage import triage_ticket
from wire_capture import WireCapture
HISTORY: list[Any] = [{"role": "user", "content": "My invoice looks wrong"},
{"role": "assistant", "content": '{"category": "billing", "urgent": false}'}]
@pytest.mark.parametrize("name", NAMES)
def test_request_payload_snapshot(name: str) -> None:
cap = WireCapture()
chat = build_capturing(name, cap)
sent = cap.run(lambda: triage_ticket(chat, "I was charged twice, please refund", history=HISTORY, user="u-hash"))
# Method, URL and body are the contract. Headers are mostly SDK noise, so snapshot only the ones we set.
keep = {k: v for k, v in sent.headers.items() if k in {"anthropic-version", "x-client-request-id"}}
assert_matches_snapshot(f"triage_{name}", {"method": sent.method, "url": sent.url, "headers": keep, "body": sent.body})
# --- the helper itself: a snapshot test that can silently pass is worse than none --------------------------
def test_a_missing_snapshot_fails_in_ci_and_writes_nothing(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
monkeypatch.setattr(snapshot, "SNAPSHOT_DIR", tmp_path)
monkeypatch.setenv("CI", "true")
monkeypatch.delenv("UPDATE_SNAPSHOTS", raising=False)
with pytest.raises(AssertionError, match="missing in CI"):
snapshot.assert_matches_snapshot("forgotten", {"a": 1})
assert list(tmp_path.iterdir()) == [] # CI must not "fix" it by creating the file
def test_the_first_run_on_a_laptop_writes_the_snapshot(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
monkeypatch.setattr(snapshot, "SNAPSHOT_DIR", tmp_path)
monkeypatch.delenv("CI", raising=False)
monkeypatch.delenv("UPDATE_SNAPSHOTS", raising=False)
snapshot.assert_matches_snapshot("new", {"a": 1})
assert (tmp_path / "new.json").exists()
snapshot.assert_matches_snapshot("new", {"a": 1}) # ... and the second run compares
with pytest.raises(AssertionError, match="request changed"):
snapshot.assert_matches_snapshot("new", {"a": 2})Each of the five adapters builds its request through a capturing client (the wire capture of 2.5, wired by captured_adapters.py in 3.4), and the test compares method, URL, the few headers we set ourselves, and the JSON body with a committed file. The first run on a laptop writes the files; UPDATE_SNAPSHOTS=1 rewrites them when a change is intended. In CI a missing snapshot is a failure (the CI variable, which GitHub Actions sets, is checked): otherwise a snapshot nobody committed would be created on the runner and the test would pass while checking nothing. The helper's own tests, at the bottom of test_snapshot.py, pin that. One of the five snapshots, for Anthropic, is worth reading in full once. It's the exact request, including the system prompt, the alternating turns, the hashed user and the anthropic-version header:
{
"body": {
"max_tokens": 200,
"messages": [
{"content": "My invoice looks wrong", "role": "user"},
{"content": "{\"category\": \"billing\", \"urgent\": false}", "role": "assistant"},
{"content": "I was charged twice, please refund", "role": "user"}
],
"metadata": {"user_id": "u-hash"},
"model": "claude-haiku-5-5",
"system": "You triage customer-support tickets. Reply with JSON only, no prose: ..."
},
"headers": {"anthropic-version": "2026-10-21"},
"method": "POST",
"url": "https://api.anthropic.com/v1/messages"
}(Reformatted from the file to save lines; the real files use indent=2.) Now someone "tidies" the system prompt by deleting no prose. The code still works, every other test still passes, and the answers might even look fine in a quick manual try. The snapshot test fails:
F [100%]
=================================== FAILURES ===================================
___________________ test_request_payload_snapshot[anthropic] ___________________
tests/test_snapshot.py:26: in test_request_payload_snapshot
assert_matches_snapshot(f"triage_{name}", {"method": sent.method, "url": sent.url, "headers": keep, "body": sent.body})
tests/snapshot.py:28: in assert_matches_snapshot
raise AssertionError(f"request changed (rerun with UPDATE_SNAPSHOTS=1 if intended):\n{diff}")
E AssertionError: request changed (rerun with UPDATE_SNAPSHOTS=1 if intended):
E --- snapshot/triage_anthropic
E +++ actual
E @@ -20,5 +20,5 @@
E },
E "model": "claude-haiku-5-5",
E - "system": "You triage customer-support tickets. Reply with JSON only, no prose: {\"category\": \"billing\" | \"bug\" | \"how_to\" | \"other\", \"urgent\": true | false}"
E + "system": "You triage customer-support tickets. Reply with JSON only: {\"category\": \"billing\" | \"bug\" | \"how_to\" | \"other\", \"urgent\": true | false}"
E },
E "headers": {
=========================== short test summary info ============================
FAILED tests/test_snapshot.py::test_request_payload_snapshot[anthropic] - Ass...
1 failed, 6 deselected in 0.13sThe reviewer sees a prompt change as a diff in the pull request: the -/+ lines are the old and new system prompt. They can decide it's intended, run UPDATE_SNAPSHOTS=1, and commit the new snapshot alongside the code. That is the entire workflow, and it makes "who changed the prompt?" answerable from git blame. (Libraries such as syrupy and inline-snapshot offer more features: pretty diffs, inline snapshots, review commands. The short helper shows the whole idea.)
Notice the two other things the five snapshots give you for free: the differences between providers are documented in code (Gemini's generationConfig.maxOutputTokens, systemInstruction and labels, Anthropic's system and metadata, OpenRouter's max_tokens and user, OpenAI's safety_identifier), and any SDK upgrade that changes how a request is serialized shows up as a snapshot diff in the dependency-bump pull request (03.1, 4.4).
7.7 Contract tests against the local stand-in#
Mock transports and cassettes test your code against your idea of the server. A contract test puts a real server on the other end of a real socket, to check that the two sides still agree. The free local stand-in (03.1, Part 12) is exactly that: Ollama speaks the OpenAI Chat Completions, OpenAI Responses and Anthropic Messages formats. It does not speak Gemini's, so there is no Gemini contract test here: for Gemini, use the mocks of Part 6 or a hosted live test (7.8).
# tests/test_contract_standin.py
"""Contract tests against the free local stand-in: Ollama, for the openai and anthropic SDK paths.
They check SHAPES (the SDK parsed it, fields exist, types are right), never the words a small local model chose.
Skipped automatically when the stand-in is not running."""
from __future__ import annotations
import anthropic
import openai
import pytest
from adapters import AnthropicChat, ChatCompletionsChat, OpenAIResponsesChat
from conftest import port_open
pytestmark = pytest.mark.stand_in
needs_ollama = pytest.mark.skipif(not port_open("localhost", 11434), reason="Ollama is not running on :11434")
MESSAGES = [{"role": "user", "content": "Reply with the single word: ready"}]
def check_shape(c) -> None: # type: ignore[no-untyped-def]
assert isinstance(c.text, str) and c.outcome in {"ok", "truncated"}
assert c.model and c.attempts == 1
assert isinstance(c.uncached_input_tokens, int) and isinstance(c.output_tokens, int)
@needs_ollama
def test_openai_responses_against_ollama() -> None:
client = openai.OpenAI(base_url="http://localhost:11434/v1", api_key="ollama", max_retries=0)
check_shape(OpenAIResponsesChat(client, "gpt-6-luna").complete("Be brief.", MESSAGES, max_tokens=20)) # type: ignore[arg-type]
@needs_ollama
@pytest.mark.parametrize("openrouter", [False, True], ids=["openai_chat", "openrouter_chat"])
def test_chat_completions_against_ollama(openrouter: bool) -> None:
"""Both branches of ChatCompletionsChat. OpenAI proper gets max_completion_tokens and safety_identifier; the
OpenRouter branch gets max_tokens and user. Ollama accepts either name and honours only max_tokens, so this proves the
request is well-formed and the response parses, NOT that a cap was enforced (that needs a hosted server or a mock)."""
client = openai.OpenAI(base_url="http://localhost:11434/v1", api_key="ollama", max_retries=0)
chat = ChatCompletionsChat(client, "gpt-6-luna", openrouter=openrouter)
check_shape(chat.complete("Be brief.", MESSAGES, max_tokens=20, user="u-hash")) # type: ignore[arg-type]
@needs_ollama
def test_anthropic_messages_against_ollama() -> None:
client = anthropic.Anthropic(base_url="http://localhost:11434", api_key="ollama", max_retries=0)
check_shape(AnthropicChat(client, "claude-haiku-5-5").complete("Be brief.", MESSAGES, max_tokens=20)) # type: ignore[arg-type]
@needs_ollama
def test_an_unknown_model_is_a_typed_error_not_a_crash() -> None:
client = openai.OpenAI(base_url="http://localhost:11434/v1", api_key="ollama", max_retries=0)
with pytest.raises(openai.NotFoundError):
OpenAIResponsesChat(client, "no-such-model").complete("Be brief.", MESSAGES, max_tokens=20) # type: ignore[arg-type]The design points:
- They check shapes, never words.
check_shapeverifies that the SDK parsed the response, the fields have the right types, the model name is present, and only one attempt was needed. A small local model's text is meaningless; the test never reads it. - A marker (
@pytest.mark.stand_in) labels them so CI can select or skip the group (7.9), andconftest.pygives marked tests the exception to--disable-socket. - They skip themselves when the stand-in isn't running, so a teammate without Ollama sees a skip, not a failure. The helper
port_opentries a TCP connection for 0.3 seconds. - Both Chat Completions branches run.
ChatCompletionsChatsendsmax_completion_tokensandsafety_identifierto OpenAI proper andmax_tokensanduserto OpenRouter, so the test is parametrized overopenrouter=FalseandTrue. Ollama ignoresmax_completion_tokensand honours onlymax_tokens(known quirk), so a pass proves the request is well-formed and the response parses, not that a cap was enforced. Running only the OpenRouter branch under an OpenAI name would leave themax_completion_tokenspath unexercised, which is why both are tested. If you copy the wrong flag from a stand-in-tested sample, a hosted OpenAI model is where you find out. - The error test is a contract too. An unknown model must surface as
openai.NotFoundError(a typed exception), which proves your error handling will see the right class.
============================= test session starts ==============================
collected 5 items
tests/test_contract_standin.py::test_openai_responses_against_ollama PASSED [ 20%]
tests/test_contract_standin.py::test_chat_completions_against_ollama[openai_chat] PASSED [ 40%]
tests/test_contract_standin.py::test_chat_completions_against_ollama[openrouter_chat] PASSED [ 60%]
tests/test_contract_standin.py::test_anthropic_messages_against_ollama PASSED [ 80%]
tests/test_contract_standin.py::test_an_unknown_model_is_a_typed_error_not_a_crash PASSED [100%]
============================== 5 passed in 1.19s ===============================And with the stand-in switched off. This run was made on the same machine with the tests' port numbers pointed at unused ports, which is what "not running" looks like to port_open:
sssss [100%]
=========================== short test summary info ============================
SKIPPED [1] tests/test_contract_standin.py:24: Ollama is not running on :11434
SKIPPED [2] tests/test_contract_standin.py:30: Ollama is not running on :11434
SKIPPED [1] tests/test_contract_standin.py:41: Ollama is not running on :11434
SKIPPED [1] tests/test_contract_standin.py:47: Ollama is not running on :11434
5 skipped in 0.60sFive skips (the Chat Completions test is two tests), each with a reason; the suite stays green.
7.8 Live smoke tests#
Eventually something has to talk to the real API, because nothing else tells you the provider still accepts your requests, your key still works, and the model alias you rely on still exists. A smoke test is the smallest check that "the whole thing is on fire or not". Four rules keep live tests useful and cheap:
- Opt in twice. A test runs only if the provider's key is set and
RUN_LIVE_TESTS=1. A developer with keys in.envwho typespytestmust not spend money by accident. - Cheap model, tiny cap, few calls. The default model of each provider,
max_tokens=200(enough for models that think first; 02.8), one call each. - A hard budget. The
live_budgetfixture (inconftest.py) counts calls and fails the run if a loop makes more thanLIVE_CALL_BUDGET(default 6). This is the seatbelt for the day someone parametrizes a live test over 200 inputs. - Run on a schedule, not on every commit (Part 12). Live tests are slow, cost money, and fail for reasons that aren't your code's fault (outages, rate limits). They're a canary, not a gate.
# tests/test_live_smoke.py
"""Live smoke tests: one tiny call per provider, against the REAL APIs. Run on a schedule, not on every commit.
Opt-in twice (RUN_LIVE_TESTS=1 and the provider's key), a cheap model, a tiny output cap, and a hard call budget."""
from __future__ import annotations
import os
import anthropic
import pytest
from dotenv import load_dotenv
from google import genai
from openai import OpenAI
from adapters import AnthropicChat, ChatCompletionsChat, GeminiChat, OpenAIResponsesChat
from chat_types import Completion
load_dotenv()
pytestmark = pytest.mark.live
MESSAGES: list = [{"role": "user", "content": "Reply with the single word: ready"}]
def need(key: str) -> pytest.MarkDecorator:
reason = (f"{key} is not set" if not os.environ.get(key)
else "set RUN_LIVE_TESTS=1 to spend money on live tests" if os.environ.get("RUN_LIVE_TESTS") != "1" else "")
return pytest.mark.skipif(bool(reason), reason=reason or "")
def check_live(c: Completion) -> None:
assert c.text.strip() and c.outcome == "ok"
assert (c.total_input_tokens or 0) > 0 and (c.output_tokens or 0) > 0
redirected = any(os.environ.get(v) for v in ("OPENAI_BASE_URL", "ANTHROPIC_BASE_URL", "GOOGLE_GEMINI_BASE_URL"))
if not redirected: # a local stand-in sends no request ids and may omit the model
assert c.request_id
assert c.model # the SERVED model: log it, it can differ from the alias
@need("OPENAI_API_KEY")
def test_openai_responses(live_budget) -> None: # type: ignore[no-untyped-def]
live_budget.spend()
check_live(OpenAIResponsesChat(OpenAI(max_retries=2, timeout=30), "gpt-6-luna").complete("Be brief.", MESSAGES, max_tokens=200))
@need("ANTHROPIC_API_KEY")
def test_anthropic_messages(live_budget) -> None: # type: ignore[no-untyped-def]
live_budget.spend()
check_live(AnthropicChat(anthropic.Anthropic(max_retries=2, timeout=30), "claude-haiku-5-5").complete("Be brief.", MESSAGES, max_tokens=200))
@need("GEMINI_API_KEY")
def test_gemini_generate_content(live_budget) -> None: # type: ignore[no-untyped-def]
live_budget.spend()
check_live(GeminiChat(genai.Client(), "gemini-3.8-flash").complete("Be brief.", MESSAGES, max_tokens=200))
@need("OPENROUTER_API_KEY")
def test_openrouter_chat(live_budget) -> None: # type: ignore[no-untyped-def]
live_budget.spend()
client = OpenAI(base_url="https://openrouter.ai/api/v1", api_key=os.environ.get("OPENROUTER_API_KEY"), max_retries=2, timeout=30,
default_headers={"HTTP-Referer": "https://example.com", "X-OpenRouter-Title": "Smoke tests"})
check_live(ChatCompletionsChat(client, "openai/gpt-6-luna", openrouter=True).complete("Be brief.", MESSAGES, max_tokens=200))This is a provider sample (it calls hosted APIs when run with keys). It uses the standard forms (OpenAI(...), anthropic.Anthropic(...), genai.Client(), keys from the environment through python-dotenv), and each provider is checked against its own documentation: the request IDs, served-model fields and usage fields in 1.5, and the OpenRouter attribution headers (03.1, 6.6). What a passing live test asserts is deliberately modest: non-empty text, outcome ok, positive token counts, a request ID and a served model name (the last two are skipped when the SDK is redirected to a stand-in, because Ollama sends neither).
With no keys, which is how every learner and every CI push starts, the tests report themselves as skipped, with the reason:
============================= test session starts ==============================
collected 4 items
tests/test_live_smoke.py::test_openai_responses SKIPPED (OPENAI_API_...) [ 25%]
tests/test_live_smoke.py::test_anthropic_messages SKIPPED (ANTHROPIC...) [ 50%]
tests/test_live_smoke.py::test_gemini_generate_content SKIPPED (set ...) [ 75%]
tests/test_live_smoke.py::test_openrouter_chat SKIPPED (OPENROUTER_A...) [100%]
=========================== short test summary info ============================
SKIPPED [1] tests/test_live_smoke.py:36: OPENAI_API_KEY is not set
SKIPPED [1] tests/test_live_smoke.py:42: ANTHROPIC_API_KEY is not set
SKIPPED [1] tests/test_live_smoke.py:48: set RUN_LIVE_TESTS=1 to spend money on live tests
SKIPPED [1] tests/test_live_smoke.py:54: OPENROUTER_API_KEY is not set
============================== 4 skipped in 0.57s ==============================With keys and the opt-in, all four should pass. The sample below is illustrative: it follows a run of the OpenAI, Anthropic and OpenRouter tests against the local stand-in (all passed, the OpenRouter URL redirected to Ollama), with timings plausible for hosted models. The Gemini test is hosted-only (Gemini has no local stand-in, so it was not run) and its line is illustrative too.
============================= test session starts ==============================
collected 4 items
tests/test_live_smoke.py::test_openai_responses PASSED [ 25%]
tests/test_live_smoke.py::test_anthropic_messages PASSED [ 50%]
tests/test_live_smoke.py::test_gemini_generate_content PASSED [ 75%]
tests/test_live_smoke.py::test_openrouter_chat PASSED [100%]
============================== 4 passed in 5.37s ===============================The budget guard, shown for real with LIVE_CALL_BUDGET=2 against the local stand-in (the tests were pointed at it by environment variables; no hosted API was called, and the Gemini test is one of the two that fail before making any call):
============================= test session starts ==============================
collected 4 items
tests/test_live_smoke.py::test_openai_responses PASSED [ 25%]
tests/test_live_smoke.py::test_anthropic_messages PASSED [ 50%]
tests/test_live_smoke.py::test_gemini_generate_content FAILED [ 75%]
tests/test_live_smoke.py::test_openrouter_chat FAILED [100%]
=========================== short test summary info ============================
FAILED tests/test_live_smoke.py::test_gemini_generate_content - Failed: live-...
FAILED tests/test_live_smoke.py::test_openrouter_chat - Failed: live-call bud...
========================= 2 failed, 2 passed in 0.87s ==========================The first two tests spend the budget; the next two fail before making a call. A runaway loop is stopped by the guard, not by your credit limit.
7.9 Markers, selection and pytest.ini#
All the pieces above are tied together by two small files. pytest.ini registers the markers (and --strict-markers turns a misspelt marker into an error instead of a silently unselected test), turns on the network guard, and configures async tests:
# pytest.ini
[pytest]
testpaths = tests
pythonpath = .
markers =
stand_in: contract test that needs the local stand-in (Ollama) running
live: calls a real provider; skipped unless the provider's key is set
asyncio_mode = strict
asyncio_default_fixture_loop_scope = function
addopts = --strict-markers --disable-socket --allow-unix-socket
filterwarnings =
ignore:A test tried to use socket:UserWarningAnd tests/conftest.py holds what's shared: the cassette scrubbers and settings, the port_open helper, the rule that tests marked stand_in or live are exempt from the socket ban, and the live-call budget:
# tests/conftest.py
"""conftest.py: shared pytest setup. Nothing here constructs an SDK client at import time."""
from __future__ import annotations
import os
import socket
import pytest
from wire_log import redact_url
# A cassette is committed and read by strangers, so it is written by ALLOW-LIST: only the headers listed here are kept,
# in the request and in the response. A credential header nobody thought of, a Set-Cookie, an organization ID or a
# machine fingerprint (x-stainless-os, user-agent) is dropped because it is not on the list, not because someone remembered it.
KEEP_REQUEST_HEADERS = {"content-type", "accept", "anthropic-version"}
KEEP_RESPONSE_HEADERS = {"content-type", "x-request-id", "request-id", "x-generation-id", "retry-after", "retry-after-ms"}
KEEP_RESPONSE_PREFIXES = ("x-ratelimit-", "anthropic-ratelimit-")
def scrub_request(request): # type: ignore[no-untyped-def]
request.headers = {k: v for k, v in request.headers.items() if k.lower() in KEEP_REQUEST_HEADERS}
request.uri = redact_url(request.uri) # userinfo and query values (?key=...) never reach the file
return request
def scrub_response(response: dict) -> dict:
response["headers"] = {k: v for k, v in response["headers"].items()
if k.lower() in KEEP_RESPONSE_HEADERS or k.lower().startswith(KEEP_RESPONSE_PREFIXES)}
return response
@pytest.fixture(scope="module")
def vcr_config() -> dict:
"""Settings for pytest-recording / vcrpy (used by tests marked @pytest.mark.vcr)."""
return {
"before_record_request": scrub_request, # vcrpy also applies it to the request being matched
"before_record_response": scrub_response,
"match_on": ["method", "uri", "body"], # body too: if the prompt changes, the replay MISSES
"decode_compressed_response": True, # store readable text, not gzip bytes
}
def port_open(host: str, port: int) -> bool:
try:
with socket.create_connection((host, port), timeout=0.3):
return True
except OSError:
return False
def pytest_collection_modifyitems(items: list[pytest.Item]) -> None:
"""Tests that are MEANT to use the network get the exception to --disable-socket; nothing else does."""
for item in items:
if "stand_in" in item.keywords or "live" in item.keywords:
item.add_marker(pytest.mark.enable_socket)
class LiveBudget:
"""A hard cap on the number of live calls in one pytest run, so a loop can't turn into a bill."""
def __init__(self, limit: int) -> None:
self.limit, self.used = limit, 0
def spend(self) -> None:
self.used += 1
if self.used > self.limit:
pytest.fail(f"live-call budget of {self.limit} exceeded (set LIVE_CALL_BUDGET to change it)")
@pytest.fixture(scope="session")
def live_budget() -> LiveBudget:
return LiveBudget(int(os.environ.get("LIVE_CALL_BUDGET", "6")))How you select what runs:
| Command | Runs | When |
|---|---|---|
pytest |
Everything that can run; live tests skip without keys, contract tests skip without the stand-in | Local development |
pytest -m "not live and not stand_in" |
Unit, fake, mock, replay and snapshot tests: no network, no keys, no services | Every push in CI |
pytest -m stand_in |
Contract tests only | When Ollama is running |
RUN_LIVE_TESTS=1 pytest -m live -rs |
Live smoke tests (with the keys of the providers you want checked) | The scheduled job |
pytest --block-network tests/test_record_replay.py |
Replays only; fails if a cassette is missing | Verifying cassettes |
CI=1 pytest tests/test_snapshot.py |
The same tests, but a snapshot file that isn't committed fails instead of being created | Checking what CI will see |
The whole suite, with the stand-in running and no keys:
Output (illustrative: the counts, line numbers and timings were recalculated after the Gemini tests were removed and not re-run, so yours will differ):
................ssss.................................................... [ 37%]
........................................................................ [ 75%]
................................................ [100%]
=========================== short test summary info ============================
SKIPPED [1] tests/test_live_smoke.py:36: OPENAI_API_KEY is not set
SKIPPED [1] tests/test_live_smoke.py:42: ANTHROPIC_API_KEY is not set
SKIPPED [1] tests/test_live_smoke.py:48: set RUN_LIVE_TESTS=1 to spend money on live tests
SKIPPED [1] tests/test_live_smoke.py:54: OPENROUTER_API_KEY is not set
188 passed, 4 skipped in 3.34sAnd the CI selection (no network, no keys, no services):
Output (illustrative: the counts, line numbers and timings were recalculated after the Gemini tests were removed and not re-run, so yours will differ):
........................................................................ [ 39%]
........................................................................ [ 78%]
....................................... [100%]
183 passed, 9 deselected in 2.80sThe totals above come from the author's complete project, so yours will differ a little, depending on which of this lesson's test files you have saved (and on the 16 tests of test_redact.py from 4.5). Both runs finish in a few seconds. Nearly two hundred tests that cover five adapters, token arithmetic, retries, streaming, redaction, the cassettes' contents and the request payloads cost nothing and need nothing, which is what lets you run them on every save.
Part 8: Testing streaming#
Deep-dive
A streamed response is a sequence of small events over one long HTTP response, not a single JSON body (03.3 owns the format and the SDK helpers). That adds failure modes a non-streaming test never sees: an event split across two network packets, text that must be accumulated in order, usage that arrives only in the last event, an error that arrives after the 200 OK, and a consumer that must stop cleanly when the client disconnects.
8.1 Mock SSE bodies through the transport#
The approach is the same as 7.3: keep the real SDK, replace the network. The mock server returns 200 with content-type: text/event-stream and a body made of Server-Sent Events. sse_fixtures.py builds those bodies. It is a deliberately smaller copy of 03.3's mockkit.py; see 03.3, 4.2 for the larger one. Its event names and fields follow the providers' streaming documentation (03.3, Part 3 lists every provider's events), with made-up IDs and counts:
# tests/sse_fixtures.py
"""sse_fixtures.py: MOCK streaming bodies. Event names and fields follow the providers' streaming docs; ids are made up."""
import json
from collections.abc import Iterator
from typing import Any
import httpx2
def sse(events: list[tuple[str, dict[str, Any]]]) -> bytes:
return b"".join(f"event: {name}\ndata: {json.dumps(data)}\n\n".encode() for name, data in events)
def slices(body: bytes, size: int) -> Iterator[bytes]:
"""Deliver the body in tiny pieces: real networks split events (and even UTF-8 characters) anywhere."""
for i in range(0, len(body), size):
yield body[i:i + size]
def stream_response(body: bytes, chunk_size: int | None = None) -> httpx2.Response:
return httpx2.Response(200, headers={"content-type": "text/event-stream"},
content=slices(body, chunk_size) if chunk_size else body)
def openai_stream(deltas: list[str], *, input_tokens: int = 20, output_tokens: int = 5) -> bytes:
text = "".join(deltas)
base = {"id": "resp_s1", "object": "response", "model": "gpt-6-luna-2026-10-01", "output": [],
"status": "in_progress"}
msg = {"type": "message", "id": "msg_1", "role": "assistant", "status": "completed",
"content": [{"type": "output_text", "text": text, "annotations": []}]}
done = {**base, "status": "completed", "output": [msg],
"usage": {"input_tokens": input_tokens, "output_tokens": output_tokens, "total_tokens": input_tokens + output_tokens,
"input_tokens_details": {"cached_tokens": 0}, "output_tokens_details": {"reasoning_tokens": 0}}}
events: list[tuple[str, dict[str, Any]]] = [
("response.created", {"type": "response.created", "sequence_number": 0, "response": base}),
("response.output_item.added", {"type": "response.output_item.added", "sequence_number": 1, "output_index": 0,
"item": {**msg, "status": "in_progress", "content": []}}),
("response.content_part.added", {"type": "response.content_part.added", "sequence_number": 2, "output_index": 0,
"item_id": "msg_1", "content_index": 0,
"part": {"type": "output_text", "text": "", "annotations": []}})]
for i, d in enumerate(deltas):
events.append(("response.output_text.delta", {"type": "response.output_text.delta", "sequence_number": 3 + i,
"output_index": 0, "item_id": "msg_1", "content_index": 0,
"delta": d, "logprobs": []}))
n = 3 + len(deltas)
events += [
("response.output_text.done", {"type": "response.output_text.done", "sequence_number": n, "output_index": 0,
"item_id": "msg_1", "content_index": 0, "text": text, "logprobs": []}),
("response.content_part.done", {"type": "response.content_part.done", "sequence_number": n + 1, "output_index": 0,
"item_id": "msg_1", "content_index": 0, "part": msg["content"][0]}),
("response.output_item.done", {"type": "response.output_item.done", "sequence_number": n + 2, "output_index": 0, "item": msg}),
("response.completed", {"type": "response.completed", "sequence_number": n + 3, "response": done})]
return sse(events)
def anthropic_stream(deltas: list[str], *, error_after: int | None = None) -> bytes:
"""Anthropic's event order. error_after=N inserts an `error` event after N deltas (a mid-stream failure)."""
events: list[tuple[str, dict[str, Any]]] = [
("message_start", {"type": "message_start", "message": {
"id": "msg_s1", "type": "message", "role": "assistant", "content": [], "model": "claude-haiku-5-5-20261015",
"stop_reason": None, "stop_sequence": None, "usage": {"input_tokens": 20, "output_tokens": 1}}}),
("content_block_start", {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}),
("ping", {"type": "ping"})]
for i, d in enumerate(deltas):
if error_after is not None and i == error_after:
events.append(("error", {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}))
return sse(events)
events.append(("content_block_delta", {"type": "content_block_delta", "index": 0,
"delta": {"type": "text_delta", "text": d}}))
events += [("content_block_stop", {"type": "content_block_stop", "index": 0}),
("message_delta", {"type": "message_delta", "delta": {"stop_reason": "end_turn", "stop_sequence": None},
"usage": {"output_tokens": 5}}),
("message_stop", {"type": "message_stop"})]
return sse(events)Two details matter:
slices(body, size)yields the body in tiny pieces. A real network delivers an event in whatever fragments TCP chooses, including in the middle of a multi-byte UTF-8 character, and a parser that only works when each read is a whole event is broken.openai_stream(...)produces the complete event sequence the OpenAI Responses stream helper needs (response.created, the item and part events, oneresponse.output_text.deltaper piece,...doneevents and aresponse.completedcarrying the finalusage); the SDK'sstream()helper builds its finalResponsefrom the events as they arrive, so a fixture with events missing or out of order tends to fail loudly, which is a useful check on the fixture itself.
Next, the code under test. streamer.py streams a reply, collects the text deltas, times the first one, and returns the stats. The clock is a parameter, so a test can control time:
# streamer.py
"""streamer.py: stream a reply, collect the text, and time it. The clock is a parameter, so tests control time."""
from __future__ import annotations
import time
from collections.abc import AsyncIterator, Callable
from dataclasses import dataclass, field
import anthropic
import openai
from anthropic import AsyncAnthropic
from openai import OpenAI
from openai.types.responses import Response
from chat_types import Message
@dataclass
class StreamStats:
text: str = ""
chunks: int = 0
ttft_ms: int | None = None # time to first text delta (None = no text ever arrived)
total_ms: int | None = None
deltas: list[str] = field(default_factory=list)
class StreamTimer:
"""Feed it every text delta. It never reads the real clock unless you let it."""
def __init__(self, clock: Callable[[], float] = time.perf_counter) -> None:
self.clock, self.started, self.stats = clock, clock(), StreamStats()
def on_delta(self, text: str) -> None:
if self.stats.ttft_ms is None:
self.stats.ttft_ms = round((self.clock() - self.started) * 1000)
self.stats.chunks += 1
self.stats.deltas.append(text)
def finish(self) -> StreamStats:
self.stats.total_ms = round((self.clock() - self.started) * 1000)
self.stats.text = "".join(self.stats.deltas)
return self.stats
def stream_openai(client: OpenAI, model: str, prompt: str, *, clock: Callable[[], float] = time.perf_counter
) -> tuple[StreamStats, Response]:
timer = StreamTimer(clock)
with client.responses.stream(model=model, input=prompt, max_output_tokens=100) as stream:
for event in stream:
if event.type == "response.output_text.delta":
timer.on_delta(event.delta)
final = stream.get_final_response() # the SDK's own accumulation: assert against this too
return timer.finish(), final
async def astream_anthropic(client: AsyncAnthropic, model: str, messages: list[Message],
*, clock: Callable[[], float] = time.perf_counter) -> StreamStats:
timer = StreamTimer(clock)
async with client.messages.stream(model=model, max_tokens=100,
messages=[{"role": "user", "content": m["content"]} for m in messages]) as stream:
async for text in stream.text_stream:
timer.on_delta(text)
return timer.finish()
class StreamInterrupted(Exception):
"""A stream failed part-way. `stats` holds what had arrived, so the caller can log it and decide what to show."""
def __init__(self, stats: StreamStats) -> None:
super().__init__(f"stream interrupted after {stats.chunks} chunks")
self.stats = stats
async def consume(deltas: AsyncIterator[str], timer: StreamTimer) -> StreamStats:
"""Drain any async source of text deltas. It knows nothing about SDKs, so a test can feed it a fake."""
try:
async for delta in deltas:
timer.on_delta(delta)
except Exception as exc: # CancelledError is a BaseException: it passes through untouched
raise StreamInterrupted(timer.finish()) from exc
return timer.finish()8.2 What to assert#
# tests/test_streaming.py
"""Testing streams: mock SSE bodies through the real SDK's transport, awkward chunk boundaries, a mid-stream error,
an async stream, and the timer with a fake clock. No network, no sleeping."""
from __future__ import annotations
import asyncio
from collections.abc import AsyncIterator
import anthropic
import httpx2
import openai
import pytest
from sse_fixtures import anthropic_stream, openai_stream, stream_response
from streamer import StreamInterrupted, StreamTimer, astream_anthropic, consume, stream_openai
DELTAS = ["Hel", "lo ", "wörld", "!"] # 'ö' is two bytes: a boundary can fall inside it
def openai_client(body: bytes, chunk_size: int | None = None) -> openai.OpenAI:
transport = httpx2.MockTransport(lambda request: stream_response(body, chunk_size))
return openai.OpenAI(api_key="sk-test", max_retries=0, http_client=httpx2.Client(transport=transport))
def test_openai_stream_text_and_final_response_agree() -> None:
stats, final = stream_openai(openai_client(openai_stream(DELTAS)), "gpt-6-luna", "Say hello")
assert stats.text == "Hello wörld!" == final.output_text # our accumulation == the SDK's
assert stats.chunks == 4
assert final.status == "completed" and final.usage and final.usage.output_tokens == 5
@pytest.mark.parametrize("chunk_size", [1, 2, 3, 7, 64])
def test_same_result_whatever_the_network_chunking(chunk_size: int) -> None:
stats, final = stream_openai(openai_client(openai_stream(DELTAS), chunk_size), "gpt-6-luna", "Say hello")
assert stats.text == "Hello wörld!" and final.status == "completed"
def test_timer_with_a_fake_clock_is_exact() -> None:
ticks = iter([0.0, 0.250, 0.900]) # the timer reads the clock at start, at the FIRST delta, at finish
timer = StreamTimer(clock=lambda: next(ticks))
timer.on_delta("a")
timer.on_delta("b")
stats = timer.finish()
assert (stats.ttft_ms, stats.total_ms, stats.text) == (250, 900, "ab")
def test_a_stream_that_never_produces_text_has_no_ttft() -> None:
timer = StreamTimer(clock=lambda: 1.0)
assert timer.finish().ttft_ms is None # None, not 0: "no first token" is not "instant"
def anthropic_async_client(body: bytes) -> anthropic.AsyncAnthropic:
transport = httpx2.MockTransport(lambda request: stream_response(body))
return anthropic.AsyncAnthropic(api_key="sk-ant-test", max_retries=0, http_client=httpx2.AsyncClient(transport=transport))
@pytest.mark.asyncio
async def test_async_anthropic_stream_collects_text() -> None:
stats = await astream_anthropic(anthropic_async_client(anthropic_stream(DELTAS)), "claude-haiku-5-5",
[{"role": "user", "content": "Say hello"}])
assert stats.text == "Hello wörld!" and stats.chunks == 4 # the ping event produced no text
@pytest.mark.asyncio
async def test_mid_stream_error_raises_and_keeps_what_arrived() -> None:
client = anthropic_async_client(anthropic_stream(DELTAS, error_after=2))
timer_text: list[str] = []
with pytest.raises(anthropic.APIStatusError) as info:
async with client.messages.stream(model="claude-haiku-5-5", max_tokens=50,
messages=[{"role": "user", "content": "Say hello"}]) as stream:
async for text in stream.text_stream:
timer_text.append(text)
assert "".join(timer_text) == "Hello " # two deltas arrived before the error
assert info.value.status_code == 200 # the HTTP status was 200: errors came later
assert not isinstance(info.value, anthropic.OverloadedError) # SDK 2.4.0 quirk, see lesson 03.3
# --- a fake async iterator: no SDK, no HTTP, no real time --------------------------------------------------
async def fake_deltas(*items: str | Exception) -> AsyncIterator[str]:
for item in items:
await asyncio.sleep(0) # yield to the event loop, like a real stream
if isinstance(item, Exception):
raise item
yield item
@pytest.mark.asyncio
async def test_consume_collects_text_from_any_async_source() -> None:
ticks = iter([0.0, 0.2, 0.5])
stats = await consume(fake_deltas("a", "b", "c"), StreamTimer(clock=lambda: next(ticks)))
assert (stats.text, stats.chunks, stats.ttft_ms, stats.total_ms) == ("abc", 3, 200, 500)
@pytest.mark.asyncio
async def test_a_failure_part_way_keeps_the_partial_result() -> None:
with pytest.raises(StreamInterrupted) as info:
await consume(fake_deltas("Hel", "lo", ConnectionResetError("peer reset")), StreamTimer())
assert info.value.stats.text == "Hello" and isinstance(info.value.__cause__, ConnectionResetError)
@pytest.mark.asyncio
async def test_cancellation_is_not_swallowed() -> None:
async def forever() -> AsyncIterator[str]:
while True:
await asyncio.sleep(3600)
yield "never"
task = asyncio.create_task(consume(forever(), StreamTimer()))
await asyncio.sleep(0)
task.cancel()
with pytest.raises(asyncio.CancelledError): # not wrapped in StreamInterrupted
await task
@pytest.mark.asyncio
async def test_an_empty_stream_is_not_an_error_but_has_no_ttft() -> None:
stats = await consume(fake_deltas(), StreamTimer())
assert stats.text == "" and stats.ttft_ms is None============================= test session starts ==============================
collected 14 items
tests/test_streaming.py::test_openai_stream_text_and_final_response_agree PASSED [ 7%]
tests/test_streaming.py::test_same_result_whatever_the_network_chunking[1] PASSED [ 14%]
tests/test_streaming.py::test_same_result_whatever_the_network_chunking[2] PASSED [ 21%]
tests/test_streaming.py::test_same_result_whatever_the_network_chunking[3] PASSED [ 28%]
tests/test_streaming.py::test_same_result_whatever_the_network_chunking[7] PASSED [ 35%]
tests/test_streaming.py::test_same_result_whatever_the_network_chunking[64] PASSED [ 42%]
tests/test_streaming.py::test_timer_with_a_fake_clock_is_exact PASSED [ 50%]
tests/test_streaming.py::test_a_stream_that_never_produces_text_has_no_ttft PASSED [ 57%]
tests/test_streaming.py::test_async_anthropic_stream_collects_text PASSED [ 64%]
tests/test_streaming.py::test_mid_stream_error_raises_and_keeps_what_arrived PASSED [ 71%]
tests/test_streaming.py::test_consume_collects_text_from_any_async_source PASSED [ 78%]
tests/test_streaming.py::test_a_failure_part_way_keeps_the_partial_result PASSED [ 85%]
tests/test_streaming.py::test_cancellation_is_not_swallowed PASSED [ 92%]
tests/test_streaming.py::test_an_empty_stream_is_not_an_error_but_has_no_ttft PASSED [100%]
============================== 14 passed in 0.79s ==============================The groups, and the bug each one stands for:
| Test | Catches |
|---|---|
test_openai_stream_text_and_final_response_agree |
Your accumulation differing from the SDK's. It compares your joined deltas with stream.get_final_response().output_text, and checks the final status and usage. If you ever write your own accumulator (03.3, Part 5), always test it against the SDK's |
test_same_result_whatever_the_network_chunking[1, 2, 3, 7, 64] |
Parsers that assume one read equals one event, and UTF-8 characters cut in half ("wörld" has a two-byte ö; chunk sizes 1 and 3 split it). The same text must come out |
test_timer_with_a_fake_clock_is_exact |
Time-to-first-token arithmetic. Three clock readings (start, first delta, end) give exactly 250 and 900 ms |
test_a_stream_that_never_produces_text_has_no_ttft |
None is not 0: "no first token" is not "instant" |
test_async_anthropic_stream_collects_text |
The async path of an SDK; the ping event the server sends produces no text |
test_mid_stream_error_raises_and_keeps_what_arrived |
An error after the 200. Anthropic's error event arrives when two deltas have been delivered; the SDK raises anthropic.APIStatusError, the code that was iterating has "Hello " in hand, and the status code on the exception is 200, not 529 |
test_consume_* (fake async iterator) |
The consumer logic with no SDK at all: collecting, partial results after a failure, cancellation passing through, and an empty stream |
Three of these deserve a closer look.
The mid-stream error test documents an SDK quirk. Anthropic's streaming docs say an overloaded_error can arrive as an event after the 200 (03.3, Part 7). With anthropic 2.4.0 it raises a generic APIStatusError with status_code=200, not OverloadedError, so except anthropic.OverloadedError won't catch a streamed overload, and a retry policy that looks at the status code sees "200". The test pins that behaviour: if a future SDK version fixes it, this test fails, and you learn about the change from CI rather than from an incident.
consume() is the technique for testing streaming consumers. Most streaming code in an application isn't the SDK call; it's what you do with the deltas (forward them to a browser, update a UI, write a log). Write that code against AsyncIterator[str], and a test can hand it an async def generator that yields scripted pieces and raises on cue. test_cancellation_is_not_swallowed checks the rule that matters most in async code: except Exception must not catch asyncio.CancelledError (it is a BaseException), or a disconnected client leaves your task running and your tokens billing (03.3, 8.5).
The partial result is preserved. StreamInterrupted carries stats, so a failed stream still produces a log record with chunks, partial text length and the TTFT, while its usage stays unknown. 4.9 builds that record for real (logged_stream) and tests it with these same fixtures (03.3, 7.6 explains the usage rule).
8.3 More to test, and how#
- A streaming HTTP endpoint. If your service re-streams to a browser with FastAPI, drive it with
TestClient(app).stream(...)and a fakeAsyncIteratorupstream, and test that disconnecting stops the upstream. Lesson 03.3, 11.6 does it end to end. - Other providers' streams. Build fixtures for the event sequences in 03.3 (OpenAI Chat Completions chunks ending in
[DONE], Gemini's chunks, OpenRouter's keep-alive comments). The cheapest way to get authentic bodies is to record a real stream once withvcrpy(7.5; streaming responses record and replay) and keep the cassette. - Tool-call fragments. Streamed tool arguments arrive as JSON fragments that must be concatenated before parsing; the local stand-in sends them as one piece, so only a mock exercises the accumulation (03.3, 6.2).
- Async fan-out. If you stream several requests concurrently, test the concurrency limit with fake async iterators and a counter of how many are active at once; the patterns are in 03.9.
- Timing without sleeping. Use a fake clock for TTFT and gaps; use
asyncio.sleep(0)to yield; and when you really need a stall (to test a read timeout), injecthttpx2.ReadTimeoutfrom the handler instead of waiting for one (Part 9). - SDKs don't retry a stream that has started (03.3, 7.4), so a test for "what happens when the stream breaks at chunk 7" is a test of your restart logic, and the mock transport is how you cause it on demand.
Part 9: Testing retries and timeouts without waiting#
Deep-dive
Retries and timeouts are where LLM code is most likely to be wrong and most expensive to test naively: a real retry sleeps for seconds, a real timeout takes minutes (the SDKs default to ten minutes, 03.8, Part 6), and a real 429 is a thing you can't make a provider produce on demand. The solution is the pattern of Part 7: a mock transport produces the failure instantly, and the waiting is replaced, shortened or measured instead of endured.
Lesson 03.8 owns what the right retry policy is. This part is about proving that your code implements it.
9.1 Three rules#
- Set
max_retriesexplicitly in every test client. The default is2foropenaiandanthropic. A test that triggers an error path with the default retries makes three requests and sleeps in between, so it is slow, and it may "pass" for the wrong reason. Use0when you're testing what happens on the first failure, and a specific number when you're testing the retry itself. - Assert on counts and headers, not on elapsed time. The number of requests the mock saw, and the
x-stainless-retry-countheader on each, say exactly what happened. A test that assertselapsed < 2sis a flaky test on a loaded CI machine. - Never really sleep. Replace the sleep, or make the server ask for a tiny wait (the fixtures use
retry-after-ms: 5), or both.
9.2 SDK retries#
# tests/test_retries.py
"""Retries and timeouts WITHOUT waiting: count attempts, read the retry-count header, and replace the sleep."""
from __future__ import annotations
import httpx2
import openai
import pytest
from tenacity import Retrying, retry_if_exception_type, stop_after_attempt, wait_exponential
from fixtures import SCENARIOS
from mocks import Script, openai_client
OK = SCENARIOS["openai_responses"]["ok"]
RATE = SCENARIOS["openai_responses"]["rate_limited"] # carries retry-after-ms: 5, so the SDK waits 5 ms
def call(client: openai.OpenAI) -> None:
client.responses.create(model="gpt-6-luna", input="hi")
def test_sdk_retries_twice_by_default_and_each_attempt_says_which_it_is() -> None:
script = Script(RATE, RATE, OK)
call(openai_client(script, max_retries=2))
assert [s.headers["x-stainless-retry-count"] for s in script.seen] == ["0", "1", "2"]
def test_gives_up_after_max_retries_plus_one_attempts() -> None:
script = Script(RATE, RATE, RATE)
with pytest.raises(openai.RateLimitError):
call(openai_client(script, max_retries=2))
assert len(script.seen) == 3
def test_a_400_is_never_retried() -> None:
bad = (400, {"error": {"message": "bad request", "type": "invalid_request_error"}}, {})
script = Script(bad, OK) # the OK reply must stay unused
with pytest.raises(openai.BadRequestError):
call(openai_client(script, max_retries=2))
assert len(script.seen) == 1 and len(script.replies) == 1
def test_backoff_delays_without_sleeping(monkeypatch: pytest.MonkeyPatch) -> None:
slept: list[float] = []
monkeypatch.setattr("time.sleep", slept.append) # the openai SDK calls time.sleep between attempts
no_hint = (429, {"error": {"message": "slow down", "type": "rate_limit_error"}}, {}) # no retry-after header
script = Script(no_hint, no_hint, OK)
call(openai_client(script, max_retries=2)) # would take about 1.5 s with a real sleep
assert len(slept) == 2 and all(0 < d <= 8 for d in slept) # exponential with jitter, capped (see lesson 03.8)
def test_a_huge_retry_after_makes_the_openai_sdk_give_up_instead_of_waiting(monkeypatch: pytest.MonkeyPatch) -> None:
slept: list[float] = []
monkeypatch.setattr("time.sleep", slept.append)
hour = (429, RATE[1], {"retry-after": "3600"})
script = Script(hour, OK)
with pytest.raises(openai.RateLimitError):
call(openai_client(script, max_retries=2))
assert len(script.seen) == 1 and slept == [] # no retry, no sleep
def test_a_timeout_is_an_exception_class_you_can_test(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr("time.sleep", lambda seconds: None)
def too_slow(request: httpx2.Request) -> httpx2.Response:
raise httpx2.ReadTimeout("simulated: no bytes within the read timeout", request=request)
client = openai.OpenAI(api_key="sk-test", max_retries=1, http_client=httpx2.Client(transport=httpx2.MockTransport(too_slow)))
with pytest.raises(openai.APITimeoutError): # a simulated timeout: no real 10-minute wait
client.responses.create(model="gpt-6-luna", input="hi")
@pytest.mark.parametrize("error, expected", [
(httpx2.ConnectTimeout, openai.APITimeoutError), (httpx2.ReadTimeout, openai.APITimeoutError),
(httpx2.WriteTimeout, openai.APITimeoutError), (httpx2.PoolTimeout, openai.APITimeoutError),
(httpx2.ConnectError, openai.APIConnectionError), (httpx2.RemoteProtocolError, openai.APIConnectionError),
])
def test_which_transport_failure_becomes_which_sdk_exception(error: type[httpx2.TransportError], expected: type[Exception],
monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr("time.sleep", lambda seconds: None)
def fail(request: httpx2.Request) -> httpx2.Response:
raise error("simulated", request=request)
client = openai.OpenAI(api_key="sk-test", max_retries=0, http_client=httpx2.Client(transport=httpx2.MockTransport(fail)))
with pytest.raises(expected) as info:
client.responses.create(model="gpt-6-luna", input="hi")
assert type(info.value) is expected # timeouts are a SUBCLASS of connection errors: check the exact type
def test_the_timeout_in_force_is_visible_in_the_request_header() -> None:
script = Script(OK)
client = openai.OpenAI(api_key="sk-test", timeout=30, http_client=httpx2.Client(transport=httpx2.MockTransport(script.handler(httpx2))))
call(client)
assert script.seen[0].headers["x-stainless-read-timeout"] == "30" # a configuration test, with no waiting
def test_your_own_tenacity_policy_with_an_injected_sleep() -> None:
script = Script(RATE, RATE, OK)
client = openai_client(script, max_retries=0) # the SDK must not retry: ONE layer owns retries
slept: list[float] = []
for attempt in Retrying(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=1, max=30),
retry=retry_if_exception_type(openai.RateLimitError), sleep=slept.append, reraise=True):
with attempt:
call(client)
assert slept == [1, 2] and len(script.seen) == 3 # waited 1 s then 2 s ... in zero real seconds============================= test session starts ==============================
collected 14 items
tests/test_retries.py::test_sdk_retries_twice_by_default_and_each_attempt_says_which_it_is PASSED [ 7%]
tests/test_retries.py::test_gives_up_after_max_retries_plus_one_attempts PASSED [ 14%]
tests/test_retries.py::test_a_400_is_never_retried PASSED [ 21%]
tests/test_retries.py::test_backoff_delays_without_sleeping PASSED [ 28%]
tests/test_retries.py::test_a_huge_retry_after_makes_the_openai_sdk_give_up_instead_of_waiting PASSED [ 35%]
tests/test_retries.py::test_a_timeout_is_an_exception_class_you_can_test PASSED [ 42%]
tests/test_retries.py::test_which_transport_failure_becomes_which_sdk_exception[ConnectTimeout-APITimeoutError] PASSED [ 50%]
tests/test_retries.py::test_which_transport_failure_becomes_which_sdk_exception[ReadTimeout-APITimeoutError] PASSED [ 57%]
tests/test_retries.py::test_which_transport_failure_becomes_which_sdk_exception[WriteTimeout-APITimeoutError] PASSED [ 64%]
tests/test_retries.py::test_which_transport_failure_becomes_which_sdk_exception[PoolTimeout-APITimeoutError] PASSED [ 71%]
tests/test_retries.py::test_which_transport_failure_becomes_which_sdk_exception[ConnectError-APIConnectionError] PASSED [ 78%]
tests/test_retries.py::test_which_transport_failure_becomes_which_sdk_exception[RemoteProtocolError-APIConnectionError] PASSED [ 85%]
tests/test_retries.py::test_the_timeout_in_force_is_visible_in_the_request_header PASSED [ 92%]
tests/test_retries.py::test_your_own_tenacity_policy_with_an_injected_sleep PASSED [100%]
============================== 14 passed in 0.66s ==============================What each test pins down:
| Test | What it proves | Why it matters |
|---|---|---|
test_sdk_retries_twice_by_default_... |
Two 429s then a 200 takes three requests, labelled 0, 1, 2 by x-stainless-retry-count |
The retry count header is the cleanest way to verify "it retried N times" |
test_gives_up_after_max_retries_plus_one_attempts |
max_retries=2 means three attempts in total, then the real RateLimitError |
Off-by-one errors in "retries" vs "attempts" are everywhere |
test_a_400_is_never_retried |
A bad request is tried once, and the second scripted reply stays unused | Proves that fixing the request, not retrying, is the only cure |
test_backoff_delays_without_sleeping |
With no retry-after hint, the SDK sleeps twice, each time a positive amount no larger than 8 seconds, and the test took milliseconds |
The SDK's backoff checked without its real delay. monkeypatch.setattr("time.sleep", slept.append) records what the SDK would have slept |
test_a_huge_retry_after_makes_the_openai_sdk_give_up... |
A retry-after: 3600 makes openai stop after one attempt, with no sleep |
The behaviour 03.8, 5.1 describes (it refuses waits over 120 seconds), now guarded by a test: if a future SDK changes it, you learn from CI |
test_a_timeout_is_an_exception_class_you_can_test |
A simulated ReadTimeout becomes openai.APITimeoutError, after the one retry |
A ten-minute timeout, tested in milliseconds |
test_which_transport_failure_becomes_which_sdk_exception |
Four timeout types map to APITimeoutError; connection and protocol errors map to APIConnectionError |
The exception hierarchy trap from 03.8: a timeout is a subclass of a connection error, so except APIConnectionError catches both. The test compares the exact type |
test_the_timeout_in_force_is_visible_in_the_request_header |
OpenAI(timeout=30) sends x-stainless-read-timeout: 30 |
A configuration test without any waiting: it proves a timeout you set is the timeout that's applied |
test_your_own_tenacity_policy_with_an_injected_sleep |
A tenacity policy sleeps [1, 2] seconds between three attempts, in zero real seconds |
tenacity accepts a sleep= function precisely for tests. Note max_retries=0 on the SDK client: exactly one layer owns retries (03.8, 5.5) |
real_sleep = asyncio.sleep # keep a reference before patching
async def fake_sleep(seconds: float) -> None:
slept.append(seconds)
await real_sleep(0) # a bare "return" starves the loop: some code uses sleep(0) as a yield point
monkeypatch.setattr("anyio.sleep", fake_sleep)(In a check with the versions named in Setup, with that replacement an AsyncOpenAI call that got a 429 then a 200 recorded one sleep of about 0.44 seconds and finished in 0.05 seconds. A version of fake_sleep without the await hung.) The retry-after-ms hint approach needs no patching at all and works in both worlds, which is why the fixtures use it.
9.3 Timeouts and google-genai#
Everything above used openai, and the same patterns apply to anthropic (httpx2 transports, x-stainless-* headers). google-genai differs in ways 03.8 documents, and each is a test you can add:
client.models.*makes one attempt unlessHttpRetryOptionsis set;attempts=Nmeans N total attempts there, but N retries for Interactions (03.8, 5.2). The mock-transport suite of 7.3 usesHttpRetryOptions(attempts=2, initial_delay=0.001, jitter=0)to make a429retry in microseconds.- Its
timeoutis in milliseconds (HttpOptions(timeout=30)is 30 ms). A test that builds your client and checks the effective timeout catches the classic "I set 30 and everything fails" bug (03.8, 6.1). - Its
models.*calls have no default timeout, so a stuck call hangs forever; a test with a handler that raiseshttpx.ReadTimeoutshows what your wrapper does about it.
9.4 Time as a dependency: testing the logger with a fake clock#
Production code that measures time should receive the clock. LoggedChat takes clock, LogConfig takes rng, and the result is that a test can assert exact numbers instead of "greater than zero". The logger from Part 4 runs on every call, so a bug in it is a bug everywhere, and it deserves a real suite. The three tests worth copying are in one short file: the schema test (a refactor that drops a field fails here instead of silently emptying a dashboard), the exception test (it puts a fake key in the exception message and asserts it appears nowhere in the log line, pinning the rule of 4.1: log the class and status, never the free text) and the hash-key test (no default outside dev, and the key never appears in a repr):
# tests/test_llm_log.py
"""Testing the logger itself: it runs on every call, so a bug here is a bug everywhere. Fake clock, fake model.
This file holds the three tests worth copying; the rest (sampling, content flag, price failures, ...) are in
test_llm_log_rules.py and are summarized in a table in the lesson."""
import json
import logging
import pytest
from fakes import FakeChat, ok
from llm_log import JsonFormatter, LoggedChat, LogConfig
# The schema: a refactor that drops a field fails here, instead of silently emptying a dashboard.
REQUIRED = {"ts", "level", "event", "trace_id", "env", "feature", "provider", "api", "model_requested", "sdk",
"prompt_version", "user", "max_tokens", "input_chars", "prompt_sha256", "latency_ms", "ttft_ms", "attempts",
"outcome", "finish_reason", "request_id", "model_resolved", "uncached_input_tokens", "cached_input_tokens",
"cache_write_tokens", "total_input_tokens", "output_tokens", "reasoning_tokens", "cost_usd"}
MESSAGES = [{"role": "user", "content": "Mail jane@example.com about the double charge"}]
def make(inner: FakeChat, **kw) -> LoggedChat: # type: ignore[no-untyped-def]
return LoggedChat(inner, provider="openai", api="responses", model="gpt-6-luna", feature="triage",
sdk_package="openai", **kw)
def lines(caplog: pytest.LogCaptureFixture) -> list[dict]:
"""Render the captured records the way the real handler would, and parse them back."""
return [json.loads(JsonFormatter().format(r)) for r in caplog.records if r.name == "llm.calls" and r.getMessage() == "llm_call"]
@pytest.fixture(autouse=True)
def capture(caplog: pytest.LogCaptureFixture) -> None:
caplog.set_level(logging.INFO, logger="llm.calls")
def test_one_line_per_call_with_every_expected_field(caplog) -> None: # type: ignore[no-untyped-def]
make(FakeChat(ok("fine"))).complete("Be brief.", MESSAGES, max_tokens=50) # type: ignore[arg-type]
(line,) = lines(caplog)
assert REQUIRED <= line.keys(), f"missing: {sorted(REQUIRED - line.keys())}"
def test_an_exception_is_logged_once_and_then_raised(caplog) -> None: # type: ignore[no-untyped-def]
with pytest.raises(TimeoutError):
make(FakeChat(TimeoutError("sk-test-should-never-be-logged"))).complete("s", MESSAGES, max_tokens=5) # type: ignore[arg-type]
(line,) = lines(caplog)
assert line["level"] == "ERROR" and line["error_class"] == "TimeoutError" and "sk-test" not in json.dumps(line)
def test_the_hash_key_has_no_default_outside_dev(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.delenv("USER_ID_PEPPER", raising=False)
with pytest.raises(ValueError, match="needs a secret hash key"):
LogConfig(env="prod") # forgetting the key stops the service: it can't weaken the hash
monkeypatch.setenv("USER_ID_PEPPER", "from-the-secret-store")
assert LogConfig(env="prod").key == b"from-the-secret-store"
assert "from-the-secret-store" not in repr(LogConfig(env="prod")) # and it never shows up in a repr or a log============================= test session starts ==============================
collected 3 items
tests/test_llm_log.py::test_one_line_per_call_with_every_expected_field PASSED [ 33%]
tests/test_llm_log.py::test_an_exception_is_logged_once_and_then_raised PASSED [ 66%]
tests/test_llm_log.py::test_the_hash_key_has_no_default_outside_dev PASSED [100%]
============================== 3 passed in 0.60s ===============================The remaining rules are one short test each, in a second file; their names in the output below say what they pin down, and they use the same tiny helpers (make, lines) and the scripted FakeChat of 7.2. Writing the rest from this list is exercise 20:
============================= test session starts ==============================
collected 10 items
tests/test_llm_log_rules.py::test_latency_comes_from_the_injected_clock PASSED [ 10%]
tests/test_llm_log_rules.py::test_content_is_not_logged_by_default PASSED [ 20%]
tests/test_llm_log_rules.py::test_content_flag_logs_redacted_text PASSED [ 30%]
tests/test_llm_log_rules.py::test_sampling_is_deterministic_with_an_injected_rng[0.005-True] PASSED [ 40%]
tests/test_llm_log_rules.py::test_sampling_is_deterministic_with_an_injected_rng[0.5-False] PASSED [ 50%]
tests/test_llm_log_rules.py::test_the_model_receives_a_hash_not_the_raw_user_id PASSED [ 60%]
tests/test_llm_log_rules.py::test_a_failing_price_function_never_breaks_the_call PASSED [ 70%]
tests/test_llm_log_rules.py::test_unknown_usage_is_null_not_zero PASSED [ 80%]
tests/test_llm_log_rules.py::test_the_trace_id_does_not_leak_into_the_next_request PASSED [ 90%]
tests/test_llm_log_rules.py::test_the_log_line_carries_the_convention_and_prices_the_same_either_way PASSED [100%]
============================== 10 passed in 0.58s ==============================Two of them tie this part to the rest of the lesson. test_the_log_line_carries_the_convention_and_prices_the_same_either_way builds a cache-heavy Completion (30 uncached, 60 cached and 10 written input tokens, 40 output tokens), logs it with price_with(...) and checks the cost against hand arithmetic over the fake table (30 × $1 + 60 × $0.10 + 10 × $1.25 + 40 × $5 per million), then turns the logged line back into a cost_calc.Usage with usage_from_record and checks that it prices identically. And test_unknown_usage_is_null_not_zero checks that a Completion with no usage logs null for every token field, never 0.
9.5 What a fast retry test cannot tell you#
A mock proves your code reacts correctly to a 429 that arrives with a retry-after-ms header. It can't prove that the real provider sends that header, or sends retry-after in seconds, or an HTTP date, or that the rate-limit body has the shape you expect. Those are facts about the provider; they come from the documentation, from captured real responses (record/replay), and from the shapes that 03.8's mock-server samples copied from each provider's docs. Treat fixtures for error responses as documentation you can run, and update them when the docs or your captures change.
Part 10: Testing structured output and tool calls#
Deep-dive
Two kinds of model output are meant for code rather than for people: JSON that must match a schema (03.4) and tool calls whose arguments you will act on (03.5). They fail in more ways than prose does, and the failures are the kind a real model produces rarely enough that you won't see them in manual tests. So build fixtures for them: a small, named collection of response bodies, one per way the output can go wrong.
10.1 The four fixtures every structured-output path needs#
| Fixture | What the provider returns | What your code must do |
|---|---|---|
| Valid | Text that parses and matches the schema | Return the object |
| Invalid | Text that is JSON but breaks the schema (a wrong type, an unknown value, a missing key), or isn't JSON at all | Raise a specific, handled error, or retry with the error message (03.4, Part 7) |
| Refused | A 200 with a refusal instead of content |
Not try to parse it; surface the refusal |
| Truncated | A 200 cut off by the output cap, so the JSON stops mid-way |
Not treat it as complete; raise the cap or fail clearly |
All of them go through the real SDK parse helper with a mock transport, so the test exercises the SDK's own behaviour, which differs by provider:
# tests/test_outputs.py
"""Structured output and tool calls: fixtures for the cases that break parsers (valid, invalid, refused, truncated),
run through the REAL SDK parse helpers, plus property-based tests with hypothesis."""
from __future__ import annotations
import json
from typing import Any
import openai
import pydantic
import pytest
from hypothesis import given, strategies as st
from openai.types.responses import ParsedResponse
from check_response import Status, check_response
from fixtures import SCENARIOS
from mocks import Script, openai_client
from toolargs import ToolArgumentError, parse_tool_args
from triage import FENCE, Triage, TriageParseError, parse_triage
from triage_strategies import ANY_SLOTS
class TriageModel(pydantic.BaseModel):
category: str
urgent: bool
def parse_with_sdk(reply: Any) -> ParsedResponse[TriageModel]:
client = openai_client(Script(reply))
return client.responses.parse(model="gpt-6-luna", input="hi", text_format=TriageModel)
def test_valid_output_is_parsed_into_the_model() -> None:
response = parse_with_sdk(SCENARIOS["openai_responses"]["ok"])
assert response.output_parsed == TriageModel(category="billing", urgent=False)
def test_output_that_breaks_the_schema_raises_validation_error() -> None:
status, body, headers = SCENARIOS["openai_responses"]["ok"]
body = json.loads(json.dumps(body))
body["output"][0]["content"][0]["text"] = '{"category": "billing", "urgent": "maybe"}'
with pytest.raises(pydantic.ValidationError):
parse_with_sdk((status, body, headers))
def test_refusal_has_no_parsed_object_and_is_detected() -> None:
parsed = parse_with_sdk(SCENARIOS["openai_responses"]["refused"])
assert parsed.output_parsed is None # nothing to parse: the model declined
assert check_response(parsed).status is Status.REFUSED # check_response (03.8, 10.2) accepts the ParsedResponse as is
def test_truncated_output_is_never_treated_as_complete() -> None:
reply = SCENARIOS["openai_responses"]["truncated"]
with pytest.raises(pydantic.ValidationError): # the cut-off JSON can't be parsed ...
parse_with_sdk(reply)
# ... but the same reply read as a plain response gets a name from check_response: the output cap was hit
plain = openai_client(Script(reply)).responses.create(model="gpt-6-luna", input="hi")
assert check_response(plain).status is Status.TRUNCATED
# --- tool calls: the arguments are a string the model wrote -------------------------------------------
@pytest.mark.parametrize("arguments, required, expected", [
('{"order_id": "A-1"}', {"order_id"}, {"order_id": "A-1"}),
("", set(), {}), # a tool with no parameters may send an empty string
])
def test_valid_tool_arguments(arguments: str, required: set[str], expected: dict[str, Any]) -> None:
assert parse_tool_args(arguments, required) == expected
@pytest.mark.parametrize("arguments", ['{"order_id": "A-1"', "[1, 2]", '{"id": 1}', "null"])
def test_bad_tool_arguments_are_rejected_before_anything_runs(arguments: str) -> None:
with pytest.raises(ToolArgumentError):
parse_tool_args(arguments, {"order_id"})
# --- property-based: whatever the model produces, the parser either succeeds or raises ITS error ------------------
@given(st.text())
def test_parse_triage_never_crashes_on_any_text(text: str) -> None:
try:
parse_triage(text)
except TriageParseError:
pass # the one failure the app knows how to handle
@given(ANY_SLOTS)
def test_parse_triage_never_crashes_on_valid_json_with_any_values(slots: dict) -> None:
"""The text generator above almost never makes valid JSON. This one always does, with ANY JSON value in each slot.
It found parse_triage's crash on {"category": []} (see s10_4_json_strategy_test.py)."""
try:
parse_triage(json.dumps(slots))
except TriageParseError:
pass
@pytest.mark.parametrize("text", ["[" * 100_000, '{"category":' * 5_000])
def test_parse_triage_survives_absurdly_nested_input(text: str) -> None:
with pytest.raises(TriageParseError): # json.loads raises RecursionError on this, not JSONDecodeError
parse_triage(text)
@given(st.sampled_from(["billing", "bug", "how_to", "other"]), st.booleans(), st.booleans(), st.text(" \n\t", max_size=3))
def test_every_valid_answer_round_trips_even_inside_a_code_fence(category: str, urgent: bool, fenced: bool, pad: str) -> None:
body = json.dumps({"category": category, "urgent": urgent})
text = f"{pad}{FENCE}json\n{body}\n{FENCE}{pad}" if fenced else f"{pad}{body}{pad}"
assert parse_triage(text) == Triage(category, urgent)
# --- Gemini: a truncated answer gives `parsed = None` instead of raising ------------------------------------
def test_gemini_parsed_is_none_when_the_answer_is_cut_off() -> None:
from google.genai import types
from mocks import gemini_client
config = types.GenerateContentConfig(response_mime_type="application/json", response_schema=TriageModel, max_output_tokens=5)
ok = gemini_client(Script(SCENARIOS["gemini"]["ok"])).models.generate_content(model="gemini-3.8-flash", contents="hi", config=config)
cut = gemini_client(Script(SCENARIOS["gemini"]["truncated"])).models.generate_content(model="gemini-3.8-flash", contents="hi", config=config)
assert ok.parsed == TriageModel(category="billing", urgent=False)
assert cut.parsed is None # silent! check finish_reason (or outcome) before using .parsed
# --- tool calls through the real SDK: the model's arguments are text, and may be cut off ---------------------
def function_call_reply(arguments: str) -> Any:
body = {"id": "resp_t", "object": "response", "status": "completed", "model": "gpt-6-luna-2026-10-01",
"output": [{"type": "function_call", "id": "fc_1", "call_id": "call_1", "name": "get_order",
"arguments": arguments, "status": "completed"}],
"usage": {"input_tokens": 30, "output_tokens": 9, "total_tokens": 39,
"input_tokens_details": {"cached_tokens": 0}, "output_tokens_details": {"reasoning_tokens": 0}}}
return (200, body, {"x-request-id": "req_tool"})
def test_a_cut_off_tool_call_is_caught_before_anything_runs() -> None:
response = openai_client(Script(function_call_reply('{"order_id": "A-1'))).responses.create(model="gpt-6-luna", input="hi")
call = next(item for item in response.output if item.type == "function_call")
assert isinstance(call.arguments, str) # the SDK hands you the STRING; parsing is your job
with pytest.raises(ToolArgumentError):
parse_tool_args(call.arguments, {"order_id"})
def test_a_complete_tool_call_passes_and_keeps_its_call_id() -> None:
response = openai_client(Script(function_call_reply('{"order_id": "A-1"}'))).responses.create(model="gpt-6-luna", input="hi")
call = next(item for item in response.output if item.type == "function_call")
assert parse_tool_args(call.arguments, {"order_id"}) == {"order_id": "A-1"} and call.call_id == "call_1"
# --- the schema you send is part of the request: snapshot it ------------------------------------------------
def test_the_json_schema_sent_to_the_provider_is_stable() -> None:
from snapshot import assert_matches_snapshot
assert_matches_snapshot("triage_model_json_schema", TriageModel.model_json_schema())============================= test session starts ==============================
collected 19 items
tests/test_outputs.py::test_valid_output_is_parsed_into_the_model PASSED [ 5%]
tests/test_outputs.py::test_output_that_breaks_the_schema_raises_validation_error PASSED [ 10%]
tests/test_outputs.py::test_refusal_has_no_parsed_object_and_is_detected PASSED [ 15%]
tests/test_outputs.py::test_truncated_output_is_never_treated_as_complete PASSED [ 21%]
tests/test_outputs.py::test_valid_tool_arguments[{"order_id": "A-1"}-required0-expected0] PASSED [ 26%]
tests/test_outputs.py::test_valid_tool_arguments[-required1-expected1] PASSED [ 31%]
tests/test_outputs.py::test_bad_tool_arguments_are_rejected_before_anything_runs[{"order_id": "A-1"] PASSED [ 36%]
tests/test_outputs.py::test_bad_tool_arguments_are_rejected_before_anything_runs[[1, 2]] PASSED [ 42%]
tests/test_outputs.py::test_bad_tool_arguments_are_rejected_before_anything_runs[{"id": 1}] PASSED [ 47%]
tests/test_outputs.py::test_bad_tool_arguments_are_rejected_before_anything_runs[null] PASSED [ 52%]
tests/test_outputs.py::test_parse_triage_never_crashes_on_any_text PASSED [ 57%]
tests/test_outputs.py::test_parse_triage_never_crashes_on_valid_json_with_any_values PASSED [ 63%]
tests/test_outputs.py::test_parse_triage_survives_absurdly_nested_input[text0] PASSED [ 68%]
tests/test_outputs.py::test_parse_triage_survives_absurdly_nested_input[text1] PASSED [ 73%]
tests/test_outputs.py::test_every_valid_answer_round_trips_even_inside_a_code_fence PASSED [ 78%]
tests/test_outputs.py::test_gemini_parsed_is_none_when_the_answer_is_cut_off PASSED [ 84%]
tests/test_outputs.py::test_a_cut_off_tool_call_is_caught_before_anything_runs PASSED [ 89%]
tests/test_outputs.py::test_a_complete_tool_call_passes_and_keeps_its_call_id PASSED [ 94%]
tests/test_outputs.py::test_the_json_schema_sent_to_the_provider_is_stable PASSED [100%]
============================== 19 passed in 1.25s ==============================What the tests establish (with openai 3.42.1, google-genai 2.34.0; run them again after an upgrade):
- Valid:
responses.parse(text_format=TriageModel)returns the Pydantic object inoutput_parsed. - Invalid: a schema violation raises
pydantic.ValidationErrorout of the SDK call. If your code doesn't expect that exception, a model that writes"urgent": "maybe"becomes an unhandled crash. - Refused:
output_parsedisNoneand the refusal is in the output items.check_response()(03.8, 10.2) takes theParsedResponsethatparse()returns as it is (it looks at the class's whole inheritance chain with theParsedandBetaprefixes removed, soParsedResponse,BetaMessageandParsedMessageall work) and names the refusalREFUSED. - Truncated: with OpenAI the cut-off JSON raises
ValidationErrorout ofparse()(so there is noParsedResponseto inspect; the test reads the same reply as a plain response, andcheck_responsenames the causeTRUNCATED); with Gemini,response.parsedis silentlyNone(the last test). A path that only checksif result.parsed:conflates "the model refused", "the answer was cut off" and "the schema didn't match". Check the finish reason oroutcomefirst. - Tool calls: the SDK gives you the arguments as a string the model wrote (
call.arguments).parse_tool_argsvalidates it (is it JSON, an object, with the required keys) before anything with side effects runs, and the cut-off argument string is caught there. Anthropic'stool_useblocks carryinputas an already-parsed dictionary, which can still be missing required keys; the validation applies either way (03.5, 7.1). - The JSON Schema you send is part of the request, and SDKs transform it (strict-mode rewrites,
additionalProperties,required). Snapshotmodel_json_schema()(the last test) so a change to a field's type or a rename shows up in review (03.4 explains how each provider treats the schema).
# toolargs.py
"""toolargs.py: models send tool-call arguments as a JSON STRING that may be invalid, partial or missing keys."""
import json
from typing import Any
class ToolArgumentError(ValueError):
pass
def parse_tool_args(arguments: str, required: set[str]) -> dict[str, Any]:
"""Pure: parse and check the arguments of one tool call before running anything with side effects."""
try:
data = json.loads(arguments or "{}")
except json.JSONDecodeError as exc:
raise ToolArgumentError(f"arguments are not valid JSON: {arguments[:40]!r}") from exc
if not isinstance(data, dict):
raise ToolArgumentError(f"arguments must be a JSON object, got {type(data).__name__}")
if missing := required - data.keys():
raise ToolArgumentError(f"missing required arguments: {sorted(missing)}")
return data10.2 Property-based tests with hypothesis (optional, and very good for parsers)#
A normal test checks examples you thought of. A property-based test states a rule that must hold for all inputs ("every valid answer round-trips, even inside a code fence"), and a library, hypothesis, generates hundreds of inputs, hunts for one that breaks the rule, and then shrinks it to the smallest failing case. Parsers of model output are ideal targets, because models produce inputs you didn't imagine.
Three properties are in test_outputs.py above: "parse_triage never crashes with anything but TriageParseError, for any text at all" (st.text() includes empty strings, control characters, emoji and enormous strings), the same property for valid JSON with arbitrary values in the slots (the second half of this section explains why that one matters), and "every valid answer round-trips with padding and an optional fence". To see the tool earn its keep, here is the "obviously fine" parser from half the blog posts, tested against the three fence styles models really use (a fence labelled json, a plain fence with no label, and no fence at all; the sample names them json, plain and none so the failing example is readable):
# s10_3_naive_parser_test.py
"""A property-based test finds a bug in a 'obviously fine' parser. Run with: pytest s10_3_naive_parser_test.py"""
import json
from hypothesis import given, strategies as st
from triage import FENCE, parse_triage
def naive_parse(text: str) -> dict:
"""Strips a code fence the way most blog posts do."""
body = text.strip().removeprefix(f"{FENCE}json").removesuffix(FENCE)
return json.loads(body)
OPENINGS = {"json": f"{FENCE}json\n", "plain": f"{FENCE}\n", "none": ""} # models use all three
FENCES = st.sampled_from(sorted(OPENINGS))
ANSWERS = st.fixed_dictionaries({"category": st.sampled_from(["billing", "bug", "how_to", "other"]),
"urgent": st.booleans()})
def wrap(answer: dict, style: str) -> str:
opening = OPENINGS[style]
return f"{opening}{json.dumps(answer)}{chr(10) + FENCE if opening else ''}"
@given(ANSWERS, FENCES)
def test_naive_parser_round_trips(answer: dict, fence: str) -> None:
assert naive_parse(wrap(answer, fence)) == answer
@given(ANSWERS, FENCES)
def test_our_parser_round_trips(answer: dict, fence: str) -> None:
parsed = parse_triage(wrap(answer, fence))
assert {"category": parsed.category, "urgent": parsed.urgent} == answerF. [100%]
=================================== FAILURES ===================================
________________________ test_naive_parser_round_trips _________________________
s10_3_naive_parser_test.py:27: in test_naive_parser_round_trips
def test_naive_parser_round_trips(answer: dict, fence: str) -> None:
s10_3_naive_parser_test.py:28: in test_naive_parser_round_trips
assert naive_parse(wrap(answer, fence)) == answer
s10_3_naive_parser_test.py:12: in naive_parse
return json.loads(body)
E json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
E Failing test case: test_naive_parser_round_trips(
E answer={'category': 'billing',
E 'urgent': False}, # or any other generated value
E fence='plain',
E )
=========================== short test summary info ============================
FAILED s10_3_naive_parser_test.py::test_naive_parser_round_trips - json.decod...
1 failed, 1 passed in 0.12shypothesis found the case in under a tenth of a second, shrank it to its simplest form (fence='plain', the unlabelled fence), and printed it as a ready-to-paste failing example. naive_parse only strips an opening fence labelled json, so a plain opening fence stays in the text and json.loads chokes. The second test, for parse_triage from triage.py, passed. Notice the discipline: the model never ran. The inputs are the model's habits, written down as a generator.
A property test is only as good as its generator. The "never crashes" property above passes for a naive parse_triage too, and the claim is still false. st.text() makes arbitrary strings, and an arbitrary string is almost never valid JSON, so every example was rejected by json.loads on the first line and the code after it (the check on the values) was never reached. The bug lived there: {"category": [], "urgent": true} is valid JSON, [] in CATEGORIES raises TypeError: unhashable type: 'list', and that is not a TriageParseError, so one odd model reply would have crashed the ticket flow, the exact thing the one-exception rule was meant to make impossible. The fix is a better generator, written down in triage_strategies.py: st.recursive builds any JSON value (null, booleans, numbers, strings, nested lists and objects), and ANY_SLOTS puts one in each slot of an answer-shaped object. Here is the naive version of the parser (kept in the sample as parse_triage_v1) and the current one under the same property:
# triage_strategies.py
"""triage_strategies.py: hypothesis strategies for model output that LOOKS like our JSON but holds any JSON in its slots."""
from hypothesis import strategies as st
# Any JSON value, nested up to a few levels: null, booleans, numbers, strings, lists and objects
JSON_VALUES = st.recursive(
st.none() | st.booleans() | st.integers() | st.floats(allow_nan=False, allow_infinity=False) | st.text(max_size=8),
lambda children: st.lists(children, max_size=3) | st.dictionaries(st.text(max_size=8), children, max_size=3),
max_leaves=12)
# {"category": <any JSON>, "urgent": <any JSON>}: valid JSON with the right keys and the wrong kind of value
ANY_SLOTS = st.fixed_dictionaries({"category": JSON_VALUES, "urgent": JSON_VALUES})# s10_4_json_strategy_test.py
"""The same property, with a generator that produces ARBITRARY JSON in the answer's slots. It finds a crash in the
naive parse_triage that the 'any text' generator never could, and shows the fixed one passes.
Run with: pytest s10_4_json_strategy_test.py --hypothesis-seed=0"""
import json
import re
from hypothesis import given
from triage import CATEGORIES, FENCE, Triage, TriageParseError, parse_triage
from triage_strategies import ANY_SLOTS
def parse_triage_v1(text: str) -> Triage:
"""A naive parse_triage: the membership test sits OUTSIDE the try block."""
body = re.sub(rf"^{FENCE}(?:json)?\s*|\s*{FENCE}$", "", text.strip())
try:
data = json.loads(body)
category, urgent = data["category"], data["urgent"]
except (json.JSONDecodeError, KeyError, TypeError) as exc:
raise TriageParseError("not the expected JSON") from exc
if category not in CATEGORIES or not isinstance(urgent, bool): # a list in `category` raises TypeError HERE
raise TriageParseError("unexpected values")
return Triage(category, urgent)
@given(ANY_SLOTS)
def test_v1_only_ever_raises_its_own_error(slots: dict) -> None:
try:
parse_triage_v1(json.dumps(slots))
except TriageParseError:
pass # any OTHER exception fails the test
@given(ANY_SLOTS)
def test_current_parse_triage_only_ever_raises_its_own_error(slots: dict) -> None:
try:
parse_triage(json.dumps(slots))
except TriageParseError:
passF. [100%]
=================================== FAILURES ===================================
____________________ test_v1_only_ever_raises_its_own_error ____________________
s10_4_json_strategy_test.py:27: in test_v1_only_ever_raises_its_own_error
def test_v1_only_ever_raises_its_own_error(slots: dict) -> None:
^^^
s10_4_json_strategy_test.py:29: in test_v1_only_ever_raises_its_own_error
parse_triage_v1(json.dumps(slots))
s10_4_json_strategy_test.py:21: in parse_triage_v1
if category not in CATEGORIES or not isinstance(urgent, bool): # a list in `category` raises TypeError HERE
^^^^^^^^^^^^^^^^^^^^^^^^^^
E TypeError: unhashable type: 'list'
E Failing test case: test_v1_only_ever_raises_its_own_error(
E slots={
E 'category': [],
E 'urgent': None, # or any other generated value
E },
E )
=========================== short test summary info ============================
FAILED s10_4_json_strategy_test.py::test_v1_only_ever_raises_its_own_error - ...
1 failed, 1 passed in 1.43shypothesis found {"category": [], "urgent": None} in a second and shrank it to the smallest example. The fixed parse_triage passes the same property: it now tests isinstance(category, str) before the membership test, and its except also catches RecursionError, because json.loads on absurdly nested input ("[" * 100000) raises that rather than JSONDecodeError (the last test in test_outputs.py pins it). Both properties and both regression cases ([] and {} in the category slot) now live in the permanent suite.
Use hypothesis sparingly: for parsers, converters, token-budget arithmetic and redaction, where "for all inputs" is meaningful. It isn't a way to test the model. (It also stores failing examples in a .hypothesis folder; add it to .gitignore.)
10.3 Testing validate-and-retry loops#
If your code validates a structured answer and retries with the error message (03.4, Part 7), test the loop with a FakeChat whose script is [invalid, valid] (expect one retry and the valid result), [invalid, invalid, invalid] (expect it to stop at your attempt cap and report failure, with the number of model calls equal to the cap) and [refused] (expect no retry at all: a refusal won't improve). The assertions that matter are on len(fake.calls): a loop that retries forever, or retries a refusal, is a bill, and the fake's "called more times than scripted" failure from 7.2 catches it.
Part 11: Static checks: catch typos before any request#
Deep-dive
The cheapest bug to find is one that never reaches a test, let alone a provider. openai, anthropic and google-genai all ship type hints (they include a py.typed marker): every method's parameters are typed, request dictionaries are TypedDicts with known keys, and google-genai's config objects are Pydantic models with known fields. A type checker (pyright or mypy) reads those hints and reports a misspelt parameter, a wrong key or a wrong type without running anything: no request, no key, no cost.
Why this matters more for LLM code than for most code: the failure for a typo in a nested request dictionary ({"role": "user", "contnt": "hi"}) is a 400 from a paid API, usually found in production on the one code path nobody exercised. Keyword typos at the top level raise a TypeError when the line runs; typos inside dictionaries and config objects often go all the way to the server.
11.1 Four seeded mistakes, four catches#
This file is wrong on purpose, four ways: a misspelt keyword argument, a misspelt key inside a message dictionary, a misspelt field in a Gemini config object, and a string where the API needs an integer. It's never run.
# s11_bad_calls.py
"""Four seeded mistakes. No request is ever sent: the type checker finds each one from the SDKs' type hints."""
import anthropic
from google import genai
from google.genai import types
from openai import OpenAI
oai = OpenAI(api_key="sk-test")
claude = anthropic.Anthropic(api_key="sk-ant-test")
gem = genai.Client(api_key="gemini-test")
# 1. A misspelt keyword argument (the real one is max_output_tokens)
oai.responses.create(model="gpt-6-luna", input="hi", max_output_token=100)
# 2. A misspelt key inside a message dict
claude.messages.create(model="claude-haiku-5-5", max_tokens=100, messages=[{"role": "user", "contnt": "hi"}])
# 3. A misspelt field in a Gemini config object
gem.models.generate_content(model="gemini-3.8-flash", contents="hi",
config=types.GenerateContentConfig(max_output_token=100))
# 4. A value of the wrong type (a string where the API wants an integer)
claude.messages.create(model="claude-haiku-5-5", max_tokens="100", messages=[{"role": "user", "content": "hi"}])Run pyright against it with the project's configuration (shown in 11.3). In your project that is uv run pyright s11_bad_calls.py (this module checks its own samples with a script, typecheck.sh, that runs the same command against the SDK versions named in Setup). The report:
uv run pyright s11_bad_calls.pys11_bad_calls.py
s11_bad_calls.py:12:1 - error: No overloads for "create" match the provided arguments
Argument types: (Literal['gpt-6-luna'], Literal['hi'], Literal[100]) (reportCallIssue)
s11_bad_calls.py:15:76 - error: Argument of type "list[dict[str, str]]" cannot be assigned to parameter "messages" of type "Iterable[MessageParam]" in function "create"
Type "dict[str, str]" is not assignable to type "MessageParam"
"dict[str, str]" is not assignable to "UserMessageParam"
"dict[str, str]" is not assignable to "AssistantMessageParam"
"dict[str, str]" is not assignable to "SystemMessageParam" (reportArgumentType)
s11_bad_calls.py:19:64 - error: No parameter named "max_output_token" (reportCallIssue)
s11_bad_calls.py:22:61 - error: Argument of type "Literal['100']" cannot be assigned to parameter "max_tokens" of type "int" in function "create"
"Literal['100']" is not assignable to "int" (reportArgumentType)
4 errors, 0 warnings, 0 informationsFour mistakes, four errors, on the right lines (12, 15, 19, 22): a four-out-of-four catch. Reading the messages is a skill of its own:
No overloads for "create" match the provided arguments(line 12): the SDK method has several signatures (streaming and non-streaming), so the checker can only say "none fit". The message lists the argument types you passed, not which name is wrong. The cause is almost always one misspelt or unsupported keyword. Compare your keywords with the method's parameter list (inspect.signature(client.responses.create), or your editor's hover).No parameter named "max_output_token"(line 19): the clearest form. The Gemini config is a class, so the checker names the field.... "dict[str, str]" is not assignable to "UserMessageParam"(line 15): the dictionary was checked against each allowed message shape, and none matched. The misspelt keycontntis why. Read the shape names it lists (UserMessageParam,AssistantMessageParam) and compare keys.Literal['100'] is not assignable to "int"(line 22): the plainest type error.
mypy (2.4.1 here) finds the same four mistakes, and for the overloaded create calls its messages are more helpful than pyright's: it names the misspelt keyword itself and suggests the fix. Run in the same environment:
uv run --with mypy mypy s11_bad_calls.pyOutput (the "Possible overload variants" notes that mypy prints after the overload errors are left out for length):
s11_bad_calls.py:12: error: Unexpected keyword argument "max_output_token" for overloaded function "create" of "Responses"; did you mean "max_output_tokens"? [call-overload]
s11_bad_calls.py:12: error: No overload variant of "create" of "Responses" matches argument types "str", "str", "int" [call-overload]
s11_bad_calls.py:15: error: List item 0 has incompatible type "dict[str, str]"; expected "UserMessageParam | AssistantMessageParam | SystemMessageParam" [list-item]
s11_bad_calls.py:19: error: Unexpected keyword argument "max_output_token" for "GenerateContentConfig"; did you mean "max_output_tokens"? [call-arg]
s11_bad_calls.py:22: error: No overload variant of "create" of "Messages" matches argument types "str", "str", "list[dict[str, str]]" [call-overload]The [call-overload], [list-item] and [call-arg] tags are mypy's error codes. Use whichever checker your team prefers; the point is to use one, and to run it in CI.
11.2 The SDK's types follow the API's changes#
Type hints are also the first place an API change shows up. Anthropic's API version 2026-10-21, which anthropic 2.x sends, removed temperature, top_p and top_k; sending them is a 400 (03.1, 9.1). Habit makes people still pass temperature=0.2. Because the 2.x SDK removed those parameters from its signatures, the checker flags it before the request:
# s11_removed_param.py
"""Anthropic's API version 2026-10-21 removed temperature, top_p and top_k. The SDK's type hints reflect that."""
import anthropic
claude = anthropic.Anthropic(api_key="sk-ant-test")
claude.messages.create(model="claude-haiku-5-5", max_tokens=100, temperature=0.2,
messages=[{"role": "user", "content": "hi"}])s11_removed_param.py
s11_removed_param.py:5:1 - error: No overloads for "create" match the provided arguments
Argument types: (Literal['claude-haiku-5-5'], Literal[100], float, list[dict[str, str]]) (reportCallIssue)
1 error, 0 warnings, 0 informationspyright gives its usual "no overloads" message and lists a float among the argument types; mypy names the parameter directly. Same command, this file:
uv run --with mypy mypy s11_removed_param.pys11_removed_param.py:5: error: Unexpected keyword argument "temperature" for overloaded function "create" of "Messages" [call-overload]
s11_removed_param.py:5: error: No overload variant of "create" of "Messages" matches argument types "str", "int", "float", "list[dict[str, str]]" [call-overload]If you're migrating a codebase from an older SDK, running the checker over it is the fastest way to find every call that needs changing.
11.3 Configuring the checker#
A pyrightconfig.json (or [tool.pyright] in pyproject.toml) in the project root makes pyright behave the same on every machine and in CI. This is the configuration the module uses to check its own samples:
{
"typeCheckingMode": "standard",
"exclude": ["s11_*.py", ".venv", ".mypy_cache"],
"reportOptionalMemberAccess": "none",
"reportOptionalSubscript": "none",
"reportOptionalIterable": "none",
"reportOptionalOperand": "none",
"reportOptionalCall": "none",
"reportAttributeAccessIssue": "warning",
"reportPossiblyUnboundVariable": "warning"
}What the choices mean:
typeCheckingMode: "standard"is the balanced default: it checks calls, assignments and returns, without the pedantry of"strict".- The
reportOptional...rules are off because LLM responses are full ofOptionalfields (message.content,choice.message.content,response.usage) and the lesson samples tolerate them for readability. In your own production code, turn them back on: that is exactly where aNoneusage becomes a crash. excludekeepspyrightaway from the files that are wrong on purpose (thes11_*seeded mistakes), souv run pyrightin CI doesn't fail on them. Name a file on the command line, as above, and the exclusion doesn't apply: that is how the demo reaches it.reportPossiblyUnboundVariable: "warning"keeps "this variable might not be assigned" visible without failing the build. (Older write-ups call this settingreportPossiblyUnbound; currentpyrightrejects that name with a one-line notice, "Config contains unrecognized setting". Use the new name.)reportAttributeAccessIssue: "warning"downgrades attribute errors on union types to warnings. A response'scontentlist is a union of block types, and.textexists only on the text block. A warning here is usually fine (you checkedblock.type == "text"first), whereas a misspelt attribute on a plain object is a real bug, so read the warnings and don't suppress them blindly.
Install it as a development dependency and run it in CI before the tests (Part 12): uv add --dev pyright and uv run pyright.
11.4 Let the checker verify your test doubles#
Part 6 introduced ChatModel as a Protocol. A payoff of that choice: the type checker verifies that every fake and adapter fits it. When someone later adds max_tokens and user to the interface, any fake written against the old shape stops fitting, and the checker says so before a test run:
# s11_protocol_check.py
"""A Protocol lets the type checker verify your test doubles. Two fakes: one fits ChatModel, one drifted."""
from chat_types import ChatModel, Completion, Message
class GoodFake:
def complete(self, system: str, messages: list[Message], *, max_tokens: int, user: str | None = None) -> Completion:
return Completion(text="ok", outcome="ok", finish_reason="stop", model="fake", request_id=None)
class DriftedFake:
"""Written before someone added `max_tokens` and `user` to the interface; nothing noticed."""
def complete(self, system: str, messages: list[Message]) -> Completion:
return Completion(text="ok", outcome="ok", finish_reason="stop", model="fake", request_id=None)
good: ChatModel = GoodFake() # fits: no error, and GoodFake never had to inherit from anything
bad: ChatModel = DriftedFake() # does not fit: the checker says exactly whys11_protocol_check.py
s11_protocol_check.py:18:18 - error: Type "DriftedFake" is not assignable to declared type "ChatModel"
"DriftedFake" is incompatible with protocol "ChatModel"
"complete" is an incompatible type
Type "(system: str, messages: list[Message]) -> Completion" is not assignable to type "(system: str, messages: list[Message], *, max_tokens: int, user: str | None = None) -> Completion"
Missing keyword parameter "max_tokens"
Missing keyword parameter "user" (reportAssignmentType)
1 error, 0 warnings, 0 informationsGoodFake fits without inheriting from anything. DriftedFake doesn't, and the message names the missing keyword parameters. Without this check, the drifted fake would pass type-agnostic tests until the day a test called it with the new arguments and failed with a confusing TypeError. Lesson 03.11 leans on the same idea for its adapters.
11.5 What static checks can't catch#
They are a complement to the tests of Part 7, not a replacement:
- A valid-looking parameter the API rejects or ignores. The types say a parameter exists; they don't know that a particular model rejects
reasoning.effortor that the Responses API on a local stand-in ignorestool_choice. Contract and live tests (7.7, 7.8) cover that. - Anything inside
extra_body=,extra_headers=or anAny-typed dictionary. These are escape hatches that bypass the types. Use them only for provider-specific fields (such as OpenRouter'sprovider,modelsandplugins), with a comment saying why. - Model names. Some SDKs type the
modelargument as a union of known literals andstr, so a misspelt model passes the checker. Keep model IDs in one configuration place and cover them with a live smoke test. - Business meaning. The checker can't tell that the system prompt is empty, or that the history was trimmed to two turns. Request summaries and snapshots can (3.4, 7.6).
Part 12: CI without keys#
Deep-dive
Continuous integration (CI) runs your checks automatically on every push or pull request, on a clean machine that isn't yours. For LLM projects it has two special constraints: the runner has no API keys (and you don't want it to), and anything that does call a provider is slow, costs money and fails for reasons outside your code. Parts 6 to 11 were built to fit: almost everything runs offline.
12.1 What runs where#
flowchart TD
subgraph push ["On every push and pull request: no keys, no network"]
A["Static checks: pyright"] --> B["pytest -m not stand_in and not live<br/>unit, fakes, mocks, replay, snapshots"]
end
subgraph night ["On a schedule: keys, tiny budget"]
C["Live smoke tests<br/>RUN_LIVE_TESTS=1, LIVE_CALL_BUDGET=6"] --> D["Alert a human<br/>if a provider changed"]
end
subgraph opt ["Optional job: local stand-in"]
E["Start Ollama container<br/>pull a tiny model"] --> F["pytest -m stand_in"]
end
push --> opt
night -.->|"secrets only here"| S["Repository secrets<br/>CI-only keys with spend limits"]| Job | Trigger | Keys? | Runs | Why here |
|---|---|---|---|---|
| Offline | Every push and pull request | None | pyright, then pytest -m "not live and not stand_in": unit tests, fakes, mock transports, cassette replays, request snapshots, streaming and retry tests |
Fast (seconds), free, deterministic. It's the required check that blocks merges |
| Stand-in (optional) | Every push, or only on main |
None | pytest -m stand_in against Ollama in a container |
Real HTTP and real SDK parsing, no keys. Slower (a model download, a minute or two), so it's optional |
| Live smoke | A schedule (for example once a day on weekdays) and a manual button | CI-only keys, in repository secrets | pytest -m live with RUN_LIVE_TESTS=1, a call budget and a timeout |
A canary for provider changes and broken keys. Never a required check for pull requests |
The rule of thumb: anything a pull request author could break belongs in the offline job; anything a provider could break belongs in the scheduled job. If a live test fails on Tuesday morning with no code change, the provider (or your key, or your quota) changed, and that's information, not a blocked merge.
12.2 The workflows#
Two small files in .github/workflows/ cover it. This is a sketch for GitHub Actions (the examples are not run here, and the action versions were the latest releases when this lesson was written: actions/checkout v7 and astral-sh/setup-uv v10.3.3; check yours). The YAML was parsed to confirm it's valid, and the commands inside are the ones the earlier parts ran locally.
# .github/workflows/tests.yml
name: tests
on:
push:
pull_request: # fork PRs run this workflow too, and GitHub gives them NO secrets: that is why it needs none
permissions:
contents: read # the default token can read the repo and nothing else
jobs:
offline:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@v7
- uses: astral-sh/setup-uv@v10.3.3 # real repositories: pin the full commit SHA instead of a tag
with:
python-version: "3.13" # must satisfy requires-python in pyproject.toml (uv init --python 3.13 wrote ">=3.13")
- run: uv sync --frozen # exact versions from uv.lock: openai 3.42.1, anthropic 2.4.0, ...
- run: uv run pyright # catches misspelt SDK parameters before any test runs
- run: uv run pytest -m "not live and not stand_in"
env:
OPENAI_API_KEY: "" # explicitly empty: a stray key on a runner must not enable live tests
ANTHROPIC_API_KEY: ""
GEMINI_API_KEY: ""
OPENROUTER_API_KEY: ""
stand-in: # optional: contract tests against a tiny local model (overview only)
runs-on: ubuntu-latest
timeout-minutes: 20
needs: offline
steps:
- uses: actions/checkout@v7
- uses: astral-sh/setup-uv@v10.3.3
with:
python-version: "3.13"
- run: uv sync --frozen
- name: Start Ollama and pull a small model
run: |
docker run -d --name ollama -p 11434:11434 ollama/ollama
until curl -sf localhost:11434/api/version; do sleep 1; done
docker exec ollama ollama pull qwen2.5:0.5b
for id in gpt-6-luna claude-haiku-5-5; do docker exec ollama ollama cp qwen2.5:0.5b "$id"; done
- run: uv run pytest -m stand_in# .github/workflows/live-smoke.yml
name: live-smoke
on:
schedule:
- cron: "17 5 * * 1-5" # weekdays 05:17 UTC; off the hour, because the top of the hour is busiest
workflow_dispatch: # and a manual "Run workflow" button
permissions:
contents: read
concurrency:
group: live-smoke # never two runs at once: they would double the spend
cancel-in-progress: false
jobs:
live:
runs-on: ubuntu-latest
timeout-minutes: 10
environment: live-smoke # an environment can require approval and holds the secrets for this job only
steps:
- uses: actions/checkout@v7
- uses: astral-sh/setup-uv@v10.3.3
with:
python-version: "3.13" # must satisfy requires-python in pyproject.toml (uv init --python 3.13 wrote ">=3.13")
- run: uv sync --frozen
- run: uv run pytest -m live -rs
env:
RUN_LIVE_TESTS: "1"
LIVE_CALL_BUDGET: "6" # the suite fails if it tries to make a 7th call
OPENAI_API_KEY: ${{ secrets.CI_OPENAI_API_KEY }} # separate CI-only keys with provider-side spend limits
ANTHROPIC_API_KEY: ${{ secrets.CI_ANTHROPIC_API_KEY }}
GEMINI_API_KEY: ${{ secrets.CI_GEMINI_API_KEY }}
OPENROUTER_API_KEY: ${{ secrets.CI_OPENROUTER_API_KEY }}Things worth noticing:
- The Python version must satisfy
requires-python.uv init llm-testing --bare --python 3.13(the Setup line) writesrequires-python = ">=3.13", so the workflows saypython-version: "3.13"in every job; anduv sync --frozenrefuses an interpreter that the project doesn't allow, so a workflow that said 3.12 here would be red on the first push. Keep the two in step (or letuvchoose from the project: it readsrequires-pythonwhen you give it no version). uv sync --frozeninstalls from the lockfile, so CI runs exactly the SDK versions you pinned (03.1, 4.4). A dependency bump becomes a deliberate pull request whose snapshot and cassette diffs a reviewer can read, not a surprise on Monday.- The offline job sets the four key variables to empty strings. A stray key on a self-hosted runner, or one inherited from the environment, must not turn live tests on by accident. (They're also guarded by
RUN_LIVE_TESTS, which the offline job never sets: belt and braces.) Empty is not the same as unset, and the SDKs raise at construction for an empty key, so the offline tests must not trip over it: the replay tests reados.environ.get(name) or "replay-only". 7.5 shows the replay passing with all four variables empty; tests that read the variable with a plain default would make this job red. - GitHub sets
CI=true, which makes the snapshot helper fail on a snapshot file that was never committed (7.6). The cassette lint (7.5) runs in this job too, as part ofpytest. pyrightruns before the tests, because a typo is cheaper to report than to execute (Part 11).permissions: contents: readgives the workflow's built-in token the minimum.- The scheduled workflow runs "off the hour" (
17 5 * * 1-5). GitHub's docs say scheduled runs can be delayed under high load, and that load peaks at the start of each hour, so avoid:00. concurrencystops two live runs overlapping, which would double the spend;timeout-minutesstops a hung job from running for hours.
Facts about GitHub Actions scheduling, from GitHub's documentation (as of November 2026; events that trigger workflows): scheduled workflows run on the default branch; the shortest interval is once every five minutes; and in public repositories a scheduled workflow is automatically disabled after 60 days without repository activity, so a quiet project's canary can silently stop. Add a calendar reminder, or look at the Actions tab occasionally.
12.3 Secrets in CI#
Live tests need real keys, which makes CI a place where keys live. Treat that as a security design, not a convenience:
- Separate CI keys, never your personal one. Create a key per provider used only by CI, in a project or workspace of its own, with a spend limit set on the provider's side (03.1, 3.3). If the key leaks, the damage is bounded, and rotation breaks nothing else (03.1, 3.6).
- Store them as repository (or environment) secrets, and expose them only to the job that needs them:
OPENAI_API_KEY: ${{ secrets.CI_OPENAI_API_KEY }}in theenv:of that step. The offline job doesn't mention them. - Pull requests from forks don't get your secrets. GitHub's documentation says secrets "are not passed to the runner when a workflow is triggered from a forked repository" (with the exception of the built-in
GITHUB_TOKEN). That's exactly what you want for the offline job, and it's why its tests must not need a key. Don't "fix" this by switching to thepull_request_targetevent: GitHub warns that "running untrusted code on thepull_request_targettrigger may lead to security vulnerabilities", because it runs in the context of the base repository, where secrets and write access are available to code from the pull request. - An
environmentcan require a human to approve a job before its secrets are released. The live workflow names one (live-smoke), which is where you'd add that rule and where its secrets can live. - Never print them. GitHub masks the exact secret value in logs, but only that exact string: a base64 or URL-encoded form, or a header dump, can slip through. So don't turn on
ANTHROPIC_LOG=debugin CI (it also logs prompts, 2.1), don'tenv | sort, and let the redaction of Part 2 handle any wire logs. - Rotate on a schedule and after any incident, and keep the keys' provider-side limits low enough that a runaway test is a small bill.
12.4 The stand-in in CI (overview)#
The stand-in job in the first workflow starts Ollama in a container, pulls the small model and aliases it to the model names the tests use, then runs only the stand_in tests. It's optional because it trades time (a model download, a cold start) for realism: real HTTP, real SDK parsing, no keys. Cache the model volume between runs if you keep it. Gemini has no local stand-in, so there is no second container to add for it. This job is a sketch: it was not executed here (the same steps run locally in 03.1, Part 12).
12.5 What CI for prompts and evals adds (not this lesson)#
Everything above tests code. Gating a deployment on whether a new prompt scores better than the old one on a dataset, comparing model versions, and promoting prompts through environments is a different pipeline with different tools: that's Module 10A (the evals) and Module 11C (CI/CD for prompts). The pieces here (a clean offline job, pinned dependencies, scheduled live checks, request snapshots) are what those pipelines sit on.
Part 13: Cost-safe development habits#
An LLM project can spend real money while nobody is looking: a test run in a loop, a notebook cell re-run twenty times, a retry bug, a script left running over a weekend. Lesson 03.8, 4.5 shows a retry bug that burns money, and 03.7 covers tracking and budgets in production. These are the development habits that keep the bill dull.
13.1 The habits#
These repeat what 03.1, 03.7 and Part 7 already teach, so each is one line with its owner:
- Develop on the cheapest model that exercises the code path (
gpt-6-luna,claude-haiku-5-5,gemini-3.8-flash, 02.9), with the model ID in config. Most bugs are in your code, not in model quality. - Put a hard
max_tokenson every call and a small one in tests (03.7, 12.1); leave room for reasoning models. - Use separate keys per environment, each with a provider-side spend limit (03.1, 3.3 and 3.6), and look at the provider's usage page weekly, with an alert on spend (03.7, 12.5).
- Make tests not call the API by default (the network guard, 7.4, and the opt-in live tests, 7.8) and count calls in any loop that calls a model (
LiveBudget): a failing test is cheaper than an invoice. - Practise against the free local model (03.1, Part 12), log cost in development too (Part 4), and cache while iterating (13.2).
- Treat batch and large jobs as separate, reviewed runs: estimate first (03.7, Part 2), run a 10-item sample, then the rest (03.9).
13.2 A disk cache for development#
When you're iterating on the code around a model call (parsing, formatting, the next step in a pipeline), the model's answer is the same every time you re-run, and re-asking is waste. A development response cache saves each reply on disk, keyed by the request, and serves the saved one when the same request comes again.
Where to put it matters. A cache in your own function (@lru_cache) misses the SDK's behaviour entirely. A cache at the HTTP transport is better, because everything above it is the real SDK, so the cached path exercises the same request building and response parsing as the live one. devcache.py is a transport wrapper of about 50 lines:
# devcache.py
"""devcache.py: a disk cache for DEVELOPMENT, as an httpx2 transport. Same request body -> same saved reply.
Never use it in production: it hides non-determinism, outages and every change the provider makes."""
from __future__ import annotations
import hashlib
import json
import os
import time
from pathlib import Path
from typing import Any
import httpx2
def _keyable_body(request: httpx2.Request) -> tuple[bool, Any]:
"""(True, body) when the request can be keyed, (False, None) when it can't. A streamed body
(a multipart file upload) raises RequestNotRead on .content, and a body that isn't JSON has
no canonical form — never cache what you can't key."""
try:
content = request.content
except httpx2.RequestNotRead:
return False, None
if not content:
return True, {}
try:
return True, json.loads(content)
except ValueError: # JSONDecodeError and UnicodeDecodeError are both ValueErrors
return False, None
def cache_key(request: httpx2.Request) -> str:
"""Method + URL + normalized JSON body. Headers are left out on purpose: the API key must not change the key
(or end up on disk), and the SDK's retry-count and timeout headers differ between identical requests."""
_, body = _keyable_body(request)
canonical = json.dumps([request.method, str(request.url), body], sort_keys=True, ensure_ascii=False)
return hashlib.sha256(canonical.encode()).hexdigest()[:24]
class DiskCacheTransport(httpx2.BaseTransport):
def __init__(self, inner: httpx2.BaseTransport, directory: str | Path = ".llm_cache", *, ttl_seconds: float | None = 86_400) -> None:
self.inner, self.dir, self.ttl = inner, Path(directory), ttl_seconds
self.hits = self.misses = 0
self.dir.mkdir(mode=0o700, exist_ok=True) # the folder holds user prompts and replies: owner only
def handle_request(self, request: httpx2.Request) -> httpx2.Response:
cacheable, body = _keyable_body(request)
if not cacheable or (isinstance(body, dict) and body.get("stream")):
return self.inner.handle_request(request) # streams and unkeyable bodies bypass: always live
path = self.dir / f"{cache_key(request)}.json"
if path.exists() and (self.ttl is None or time.time() - path.stat().st_mtime < self.ttl):
saved = json.loads(path.read_text())
self.hits += 1
return httpx2.Response(saved["status"], headers=saved["headers"], content=saved["body"].encode(), request=request)
response = self.inner.handle_request(request)
response.read()
self.misses += 1
if response.status_code == 200: # never cache errors: a 429 would be replayed forever
keep = {k: v for k, v in response.headers.items() if k.lower() in {"content-type", "x-request-id", "request-id"}}
# created owner-only (0o600) from the first byte; written to a temp name, then renamed, so a crash
# in the middle can never leave half a JSON file that the next run would trust
tmp = path.with_suffix(".tmp")
with os.fdopen(os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "w") as f:
f.write(json.dumps({"status": 200, "headers": keep, "body": response.text}))
tmp.replace(path)
return responseIts design choices are each a pitfall avoided:
- The key is the method, the URL and the normalized JSON body (sorted keys). Any change to the prompt, the model, a parameter or the output cap is a different request, so an edited prompt always gets a fresh answer.
- Headers are left out of the key on purpose: the API key must not decide the key (or end up on disk), and the SDK's
x-stainless-retry-countand timeout headers differ between otherwise identical requests. (The downside is in the pitfalls below.) - Only
200responses are cached. An error would be replayed forever; the testtest_errors_are_never_cachedpins that. - Streams are bypassed (
"stream": truein the body): replaying an event stream from a file needs a different design, and 7.5's cassettes already do it for tests. - Bodies that can't be keyed bypass too. A streamed body — a multipart file upload — raises
RequestNotReadon.content(the same trapwire_log.pyguards against in 2.3), and a body that isn't JSON has no canonical form. Both go straight to the inner transport: never cache what you can't key. - A time limit (
ttl_seconds, a day by default) so entries expire; the test ages a file instead of sleeping. - Owner-only files, written atomically. The folder is created
0o700and each entry0o600from the first byte, and written to a temporary name and renamed, so a crash can't leave half a JSON file that the next run trusts. The folder holds your prompts and the model's replies.
Use it on the free local model:
# s13_dev_cache.py
"""A disk cache for development (layer 2: the free local model). The second identical call never reaches the model."""
import tempfile
import time
import httpx2
import openai
from openai import OpenAI
from devcache import DiskCacheTransport
cache_dir = tempfile.mkdtemp(prefix="llm_cache_")
transport = DiskCacheTransport(httpx2.HTTPTransport(), cache_dir) # wraps the real network transport
client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama-local",
http_client=openai.DefaultHttpx2Client(transport=transport))
def ask(question: str, max_tokens: int = 30) -> str:
started = time.perf_counter()
text = client.responses.create(model="gpt-6-luna", input=question, max_output_tokens=max_tokens).output_text
print(f" {(time.perf_counter() - started) * 1000:7.1f} ms hits={transport.hits} misses={transport.misses} {text[:40]!r}")
return text
print("same request twice:")
first, second = ask("Name one colour."), ask("Name one colour.")
print("identical text:", first == second)
print("a different max_tokens is a different request:")
ask("Name one colour.", max_tokens=31)
print("files on disk:", sorted(p.name for p in transport.dir.iterdir()))
print("API key stored on disk?", any("ollama-local" in p.read_text() for p in transport.dir.iterdir()))same request twice:
278.8 ms hits=0 misses=1 'Red is a popular and recognizable color '
0.8 ms hits=1 misses=1 'Red is a popular and recognizable color '
identical text: True
a different max_tokens is a different request:
220.3 ms hits=1 misses=2 'Red is one of the most recognizable and '
files on disk: ['ceded0530cf7e372898fe48b.json', 'f83931ec2d2d76b7254dd8de.json']
API key stored on disk? FalseThe first call took a few hundred milliseconds (a real round trip to the model) and the identical second call about a millisecond (hits=1), with identical text. Changing max_tokens from 30 to 31 is a different request and a miss. Two files are on disk, and the dummy key ollama-local appears in neither. The test file tests/test_dev_cache.py pins those rules (it also checks the permissions with the loosest possible umask):
# tests/test_dev_cache.py
"""The development cache is code too: test what could go wrong with it."""
import io
import os
import stat
import time
import httpx2
import openai
from devcache import DiskCacheTransport, cache_key
from fixtures import SCENARIOS
from mocks import Script
def client_over(script: Script, tmp_path, **kw) -> tuple[openai.OpenAI, DiskCacheTransport]:
transport = DiskCacheTransport(httpx2.MockTransport(script.handler(httpx2)), tmp_path, **kw)
return openai.OpenAI(api_key="sk-test", max_retries=0, http_client=httpx2.Client(transport=transport)), transport
def test_second_identical_call_is_served_from_disk(tmp_path) -> None:
script = Script(SCENARIOS["openai_responses"]["ok"]) # only ONE reply: a second network call would fail
client, cache = client_over(script, tmp_path)
a = client.responses.create(model="gpt-6-luna", input="hi")
b = client.responses.create(model="gpt-6-luna", input="hi")
assert a.output_text == b.output_text and (cache.hits, cache.misses) == (1, 1)
def test_any_changed_parameter_is_a_new_request(tmp_path) -> None:
script = Script(SCENARIOS["openai_responses"]["ok"], SCENARIOS["openai_responses"]["ok"])
client, cache = client_over(script, tmp_path)
client.responses.create(model="gpt-6-luna", input="hi", max_output_tokens=10)
client.responses.create(model="gpt-6-luna", input="hi", max_output_tokens=11)
assert (cache.hits, cache.misses) == (0, 2)
def test_errors_are_never_cached(tmp_path) -> None:
script = Script(SCENARIOS["openai_responses"]["rate_limited"], SCENARIOS["openai_responses"]["ok"])
client, cache = client_over(script, tmp_path)
try:
client.responses.create(model="gpt-6-luna", input="hi")
except openai.RateLimitError:
pass
assert client.responses.create(model="gpt-6-luna", input="hi").output_text # the retry reaches the server
assert cache.misses == 2 and cache.hits == 0
def test_the_key_ignores_credentials_and_retry_headers(tmp_path) -> None:
def key(api_key: str, retry: str) -> str:
return cache_key(httpx2.Request("POST", "https://x/v1/responses", json={"a": 1},
headers={"authorization": f"Bearer {api_key}", "x-stainless-retry-count": retry}))
assert key("sk-one", "0") == key("sk-two", "1")
def test_streams_bypass_the_cache(tmp_path) -> None:
script = Script(SCENARIOS["openai_responses"]["ok"], SCENARIOS["openai_responses"]["ok"])
client, cache = client_over(script, tmp_path)
for _ in range(2):
try:
client.responses.create(model="gpt-6-luna", input="hi", stream=True)
except Exception: # the mock's JSON is not an event stream: irrelevant here
pass
assert (cache.hits, cache.misses) == (0, 0) and len(script.seen) == 2
def test_a_multipart_upload_bypasses_the_cache(tmp_path) -> None:
"""files.create sends a streamed multipart body: request.content raises RequestNotRead.
The cache must not read it, must not key it, and must not store the reply — twice, to prove it."""
seen: list[bytes] = []
def handler(request: httpx2.Request) -> httpx2.Response:
seen.append(request.read()) # the "server" receives the whole upload
return httpx2.Response(200, json={"id": "file-1", "object": "file", "bytes": 3, "created_at": 1,
"filename": "a.txt", "purpose": "user_data"})
transport = DiskCacheTransport(httpx2.MockTransport(handler), tmp_path)
client = openai.OpenAI(api_key="sk-test", max_retries=0, http_client=httpx2.Client(transport=transport))
for _ in range(2):
assert client.files.create(file=("a.txt", io.BytesIO(b"abc")), purpose="user_data").id == "file-1"
assert (transport.hits, transport.misses) == (0, 0) and len(seen) == 2 and not list(tmp_path.glob("*.json"))
def test_an_entry_older_than_the_ttl_is_asked_again(tmp_path) -> None:
script = Script(SCENARIOS["openai_responses"]["ok"], SCENARIOS["openai_responses"]["ok"])
client, cache = client_over(script, tmp_path, ttl_seconds=60)
client.responses.create(model="gpt-6-luna", input="hi")
entry = next(tmp_path.glob("*.json"))
two_minutes_ago = time.time() - 120
os.utime(entry, (two_minutes_ago, two_minutes_ago)) # age the file instead of sleeping
client.responses.create(model="gpt-6-luna", input="hi")
assert (cache.hits, cache.misses) == (0, 2)
def test_the_cache_holds_user_content_so_it_is_owner_only(tmp_path) -> None:
old = os.umask(0) # the loosest umask: only our explicit modes protect us
try:
client, cache = client_over(Script(SCENARIOS["openai_responses"]["ok"]), tmp_path / "cache")
client.responses.create(model="gpt-6-luna", input="hi")
finally:
os.umask(old)
assert stat.S_IMODE(cache.dir.stat().st_mode) == 0o700
(entry,) = cache.dir.glob("*.json")
assert stat.S_IMODE(entry.stat().st_mode) == 0o600============================= test session starts ==============================
collected 8 items
tests/test_dev_cache.py::test_second_identical_call_is_served_from_disk PASSED [ 12%]
tests/test_dev_cache.py::test_any_changed_parameter_is_a_new_request PASSED [ 25%]
tests/test_dev_cache.py::test_errors_are_never_cached PASSED [ 37%]
tests/test_dev_cache.py::test_the_key_ignores_credentials_and_retry_headers PASSED [ 50%]
tests/test_dev_cache.py::test_streams_bypass_the_cache PASSED [ 62%]
tests/test_dev_cache.py::test_a_multipart_upload_bypasses_the_cache PASSED [ 75%]
tests/test_dev_cache.py::test_an_entry_older_than_the_ttl_is_asked_again PASSED [ 87%]
tests/test_dev_cache.py::test_the_cache_holds_user_content_so_it_is_owner_only PASSED [100%]
============================== 8 passed in 0.62s ===============================The pitfalls, which are why this is for development only:
- It hides non-determinism. A feature that works because the cache keeps returning one lucky answer is not working. Clear the cache (or run uncached) before you conclude anything, and never use the cache for the replays of Part 5.
- It hides provider changes and outages. A cached call can't fail, slow down or be rate-limited, so it won't show you error handling. It also won't notice the alias moving to a new model (5.4).
- It can cache a bad answer. A refusal or a truncated reply is a
200and gets saved. Delete the cache entry (or the folder) after you changemax_tokens-sensitive code, and consider caching only replies whoseoutcomeisok. - The key ignores headers. Two requests that differ only in a header the API treats as meaningful (a beta header,
anthropic-version) share one entry. Add such headers to the key if you use them. - The folder holds user content. Put it in
.gitignore, don't share it, and delete it when you're done (Part 5 applies: it's a store of prompts). - It's not a production cache. Production response caching (exact and semantic) has its own design problems (staleness, personalization, privacy) and belongs to Module 11B. Provider-side prompt caching, which reduces cost by reusing prompt prefixes on the provider's servers, is a different thing again (03.7).
13.3 Cost-safe habits for tests specifically#
Three extras that matter for tests: count live calls, not only dollars (a per-run call budget fails fast; a dollar budget needs prices, 03.7); parametrize live tests sparingly (50 prompts is 50 calls on every scheduled run: wide sweeps belong in an evaluation, Module 10A); and cap concurrency in async tests (200 concurrent calls spend 200 calls' money at once and trip rate limits, 03.9). Prefer the stand-in for "does the code path work?", mocks for "does it handle this error?", and the real API only for "does the provider still accept this?". Don't re-record cassettes casually: each re-record is a real call.
Common misconceptions#
| Misconception | Reality |
|---|---|
| "If the model gave a bad answer, the model is the problem." | Most "bad answer" bugs are bad requests: an empty system prompt, trimmed history, a moved alias, an ignored parameter. Look at the exact request first (Part 1, 3.1) |
"OPENAI_LOG=debug and ANTHROPIC_LOG=debug are equivalent." |
openai's switch logs method, status and request ID only. anthropic's also turns on the httpx2 logger and logs the full request body, prompts included (2.1) |
| "Logging the full request temporarily is harmless." | It puts prompts and personal data into log retention, often permanently. Log hashes and sizes by default; content behind a flag, redacted and sampled (4.1, 4.5) |
"Hiding authorization and x-api-key makes header logs safe." |
A deny-list leaks every credential header you haven't heard of (x-portkey-api-key, helicone-auth). Show only allow-listed headers and hide the rest, and test it (2.3) |
| "Redaction with regular expressions makes logs safe." | It reduces risk. It still misses obfuscated emails, names and addresses and echoed fragments of keys, it over-redacts long digit runs, and every new vendor key prefix needs a pattern and a test (4.5) |
| "The request ID in my log is the one support needs." | After a retry it's the successful attempt's. The failed attempt has its own ID, visible to hooks and middleware (2.4, 4.3) |
"respx mocks my openai calls." |
respx patches httpx; openai 3.x and anthropic 2.x use httpx2. The call silently goes to the network. Inject an httpx2.MockTransport and add --disable-socket (7.4) |
| "I'll assert the model's answer in a test." | Real answers vary. Assert shapes and invariants, snapshot the request, and leave quality to evaluation (7.1, 7.6, Module 10A) |
| "A passing test against the local stand-in means the hosted API will accept my request." | The stand-in ignores many parameters and sends no request IDs or rate-limit headers. It proves the code runs, not that the provider accepts it (7.7) |
| "My hand-written mock is the provider's behaviour." | It's your belief about it. Copy fixtures from the docs, refresh them from real recordings, and keep a live test (7.3, 7.8) |
| "Five clean runs show the bug is fixed." | A 10% failure is invisible in five runs 59% of the time. Compare rates over enough replays (5.5) |
| "Tests of error paths are slow because retries are slow." | Set max_retries explicitly, count attempts and read x-stainless-retry-count, shorten waits with retry-after-ms and replace the sleep (Part 9) |
| "Static type checking is for big codebases." | It caught four of four misspelt parameters here, with no request and no key, including mistakes nested inside request dictionaries (Part 11) |
| "CI needs my API keys." | The push-by-push job needs none. Only a scheduled canary does, with CI-only keys that have spend limits (Part 12) |
"A cassette is safe to commit because the authorization header was filtered." |
Response headers (cookies, organization IDs) and the recording machine's details leak too. Scrub by allow-list in both directions and lint the files (7.5) |
| "A development cache is a production cache." | It hides non-determinism, outages and provider changes, and it stores user content on disk. It's a habit for iteration only (13.2) |
Key takeaways#
- Debug the request before the model. Capture exactly what was sent (debug logs, event hooks with redaction, raw responses, or a wire capture that sends nothing), then diff it against what you expected (Parts 1 to 3).
ANTHROPIC_LOG=debuglogs your prompts;OPENAI_LOG=debugdoesn't log URLs, headers or bodies. Neither belongs in production atdebug.google-genaihas no log switch: use theloggingmodule and the HTTP library's logger.- Event hooks run per HTTP attempt, so they see retries, status codes and request IDs the final result hides. Redact fail-closed: show only allow-listed headers and URL query values, summarize bodies as size plus hash, never read a streamed (file upload) body, never let a hook raise, and use
asynchooks on async clients. - Work down the checklist (wrong model or alias, API family, missing or misplaced system prompt, truncated history, dropped reasoning items, mis-threaded tool results, stale SDK, ignored parameter, small output cap, unchecked finish reason, cache miss, stray environment variable, hidden retries). Change one thing at a time and save the evidence first.
- Log one structured record per call: trace ID, provider request ID, provider and API, model requested and served, latency (and time to first token for streams), attempts, every token field in the module convention (uncached input, cached, cache-written and total input, output including reasoning, from 03.7's
cost_calc.from_*), cost (null when unknown), finish reason and outcome, error class and status, feature, hashed user, prompt version and hash, SDK version. Don't log content, keys, raw user IDs, tool arguments or free-text provider messages by default. The hash key has no default outside dev. Async and streamed calls write the same line, with a realttft_ms. - Content logging is a flag, redacted, truncated and sampled, with short retention. Regex redaction is a safety net, not a guarantee.
- Correlate: one trace ID per user request in a
ContextVar, on every log line, sent asX-Client-Request-Idto OpenAI (ASCII, up to 512 characters) and to others where a field exists. Log the provider's own ID as well. A client request ID is for finding calls, not for making them idempotent. anthropichas built-in OpenTelemetry spans (theopen_telemetryoption,metadata_onlyby default,contentopt-in);openaiandgoogle-genaidon't. The GenAI conventions are still in development. Platforms are Module 11A.- Keep evidence to reproduce: store the exact body of flagged calls (never headers, and a redacted URL), created owner-only from the first byte, with a retention limit; replay it N times, because LLM behaviour is probabilistic, and only to hosts you've allow-listed; log the model that actually served the call, and pin where reproducibility matters.
- Design for testability: inject the client, keep prompt building, parsing and rules as pure functions, put a
Protocolat the seam, never construct clients at import time, and pass the clock and randomness in. - The toolbox: unit tests, fake clients, mock transports under the real SDK, record/replay cassettes (
vcrpysupportshttpx2; scrub by allow-list and lint them), request snapshots (a missing one fails in CI), contract tests against the stand-in, and tiny gated live smoke tests. Most of the value is in the middle. respxandpytest-httpxdon't mockopenaioranthropic. Usehttpx2.MockTransport, make the mock fail on unexpected calls, assert it was used, and block sockets for the whole run with--disable-socket.- Snapshot requests, assert response shapes. Build fixtures for valid, invalid, refused and truncated outputs and cut-off tool arguments; use
hypothesisfor parsers, with a generator that reaches the code you care about (arbitrary JSON, not just arbitrary text). - Test retries without waiting: explicit
max_retries, count requests andx-stainless-retry-count, tinyretry-after-ms, an injected or patched sleep (async SDKs sleep withanyio.sleep, and a fake sleep must still yield). - Type-check LLM code. The SDKs' hints catch misspelt parameters, wrong dictionary keys and removed parameters before any request; they can't catch a parameter a model rejects.
- CI: an offline job with no keys (empty variables must be harmless) on every push, on the Python version
requires-pythonallows; a scheduled live canary with CI-only keys, a call budget and spend limits; fork pull requests get no secrets. - Keep development cheap: small model, hard
max_tokens, separate capped keys, call budgets, the free local model, and a development cache that you never mistake for a production one.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Structured log | One machine-readable record (usually a JSON object per line) with the same fields on every call, instead of free text |
| JSON Lines | A file or stream format with one complete JSON object per line, which log pipelines read well |
| Trace ID (correlation ID) | An ID you create once per user request and put on every log line (and send to providers that accept one) to find all the work for it |
| Provider request ID | The ID a provider assigns to one HTTP request (x-request-id, request-id, X-Generation-Id), which its support asks for |
| Event hook | A function registered on an HTTP client that receives every request before it's sent and every response when it arrives |
| Redaction | Replacing secrets and personal data with markers before they're logged or stored |
| Allow-list (fail closed) | Showing only what is on a list and hiding everything else, so a new or unknown credential is hidden by default; the opposite of a deny-list |
| Pure function | A function whose output depends only on its inputs and that touches no network, clock or global state |
Protocol |
A typing construct describing the methods an object must have, without requiring inheritance |
| Test double | Anything that stands in for a real dependency in a test: a fake, a stub or a mock |
| Fake client | A hand-written stand-in for the model client that returns scripted replies and records how it was called |
| Cassette (record/replay) | A saved file of real request/response pairs that tests replay instead of calling the network |
| Snapshot test | A test that saves a function's output the first time and fails when it later changes; for LLM code, applied to the request |
| Contract test | A test that checks your code against a real server speaking the same protocol (here, the local stand-in), checking shapes rather than wording |
| Smoke test | A minimal check that the whole system works at all; a live smoke test makes one tiny real call per provider |
| Network guard | A test setting (--disable-socket) that fails any test which opens a network connection |
| Property-based test | A test that states a rule for all inputs and lets a library (hypothesis) search for and shrink a counterexample |
| Live-call budget | A hard cap on the number of real API calls a test run may make |
| OpenTelemetry GenAI semantic conventions | A standard set of span attribute names (gen_ai.*) for describing LLM calls; content attributes are opt-in |
| Cassette lint | A test that scans committed cassettes for keys, cookies, account IDs, machine fingerprints and the values of your own key variables |
| Reproduction case | The stored exact request behind a flagged call, with its trace ID and context, for replaying later |
| Development response cache | A disk cache that serves saved replies for identical requests while you iterate; never a production cache |
Exercises#
All of these run without keys. The files are in the project layout of 1.4.
- Debug logs (2.1): run
s2_1_debug_openai.pywithOPENAI_LOG=info, thendebug, then withANTHROPIC_LOGset for the Anthropic script. Which lines appear at each level? Find where in the output a prompt would show up for each SDK. - Hooks (2.3): add a response header of your choice to
KEEP_RESPONSEinwire_log.py, and write a test that a request withAuthorization: Bearer <fake>,x-goog-api-key: <fake>and an inventedx-acme-signing-key: <fake>logs none of the three values (build each fake in code, as the lesson's tests do). Which of the three would a deny-list of the first two have leaked? Then attachmake_async_event_hooks()to anAsyncOpenAIclient withopenai.DefaultAsyncHttpx2Clientand callfiles.retrieve. - Request diff (3.3): change
prodins3_3_request_diff.pyso that onlyhistory_turnsdiffers (say 12 turns against 11). Predict how many linesdiff()prints, then run it: why does dropping one turn produce a list-length line and manycontentlines? (Hint: look at what happens to every index after the first.) Then write the script that would produce the same comparison from two stored cases (Part 5). - Logging (4.3): use
s4_2_json_log.pyto log a call whose mock returnsincompletewith reasonmax_output_tokens. What areoutcome,finish_reasonand the log level? AddLogConfig(content_sample_rate=1.0)and confirm the content appears redacted. - Trace IDs (4.4): the middleware already replaces an
x-request-idthat is too long or too short: find the condition that does it, then prove it withTestClienttests (a 65-character ID and a 7-character one). Then send the trace ID to OpenAI asX-Client-Request-Idthrough a mock transport and assert the header. - Redaction (4.5): add a pattern for IBAN-like strings (
GB82 WEST 1234 5698 7654 32) toredact.py. Write a test with a string it should catch and one it must leave alone (an order number). The IBAN contains a long run of digits, which the existingCARDpattern may take first: which pattern wins, and does the order of the two lists matter? What other false positive can you find? Build any key-shaped value in your test from an obviously fake body, astests/test_redact.pydoes. - OpenTelemetry (4.7): run
s4_7_otel.pywithANTHROPIC_OPEN_TELEMETRY_TRACES_CONTENT_MODE=contentset and the option left out of the constructor. Then passopen_telemetry={}. Which one wins, and why? - Reproduction (5.3): change
s5_1_reproduce.pyto replay 20 times and report the share of replies that start with the most common opening. How many replays would you want to estimate a 5% failure rate? - Fakes (7.2): write a test for a validate-and-retry loop with a
FakeChatscripted[invalid, valid], one with three invalids and one with a refusal. Assert onlen(fake.calls). - Mock transports (7.3): add a fifth scenario, a
529overloaded error for Anthropic then a200, tofixtures.py. Is the exception for a streamed overload the same as for a plain one? (Check 8.2.) - The
respxtrap (7.4): remove--disable-socketfrompytest.iniand runtest_network_guard.py. What does each test do now, and how long does it take? Put the flag back. - Cassettes (7.5): delete one cassette and run with
--block-network. What error do you get? Re-record it against the stand-in, then runtests/test_cassettes.py. Now addset-cookietoKEEP_RESPONSE_HEADERSon purpose, re-record, and read the lint's failure message. - Snapshots (7.6): rename a field in
TriageModeland runtest_the_json_schema_sent_to_the_provider_is_stable. Read the diff, then update the snapshot on purpose. - Retries (9.2): write the async version of
test_backoff_delays_without_sleepingwithAsyncOpenAI,httpx2.AsyncClientand a patchedanyio.sleep. Does it hang iffake_sleepdoesn't await? - Streaming (8.2): add an Anthropic
thinkingblock, or a tool-call fragment sequence, tosse_fixtures.py(03.3, Part 6) and assert on the accumulated message. - Static checks (11.1): introduce a fifth mistake of your own, such as
reasoning={"effort": "hihg"}, and see whetherpyrightormypycatches it. Why (or why not)? - CI (12.2): write a third workflow, or a job, that runs
pytest -m stand_inonly when a pull request carries a label. What changes if the PR comes from a fork? - Dev cache (13.2): add the request's
anthropic-versionheader to the cache key, with a test that two versions don't collide. Then make the cache store only replies whose JSON has noerrorkey. - Async and streamed logging (4.9): write the five tests of the table in 4.9 yourself, from the description alone, with
httpx2.MockTransport, the fixtures of 8.1 and a scripted clock. Then makelogged_streamalso recordoutput_tokensfrom a running count when the stream breaks before the final message (what would the log line claim, and is it a count or an estimate?). - The logger's rules (9.4): write the other tests of the
llm_logsuite from the names in the 9.4 output: content flag and redaction, deterministic sampling, the model receiving a hash, a failing price function, unknown usage asnull, no trace-ID leak. Then re-price a logged line withusage_from_recordand a different fake price table.
Hints and what to expect
- At
OPENAI_LOG=infoa plain successful call prints nothing (the INFO lines are about retries);debugprints four short lines (building, sending, response status, request ID) and never the prompt.ANTHROPIC_LOG=debugprints thejson_dataof the request in its first line: that is where the prompt shows up. - A deny-list of
authorizationandx-goog-api-keyleaksx-acme-signing-key, the header nobody had heard of. For the async client,openai.DefaultAsyncHttpx2Client(event_hooks=make_async_event_hooks())should log exactly two events,http_requestthenhttp_response. - Dropping one turn prints 25 lines, not 2: one list-length line, and then a
contentline and aroleline for each of the 12 shifted positions, because every turn moves up one index and the roles alternate. To compare two stored cases, load both withload_caseand calldiff(a["body"], b["body"]). outcomeistruncated,finish_reasonisincomplete:max_output_tokens, and the level isWARNING(any outcome other thanokis a warning). Withcontent_sample_rate=1.0thecontentfield appears with[EMAIL]and[API_KEY]markers where the fake PII was.- The condition is
8 <= len(incoming) <= 64(together with the ASCII and alphanumeric checks). Post"a" * 65and"a" * 7: in both cases the response header must differ from what you sent and be a fresh 32-character hex ID. For the OpenAI header, copytest_openai_sends_our_trace_id_as_x_client_request_idfrom 7.3 and settrace_id_varyourself. - Both patterns can match the digits, and the first one to run replaces them, so the order of the lists matters: put the IBAN pattern before the
CARDone (or the tail of the IBAN becomes[CARD]). One more false positive: any long run of digits that is not a card (a tracking number, 4.5). - With the environment variable set and the option left out, the variable applies and spans carry content. With
open_telemetry={}the option wins and the variables are ignored, so the mode is back tometadata_only(the lesson states the rule in 4.7: a client given the option, even{}, ignores them). - For a 5% failure rate you need about 59 replays to have a 95% chance of seeing it at least once (the table in 5.5;
3 / pis the shortcut), and many more to estimate the rate itself with any precision. [invalid, valid]should leavelen(fake.calls) == 2; three invalids should stop exactly at your attempt cap (solen(fake.calls)equals the cap, and the result reports failure);[refused]should make exactly one call, because a refusal won't improve on retry. If the loop over-calls,FakeChatraises its "more times than the test scripted"AssertionError, so the test fails by itself.- No. A plain
529becomesanthropic.OverloadedError; an overload event inside a stream (after the200) raises a genericAPIStatusErrorwithstatus_code == 200in 2.4.0 (8.2). - The first test no longer gets
SocketBlockedError: the request goes out and fails to connect, because.invalidnever resolves, sopytest.raises(SocketBlockedError)fails. The second test tries the realapi.openai.comwith a fake key (a401if you are online, a connection error if not), and also fails. Timing depends on your network, which is the point of the guard. - With the cassette missing and
--block-network, nothing can be played back and nothing may be recorded, sovcrpyraisesCannotOverwriteExistingCassetteException. Re-recording against the stand-in fixes it. Withset-cookieallowed, the lint should reportresponse header 'set-cookie'(and the forbidden fragmentcookie) if the recording contained one. - Renaming
urgenttois_urgentchanges bothpropertiesandrequiredin the schema, so the unified diff shows those lines as-and+. Review it, run once withUPDATE_SNAPSHOTS=1to accept it on purpose (or revert the rename), and commit the snapshot file with the code change. - Yes: without the
await real_sleep(0)insidefake_sleep, the event loop is never given a turn and the test hangs. - For a thinking block, add a block at index 0 with a
content_block_startof typethinking, somecontent_block_deltaevents withthinking_delta, onesignature_delta, and acontent_block_stop, then move the text block to index 1.stream.text_streamyields only text, soStreamTimerstill counts the text deltas; assert onget_final_message().content, which should hold a thinking block followed by a text block (03.3, 6.1). - It depends on how the SDK types the field. In the OpenAI SDK's current source,
effortisOptional[ReasoningEffort], aLiteralofnone,minimal,low,medium,high,xhighandmax, so both checkers should report the typo (astrtyping would let it through). Check the type in your installed version (reasoningis aTypedDictinopenai.types.shared_params,ReasoningEffortinopenai.types.shared); this lesson did not run the checkers. This is the "valid-looking parameter" limit of 11.5. - Add
if: contains(github.event.pull_request.labels.*.name, 'run-standin')to the job. A fork's pull request still runs the workflow (thepull_requestevent), and the stand-in job needs no secrets, so nothing changes for it; only a maintainer can add the label. - Add
request.headers.get("anthropic-version")to the list insidejson.dumps(...)incache_key, and test that two otherwise identical requests with different versions get different keys (and that two different API keys still get the same one). For the second part, parseresponse.textas JSON before writing and skip the file when it is not an object or has anerrorkey. - Build each test from its row of the table: an
httpx2.MockTransportthat answers a429then a200for the retry test, the SSE fixtures of 8.1 for the stream tests, and a scripted clock such asiter([0.0, 0.25, 0.9]).__next__. For the running count: a chunk is not a token, so the number can only be an estimate. Log it under its own name (for exampleoutput_tokens_estimate) and leaveoutput_tokensasnull, since the provider's real count is unknown and unknown is never zero. - Each rule is a few lines with the helpers
makeandlinesand a scriptedFakeChat: a clock such asiter([0.0, 0.25]).__next__giveslatency_ms == 250;LogConfig(log_content=True)adds a redactedcontentfield, and the default has none;rng=lambda: 0.005withcontent_sample_rate=0.01logs content whilerng=lambda: 0.5does not;FakeChat.calls[0]["user"]must equalhash_user(raw, key, "llm-abuse-v1"), never the raw ID;price=lambda c: 1 / 0must still return the completion, withcost_usdnull; aCompletionwith nousagelogsnulltoken fields; andtrace_id_var.get()isNoneagain after the call. For the re-pricing, turn the logged line into aUsageonce withusage_from_record, load a second table withPriceTable.load(...), and callcost_calc.price(usage, table)with each table.
Check yourself#
- What is the first question to ask when an LLM feature gives a bad answer, and why?"What did we actually send?" Most bugs are in the request (config that didn't load, trimmed history, a moved model alias, an ignored parameter), and the request is JSON you can capture, diff and test (1.1).
- Which of
OPENAI_LOG=debugandANTHROPIC_LOG=debugcan leak your prompts, and why is each one different from the other?ANTHROPIC_LOG=debuglogs the request options including the body, so prompts appear in the log.OPENAI_LOG=debuglogs the method, status, retry decisions and request ID, and leaves the HTTP library's loggers (which may log full URLs) to your application. Both are development switches (2.1). - Why do event hooks see something that
with_raw_responseon the final call can't? - You log the request ID of a call that was retried once and succeeded. Which attempt's ID is it, and where would you find the other?The successful attempt's. The failed attempt's ID is visible to an event hook or middleware (or the debug log) and, if the call finally failed, on the exception (
exc.request_id) (2.4). - Name six fields you'd put in the structured record of every model call, and four things you wouldn't log by default.Any six of: trace ID, request ID, provider, model requested and served, latency, attempts, token counts, cost, finish reason or outcome, error class, feature, hashed user, prompt version, SDK version. Not by default: prompts and replies, keys and auth headers, raw user IDs or emails, tool arguments and results, free-text provider error messages, images and files (4.1).
- A teammate suggests hashing user IDs with plain SHA-256 before logging them. What's the weakness, and what's the alternative used here?A plain hash can be reversed by hashing a list of likely emails. A keyed hash (HMAC) with a secret key gives a stable ID that can't be rebuilt without the key, which is why
LogConfighas no default key outside dev and raises if it's missing: a default would be a key everybody knows (4.2). - Why does
LoggedChatwrite a log line for failures and then re-raise, rather than catching the error? - A test mocks an
openaicall withrespx, passes, and your cloud bill shows a request. What happened, and what are two defences?respxpatcheshttpx, butopenai3.x useshttpx2, so the mock never applied and the request went out. Defences:--disable-socketfor the whole run, and injecting anhttpx2.MockTransportthat fails on unexpected requests (and asserting the mock was used) (7.4). - Why is snapshotting the request a good idea while snapshotting the response isn't?The request is deterministic and shows up as a diff in review when a prompt, parameter or history rule changes. A response varies from run to run, so its snapshot fails for reasons unrelated to your code (7.6).
- What does a contract test against the local stand-in prove, and what can't it prove?It proves the code runs end to end through the real SDK and a real HTTP server, and parses the right shapes. It can't prove a hosted model behaves the same, that the provider accepts every parameter, or what real usage, headers and limits look like (7.7).
- Your Gemini structured-output test gets
parsed is Noneand no exception. What are three possible causes, and what should the code check first?The answer was cut off at the output cap, the model refused or the prompt was blocked, or the text didn't match the schema. Check the finish reason oroutcomebefore using.parsed(Part 10). - How do you test a 30-second backoff in a few milliseconds, with two different techniques?Make the mock server send a tiny
retry-after-ms, and/or replace the sleep with a recorder (monkeypatchoftime.sleep,anyio.sleep, ortenacity'ssleep=argument), then assert on the recorded delays and attempt counts (Part 9). - Why must a replacement for
anyio.sleepin a test await something?Because the SDK's retry code (and other code) may rely onsleepyielding to the event loop; a replacement that returns immediately without awaiting can starve the loop and hang the test. Awaitasyncio.sleep(0)(9.2). - A pull request from a fork runs your CI. Which jobs can use keys, and why is that the right behaviour?Only the offline job runs, and it needs no keys, because GitHub doesn't pass secrets to workflows triggered from forks. That protects your keys from code in untrusted pull requests (12.3).
- Name three pitfalls of a development response cache.Any three of: it hides non-determinism; it hides outages, errors and model changes; it can cache refusals and truncations; its key ignores headers; it stores user content on disk; and it isn't a production cache (13.2).
- Why is an allow-list of headers safer than a deny-list for a hook that logs requests, and what does it cost you?A deny-list hides only the names someone remembered, so an unfamiliar credential header (a gateway's
x-portkey-api-key) is logged in clear. An allow-list hides everything it doesn't recognize, so a new secret is hidden by default. The cost is that a harmless header you want to see stays hidden until you add it to the list, which is a safe way to be wrong (2.3).
Further resources#
- OpenAI, API reference overview: request IDs (
x-request-id),X-Client-Request-Id,openai-processing-ms, and the other response headers. - Anthropic, Errors (request IDs and error shapes), the Python SDK page (logging) and Set up OpenTelemetry with the Claude SDK (the
open_telemetryoption and content modes; beta as of November 2026). - Google, the Gemini API reference for
generateContent(responseId,modelVersion,labels). - OpenRouter, Broadcast (the
user,session_idandtracefields) and its API reference. - OpenTelemetry, the semantic conventions for generative AI: span, attribute and opt-in content definitions (status: development).
- SDK repositories: openai-python, anthropic-sdk-python, python-genai. Reading
_base_client.pyin each shows exactly what is logged, retried and hooked. - Testing tools: pytest, pytest-socket, vcrpy and pytest-recording, Hypothesis, syrupy (snapshot testing), respx (for
httpx, nothttpx2) and structlog. - Type checkers: pyright and mypy.
- GitHub, Using secrets in GitHub Actions and Events that trigger workflows (
schedule,workflow_dispatch,pull_request_target). - Hamel Husain, "Your AI Product Needs Evals": where this lesson stops and Module 10A begins; a well-known practitioner's argument for looking at your data and building evaluation on top of solid tests.
- IETF, RFC 6761 (special-use domain names, including
.invalid, used in therespxdemonstration).
← 03.9 — Async, Concurrency and Batch Processing | Module 03 overview | 03.11 — Building a Provider-Agnostic Client →