03.11 Building a Provider-Agnostic Client
Ten lessons have taught you to call four providers well: messages, streaming, structured output, tools, media, cost, errors, concurrency and tests. Every one of them ended with the same awkward fact: the code is different on every provider. This capstone lesson puts the module together into one small, tested package that your application calls with one request type, and that translates it to OpenAI (Responses and Chat Completions) and Anthropic (Messages), the two required adapters, plus the optional Gemini (generate_content and Interactions), OpenRouter and OpenAI-compatible local-server adapters. You will design the canonical types, write the adapters, normalize streaming, structured output, tool calls, media, reasoning, usage, cost and errors, put retries, timeouts and a simple cross-provider fallback in exactly one place, drive model choice from a YAML file, and test the whole thing with one contract suite that every adapter must pass. Then you will see how LiteLLM, any-llm, aisuite, Pydantic AI, instructor, OpenRouter and the providers' own compatibility layers solve the same problem, and decide honestly when to use them instead.
Almost nothing in this lesson is new mechanism. Each earlier lesson owns the mechanism and this lesson links to it. What is new is the design: where to draw the line between what you normalize and what you leave alone, because a bad abstraction is worse than none.
What you'll learn
- Which adapters are required. You must build and test the OpenAI adapter (Responses, and Chat Completions) and the Anthropic adapter (Messages), and prove that a request can fall back from one to the other. The Gemini, OpenRouter and local (Ollama) adapters are optional extensions of the same pattern
- When a provider-agnostic layer pays for itself, when it costs more than it earns, and the thin wrapper principle that keeps it honest
- A decision table for build vs buy vs gateway: your own wrapper, a library, a hosted gateway, a self-hosted proxy, and "OpenAI-compatible everywhere" with its real limits
- How to design canonical types (messages made of typed parts, tool specs, requests, responses, usage, finish reasons and errors), and the reasoning behind each choice
- How to write adapters as pure translation plus a thin I/O layer, for OpenAI Responses, OpenAI Chat Completions, Anthropic Messages and, as optional extras, OpenAI-compatible Chat Completions for OpenRouter and Ollama, Gemini
generate_contentand Gemini Interactions, and whygenerate_contentis the default Gemini adapter here - How to normalize the hard parts: one stream event vocabulary, structured output from a Pydantic model, tool calls with ID threading, images and PDFs, reasoning effort per model, opaque reasoning that must round-trip, and usage and cost
- A normalized error hierarchy with a
retryableflag, mapped from lesson 03.8's taxonomy, with the SDK's exception always kept as__cause__ - A capability registry in YAML: aliases (
fast,smart,vision) mapped to ordered chains of models, prices kept in one place, capability checks that fail before anything is sent, and an audit against the providers' Models APIs - Reliability in one place: who owns retries, a per-attempt timeout and a total deadline, an ordered fallback chain across providers, and what must not trigger a fallback
- Hooks for logging, cost, metrics and OpenTelemetry spans, plus request and response middleware that fails closed: a gate or redactor that crashes stops the call instead of being ignored
- How to test the wrapper: a shared contract suite (parametrized across six adapter shapes), fault-injecting tests (a hung provider, a crashing redactor, an HTTP 200 that says "failed"), mock transports for errors and streams, tests against the free local stand-in, and live smoke tests gated by keys
- How the existing libraries and gateways compare, with the same task written in each and real dependency-conflict results, and the March and October 2026 LiteLLM supply-chain compromises as a lesson about any dependency
- The migration story: moving an application from one provider to another, and what the wrapper cannot do for you
- Where the market stands in November 2026 beyond the libraries: a gateway in front of your client (what changes in the registry, the policy and the cost record), Open Responses, OpenRouter's provider-routing preferences and the model layers inside agent SDKs, with the production side left to Module 11B and Module 11C
What you don't need
- Any API key. Everything here runs against mock servers, the free local stand-in (03.1, Part 12) or pure Python. Hosted-provider samples are labelled and shown with illustrative output.
- To re-learn the mechanisms. Messages, streaming, structured output, tools, media, cost and errors are linked, not repeated.
- Production routing. Circuit breakers, health-based routing, cascades and gateways in production are Module 11B and Module 11C; this lesson builds a simple ordered fallback and previews the rest.
Setup
You need Python 3.11 or newer and uv (03.1, Part 4 has the full steps). Unlike lessons 03.1 to 03.9, which share the llm-apis project, this lesson starts its own package in a new folder, so run uv init even if you already have llm-apis. The package is written for Python 3.11 and newer (it uses nothing later) and every test and demo in this lesson was run on Python 3.12.13; --python 3.13 below is the module's default project interpreter (03.1, 4.2). The commands below name the packages without versions, so you get the newest releases. This lesson was written and checked against openai 3.42.1, anthropic 2.4.0 and google-genai 2.34.0 as of November 2026; a newer major version may change names or defaults, so check the SDK's changelog if something does not match:
uv init agnostic-client --bare --python 3.13 && cd agnostic-client # --python matters: see lesson 03.1, 4.2
# (the project is NAMED agnostic-client; the package inside it is provider_agnostic)
uv add openai anthropic google-genai pydantic pyyaml python-dotenv httpx
uv add --dev pytest pytest-asyncio # or: pip install ... with the same package namesA project that installs all three SDKs also gets tenacity 9.1.4 (google-genai 2.34.0 requires tenacity<9.2.0). The wrapper does not use it: its retry loop is 40 lines you can read in one go (Part 8), but 03.8, Part 8 shows the same policy in tenacity if you prefer it.
The package is called provider_agnostic, not llm. The obvious name is taken: llm on PyPI is Simon Willison's popular command-line tool and Python library (version 0.37.1 on 4 November 2026). Two packages with one import name in one environment means one silently shadows the other, and uv add llm would fetch his, not yours. Check the index before you name an importable package, and prefer a distinctive name even for code that will never be published (the import name is what collides, not the project name). Run curl -s -o /dev/null -w '%{http_code}' https://pypi.org/pypi/<name>/json and a 200 means the name is taken.
The package builds on files from earlier lessons. Copy them into the project root, next to the new provider_agnostic/ folder:
| File | From | Used for |
|---|---|---|
cost_calc.py, prices.py, prices.yaml |
03.7, Parts 3 and 4 | turning usage into dollars; the single price table |
llm_errors.py, retry_after.py, check_response.py |
03.8, Part 4 and Part 10 | classify(): reading any SDK's exception; check_response(): spotting an error inside an HTTP 200 |
weather_tools.py |
03.5, 2.1 | example tools for the tool-call demos |
These are copies of the final files from those lessons. If you copied them earlier, copy them again: 03.7 added service tiers, 12-hour cache writes and fast mode to cost_calc.py, and 03.8 added the httpx2 exception families and the "maximum context length" hint to llm_errors.py, all of which this package relies on. retry_after.py has since been corrected too: an HTTP-date Retry-After with no zone (or -0000) is read as UTC, not in the machine's local time zone, so a copy made before that fix can wait the wrong time on a non-UTC machine.
Your .env file holds the keys, as always (OPENAI_API_KEY, ANTHROPIC_API_KEY, GEMINI_API_KEY, OPENROUTER_API_KEY); none of the runnable parts below need them. For the free practice path, start Ollama, then source localstack/env.sh: this lesson's appendix provides the small localstack/env.sh file; 03.1, Part 12 explains the stand-in itself and walks through the same setup by hand. The stand-in is Ollama alone, so the OpenAI Responses, OpenAI Chat Completions and Anthropic Messages routes run locally, while the Gemini routes are hosted-only (Ollama does not speak Gemini's API: 03.1, 12.4) and are tested with mocks here. The stand-in registry reads one variable of its own, LOCAL_API_KEY (any value, or unset: Ollama ignores it), and deliberately never OPENAI_API_KEY, ANTHROPIC_API_KEY or GEMINI_API_KEY: a real hosted key in your .env must not be sent to a server on localhost.
What you must be able to do after this lesson#
- Decide whether to abstract providers at all
- Define canonical types for requests and responses
- Write an adapter for a provider
- Map provider errors to one error hierarchy
- Add retries, logging and cost hooks in one place
- Test the wrapper against a local stand-in
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
| "Let's add a fallback to Claude in case OpenAI is down." | Part 8 |
| "Should we use LiteLLM, or build our own?" | Part 1, Part 13 |
| "Why did our retries make the outage worse?" | 8.1 One layer owns retries |
| "The provider hung and the fallback never kicked in." | 8.2 Timeouts and the deadline |
| "Our redaction hook crashed and the prompt went out anyway." | Part 9 |
"The response said failed, and we treated it as a success." |
Part 6 |
| "The wrapper swallowed the error, and now we can't open a ticket." | Part 6 |
| "Switch the summarizer to the cheaper model: it is a config change, right?" | Part 7, Part 14 |
| "It works on OpenAI but returns a 400 on Claude." | 7.3 Capability checks |
| "Our cost dashboard says zero for the new model." | 5.6 Usage and cost |
| "We pinned LiteLLM after that supply-chain thing." | 13.2 LiteLLM, 13.9 Dependency hygiene |
| "We already have a gateway: do we still need a client?" | 13.8b |
| "Is the OpenAI-compatible endpoint good enough for production?" | 1.4 Build, buy or gateway, 13.7 Compatibility layers |
| "How do we test code that calls four APIs?" | Part 11 |
Part 1: Should you abstract at all?#
1.1 What a provider-agnostic layer buys you#
| Reason | What it looks like in practice |
|---|---|
| Resilience | OpenAI returns 503s for twenty minutes; the same request is answered by Claude. Every provider has outages and rate-limit spikes (02.9, 10.5), and a second model from the same provider often shares the outage |
| Cost routing | The classifier runs on the cheap tier, the hard question on the strong one, and a price change on one provider moves traffic by editing a file |
| Testing | One fake adapter stands in for all four providers in unit tests; one contract suite proves every adapter behaves the same (Part 11) |
| Vendor leverage | A migration that takes an afternoon is a negotiating position. A codebase with openai. calls in 140 files is not |
| One place for the boring work | Logging with request IDs, cost per call, timeouts, retries and error mapping written once, not once per call site and per provider |
| A smaller surface to learn | Application code deals with Request and Response. Only the adapters know that Claude puts tool_result blocks first or that Gemini calls the assistant model |
1.2 What it costs#
| Cost | Why it bites |
|---|---|
| Lowest common denominator | A shared interface can only expose what every provider offers. Provider features (Anthropic's cache breakpoints, OpenAI's prompt_cache_key, Gemini's explicit caches, OpenRouter's routing) don't fit one shape |
| Leaky abstractions | "Same" parameters don't behave the same: a max_output_tokens that includes reasoning on one provider and not on another, a "required" tool choice that is a 400 on some Claude models. Joel Spolsky's law of leaky abstractions applies in full |
| Day-one features | A provider ships a feature on Tuesday. With the official SDK you use it on Tuesday. Through a wrapper you wait for the wrapper |
| Maintenance | Four SDKs, each releasing weekly, each with breaking changes (this module names the SDK versions it was checked against because openai 3.0 and anthropic 2.x moved to httpx2, 03.1, 4.5). Someone owns that work |
| The debugging tax | When a call misbehaves, you now debug your layer and the SDK and the provider. The question "what did we actually send?" gets harder to answer |
| Hidden quality differences | Switching the model in config does not switch the prompt, the evals or the caching strategy. An abstraction that makes switching look free is dangerous (Part 14) |
1.3 The thin-wrapper principle#
The design in this lesson follows four rules. They are the reason the package is about 3,000 lines and not 30,000.
- Normalize the 80% you use everywhere. Text, images and PDFs in; text, tool calls and structured objects out; usage, finish reasons, request IDs and errors. Everything else stays provider-native.
- Keep an explicit escape hatch.
Request.extracarries provider-specific fields, keyed by provider name so a fallback never sends an OpenAI-only field to Gemini.Response.rawis the SDK's own object, untouched. Prompt caching, for example, is deliberately not abstracted: its semantics differ too much (03.7), so you reach it throughextra(the recipes in 3.2 show working shapes).extrais merged into what the adapter built, never allowed to replace the model, the messages or the stream flag. - Never silently drop an option. If a route can't do what the request asks (a forced tool call on a model that returns a 400, an image URL on a server that can't fetch it, a schema where structured output isn't enforced, a stop sequence on an API that has no such parameter,
parallel_tool_calls=Falsewhere there is no switch), the wrapper raises before sending anything. A silent drop turns a loud bug into a quiet quality problem. This rule is not a slogan: a test sets every field ofRequeston every route and fails unless the value is on the wire or the route refuses it (7.3). The first version broke the rule twice (stopon the Responses API andparallel_tool_callson Gemini were dropped without a word) and only that test found it. - Never hide the provider's own facts. The raw finish reason travels beside the normalized one. The provider's request ID is on every
Responseand every error. The SDK's original exception is__cause__of ours. Normalizing loses information, so the original must stay reachable.
1.4 Build, buy or gateway#
There are five ways to get "one API for many providers". They are not equivalent, and the right one depends on your constraints more than on taste.
| Option | What it is | Strengths | Weaknesses | Choose it when |
|---|---|---|---|---|
| Your own thin wrapper (this lesson) | ~3,000 lines of Python over the official SDKs | Exactly the features you use; official SDK behaviour; you can read all of it; no new supply-chain risk; tests you control | You maintain it; each new provider feature is your work | 2 to 4 providers, text, tools and JSON are 90% of the calls, and you want to understand every byte |
| A library (LiteLLM, any-llm, aisuite, Pydantic AI, instructor) | Someone else's wrapper, as a dependency | Wide coverage immediately; community fixes new providers | Another dependency tree (conflicts, 13.9); some make their own HTTP calls instead of using the official SDKs and can lag or drift; its abstractions are not yours | Many providers, fast changes, small team, and a library's lowest common denominator is acceptable |
| A hosted gateway (OpenRouter) | One endpoint, one key, many models, routing and fallbacks on the provider's side | Zero code for routing; one bill; wide model catalogue | A third party sees your prompts (a data processor, 02.9, 5.4); a fee; its own outages and its own error shapes | Prototypes, long-tail models, and teams that want to buy convenience |
| A self-hosted proxy (LiteLLM proxy, an internal gateway) | A server you run that speaks one API and fans out | Central keys, budgets, logging for many apps and languages; nothing leaves your network except to the providers | You operate a critical server; it is also a dependency and an attack surface (13.2) | Several services or teams, several languages, and a platform team |
| "OpenAI-compatible everywhere" | Point the openai SDK at another base URL (Gemini's /v1beta/openai/, Ollama, vLLM, OpenRouter) |
The least code of all; works today | "Compatible" covers the URL and the JSON envelope, not the features (13.7); the providers call their own layers beta or "not a production solution" | Evaluating models, local development, and servers that really are OpenAI clones |
flowchart TD
start["I call LLMs from my app"] --> q1{"One provider,<br/>and that is final?"}
q1 -->|"yes"| native["Use the official SDK directly.<br/>Add your own retry and logging helpers"]
q1 -->|"no"| q2{"Do you need to run the<br/>models inside your own network?"}
q2 -->|"yes"| proxy["Self-hosted proxy<br/>(LiteLLM proxy, an internal gateway)"]
q2 -->|"no"| q3{"Is a third party allowed to see<br/>your prompts, and a fee fine?"}
q3 -->|"yes, and I want one API"| hosted["Hosted gateway<br/>(OpenRouter)"]
q3 -->|"no, or I want full control"| q4{"Do you mostly need plain text,<br/>tools and JSON, on 2 to 4 providers?"}
q4 -->|"yes"| own["Your own thin wrapper<br/>(this lesson)"]
q4 -->|"no: dozens of providers,<br/>or a feature every week"| lib["A library<br/>(LiteLLM, any-llm, Pydantic AI)"]Two honest observations. First, the options compose: this lesson's wrapper has an OpenAI-compatible adapter and an OpenRouter adapter inside it, and a LiteLLM proxy can sit behind it as one more route. Second, the wrapper is a decision about where your code touches the providers, not about whether it does. You still need to read each provider's documentation. The wrapper just means you read it once, in one file.
1.5 What this lesson builds#
flowchart TB
app["Your application code"] --> client
subgraph pkg ["provider_agnostic package"]
client["LLMClient<br/>retries, deadline, fallback, hooks<br/>(middleware fail-closed)"]
reg["Registry<br/>aliases, capabilities, limits"]
types["Canonical types<br/>Request, Message, Part, Response, errors"]
client --- reg
client --- types
subgraph adapters ["Adapters (pure translation plus thin I/O)"]
a1["responses"]
a2["chat<br/>OpenAI, OpenRouter, Ollama"]
a3["messages"]
a4["generate_content"]
a5["interactions"]
end
client --> adapters
end
a1 --> sdk1["openai SDK"]
a2 --> sdk1
a3 --> sdk2["anthropic SDK"]
a4 --> sdk3["google-genai SDK"]
a5 --> sdk3
sdk1 --> http["HTTPS to the provider,<br/>or to the local stand-in, or to a mock"]
sdk2 --> http
sdk3 --> httpThe package is small on purpose, and every file has one job:
| File | Job | Lesson that owns the mechanism |
|---|---|---|
provider_agnostic/types.py |
Canonical types: parts, messages, tool specs, requests, responses, usage, finish reasons, stream events | 03.2, 03.5 |
provider_agnostic/errors.py |
The error hierarchy and the mapping from SDK exceptions | 03.8 |
provider_agnostic/registry.py, provider_agnostic/models.yaml |
Aliases, ordered chains, capabilities, limits, the capability checks | 02.9, 03.1 |
provider_agnostic/schemas.py |
Strict JSON Schema for each provider's structured output and tools | 03.4 |
provider_agnostic/adapters/*.py |
One adapter per API: pure build() / parse() / stream parser, thin I/O |
03.2 to 03.6 |
provider_agnostic/client.py |
LLMClient: retries, timeouts, deadline, fallback, hooks, sync and async |
03.8, 03.9 |
provider_agnostic/hooks.py, provider_agnostic/redact.py, provider_agnostic/cost.py |
Hooks (logging, cost file, metrics, OpenTelemetry, redaction); the redactor and keyed user hash; usage to dollars | 03.7, 03.10 |
provider_agnostic/refresh.py |
Audit the registry against the Models APIs | 03.1 |
tests/ |
Fake servers, the contract suite, stand-in tests | 03.10 |
Part 2: The shape of the package#
Deep-dive
Two design decisions shape everything else, so they come first.
Decision 1: an adapter is pure translation plus a thin I/O layer. Every adapter implements three pure functions and four tiny I/O methods:
| Method | Network? | Why separate | |
|---|---|---|---|
| Pure | build(request) -> kwargs |
no | You can print exactly what would be sent ("show the wire", 4.6) and unit-test it with no mock server |
| Pure | parse(sdk_response) -> Response |
no | Fixtures from the provider's docs become tests |
| Pure | new_stream() returns a parser with feed(event) and finish() |
no | The messiest code in the package becomes a state machine you can feed events by hand |
| I/O | send, asend, open_stream, aopen_stream |
yes | One or two lines each, over the official SDK; sync and async share everything above |
Decision 2: the wrapper uses the official SDKs. It does not reimplement HTTP calls. You keep each SDK's authentication, request building, streaming parsers and bug fixes, and the wrapper stays small. The price is the SDKs' dependency tree, which you already have.
One client is shared. Build one LLMClient per process and share it between threads and between tasks on an event loop: the adapters (and the SDK clients, with their connection pools) are created lazily under a lock, so two threads racing on the first call cannot build two clients and leak one. Close it once, with with or await client.aclose().
The retry and fallback logic lives in LLMClient alone. The SDK clients are built with max_retries=0 (and no retry_options on Gemini's models.*), so exactly one layer retries (03.8, 5.5).
Part 3: Canonical types#
3.1 Parts and messages#
A canonical message has a role and a list of typed parts, because every provider's native format does (03.2, Part 3). A plain content: str would be simpler, and would break the first time a model returns a tool call next to text, or a Claude thinking block next to both.
# provider_agnostic/types.py (1 of 4): parts and messages. Nothing in this file imports a provider SDK.
class Native(BaseModel):
"""A provider's own serialization of a part, kept so it can be replayed verbatim."""
provider: str # "openai" | "anthropic" | "gemini" | "openrouter" | "local" ...
api: str # "responses" | "chat" | "messages" | "generate_content" | "interactions"
payload: dict[str, Any]
class _Part(BaseModel):
native: Native | None = None # replayed only when provider AND api match the adapter
class TextPart(_Part):
type: Literal["text"] = "text"
text: str
class ImagePart(_Part):
type: Literal["image"] = "image"
media_type: str # "image/png"
data_b64: str | None = None # inline bytes, base64
url: str | None = None # https URL (not every provider fetches URLs: see capabilities)
detail: Literal["auto", "low", "high"] = "auto" # OpenAI-style hint; others ignore it
class DocumentPart(_Part):
type: Literal["document"] = "document"
media_type: str = "application/pdf"
data_b64: str
filename: str = "document.pdf"
class ToolCallPart(_Part):
type: Literal["tool_call"] = "tool_call"
id: str # the ID the result must echo: opaque, never parsed
name: str
arguments: dict[str, Any] # always a parsed dict: OpenAI's JSON string is parsed once, here
arguments_error: str | None = None # set when the model sent invalid JSON (the raw text is in native)
class ToolResultPart(_Part):
type: Literal["tool_result"] = "tool_result"
call_id: str # == ToolCallPart.id
name: str # Gemini matches results by name as well
content: str
is_error: bool = False
class ReasoningPart(_Part):
"""Opaque reasoning that must round-trip. `text` is a human-readable summary, if the
provider gave one. It is NOT enough to replay: `native` is."""
type: Literal["reasoning"] = "reasoning"
text: str | None = None
Part = Annotated[TextPart | ImagePart | DocumentPart | ToolCallPart | ToolResultPart | ReasoningPart,
Field(discriminator="type")]
class Message(BaseModel):
role: Literal["user", "assistant", "tool"]
parts: list[Part]
@classmethod
def user(cls, text: str) -> "Message":
return cls(role="user", parts=[TextPart(text=text)])
@classmethod
def assistant(cls, text: str) -> "Message":
return cls(role="assistant", parts=[TextPart(text=text)])
@classmethod
def tool_results(cls, *results: ToolResultPart) -> "Message":
return cls(role="tool", parts=list(results))
@property
def text(self) -> str:
return "".join(p.text for p in self.parts if isinstance(p, TextPart))Each choice has a reason:
| Choice | Reason |
|---|---|
| Pydantic models, not dataclasses | These are data that crosses boundaries: saved to a conversation store, logged, sent to a worker. Pydantic gives you model_dump_json(), validation on load, and a discriminated union (type decides the class), so Message.model_validate_json(...) rebuilds the right part classes |
Three roles: user, assistant, tool |
Providers disagree on where tool results live: a tool role, a user message with tool_result blocks, a function_call_output item, a function_result step (03.5, Part 16). One canonical home, translated at the edge. The system prompt is not a message: it is Request.system, because Anthropic and Gemini treat it that way (03.2, Part 2) |
Tool-call arguments is always a dict |
OpenAI sends a JSON string, the others a parsed object (03.5, 5.2). Parse once, at the edge. If the model sent invalid JSON, arguments is {} and arguments_error says why, so the caller can return the error to the model as a tool result instead of crashing |
ToolResultPart carries name as well as call_id |
Gemini matches function responses by name and order when it sends no call ID (03.5, 5.3); the other providers ignore the name |
native: every part can carry its provider-native twin |
The most important field in the file. See below |
ImagePart has data_b64 or url |
Both are real routes (03.6, 1.4). File IDs are provider-specific and go in extra |
The native twin. Some provider output must go back exactly as received for the conversation to continue correctly: OpenAI reasoning and function_call items (with their fc_ IDs), Anthropic thinking blocks with their signatures, Gemini parts with thought_signature, OpenRouter reasoning_details (02.8, 8.2). The canonical fields are not enough to rebuild them. So an adapter that parses a response stores the provider's own serialization in part.native, tagged with provider and api, and an adapter that builds a request replays it only when both tags match its own. A Claude thinking block sent to OpenAI is simply dropped. That one rule is how opaque reasoning survives a tool loop on one provider and never leaks to another (5.5).
3.2 Tools and the request#
# provider_agnostic/types.py (2 of 4): tools and the request
class ToolSpec(BaseModel):
name: str
description: str
parameters: dict[str, Any] # JSON Schema for the arguments
strict: bool = False # ask the provider to enforce the schema, where it can
@classmethod
def from_model(cls, model: type[BaseModel], *, strict: bool = False) -> "ToolSpec":
"""Name = class name, description = docstring, parameters = the Pydantic JSON Schema."""
return cls(name=model.__name__, description=(model.__doc__ or "").strip(),
parameters=model.model_json_schema(), strict=strict)
class ForcedTool(BaseModel):
name: str
ToolChoice = Literal["auto", "required", "none"] | ForcedTool
Effort = Literal["off", "low", "medium", "high"] # "minimal", "xhigh" and "max" exist on some models: use `extra`
TAG_KEY = re.compile(r"[a-z][a-z0-9_]{0,31}") # metadata keys: lower_snake_case, at most 32 characters
MAX_TAGS = 16
MAX_TAG_VALUE = 128
class Request(BaseModel):
"""Everything an application may ask for, in provider-neutral words."""
model_config = ConfigDict(arbitrary_types_allowed=True)
model: str # an ALIAS from models.yaml ("fast"), or a model key
messages: list[Message]
system: str | None = None
max_output_tokens: int | None = None # None = the registry's default for this model
tools: list[ToolSpec] = Field(default_factory=list)
tool_choice: ToolChoice = "auto"
parallel_tool_calls: bool | None = None # None = provider default
output_schema: type[BaseModel] | None = None # structured output
reasoning_effort: Effort | None = None # None = provider default
stop: list[str] = Field(default_factory=list)
metadata: dict[str, str] = Field(default_factory=dict) # app-level labels, e.g. feature, user hash
timeout_s: float | None = None # per attempt; None = the client's policy
extra: dict[str, dict[str, Any]] = Field(default_factory=dict)
# ^ escape hatch, keyed by PROVIDER NAME so a fallback never sends OpenAI-only fields to Gemini:
# extra={"openai": {"service_tier": "flex"}, "openrouter": {"extra_body": {"provider": {"sort": "price"}}}}
# Dicts are MERGED into what the adapter built (extra wins on scalars); model, messages and stream are reserved.
@field_validator("metadata")
@classmethod
def _tags_are_safe_to_log(cls, tags: dict[str, str]) -> dict[str, str]:
"""Metadata lands in every log line and cost record: keep keys boring and values short (lesson 03.10, 4.1)."""
if len(tags) > MAX_TAGS:
raise ValueError(f"at most {MAX_TAGS} metadata tags")
for key, value in tags.items():
if not TAG_KEY.fullmatch(key):
raise ValueError(f"metadata key {key!r} must match {TAG_KEY.pattern}")
if len(value) > MAX_TAG_VALUE:
raise ValueError(f"metadata value for {key!r} is longer than {MAX_TAG_VALUE} characters")
return tagsToolSpec.from_modelmakes the Pydantic class the single source of truth for a tool's schema, as 03.5, 2.1 does.tool_choicehas four intents (auto,required,none, one named tool). Each adapter translates them (anyon Claude,ANYon Gemini). Some models reject forced choices, which the registry records (Part 7).- There are no sampling parameters. Current frontier models reject or ignore
temperatureandtop_p(02.5, Part 6), and Claude API version 2026-10-21 returns a 400 for them. A canonical field every adapter would have to refuse is worse than none. If you run a model that takes them, they go inextra. max_output_tokensis optional here and required on the wire. Anthropic requiresmax_tokens; the registry'sdefault_max_output_tokensfills the gap for every provider, so no call is ever unbounded (03.7, 12.1).reasoning_effortisoff,low,mediumorhigh: one app-level setting, translated per model (5.5).metadatanever goes to a provider. It is for your logs and cost records (feature name, hashed user ID), delivered to the hooks. It is validated when theRequestis built (at most 16 keys,lower_snake_case, at most 32 characters, values at most 128 characters) and scrubbed of credential and card shapes before any hook sees it, because it is copied into every log line and cost record. Put a keyed hash of the user ID there, never the ID or an email:hash_user(user_id)inredact.pyis the keyed hash of 03.2, 10.3: an HMAC-SHA256 overpurpose:user_idwith a secret fromUSER_ID_PEPPERand no default key (a missing key raisesConfigError, as 03.10 requires: 4.1). Its default purpose is"logs-v1", for your own logs and cost records. Provider-side identifiers (safety_identifier, Anthropic'smetadata.user_id) differ in meaning and shape (03.2, Part 10; the mapping per provider is in 03.2, 9.1), so they go throughextra, and the value there should come from the same function withpurpose="llm-abuse-v1", so a provider's abuse report can't be matched to your logs.extrais keyed by provider name, and it is merged.extra={"openai": {"service_tier": "flex"}}reaches OpenAI and nobody else. That is what makes the escape hatch fallback-safe. Nested dicts are deep-merged into what the adapter built andextrawins on scalars, soextra={"anthropic": {"output_config": {"effort": "max"}}}keeps the structured-outputformatthat sits in the sameoutput_config(the first version's shallow{**params, **extra}deleted it without a word, and replacedreasoning.effortand Gemini'sthinking_configthe same way).model,messages(orinput) andstreamare reserved: setting them raisesUnsupportedFeature, because that would change what the caller asked for. A test pins both rules.extrarecipes. Each row is a working shape, pinned bytest_caching_and_other_extra_recipes_reach_the_wire(the parameter names are checked against the SDK signatures in the versions named in Setup):
| You want | extra= |
Why it is here and not a canonical field |
|---|---|---|
| Anthropic automatic prompt caching | {"anthropic": {"cache_control": {"type": "ephemeral"}}} |
A top-level cache_control is accepted for automatic caching (Anthropic's prompt-caching page; 03.7) |
| OpenAI cache routing, abuse identifier, flex tier | {"openai": {"prompt_cache_key": "support-bot-v3", "safety_identifier": "u-3f9a", "service_tier": "flex"}} |
OpenAI-only semantics (03.7, Part 7, 03.2, 9.1) |
OpenAI reasoning summaries (so ReasoningDelta has text) |
{"openai": {"reasoning": {"summary": "auto"}}} |
Merged with the effort the adapter set; not requested by default because some accounts need verification for it |
Claude effort max, an effort the Effort literal lacks |
{"anthropic": {"output_config": {"effort": "max"}}} (with reasoning_effort="high") |
The canonical scale stops at high; minimal, xhigh and max exist only on some models |
| OpenRouter provider routing | {"openrouter": {"extra_body": {"provider": {"sort": "price"}}}} |
OpenRouter-only field, not in the SDK's types (03.4, 3.6) |
| Gemini explicit cache | {"gemini": {"cached_content": "cachedContents/abc"}} |
A GenerateContentConfig field; a generate_content feature (03.7, 8.2) |
output_schemais a Pydantic class. The adapter picks the provider's native mechanism (5.2).
3.3 Responses, finish reasons, usage and cost#
# provider_agnostic/types.py (3 of 4): what comes back
class FinishReason(str, enum.Enum):
STOP = "stop" # natural end or stop sequence
LENGTH = "length" # hit max_output_tokens
CONTEXT_FULL = "context_full" # the context window filled up (Anthropic)
TOOL_CALLS = "tool_calls" # the model wants tools run
CONTENT_FILTER = "content_filter" # a safety system blocked the prompt or the answer
REFUSAL = "refusal" # the model declined
PAUSED = "paused" # Anthropic pause_turn: send it back to continue
ERROR = "error" # failed inside a 200 (status failed, malformed call...)
OTHER = "other" # a value we have no mapping for: look at raw_finish_reason
class Usage(BaseModel):
"""The same numbers as lesson 03.7's `cost_calc.Usage` (the adapters build it by calling `cost_calc.from_*`),
under the field names of 03.7's and 03.10's cost log: uncached_input_tokens EXCLUDES cache reads and writes;
output_tokens INCLUDES reasoning."""
uncached_input_tokens: int = 0 # billed at the plain input rate (03.7's `input`)
cached_input_tokens: int = 0 # cache reads (03.7's `cached_input`)
cache_write_tokens: dict[str, int] = Field(default_factory=dict) # lifetime -> tokens (the logs sum it)
output_tokens: int = 0
reasoning_tokens: int = 0 # informational: already inside output_tokens
tier: str = "standard" # standard | batch | flex | fast | ultrafast | priority (what SERVED the call)
geo: str | None = None # Anthropic inference_geo: priced at a multiplier
regional: bool = False # OpenAI data-residency endpoint: priced at an uplift
web_searches: int = 0 # server-side web searches: billed per 1,000, on top of tokens
grounding_searches: int = 0 # Gemini grounding queries
modality_input: dict[str, int] = Field(default_factory=dict) # uncached input by non-text modality
reported_cost_usd: float | None = None # OpenRouter's usage.cost: trust it over our arithmetic
@property
def total_input_tokens(self) -> int:
"""Every prompt token, however it was billed. `total - cached - written == uncached_input_tokens` (lesson 03.7, 3.1)."""
return self.uncached_input_tokens + self.cached_input_tokens + sum(self.cache_write_tokens.values())
class Cost(BaseModel):
usd: float | None # None = unknown. Never 0 for "we couldn't price it"
source: Literal["computed", "provider", "unknown"]
price_version: str | None = None
class Attempt(BaseModel):
"""One try at one model: what the retry/fallback layers did, for logs and for tests."""
model_key: str
provider: str
api: str
n: int # 1-based attempt number for this model
ok: bool
error_type: str | None = None
status: int | None = None
request_id: str | None = None
latency_ms: int = 0
usage: "Usage | None" = None # set when the attempt got a response, even one we then discarded
cost_usd: float | None = None # ...so a discarded (billed) response is still visible in the totals
class Response(BaseModel):
model_config = ConfigDict(arbitrary_types_allowed=True)
parts: list[Part]
finish_reason: FinishReason
raw_finish_reason: str | None # the provider's own word: "end_turn", "STOP", "incomplete:max_output_tokens"
usage: Usage | None # None = unknown (a broken stream), never a silent zero
cost: Cost | None = None
provider: str
api: str
model_key: str = "" # the registry entry that served it
requested_model: str = "" # what the caller asked for (an alias)
resolved_model: str | None = None # what the provider says it ran: often a dated snapshot
request_id: str | None = None # the PROVIDER's ID for support tickets: the x-request-id header when it sends one
provider_response_id: str | None = None # the ID in the body (resp_..., msg_..., chatcmpl-..., Gemini's responseId)
call_id: str = "" # OUR ID for the whole call, fallbacks included (hooks and logs use it)
latency_ms: int = 0
attempts: list[Attempt] = Field(default_factory=list)
parsed: BaseModel | None = None # set when output_schema was requested and validated
raw: Any = Field(default=None, exclude=True, repr=False) # the SDK's own response object
@property
def text(self) -> str:
return "".join(p.text for p in self.parts if isinstance(p, TextPart))
@property
def tool_calls(self) -> list[ToolCallPart]:
return [p for p in self.parts if isinstance(p, ToolCallPart)]
@property
def reasoning(self) -> str:
return "".join(p.text or "" for p in self.parts if isinstance(p, ReasoningPart))
@property
def message(self) -> Message:
"""The assistant turn, ready to append to the history (natives included)."""
return Message(role="assistant", parts=list(self.parts))The finish reason is an enum, and the original travels with it. Every provider's value maps onto nine canonical ones, following 02.5, 4.5:
| Canonical | OpenAI Responses | OpenAI Chat / OpenRouter | Anthropic | Gemini generate_content |
Gemini Interactions |
|---|---|---|---|---|---|
STOP |
completed |
stop |
end_turn, stop_sequence |
STOP |
completed |
LENGTH |
incomplete + max_output_tokens |
length |
max_tokens |
MAX_TOKENS, CONTINUATION (stopped at the per-request limit, not finished; the SDK hides it by default, you see it with automatic_continuation=False: 03.3, 4.5b) |
incomplete |
CONTEXT_FULL |
(arrives as LENGTH) |
(arrives as LENGTH) |
model_context_window_exceeded |
(arrives as LENGTH) |
not documented |
TOOL_CALLS |
a function_call item |
tool_calls |
tool_use |
STOP plus a function-call part |
a function_call step |
CONTENT_FILTER |
incomplete + content_filter |
content_filter |
no equivalent | SAFETY, PROHIBITED_CONTENT, BLOCKLIST, SPII, RECITATION, LANGUAGE, image variants; a blocked prompt |
no documented signal |
REFUSAL |
a refusal content part |
message.refusal |
refusal |
(a block, see above) | no documented signal |
PAUSED |
n/a | n/a | pause_turn |
n/a | n/a |
ERROR |
n/a: failed and cancelled are raised (6) |
n/a: error is raised |
n/a | MALFORMED_FUNCTION_CALL, UNEXPECTED_TOOL_CALL, TOO_MANY_TOOL_CALLS, OTHER |
n/a: failed, cancelled and budget_exceeded are raised |
OTHER |
anything unmapped | anything unmapped | anything unmapped | anything unmapped | anything unmapped |
Three things about this table matter more than the table:
-
Normalizing loses information.
STOPhides that Gemini saysSTOPfor a stop sequence and for a natural end, and that an OpenAI refusal arrives with statuscompleted. SoResponse.raw_finish_reasonkeeps the provider's own word (end_turn,STOP,completed,incomplete:max_output_tokens) next to the enum. When a result surprises you, the raw value is the first thing to read. -
The mapping is a decision, and
OTHERis the honest default. An unknown value must not be coerced toSTOP: that would make a new failure mode look like success.OTHERplus the raw value gets logged and noticed. -
A
Responseis returned for every HTTP 200 that carries an answer, including a refusal or a truncation. An HTTP 200 whose body says the response failed is not an answer: it is raised as an error and retried when its code is transient (Part 6).ERRORis left for the Gemini finish reasons that come with a candidate (a malformed function call), so you can opt into falling back on them.Whether a refusal or a truncation is an error is your application's decision: for a summarizer
LENGTHmay be fine; for a JSON extractor it is a failure.raise_for_finish(response)turns the bad ones into exceptions when you want that (Part 6).
Usage uses one convention, written down. Providers count differently (02.2, 6.6). Usage carries exactly the numbers of 03.7's cost_calc.Usage, under the field names of the cost log in 03.7 and 03.10: uncached_input_tokens (03.7's input), cached_input_tokens (its cached_input, the cache reads), cache_write_tokens (its cache_writes: a dict from lifetime to tokens here, because the lifetimes are priced differently; the log records add it up into one number), output_tokens and reasoning_tokens, plus the read-only property total_input_tokens. The adapters get them by calling 03.7's cost_calc.from_* functions on the SDK object, not by redoing the arithmetic: uncached_input_tokens excludes cache reads and writes, output_tokens includes reasoning, and reasoning_tokens is informational. There is no bare input_tokens: on the providers' own objects it means different things (OpenAI and Gemini include the cached part, Anthropic excludes it), so this type does not use the name. 03.2's chatfmt.py is not superseded, it just keeps a different number on purpose: its store keeps the total input (input_tokens there is uncached + cached + written), so a conversation's size is comparable across providers. The two are one subtraction apart, uncached_input_tokens = total - cached - written, and Usage.total_input_tokens gives 03.2's number back. Pick one convention per codebase, write it where the type is defined, and test it: the parity test in Part 11 checks every adapter against 03.7's calculator.
The modifiers that change the price travel on Usage too, because they are billed on top of tokens: tier (standard, batch, flex, fast, ultrafast, priority: the tier that served the call), geo (Anthropic's inference_geo, 1.1x), regional (OpenAI's data-residency uplift), web_searches and grounding_searches (per-query fees), modality_input, and cache writes split by lifetime (5m, 1h, 30m, 12h). The first version's own arithmetic ignored fast mode (2x), inference_geo, web searches, ultrafast (6x) and 12-hour cache writes, and hard-coded one write lifetime per provider, so a cost dashboard fed from it would have been quietly low. Gemini's tier comes from the x-gemini-service-tier response header (usage_metadata.traffic_type is not supported on the Developer API). None means unknown, never zero. A broken stream has no usage, and recording 0 would make the dashboard lie. The same goes for Cost.usd.
Identifiers stay visible, and mean one thing. Response.request_id is the ID a support ticket needs (03.8, Part 12): the x-request-id / request-id header when the provider sends one, on streams as well as plain calls (the first version reported the body's object ID, msg_..., on streams, which support cannot look up). Google sends no such header, so for Gemini it is the responseId. Response.provider_response_id is always the ID in the body (resp_..., msg_..., chatcmpl-...). Response.call_id is yours, one per complete() call, shared by every attempt and every fallback, so a log search for one user action finds all of it. resolved_model is what the provider says it ran, often a dated snapshot, which is what you record when output quality changes mysteriously (02.9, Part 8). attempts lists every try. raw is the SDK's own response object, excluded from serialization.
3.4 Stream events#
# provider_agnostic/types.py (4 of 4): stream events
class TextDelta(BaseModel):
type: Literal["text_delta"] = "text_delta"
text: str
class ReasoningDelta(BaseModel):
type: Literal["reasoning_delta"] = "reasoning_delta"
text: str
class ToolCallStart(BaseModel):
type: Literal["tool_call_start"] = "tool_call_start"
index: int
id: str
name: str
class ToolCallDelta(BaseModel):
type: Literal["tool_call_delta"] = "tool_call_delta"
index: int
arguments_fragment: str # a JSON FRAGMENT: parse only the finished call
class UsageEvent(BaseModel):
type: Literal["usage"] = "usage"
usage: Usage # cumulative: the latest replaces the earlier ones
class Done(BaseModel):
type: Literal["done"] = "done"
response: Response # the fully assembled response, same type as complete()
class StreamError(BaseModel):
type: Literal["error"] = "error"
error_type: str
message: str
retryable: bool
StreamEvent = TextDelta | ReasoningDelta | ToolCallStart | ToolCallDelta | UsageEvent | Done | StreamErrorA stream is a sequence of these. The last event on success is always Done, carrying the same Response type that complete() returns, so code that handles a final answer doesn't care how it arrived. Text, reasoning and tool-argument fragments arrive as deltas. Usage is cumulative: the latest event replaces earlier ones, never add them. Tool-argument fragments are JSON pieces you can only parse when the call is complete, which the Done response has already done for you (03.3, Part 5). 5.1 shows the machinery. (StreamError is part of the vocabulary for consumers that forward events to a browser, 03.3, Part 11; the client itself raises exceptions instead.)
3.5 Try it: the types, with no network#
"""s3_types_demo.py: the canonical types in action (layer 1: pure Python, no network, no key)."""
from pydantic import BaseModel
from provider_agnostic import (FinishReason, ForcedTool, Message, Native, ReasoningPart, Request, Response, TextPart, ToolCallPart,
ToolResultPart, ToolSpec, Usage)
class GetWeather(BaseModel):
"""Get the current weather for one city."""
city: str
# 1. A conversation with a tool round trip, in canonical form
history = [
Message.user("What is the weather in Paris?"),
Message(role="assistant", parts=[
ReasoningPart(text="I need the weather tool.",
native=Native(provider="anthropic", api="messages",
payload={"type": "thinking", "thinking": "I need the weather tool.", "signature": "EqQB..."})),
ToolCallPart(id="toolu_01A", name="GetWeather", arguments={"city": "Paris"})]),
Message.tool_results(ToolResultPart(call_id="toolu_01A", name="GetWeather", content='{"temp_c": 12}')),
]
request = Request(model="fast", messages=history, system="Be brief.", tools=[ToolSpec.from_model(GetWeather)],
tool_choice=ForcedTool(name="GetWeather"), reasoning_effort="off", metadata={"feature": "demo"})
print("Request fields :", sorted(Request.model_fields))
print("tool spec :", request.tools[0].model_dump())
print("tool_choice :", request.tool_choice)
# 2. Messages are plain data: they round-trip through JSON (this is how a conversation store saves them)
as_json = history[1].model_dump_json()
print("assistant turn :", as_json[:150] + "...")
again = Message.model_validate_json(as_json)
print("round trip ok :", again == history[1], "| part types:", [type(p).__name__ for p in again.parts])
# 3. A response, with the normalized and the raw finish reason side by side
response = Response(parts=[TextPart(text="It is 12 C in Paris.")], finish_reason=FinishReason.STOP,
raw_finish_reason="end_turn", provider="anthropic", api="messages",
usage=Usage(uncached_input_tokens=12, cached_input_tokens=8, output_tokens=7, reasoning_tokens=2),
resolved_model="claude-haiku-5-5", request_id="req_011CV...")
print("response :", response.model_dump(mode="json", exclude={"raw"}))
print("total input :", response.usage.total_input_tokens, "(uncached 12 + cache reads 8)")
print("append to chat :", response.message.role, [type(p).__name__ for p in response.message.parts])Request fields : ['extra', 'max_output_tokens', 'messages', 'metadata', 'model', 'output_schema', 'parallel_tool_calls', 'reasoning_effort', 'stop', 'system', 'timeout_s', 'tool_choice', 'tools']
tool spec : {'name': 'GetWeather', 'description': 'Get the current weather for one city.', 'parameters': {'description': 'Get the current weather for one city.', 'properties': {'city': {'title': 'City', 'type': 'string'}}, 'required': ['city'], 'title': 'GetWeather', 'type': 'object'}, 'strict': False}
tool_choice : name='GetWeather'
assistant turn : {"role":"assistant","parts":[{"native":{"provider":"anthropic","api":"messages","payload":{"type":"thinking","thinking":"I need the weather tool.","si...
round trip ok : True | part types: ['ReasoningPart', 'ToolCallPart']
response : {'parts': [{'native': None, 'type': 'text', 'text': 'It is 12 C in Paris.'}], 'finish_reason': 'stop', 'raw_finish_reason': 'end_turn', 'usage': {'uncached_input_tokens': 12, 'cached_input_tokens': 8, 'cache_write_tokens': {}, 'output_tokens': 7, 'reasoning_tokens': 2, 'tier': 'standard', 'geo': None, 'regional': False, 'web_searches': 0, 'grounding_searches': 0, 'modality_input': {}, 'reported_cost_usd': None}, 'cost': None, 'provider': 'anthropic', 'api': 'messages', 'model_key': '', 'requested_model': '', 'resolved_model': 'claude-haiku-5-5', 'request_id': 'req_011CV...', 'provider_response_id': None, 'call_id': '', 'latency_ms': 0, 'attempts': [], 'parsed': None}
total input : 20 (uncached 12 + cache reads 8)
append to chat : assistant ['TextPart']The demos below are complete files, not fragments: save each sN_*.py block as demos/<name>.py (create demos/ next to pytest.ini) and run it from the project root with PYTHONPATH=. uv run python demos/s3_types_demo.py (on Windows PowerShell: $env:PYTHONPATH = "." first, then uv run python demos/s3_types_demo.py). The PYTHONPATH=. matters: a uv init --bare project has no build backend, so provider_agnostic is not installed, and a script in demos/ does not see the project root on its own; the demos that import tests.fakes need it even after the package is installed (Packaging it). Layer 1: pure Python, nothing was sent. Notice that the assistant turn (a signed Claude thinking block plus a tool call) round-trips through JSON and comes back as the same classes. That is what lets a conversation store (03.2, Part 5) hold canonical messages and replay them to any adapter.
Part 4: Adapters#
Each adapter owns one API and nothing else. Reading them side by side is the fastest way to see how different the four providers are, and to see that the differences are small and finite. The full files are in the appendix; this part shows the pieces that carry the design.
4.1 The base class#
# provider_agnostic/adapters/base.py: the contract every adapter fulfils
@dataclass(frozen=True)
class Opened:
"""The first item every `open_stream()` yields: what the HTTP response HEADERS said, before any event.
Streams used to report the body's object ID (`msg_...`) where `complete()` reported the request ID header,
so the same field meant two things. Now both carry the header when the provider sends one."""
request_id: str | None
def request_id_from(headers: Mapping[str, str] | None) -> str | None:
"""The ID a support ticket needs: x-request-id (OpenAI), request-id (Anthropic), x-generation-id (OpenRouter)."""
lower = {k.lower(): v for k, v in (headers or {}).items()}
return lower.get("x-request-id") or lower.get("request-id") or lower.get("x-generation-id")
@contextlib.contextmanager
def closing(iterator: Any) -> Iterator[Any]:
"""Close a stream iterator when we leave the block, EVEN on an early exit. SDKs type their streams as plain
`Iterator`s although at runtime they are generators with a close(): call it when it is there."""
try:
yield iterator
finally:
if (close := getattr(iterator, "close", None)) is not None:
close()
def usage_or_none(build: Callable[[], cost_calc.Usage]) -> Usage | None:
"""Usage by lesson 03.7's `cost_calc.from_*`, converted to the canonical type. A ValueError (no usage in the
response, or a service tier with no per-token price) means UNKNOWN: None, never a guessed or zero number."""
try:
return usage_from_cost_calc(build())
except ValueError:
return None
RESERVED_EXTRA = {"model", "messages", "input", "contents", "stream"}
def deep_merge(base: dict[str, Any], extra: Mapping[str, Any]) -> dict[str, Any]:
"""`extra` merged INTO what the adapter built: nested dicts merge, anything else is replaced by `extra`.
A shallow `{**params, **extra}` let extra={"output_config": {"effort": "max"}} silently delete the structured-output
`format` the adapter had just put in the same dict."""
out = dict(base)
for key, value in extra.items():
out[key] = deep_merge(out[key], value) if isinstance(out.get(key), dict) and isinstance(value, Mapping) else value
return out
def apply_extra(params: dict[str, Any], req: Request, provider: str, reserved: set[str] = RESERVED_EXTRA) -> dict[str, Any]:
"""The escape hatch: Request.extra[<provider name>], merged, but never allowed to replace the model, the
messages or the stream flag (that would change what the caller asked for without a word)."""
extra = req.extra.get(provider, {})
clash = sorted(reserved & extra.keys())
if clash:
raise UnsupportedFeature(f"Request.extra[{provider!r}] may not set {clash}: use the Request fields", provider=provider)
return deep_merge(params, extra)
def error_result_text(content: str) -> str:
"""OpenAI has no `is_error` marker on a tool result (lesson 03.5, 7.4): the text must say so. A visible, documented
translation, applied only when the caller flagged an error and did not already say so."""
return content if content.lower().startswith("error") else f"Error: {content}"
class Adapter(ABC):
api: str # "responses" | "chat" | "messages" | ...
def __init__(self, spec: ModelSpec, *, http_client: Any = None, async_http_client: Any = None) -> None:
self.spec = spec
self._http_client, self._async_http_client = http_client, async_http_client # for mock transports
self._client: Any = None
self._aclient: Any = None
def sdk_kwargs(self) -> dict[str, Any]:
"""Constructor arguments shared by the openai and anthropic clients. max_retries=0: the wrapper's
client owns retries, so an outage is not multiplied by the SDK's own loop (lesson 03.8, 5.5)."""
return {"api_key": resolve_api_key(self.spec), "base_url": resolved_base_url(self.spec), "max_retries": 0,
"default_headers": resolve_headers(self.spec)}
# ---- pure translation -------------------------------------------------------------------
@abstractmethod
def build(self, req: Request) -> dict[str, Any]:
"""Canonical request -> keyword arguments for the SDK call (stream flag not included)."""
@abstractmethod
def parse(self, raw: Any) -> Response:
"""The SDK's response object -> canonical Response (no cost, latency or attempts yet)."""
@abstractmethod
def new_stream(self) -> "StreamParser":
"""A fresh state machine for one streamed response."""
# ---- thin I/O ---------------------------------------------------------------------------
@abstractmethod
def send(self, params: dict[str, Any], timeout_s: float) -> Any: ...
@abstractmethod
async def asend(self, params: dict[str, Any], timeout_s: float) -> Any: ...
@abstractmethod
def open_stream(self, params: dict[str, Any], timeout_s: float) -> Iterator[Any]: ...
@abstractmethod
def aopen_stream(self, params: dict[str, Any], timeout_s: float) -> AsyncIterator[Any]: ...
def close(self) -> None:
"""Close the SDK clients (sync only; await aclose() for async)."""
if self._client is not None and hasattr(self._client, "close"):
self._client.close()
async def aclose(self) -> None:
if self._aclient is not None and hasattr(self._aclient, "close"):
await self._aclient.close()
class StreamParser(ABC):
"""feed() every raw provider event; finish() once the stream ended. Never raises on unknown events."""
def __init__(self, spec: ModelSpec, api: str) -> None:
self.spec, self.api = spec, api
self.b = Builder()
@abstractmethod
def feed(self, event: Any) -> list[StreamEvent]: ...
def finish(self) -> Response:
return self.b.to_response(provider=self.spec.provider, api=self.api)sdk_kwargs(), in the class above, is where client construction is decided once, for every OpenAI-family and Anthropic adapter (Gemini's make_genai_client does the same job).
The helpers above the class are shared by every adapter: usage_or_none turns 03.7's cost_calc.from_* into the canonical Usage (a response with no usage, or a service tier the price table has no rate for, becomes None: unknown, never a guess); apply_extra is the merging escape hatch of 3.2; error_result_text is how a flagged tool-result error is made visible on APIs with no is_error field; and Opened is the first item every stream yields, carrying the request-ID header (5.1).
Three decisions hide in those few lines. max_retries=0: the wrapper's client owns retries, so an outage is not multiplied by the SDK's own loop. The key comes from the environment variable named in the registry (resolve_api_key), so no key ever appears in a config file, and a missing key fails with a message that says which variable to set (and never prints a value). Gateway headers that carry a key work the same way, through headers_env (7.1). Clients are created lazily and then reused, one per registry entry, so connection pools are shared and never created per request (03.1, 7.5).
The adapters also accept an injected HTTP client (http_client=). That is how the tests put a mock transport under the real SDKs: httpx2.Client(transport=httpx2.MockTransport(...)) for openai and anthropic, httpx.Client(...) for google-genai (03.1, 4.5; respx would not intercept the first two). That httpx.Client is a plain import httpx, which works here because the pinned google-genai installs httpx; with google-genai 3.x, httpx is no longer installed with the SDK (httpx2 is required and the default), so run uv add httpx yourself or build the Gemini mock with httpx2 instead (03.1, 4.5); this path stays on 2.34.0.
4.2 OpenAI Responses#
The primary OpenAI adapter. Its build() is the clearest example of "translate, don't pass through":
# provider_agnostic/adapters/openai_responses.py: canonical Request -> Responses API arguments
def build(self, req: Request) -> dict[str, Any]:
spec = self.spec
params: dict[str, Any] = {
"model": spec.model,
"input": self._input_items(req),
"max_output_tokens": req.max_output_tokens or spec.default_max_output_tokens,
"store": False, # stateless: we re-send history (lesson 03.2)
}
if req.system:
params["instructions"] = req.system
if req.tools:
params["tools"] = [{"type": "function", "name": t.name, "description": t.description,
"parameters": openai_strict(t.parameters) if t.strict else t.parameters,
"strict": t.strict} for t in req.tools]
params["tool_choice"] = self._tool_choice(req)
if req.parallel_tool_calls is not None:
params["parallel_tool_calls"] = req.parallel_tool_calls
if req.output_schema is not None:
params["text"] = {"format": {"type": "json_schema", "name": schema_name(req.output_schema),
"schema": openai_strict(req.output_schema), "strict": True}}
if spec.capabilities.reasoning:
effort = spec.reasoning_off if req.reasoning_effort == "off" else req.reasoning_effort
if effort:
params["reasoning"] = {"effort": effort}
# store=False means the server keeps nothing: ask for the encrypted reasoning so we can replay it
params["include"] = ["reasoning.encrypted_content"]
return apply_extra(params, req, spec.provider) # the escape hatch, keyed by provider, deep-merged
@staticmethod
def _tool_choice(req: Request) -> Any:
tc = req.tool_choice
if isinstance(tc, ForcedTool):
return {"type": "function", "name": tc.name}
return tc # "auto" | "required" | "none"Things worth noticing:
stopis not sent, and the route says so. The Responses API has no stop-sequence parameter (itscreate()signature has none: we checked the SDK version named in Setup), so the registry marks these routesstop: falseand a request withstop=[...]raisesUnsupportedFeatureinstead of losing the sequence (7.3). Truncating the text yourself is the alternative, and a poor one for streams, where a stop sequence can straddle two chunks.store=Falsealways. The wrapper is stateless: it re-sends history, so the same conversation can move between providers (03.2, Part 7 covers server-side state, which is a deliberate non-goal here).- With
store=False, ask forinclude=["reasoning.encrypted_content"]so reasoning items can be replayed on the next turn, as 02.8, 8.2 requires. - Strict schemas are opt-in per tool (
ToolSpec.strict), throughschemas.openai_strict(), a thin wrapper over the SDK's own strict transform (03.4, 2.9). That helper lives in a private module (openai.lib._pydantic), so a test pins its behaviour and fails first when you upgrade (Part 11). - The input is built from canonical parts, with images as
input_image(including thedetailfield that openai 3.42.1 marks required, 03.6) and PDFs asinput_file:
# provider_agnostic/adapters/openai_responses.py: canonical messages -> Responses input items
def _input_items(self, req: Request) -> list[dict[str, Any]]:
items: list[dict[str, Any]] = []
for m in req.messages:
if m.role == "user":
content: list[dict[str, Any]] = []
for p in m.parts:
if isinstance(p, TextPart):
if p.text: # an empty text part is a 400 on some APIs: omit it
content.append({"type": "input_text", "text": p.text})
elif isinstance(p, ImagePart):
url = p.url if p.url and not p.data_b64 else data_url(p.media_type, p.data_b64 or "")
content.append({"type": "input_image", "image_url": url, "detail": p.detail})
elif isinstance(p, DocumentPart):
content.append({"type": "input_file", "filename": p.filename,
"file_data": data_url(p.media_type, p.data_b64)})
if content:
items.append({"role": "user", "content": content})
elif m.role == "assistant":
text_buf: list[str] = []
def flush() -> None:
if any(text_buf): # a tool-only or reasoning-only turn has no text item
items.append({"role": "assistant", "content": "".join(text_buf)})
text_buf.clear()
for p in m.parts:
if isinstance(p, TextPart):
text_buf.append(p.text)
elif isinstance(p, ReasoningPart):
flush()
if (native := self._native(p)) is not None: # only OUR reasoning can be replayed
items.append(native)
elif isinstance(p, ToolCallPart):
flush()
items.append(self._native(p) or {"type": "function_call", "call_id": p.id,
"name": p.name, "arguments": json.dumps(p.arguments)})
flush()
else: # role == "tool"
for p in m.parts:
if isinstance(p, ToolResultPart):
items.append({"type": "function_call_output", "call_id": p.call_id,
"output": error_result_text(p.content) if p.is_error else p.content}) # no is_error field here
return itemsAnd its parse() starts with the check the first version forgot: a response whose status is failed or cancelled is an error, not a response (HTTP 200 notwithstanding). raise_if_failed runs 03.8's check_response() on the SDK object and maps its error.code to a class (Part 6). Only then does it decide the finish reason from the combination of status, incomplete_details and the output items, because Responses has no single field for it. Usage is one call into 03.7's cost_calc.from_openai_response:
# provider_agnostic/adapters/openai_responses.py: Response object -> canonical Response
def parse(self, raw: Any) -> Response:
request_id = getattr(raw, "_request_id", None)
raise_if_failed(raw, self.spec.provider, request_id or raw.id) # HTTP 200 + status "failed" is an ERROR, not a Response
parts: list[Part] = []
refusal = False
for item in raw.output:
if item.type == "message":
for c in item.content:
if c.type == "output_text":
parts.append(TextPart(text=c.text))
elif c.type == "refusal":
refusal = True
parts.append(TextPart(text=c.refusal))
elif item.type == "function_call":
args, err = parse_arguments(item.arguments)
parts.append(ToolCallPart(id=item.call_id, name=item.name, arguments=args, arguments_error=err,
native=Native(provider=self.spec.provider, api=self.api,
payload=item.model_dump(exclude_none=True))))
elif item.type == "reasoning":
summary = "\n".join(s.text for s in item.summary or [])
parts.append(ReasoningPart(text=summary or None,
native=Native(provider=self.spec.provider, api=self.api,
payload=item.model_dump(exclude_none=True))))
finish, raw_finish = self._finish(raw, refusal)
return Response(parts=parts, finish_reason=finish, raw_finish_reason=raw_finish,
usage=usage_or_none(lambda: cost_calc.from_openai_response(raw)), provider=self.spec.provider,
api=self.api, resolved_model=raw.model, request_id=request_id or raw.id,
provider_response_id=raw.id, raw=raw)
@staticmethod
def _finish(raw: Any, refusal: bool) -> tuple[FinishReason, str]:
status = raw.status
reason = raw.incomplete_details.reason if raw.incomplete_details else None
shown = f"{status}:{reason}" if reason else str(status)
if refusal:
return FinishReason.REFUSAL, shown
if status == "incomplete":
return {"max_output_tokens": FinishReason.LENGTH,
"content_filter": FinishReason.CONTENT_FILTER}.get(reason or "", FinishReason.OTHER), shown
if status == "completed": # "failed" and "cancelled" never get here: parse() raised already
has_call = any(i.type == "function_call" for i in raw.output)
return (FinishReason.TOOL_CALLS if has_call else FinishReason.STOP), shown
return FinishReason.OTHER, shown4.3 One Chat Completions adapter, three dialects#
OpenAI Chat Completions, OpenRouter and Ollama (and vLLM and most local servers) share a wire format, so they share one class. But "OpenAI-compatible" is a promise about the URL and the JSON envelope, not about the features (03.1, 5.5). Every difference we have measured in this module goes in one table, not in if provider == ... scattered through the code:
# provider_agnostic/adapters/openai_chat.py: each server's quirks, in one place
@dataclass(frozen=True)
class Dialect:
max_tokens_param: str # the output-cap parameter this server honours
reasoning: str # "reasoning_effort" | "openrouter" | "none"
reports_cost: bool = False # OpenRouter puts usage.cost in the response
DIALECTS = {
"openai": Dialect("max_completion_tokens", "reasoning_effort"),
"openrouter": Dialect("max_tokens", "openrouter", reports_cost=True),
"local": Dialect("max_tokens", "none"), # Ollama ignores max_completion_tokens
}| Setting | openai |
openrouter |
local (Ollama and similar) |
Source |
|---|---|---|---|---|
| Output cap parameter | max_completion_tokens |
max_tokens |
max_tokens (Ollama ignores max_completion_tokens) |
03.1, stand-in notes |
| Reasoning control | reasoning_effort |
extra_body={"reasoning": {...}} |
none | 02.8, 3.4 |
| Cost in the response | no | usage.cost (in model_extra) |
no | 03.7, 9.3 |
| Finish-reason extras | none | native_finish_reason |
none | 03.3, 3.6 |
| An error inside HTTP 200 | no | possible: error object, no choices |
no | 03.8, Part 10 |
| Attribution headers | no | HTTP-Referer, X-OpenRouter-Title (registry headers:) |
no | 03.1, 6.6 |
| Strict tool schemas enforced | yes | not guaranteed | no (Ollama ignores strict) |
registry capability strict_tools: ToolSpec.strict=True raises where it would be ignored |
| Usage normalizer | cost_calc.from_openai_chat |
cost_calc.from_openrouter (carries usage.cost) |
from_openai_chat |
03.7, Part 3 |
Adding vLLM, LM Studio or another compatible server means adding one Dialect and one models.yaml entry, then running the contract suite against it. The tests tell you immediately which behaviours differ.
parse() here must cope with OpenRouter's HTTP-200-with-an-error-body, which the openai SDK parses without raising (choices is None, 03.8, Part 10):
# provider_agnostic/adapters/openai_chat.py: parse(), including OpenRouter's error-in-200 and reasoning extras
def parse(self, raw: Any) -> Response:
extra = raw.model_extra or {}
if not raw.choices: # OpenRouter: HTTP 200 with only an error body
raise error_from_body(self.spec.provider, extra.get("error"), request_id=raw.id)
choice = raw.choices[0]
msg = choice.message
parts: list[Part] = []
reasoning_extra = {k: v for k, v in (msg.model_extra or {}).items() if k in ("reasoning_details",) and v}
reasoning_text = (msg.model_extra or {}).get("reasoning") or (msg.model_extra or {}).get("reasoning_content")
if reasoning_text or reasoning_extra:
parts.append(ReasoningPart(text=reasoning_text or None, native=Native(
provider=self.spec.provider, api=self.api, payload=reasoning_extra) if reasoning_extra else None))
if msg.content:
parts.append(TextPart(text=msg.content))
for tc in msg.tool_calls or []:
if tc.type != "function":
continue
args, err = parse_arguments(tc.function.arguments)
parts.append(ToolCallPart(id=tc.id, name=tc.function.name, arguments=args, arguments_error=err,
native=Native(provider=self.spec.provider, api=self.api,
payload={"arguments": tc.function.arguments}) if err else None))
finish = FinishReason.REFUSAL if msg.refusal else _FINISH.get(choice.finish_reason or "", FinishReason.OTHER)
if msg.refusal:
parts.append(TextPart(text=msg.refusal))
raw_finish = choice.finish_reason
native_finish = (choice.model_extra or {}).get("native_finish_reason") # OpenRouter keeps the original
if native_finish:
raw_finish = f"{choice.finish_reason}|{native_finish}"
request_id = getattr(raw, "_request_id", None)
if choice.finish_reason == "error": # the provider failed mid-request, inside a 200
raise error_from_failed(self.spec.provider, "server_error",
f"the response ended with finish_reason=error ({native_finish or 'no detail'})",
request_id=request_id or raw.id)
return Response(parts=parts, finish_reason=finish, raw_finish_reason=raw_finish, usage=self._usage(raw),
provider=self.spec.provider, api=self.api, resolved_model=raw.model,
request_id=request_id or raw.id, provider_response_id=raw.id, raw=raw)error_from_body (in errors.py) turns that body into the same exception class the equivalent HTTP status would have produced (Part 6); a choice that ends with finish_reason="error" is raised as a retryable ServerError the same way. When the replayed tool-call arguments were invalid JSON (arguments_error is set), the adapter sends back what the model actually said, kept in the part's native, instead of rewriting it as {}: the Responses adapter already replays its native item, and the two now agree.
4.4 Anthropic Messages#
Three Anthropic rules do the most damage in provider-neutral code (03.2, Part 4, 03.5, 6.4): roles must alternate, tool_result blocks must come first in the user message that answers a tool_use, and there is no max_tokens default. The adapter encodes all three:
# provider_agnostic/adapters/anthropic_messages.py: messages, with tool results first and neighbours merged
def _messages(self, req: Request) -> list[dict[str, Any]]:
out: list[dict[str, Any]] = []
for m in req.messages:
blocks: list[dict[str, Any]] = []
if m.role in ("user", "tool"):
# tool_result blocks must come FIRST in the user message that answers the tool_use
results = [p for p in m.parts if isinstance(p, ToolResultPart)]
blocks += [{"type": "tool_result", "tool_use_id": p.call_id, "content": p.content,
**({"is_error": True} if p.is_error else {})} for p in results]
for p in m.parts:
if isinstance(p, TextPart):
if p.text: # an empty text block is a 400 on the Messages API
blocks.append({"type": "text", "text": p.text})
elif isinstance(p, ImagePart):
src = ({"type": "url", "url": p.url} if p.url and not p.data_b64 else
{"type": "base64", "media_type": p.media_type, "data": p.data_b64})
blocks.append({"type": "image", "source": src})
elif isinstance(p, DocumentPart):
blocks.append({"type": "document", "source": {
"type": "base64", "media_type": p.media_type, "data": p.data_b64}})
role = "user"
else:
role = "assistant"
for p in m.parts:
if isinstance(p, ReasoningPart):
if (native := self._native(p)) is not None: # thinking blocks + signatures, unchanged
blocks.append(native)
elif isinstance(p, TextPart):
if p.text:
blocks.append({"type": "text", "text": p.text})
elif isinstance(p, ToolCallPart):
blocks.append({"type": "tool_use", "id": p.id, "name": p.name, "input": p.arguments})
if not blocks: # nothing to send for this turn: omit it entirely
continue
if out and out[-1]["role"] == role: # the API wants alternating roles: merge neighbours
out[-1]["content"] += blocks
else:
out.append({"role": role, "content": blocks})
return outThe tool role disappears here: a canonical tool message and a following user message become one Claude user message with the results first. Sampling parameters are absent on purpose. The rest of build() handles tools, tool_choice, structured output through output_config.format and the model-dependent thinking settings:
# provider_agnostic/adapters/anthropic_messages.py: the rest of the request
def build(self, req: Request) -> dict[str, Any]:
spec = self.spec
params: dict[str, Any] = {"model": spec.model, "messages": self._messages(req),
"max_tokens": req.max_output_tokens or spec.default_max_output_tokens}
if req.system:
params["system"] = req.system
if req.stop:
params["stop_sequences"] = req.stop
if req.tools:
params["tools"] = [{"name": t.name, "description": t.description,
"input_schema": anthropic_schema(t.parameters) if t.strict else t.parameters,
**({"strict": True} if t.strict else {})} for t in req.tools]
tc = req.tool_choice
choice: dict[str, Any] = ({"type": "tool", "name": tc.name} if isinstance(tc, ForcedTool)
else {"type": {"auto": "auto", "required": "any", "none": "none"}[tc]})
if req.parallel_tool_calls is False and choice["type"] != "none":
choice["disable_parallel_tool_use"] = True
if choice != {"type": "auto"}:
params["tool_choice"] = choice
output_config: dict[str, Any] = {}
if req.output_schema is not None:
output_config["format"] = {"type": "json_schema", "schema": anthropic_schema(req.output_schema)}
if spec.capabilities.reasoning and req.reasoning_effort: # 02.8, 3.6: depends on the MODEL
if req.reasoning_effort == "off" and spec.reasoning_off in ("disabled", "between_tools"):
params["thinking"] = {"type": spec.reasoning_off} # these modes take no other fields
else:
effort = spec.reasoning_off if req.reasoning_effort == "off" else req.reasoning_effort
params["thinking"] = {"type": "adaptive", "display": "summarized"}
output_config["effort"] = effort
if output_config:
params["output_config"] = output_config
return apply_extra(params, req, spec.provider) # deep-merged: output_config.effort keeps output_config.formatThe file is named anthropic_messages.py, not anthropic.py, on purpose: a module called anthropic inside your own package would shadow the SDK for anyone who runs a script from that folder, and a type checker would stop resolving import anthropic. (We found this the hard way: the first version failed type checking with six "not a known attribute" warnings.)
4.5 Gemini: which API does the wrapper call?#
This module's own choice makes generate_content its primary Gemini API, and Google recommends Interactions for new projects (generally available since June 2026). The wrapper ships both adapters, and registers generate_content as the default (flash) with Interactions one registry entry away (flash-interactions). The reasons for that default are engineering ones, not taste, and you should re-weigh them for your own project:
| Question | generate_content |
Interactions |
|---|---|---|
| Can the SDK's own retries be turned off, so the wrapper owns retries? | Yes. models.* makes one attempt unless you pass retry_options (03.8, 5.2) |
No. It retries 3 times by default, and attempts=0 is silently rewritten to 1 retry. The adapter can only stop status retries, and connection errors are still retried once |
| Are batch and explicit caches available? | Yes (03.9, Part 9, 03.7, 8.2) | Batch lines are GenerateContentRequests; explicit caches are a generate_content feature, with implicit caching only on Interactions (03.9, 9.5, 03.7, 8.5) |
| Stateless use? | Natural | Works with store=False and the full input each time, which is how the adapter uses it |
| Where do errors come from? | google.genai.errors |
The private google.genai._interactions module (03.8, 3.4); classify() imports it defensively |
| Does it run on the local stand-in? | No: hosted-only (Ollama does not speak Gemini's API), so it is tested with mocks here | No: hosted-only, tested with mocks and recorded fixtures here |
| Google's recommendation | "Remains fully supported", now called legacy by Google | "The recommended interface for all new projects" |
So the trade is: take Google's recommended interface and give up control of retries, or keep generate_content and keep a single retry layer. If you choose Interactions, change one line in the registry and run the contract suite; the adapter exists and is tested against fixtures. The two adapters also show how little differs once the SDK has done its job: both turn a function call into a ToolCallPart, both keep thought signatures in native, both give usage as input, cached and output counts.
# provider_agnostic/adapters/gemini_generate.py: build() for generate_content
def build(self, req: Request) -> dict[str, Any]:
spec = self.spec
cfg: dict[str, Any] = {"max_output_tokens": req.max_output_tokens or spec.default_max_output_tokens,
"automatic_function_calling": {"disable": True}} # we run tools; the SDK must not
if req.system:
cfg["system_instruction"] = req.system
if req.stop:
cfg["stop_sequences"] = req.stop
if req.tools:
cfg["tools"] = [{"function_declarations": [
{"name": t.name, "description": t.description, "parameters_json_schema": t.parameters}
for t in req.tools]}]
tc = req.tool_choice
if isinstance(tc, ForcedTool):
fc = {"mode": "ANY", "allowed_function_names": [tc.name]}
else:
fc = {"mode": {"auto": "AUTO", "required": "ANY", "none": "NONE"}[tc]}
cfg["tool_config"] = {"function_calling_config": fc}
if req.output_schema is not None:
cfg["response_mime_type"] = "application/json"
cfg["response_json_schema"] = plain_schema(req.output_schema)
if spec.capabilities.reasoning and req.reasoning_effort:
level = spec.reasoning_off if req.reasoning_effort == "off" else req.reasoning_effort
cfg["thinking_config"] = {"thinking_level": str(level).upper(), "include_thoughts": True}
cfg = apply_extra(cfg, req, spec.provider, reserved=set()) # the extras are GenerateContentConfig fields, merged
return {"model": spec.model, "contents": self._contents(req),
"config": types.GenerateContentConfig.model_validate(cfg)}
def _contents(self, req: Request) -> list[types.Content]:
out: list[dict[str, Any]] = []
for m in req.messages:
parts: list[dict[str, Any]] = []
for p in m.parts:
if isinstance(p, TextPart):
if p.text:
parts.append(self._native(p) or {"text": p.text})
elif isinstance(p, ImagePart):
if p.data_b64 is not None:
parts.append({"inline_data": {"mime_type": p.media_type, "data": base64.b64decode(p.data_b64)}})
else: # a public https URL: Gemini fetches it (up to 15 MB, lesson 03.6)
parts.append({"file_data": {"file_uri": p.url, "mime_type": p.media_type}})
elif isinstance(p, DocumentPart):
parts.append({"inline_data": {"mime_type": p.media_type, "data": base64.b64decode(p.data_b64)}})
elif isinstance(p, ReasoningPart):
if (native := self._native(p)) is not None:
parts.append(native)
elif isinstance(p, ToolCallPart):
parts.append(self._native(p) or {"function_call": {"id": p.id or None, "name": p.name,
"args": p.arguments}})
elif isinstance(p, ToolResultPart):
body = {"error": p.content} if p.is_error else {"output": p.content}
parts.append({"function_response": {"id": p.call_id or None, "name": p.name, "response": body}})
if parts: # a Content with no parts is a 400
out.append({"role": "model" if m.role == "assistant" else "user", "parts": parts})
return [types.Content.model_validate(c) for c in out]Two Gemini details are easy to get wrong and are handled here:
automatic_function_callingis disabled. The SDK can run Python functions for you; a wrapper that returns tool calls to its caller must not let it (03.5, 15.3).- Timeouts are in milliseconds on google-genai's
HttpOptions, seconds everywhere else; the adapter converts so thatPolicy.attempt_timeout_smeans the same thing on every route (03.8, Part 6).
The finish reason for Gemini needs care, because a blocked prompt has no candidate at all, and because CONTINUATION (the per-request token limit was hit and the answer is not finished) must not read as STOP. The SDK hides continuation by default (03.3, 4.5b); with automatic_continuation=False you see it, and it maps to LENGTH with the raw word kept:
# provider_agnostic/adapters/gemini_generate.py: parts and finish reason, including a blocked prompt
def _parts_and_finish(self, raw: Any) -> tuple[list[Part], FinishReason, str | None]:
parts: list[Part] = []
cand = raw.candidates[0] if raw.candidates else None
calls = False
for p in (cand.content.parts if cand and cand.content and cand.content.parts else []):
payload = p.model_dump(mode="json", exclude_none=True) # signatures included, base64
native = Native(provider=self.spec.provider, api=self.api, payload=payload)
if p.function_call:
calls = True
parts.append(ToolCallPart(id=p.function_call.id or "", name=p.function_call.name or "",
arguments=dict(p.function_call.args or {}), native=native))
elif p.thought and p.text is not None:
parts.append(ReasoningPart(text=p.text, native=native))
elif p.text is not None:
parts.append(TextPart(text=p.text, native=native if p.thought_signature else None))
name = cand.finish_reason.name if cand and cand.finish_reason else None
if cand is None: # the PROMPT was blocked: no candidate
block = raw.prompt_feedback.block_reason if raw.prompt_feedback else None
return parts, FinishReason.CONTENT_FILTER, f"prompt_blocked:{block.name if block else None}"
if name in _BLOCKED:
return parts, FinishReason.CONTENT_FILTER, name
if name in ("MAX_TOKENS", "CONTINUATION"): # CONTINUATION: stopped at the per-request limit, NOT finished
return parts, FinishReason.LENGTH, name # (the SDK hides it by default: 03.3, 4.5b; you see it with automatic_continuation=False)
if name in _TOOL_FAILURES:
return parts, FinishReason.ERROR, name
if name in ("STOP", None):
return parts, (FinishReason.TOOL_CALLS if calls else FinishReason.STOP), name
return parts, FinishReason.OTHER, name4.6 Try it: one request, five wire formats#
This is the proof that the translation works, and the best way to learn the four APIs side by side. One canonical request (a system prompt, a tool, an output cap and reasoning_effort="off") goes through the real SDKs into a mock transport that records the HTTP request instead of sending it (layer 5: a wire capture, nothing leaves your machine). The authorization header is redacted.
"""s4_wire_capture.py: ONE canonical request, five wire formats (layer 5: the real SDKs build real HTTP requests,
a mock transport captures them, nothing leaves your machine). The authorization header is redacted."""
import json
import os
from provider_agnostic import LLMClient, Message, Registry, Request, ToolSpec
from tests.fakes import FakeAnthropic, FakeChat, FakeGemini, FakeInteractions, FakeResponses, Server
for name in ("OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GEMINI_API_KEY", "OPENROUTER_API_KEY"):
os.environ[name] = "sk-test" # an obviously fake placeholder: nothing is ever sent
WEATHER = ToolSpec(name="get_weather", description="Get the current weather for one city.",
parameters={"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]})
REQUEST = Request(model="m", system="You are terse.", max_output_tokens=200, reasoning_effort="off",
tools=[WEATHER], messages=[Message.user("What is the weather in Paris?")])
ROUTES = [("luna", FakeResponses()), ("luna-chat", FakeChat()), ("haiku", FakeAnthropic()),
("flash", FakeGemini()), ("flash-interactions", FakeInteractions()), ("or-luna", FakeChat(openrouter=True))]
registry = Registry.load()
SHOW = ("content-type", "authorization", "x-api-key", "x-goog-api-key", "anthropic-version", "http-referer", "x-openrouter-title")
for key, fake in ROUTES:
server = Server([fake.text()], flavour=fake.flavour)
spec = registry.models[key]
# point each entry at the mock instead of the real host; everything else is the real registry entry
mocked = Registry({"version": "demo", "models": {key: {**spec.model_dump(exclude={"key"}), "base_url": fake.base_url}}})
with LLMClient(mocked, http_clients={key: server.clients()}) as client:
client.complete(REQUEST.model_copy(update={"model": key}))
sent = server.requests[0]
headers = {h: ("<redacted>" if h in ("authorization", "x-api-key", "x-goog-api-key") else v)
for h, v in sent["headers"].items() if h in SHOW}
print(f"=== {key}: {spec.provider} / {spec.api}")
query = sent["query"].removeprefix("b'").removesuffix("'")
print(f"{sent['method']} {sent['path']}{'?' + query if query else ''}")
print("headers:", json.dumps(headers))
for field, value in sent["json"].items(): # one top-level field per line, values compact
print(f" {field}: {json.dumps(value, separators=(',', ':'))}")=== luna: openai / responses
POST /v1/responses
headers: {"authorization": "<redacted>", "content-type": "application/json"}
model: "gpt-6-luna"
include: ["reasoning.encrypted_content"]
input: [{"role":"user","content":[{"type":"input_text","text":"What is the weather in Paris?"}]}]
instructions: "You are terse."
max_output_tokens: 200
reasoning: {"effort":"none"}
store: false
tool_choice: "auto"
tools: [{"type":"function","name":"get_weather","description":"Get the current weather for one city.","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]},"strict":false}]
=== luna-chat: openai / chat
POST /v1/chat/completions
headers: {"authorization": "<redacted>", "content-type": "application/json"}
model: "gpt-6-luna"
messages: [{"role":"system","content":"You are terse."},{"role":"user","content":[{"type":"text","text":"What is the weather in Paris?"}]}]
max_completion_tokens: 200
reasoning_effort: "none"
tool_choice: "auto"
tools: [{"type":"function","function":{"name":"get_weather","description":"Get the current weather for one city.","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}}]
=== haiku: anthropic / messages
POST /v1/messages
headers: {"content-type": "application/json", "authorization": "<redacted>", "anthropic-version": "2026-10-21"}
max_tokens: 200
messages: [{"role":"user","content":[{"type":"text","text":"What is the weather in Paris?"}]}]
model: "claude-haiku-5-5"
system: "You are terse."
thinking: {"type":"disabled"}
tools: [{"name":"get_weather","description":"Get the current weather for one city.","input_schema":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}]
=== flash: gemini / generate_content
POST /v1beta/models/gemini-3.8-flash:generateContent
headers: {"content-type": "application/json", "x-goog-api-key": "<redacted>"}
contents: [{"parts":[{"text":"What is the weather in Paris?"}],"role":"user"}]
systemInstruction: {"parts":[{"text":"You are terse."}],"role":"user"}
tools: [{"functionDeclarations":[{"description":"Get the current weather for one city.","name":"get_weather","parameters_json_schema":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}]}]
toolConfig: {"functionCallingConfig":{"mode":"AUTO"}}
generationConfig: {"maxOutputTokens":200,"thinkingConfig":{"include_thoughts":true,"thinking_level":"LOW"}}
=== flash-interactions: gemini / interactions
POST /v1beta/interactions
headers: {"content-type": "application/json", "x-goog-api-key": "<redacted>"}
model: "gemini-3.8-flash"
generation_config: {"max_output_tokens":200,"thinking_level":"low","thinking_summaries":"auto","tool_choice":"auto"}
input: [{"content":[{"text":"What is the weather in Paris?","type":"text"}],"type":"user_input"}]
store: false
system_instruction: "You are terse."
tools: [{"description":"Get the current weather for one city.","name":"get_weather","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]},"type":"function"}]
=== or-luna: openrouter / chat
POST /v1/chat/completions
headers: {"authorization": "<redacted>", "content-type": "application/json", "http-referer": "https://example.com/wrapper-demo", "x-openrouter-title": "wrapper demo"}
model: "openai/gpt-6-luna"
messages: [{"role":"system","content":"You are terse."},{"role":"user","content":[{"type":"text","text":"What is the weather in Paris?"}]}]
max_tokens: 200
tool_choice: "auto"
tools: [{"type":"function","function":{"name":"get_weather","description":"Get the current weather for one city.","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}}]
reasoning: {"effort":"none"}Read the output field by field and the whole module comes back:
- System prompt:
instructions(Responses), a firstsystemmessage (Chat, OpenRouter),system(Anthropic),systemInstruction(Gemini),system_instruction(Interactions). - Output cap:
max_output_tokens,max_completion_tokens,max_tokens(OpenRouter),max_tokens(Anthropic),generationConfig.maxOutputTokens,generation_config.max_output_tokens. - Tools: flat on Responses, nested under
functionon Chat,input_schemaon Anthropic,functionDeclarationson Gemini, flat withparameterson Interactions. - "Reasoning off":
effort: noneon Luna,thinking: disabledon Haiku,thinking_level: LOWon Gemini 3.8 Flash (which rejectsminimal), and OpenRouter'sreasoningobject in the body. One setting, five meanings. - Headers: Anthropic sends
anthropic-version: 2026-10-21(03.1, 9.1); OpenRouter's attribution header comes from the registry entry.
Capturing the wire like this is also the first debugging move when a provider returns a 400 you don't understand (03.10).
4.7 What the adapters leave out#
On purpose, and each omission is something you can add behind extra or a new adapter method without changing the canonical types: prompt-cache breakpoints and keys (03.7), server-side state (previous_response_id, previous_interaction_id, 03.2), file IDs and Files APIs (03.6, Part 5), built-in server tools (03.5, Part 13), logprobs, batches (03.9 builds its own runner on these types' conventions), citations, audio and video, and embeddings (Module 06). A wrapper that tried to normalize all of that would be the lowest-common-denominator trap from Part 1.
Part 5: Normalizing the hard parts#
Deep-dive
5.1 Streaming: six formats in, one vocabulary out#
Lesson 03.3 catalogued every provider's stream: semantic events on Responses, bare chunks on Chat, content-block events on Anthropic, whole-response chunks on Gemini, step events on Interactions. Each adapter's new_stream() returns a small state machine with two methods: feed(raw_event) returns zero or more canonical events, and finish() returns the assembled Response. All six share one builder that applies the rules from 03.3, 5.2:
# provider_agnostic/adapters/base.py: the shared accumulator
class Builder:
"""Assembles the final Response from stream pieces. Handles the traps from lesson 03.3, Part 5:
blocks keyed by index (interleaved text and tool calls), tool arguments as JSON FRAGMENTS parsed once,
finish reason overwritten (never appended), usage replaced (never summed), None = unknown."""
def __init__(self) -> None:
self.blocks: dict[Any, dict[str, Any]] = {}
self.finish_reason: FinishReason | None = None
self.raw_finish_reason: str | None = None
self.usage: Usage | None = None
self.request_id: str | None = None # the HTTP header ID when the provider sends one, else the body ID
self.response_id: str | None = None # the body's own ID (resp_..., msg_..., chatcmpl-...)
self.resolved_model: str | None = None
@property
def ended(self) -> bool:
"""Did the stream reach its terminal event? A stream that just stops is NOT a finished answer."""
return self.finish_reason is not None
def _block(self, key: Any, kind: str) -> dict[str, Any]:
return self.blocks.setdefault(key, {"kind": kind, "text": "", "args": "", "id": None, "name": None,
"native": None})
def text(self, key: Any, s: str) -> TextDelta:
self._block(key, "text")["text"] += s
return TextDelta(text=s)
def reasoning(self, key: Any, s: str) -> ReasoningDelta:
self._block(key, "reasoning")["text"] += s
return ReasoningDelta(text=s)
def tool_start(self, key: Any, call_id: str, name: str, index: int) -> ToolCallStart:
blk = self._block(key, "tool")
blk["id"], blk["name"] = call_id, name
return ToolCallStart(index=index, id=call_id, name=name)
def tool_args(self, key: Any, fragment: str, index: int) -> ToolCallDelta:
self._block(key, "tool")["args"] += fragment
return ToolCallDelta(index=index, arguments_fragment=fragment)
def native(self, key: Any, native: Any, kind: str = "reasoning") -> None:
self._block(key, kind)["native"] = native # the provider's own item, kept for replay
def set_usage(self, usage: Usage) -> UsageEvent:
self.usage = usage # replace, never add: providers send cumulative numbers
return UsageEvent(usage=usage)
def to_response(self, *, provider: str, api: str) -> Response:
parts: list[Part] = []
for key in sorted(self.blocks, key=_order_key):
blk = self.blocks[key]
if blk["kind"] == "text" and blk["text"]:
parts.append(TextPart(text=blk["text"], native=blk["native"]))
elif blk["kind"] == "reasoning":
parts.append(ReasoningPart(text=blk["text"] or None, native=blk["native"]))
elif blk["kind"] == "tool":
args, err = parse_arguments(blk["args"])
native = blk["native"]
if err and native is None: # keep what the model really said: it is replayed, not rewritten
native = Native(provider=provider, api=api, payload={"arguments": blk["args"]})
parts.append(ToolCallPart(id=blk["id"] or "", name=blk["name"] or "", arguments=args,
arguments_error=err, native=native))
# finish_reason None means the stream never reached its terminal event: say so, loudly
finish = self.finish_reason or FinishReason.ERROR
raw = self.raw_finish_reason if self.finish_reason else "stream ended without a terminal event"
return Response(parts=parts, finish_reason=finish, raw_finish_reason=raw, usage=self.usage,
provider=provider, api=api, resolved_model=self.resolved_model,
request_id=self.request_id or self.response_id, provider_response_id=self.response_id)
def parse_arguments(raw: str | dict[str, Any] | None) -> tuple[dict[str, Any], str | None]:
"""Tool arguments -> (dict, error). OpenAI-style JSON strings are parsed here, once, for everyone.
An empty string is legal for a tool with no parameters. Invalid JSON is reported, not raised:
the caller decides (usually: send the error back to the model as a tool result)."""
if isinstance(raw, dict):
return raw, None
if raw is None or not raw.strip():
return {}, None
try:
value = json.loads(raw)
except json.JSONDecodeError as exc:
return {}, f"invalid JSON arguments ({exc.msg} at char {exc.pos})"
return (value, None) if isinstance(value, dict) else ({}, "arguments JSON is not an object")The traps it handles, each of which was a real bug in somebody's streaming code:
| Trap | How the builder avoids it |
|---|---|
| Text and tool calls interleave by index | Blocks are keyed by the provider's own index and sorted by it at the end. The Chat and generate_content streams have no block index, so their blocks (reasoning, text, each call by its position) keep the order in which they opened |
| Tool arguments arrive as JSON fragments | Fragments are concatenated per call and parsed once, in to_response(). A parse failure becomes arguments_error, not an exception |
| A tool with no parameters streams no fragments | An empty string parses as {} |
Usage is cumulative (Anthropic's message_delta) |
set_usage() replaces |
| OpenRouter repeats the finish reason | The finish reason is overwritten, never appended |
| A stream that never reaches its terminal event | finish_reason stays None (Builder.ended is false), to_response() reports ERROR with "stream ended without a terminal event" instead of pretending it was STOP, and the client raises a retryable ServerError rather than returning it as a success |
A stream whose terminal event says failed, or that carries an error event |
The parser raises the mapped error with its code (rate_limit_exceeded becomes RateLimited, invalid_prompt becomes BadRequest), so the client retries or raises exactly as it would for the same failure on a plain call (Part 6) |
| The request ID is in the HTTP headers, not in the events | Each open_stream yields Opened(request_id) first; the client hands it to the parser, so Done.response.request_id is the header ID, the same as on a plain call |
| New or unknown event types | The adapter's feed() ignores them: new events must never crash a working client |
Here is what the same three-piece text answer, and the same tool call with fragmented arguments, look like from each of the six routes (layer 3: each provider's documented stream shape from a mock server, read by the real SDK and our parsers):
"""s5_stream_events.py: six different stream formats in, ONE event vocabulary out (layer 3: mock servers).
The fixtures follow each provider's documented stream shape (lesson 03.3, Part 3); the SDKs and our parsers are real."""
import os
from provider_agnostic import Done, LLMClient, Message, Registry, Request, TextDelta, ToolCallDelta, ToolCallStart, ToolSpec, UsageEvent
from tests.fakes import FakeAnthropic, FakeChat, FakeGemini, FakeInteractions, FakeResponses, Server
for name in ("OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GEMINI_API_KEY", "OPENROUTER_API_KEY"):
os.environ[name] = "sk-test"
registry = Registry.load()
ROUTES = [("luna", FakeResponses()), ("luna-chat", FakeChat()), ("haiku", FakeAnthropic()),
("flash", FakeGemini()), ("flash-interactions", FakeInteractions()), ("or-luna", FakeChat(openrouter=True))]
WEATHER = ToolSpec(name="get_weather", description="Weather for a city",
parameters={"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]})
def describe(ev) -> str:
if isinstance(ev, TextDelta):
return f"text{ev.text!r}"
if isinstance(ev, ToolCallStart):
return f"tool_start({ev.name} id={ev.id})"
if isinstance(ev, ToolCallDelta):
return f"args{ev.arguments_fragment!r}"
if isinstance(ev, UsageEvent):
u = ev.usage
return f"usage(in={u.uncached_input_tokens} cached={u.cached_input_tokens} out={u.output_tokens})"
if isinstance(ev, Done):
r = ev.response
calls = [(c.name, c.arguments) for c in r.tool_calls]
return f"DONE(finish={r.finish_reason.value} raw={r.raw_finish_reason!r} text={r.text!r} calls={calls})"
return ev.type
def run(key: str, fake, reply, request: Request) -> None:
server = Server([reply], flavour=fake.flavour)
spec = registry.models[key]
mocked = Registry({"version": "demo", "models": {key: {**spec.model_dump(exclude={"key"}), "base_url": fake.base_url}}})
with LLMClient(mocked, http_clients={key: server.clients()}) as client:
events = list(client.stream(request.model_copy(update={"model": key})))
print(f"{key:19s}", " | ".join(describe(e) for e in events))
print("--- text: three pieces, 20 prompt tokens of which 8 were cached")
for key, fake in ROUTES:
run(key, fake, fake.stream_text(["Hel", "lo ", "there"]), Request(model="m", messages=[Message.user("Hi")]))
print("\n--- one tool call, arguments streamed in pieces (Gemini sends the whole call at once)")
for key, fake in ROUTES:
run(key, fake, fake.stream_tool("call_7", "get_weather", ['{"city": "Pa', 'ris"}']),
Request(model="m", messages=[Message.user("Weather in Paris?")], tools=[WEATHER]))--- text: three pieces, 20 prompt tokens of which 8 were cached
luna text'Hel' | text'lo ' | text'there' | usage(in=12 cached=8 out=5) | DONE(finish=stop raw='completed' text='Hello there' calls=[])
luna-chat text'Hel' | text'lo ' | text'there' | usage(in=12 cached=8 out=5) | DONE(finish=stop raw='stop' text='Hello there' calls=[])
haiku usage(in=12 cached=8 out=1) | text'Hel' | text'lo ' | text'there' | usage(in=12 cached=8 out=5) | DONE(finish=stop raw='end_turn' text='Hello there' calls=[])
flash text'Hel' | text'lo ' | usage(in=12 cached=8 out=7) | text'there' | DONE(finish=stop raw='STOP' text='Hello there' calls=[])
flash-interactions text'Hel' | text'lo ' | text'there' | usage(in=12 cached=8 out=7) | DONE(finish=stop raw='completed' text='Hello there' calls=[])
or-luna text'Hel' | text'lo ' | text'there' | usage(in=12 cached=8 out=5) | DONE(finish=stop raw='stop' text='Hello there' calls=[])
--- one tool call, arguments streamed in pieces (Gemini sends the whole call at once)
luna tool_start(get_weather id=call_7) | args'{"city": "Pa' | args'ris"}' | usage(in=30 cached=0 out=12) | DONE(finish=tool_calls raw='completed' text='' calls=[('get_weather', {'city': 'Paris'})])
luna-chat tool_start(get_weather id=call_7) | args'{"city": "Pa' | args'ris"}' | usage(in=30 cached=0 out=12) | DONE(finish=tool_calls raw='tool_calls' text='' calls=[('get_weather', {'city': 'Paris'})])
haiku usage(in=30 cached=0 out=1) | tool_start(get_weather id=call_7) | args'{"city": "Pa' | args'ris"}' | usage(in=30 cached=0 out=12) | DONE(finish=tool_calls raw='tool_use' text='' calls=[('get_weather', {'city': 'Paris'})])
flash usage(in=30 cached=0 out=14) | tool_start(get_weather id=call_7) | args'{"city": "Paris"}' | DONE(finish=tool_calls raw='STOP' text='' calls=[('get_weather', {'city': 'Paris'})])
flash-interactions tool_start(get_weather id=call_7) | args'{"city": "Pa' | args'ris"}' | usage(in=30 cached=0 out=14) | DONE(finish=tool_calls raw='completed' text='' calls=[('get_weather', {'city': 'Paris'})])
or-luna tool_start(get_weather id=call_7) | args'{"city": "Pa' | args'ris"}' | usage(in=30 cached=0 out=12) | DONE(finish=tool_calls raw='tool_calls' text='' calls=[('get_weather', {'city': 'Paris'})])Look at what differs and what does not. The content events (text, tool_start, args) are identical across providers except where the provider really differs: Gemini generate_content sends the whole call at once, so it has one args event, not two. The usage events sit in different places (first, middle, last), because providers send them at different times, and Done always has the final numbers. Gemini's streamed output tokens read 7, not 5, because the wrapper adds the 2 thinking tokens Gemini reports separately (5.6). And raw= keeps 'completed', 'stop', 'end_turn', 'STOP' for anyone who needs the original.
Retry and fallback inside a stream. A stream can fail before the first byte (a 503 when opening the connection) or after text has already reached your user. These are different situations (03.3, 7.5). LLMClient.stream() implements the one rule that is always safe:
sequenceDiagram
participant App as Your code
participant C as LLMClient.stream
participant P as Provider A
participant Q as Provider B
App->>C: stream(request)
C->>P: open stream
P-->>C: 503 before any text
Note over C: nothing reached the caller yet, so retry or fall back is safe
C->>Q: open stream
Q-->>C: usage, then first text delta
Note over C: usage and empty thinking deltas draw nothing: held back until content
C-->>App: UsageEvent, TextDelta
Note over C,App: first content event delivered: from here on a failure is raised, never retried
Q-->>C: more deltas
C-->>App: TextDelta ...
Q-->>C: terminal event
C-->>App: Done with the assembled Response- Before the first content event reaches the caller: a failure is handled like any other: retry, then fall back. "Content" is anything the caller's UI could render: answer text, reasoning text, or a tool call starting. Events that draw nothing (the
usageevent Anthropic sends first, an empty hidden-thinking delta) are held back and released only when the first content event commits the stream, so a retry never shows the consumer half of a discarded attempt. - After the first content event: a failure is raised, never silently retried, because restarting on another model would splice two different answers together. This is the conservative library-level rule: a library can't clear anyone's screen. An application that owns the UI can instead restart and send a
resetevent that clears everything it showed (03.3, 7.5). The exception carrieserr.partial, aResponsebuilt from what arrived (itsusageisNonewhen the provider never reported it), so you can log it, bill for it approximately, or continue deliberately (03.3, 7.5 and 7.6).
The empty-delta detail is a real trap, not a nicety. Claude 5.x opens a thinking block with an empty thinking_delta (display defaults to "omitted": Anthropic's thinking docs). The first version counted any ReasoningDelta as content, so that empty delta committed the stream, and a 529 a moment later was raised to the user although no visible output existed yet. _is_content now treats a reasoning delta as content only when it has text, and test_an_empty_thinking_delta_does_not_commit_the_stream pins it (it fails against the old rule).
# provider_agnostic/client.py: what counts as content, and one streaming attempt
def _is_content(ev: StreamEvent) -> bool:
"""Content = anything the caller's UI could draw: answer text, REASONING TEXT, or a tool call starting.
An empty reasoning delta draws nothing (Claude 5.x opens a thinking block with one), so it is not content."""
if isinstance(ev, ReasoningDelta):
return bool(ev.text)
return isinstance(ev, (TextDelta, ToolCallStart, ToolCallDelta))
class _StreamAttempt:
"""One streaming attempt: feeds raw events to the parser and applies the commit rule (lesson 03.11, 5.1).
Events that draw nothing are held back until the first CONTENT event commits the stream, so a retry before that
point never shows the consumer half of a discarded attempt."""
def __init__(self, parser: StreamParser) -> None:
self.parser, self.pending, self.committed = parser, [], False
def feed(self, raw: Any) -> list[StreamEvent]:
if isinstance(raw, Opened): # the HTTP headers: the provider's request ID
self.parser.b.request_id = raw.request_id
return []
out: list[StreamEvent] = []
for ev in self.parser.feed(raw):
if self.committed:
out.append(ev)
elif _is_content(ev):
self.committed = True
out += [*self.pending, ev]
self.pending = []
else:
self.pending.append(ev)
return out
def finish(self, provider: str) -> Response:
if not self.parser.b.ended: # a body that just stops is not an answer
raise ServerError("the stream ended without a terminal event", provider=provider)
return self.parser.finish()
def flush(self) -> list[StreamEvent]:
out, self.pending = self.pending, []
return out# provider_agnostic/client.py: streaming with commit-on-first-content
def stream(self, req: Request) -> Iterator[StreamEvent]:
"""Yields canonical events, ending with Done(response). Retries and fallback happen only BEFORE the first
content event reaches you: after that, silently switching models would mix two answers (lesson 03.3, 7.5).
Close the generator early (break, `with contextlib.closing(...)`) and the abandoned hook fires."""
run = self._start(req)
state: _StreamAttempt | None = None
started, done = self.clock(), False
try:
while True:
spec, ad = run.spec, self.adapter(run.spec)
started, state = self.clock(), _StreamAttempt(ad.new_stream())
try:
with closing(ad.open_stream(ad.build(run.req), run.timeout())) as raw_events:
for raw in raw_events:
yield from state.feed(raw)
resp = state.finish(spec.provider)
except Exception as exc:
err = exc if isinstance(exc, LLMError) else wrap(exc, spec.provider)
run.record(ok=False, started=started, err=err)
action, wait = run.decide(err)
if state.committed or action == "raise":
err.partial = state.parser.finish() # what arrived before it broke (usage may be None)
raise self._fail(run, err) from (exc if err is not exc else None)
if action == "retry":
self.sleep(wait)
else:
run.advance()
continue
run.record(ok=True, started=started, resp=resp)
yield from state.flush()
done = True # from here on the response is complete
yield Done(response=self._finalize(run, resp, spec))
return
except GeneratorExit: # the consumer walked away
if state is not None and not done:
self._abandon(run, state, started)
raiseThe async twin, astream(), is the same code with async for (03.9 covers running many streams at once).
5.2 Structured output: the native mechanism per provider#
Pass a Pydantic class as Request.output_schema. The adapter chooses the provider's constrained mechanism (03.4, Part 3) rather than "please reply in JSON" in the prompt:
| Route | Where the schema goes | Schema dialect |
|---|---|---|
| OpenAI Responses | text.format = {"type": "json_schema", "name", "schema", "strict": true} |
OpenAI strict (every property required, additionalProperties: false) |
| OpenAI Chat, OpenRouter, Ollama | response_format = {"type": "json_schema", "json_schema": {...}} |
OpenAI strict |
| Anthropic | output_config.format = {"type": "json_schema", "schema"} |
anthropic.transform_schema() (public): unsupported constraints are moved into descriptions |
Gemini generate_content |
response_mime_type="application/json" and response_json_schema |
The Pydantic schema as it is |
| Gemini Interactions | response_format = {"type": "text", "mime_type": "application/json", "schema"} |
The Pydantic schema as it is |
# provider_agnostic/schemas.py: three dialects behind three functions
"""provider_agnostic/schemas.py: JSON Schema for tools and structured output, in each provider's dialect.
Lesson 03.4 explains the dialects. The wrapper needs exactly one thing from them: given a Pydantic
model (or a plain schema dict), produce what each provider's strict mode accepts.
"""
from __future__ import annotations
import copy
import inspect
from typing import Any
import anthropic
from pydantic import BaseModel
def openai_strict(schema: type[BaseModel] | dict[str, Any]) -> dict[str, Any]:
"""OpenAI (and OpenRouter, Ollama): every property required, additionalProperties false.
PRIVATE helpers from the openai SDK: `responses.parse()` uses the same ones. They may change in
any release, so tests/test_parity_schemas.py pins their behaviour; revisit it when you upgrade openai."""
from openai.lib._pydantic import _ensure_strict_json_schema, to_strict_json_schema
if inspect.isclass(schema) and issubclass(schema, BaseModel):
return to_strict_json_schema(schema)
root = copy.deepcopy(schema)
return _ensure_strict_json_schema(root, path=(), root=root)
def anthropic_schema(schema: type[BaseModel] | dict[str, Any]) -> dict[str, Any]:
"""Anthropic: PUBLIC `transform_schema` (what messages.parse() uses): drops constraints the grammar
can't enforce into the field descriptions, adds additionalProperties false."""
return anthropic.transform_schema(schema)
def plain_schema(schema: type[BaseModel] | dict[str, Any]) -> dict[str, Any]:
"""Gemini takes the Pydantic schema as it is (response_json_schema / Interactions schema)."""
return schema.model_json_schema() if inspect.isclass(schema) else schema
def schema_name(model: type[BaseModel]) -> str:
return model.__name__The wrapper validates the reply itself, on every route. The SDKs' parse helpers behave differently when something goes wrong: responses.parse and messages.parse raise ValidationError, Gemini's .parsed is silently None (03.4, 3.9). The wrapper avoids the helpers, sends the schema itself, and runs model_validate_json on the text only when the finish reason is STOP:
# provider_agnostic/client.py: one validation step for every adapter
def _finish(self, run: _Run, resp: Response, spec: ModelSpec) -> Response:
"""Everything that happens to a successful response, identically for sync, async and streams."""
self._stamp(run, resp, spec)
schema = run.req.output_schema
if schema is not None and resp.finish_reason is FinishReason.STOP:
try:
resp.parsed = schema.model_validate_json(resp.text)
except ValidationError as exc:
err = OutputInvalid(f"reply did not match {schema.__name__}: {exc.errors()[0]['msg']}",
provider=spec.provider, request_id=resp.request_id)
err.response = resp # the reply was PAID FOR: keep its text, usage and cost reachable
raise err from exc
for h in self.hooks: # response middleware
try:
resp = h.after(run.ctx, run.req, resp)
except Exception as exc:
if not h.fail_closed: # an observer: contain it
log.warning("observer hook %s.after failed: %s", type(h).__name__, type(exc).__name__)
continue
err = exc if isinstance(exc, LLMError) else HookError(
f"hook {type(h).__name__}.after raised {type(exc).__name__}: the response was withheld", code="hook_failed")
err.response = err.response or resp # billed, so it stays visible to the error hooks
raise err from (None if err is exc else exc)
return respA reply that fails validation was paid for, so OutputInvalid carries it: err.response holds the text, usage and cost, the error hooks fire (JsonlCostHook writes outcome: "invalid", MetricsHook counts failed.OutputInvalid), and the attempt log is intact. The first version raised from _finish before any hook ran, so the most common structured-output failure was billed and invisible. That gives you the consistent outcomes 03.4, 6.4 asks for: a truncated reply has finish_reason=LENGTH and no parsed (check it, or call raise_for_finish), a refusal has REFUSAL and no parsed, and a reply that finishes normally but doesn't fit the schema raises OutputInvalid with the Pydantic error as __cause__. Validate-and-retry with the error fed back to the model is the next layer up (03.4, Part 7), and belongs in your application, where you know how to word the correction.
Three honest limits of "one schema, five routes":
- Provider schema subsets differ (03.4, Part 4). A schema that works on OpenAI may be rejected by another provider (recursion,
oneOf,patternflavours, nesting depth). The wrapper does not lint schemas. Run 03.4's pre-flight linter in CI against every provider in the fallback chain. - OpenRouter forwards to whatever endpoint it picks, and not every endpoint enforces schemas. For strict behaviour, pass OpenRouter's
provider.require_parametersthroughextra={"openrouter": {"extra_body": {"provider": {"require_parameters": True}}}}(03.4, 3.6). - The local stand-in doesn't enforce every route. Ollama's Anthropic route ignores
output_config, so the local registry declaresstructured_output: falsefor it and the wrapper refuses before sending (Part 7).
5.3 Tool calls and ID threading#
Tool calling is where abstractions leak most, because each provider threads IDs differently. The canonical design needs three rules (03.5, Part 16):
- Every
ToolCallParthas anid, and everyToolResultPartechoes it ascall_id. On OpenAI Responses this is the item'scall_id(not itsid, the classic bug); on Chat and OpenRoutertool_calls[].id; on Anthropictool_use.id; on Interactions the stepid. The adapter picks the right field in both directions. Treat IDs as opaque. - Gemini
generate_contentmay send no ID at all (current models fill it in; older models don't). The canonical call then hasid="", the result carries thename, and Gemini matches by name and order. The wrapper never invents an ID. - The assistant turn goes back whole (03.5, 6.8).
response.messageholds every part, including thenativeitem for each call and any reasoning, so you append that to the history, not a rebuilt copy. The adapter replays natives for its own API and rebuilds calls fromid,nameandargumentsfor others.
The canonical round trip looks the same on every provider:
first = client.complete(Request(model="fast", tools=[tool], messages=[Message.user("Weather in Paris?")]))
call = first.tool_calls[0]
output, is_error = run_tool(call.name, call.arguments) # your code: 03.5, Part 7
history = [Message.user("Weather in Paris?"), first.message, # the whole assistant turn
Message.tool_results(ToolResultPart(call_id=call.id, name=call.name, content=output, is_error=is_error))]
second = client.complete(Request(model="fast", tools=[tool], messages=history))The tool-message translation is where the four shapes diverge. The test below (from the suite in Part 11) pins exactly where a canonical tool message lands on each provider, and is worth reading as a reference:
# tests/test_wire.py: where a tool result lands, per provider
def test_tool_result_placement(monkeypatch) -> None:
for k in ("OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GEMINI_API_KEY", "OPENROUTER_API_KEY"):
monkeypatch.setenv(k, "x")
history = [Message.user("w?"),
Message(role="assistant", parts=[ToolCallPart(id="call_1", name="get_weather", arguments={"city": "Paris"})]),
Message.tool_results(ToolResultPart(call_id="call_1", name="get_weather", content="12C")),
Message.user("Thanks, and tomorrow?")]
req = Request(model="x", messages=history, tools=[WEATHER])
items = build("luna", req)["input"]
assert items[1] == {"type": "function_call", "call_id": "call_1", "name": "get_weather", "arguments": '{"city": "Paris"}'}
assert items[2] == {"type": "function_call_output", "call_id": "call_1", "output": "12C"}
msgs = build("luna-chat", req)["messages"]
assert msgs[2] == {"role": "tool", "tool_call_id": "call_1", "content": "12C"}
a = build("haiku", req)["messages"]
assert [m["role"] for m in a] == ["user", "assistant", "user"] # tool result + next user text MERGED
assert a[2]["content"][0] == {"type": "tool_result", "tool_use_id": "call_1", "content": "12C"} # and it comes FIRST
assert a[2]["content"][1]["type"] == "text"
g = dump(build("flash", req))["contents"]
assert g[2]["parts"][0]["function_response"] == {"name": "get_weather", "response": {"output": "12C"}, "id": "call_1"}
steps = build("flash-interactions", req)["input"]
assert {"type": "function_result", "call_id": "call_1", "name": "get_weather", "result": "12C", "is_error": False} in stepsWhat the wrapper does not do is run the loop. Executing tools, validating arguments, step limits, parallel-call ordering and error handling are 03.5 and Module 08A; the wrapper only makes the round trip uniform, which is all it should do. parallel_tool_calls=False is translated where a switch exists (parallel_tool_calls on OpenAI, disable_parallel_tool_use on Claude). Gemini has no switch, so the registry marks its routes parallel_tool_switch: false and the request raises UnsupportedFeature instead of dropping the setting (the first version dropped it silently, while this very paragraph said Gemini has no switch): match results by ID and order, and expect parallel calls there. is_error on a ToolResultPart is native on Anthropic (is_error), Gemini ({"error": ...}) and Interactions (is_error). OpenAI has no such field (03.5, 7.4), so the adapters send the text with an Error: prefix, a visible, documented translation and not a drop.
5.4 Media: images and PDFs#
ImagePart and DocumentPart translate to input_image / input_file (Responses), image_url / file (Chat), image / document blocks (Anthropic), inline_data or file_data parts (Gemini) and image / document content (Interactions). 03.6, Part 7 gives a different default per provider (Claude: media first; OpenRouter: text first; Gemini: test both), so part order is a per-provider setting the caller chooses, and the wrapper preserves the order you give it.
What the wrapper adds is the capability check. Whether a provider fetches an https image URL itself, or accepts PDFs at all, is recorded in the registry, and check_capabilities() raises before anything is sent (7.3). The local stand-in, for example, accepts neither on its text-only model, and says so. Image cost depends on four different token rules (03.6, Part 3); the wrapper reports the real usage afterwards rather than trying to predict it. File IDs from the Files APIs (03.6, Part 5) are provider-specific, so they go through extra.
5.5 Reasoning effort and opaque reasoning#
Lesson 02.8, 3.6 built an effort adapter and said "Module 03 builds a fuller multi-provider client". This is it, folded in rather than rebuilt: the lookup table of each model's lowest accepted setting moved from a Python dict into the registry (reasoning_off: per entry), and the translation moved into each adapter, because "off" means something different for each model, not each provider:
"""s5_reasoning_demo.py: one app-level reasoning setting, translated per MODEL; and opaque reasoning that
must not cross providers (layer 1: build() is pure, no network, no key)."""
import json
import os
from provider_agnostic import Message, Native, ReasoningPart, Registry, Request, TextPart
from provider_agnostic.client import ADAPTERS
for name in ("OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GEMINI_API_KEY", "OPENROUTER_API_KEY"):
os.environ[name] = "sk-test"
registry = Registry.load()
def build(key: str, request: Request) -> dict:
spec = registry.models[key]
return ADAPTERS[spec.api](spec).build(request)
def reasoning_part(params: dict) -> str:
keys = ("reasoning", "reasoning_effort", "thinking", "output_config", "extra_body", "config", "generation_config")
found = {}
for k in keys:
if k in params:
v = params[k]
v = v.model_dump(mode="json", exclude_none=True) if hasattr(v, "model_dump") else v
if k == "config":
v = {"thinking_config": v.get("thinking_config")}
if k == "generation_config":
v = {x: v[x] for x in ("thinking_level", "thinking_summaries") if x in v}
if k == "extra_body" or v:
found[k] = v
return json.dumps(found, separators=(",", ":"))
print("One setting (reasoning_effort), seven model routes:")
for key in ("luna", "sol", "haiku", "sonnet", "flash", "flash-interactions", "or-luna"):
for level in ("off", "high"):
params = build(key, Request(model="m", messages=[Message.user("x")], reasoning_effort=level))
print(f" {key:19s} {level:4s} -> {reasoning_part(params)}")
print("\nA Claude turn that carries a signed thinking block, replayed to three different routes:")
thinking = {"type": "thinking", "thinking": "The user wants Paris.", "signature": "EqQBCkYI..."}
history = [Message.user("Capital of France?"),
Message(role="assistant", parts=[ReasoningPart(text="The user wants Paris.",
native=Native(provider="anthropic", api="messages", payload=thinking)),
TextPart(text="Paris.")]),
Message.user("And Spain?")]
request = Request(model="m", messages=history)
claude = build("sonnet", request)["messages"][1]["content"]
print(" sonnet (same provider) :", json.dumps(claude, separators=(",", ":")))
print(" luna (other provider) :", json.dumps(build("luna", request)["input"][1], separators=(",", ":")))
gem = build("flash", request)["contents"][1].model_dump(mode="json", exclude_none=True)
print(" flash (other provider) :", json.dumps(gem, separators=(",", ":")))One setting (reasoning_effort), seven model routes:
luna off -> {"reasoning":{"effort":"none"}}
luna high -> {"reasoning":{"effort":"high"}}
sol off -> {"reasoning":{"effort":"low"}}
sol high -> {"reasoning":{"effort":"high"}}
haiku off -> {"thinking":{"type":"disabled"}}
haiku high -> {"thinking":{"type":"adaptive","display":"summarized"},"output_config":{"effort":"high"}}
sonnet off -> {"thinking":{"type":"between_tools"}}
sonnet high -> {"thinking":{"type":"adaptive","display":"summarized"},"output_config":{"effort":"high"}}
flash off -> {"config":{"thinking_config":{"include_thoughts":true,"thinking_level":"LOW"}}}
flash high -> {"config":{"thinking_config":{"include_thoughts":true,"thinking_level":"HIGH"}}}
flash-interactions off -> {"generation_config":{"thinking_level":"low","thinking_summaries":"auto"}}
flash-interactions high -> {"generation_config":{"thinking_level":"high","thinking_summaries":"auto"}}
or-luna off -> {"extra_body":{"reasoning":{"effort":"none"}}}
or-luna high -> {"extra_body":{"reasoning":{"effort":"high"}}}
A Claude turn that carries a signed thinking block, replayed to three different routes:
sonnet (same provider) : [{"type":"thinking","thinking":"The user wants Paris.","signature":"EqQBCkYI..."},{"type":"text","text":"Paris."}]
luna (other provider) : {"role":"assistant","content":"Paris."}
flash (other provider) : {"parts":[{"text":"Paris."}],"role":"model"}Read the first block. "Off" is a real switch on Luna (effort: none) and Haiku (thinking: disabled), "no up-front thinking" on Sonnet (between_tools), and merely the lowest accepted level on Sol and Gemini 3.8 Flash. Those models will still think, and you will still pay for it (02.8, 3.6). A "high" on one model is not the same amount of thinking as "high" on another, so treat the mapping as configuration you test per model (02.8, Part 10). The capability check refuses an effort other than off on a route that doesn't reason (the local stand-in returns a 400 for any thinking config), rather than quietly ignoring it.
Now the second block, which is the gotcha that makes provider-neutral reasoning hard. A signed Claude thinking block came back from a tool-using turn. Replayed to Claude, it goes back unchanged, signature and all (a modified or missing block breaks the next request on some models). Replayed to OpenAI or Gemini, it is dropped: opaque reasoning cannot cross providers, because it is encrypted or signed for the provider that made it, and the other providers neither accept nor understand it.
Reasoning text (summaries) is surfaced as ReasoningPart.text and ReasoningDelta, and is for display and logging only. Never feed it back as ordinary text.
5.6 Usage and cost#
Each adapter gets the canonical Usage by calling 03.7's cost_calc.from_* on the SDK object (from_openai_response, from_openai_chat, from_openrouter, from_anthropic, from_gemini, from_gemini_interaction) and converting the result: input and cache arithmetic, the tier that served the call, inference_geo, web searches and the cache-write lifetimes all come from that one calculator. On a stream the same functions run on what the stream provides: the Responses terminal event carries the whole object, a Chat chunk has the usage, model and service_tier the function reads, and Anthropic's message_start and message_delta are merged into a message-shaped view. Rather than trusting any of it, the test suite compares every adapter's Usage to 03.7's own output on the same fixtures, for plain calls and streams, including fast mode, us inference, web searches, 1-hour and 12-hour cache writes, ultrafast and a Gemini flex header (Part 11).
Cost is then one call into 03.7's calculator and price table:
# provider_agnostic/cost.py: canonical Usage <-> 03.7's cost_calc.Usage, and Usage -> dollars
"""provider_agnostic/cost.py: canonical Usage <-> lesson 03.7's `cost_calc.Usage`, and Usage -> dollars.
The adapters do NOT redo 03.7's arithmetic. They call `cost_calc.from_openai_response`, `from_anthropic`,
`from_gemini`... on the SDK object, which already knows the cached-token convention, fast mode (2x), the geo
multiplier, web-search fees, 12-hour cache writes and every service tier, and convert the result with
`usage_from_cost_calc`. A price table and a calculator that drift from the adapters were the bug; one source is the fix.
"""
from __future__ import annotations
import datetime as dt
import cost_calc # lesson 03.7
from prices import PriceTable # lesson 03.7
from .registry import ModelSpec
from .types import Cost, Usage
def usage_from_cost_calc(u: cost_calc.Usage) -> Usage:
return Usage(uncached_input_tokens=u.input, cached_input_tokens=u.cached_input, cache_write_tokens=dict(u.cache_writes),
output_tokens=u.output, reasoning_tokens=u.reasoning, tier=u.tier, geo=u.geo, regional=u.regional,
web_searches=u.web_searches, grounding_searches=u.grounding_searches,
modality_input=dict(u.modality_input), reported_cost_usd=u.reported_cost)
def to_cost_calc(usage: Usage, spec: ModelSpec) -> cost_calc.Usage:
"""The price table is keyed by the registry's provider and model ID, not by the dated snapshot the provider ran."""
return cost_calc.Usage(provider=spec.provider, model=spec.model, input=usage.uncached_input_tokens,
cached_input=usage.cached_input_tokens, cache_writes=dict(usage.cache_write_tokens),
output=usage.output_tokens, reasoning=usage.reasoning_tokens, tier=usage.tier,
geo=usage.geo, regional=usage.regional, web_searches=usage.web_searches,
grounding_searches=usage.grounding_searches, modality_input=dict(usage.modality_input),
reported_cost=usage.reported_cost_usd)
def price_usage(usage: Usage | None, spec: ModelSpec, table: PriceTable | None) -> Cost:
if usage is None:
return Cost(usd=None, source="unknown")
if spec.free:
return Cost(usd=0.0, source="computed", price_version="free-local")
if table is None:
return Cost(usd=None, source="unknown")
try:
result = cost_calc.price(to_cost_calc(usage, spec), table, dt.date.today())
except (KeyError, ValueError): # no price, a tier the table lacks, or OpenRouter without usage.cost: unknown, NEVER zero
return Cost(usd=None, source="unknown", price_version=table.version)
return Cost(usd=result.usd, source="provider" if usage.reported_cost_usd is not None else "computed",
price_version=table.version)Four rules are encoded here, all from 03.7:
- Unknown is
None, never0. A model missing fromprices.yaml, a service tier the table has no rate for, or an OpenRouter response withoutusage.costgivesCost(usd=None, source="unknown"). Usage that is all zeros next to a real answer (a proxy can send it on streams) is unknown too, not a free call. A silent$0is how dashboards stay wrong for months. - Free local routes say so.
free: truein the registry gives an honest$0.0, so the stand-in doesn't pollute "unknown" counts. - OpenRouter's reported cost wins over arithmetic (
source="provider"), because it includes discounts and fees (03.7, 9.3). - Prices live in one place. The registry has no prices;
prices.yamldoes. Two price sources always drift apart.
Which paths are priced, exactly. Every call that returns a response is priced, whatever happened to it afterwards: a success; a reply that failed schema validation (err.response); a reply discarded for the fallback (its own Attempt.usage and cost_usd, the discarded_cost_usd of the final record); a stream the consumer abandoned (the usage the provider had reported by then); and a stream that broke half way (err.partial, with the usage it carried, None when the provider never sent any). A failed attempt with no response (a 503, a connection reset) is not priced: a 503 is normally not billed, a timeout may be (03.8, 6.6), and those stay visible in Response.attempts and the logs. 03.7, Part 13 shows how to reconcile your numbers against the provider's invoice.
Part 6: Errors: one hierarchy, nothing swallowed#
Deep-dive
The hard part of error handling across providers was lesson 03.8: four SDKs raise roughly fifteen different exception classes, and a 429 can mean "slow down" or "you are out of money". llm_errors.classify() from that lesson already reads any of them and returns one decision. This lesson only turns that decision into classes you can except on.
# provider_agnostic/errors.py (the hierarchy)
class LLMError(Exception):
"""Base class. `retryable` says whether the SAME request may succeed if sent again later."""
retryable: bool = False
def __init__(self, message: str, *, provider: str | None = None, status: int | None = None,
code: str | None = None, request_id: str | None = None,
retry_after_s: float | None = None) -> None:
super().__init__(message)
self.message, self.provider, self.status, self.code = message, provider, status, code
self.request_id, self.retry_after_s = request_id, retry_after_s
self.attempts: list = [] # filled by the client: every try that led here
self.partial: "Response | None" = None # streams: what arrived before the failure
self.response: "Response | None" = None # a COMPLETE response that was rejected after it was paid for
def __str__(self) -> str:
bits = [f"{self.provider}" if self.provider else "", f"HTTP {self.status}" if self.status else "",
self.code or "", f"request_id={self.request_id}" if self.request_id else ""]
detail = " ".join(b for b in bits if b)
return f"{self.message} [{detail}]" if detail else self.message # no empty "[]" when there is nothing to add
class RateLimited(LLMError): retryable = True # 429 that clears with time
class Overloaded(LLMError): retryable = True # 503 / 529: the provider is busy
class ServerError(LLMError): retryable = True # 500 / 502 / 504 / 409
class Timeout(LLMError): retryable = True # we gave up waiting; the call MAY still bill
class ConnectionFailed(LLMError): retryable = True # DNS, TLS, refused, reset
class QuotaExceeded(LLMError): pass # credits, spend cap, daily quota (often a 429!)
class AuthFailed(LLMError): pass # 401: wrong or revoked key
class PermissionDenied(LLMError): pass # 403: no access to this model or feature
class BadRequest(LLMError): pass # 400, 404, 413, 422: a bug in the request
class ContextTooLong(BadRequest): pass # trim the input, then try again
class Truncated(LLMError): pass # hit max_output_tokens (or the context window)
class Refused(LLMError): pass # the model declined
class ContentBlocked(LLMError): pass # a safety system blocked the prompt or answer
class ResponseFailed(LLMError): pass # an HTTP 200 whose body says "failed" with a permanent (or no) code
class UnsupportedFeature(LLMError): pass # capability check failed: nothing was sent
class OutputInvalid(LLMError): pass # structured output did not validate (the paid-for reply is on .response)
class ConfigError(LLMError): pass # bad registry, missing key, unknown alias
class HookError(LLMError): pass # a fail-closed hook raised: the call was stopped (cause = the hook's exception)flowchart TD
E["LLMError<br/>retryable, provider, status, code,<br/>request_id, retry_after_s, attempts, partial"] --> T["Retryable: RateLimited, Overloaded,<br/>ServerError, Timeout, ConnectionFailed"]
E --> A["Your side or your account:<br/>QuotaExceeded, AuthFailed, PermissionDenied, BadRequest"]
A --> C["ContextTooLong (a BadRequest)"]
E --> H["HTTP 200 outcomes:<br/>Truncated, Refused, ContentBlocked (you choose to raise),<br/>ResponseFailed (a body that says failed: always raised)"]
E --> L["Raised by this package:<br/>UnsupportedFeature, OutputInvalid, ConfigError, HookError"]| Class | Raised when | retryable |
Typical response |
|---|---|---|---|
RateLimited |
429 that clears with time | yes | back off, or fall back |
Overloaded |
503, 529 (Anthropic's "overloaded") | yes | back off, or fall back |
ServerError |
500, 502, 504, 409 | yes | a few retries |
Timeout |
we stopped waiting | yes, but the call may still have run and billed | retry once (Policy.max_timeout_attempts=2 tries in all), then fall back (8.3) |
ConnectionFailed |
DNS, TLS, refused, reset | yes | retry |
QuotaExceeded |
credits, a spend cap, a daily quota (often a 429!) | no | alert a human; a different provider may still work |
AuthFailed |
401 | no | alert: a revoked or wrong key |
PermissionDenied |
403 | no | no access to this model or feature |
BadRequest |
400, 404, 413, 422 | no | a bug in your request |
ContextTooLong |
the prompt exceeds the context window | no | trim the input (02.7, 2.6) |
Truncated, Refused, ContentBlocked |
only when you call raise_for_finish(resp), or when a 200's body carries a policy failure code (bio_policy) |
no | your decision (03.8, Part 10) |
ResponseFailed |
an HTTP 200 whose body says failed, cancelled or budget_exceeded with a permanent (or no) code |
no | read err.code and err.response; do not retry the same request |
UnsupportedFeature |
the capability check failed; nothing was sent | no | fix the request or the alias |
OutputInvalid |
a reply finished normally but didn't match the schema | no | validate-and-retry in your app |
ConfigError |
unknown alias, a typo in the registry, a missing key variable anywhere in the alias chain | no | fix the configuration |
HookError |
a fail-closed hook raised (every before, and an after with fail_closed = True): __cause__ is the hook's exception |
no | fix the hook; the call was stopped on purpose (Part 9) |
retryable is an instance attribute: the class sets the default, and wrap() overrides it from the server's own x-should-retry verdict when it sends one (03.8, 4.3).
# provider_agnostic/errors.py: the mapping from 03.8's classifier, and the one rule that matters
def wrap(exc: BaseException, provider: str) -> LLMError:
"""Turn any SDK exception into the matching LLMError. Use as `raise wrap(e, p) from e`."""
if isinstance(exc, LLMError):
return exc
# An `error` object inside an SSE chunk (OpenRouter documents it): the openai SDK raises a plain APIError with no
# HTTP status, and the code is in the body. Read it like an error-in-200 instead of guessing "unknown".
body = getattr(exc, "body", None)
if (type(exc) is openai.APIError and isinstance(body, dict) and isinstance(body.get("code"), int)):
return error_from_body(provider, body)
failure: Failure = classify(exc)
cls = _BY_KIND[failure.kind]
err = cls(failure.message, provider=provider, status=failure.status, code=failure.code,
request_id=failure.request_id, retry_after_s=failure.retry_after)
# x-should-retry (the server's own verdict) can override the class default, per instance
err.retryable = failure.retryable
return err
def error_from_body(provider: str, error: dict | None, *, request_id: str | None = None) -> LLMError:
"""OpenRouter (and some proxies) can answer HTTP 200 with an `error` object and no `choices`
(lesson 03.8, Part 10). Treat it as the failure it is: the class the same HTTP status would have given.
`error` looks like {"code": 429, "message": ...}. Codes that are not 4xx or 5xx numbers are server trouble."""
error = error or {}
code = error.get("code")
status = code if isinstance(code, int) else None
message = str(error.get("message") or "provider returned an error inside HTTP 200")
cls: type[LLMError] = {429: RateLimited, 502: Overloaded, 503: Overloaded, 529: Overloaded, 408: Timeout,
402: QuotaExceeded, 401: AuthFailed, 403: PermissionDenied}.get(status or 0, ServerError)
if status in (400, 404, 413, 422): # a bug in the request, not the server
cls = ContextTooLong if _context_hint(message) else BadRequest
return cls(message, provider=provider, status=status, code=str(code) if code is not None else None,
request_id=request_id)
def error_from_failed(provider: str, code: str | None, message: str | None = None, *,
request_id: str | None = None) -> LLMError:
"""An HTTP 200 whose body says the response FAILED (OpenAI Responses `status: failed`, Interactions `failed`,
an `error` stream event...). Lesson 03.8, Part 10 sorts the codes: transient ones (`server_error`,
`rate_limit_exceeded`...) can succeed on a retry, everything else is permanent. We reuse its table
(TRANSIENT_FAILED_CODES) and only add the step 03.8 does not need: choosing a class you can `except` on."""
c = (code or "").lower()
text = message or f"the provider reported a failed response ({code or 'no error code'})"
cls: type[LLMError]
if c in TRANSIENT_FAILED_CODES:
cls = _FAILED_CLASS.get(c, ServerError)
elif "policy" in c:
cls = ContentBlocked # bio_policy, image_content_policy_violation...
elif c.startswith(("invalid_", "image_", "unsupported_", "empty_", "failed_to_download", "data_residency")):
cls = BadRequest # invalid_prompt, invalid_image_url...
else:
cls = ResponseFailed # cancelled, budget_exceeded, or no code at all
return cls(text, provider=provider, status=200, code=code, request_id=request_id)
def raise_if_failed(raw: Any, provider: str, request_id: str | None = None) -> None:
"""Raise when an SDK response object is a FAILED outcome. Detection is 03.8's check_response(), as is (it accepts a
whole response and the Interactions stream's terminal object); the message comes from `error_message`."""
outcome = check_response(raw)
if outcome.status is Status.FAILED:
raise error_from_failed(provider, outcome.error_code, error_message(raw), request_id=request_id)
def raise_for_finish(resp: "Response") -> "Response":
"""Opt-in strictness: turn a bad finish reason into an exception. Returns resp if it is usable.
`retryable` is the class default (False for all of these): the same request would not come back different."""
from .types import FinishReason as F
bad: dict[F, type[LLMError]] = {F.LENGTH: Truncated, F.CONTEXT_FULL: Truncated,
F.CONTENT_FILTER: ContentBlocked, F.REFUSAL: Refused,
F.ERROR: ResponseFailed}
cls = bad.get(resp.finish_reason)
if cls is None:
return resp
err = cls(f"finish_reason={resp.finish_reason.value} (provider said {resp.raw_finish_reason!r})",
provider=resp.provider, request_id=resp.request_id, code=resp.raw_finish_reason)
err.response = resp
raise errThe rule that matters is raise ... from exc. The wrapper must never turn a provider's exception into a bare Exception("call failed"). Every canonical error keeps the SDK's original as __cause__ (with its status, headers and body), carries the provider's request ID (the first thing a support ticket needs), and carries attempts, the list of every try that led here. The client's raise self._fail(...) from exc line is that rule in code, and the contract suite asserts it for every adapter (Part 11).
A 200 that says failed is an error. OpenAI's Responses API answers HTTP 200 with status: "failed" and an error object (often server_error or rate_limit_exceeded); Interactions has failed, cancelled and budget_exceeded; a stream can end with response.failed or carry an error event; OpenRouter can end a choice with finish_reason="error". 03.8, Part 10 says transient codes inside a 200 are retried, and the first version of this client did not: it mapped them to FinishReason.ERROR, returned them as a normal Response with empty text, logged the attempt ok=True, and never retried or fell back. The fix is one rule applied in parse() and in every stream parser, before an attempt is recorded as successful: detection is 03.8's check_response(), used as is (it accepts the terminal object of an Interactions stream as well as a whole Interaction; the single extra rule here is that budget_exceeded, which 03.8 reports as INCOMPLETE, is a permanent error), the transient codes are 03.8's TRANSIENT_FAILED_CODES, and error_from_failed only adds the choice of a class you can except on (rate_limit_exceeded becomes RateLimited, server_error becomes ServerError, vector_store_timeout becomes Timeout, a *_policy code becomes ContentBlocked, invalid_* and image codes become BadRequest, anything else ResponseFailed). Transient classes are retried and may fall back; permanent ones raise once. The error's code is kept: an error event with rate_limit_exceeded used to become a generic ServerError.
"""s6b_failed_in_200_demo.py: an HTTP 200 whose body says "failed" is an error, retried when the code is transient (layer 3).
Six shapes, one rule: transient codes (server_error, rate_limit_exceeded...) are retried, everything else raises once.
The fixtures copy the documented shapes (lesson 03.8, Part 10); the SDKs and the wrapper are real."""
import os
from provider_agnostic import LLMClient, LLMError, Message, Policy, Registry, Request
from tests.fakes import FakeChat, FakeInteractions, FakeResponses, Server
for name in ("OPENAI_API_KEY", "GEMINI_API_KEY", "OPENROUTER_API_KEY"):
os.environ[name] = "sk-test"
registry = Registry.load()
ROUTES = {"luna": FakeResponses(), "or-luna": FakeChat(openrouter=True), "flash-interactions": FakeInteractions()}
CASES = [("luna", "failed", {"code": "server_error"}), ("luna", "failed", {"code": "rate_limit_exceeded"}),
("luna", "failed", {"code": "invalid_prompt"}), ("luna", "cancelled", {"code": "server_error", "status": "cancelled"}),
("or-luna", "finish_reason=error", {}), ("flash-interactions", "failed", {"code": "rate_limit_exceeded"}),
("flash-interactions", "budget_exceeded", {"code": None, "status": "budget_exceeded"})]
def client_for(key: str, fake, replies: list) -> tuple[LLMClient, Server]:
server = Server(replies, flavour=fake.flavour)
entry = {**registry.models[key].model_dump(exclude={"key"}), "base_url": fake.base_url}
return LLMClient(Registry({"version": "demo", "models": {key: entry}}), policy=Policy(max_attempts=3),
http_clients={key: server.clients()}, sleep=lambda s: None), server
print(f"{'route':19s} {'status inside the 200':20s} {'code':22s} {'requests':8s} outcome")
for key, label, kw in CASES:
fake = ROUTES[key]
client, server = client_for(key, fake, [fake.failed(**kw), fake.text("recovered")])
req = Request(model=key, messages=[Message.user("Hi")])
try:
resp = client.complete(req)
outcome = f"returned {resp.text!r} after attempts " + str([(a.ok, a.error_type) for a in resp.attempts])
except LLMError as err:
outcome = f"raised {type(err).__name__} (retryable={err.retryable})"
print(f"{key:19s} {label:20s} {str(kw.get('code')):22s} {server.n:<8d} {outcome}")Output (layer 3: each fixture is the documented shape, inside HTTP 200; the SDKs and the wrapper are real):
route status inside the 200 code requests outcome
luna failed server_error 2 returned 'recovered' after attempts [(False, 'ServerError'), (True, None)]
luna failed rate_limit_exceeded 2 returned 'recovered' after attempts [(False, 'RateLimited'), (True, None)]
luna failed invalid_prompt 1 raised BadRequest (retryable=False)
luna cancelled server_error 1 raised ResponseFailed (retryable=False)
or-luna finish_reason=error None 2 returned 'recovered' after attempts [(False, 'ServerError'), (True, None)]
flash-interactions failed rate_limit_exceeded 2 returned 'recovered' after attempts [(False, 'RateLimited'), (True, None)]
flash-interactions budget_exceeded None 1 raised ResponseFailed (retryable=False)Here are real mappings from every route (layer 3: each fixture follows the provider's documented error shape, 03.8, Part 3; the SDKs and the wrapper are real):
"""s6_errors_demo.py: provider errors in, canonical errors out (layer 3: the SDKs are real, the servers are mocks).
Each fixture copies the documented error shape of its provider (lesson 03.8, Part 3). One attempt each, no retries."""
import os
from provider_agnostic import LLMClient, LLMError, Message, Policy, Registry, Request, raise_for_finish
from tests.fakes import FakeAnthropic, FakeChat, FakeGemini, FakeInteractions, FakeResponses, Server
for name in ("OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GEMINI_API_KEY", "OPENROUTER_API_KEY"):
os.environ[name] = "sk-test"
registry = Registry.load()
ROUTES = [("luna", FakeResponses()), ("haiku", FakeAnthropic()), ("flash", FakeGemini()),
("flash-interactions", FakeInteractions()), ("or-luna", FakeChat(openrouter=True))]
HELLO = Request(model="m", messages=[Message.user("Hi")])
def client_for(key: str, fake, reply) -> LLMClient:
server = Server([reply], flavour=fake.flavour)
spec = registry.models[key]
mocked = Registry({"version": "demo", "models": {key: {**spec.model_dump(exclude={"key"}), "base_url": fake.base_url}}})
return LLMClient(mocked, policy=Policy(max_attempts=1), http_clients={key: server.clients()})
print(f"{'route':19s} {'case':11s} {'SDK exception (the __cause__)':36s} -> {'canonical':17s} retryable status request_id")
for key, fake in ROUTES:
for case in ("rate_limit", "overloaded", "quota", "context"):
with client_for(key, fake, fake.error(case)) as client:
try:
client.complete(HELLO.model_copy(update={"model": key}))
except LLMError as err:
cause = type(err.__cause__)
print(f"{key:19s} {case:11s} {cause.__module__.split('.')[0] + '.' + cause.__name__:36s} -> "
f"{type(err).__name__:17s} {str(err.retryable):9s} {err.status} {err.request_id}")
print()
print("HTTP 200 that is not a success (nothing raised until you ask):")
for key, fake in [r for r in ROUTES if r[0] != "flash-interactions"]: # Interactions documents no refusal signal
with client_for(key, fake, fake.refusal()) as client:
resp = client.complete(HELLO.model_copy(update={"model": key}))
try:
raise_for_finish(resp)
except LLMError as err:
print(f"{key:19s} finish={resp.finish_reason.value:15s} raw={resp.raw_finish_reason!r:34s} -> {type(err).__name__}")route case SDK exception (the __cause__) -> canonical retryable status request_id
luna rate_limit openai.RateLimitError -> RateLimited True 429 req_err_1
luna overloaded openai.InternalServerError -> Overloaded True 503 req_err_1
luna quota openai.RateLimitError -> QuotaExceeded False 429 req_err_1
luna context openai.BadRequestError -> ContextTooLong False 400 req_err_1
haiku rate_limit anthropic.RateLimitError -> RateLimited True 429 req_err_3
haiku overloaded anthropic.OverloadedError -> Overloaded True 529 req_err_3
haiku quota anthropic.APIStatusError -> QuotaExceeded False 402 req_err_3
haiku context anthropic.BadRequestError -> ContextTooLong False 400 req_err_3
flash rate_limit google.ClientError -> RateLimited True 429 None
flash overloaded google.ServerError -> Overloaded True 503 None
flash quota google.ClientError -> RateLimited True 429 None
flash context google.ClientError -> ContextTooLong False 400 None
flash-interactions rate_limit google.RateLimitError -> RateLimited True 429 None
flash-interactions overloaded google.InternalServerError -> Overloaded True 503 None
flash-interactions quota google.RateLimitError -> QuotaExceeded False 429 None
flash-interactions context google.BadRequestError -> ContextTooLong False 400 None
or-luna rate_limit openai.RateLimitError -> RateLimited True 429 req_err_2
or-luna overloaded openai.InternalServerError -> Overloaded True 503 req_err_2
or-luna quota openai.APIStatusError -> QuotaExceeded False 402 req_err_2
or-luna context openai.BadRequestError -> ContextTooLong False 400 None
HTTP 200 that is not a success (nothing raised until you ask):
luna finish=refusal raw='completed' -> Refused
haiku finish=refusal raw='refusal' -> Refused
flash finish=content_filter raw='SAFETY' -> ContentBlocked
or-luna finish=refusal raw='stop' -> RefusedStudy the second column against the fourth. Thirteen distinct SDK exception class names (openai.RateLimitError, openai.InternalServerError, anthropic.OverloadedError, a plain anthropic.APIStatusError for 402, google.genai.errors.ClientError and ServerError, the separate Interactions family, and more) become four canonical classes in this table, and application code catches only those. Three lines in the output are worth a second look:
- Quota vs rate limit. OpenAI's
insufficient_quota429 becomesQuotaExceeded(not retryable), and so does Anthropic's 402billing_errorand OpenRouter's 402. But Geminigenerate_content'sRESOURCE_EXHAUSTEDbecomesRateLimitedfor both the "slow down" and the "out of quota" fixtures, because nothing in the body distinguishes them (03.8, 4.2). The contract suite records this as an explicit, named exception to the rule, and the retry budget (a few attempts, then fall back) caps the cost of being wrong. Interactions does sendquota_exceeded, so it classifies correctly. - The context-too-long check is by message text (
"context window","prompt is too long","input token count","maximum context length"...), because providers send it as a plain 400. The last one is OpenRouter's wording, which the first version of 03.8's hint list missed and this package patched with a private copy; 03.8's final list has it, so there is one list again. It is a small, real example of why a hand-maintained classifier needs a test per provider. - Request IDs are present on every route that sends a header. Google sends no request-ID header (03.8, Part 12); for Gemini, record your own
call_idand the time. Theor-luna contextrow showsNonetoo, for a different reason: OpenRouter's 400 body fixture here carries no header, and a real one may.
The bottom block shows HTTP-200 outcomes. Nothing raised until raise_for_finish() was called, and the Gemini block arrives as a SAFETY finish reason, not an error. The Interactions route is excluded because Google documents no refusal signal for it; its fixture would be invented.
Part 7: The capability registry#
7.1 Aliases, entries and a YAML file#
Application code should say model="fast", not model="gpt-6-luna". The alias names a role; the registry maps it to an ordered chain of concrete model entries (the fallback order, Part 8); each entry records everything the wrapper needs to know about that route.
# provider_agnostic/models.yaml (abridged; the full file is in the appendix)
version: 2026-11-04
aliases:
fast: [luna, haiku, flash] # cheap and quick; three providers
smart: [sol, sonnet] # harder tasks
vision: [flash, haiku, luna] # image input
cheap-or: [or-luna, or-haiku] # everything through OpenRouter
models:
luna:
provider: openai
api: responses
model: gpt-6-luna
api_key_env: OPENAI_API_KEY
context_window: 1050000 # 02.9: "1.05M", includes the output
max_output_tokens: 128000
default_max_output_tokens: 1024 # OUR default for requests that don't say; not a provider limit
reasoning_off: none # lowest setting this MODEL accepts (02.8, 3.6)
capabilities: {tools: true, forced_tool_choice: true, structured_output: true, images: true,
image_urls: true, documents: true, reasoning: true, stream_usage: true,
stop: false, # the Responses API has no stop parameter: stop=[...] raises
parallel_tool_switch: true, strict_tools: true}
sonnet:
provider: anthropic
api: messages
model: claude-sonnet-5-5
api_key_env: ANTHROPIC_API_KEY
context_window: 1000000
max_output_tokens: 128000
default_max_output_tokens: 4096
reasoning_off: between_tools
capabilities: {tools: true, forced_tool_choice: false, # any/tool tool_choice is a 400 here
structured_output: true, images: true, image_urls: true, documents: true,
reasoning: true, stream_usage: true,
stop: true, parallel_tool_switch: true, strict_tools: true}
or-haiku:
provider: openrouter
api: chat
model: anthropic/claude-haiku-5.5 # OpenRouter IDs use dots
api_key_env: OPENROUTER_API_KEY
base_url: https://openrouter.ai/api/v1
base_url_env: OPENROUTER_BASE_URL
headers: {HTTP-Referer: "https://example.com/wrapper-demo", X-OpenRouter-Title: "wrapper demo"} # NOT secret
# headers_env: {X-Portkey-Api-Key: PORTKEY_API_KEY} # a gateway key: the variable NAME, never the value
# ... flash, flash-interactions, sol, haiku, luna-chat, or-luna: see the appendixDesign notes:
- Aliases are chains, and a bare entry key is a chain of one.
model="haiku"pins one route;model="fast"allows fallback. The caller chooses whether fallback is acceptable by choosing which name to use. - The same model through two APIs is two entries (
lunaon Responses,luna-chaton Chat;flashandflash-interactions). The API is part of the route, because capabilities and failure modes differ per API. - Capabilities are facts you verified, with a date.
forced_tool_choice: falseon Sonnet is the 400 documented in 03.5, 3.3 for Opus 5.5, Sonnet 5.5, Fable 5.2 and 5.1, and Mythos 5.2 and 5.1 (Anthropic's errors page lists the same models). Three flags record where a canonical option has no equivalent:stop(the Responses API has none),parallel_tool_switch(Gemini has no way to switch parallel calls off) andstrict_tools(does the server enforce a strict tool schema? Ollama and OpenRouter do not promise it). These values are as of November 2026; the file'sversionis the date you last checked. Several are conservative guesses where documentation is silent: treat a capability asfalseuntil verified. - No prices. They live in
prices.yaml(03.7, Part 4). A test checks every registry entry has a price or isfree. - Environment overrides.
base_url_envlets a deployment point a route at a proxy or the local stand-in without editing the file (03.1, 7.2). - No credential ever lives in the file.
api_key_envis the name of a variable. A gateway that needs a key header (a LiteLLM proxy, Portkey or Helicone: the gateway kinds of 1.4 and 13.8b) usesheaders_env, a map from header name to variable name, resolved at SDK-construction time and never stored in the model, somodel_dump()andrepr()cannot show it. A literal header whose name looks like a credential (authorization,*-api-key,*token*...) is rejected when the file loads. The local stand-in entries readLOCAL_API_KEY, neverOPENAI_API_KEY,ANTHROPIC_API_KEYorGEMINI_API_KEY: a developer with a real key in.envmust not send it tolocalhost. - Validation at load time, and strictly. Both models forbid unknown keys, so
capabilites:ordefault_max_output_token:is aConfigErrorthat names the entry, not a silent fall back to the defaults (the first version's pydantic default wasextra="ignore"). An alias with an empty chain, a duplicated entry, or the same name as a model entry (which would makemodel="haiku"ambiguous) fails, and so does a missingversion:, a file that is empty or not a mapping, and amodels:oraliases:section of the wrong shape (a list where a mapping belongs, a string where a chain belongs). An alias that names a missing entry fails when the file is loaded, not at 3 a.m. under load:
# provider_agnostic/registry.py: the model entry, the loader and the chain lookup
class Capabilities(_Strict):
tools: bool = False
forced_tool_choice: bool = False # tool_choice "required" or one named tool
structured_output: bool = False
images: bool = False
image_urls: bool = False # can the provider fetch an https image URL itself?
documents: bool = False # PDFs as input
reasoning: bool = False # accepts a reasoning effort other than "off"
stream_usage: bool = True # reports usage inside a stream
stop: bool = False # honours stop sequences (the Responses API has no such parameter)
parallel_tool_switch: bool = False # can parallel_tool_calls=False be honoured? (Gemini has no switch)
strict_tools: bool = False # does ToolSpec.strict=True actually make the server enforce the schema?
class ModelSpec(_Strict):
key: str = "" # filled in by the loader
provider: str # "openai" | "anthropic" | "gemini" | "openrouter" | "local"
api: Api
model: str # the provider's model ID
api_key_env: str | None = None # the NAME of the variable that holds the key: no key ever appears in a file
key_optional: bool = False # a server that ignores keys (Ollama): use a placeholder when the variable is unset
base_url: str | None = None
base_url_env: str | None = None # an environment variable that overrides base_url (proxies, the local stand-in)
headers: dict[str, str] = Field(default_factory=dict) # NON-secret default headers, e.g. OpenRouter attribution
headers_env: dict[str, str] = Field(default_factory=dict) # header name -> NAME of the variable holding its value (gateways)
free: bool = False # local stand-ins: cost is 0, not "unknown"
context_window: int | None = None
max_output_tokens: int | None = None
default_max_output_tokens: int = 1024
reasoning_off: str | None = None # the lowest setting THIS model accepts
capabilities: Capabilities = Field(default_factory=Capabilities)
@field_validator("headers")
@classmethod
def _no_secrets_in_files(cls, headers: dict[str, str]) -> dict[str, str]:
for name in headers:
if any(h in name.lower() for h in _SECRET_HEADER_HINTS):
raise ValueError(f"header {name!r} looks like a credential: put the variable NAME under headers_env, "
"not the value under headers")
return headers
def resolved_base_url(spec: ModelSpec) -> str | None:
"""env override first, then the file, then None (the SDK's own default / its OPENAI_BASE_URL-style variable)."""
return (os.environ.get(spec.base_url_env) if spec.base_url_env else None) or spec.base_url
class Registry:
def __init__(self, data: dict[str, Any]) -> None:
if not isinstance(data, dict): # an empty file loads as None, a bare list as a list
raise ConfigError(f"the registry must be a mapping with version, aliases and models, got {type(data).__name__}")
unknown = [k for k in data if k not in ("version", "aliases", "models") and not str(k).startswith("x-")]
if unknown:
raise ConfigError(f"unknown top-level key(s) {unknown}: expected version, aliases, models")
if not data.get("version"):
raise ConfigError("the registry needs a `version:` (the date you last checked its values)")
self.version = str(data["version"])
self.models: dict[str, ModelSpec] = {}
models = data.get("models") or {}
if not isinstance(models, dict): # `models: [a, b]` is a YAML typo, not a spec error
raise ConfigError(f"`models:` must be a mapping of entry name to spec, got {type(models).__name__}")
for key, spec in models.items():
if not isinstance(spec, dict): # `models: {x: "oops"}`: {**spec} would raise a raw TypeError
raise ConfigError(f"model entry {key!r}: expected a mapping, got {type(spec).__name__}")
try:
self.models[key] = ModelSpec.model_validate({**spec, "key": key})
except ValidationError as exc: # name the entry: the pydantic path alone says "capabilites"
raise ConfigError(f"model entry {key!r}: {exc.errors()[0]['loc']} {exc.errors()[0]['msg']}") from exc
aliases = data.get("aliases") or {}
if not isinstance(aliases, dict):
raise ConfigError(f"`aliases:` must be a mapping of alias to chain, got {type(aliases).__name__}")
self.aliases: dict[str, list[str]] = {}
for alias, chain in aliases.items():
if not isinstance(chain, list): # `fast: gpt-4o` would otherwise split into characters
raise ConfigError(f"alias {alias!r}: expected a list of model entries, got {type(chain).__name__}")
self.aliases[alias] = list(chain)
for alias, chain in self.aliases.items(): # fail at load time, not at 3 a.m.
if not chain:
raise ConfigError(f"alias {alias!r} has an empty chain")
if len(set(chain)) != len(chain):
raise ConfigError(f"alias {alias!r} lists an entry twice: {chain}")
if alias in self.models:
raise ConfigError(f"{alias!r} is both an alias and a model entry: model={alias!r} would be ambiguous")
for key in chain:
if key not in self.models:
raise ConfigError(f"alias {alias!r} names unknown model entry {key!r}")
@classmethod
def load(cls, path: str | Path = DEFAULT_PATH) -> "Registry":
return cls(yaml.safe_load(Path(path).read_text()))
def chain(self, name: str) -> list[ModelSpec]:
"""An alias gives its ordered chain; a bare entry key gives a chain of one."""
if name in self.aliases:
return [self.models[k] for k in self.aliases[name]]
if name in self.models:
return [self.models[name]]
raise ConfigError(f"unknown model alias {name!r}; known aliases: {sorted(self.aliases)}, "
f"entries: {sorted(self.models)}")
def missing_credentials(self, name: str) -> list[str]:
"""Every variable the WHOLE chain needs that is not set: checked before the first request, so a fallback
whose key is missing is found today and not in the middle of an outage."""
missing: list[str] = []
for spec in self.chain(name):
wanted = [spec.api_key_env] if spec.api_key_env and not spec.key_optional else []
wanted += list(spec.headers_env.values())
missing += [f"{spec.key}: {var}" for var in wanted if not os.environ.get(var)]
return missing7.2 Why model choice is configuration#
Changing which model serves "fast" is now a one-line YAML edit and a deploy, with no code change. 02.9, Part 10 said model choice is a decision to revisit regularly as prices and models move, and this is what makes revisiting cheap. It also lets you run different chains in different environments (a free local chain in development, hosted chains in production) from the same code, which is exactly how the stand-in registry in Part 10 works.
7.3 Capability checks: fail before anything is sent#
# provider_agnostic/registry.py: raise instead of silently dropping
def check_capabilities(req: Request, spec: ModelSpec) -> None:
"""Raise UnsupportedFeature for anything this route cannot do. NEVER silently drop an option."""
caps, where = spec.capabilities, f"{spec.key} ({spec.provider}/{spec.api}/{spec.model})"
def need(ok: bool, what: str) -> None:
if not ok:
raise UnsupportedFeature(f"{where} does not support {what}", provider=spec.provider)
if req.tools:
need(caps.tools, "tools")
if any(t.strict for t in req.tools):
need(caps.strict_tools, "strict tool schemas (the server would not enforce them: set strict=False and validate arguments)")
if isinstance(req.tool_choice, ForcedTool) or req.tool_choice == "required":
need(caps.forced_tool_choice, "forced tool use (use tool_choice='auto')")
if req.parallel_tool_calls is False:
need(caps.parallel_tool_switch, "parallel_tool_calls=False (there is no switch: match results by ID)")
if req.stop:
need(caps.stop, "stop sequences (cut the text yourself, or use a route that has them)")
if req.output_schema is not None:
need(caps.structured_output, "schema-constrained structured output")
if req.reasoning_effort not in (None, "off"):
need(caps.reasoning, f"reasoning_effort={req.reasoning_effort!r}")
for message in req.messages:
for part in message.parts:
if isinstance(part, ImagePart):
need(caps.images, "image input")
if part.url and not part.data_b64:
need(caps.image_urls, "image URLs (send the bytes as data_b64)")
elif isinstance(part, DocumentPart):
need(caps.documents, "document (PDF) input")
if req.max_output_tokens and spec.max_output_tokens and req.max_output_tokens > spec.max_output_tokens:
raise UnsupportedFeature(f"{where}: max_output_tokens={req.max_output_tokens} is above the "
f"model's limit {spec.max_output_tokens}", provider=spec.provider)The client checks the whole chain up front, credentials included: client.preflight(alias) (also run by every first call) raises a ConfigError naming every missing variable of every entry, because a fallback whose key is missing was otherwise discovered during the outage, as a ConfigError that hid the original error. Capabilities are checked the same way. Imagine the primary supports forced tool choice and the fallback doesn't: without the up-front check, the request would work for months and then fail with a 400 only during an outage, which is the worst time to discover a bug. With it, complete() raises UnsupportedFeature naming the entry that can't do it, before the first byte leaves your machine (the test test_capabilities_of_the_whole_chain_are_checked_before_anything_is_sent proves the primary isn't even called).
"""s7_registry_demo.py: the capability registry and its checks (layer 1: no network, no key)."""
from pydantic import BaseModel
from provider_agnostic import ForcedTool, ImagePart, LLMError, Message, Registry, Request, ToolSpec
from provider_agnostic.registry import check_capabilities
registry = Registry.load() # provider_agnostic/models.yaml
print(f"registry version {registry.version}: {len(registry.models)} entries, aliases:")
for alias, chain in registry.aliases.items():
print(f" {alias:9s} -> " + " -> ".join(f"{k} ({registry.models[k].provider}/{registry.models[k].api})" for k in chain))
print("\nWhat one entry holds:")
print(registry.models["sonnet"].model_dump(exclude={"key"}))
class Invoice(BaseModel):
total: float
tool = ToolSpec(name="lookup", description="Look something up.", parameters={"type": "object"})
png_url = Message(role="user", parts=[ImagePart(media_type="image/png", url="https://example.com/receipt.png")])
cases = {
"forced tool on sonnet": ("sonnet", Request(model="m", messages=[Message.user("x")], tools=[tool], tool_choice=ForcedTool(name="lookup"))),
"forced tool on haiku": ("haiku", Request(model="m", messages=[Message.user("x")], tools=[tool], tool_choice=ForcedTool(name="lookup"))),
"image URL on gemini": ("flash", Request(model="m", messages=[png_url])),
"image on a local model": ("local-chat", Request(model="m", messages=[png_url])),
"too many output tokens": ("flash", Request(model="m", messages=[Message.user("x")], max_output_tokens=500_000)),
"reasoning on a local model": ("local-chat", Request(model="m", messages=[Message.user("x")], reasoning_effort="high")),
"schema on local Claude route": ("local-anthropic", Request(model="m", messages=[Message.user("x")], output_schema=Invoice)),
}
local = Registry.load("provider_agnostic/models.local.yaml")
print("\nCapability checks (they run BEFORE any request is sent):")
for label, (key, req) in cases.items():
spec = registry.models.get(key) or local.models[key]
try:
check_capabilities(req, spec)
print(f" {label:30s} ok")
except LLMError as err:
print(f" {label:30s} {type(err).__name__}: {err.message}")
print("\nAn alias that points at nothing fails when the file is loaded, not at 3 a.m.:")
try:
Registry({"version": "demo", "models": {}, "aliases": {"fast": ["gone"]}})
except LLMError as err:
print(" ", type(err).__name__ + ":", err.message)registry version 2026-11-04: 9 entries, aliases:
fast -> luna (openai/responses) -> haiku (anthropic/messages) -> flash (gemini/generate_content)
smart -> sol (openai/responses) -> sonnet (anthropic/messages)
vision -> flash (gemini/generate_content) -> haiku (anthropic/messages) -> luna (openai/responses)
cheap-or -> or-luna (openrouter/chat) -> or-haiku (openrouter/chat)
What one entry holds:
{'provider': 'anthropic', 'api': 'messages', 'model': 'claude-sonnet-5-5', 'api_key_env': 'ANTHROPIC_API_KEY', 'key_optional': False, 'base_url': None, 'base_url_env': None, 'headers': {}, 'headers_env': {}, 'free': False, 'context_window': 1000000, 'max_output_tokens': 128000, 'default_max_output_tokens': 4096, 'reasoning_off': 'between_tools', 'capabilities': {'tools': True, 'forced_tool_choice': False, 'structured_output': True, 'images': True, 'image_urls': True, 'documents': True, 'reasoning': True, 'stream_usage': True, 'stop': True, 'parallel_tool_switch': True, 'strict_tools': True}}
Capability checks (they run BEFORE any request is sent):
forced tool on sonnet UnsupportedFeature: sonnet (anthropic/messages/claude-sonnet-5-5) does not support forced tool use (use tool_choice='auto')
forced tool on haiku ok
image URL on gemini ok
image on a local model UnsupportedFeature: local-chat (local/chat/qwen2.5:0.5b) does not support image input
too many output tokens UnsupportedFeature: flash (gemini/generate_content/gemini-3.8-flash): max_output_tokens=500000 is above the model's limit 65536
reasoning on a local model UnsupportedFeature: local-chat (local/chat/qwen2.5:0.5b) does not support reasoning_effort='high'
schema on local Claude route UnsupportedFeature: local-anthropic (local/messages/qwen2.5:0.5b) does not support schema-constrained structured output
An alias that points at nothing fails when the file is loaded, not at 3 a.m.:
ConfigError: alias 'fast' names unknown model entry 'gone'Each refusal corresponds to a real provider behaviour: the forced tool choice on Sonnet would have been a 400; a 500,000-token output cap is above Gemini's documented limit; a reasoning effort on a model that can't think would have been ignored or rejected. The rule is only as good as its test. test_every_request_field_is_on_the_wire_or_refused sets each canonical field on each of the six routes and fails unless the value is on the wire or the route refuses it:
# tests/test_request_contract.py: the test that makes "never silently drop" true
def sent_or_refused(case: str, req: Request, *needles: str) -> str:
"""Either check_capabilities refuses this field on this route, or the value is on the wire. Never neither."""
spec = Registry({"version": "t", "models": {"m": CASES[case][1]}}).models["m"]
try:
check_capabilities(req, spec)
except UnsupportedFeature:
return "refused"
text = wire(case, req)
assert all(n.lower() in text for n in needles), f"{case}: {needles} silently dropped from {text[:300]}"
return "sent"
@pytest.mark.parametrize("case", CASE_IDS)
def test_every_request_field_is_on_the_wire_or_refused(case: str, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("TEST_KEY", "x")
base: dict[str, Any] = {"model": "m", "messages": CALL}
with_tool = {**base, "tools": [TOOL]}
results = {
"system": sent_or_refused(case, Request(**base, system="SYS-MARK"), "SYS-MARK"),
"max_output_tokens": sent_or_refused(case, Request(**base, max_output_tokens=777), "777"),
"stop": sent_or_refused(case, Request(**base, stop=["STOP-MARK"]), "STOP-MARK"),
"tools": sent_or_refused(case, Request(**with_tool), "tool_mark"),
"tool_choice (forced)": sent_or_refused(case, Request(**with_tool, tool_choice=ForcedTool(name="tool_mark")), "tool_mark"),
"tool_choice (required)": sent_or_refused(case, Request(**with_tool, tool_choice="required"), "tool_mark"),
"parallel_tool_calls=False": sent_or_refused(case, Request(**with_tool, parallel_tool_calls=False), "parallel"),
"strict tool": sent_or_refused(case, Request(**base, tools=[TOOL.model_copy(update={"strict": True})]), "strict"),
"output_schema": sent_or_refused(case, Request(**base, output_schema=SchemaMark), "field_mark"),
"reasoning_effort": sent_or_refused(case, Request(**base, reasoning_effort="high"), "high"),
}
assert set(results.values()) <= {"sent", "refused"}
# the answer for the two fields the first version dropped without a word
if case == "openai-responses":
assert results["stop"] == "refused" # responses.create has no `stop`
if case.startswith("gemini"):
assert results["parallel_tool_calls=False"] == "refused" # Gemini has no switchIt found stop on Responses and parallel_tool_calls=False on Gemini dropped without a word, and ToolSpec.strict sent to servers that ignore it. The principle is "raise, don't drop". Compare the alternative, where output_schema on a route that can't enforce it quietly sends a plain prompt and you find the problem when a parser fails in production.
7.4 Keeping the registry honest: the refresh path#
Prices and capabilities go stale. Context windows change with model generations; models get deprecated and retired (02.9, Part 8: Anthropic's retirement of claude-sonnet-4-5-20250929 on 30 November 2026 is a recent example). The registry's version field and the comments next to values are the first defence. The second is an audit against each provider's Models API (03.1, Part 10):
# provider_agnostic/refresh.py: audit the registry against the providers' Models APIs
"""provider_agnostic/refresh.py: audit models.yaml against the providers' Models APIs (lesson 03.1, Part 10; 03.11, Part 7).
uv run python -m provider_agnostic.refresh # prints findings; exit code 1 if anything needs a human
Run it from CI on a schedule, not on every request. It never edits the registry: a person reviews the diff.
"""
from __future__ import annotations
import datetime as dt
import os
import sys
from dataclasses import dataclass
from typing import Literal
from dotenv import load_dotenv
from .registry import ModelSpec, Registry
@dataclass
class Live:
"""What a provider's Models API says about one model (None = the API doesn't say)."""
context_window: int | None = None
max_output_tokens: int | None = None
retires_at: str | None = None
@dataclass
class Finding:
level: Literal["error", "warn", "info"]
key: str
message: str
def fetch_live(provider: str) -> dict[str, Live] | None:
"""Layer 4: one list call per provider. Returns None when its key is not set."""
if provider == "openai" and os.getenv("OPENAI_API_KEY"):
from openai import OpenAI
return {m.id: Live(retires_at=getattr(m, "shutdown_date", None) and str(m.shutdown_date))
for m in OpenAI().models.list()}
if provider == "anthropic" and os.getenv("ANTHROPIC_API_KEY"):
import anthropic
return {m.id: Live(m.max_input_tokens, m.max_tokens, m.retires_at.isoformat() if m.retires_at else None)
for m in anthropic.Anthropic().models.list(limit=1000)}
if provider == "gemini" and os.getenv("GEMINI_API_KEY"):
from google import genai
client = genai.Client()
out = {(m.name or "").removeprefix("models/"): Live(m.input_token_limit, m.output_token_limit)
for m in client.models.list(config={"page_size": 100})}
client.close()
return out
if provider == "openrouter": # the catalogue is public: no key needed
from openai import OpenAI
from openai.types import Model
models: list[Model] = list(OpenAI(base_url="https://openrouter.ai/api/v1", api_key="none").models.list())
return {m.id: Live((m.model_extra or {}).get("context_length")) for m in models}
return None
def audit(registry: Registry, live: dict[str, dict[str, Live] | None], today: dt.date | None = None) -> list[Finding]:
"""Layer 1: pure comparison, so it is unit-tested with fixtures."""
today = today or dt.date.today()
findings: list[Finding] = []
for spec in registry.models.values():
if spec.free:
continue
models = live.get(spec.provider)
if models is None:
findings.append(Finding("info", spec.key, f"{spec.provider}: no key (or no listing API), not checked"))
continue
info = models.get(spec.model)
if info is None:
findings.append(Finding("error", spec.key, f"{spec.model!r} is not in {spec.provider}'s model list "
"(renamed, retired, or not enabled for this account)"))
continue
findings += _compare(spec, info, today)
return findings
def _compare(spec: ModelSpec, info: Live, today: dt.date) -> list[Finding]:
out: list[Finding] = []
if info.retires_at:
days = (dt.date.fromisoformat(info.retires_at[:10]) - today).days
out.append(Finding("error" if days < 30 else "warn", spec.key, f"retires {info.retires_at[:10]} ({days} days)"))
for field, ours, theirs in (("context_window", spec.context_window, info.context_window),
("max_output_tokens", spec.max_output_tokens, info.max_output_tokens)):
if ours and theirs and ours != theirs:
out.append(Finding("warn", spec.key, f"{field}: registry says {ours:,}, provider says {theirs:,}"))
return out
def main() -> int:
load_dotenv()
registry = Registry.load()
live: dict[str, dict[str, Live] | None] = {}
failures: list[Finding] = []
for provider in sorted({s.provider for s in registry.models.values()}):
try:
live[provider] = fetch_live(provider)
except Exception as exc: # an audit must not crash because one API is down
live[provider] = None
failures.append(Finding("warn", provider, f"listing failed: {type(exc).__name__}: {str(exc)[:80]}"))
findings = failures + audit(registry, live)
for f in findings:
print(f"{f.level.upper():5s} {f.key:12s} {f.message}")
if not any(f.level != "info" for f in findings):
print("registry matches the providers' model lists")
return 1 if any(f.level == "error" for f in findings) else 0
if __name__ == "__main__":
sys.exit(main())audit() is pure and unit-tested with fixtures. The fetch_live() half calls each provider's list endpoint (layer 4: needs keys; OpenRouter's catalogue is public). It never edits the registry: a person reviews a flagged diff. Run it from a scheduled CI job, not on every request. A model missing from its provider's list, a retirement date within 30 days, or a context or output limit that differs from the file shows up as an error or a warning.
What the Models APIs can and cannot tell you differs: Anthropic's reports limits, lifecycle and a capabilities object; OpenAI's reports IDs and a shutdown date; Gemini's reports token limits and supported actions; OpenRouter's reports context length, supported parameters and pricing (02.9, 4.10). The audit compares only token limits and retirement dates: it does not diff Anthropic's capabilities object, Gemini's supported_actions or OpenRouter's supported_parameters against your capabilities:, so a flag that went stale is still found by a failing request or a live smoke test, not by the audit (extending _compare is a good exercise). The OpenRouter entries carry a context_window so at least that limit is audited. Pricing is refreshed separately, from the pages named in prices.yaml (03.7, 4.4). A successful models.list also doesn't prove you can call a model (03.1, 10.1): the smoke test in Part 11 does.
Run against the local stand-in, with no keys, the audit behaves as it should:
ERROR luna 'gpt-6-luna' is not in openai's model list (renamed, retired, or not enabled for this account)
ERROR luna-chat 'gpt-6-luna' is not in openai's model list (renamed, retired, or not enabled for this account)
ERROR sol 'gpt-6.1-sol' is not in openai's model list (renamed, retired, or not enabled for this account)
ERROR haiku 'claude-haiku-5-5' is not in anthropic's model list (renamed, retired, or not enabled for this account)
ERROR sonnet 'claude-sonnet-5-5' is not in anthropic's model list (renamed, retired, or not enabled for this account)
INFO flash gemini: no key (or no listing API), not checked
INFO flash-interactions gemini: no key (or no listing API), not checked(Layer 2, real run with source localstack/env.sh. The stand-in's model lists contain only local aliases, so every hosted model is "missing", and the Gemini entries are not checked at all because the stand-in has no Gemini listing API (it is hosted-only). That is a property of the stand-in, not of Google. With real keys the same command prints registry matches the providers' model lists.)
Part 8: Reliability in one place#
Deep-dive
Lesson 03.8 taught each piece: classification, timeouts, backoff, Retry-After, budgets. A provider-agnostic client is where they stop being scattered across call sites and become one policy object.
# provider_agnostic/client.py: every number that decides how hard we try
@dataclass
class Policy:
"""Every number that decides how hard we try, in one place.
The defaults obey one rule, and a test pins it: a provider that HANGS must not be able to use up the deadline.
deadline_s >= (max_timeout_attempts + 1) * attempt_timeout_s
The primary may burn max_timeout_attempts full timeouts, and the next model still gets one whole attempt.
Change one of the three and change the others with it (with a three-model chain and two hung providers, the third
gets only what is left: lower attempt_timeout_s, or raise deadline_s)."""
max_attempts: int = 3 # per model: the first try plus two retries (for errors that come back FAST)
max_timeout_attempts: int = 2 # per model: a timeout cost a whole attempt_timeout_s, so retry it once, then move on
attempt_timeout_s: float = 30.0 # one HTTP attempt (lesson 03.8, Part 6 for per-use-case values)
deadline_s: float = 120.0 # the whole call: waits and fallbacks included
base_s: float = 0.5 # full-jitter backoff: uniform(0, min(cap, base * 2**n))
cap_s: float = 8.0
max_server_wait_s: float = 20.0 # a Retry-After longer than this: stop retrying THIS model
# Errors that move us to the NEXT model once retries on this one are used up. Quota is here because
# retrying the same account can never help, while another provider can. Not here, on purpose:
# BadRequest (a bug), ContextTooLong (that is a cascade, Module 11B), Refused/ContentBlocked (a choice).
fallback_on: tuple[type[LLMError], ...] = (RateLimited, Overloaded, ServerError, Timeout, ConnectionFailed,
QuotaExceeded)
# Finish reasons that also trigger fallback. Empty by default: a refusal may be the right answer.
fallback_on_finish: frozenset[FinishReason] = frozenset()8.1 One layer owns retries#
The wrapper creates every SDK client with max_retries=0 (and uses no retry_options on Gemini's models.*), so LLMClient is the only retry layer. Here is why that is a deliberate setting and not a default to forget about (layer 3: the same always-503 server, counted at the wire):
"""s8_retry_multiplication.py: why the wrapper builds SDK clients with max_retries=0 (layer 3: mock server).
The same outage (a server that always answers 503), counted at the wire, with and without the SDK's own retries."""
import os
import httpx2
import openai
from provider_agnostic import LLMClient, LLMError, Message, Policy, Registry, Request
from tests.fakes import FakeResponses, Server
os.environ["OPENAI_API_KEY"] = "sk-test"
reply = FakeResponses().error("overloaded")
spec = Registry.load().models["luna"].model_dump(exclude={"key"})
registry = Registry({"version": "demo", "models": {"luna": {**spec, "base_url": "https://mock.test/v1"}}})
req = Request(model="luna", messages=[Message.user("Hi")])
# 1. The wrapper as designed: max_retries=0 inside, 3 attempts outside
server = Server([reply])
client = LLMClient(registry, policy=Policy(max_attempts=3), http_clients={"luna": server.clients()}, sleep=lambda s: None)
try:
client.complete(req)
except LLMError as err:
print(f"wrapper (3 attempts), SDK retries off : {server.n} requests reached the server, {len(err.attempts)} attempts logged")
# 2. The trap: the same wrapper loop on top of an SDK client that keeps its default max_retries=2
server = Server([reply])
sdk = openai.OpenAI(api_key="sk-test", base_url="https://mock.test/v1", http_client=server.clients()["sync"]) # default: 2 retries
adapter = client.adapter(registry.models["luna"])
adapter._client = sdk # swap in the SDK client with its default retries
adapter.send = lambda params, timeout_s: sdk.responses.create(**params, timeout=timeout_s) # type: ignore[method-assign]
client = LLMClient(registry, policy=Policy(max_attempts=3), http_clients={"luna": server.clients()}, sleep=lambda s: None)
client._adapters["luna"] = adapter
try:
client.complete(req)
except LLMError as err:
print(f"wrapper (3 attempts), SDK retries ON : {server.n} requests reached the server, {len(err.attempts)} attempts logged")
print("3 attempts x (1 try + 2 SDK retries) = 9: the log shows 3, the provider saw 9, and each SDK retry also sleeps.")wrapper (3 attempts), SDK retries off : 3 requests reached the server, 3 attempts logged
wrapper (3 attempts), SDK retries ON : 9 requests reached the server, 3 attempts logged
3 attempts x (1 try + 2 SDK retries) = 9: the log shows 3, the provider saw 9, and each SDK retry also sleeps.Three attempts at the wrapper level became nine requests at the provider when the SDK kept its default two retries, and the wrapper's log showed three. That is 03.8, 5.5's multiplication, on a provider that is already struggling. Two consequences follow:
- If you put a gateway in front (OpenRouter, the LiteLLM proxy, an internal gateway) that retries or fails over on its own, then it should own transient retries, and you should lower
Policy.max_attemptsto 1 for that route. - Interactions is the exception you can't fully fix: the google-genai SDK retries it by itself and cannot be told not to, so the Interactions adapter only stops status retries (4.5).
8.2 Timeouts and the deadline#
Two clocks run on every call. attempt_timeout_s bounds one HTTP attempt (it is passed to each SDK as that SDK's own timeout, converted to milliseconds for Gemini). deadline_s bounds the whole call, waits and fallbacks included, and the per-attempt timeout is always capped by what's left of it. The defaults (30 s and 120 s) are placeholders: 03.8, 6.5 gives values per use case (an interactive chat endpoint wants much less; a nightly batch can wait much longer). Request.timeout_s overrides the per-attempt value for one call. These defaults are deliberately not 03.8's RetryPolicy numbers (4 attempts and a 60 s deadline for one model): this client walks a chain of models, so each model gets 3 attempts and the whole call has 120 s, enough for a hung primary to time out and for the fallback to get a full attempt (the rule below). If you build on reliable_call() for a single model, 03.8's numbers are the right ones.
The three numbers must agree, or the fallback is unreachable. The first version had max_attempts=3, attempt_timeout_s=30 and deadline_s=90, which multiply out to exactly the deadline. A provider that hangs (the commonest real outage: connections accepted, no bytes back) used all 90 s on the primary, remaining() then failed decide()'s check, and the call raised Timeout without ever trying the fallback. The fallback demo only used fast 503s, so it never showed it. A probe with a fake clock printed RAISED Timeout [('luna',1,'Timeout'),('luna',2,'Timeout'),('luna',3,'Timeout')] claude requests: 0 t= 90.9. The fix gives timeouts their own, smaller budget (Policy.max_timeout_attempts = 2: a timeout costs a whole attempt_timeout_s, so retry it once and then move on; errors that come back fast still get max_attempts) and states the invariant in the Policy docstring, where a test pins it:
deadline_s >= (max_timeout_attempts + 1) x attempt_timeout_s 120 >= (2 + 1) x 30 = 90The primary may burn max_timeout_attempts full timeouts and the next model still gets one whole attempt. With a three-model chain and two hung providers the third gets only what is left: lower attempt_timeout_s or raise deadline_s. The demo (layer 3: a fake clock moves 30 s per hung request, so it runs in milliseconds and the timeline is exact):
"""s8_timeout_fallback_demo.py: a provider that HANGS must not be able to use up the deadline (layer 3).
OpenAI "hangs": every request waits the full 30 s attempt timeout and then times out. A fake clock moves time forward
by 30 s per request, so the demo runs in milliseconds and the timeline below is exact."""
import os
import httpx2
from provider_agnostic import Hook, LLMClient, Message, Policy, Registry, Request
from tests.fakes import FakeAnthropic, FakeResponses, Server
os.environ.update(OPENAI_API_KEY="sk-test", ANTHROPIC_API_KEY="sk-test")
now = [0.0] # the fake monotonic clock, in seconds
class Timeline(Hook):
def attempt(self, ctx, attempt):
print(f" t={now[0]:5.1f}s {attempt.model_key:6s} attempt {attempt.n}: {attempt.error_type or 'ok'}")
primary = Server([httpx2.ReadTimeout("no bytes for 30 s")], delay=lambda: now.__setitem__(0, now[0] + 30.0))
secondary = Server([FakeAnthropic().text("Hello from Claude.")])
spec = Registry.load().models
registry = Registry({"version": "demo", "models": {
"luna": {**spec["luna"].model_dump(exclude={"key"}), "base_url": "https://mock.test/v1"},
"haiku": {**spec["haiku"].model_dump(exclude={"key"}), "base_url": "https://mock.test"}}, "aliases": {"fast": ["luna", "haiku"]}})
policy = Policy() # the DEFAULTS: that is the point
client = LLMClient(registry, hooks=[Timeline()], policy=policy, clock=lambda: now[0],
sleep=lambda s: now.__setitem__(0, now[0] + s), http_clients={"luna": primary.clients(), "haiku": secondary.clients()})
print(f"policy: attempt_timeout_s={policy.attempt_timeout_s:g}, max_timeout_attempts={policy.max_timeout_attempts}, "
f"deadline_s={policy.deadline_s:g} -> (max_timeout_attempts + 1) x attempt_timeout_s = "
f"{(policy.max_timeout_attempts + 1) * policy.attempt_timeout_s:g} <= deadline_s")
resp = client.complete(Request(model="fast", messages=[Message.user("Say hello.")]))
print(f"answer: {resp.text!r} from {resp.model_key} after {now[0]:.1f} s (deadline {policy.deadline_s:g} s); "
f"OpenAI saw {primary.n} requests, Anthropic {secondary.n}")policy: attempt_timeout_s=30, max_timeout_attempts=2, deadline_s=120 -> (max_timeout_attempts + 1) x attempt_timeout_s = 90 <= deadline_s
t= 30.0s luna attempt 1: Timeout
t= 60.3s luna attempt 2: Timeout
t= 60.3s haiku attempt 1: ok
answer: 'Hello from Claude.' from haiku after 60.3 s (deadline 120 s); OpenAI saw 2 requests, Anthropic 1Streaming has its own timeout rules (the read timeout is the longest silence between events, 03.3, Part 8); for a reasoning model that thinks for a while before the first token, raise attempt_timeout_s rather than lowering retries.
8.3 The retry decision#
All the logic of "what happens after a failed attempt" is one small method:
# provider_agnostic/client.py: after a failed attempt: retry, move to the next model, or raise
def decide(self, err: LLMError) -> tuple[str, float]:
"""After a failed attempt: ('retry', wait_s) | ('next', 0) | ('raise', 0)."""
p = self.client.policy
wait = self._wait(err)
can_retry = (err.retryable and self.attempt_no < p.max_attempts and wait is not None
and self.remaining() > wait + 0.1)
if isinstance(err, Timeout): # a hang costs a whole attempt_timeout_s: do not spend the deadline on one model
can_retry = can_retry and self.timeouts < p.max_timeout_attempts
if can_retry and wait is not None:
return "retry", wait
if isinstance(err, p.fallback_on) and self.model_idx + 1 < len(self.chain) and self.remaining() > 0.2:
return "next", 0.0
return "raise", 0.0
def _wait(self, err: LLMError) -> float | None:
p = self.client.policy
if err.retry_after_s is not None:
return None if err.retry_after_s > p.max_server_wait_s else err.retry_after_s + self.client.rng.uniform(0, 0.25)
return self.client.rng.uniform(0, min(p.cap_s, p.base_s * 2 ** (self.attempt_no - 1)))
def advance(self) -> None:
self.model_idx += 1
self.attempt_no = 0
self.timeouts = 0In words:
- Retry the same model if the error is retryable, attempts remain, the wait is acceptable and the deadline allows it. A
Timeoutadditionally needs a timeout left in its ownmax_timeout_attemptsbudget. The wait is the server'sRetry-After(plus a little jitter) when it sent one, otherwise full-jitter exponential backoff (03.8, Part 7). - A
Retry-Afterlonger thanmax_server_wait_sis not waited for. Holding a user's request open for five minutes helps nobody: we skip this model and let the fallback take over (a test does exactly this with a 300-second hint). - Otherwise move to the next model in the chain, if the error is in
Policy.fallback_on. - Otherwise raise. The exception carries every attempt.
The loop itself, for the non-streaming path:
flowchart TD
s["complete(request)"] --> hk["before hooks (fail-closed):<br/>budget gate, redaction"]
hk -->|"a hook raised"| fail00["Raise HookError or the hook's own error:<br/>nothing was sent"]
hk --> chk["Check credentials and capabilities<br/>of the whole chain"]
chk -->|"ConfigError, UnsupportedFeature"| fail0["Raise: nothing was sent"]
chk --> try["Attempt on model k:<br/>build, send, parse"]
try -->|"HTTP 200"| bad{"body says failed,<br/>cancelled or budget_exceeded?"}
bad -->|"yes"| wrapx
bad -->|"no"| fin{"finish reason in<br/>fallback_on_finish?"}
fin -->|"no"| done["Validate schema, price, after hooks, return Response"]
fin -->|"yes, and another model exists"| nxt
try -->|"exception"| wrapx["wrap(): canonical LLMError"]
wrapx --> r{"retryable, attempts left<br/>(timeouts: max_timeout_attempts),<br/>deadline left, wait short enough?"}
r -->|"yes"| wait["Sleep (Retry-After or full jitter)"]
wait --> try
r -->|"no"| fb{"error in fallback_on<br/>and another model exists?"}
fb -->|"yes"| nxt["Next model in the alias chain"]
nxt --> try
fb -->|"no"| fail["Raise the LLMError<br/>with every attempt attached"]# provider_agnostic/client.py: complete()
def complete(self, req: Request) -> Response:
run = self._start(req)
while True:
spec, ad = run.spec, self.adapter(run.spec)
started = self.clock()
try:
params = ad.build(run.req)
resp = ad.parse(ad.send(params, run.timeout()))
except Exception as exc:
err = exc if isinstance(exc, LLMError) else wrap(exc, spec.provider)
run.record(ok=False, started=started, err=err)
action, wait = run.decide(err)
if action == "retry":
self.sleep(wait)
continue
if action == "next":
run.advance()
continue
raise self._fail(run, err) from (exc if err is not exc else None) # SDK exception stays as __cause__
if self._bad_finish(run, resp): # discarded for the next model: still billed, still on the record
run.record(ok=False, started=started, resp=resp, error_type=f"FinishFallback:{resp.finish_reason.value}")
run.advance()
continue
run.record(ok=True, started=started, resp=resp)
return self._finalize(run, resp, spec)The sleep and the clock are injectable (sleep=, clock=, rng= on the client), which is how the tests run a three-attempt retry in microseconds and prove the deadline logic without waiting (Part 11).
8.4 Fallback across providers#
A fallback is simply the next entry in the alias chain, tried after the current model's retries are used up. What triggers it is a policy choice, and the defaults follow 02.9, 10.5:
| Event | Falls back? | Why |
|---|---|---|
RateLimited, Overloaded, ServerError, ConnectionFailed |
Yes, after the current model's retries | Another provider probably isn't down at the same moment. A transient code inside an HTTP 200 (status: failed, server_error) is one of these (Part 6) |
Timeout |
Yes, after max_timeout_attempts (2) tries |
A hang costs a whole attempt_timeout_s each; the deadline must leave room for the next model (8.2) |
QuotaExceeded |
Yes, immediately | Retrying an empty wallet cannot help, but a different provider's account can |
AuthFailed, PermissionDenied |
No (raised) | A wrong key is a configuration bug you must see. Silent fallback would hide a broken deployment for weeks |
BadRequest |
No | A bug in the request is a bug on every provider. Falling back would double the bill for the same failure |
ContextTooLong |
No | That is a cascade decision (move to a bigger-context model), which is Module 11B's router, not a failure handler |
UnsupportedFeature, HookError, ResponseFailed |
No | Raised before anything is sent, or a permanent failure (invalid_prompt, cancelled): the same request would fail again |
A REFUSAL or CONTENT_FILTER finish |
No, unless you opt in (Policy.fallback_on_finish) |
A refusal may be the correct answer, and shopping a refused request around until some model complies defeats the safety behaviour. Opting in is a deliberate choice |
A LENGTH finish |
No | The reply isn't an error; a bigger output cap is the fix |
Here is a real fallback, with both attempts and the cost visible (layer 3: OpenAI "is down" with a 503 every time, Claude answers; the log lines are the wrapper's own LoggingHook output):
"""s8_fallback_demo.py: a fallback chain across providers (layer 3: real SDKs, mock servers).
fast = [luna (OpenAI Responses), haiku (Anthropic Messages)]. OpenAI is "down" (503 every time), Claude answers."""
import logging
import os
import sys
from provider_agnostic import LLMClient, LoggingHook, Message, Policy, Registry, Request
from prices import PriceTable
from tests.fakes import FakeAnthropic, FakeResponses, Server
logging.basicConfig(level=logging.INFO, format="%(message)s", stream=sys.stdout)
for noisy in ("httpx", "httpx2"):
logging.getLogger(noisy).setLevel(logging.WARNING) # the SDKs log every request at INFO: not needed here
os.environ.update(OPENAI_API_KEY="sk-test", ANTHROPIC_API_KEY="sk-test")
openai_down = Server([FakeResponses().error("overloaded")]) # always 503
claude_ok = Server([FakeAnthropic().text("Hello from Claude.", inp=30, out=6, cached=0)], flavour="httpx2")
spec = Registry.load().models
registry = Registry({"version": "demo", "models": {"luna": {**spec["luna"].model_dump(exclude={"key"}), "base_url": "https://mock.test/v1"},
"haiku": {**spec["haiku"].model_dump(exclude={"key"}), "base_url": "https://mock.test"}},
"aliases": {"fast": ["luna", "haiku"]}})
client = LLMClient(registry, prices=PriceTable.load(), hooks=[LoggingHook()], policy=Policy(max_attempts=2),
http_clients={"luna": openai_down.clients(), "haiku": claude_ok.clients()}, sleep=lambda s: None)
resp = client.complete(Request(model="fast", messages=[Message.user("Say hello.")]))
print()
print("answer :", resp.text)
print("served by :", resp.model_key, f"({resp.provider}, {resp.resolved_model})")
print("requests : openai", openai_down.n, "| anthropic", claude_ok.n, "(the SDKs retried nothing themselves)")
print("attempts :", [(a.model_key, a.n, a.error_type or "ok") for a in resp.attempts])
print(f"cost : ${resp.cost.usd:.7f} ({resp.cost.source}, price table {resp.cost.price_version})")
print("failed tries:", sum(not a.ok for a in resp.attempts), "(kept on resp.attempts and in the log; a 503 is normally not billed, a timeout may be)"){"event": "llm_attempt", "call_id": "f5435b0b84f7498d", "model_key": "luna", "provider": "openai", "api": "responses", "n": 1, "ok": false, "error": "Overloaded", "status": 503, "request_id": "req_err_1", "latency_ms": 66, "tags": {}}
{"event": "llm_attempt", "call_id": "f5435b0b84f7498d", "model_key": "luna", "provider": "openai", "api": "responses", "n": 2, "ok": false, "error": "Overloaded", "status": 503, "request_id": "req_err_1", "latency_ms": 1, "tags": {}}
{"event": "llm_attempt", "call_id": "f5435b0b84f7498d", "model_key": "haiku", "provider": "anthropic", "api": "messages", "n": 1, "ok": true, "error": null, "status": null, "request_id": "req_anth_1", "latency_ms": 6, "tags": {}}
{"event": "llm_call", "call_id": "f5435b0b84f7498d", "alias": "fast", "model_key": "haiku", "provider": "anthropic", "api": "messages", "resolved_model": "claude-haiku-5-5", "finish": "stop", "raw_finish": "end_turn", "uncached_input_tokens": 30, "cached_input_tokens": 0, "cache_write_tokens": 0, "total_input_tokens": 30, "output_tokens": 6, "reasoning_tokens": 0, "cost_usd": 6e-06, "request_id": "req_anth_1", "latency_ms": 72, "attempts": 3, "tags": {}}
answer : Hello from Claude.
served by : haiku (anthropic, claude-haiku-5-5)
requests : openai 2 | anthropic 1 (the SDKs retried nothing themselves)
attempts : [('luna', 1, 'Overloaded'), ('luna', 2, 'Overloaded'), ('haiku', 1, 'ok')]
cost : $0.0000060 (computed, price table 2026-11-04)
failed tries: 2 (kept on resp.attempts and in the log; a 503 is normally not billed, a timeout may be)Read the evidence the wrapper gives you (note that the tags your request carried sit under their own key, so no tag can overwrite a real field): two llm_attempt lines for OpenAI (both Overloaded, with OpenAI's request ID), one for Anthropic, and a single llm_call line that says the answer came from haiku, which provider and snapshot served it, what it cost, and that it took three attempts. Because the SDK retries were off, the mock OpenAI server saw exactly two requests.
What is deliberately not here. Circuit breakers (stop sending traffic to a provider that has failed ten times in a row, instead of paying the timeout on every request), health-based routing, latency-aware or cost-aware routing, cascades (try cheap, escalate on a failed check), weighted traffic splits and per-tenant routing are Module 11B. The simple chain here has no memory: every call tries the primary first, even in the middle of an outage, which costs one failed attempt per call. That is acceptable for a modest volume, and it is exactly the problem a circuit breaker solves. OpenRouter's server-side models fallback list and LiteLLM's Router are gateway-side versions of this feature (Part 13).
8.5 Failure semantics worth stating plainly#
- A failed attempt with no response is not billed by the wrapper, but a timeout may have been billed by the provider (03.8, 6.6). A reply that was received and then discarded (a refusal you chose to fall back from, an invalid structured reply) is billed, and is recorded: as an
AttemptmarkedFinishFallback:refusalwith its own usage and cost, or onerr.response(5.6). Duplicate generation after a timeout-then-retry is possible and, for inference, there are no idempotency keys (03.8, Part 11). Tools with side effects need your own deduplication. - Every attempt is visible.
Response.attemptson success andLLMError.attemptson failure list model, number, outcome, status, request ID and latency. - Nothing retries silently after output has started (streams, 5.1).
- A discarded fallback reply is visible. With
fallback_on_finishset, the refused reply is recordedok=Falsewith the reason, notok=True: the attempt list says why the fallback happened.
Part 9: Hooks: logging, cost and metrics#
Deep-dive
Logging, cost recording and metrics are the same thing seen three ways: something that happens on every call. The client exposes five moments, and they come in two kinds that fail in opposite directions:
# provider_agnostic/hooks.py: the extension points
@dataclass
class CallContext:
call_id: str
alias: str # what the caller asked for
started: float # monotonic clock
tags: dict[str, str] = field(default_factory=dict) # Request.metadata, validated and scrubbed: for YOUR logs only
class Hook:
fail_closed: bool = False # True: an exception in after() stops the call instead of being logged and ignored
def before(self, ctx: CallContext, req: Request) -> Request: # request middleware: ALWAYS fail-closed
return req
def attempt(self, ctx: CallContext, attempt: Attempt) -> None: # every try, ok or not
pass
def after(self, ctx: CallContext, req: Request, resp: Response) -> Response: # response middleware or observer
return resp
def error(self, ctx: CallContext, req: Request, err: LLMError) -> None: # the call failed for good
pass
def abandoned(self, ctx: CallContext, req: Request, partial: Response) -> None: # the consumer stopped reading a stream
pass| Moment | Kind | Use it for |
|---|---|---|
before(ctx, req) -> Request |
middleware, always fail-closed | Add a system-prompt suffix, enforce a per-user token budget (03.7, Part 12), redact, tag |
attempt(ctx, attempt) |
observer | Per-attempt logs and counters: one line per try, including failures |
after(ctx, req, resp) -> Response |
observer, or middleware if the hook sets fail_closed = True |
Final logging and cost records (observer); response redaction or validation (middleware) |
error(ctx, req, err) |
observer | One line when the whole call failed, with every attempt attached, plus the billed-but-rejected reply (err.response) or the part of a stream that arrived (err.partial) |
abandoned(ctx, req, partial) |
observer | The consumer stopped reading a stream; partial has the usage the provider reported (5.1) |
Observers must not break the call; middleware must. A metrics server that is down must not turn into a failed user request, so an exception from an observer is caught, and the client logs the hook, the method and the exception's type, never its message or a traceback (either can contain the very text the hook choked on). But a hook that exists to stop or change the call is the opposite: if a per-user budget gate raises to block the call, ignoring the exception sends the call anyway, and if a redactor crashes on a malformed input, ignoring it sends the unredacted prompt to a provider. The first version wrapped every hook in try/except and carried on with the original request, which is fail-open on the privacy path: exactly what 03.10 says must be fail-closed. Two probes showed it: call went through despite gate raising: 1 request(s) sent and sent body contains card: True. So now:
beforeis always fail-closed. If it raises, nothing is sent: the caller gets the hook's ownLLMErrorunchanged (a gate that raisesQuotaExceeded), or aHookErrorwhose__cause__is the hook's exception (the message names the hook and the exception type only). Theerrorhooks still fire, so the stopped call is visible.afteris fail-closed only for a hook that says so (fail_closed = True): a response redactor or validator. The response was already paid for, so it travels on theHookErroraserr.responseand the error hooks record it. Logging and cost hooks stay observers.
The failing tests came first (their real output, against the first version, is in 11.3), and s9_fail_closed_demo.py shows the fix as a measurement (the scripted server records every request; layer 3):
"""s9_fail_closed_demo.py: request middleware that raises must STOP the call, not be ignored (layer 3: scripted servers).
Both gates fail on purpose. The server records every request, so "nothing was sent" is a measurement, not a hope."""
import os
from provider_agnostic import Hook, HookError, LLMClient, Message, Policy, QuotaExceeded, RedactHook, Registry, Request
from tests.fakes import FakeResponses, Server
os.environ["OPENAI_API_KEY"] = "sk-test"
CARD = "4111 1111 1111 1111"
spec = Registry.load().models["luna"].model_dump(exclude={"key"})
registry = Registry({"version": "demo", "models": {"luna": {**spec, "base_url": "https://mock.test/v1"}}})
def run(label: str, hooks: list[Hook], text: str = f"My card is {CARD}, please help.") -> Server:
server = Server([FakeResponses().text()])
client = LLMClient(registry, hooks=hooks, policy=Policy(), http_clients={"luna": server.clients()})
try:
resp = client.complete(Request(model="luna", messages=[Message.user(text)]))
outcome = f"sent -> {resp.text!r}"
except (HookError, QuotaExceeded) as err:
outcome = f"{type(err).__name__}: {err.message}"
body = str(server.requests[0]["json"]["input"]) if server.n else "-"
print(f"{label:26s} requests={server.n} card in the sent body: {CARD in body!s:5s} {outcome}")
return server
class BudgetGate(Hook):
def before(self, ctx, req):
raise QuotaExceeded("user is over today's token budget") # a gate that blocks by raising
class BrokenRedactor(Hook):
def before(self, ctx, req):
raise ValueError("regex blew up on this input") # a redactor with a bug
run("budget gate raises", [BudgetGate()])
run("redactor crashes", [BrokenRedactor()])
run("RedactHook (working)", [RedactHook()])
run("no hooks (for contrast)", [])budget gate raises requests=0 card in the sent body: False QuotaExceeded: user is over today's token budget
redactor crashes requests=0 card in the sent body: False HookError: hook BrokenRedactor.before raised ValueError: nothing was sent
RedactHook (working) requests=1 card in the sent body: False sent -> 'Hello there'
no hooks (for contrast) requests=1 card in the sent body: True sent -> 'Hello there'Five hooks ship with the package. Middleware first:
# provider_agnostic/hooks.py: a fail-closed, allow-list redactor
class RedactHook(Hook):
"""Request middleware: scrub what you are about to send. Fail-closed in two ways.
* `Hook.before` always is: if this hook raises, the call is stopped, so a bug here can never send the original
text to a provider.
* It is allow-list shaped: it rewrites the part types it knows how to read and REFUSES anything else, including
images and PDFs (it cannot see inside them) unless you say `allow_media=True`. A future part type raises
instead of passing through unexamined.
A rewritten text, tool-result or tool-call part loses its `native` twin: that twin holds the original text
and would be replayed instead. (A `ReasoningPart` keeps its signed `native`: editing it would break the
provider's signature, so only its human-readable `text` summary is scrubbed.)"""
def __init__(self, *, allow_media: bool = False) -> None:
self.allow_media = allow_media
def before(self, ctx: CallContext, req: Request) -> Request:
messages = [Message(role=m.role, parts=[self._part(p) for p in m.parts]) for m in req.messages]
return req.model_copy(update={"messages": messages, "system": redact_text(req.system) if req.system else None})
def _part(self, p: Part) -> Part:
if isinstance(p, TextPart):
clean = redact_text(p.text)
return p if clean == p.text else TextPart(text=clean)
if isinstance(p, ToolResultPart):
clean = redact_text(p.content)
return p if clean == p.content else p.model_copy(update={"content": clean, "native": None})
if isinstance(p, ToolCallPart):
clean_args = scrub(p.arguments)
return p if clean_args == p.arguments else p.model_copy(update={"arguments": clean_args, "native": None})
if isinstance(p, ReasoningPart):
return p.model_copy(update={"text": redact_text(p.text) if p.text else p.text}) # the signed native stays
if isinstance(p, (ImagePart, DocumentPart)) and self.allow_media:
return p
raise HookError(f"RedactHook cannot inspect a {type(p).__name__}: refusing to send it "
"(pass allow_media=True if you accept that images and PDFs are not scrubbed)")RedactHook is allow-list shaped: it rewrites the part types it knows how to read (text, tool results, tool-call arguments at any depth, reasoning summaries) and refuses everything else, including images and PDFs, because it cannot see inside them (allow_media=True is a decision you make in code). A rewritten text, tool-result or tool-call part loses its native twin, because the twin holds the original text and would be replayed instead; a reasoning part keeps its signed native (editing it would break the provider's signature), so only its text summary is scrubbed. The shapes it knows (redact.py: OpenAI, Anthropic, OpenRouter, Google, GitHub and AWS keys, bearer tokens, JWTs, password=-style pairs, emails and card-like digit runs) are the same families as 03.10's redactor, which has the fuller list and the reasoning; one test per key shape keeps them honest. It is a best-effort net, not a guarantee. Where user IDs go in your tags, use the keyed hash:
# provider_agnostic/redact.py: redaction and the keyed user hash (no default key)
"""provider_agnostic/redact.py: a small, fail-closed redactor and a keyed user hash (lesson 03.10, Parts 2 and 4).
Best effort, not a guarantee: regexes only know the shapes listed here (keep them under test, as tests/test_hooks.py
does), and nothing here can look inside an image or a PDF. Lesson 03.10 has the fuller pattern list and the reasoning;
the shapes below are the same families, small enough to read in one go. Module 12 treats data protection properly.
"""
from __future__ import annotations
import hashlib
import hmac
import os
import re
from typing import Any
from .errors import ConfigError
# Credential shapes as of November 2026: OpenAI, Anthropic and OpenRouter (sk-...), Google API keys and OAuth tokens,
# GitHub, AWS access key IDs, bearer tokens and JWTs. Each prefix is a vendor's convention: re-check them.
_CREDENTIALS = re.compile(
r"(?<![A-Za-z0-9_-])(?:sk-(?:ant-|or-v1-|or-|proj-)?[A-Za-z0-9_-]{16,}|AIza[0-9A-Za-z_-]{30,}|ya29\.[A-Za-z0-9_-]{20,}"
r"|gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{30,}|(?:AKIA|ASIA)[0-9A-Z]{16}"
r"|eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,})|(?i:\bbearer\s+[A-Za-z0-9._\-]{12,})")
_KEY_VALUE = re.compile(r"""(?i)\b(password|passwd|secret|api[_-]?key|access[_-]?token|token)(["']?\s*[:=]\s*["']?)([^\s"',;&]{4,})""")
_EMAIL = re.compile(r"\b[\w.+-]+@[\w-]+(?:\.[\w-]+)+\b")
_CARD = re.compile(r"\b\d(?:[ -]?\d){12,18}\b") # long digit runs: card and account numbers
def redact_text(text: str) -> str:
"""Replace credentials, emails and card-like digit runs with a [LABEL]."""
text = _CREDENTIALS.sub("[CREDENTIAL]", text)
text = _KEY_VALUE.sub(lambda m: f"{m.group(1)}{m.group(2)}[SECRET]", text)
return _CARD.sub("[CARD]", _EMAIL.sub("[EMAIL]", text))
def scrub(value: Any) -> Any:
"""Strings inside tool arguments, at any depth."""
if isinstance(value, str):
return redact_text(value)
if isinstance(value, dict):
return {k: scrub(v) for k, v in value.items()}
if isinstance(value, list):
return [scrub(v) for v in value]
return value
def hash_user(user_id: str, *, key: bytes | None = None, purpose: str = "logs-v1") -> str:
"""A KEYED hash for `metadata={"user": hash_user(uid)}`: stable per user, but nobody can rebuild it from a list of
emails without the key. It is the recipe of lesson 03.2, 10.3: HMAC-SHA256 over "purpose:user_id". The default
purpose "logs-v1" is for IDs in your own logs and cost records; the ID you send to a provider
(`extra={"openai": {"safety_identifier": ...}}`) uses purpose="llm-abuse-v1", so the two can't be matched.
The key has NO default: pass it, or set USER_ID_PEPPER (from your secret store, like an API key). A missing key is a
ConfigError, not a quiet fallback to a public one (lesson 03.10, 4.1).
16 hex characters are enough to correlate one user's calls, not collision-proof across billions of users."""
secret = key or os.environ.get("USER_ID_PEPPER", "").encode()
if not secret:
raise ConfigError("hash_user needs a secret key: pass key= or set USER_ID_PEPPER")
return hmac.new(secret, f"{purpose}:{user_id}".encode(), hashlib.sha256).hexdigest()[:16]Then the observers:
# provider_agnostic/hooks.py: logging, cost file, metrics, OpenTelemetry
def _usage_fields(u: Usage | None) -> dict[str, Any]:
"""The same names as the `Usage` fields (03.7's columns): `uncached_input_tokens` is billed at the plain rate;
there is no bare `input_tokens`. `cache_write_tokens` is the sum over lifetimes here."""
if u is None:
return {"uncached_input_tokens": None, "cached_input_tokens": None, "cache_write_tokens": None,
"total_input_tokens": None, "output_tokens": None, "reasoning_tokens": None}
return {"uncached_input_tokens": u.uncached_input_tokens, "cached_input_tokens": u.cached_input_tokens,
"cache_write_tokens": sum(u.cache_write_tokens.values()), "total_input_tokens": u.total_input_tokens,
"output_tokens": u.output_tokens, "reasoning_tokens": u.reasoning_tokens}
class LoggingHook(Hook):
"""One JSON line per attempt and per call. Logs sizes and IDs, never prompt or answer text.
Your tags live under their own `tags` key, so a tag called `cost_usd` or `event` can never overwrite a real field."""
def attempt(self, ctx: CallContext, attempt: Attempt) -> None:
a = attempt
log.info(json.dumps({"event": "llm_attempt", "call_id": ctx.call_id, "model_key": a.model_key,
"provider": a.provider, "api": a.api, "n": a.n, "ok": a.ok,
"error": a.error_type, "status": a.status, "request_id": a.request_id,
"latency_ms": a.latency_ms, "tags": ctx.tags}))
def after(self, ctx: CallContext, req: Request, resp: Response) -> Response:
log.info(json.dumps({
"event": "llm_call", "call_id": ctx.call_id, "alias": ctx.alias, "model_key": resp.model_key,
"provider": resp.provider, "api": resp.api, "resolved_model": resp.resolved_model,
"finish": resp.finish_reason.value, "raw_finish": resp.raw_finish_reason,
**_usage_fields(resp.usage), "cost_usd": resp.cost.usd if resp.cost else None,
"request_id": resp.request_id, "latency_ms": resp.latency_ms, "attempts": len(resp.attempts),
"tags": ctx.tags}))
return resp
def error(self, ctx: CallContext, req: Request, err: LLMError) -> None:
paid = err.response or err.partial # a billed reply we rejected, or the part of a stream that arrived
log.warning(json.dumps({"event": "llm_call_failed", "call_id": ctx.call_id, "alias": ctx.alias,
"error": type(err).__name__, "status": err.status, "code": err.code,
"request_id": err.request_id, "attempts": len(err.attempts),
**_usage_fields(paid.usage if paid else None),
"cost_usd": paid.cost.usd if paid and paid.cost else None, "tags": ctx.tags}))
def abandoned(self, ctx: CallContext, req: Request, partial: Response) -> None:
log.warning(json.dumps({"event": "llm_stream_abandoned", "call_id": ctx.call_id, "alias": ctx.alias,
"model_key": partial.model_key, "request_id": partial.request_id,
**_usage_fields(partial.usage), "cost_usd": partial.cost.usd if partial.cost else None,
"tags": ctx.tags}))
class JsonlCostHook(Hook):
"""Append one record per call to a JSON Lines file, whatever its outcome (same columns as lesson 03.7's tracker):
`ok`, `invalid` (a reply that failed validation: billed), `failed` (an error, with the partial usage of a broken
stream when it is known) or `abandoned` (the consumer stopped reading). `cost_usd` is null, never 0, when unknown.
The file holds spend, request IDs and user-hash tags, so it is created owner-only: the directory 0700, the file 0600,
from the first byte (os.open with the mode, not write-then-chmod). It rotates to `<name>.1` at `max_bytes` (one
generation: ship the old file to your log store before it is replaced), and `fsync=True` makes each record durable."""
def __init__(self, path: str | Path, *, max_bytes: int = 50_000_000, fsync: bool = False) -> None:
self.path, self.max_bytes, self.fsync, self._lock = Path(path), max_bytes, fsync, threading.Lock()
self.path.parent.mkdir(parents=True, mode=0o700, exist_ok=True)
os.close(self._open()) # create it now: a bad path fails at startup, not mid-call
def _open(self) -> int:
flags = os.O_WRONLY | os.O_CREAT | os.O_APPEND | getattr(os, "O_NOFOLLOW", 0) # never follow a planted symlink
fd = os.open(self.path, flags, 0o600)
if hasattr(os, "fchmod") and os.fstat(fd).st_mode & 0o077: # an older, wider file: tighten it before writing a byte (POSIX only)
os.fchmod(fd, 0o600)
return fd
def _write(self, record: dict[str, Any]) -> None:
line = (json.dumps(record, default=str) + "\n").encode()
with self._lock:
if self.path.exists() and self.path.stat().st_size + len(line) > self.max_bytes:
os.replace(self.path, self.path.with_name(self.path.name + ".1"))
fd = self._open()
try:
os.write(fd, line)
if self.fsync:
os.fsync(fd)
finally:
os.close(fd)
def _record(self, ctx: CallContext, outcome: str, resp: Response | None, err: LLMError | None = None) -> dict[str, Any]:
usage = resp.usage if resp else None
wasted = sum(a.cost_usd or 0.0 for a in (resp.attempts if resp else []) if not a.ok) # discarded, billed replies
return {"call_id": ctx.call_id, "kind": "call", "outcome": outcome, "alias": ctx.alias,
"provider": resp.provider if resp else None, "model_key": resp.model_key if resp else None,
"served_model": resp.resolved_model if resp else None, "api": resp.api if resp else None,
"request_id": (resp.request_id if resp else None) or (err.request_id if err else None),
"tier": usage.tier if usage else None, "batch": bool(usage and usage.tier == "batch"),
"regional": bool(usage and usage.regional), **_usage_fields(usage),
"cost_usd": resp.cost.usd if resp and resp.cost else None,
"cost_source": resp.cost.source if resp and resp.cost else "unknown",
"price_version": resp.cost.price_version if resp and resp.cost else None,
"discarded_cost_usd": wasted or None,
"finish_reason": resp.raw_finish_reason if resp else None,
"error": type(err).__name__ if err else None,
"attempts": len(resp.attempts) if resp else (len(err.attempts) if err else None),
"latency_ms": resp.latency_ms if resp else None, "tags": ctx.tags}
def after(self, ctx: CallContext, req: Request, resp: Response) -> Response:
self._write(self._record(ctx, "ok", resp))
return resp
def error(self, ctx: CallContext, req: Request, err: LLMError) -> None:
paid = err.response or err.partial
self._write(self._record(ctx, "invalid" if err.response is not None else "failed", paid, err))
def abandoned(self, ctx: CallContext, req: Request, partial: Response) -> None:
self._write(self._record(ctx, "abandoned", partial))
class MetricsHook(Hook):
"""In-memory counters. Swap the body for Prometheus, StatsD or OpenTelemetry (Module 11A)."""
def __init__(self) -> None:
self.counts: Counter[str] = Counter()
self.latency_ms_total = 0
self._lock = threading.Lock()
def attempt(self, ctx: CallContext, attempt: Attempt) -> None:
with self._lock:
self.counts[f"attempt.{attempt.model_key}.{'ok' if attempt.ok else attempt.error_type}"] += 1
self.latency_ms_total += attempt.latency_ms
def after(self, ctx: CallContext, req: Request, resp: Response) -> Response:
with self._lock:
self.counts[f"finish.{resp.finish_reason.value}"] += 1
return resp
def error(self, ctx: CallContext, req: Request, err: LLMError) -> None:
with self._lock:
self.counts[f"failed.{type(err).__name__}"] += 1
def abandoned(self, ctx: CallContext, req: Request, partial: Response) -> None:
with self._lock:
self.counts["abandoned"] += 1
class OTelHook(Hook):
"""One span per call, with OpenTelemetry's GenAI attribute names (lesson 03.10, 4.7: still marked Development, so
the names can change). Pass `trace.get_tracer("my-app")`. No prompt or answer text goes on the span.
It is an observer: a broken tracer is logged and ignored (it must never stop a call), and the span is closed on
every path: success, failure and an abandoned stream. List it FIRST so the span covers the other hooks."""
def __init__(self, tracer: Tracer) -> None:
self.tracer, self._spans, self._lock = tracer, {}, threading.Lock()
def before(self, ctx: CallContext, req: Request) -> Request:
try:
span = self.tracer.start_span(f"chat {req.model}")
span.set_attribute("gen_ai.operation.name", "chat")
span.set_attribute("gen_ai.request.model", req.model) # the ALIAS; the served model is set at the end
with self._lock:
self._spans[ctx.call_id] = span
except Exception as exc: # an observer inside a fail-closed slot: contain it here
log.warning("OTelHook.before failed: %s", type(exc).__name__)
return req
def _finish(self, ctx: CallContext, attrs: dict[str, Any]) -> None:
with self._lock:
span = self._spans.pop(ctx.call_id, None)
if span is None:
return
for key, value in attrs.items():
if value is not None:
span.set_attribute(key, value)
span.end()
def after(self, ctx: CallContext, req: Request, resp: Response) -> Response:
u = resp.usage
self._finish(ctx, {"gen_ai.provider.name": resp.provider, "gen_ai.response.model": resp.resolved_model,
"gen_ai.response.id": resp.provider_response_id or resp.request_id, "gen_ai.response.finish_reasons": [resp.finish_reason.value],
"gen_ai.usage.input_tokens": u.total_input_tokens if u else None, # the semconv counts ALL input
"gen_ai.usage.output_tokens": u.output_tokens if u else None,
"gen_ai.usage.cache_read.input_tokens": u.cached_input_tokens if u else None})
return resp
def error(self, ctx: CallContext, req: Request, err: LLMError) -> None:
self._finish(ctx, {"error.type": type(err).__name__})
def abandoned(self, ctx: CallContext, req: Request, partial: Response) -> None:
self._finish(ctx, {"error.type": "Abandoned"})LoggingHookwrites one JSON line per attempt and per call, with IDs, sizes, finish reasons and cost, never prompt or answer text. Yourmetadataappears under its owntagskey, sometadata={"cost_usd": "0", "event": "llm_call"}cannot overwrite a real field (the first version spread tags last into the line, which let a caller forge a log entry). Tag keys and values are validated when theRequestis built and scrubbed of credential shapes before any hook sees them (3.2). The token fields use the same names asUsageand as 03.7's and 03.10's cost logs (uncached_input_tokens,cached_input_tokens,cache_write_tokensas one summed number,total_input_tokens,output_tokens,reasoning_tokens): there is no bareinput_tokens, which means different things on different providers. What to log, what to redact and how to reproduce a failure from the log are 03.10's subject; the discipline here is that the wrapper is the one place all of it is logged, so a new call site gets it for free.JsonlCostHookis the same idea as 03.7'sCostTracker(one JSON line per call,nullfor unknown cost, the price-table version), with the same column names (uncached_input_tokens,cached_input_tokens,cache_write_tokens,total_input_tokens,served_model,api,batch,regional,attempts...), and one more:outcome, one ofok,invalid(a billed reply that failed validation),failed(with the partial usage of a broken stream when it is known) andabandoned. Every paid-for path leaves a record. The file holds spend, request IDs and user-hash tags, so it follows 03.10's file rules: the directory is created0700and the file0600from the first byte (os.openwith the mode, not write-then-chmod, which leaves a window at the umask default), a wider existing file is tightened before anything is written (on Windows, which has nofchmodand no owner-only mode bits, that step is skipped), a symlink planted at the path is refused (O_NOFOLLOW), and it rotates to<name>.1atmax_bytes(one generation: ship the old file to your log store first).fsync=Truemakes each record durable at a cost. It is a deliberately smaller version of 03.7's tracker (which records a Responses or Interactions object that endsfailedorcancelledasstatus: "error:failed"; here that case never reaches the file as a success, because the adapters raise it and the record isoutcome: "failed"); if you built that one with customer hashing and budgets, call it from anafterhook instead and keep one cost log.MetricsHookcounts attempts per route, failures per class and abandoned streams in memory. Replace the body with Prometheus or StatsD calls (Module 11A covers tracing and dashboards).OTelHookmaps one call to one OpenTelemetry span with the GenAI attribute names 03.10, 4.7 lists (gen_ai.request.model,gen_ai.response.model,gen_ai.response.id,gen_ai.usage.input_tokens,gen_ai.usage.output_tokens,gen_ai.usage.cache_read.input_tokens,gen_ai.response.finish_reasons), with no prompt or answer text. The conventions are still marked Development, so the names can change. It takes any object withstart_span, so the tests drive it with a fake tracer and you passtrace.get_tracer("my-app"). It is an observer inside a slot that is fail-closed (beforestarts the span), so it contains its own exceptions: a collector that is down must not stop a call. The span is closed on every path (success, error, abandoned stream).
# provider_agnostic/client.py: observers are fired through one guarded function; `before` through none
def _fire(self, name: str, *args: Any) -> None:
"""Observers: a broken one is contained. Log the hook, the method and the exception TYPE only: the message and
the traceback can contain the very text the hook choked on (a prompt, a card number)."""
for h in self.hooks:
try:
getattr(h, name)(*args)
except Exception as exc:
log.warning("observer hook %s.%s failed: %s", type(h).__name__, name, type(exc).__name__)
def _start(self, req: Request) -> _Run:
ctx = CallContext(call_id=uuid.uuid4().hex[:16], alias=req.model, started=self.clock(),
tags={k: redact_text(v) for k, v in req.metadata.items()})
original = req
for h in self.hooks: # request middleware, in order: FAIL-CLOSED
try:
req = h.before(ctx, req)
except LLMError as err: # the hook chose its own error (a budget gate: QuotaExceeded)
raise self._fail_before(ctx, original, err) from None
except Exception as exc: # a bug in the hook: stop the call, never send the original
err = HookError(f"hook {type(h).__name__}.before raised {type(exc).__name__}: nothing was sent",
code="hook_failed")
raise self._fail_before(ctx, original, err) from exc
self.preflight(req.model) # every key the chain needs, before the first request
chain = self.registry.chain(req.model)
for spec in chain: # check the WHOLE chain up front: no half-working fallbacks
check_capabilities(req, spec)
return _Run(self, req, ctx, chain)Part 10: Running it against the local stand-in#
Everything so far was a mock or pure Python. Now the same package makes real requests through the real SDKs to the free local stand-in (03.1, Part 12): Ollama for the OpenAI Responses, OpenAI Chat and Anthropic Messages routes. Ollama does not speak Gemini's API, so the Gemini routes (generate_content and Interactions) have no local entry: they are hosted-only and covered by the mock-server tests of Part 11 and the hosted sample of Part 12. The stand-in registry uses the same three API shapes as the hosted one for those routes, pointed at localhost, and marks them free: true:
# provider_agnostic/models.local.yaml (abridged): the same adapters, a different registry
aliases:
local: [local-responses, local-chat, local-anthropic]
models:
local-responses:
provider: local # selects the "local" dialect of the Chat adapter, the plain Responses adapter
api: responses
model: qwen2.5:0.5b
base_url: http://localhost:11434/v1
api_key_env: LOCAL_API_KEY # NOT OPENAI_API_KEY: a real key must never go to localhost
key_optional: true # Ollama ignores keys: unset means the placeholder "local"
free: true
capabilities: {tools: true, forced_tool_choice: false, structured_output: true, images: false,
documents: false, reasoning: false, stream_usage: true,
stop: false, parallel_tool_switch: false, strict_tools: false} # Ollama ignores strict and tool_choice
local-anthropic:
provider: local
api: messages
model: qwen2.5:0.5b
base_url: http://localhost:11434
api_key_env: LOCAL_API_KEY
key_optional: true
free: true
capabilities: {tools: true, forced_tool_choice: false, structured_output: false, # Ollama ignores output_config
images: false, documents: false, reasoning: false, stream_usage: true,
stop: true, parallel_tool_switch: false, strict_tools: false}
# local-chat: see the appendix. There is no local Gemini entry: Ollama does not speak Gemini's API (03.1, 12.4).Notice how little changes between development and production: the registry file, not the code. capabilities honestly says what this stand-in cannot do (no forced tool choice, no schema enforcement on the Anthropic route, no images, no strict tools), so the wrapper refuses those requests instead of letting a toy model produce confident nonsense. The key variable is the stand-in's own: LOCAL_API_KEY (optional), never a hosted provider's variable.
Start the stand-in: Ollama running, then source localstack/env.sh (localstack/env.sh, in the appendix, points the SDKs at localhost and sets the stand-in's dummy keys). With Ollama running, run the demo (layer 2):
"""s10_standin_demo.py: the wrapper end to end against the LOCAL stand-in (layer 2).
Run it after `. localstack/env.sh` with Ollama running.
A 0.5B model writes the text; what this proves is the plumbing through the three real SDK paths."""
import asyncio
from pydantic import BaseModel
from provider_agnostic import (Done, LLMClient, Message, Policy, Registry, Request, TextDelta, ToolResultPart, ToolSpec, UnsupportedFeature)
from weather_tools import GetWeather, run_tool # lesson 03.5's example tools
ROUTES = ["local-responses", "local-chat", "local-anthropic"]
client = LLMClient(Registry.load("provider_agnostic/models.local.yaml"), policy=Policy(max_attempts=1, attempt_timeout_s=60))
class Capital(BaseModel):
city: str
country: str
print("1. plain call")
for route in ROUTES:
r = client.complete(Request(model=route, system="Be brief.", messages=[Message.user("Say hello in three words.")]))
print(f" {route:16s} {r.text.strip()!r:34} finish={r.finish_reason.value} tokens={r.usage.uncached_input_tokens}+{r.usage.output_tokens} "
f"cost=${r.cost.usd} id={r.request_id}")
print("2. streaming (one event vocabulary for all three)")
for route in ROUTES:
events = list(client.stream(Request(model=route, max_output_tokens=40, messages=[Message.user("Count to three.")])))
deltas = [e.text for e in events if isinstance(e, TextDelta)]
done = events[-1]
assert isinstance(done, Done)
print(f" {route:16s} {len(deltas):2d} text events, then Done(finish={done.response.finish_reason.value}, "
f"usage={'n/a' if done.response.usage is None else done.response.usage.output_tokens})")
print("3. structured output (a Pydantic model in, a validated object out)")
for route in ROUTES:
try:
r = client.complete(Request(model=route, max_output_tokens=80, output_schema=Capital,
messages=[Message.user("Name the capital of France. Give the city and the country.")]))
print(f" {route:16s} {r.parsed!r}")
except UnsupportedFeature as err:
print(f" {route:16s} UnsupportedFeature: {err.message}")
print("4. one tool round trip")
tool = ToolSpec.from_model(GetWeather)
for route in ROUTES:
req = Request(model=route, max_output_tokens=200, tools=[tool],
messages=[Message.user("What is the weather in Paris, in celsius? Use the tool.")])
first = client.complete(req)
if not first.tool_calls:
print(f" {route:16s} the small model answered without calling the tool")
continue
call = first.tool_calls[0]
output, is_error = run_tool(call.name, call.arguments)
second = client.complete(req.model_copy(update={"messages": [
*req.messages, first.message, Message.tool_results(ToolResultPart(call_id=call.id, name=call.name, content=output, is_error=is_error))]}))
print(f" {route:16s} call id={call.id[:12]!r:15} args={call.arguments} -> {second.text.strip()[:60]!r}")
async def main() -> None:
print("5. async: three calls at once on the same client")
replies = await asyncio.gather(*(client.acomplete(Request(model=r, max_output_tokens=20, messages=[Message.user("Hi")]))
for r in ROUTES))
print(" ", [r.model_key for r in replies], "all finished:", all(r.text for r in replies))
await client.aclose()
asyncio.run(main())Output (local model qwen2.5:0.5b via Ollama; a hosted model's text would differ):
1. plain call
local-responses 'Hello, how are you?' finish=stop tokens=22+7 cost=$0.0 id=resp_190052
local-chat 'Hello, how are you today?' finish=stop tokens=22+8 cost=$0.0 id=chatcmpl-915
local-anthropic 'Hello, how are you?' finish=stop tokens=22+7 cost=$0.0 id=msg_73c0c26c980d0c34cb5385f9
2. streaming (one event vocabulary for all three)
local-responses 40 text events, then Done(finish=stop, usage=40)
local-chat 40 text events, then Done(finish=length, usage=40)
local-anthropic 24 text events, then Done(finish=stop, usage=25)
3. structured output (a Pydantic model in, a validated object out)
local-responses Capital(city='Paris', country='France')
local-chat Capital(city=' Paris', country='France')
local-anthropic UnsupportedFeature: local-anthropic (local/messages/qwen2.5:0.5b) does not support schema-constrained structured output
4. one tool round trip
local-responses call id='call_4w5lcxl' args={'city': 'Paris', 'unit': 'celsius'} -> 'The weather in Paris is currently 10°C. You can get the curr'
local-chat call id='call_0gzkjjw' args={'unit': 'celsius', 'city': 'Paris'} -> "I found the weather in Paris, but I don't have the function "
local-anthropic call id='call_rhffxkh' args={'city': 'Paris', 'unit': 'celsius'} -> "It seems I don't have a tool named 'GetWeather' available. H"
5. async: three calls at once on the same client
['local-responses', 'local-chat', 'local-anthropic'] all finished: TrueWhat this proves, and what it doesn't:
- It proves the plumbing for three real SDK paths. The same
Requestran through the Responses, Chat and Messages adapters; three streams became one event vocabulary (Donealways last); a Pydantic model became a validated object on two routes and a clearUnsupportedFeatureon the third; tool calls were parsed, executed with 03.5'srun_tool, and sent back with their IDs; the async client served three calls concurrently on one set of adapters. (Ollama runs requests almost serially, so this says nothing about throughput: 03.9 uses mocks for concurrency.) - It does not prove hosted behaviour. The 0.5B model's answers to the weather question are poor ("I'm unable to retrieve the weather directly..."): it called the tool correctly and then ignored the result, which tells you about the model, not the wrapper. Ollama ignores
strictandtool_choice, doesn't verify how tool calls pair with results, and accepts histories a real provider would reject with a 400 (03.5, 9.1). - One stand-in quirk is visible in the output, a property of the stand-in and not of the wrapper: the Chat route's structured output has stray leading spaces in its strings (the tiny model's habit). The Gemini-specific cases (no response ID, a function call with no ID, a stream whose usage arrives as zeros) cannot be produced by this stand-in, so the wrapper's handling of them is covered by the mock-server tests of Part 11 instead.
cost=$0.0is the registry'sfree: true, deliberately different from theNone("unknown") a hosted, unpriced model gets.
Part 11: Testing the wrapper#
A provider-agnostic client is only as trustworthy as its tests, and the testing strategy is the part that most differs from "it worked when I tried it". The techniques (mock transports, fakes, recorded fixtures, contract tests, CI without keys) are lesson 03.10's; this part applies them. There are six kinds of test, cheapest first.
| Layer | What it checks | Needs | Files |
|---|---|---|---|
| Pure unit tests | Canonical types round-trip; registry loading, typos, credentials and capability checks; every Request field on the wire or refused; extra merging; each adapter's build() output for the same request; reasoning translation; usage arithmetic vs 03.7; the pin on the private OpenAI schema helper; registry audit |
nothing | test_types_registry.py, test_request_contract.py, test_wire.py, test_parity_schemas.py, test_refresh.py |
| The shared contract suite | Every adapter behaves the same: plain text, usage, truncation, refusal, tools, structured output, error mapping, retry counts, streaming (text, tool fragments, mid-stream failure, retry before first text), async | mock servers (the real SDKs run) | test_contract.py |
| Policy tests | Fallback, deadline, quota, refusal-doesn't-fall-back, hooks, cost, OpenRouter's cost and error-in-200 | mock servers | test_fallback_hooks.py |
| Fault-injection tests | A hung provider, a crashing redactor or budget gate, an HTTP 200 that says "failed", an invalid or abandoned or half-finished paid call, the empty thinking delta, usage modifiers (fast mode, geo, 12h writes, flex), request IDs on streams, the hooks' files and logs | mock servers, a fake clock | test_critical_fixes.py, test_billing_and_ids.py, test_hooks.py, test_stream_rules.py |
| Stand-in tests | The same wrapper against a real local model, for the Responses, Chat and Messages routes (the Gemini routes are hosted-only and covered by the mock servers) | Ollama | test_standin.py (marker standin, skipped when the servers are down or this shell has not sourced env.sh, each with its own stated reason) |
| Live smoke tests | A hosted model accepts our requests and returns what we parse | keys | the hosted sample in Part 12 |
11.1 Fake servers that speak each provider's dialect#
The mock servers aren't clever. tests/fakes.py has one small class per API (FakeResponses, FakeChat, FakeAnthropic, FakeGemini, FakeInteractions), each knowing how to produce a plain reply, a tool call, a truncation, a refusal, a block, each error kind and each stream, all in that provider's documented JSON shape, trimmed to what the SDK and our parser read. A Server wraps a scripted list of replies behind a MockTransport and records every request. Because the server is scripted, it can also misbehave on request, and that is what fault injection means: testing by making a dependency fail on purpose, a provider that hangs (a reply that never comes while a fake clock advances), a hook that raises, a 200 whose body says failed. Real providers fail like this only during outages, so unless you inject the fault, the code that handles it (retries, fallback, fail-closed hooks) is never exercised before the day it matters. The rest of this part uses it (11.3 shows the method):
# tests/fakes.py (the part that matters): a scripted server behind a mock transport
@dataclass
class Server:
"""A scripted server: replies are consumed in order; the last one repeats. Records requests."""
replies: list[Reply | Exception]
flavour: str = "httpx2" # "httpx2" for openai/anthropic, "httpx" for google-genai
requests: list[dict[str, Any]] = field(default_factory=list)
delay: Callable[[], None] | None = None
def _handle(self, request: Any) -> Any:
body = request.content.decode() if request.content else ""
self.requests.append({"method": request.method, "path": request.url.path, "query": str(request.url.query),
"headers": dict(request.headers), "json": json.loads(body) if body.startswith("{") else None})
if self.delay is not None:
self.delay() # fault injection: e.g. advance a fake clock by 30 s
item = self.replies[min(len(self.requests) - 1, len(self.replies) - 1)]
if isinstance(item, Exception):
raise item
status, headers, content = item
lib = httpx2 if self.flavour == "httpx2" else httpx
return lib.Response(status, headers=headers, content=content)
def clients(self) -> dict[str, Any]:
lib = httpx2 if self.flavour == "httpx2" else httpx
transport = lib.MockTransport(self._handle)
return {"sync": lib.Client(transport=transport), "async": lib.AsyncClient(transport=transport)}
@property
def n(self) -> int:
return len(self.requests)The fakes use httpx2.MockTransport for the openai and anthropic SDKs and httpx.MockTransport for google-genai 2.34.0 (3.x needs uv add httpx first, or an httpx2 mock: 4.1): respx would not have intercepted the first two (03.1, 4.5; in a research test, a "mocked" openai call went out to the real network). Fixtures copy the documented response and error shapes (03.8, Part 3): they prove the wrapper handles those shapes, not that the live API still sends them, which is what the contract tests against the stand-in and the live smoke test are for.
11.2 One suite, every adapter#
# tests/conftest.py: the cases every contract test runs against
def make_client(case: str, replies: list, **policy: Any) -> tuple[LLMClient, Server]:
"""A real LLMClient with a real SDK underneath, talking to a scripted in-process server."""
fake, spec = CASES[case]
server = Server(replies, flavour=fake.flavour)
client = LLMClient(registry_for({"m": spec}), http_clients={"m": server.clients()},
policy=Policy(**policy), sleep=lambda s: None, asleep=_asleep)
return client, serverCASES lists six adapter shapes (OpenAI Responses, OpenAI Chat, OpenRouter, Anthropic, Gemini generate_content, Gemini Interactions), each with the capabilities its real route has (Responses: no stop; Gemini: no parallel-tool switch, no strict tools). make_client(case, replies) builds a real LLMClient with a real SDK under it, talking to a scripted in-process server. The contract tests are parametrized over CASE_IDS, so every test runs six times. A new adapter is finished when it is added to CASES and the file stays green. Some of the tests:
# tests/test_contract.py (excerpts)
def test_plain_text_and_usage(case: str) -> None:
client, server = make_client(case, [fake(case).text("Hello there", inp=20, out=5, cached=8)])
resp = client.complete(HELLO)
assert resp.text == "Hello there"
assert resp.finish_reason is FinishReason.STOP
u = resp.usage
assert u is not None
# the contract: input EXCLUDES the 8 cached tokens, output INCLUDES reasoning, on every provider
assert (u.uncached_input_tokens, u.cached_input_tokens) == (12, 8)
assert u.output_tokens in (5, 7) # Gemini adds its 2 thought tokens to the output count
assert resp.provider == CASES[case][1]["provider"] and resp.requested_model == "m"
assert resp.cost is not None and resp.cost.usd is None # no price table given: unknown, never 0
assert server.n == 1
def test_tool_call_parsed_with_dict_arguments(case: str) -> None:
client, _ = make_client(case, [fake(case).tool_call()])
resp = client.complete(Request(model="m", messages=[Message.user("Weather in Paris?")], tools=[WEATHER]))
assert resp.finish_reason is FinishReason.TOOL_CALLS
(call,) = resp.tool_calls
assert call.name == "get_weather" and call.arguments == ARGS # OpenAI's JSON string is a dict here
assert call.arguments_error is None
@pytest.mark.parametrize("kind, exc, retryable", [
("rate_limit", RateLimited, True), ("overloaded", Overloaded, True), ("server", ServerError, True),
("quota", QuotaExceeded, False), ("context", ContextTooLong, False), ("auth", AuthFailed, False),
("bad_request", BadRequest, False)])
def test_error_mapping(case: str, kind: str, exc: type[LLMError], retryable: bool) -> None:
if case == "openrouter-chat" and kind == "overloaded":
pytest.skip("covered by the OpenRouter-specific tests")
if case == "gemini-generate" and kind == "quota":
# The one honest exception to the contract: Gemini models.* sends RESOURCE_EXHAUSTED for both "slow down"
# and "out of quota", with nothing in the body to tell them apart (lesson 03.8, 4.2).
exc, retryable = RateLimited, True
client, server = make_client(case, [fake(case).error(kind)], max_attempts=1)
with pytest.raises(exc) as info:
client.complete(HELLO)
err = info.value
assert err.retryable is retryable
assert err.__cause__ is not None # the SDK exception is never swallowed
assert err.provider == CASES[case][1]["provider"]
assert len(err.attempts) == 1 and not err.attempts[0].ok
assert server.n == 1
def test_retries_happen_once_not_multiplied(case: str) -> None:
"""Primary fails twice then succeeds. If the SDK also retried (max_retries=2) we would see 6+ requests."""
f = fake(case)
client, server = make_client(case, [f.error("overloaded") if case != "openrouter-chat" else f.error("server"),
f.error("server"), f.text()], max_attempts=3)
resp = client.complete(HELLO)
assert resp.text == "Hello there"
assert server.n == 3 # exactly: fail, fail, succeed
assert [a.ok for a in resp.attempts] == [False, False, True]
def test_stream_error_after_first_text_is_not_retried(case: str) -> None:
"""After the consumer has seen text, silently starting over would splice two answers together."""
client, server = make_client(case, [fake(case).stream_midway_error(["Par"]), fake(case).stream_text(["X"])])
got: list[str] = []
with pytest.raises(LLMError) as info:
for ev in client.stream(HELLO):
if isinstance(ev, TextDelta):
got.append(ev.text)
assert got == ["Par"] and server.n == 1
assert info.value.partial is not None and info.value.partial.text == "Par"These encode the design as executable rules:
- Usage arithmetic is a contract: with 20 input tokens of which 8 were cached, every provider must report
uncached_input_tokens == 12andcached_input_tokens == 8. - Errors map to the same class and the same
retryable, keep the SDK exception as__cause__, and keep the provider's request ID. The one exception (Geminigenerate_content's indistinguishable quota error) is written into the test, named and explained, rather than hidden by a loose assertion. - Retries happen exactly once: three attempts means exactly three requests at the server. If an adapter left the SDK's own retries on, this test fails with a larger number.
- A stream that fails after the first text raises and is not retried, and
err.partialholds what arrived.
Output (the whole suite: layers 1 to 3 plus the stand-in layer; the stand-in layer covers the three Ollama routes, so Gemini is exercised by the mock servers only; illustrative: the counts, line numbers and timings were recalculated after the Gemini tests were removed and not re-run, so yours will differ):
....................................s................................... [ 23%]
...s.....................................ss............................. [ 46%]
........................................................................ [ 69%]
........................................................................ [ 92%]
...................... [100%]
306 passed, 4 skipped in 5.52sThe contract file alone, one line per case (156 cases: 152 pass and 4 are skipped with a stated reason: openrouter-chat has its own overload tests, Gemini sends no request-ID header on errors, and Google documents no refusal signal for Interactions). The first rows:
Output (illustrative: the counts, line numbers and timings were recalculated after the Gemini tests were removed and not re-run, so yours will differ):
tests/test_contract.py::test_plain_text_and_usage[openai-responses] PASSED
tests/test_contract.py::test_plain_text_and_usage[openai-chat] PASSED
tests/test_contract.py::test_plain_text_and_usage[openrouter-chat] PASSED
tests/test_contract.py::test_plain_text_and_usage[anthropic] PASSED
tests/test_contract.py::test_plain_text_and_usage[gemini-generate] PASSED
tests/test_contract.py::test_plain_text_and_usage[gemini-interactions] PASSED
tests/test_contract.py::test_truncated_is_length_and_raises_on_request[openai-responses] PASSED
tests/test_contract.py::test_truncated_is_length_and_raises_on_request[openai-chat] PASSED
tests/test_contract.py::test_truncated_is_length_and_raises_on_request[openrouter-chat] PASSED
tests/test_contract.py::test_truncated_is_length_and_raises_on_request[anthropic] PASSED
tests/test_contract.py::test_truncated_is_length_and_raises_on_request[gemini-generate] PASSED
tests/test_contract.py::test_truncated_is_length_and_raises_on_request[gemini-interactions] PASSED
tests/test_contract.py::test_refusal_or_block_is_not_stop[openai-responses] PASSED
tests/test_contract.py::test_refusal_or_block_is_not_stop[openai-chat] PASSED
tests/test_contract.py::test_refusal_or_block_is_not_stop[openrouter-chat] PASSED
tests/test_contract.py::test_refusal_or_block_is_not_stop[anthropic] PASSED
tests/test_contract.py::test_refusal_or_block_is_not_stop[gemini-generate] PASSED
tests/test_contract.py::test_refusal_or_block_is_not_stop[gemini-interactions] SKIPPED
tests/test_contract.py::test_raw_finish_reason_is_kept[openai-responses] PASSED
tests/test_contract.py::test_raw_finish_reason_is_kept[openai-chat] PASSED
tests/test_contract.py::test_raw_finish_reason_is_kept[openrouter-chat] PASSED
tests/test_contract.py::test_raw_finish_reason_is_kept[anthropic] PASSED
tests/test_contract.py::test_raw_finish_reason_is_kept[gemini-generate] PASSED
tests/test_contract.py::test_raw_finish_reason_is_kept[gemini-interactions] PASSED...and the stand-in tests (layer 2, run against Ollama; there are no Gemini stand-in tests, because Ollama does not speak Gemini's API):
Output (illustrative: the counts, line numbers and timings were recalculated after the Gemini tests were removed and not re-run, so yours will differ):
tests/test_standin.py::test_plain_call[local-responses] PASSED
tests/test_standin.py::test_plain_call[local-chat] PASSED
tests/test_standin.py::test_plain_call[local-anthropic] PASSED
tests/test_standin.py::test_streaming[local-responses] PASSED
tests/test_standin.py::test_streaming[local-chat] PASSED
tests/test_standin.py::test_streaming[local-anthropic] PASSED
tests/test_standin.py::test_structured_output[local-responses] PASSED
tests/test_standin.py::test_structured_output[local-chat] PASSED
tests/test_standin.py::test_a_route_that_cannot_enforce_a_schema_says_so_before_sending PASSED
tests/test_standin.py::test_tool_call_round_trip[local-responses] PASSED
tests/test_standin.py::test_tool_call_round_trip[local-chat] PASSED
tests/test_standin.py::test_tool_call_round_trip[local-anthropic] PASSEDCounts, so you can check yours. With the stand-in up and source localstack/env.sh run in the shell, the full suite is the 306 passed and 4 skipped above (310 tests: the 4 skips are the contract ones). The 12 stand-in tests are skipped, not failed or deselected, when they cannot run, and CI without keys or servers still runs the other 294. The skip reason says why, which matters: starting Ollama is not enough, because the SDKs find the stand-in through the variables localstack/env.sh sets, so a reader who starts the server but forgets to source it also gets skips, and a bare pytest -q would print only a summary that looks like a pass. Always add -rs to see the reasons. Output with the stand-in unreachable (the check pointed at a closed port with STANDIN_OLLAMA_URL=http://127.0.0.1:9, which fails exactly as a stopped server would; the server here is shared, so this lesson does not stop it):
Output (illustrative: the counts, line numbers and timings were recalculated after the Gemini tests were removed and not re-run, so yours will differ):
....................................s................................... [ 23%]
...s.....................................ss............................. [ 46%]
........................................................................ [ 69%]
.................................................ssssssssssss........... [ 92%]
...................... [100%]
=========================== short test summary info ============================
SKIPPED [1] tests/test_contract.py:57: Google documents no refusal signal for Interactions; a `failed` status is an ERROR (test_critical_fixes.py)
SKIPPED [1] tests/test_contract.py:129: covered by the OpenRouter-specific tests
SKIPPED [2] tests/test_contract.py:147: Google sends no request-id header (lesson 03.8, Part 12)
SKIPPED [3] tests/test_standin.py:36: stand-in not reachable (Ollama http://127.0.0.1:9): start it (lesson 03.1, Part 12)
SKIPPED [3] tests/test_standin.py:44: stand-in not reachable (Ollama http://127.0.0.1:9): start it (lesson 03.1, Part 12)
SKIPPED [2] tests/test_standin.py:52: stand-in not reachable (Ollama http://127.0.0.1:9): start it (lesson 03.1, Part 12)
SKIPPED [1] tests/test_standin.py:59: stand-in not reachable (Ollama http://127.0.0.1:9): start it (lesson 03.1, Part 12)
SKIPPED [3] tests/test_standin.py:64: stand-in not reachable (Ollama http://127.0.0.1:9): start it (lesson 03.1, Part 12)
294 passed, 16 skipped in 1.16sAnd Ollama up but the shell not prepared (the commonest mistake):
Output (illustrative: the counts, line numbers and timings were recalculated after the Gemini tests were removed and not re-run, so yours will differ):
....................................s................................... [ 23%]
...s.....................................ss............................. [ 46%]
........................................................................ [ 69%]
.................................................ssssssssssss........... [ 92%]
...................... [100%]
=========================== short test summary info ============================
SKIPPED [1] tests/test_contract.py:57: Google documents no refusal signal for Interactions; a `failed` status is an ERROR (test_critical_fixes.py)
SKIPPED [1] tests/test_contract.py:129: covered by the OpenRouter-specific tests
SKIPPED [2] tests/test_contract.py:147: Google sends no request-id header (lesson 03.8, Part 12)
SKIPPED [3] tests/test_standin.py:36: Ollama is up but this shell has not run `source localstack/env.sh` (OPENAI_BASE_URL is unset)
SKIPPED [3] tests/test_standin.py:44: Ollama is up but this shell has not run `source localstack/env.sh` (OPENAI_BASE_URL is unset)
SKIPPED [2] tests/test_standin.py:52: Ollama is up but this shell has not run `source localstack/env.sh` (OPENAI_BASE_URL is unset)
SKIPPED [1] tests/test_standin.py:59: Ollama is up but this shell has not run `source localstack/env.sh` (OPENAI_BASE_URL is unset)
SKIPPED [3] tests/test_standin.py:64: Ollama is up but this shell has not run `source localstack/env.sh` (OPENAI_BASE_URL is unset)
294 passed, 16 skipped in 1.23sRead the stand-in lines carefully: -rs groups skips by test function, so five lines ([3], [3], [2], [1], [3]: 12 tests in all) carry the line number of each function in tests/test_standin.py, and the four contract skips sit above them in both runs. A reader who only ran pytest -q would see 294 passed, 16 skipped and never learn which of the two situations they were in.
11.2b A network guard under every test#
tests/conftest.py has one more fixture, applied to every test except the stand-in ones: it replaces socket.connect with a function that raises. If a mock ever fails to intercept (the respx trap above, or a typo in a base URL), the test fails loudly instead of sending a real request with a fake key or, worse, a real one. test_network_guard.py proves it works by making an un-mocked openai call and watching the guard's RuntimeError come out of the SDK. This is the same idea as the --disable-socket option of the pytest-socket plugin, in ten lines you can read.
The same file of tests also pins an easy-to-miss rule: an assistant turn with no text must not produce empty content. A tool-only turn, a reply cut off while it was still thinking, and a refusal-only turn have no text. Only Anthropic's rule is documented (text blocks must be non-empty: 03.2, 4.1); OpenAI's and Gemini's are not, so the safe move is to send exactly what the model returned, and never an empty block or string of our own. Every adapter omits empty text and drops a turn that ends up empty (test_assistant_turns_without_text_never_send_empty_content). A converter that copies "message = role + text" misses this, and the local stand-in will not tell you, because it accepts an empty Anthropic text block before a tool_use and an empty Chat content (03.5, 9.1). (03.2's chatfmt is the other design, a placeholder turn by default: 3.1.)
11.3 What the tests found#
Writing the contract suite found real bugs in the wrapper's first version, which is the point of a shared suite. The Anthropic quota fixture was wrongly a 400 (the documented billing error is a 402 billing_error), so the classifier was right and the fixture wrong. Interactions' error codes (quota_exceeded, rate_limit_exceeded) differ from generate_content's RESOURCE_EXHAUSTED, so the Gemini quota case could not be one rule. The first Anthropic adapter file was named anthropic.py and shadowed the SDK. A code reader would not have caught any of these quickly; a six-way parametrized test caught them in seconds.
An independent review then found three bugs the suite had missed, and all three were production bugs. What they have in common: every test in the first suite was a happy path or a fast error, and these only appear under a fault that real outages produce (a provider that hangs, a hook that raises, a 200 that says failed). The method for such a bug is always the same: write a failing test that injects the fault, watch it fail for the right reason, fix, watch it pass. The test file is tests/test_critical_fixes.py; its first run, against the first version's code (25 failed, 1 passed: the one that passed is the guard that observer hooks still cannot break a call):
FFFFF.FFFFFFFFFFFFFFFFFFFF [100%]
=========================== short test summary info ============================
FAILED tests/test_critical_fixes.py::test_hung_primary_falls_back_within_deadline
FAILED tests/test_critical_fixes.py::test_default_policy_leaves_room_for_the_next_model
FAILED tests/test_critical_fixes.py::test_a_failing_request_middleware_blocks_the_call
FAILED tests/test_critical_fixes.py::test_a_crashing_redactor_never_sends_the_prompt
FAILED tests/test_critical_fixes.py::test_after_middleware_that_fails_closed_returns_nothing
FAILED tests/test_critical_fixes.py::test_a_before_hook_may_raise_its_own_llm_error
FAILED tests/test_critical_fixes.py::test_failed_status_is_an_error_and_retried[openai-responses-failed-server_error]
FAILED tests/test_critical_fixes.py::test_failed_status_is_an_error_and_retried[openai-responses-failed-rate_limit_exceeded]
FAILED tests/test_critical_fixes.py::test_failed_status_is_an_error_and_retried[openai-responses-failed-vector_store_timeout]
FAILED tests/test_critical_fixes.py::test_failed_status_is_an_error_and_retried[openai-chat-failed-x]
FAILED tests/test_critical_fixes.py::test_failed_status_is_an_error_and_retried[openrouter-chat-failed-x]
FAILED tests/test_critical_fixes.py::test_failed_status_is_an_error_and_retried[gemini-interactions-failed-rate_limit_exceeded]
FAILED tests/test_critical_fixes.py::test_permanent_failed_status_raises_once[openai-responses-failed-invalid_prompt]
FAILED tests/test_critical_fixes.py::test_permanent_failed_status_raises_once[openai-responses-failed-bio_policy]
FAILED tests/test_critical_fixes.py::test_permanent_failed_status_raises_once[openai-responses-cancelled-server_error]
FAILED tests/test_critical_fixes.py::test_permanent_failed_status_raises_once[gemini-interactions-failed-None]
FAILED tests/test_critical_fixes.py::test_permanent_failed_status_raises_once[gemini-interactions-cancelled-None]
FAILED tests/test_critical_fixes.py::test_permanent_failed_status_raises_once[gemini-interactions-budget_exceeded-None]
FAILED tests/test_critical_fixes.py::test_failed_stream_before_content_is_retried[openai-responses-stream_failed]
FAILED tests/test_critical_fixes.py::test_failed_stream_before_content_is_retried[openai-responses-stream_error_event]
FAILED tests/test_critical_fixes.py::test_failed_stream_before_content_is_retried[openai-chat-stream_failed]
FAILED tests/test_critical_fixes.py::test_failed_stream_before_content_is_retried[openrouter-chat-stream_failed]
FAILED tests/test_critical_fixes.py::test_failed_stream_before_content_is_retried[gemini-interactions-stream_failed]
FAILED tests/test_critical_fixes.py::test_failed_stream_with_a_permanent_code_raises
FAILED tests/test_critical_fixes.py::test_failed_status_is_also_an_error_on_the_async_path
25 failed, 1 passed in 0.18sThe three representative failures, by name (the pytest output is real; the hook's traceback shows the exception being logged and ignored):
$ uv run pytest tests/test_critical_fixes.py::test_hung_primary_falls_back_within_deadline --tb=line -q
E provider_agnostic.errors.Timeout: Request timed out. [openai]
provider_agnostic/client.py:214: provider_agnostic.errors.Timeout: Request timed out. [openai]
=========================== short test summary info ============================
FAILED tests/test_critical_fixes.py::test_hung_primary_falls_back_within_deadline
1 failed in 0.05s
$ uv run pytest tests/test_critical_fixes.py::test_a_failing_request_middleware_blocks_the_call --tb=line -q
E Failed: DID NOT RAISE LLMError
ERROR provider_agnostic:client.py:159 hook RaisingGate.before failed
RuntimeError: user over budget
tests/test_critical_fixes.py:86: Failed: DID NOT RAISE LLMError
=========================== short test summary info ============================
FAILED tests/test_critical_fixes.py::test_a_failing_request_middleware_blocks_the_call
1 failed in 0.06s
$ uv run pytest tests/test_critical_fixes.py::test_failed_status_is_an_error_and_retried[openai-responses-failed-server_error] --tb=line -q
E AssertionError: a transient failed-in-200 must be retried
tests/test_critical_fixes.py:171: AssertionError: a transient failed-in-200 must be retried
=========================== short test summary info ============================
FAILED tests/test_critical_fixes.py::test_failed_status_is_an_error_and_retried[openai-responses-failed-server_error]
1 failed in 0.05s| The bug | The injected fault | The fix | |
|---|---|---|---|
| C1 | With the default Policy a hung provider never reached the fallback |
httpx2.ReadTimeout after a fake clock advances 30 s |
max_timeout_attempts, a deadline that satisfies the invariant (8.2) |
| C2 | A raising before() hook was ignored: budget gates and redaction failed open |
a hook that raises, a redactor with a bug | before always fail-closed, HookError, fail_closed for after (Part 9) |
| C3 | A status: failed response was returned as a success, never retried, logged ok=True |
six shapes of failed-inside-200, plain and streamed | raised in parse() and every stream parser, mapped by code (Part 6) |
After the fixes, the same file (real output):
.......................... [100%]
26 passed in 0.20sThe review also found things the suite's own assertions had hidden, which is worth knowing: the contract test for refusals accepted FinishReason.ERROR as an acceptable answer for Interactions (a failed status that is really an error), a cost test compared usage only on the happy path, and the sentence in the lesson that said Gemini has no parallel-tool switch sat next to code that dropped the setting. A test suite is only as strict as its assertions; read the loose ones.
11.4 Live smoke tests, gated by keys#
Mocks prove your code handles a documented shape. Only a hosted call proves the provider still sends it. Keep a small set of live tests (a plain call, a tool round trip, a schema call per route, a few cents in all), mark them @pytest.mark.live, skip each route when its key is missing (the hosted sample in Part 12 is exactly that, reusable as a pytest), and run them on a schedule or before a release, not on every commit (03.10 has the CI recipe and cost-safe habits). A failing live test after a green mock suite means a provider changed: update the fixture, then the code.
Part 12: The same code on the hosted providers#
Deep-dive
This is the layer-4 sample: the wrapper, unchanged, calling the four real providers (five routes: Gemini through both APIs). It needs keys in .env, skips any route whose key is missing, and prints one line per call. The code never mentions a provider-specific type:
"""s12_hosted_sample.py: the SAME wrapper code on all four hosted providers (layer 4: needs your keys in .env).
PYTHONPATH=. uv run python demos/s12_hosted_sample.py
Skips any route whose key is missing, so it is safe with a subset of keys. Prices come from prices.yaml (03.7).
"""
from dotenv import load_dotenv
from pydantic import BaseModel
from provider_agnostic import (LLMClient, LLMError, LoggingHook, Message, Registry, Request, TextDelta, ToolResultPart, ToolSpec)
from prices import PriceTable
load_dotenv() # OPENAI_API_KEY, ANTHROPIC_API_KEY, GEMINI_API_KEY, OPENROUTER_API_KEY
class Capital(BaseModel):
city: str
country: str
class GetWeather(BaseModel):
"""Get the current weather for one city."""
city: str
ROUTES = ["luna", "haiku", "flash", "flash-interactions", "or-luna"] # OpenAI, Anthropic, Gemini x2, OpenRouter
registry = Registry.load()
client = LLMClient(registry, prices=PriceTable.load(), hooks=[LoggingHook()])
missing = {r for r in ROUTES if registry.missing_credentials(r)} # names the variables, never the values
print("skipping (no key):", sorted(missing) or "none")
for route in (r for r in ROUTES if r not in missing):
try:
plain = client.complete(Request(model=route, system="Answer in one short sentence.",
messages=[Message.user("Why is the sky blue?")], reasoning_effort="off"))
usage, cost = plain.usage, plain.cost # both are None when unknown: never assume they are there
print(f"{route:19s} {plain.finish_reason.value:6s} in={usage and usage.uncached_input_tokens} out={usage and usage.output_tokens} "
f"cost=${cost and cost.usd} served_by={plain.resolved_model} id={plain.request_id}")
capital = client.complete(Request(model=route, output_schema=Capital, reasoning_effort="off", max_output_tokens=300,
messages=[Message.user("Capital of France? Give the city and the country.")]))
print(f"{'':19s} parsed -> {capital.parsed}")
tools = [ToolSpec.from_model(GetWeather)]
ask = Request(model=route, tools=tools, reasoning_effort="off", messages=[Message.user("What is the weather in Paris?")])
first = client.complete(ask)
if not first.tool_calls:
print(f"{'':19s} the model answered without calling the tool: {first.text.strip()[:60]!r}")
continue
call = first.tool_calls[0]
final = client.complete(ask.model_copy(update={"messages": [*ask.messages, first.message, Message.tool_results(
ToolResultPart(call_id=call.id, name=call.name, content='{"temp_c": 12, "sky": "cloudy"}'))]}))
print(f"{'':19s} tool {call.name}{call.arguments} -> {final.text.strip()[:70]!r}")
text = "".join(e.text for e in client.stream(Request(model=route, max_output_tokens=60, reasoning_effort="off",
messages=[Message.user("Count to five.")])) if isinstance(e, TextDelta))
print(f"{'':19s} stream -> {text.strip()!r}")
except LLMError as err: # one canonical error type for every provider
print(f"{route:19s} {type(err).__name__} (retryable={err.retryable}): {err.message[:90]} request_id={err.request_id}")skipping (no key): none
luna stop in=18 out=22 cost=$1.28e-05 served_by=gpt-6-luna id=resp_6a1f0c2e8b7d4a95
parsed -> city='Paris' country='France'
tool GetWeather{'city': 'Paris'} -> 'It is 12 C and cloudy in Paris right now.'
stream -> '1, 2, 3, 4, 5'
haiku stop in=24 out=19 cost=$1.19e-05 served_by=claude-haiku-5-5 id=msg_01Qm4VxTn2LrYb8dKc3hWePz
parsed -> city='Paris' country='France'
tool GetWeather{'city': 'Paris'} -> 'It is 12 C and cloudy in Paris right now.'
stream -> '1, 2, 3, 4, 5'
flash stop in=17 out=24 cost=$0.00010275 served_by=gemini-3.8-flash id=Zk0aadT0N8mM1MkP8bq1sQs
parsed -> city='Paris' country='France'
tool GetWeather{'city': 'Paris'} -> 'It is 12 C and cloudy in Paris right now.'
stream -> '1, 2, 3, 4, 5'
flash-interactions stop in=17 out=24 cost=$0.00010275 served_by=gemini-3.8-flash id=v1_ChdaazBhYWRUME44bU0xTWtQOGJxMXNRcxIXWmswYWFk
parsed -> city='Paris' country='France'
tool GetWeather{'city': 'Paris'} -> 'It is 12 C and cloudy in Paris right now.'
stream -> '1, 2, 3, 4, 5'
or-luna stop in=18 out=22 cost=$None served_by=openai/gpt-6-luna id=gen-1793012345-Xq0TnU8bPzV3sLkE1RaC
parsed -> city='Paris' country='France'
tool GetWeather{'city': 'Paris'} -> 'It is 12 C and cloudy in Paris right now.'
stream -> '1, 2, 3, 4, 5'How to check this sample, and how to run it against the stand-in:
| Check | Result |
|---|---|
| Compile | python -m py_compile passes with the SDK versions named in Setup |
| Type check | typecheck.sh on the sample and the whole package (and the five borrowed modules): 0 errors, 0 warnings in pyright's standard mode with the module's pyrightconfig.json, which switches off the five reportOptional* checks (what that means) |
| Run against the stand-in | Pointing the sample's base URLs at the stand-in from 03.1, Part 12 runs the OpenAI, Anthropic and OpenRouter lines (the text and tool lines are the 0.5B model's; on Anthropic the schema line is an OutputInvalid, because Ollama's Anthropic route ignores the schema: that is the wrapper reporting the stand-in's limits truthfully). The two Gemini routes are hosted-only (Ollama does not speak Gemini's API) and need GEMINI_API_KEY, so they are not run locally. Run it with OPENROUTER_BASE_URL=http://localhost:11434/v1, an absolute PYTHONPATH so the provider_agnostic package and the OpenRouter route resolve, and LOCAL_API_KEY unnecessary because the sample reads the hosted variables (the stand-in's env.sh sets dummies for them) |
Notes on the illustrative output: the cost=$None on the OpenRouter line means unknown, not free: it appears when the response carries no usage.cost; with the field present the line shows OpenRouter's own figure (5.6). The Gemini routes show their own ID shapes, and the dollar figures are what 03.7's price table gives for those token counts as of November 2026: check the table's date before trusting a number. reasoning_effort="off" keeps the sample cheap on every route, and your exact counts will differ.
Part 13: Libraries and gateways compared#
Reference
You have built the thing. Now the honest question: should you have? Every option below solves some of the same problem. All versions are the latest on PyPI as of the afternoon of 4 November 2026 (about 15:40 UTC: any-llm-sdk 1.44.0 and pydantic-ai-slim 2.66.0 were both published that same morning, and openai 3.45.0 hours earlier, so re-check before you rely on any number; on 8 November the PyPI page of litellm already showed 1.108.3, a patch release of the 1.108.0 used below, and its requires_dist still says openai<4.0.0,>=2.20.0; on 11 November the latest on PyPI was litellm 1.109.0, published that day with the same openai<4.0.0,>=2.20.0 requirement, and any-llm-sdk 1.50.0, published 10 November, with anthropic<3,>=1.2.0 and openai<4,>=2.18.0), and every code sample ran against the local stand-in (layer 2) in its own throwaway uv environment, with the exact pin shown. Check the current version and licence before you rely on any of this.
13.1 The task, and a first look at dependency conflicts#
The same four-part task everywhere: a plain call, a streamed call, a schema-validated call (Capital(city, country)), and where the library supports it, a fallback from a dead endpoint to a live one. Our own package first, as the baseline (run from the project folder; the "dead" entry points at a closed port):
"""cmp_wrapper.py: the comparison task with OUR provider_agnostic package (layer 2: local model via Ollama).
Run from the project folder: PYTHONPATH=. python ../libs/cmp_wrapper.py"""
import os
from pydantic import BaseModel
from provider_agnostic import LLMClient, Message, Policy, Registry, Request, TextDelta
os.environ.setdefault("OPENAI_API_KEY", "ollama") # Ollama ignores the key; the registry entry names the variable
class Capital(BaseModel):
city: str
country: str
REGISTRY = Registry({"version": "demo", "models": {
"local": {"provider": "local", "api": "chat", "model": "qwen2.5:0.5b", "base_url": "http://localhost:11434/v1",
"api_key_env": "OPENAI_API_KEY", "free": True, "default_max_output_tokens": 60,
"capabilities": {"structured_output": True}},
"dead": {"provider": "local", "api": "chat", "model": "qwen2.5:0.5b", "base_url": "http://localhost:9/v1",
"api_key_env": "OPENAI_API_KEY", "free": True, "capabilities": {}}},
"aliases": {"with-backup": ["dead", "local"]}})
with LLMClient(REGISTRY, policy=Policy(max_attempts=1, attempt_timeout_s=30)) as client:
r = client.complete(Request(model="local", messages=[Message.user("Say hello in three words.")]))
print("plain :", r.text.strip(), "| finish:", r.finish_reason.value, "| usage:", r.usage.uncached_input_tokens, "+", r.usage.output_tokens)
events = client.stream(Request(model="local", max_output_tokens=30, messages=[Message.user("Count to three.")]))
print("stream :", "".join(e.text for e in events if isinstance(e, TextDelta)).strip().replace("\n", " "))
r = client.complete(Request(model="local", max_output_tokens=80, output_schema=Capital,
messages=[Message.user("Name the capital of France. Give the city and the country.")]))
print("struct :", r.parsed)
print("cost :", r.cost.usd, r.cost.source)
r = client.complete(Request(model="with-backup", max_output_tokens=30, messages=[Message.user("Say hi.")]))
print("fallback:", r.text.strip(), "| attempts:", [(a.model_key, a.ok, a.error_type) for a in r.attempts])Output (local model qwen2.5:0.5b via Ollama; a hosted model's text would differ, and a 0.5B model's text differs run to run):
plain : Hello! Hello! How can I help you today? | finish: stop | usage: 35 + 12
stream : I can't count like a normal human being because I don't have the physical ability to count or use my fingers and hands for counting. However,
struct : city='Paris' country='France'
cost : 0.0 computed
fallback: Hello! How can I assist you today? | attempts: [('dead', False, 'ConnectionFailed'), ('local', True, None)]Before the code, the question that decides whether a library is even an option: can it be installed next to the SDK versions this module was checked against? uv pip compile answers without installing anything (layer 1). The script below names those versions exactly, on purpose: the answer depends on them, and it only resolves, so nothing is installed:
#!/usr/bin/env bash
# resolve.sh: can each library be installed next to the pinned SDKs? (layer 1: dependency resolution only, no install)
# uv pip compile resolves without installing. Pins: openai 3.42.1, anthropic 2.4.0, google-genai 2.34.0, tenacity 9.1.4.
PINS=$'openai==3.42.1\nanthropic==2.4.0\ngoogle-genai==2.34.0\ntenacity==9.1.4'
OUT="$(mktemp)"
try() { # try <label> <requirement lines...>
local label="$1"; shift
local f; f="$(mktemp)"; printf '%s\n%s\n' "$PINS" "$*" > "$f"
if uv pip compile --python 3.12 -q "$f" > "$OUT" 2>&1; then
echo "OK $label -> $(grep -E '^(openai|anthropic)==' "$OUT" | tr '\n' ' ')"
else
echo "CONFLICT $label -> $(grep -m1 -E 'Because|depends on' "$OUT" | sed 's/^ *[╰▶─× ]*//')"
grep -E "^ +(And |Because|and )?.*(incompatible|depends on)" "$OUT" | sed -n 2,3p
fi
rm -f "$f"
}
try "litellm==1.108.0" "litellm==1.108.0"
try "any-llm-sdk[ollama]==1.44.0" "any-llm-sdk[ollama]==1.44.0"
try "instructor==1.17.0" "instructor==1.17.0"
try "aisuite==0.2.0" "aisuite==0.2.0"
try "pydantic-ai-slim[openai,anthropic,google]==2.66.0" "pydantic-ai-slim[openai,anthropic,google]==2.66.0"OK litellm==1.108.0 -> anthropic==2.4.0 openai==3.42.1
CONFLICT any-llm-sdk[ollama]==1.44.0 -> Because any-llm-sdk>=1.44.0 depends on anthropic>=1.2.0,<2 and you
any-llm-sdk[ollama]==1.44.0 are incompatible.
CONFLICT instructor==1.17.0 -> Because instructor>=1.17.0 depends on jiter>=0.6.1,<0.15 and
openai==3.42.1 depends on jiter>=0.16.0,<1, we can conclude that
instructor>=1.17.0 and openai==3.42.1 are incompatible.
OK aisuite==0.2.0 -> anthropic==2.4.0 openai==3.42.1
OK pydantic-ai-slim[openai,anthropic,google]==2.66.0 -> anthropic==2.4.0 openai==3.42.1 Two of the five could not be installed with openai 3.42.1 and anthropic 2.4.0 at all (as of 4 to 8 November 2026; the any-llm row notes the newer release):
| Library | Why it conflicts | What it means |
|---|---|---|
| any-llm-sdk 1.44.0 | Requires anthropic>=1.2.0,<2 |
Its README says it "Leverages official provider SDKs", which means it is bound to their version ranges, and the range moved between 1.43.0 (anthropic<1,>=0.124.0) and 1.44.0 (anthropic>=1.2.0,<2) without ever reaching the 2.x this module pins (PyPI requires_dist, checked 8 November 2026; 1.45.0, published 5 November, relaxed the pin to anthropic<3, and 1.50.0, the latest on PyPI on 11 November 2026, keeps anthropic<3,>=1.2.0, so on that date the conflict with anthropic 2.x no longer applies to the newest release; re-run resolve.sh before relying on any of this). Alone it installs anthropic 1.17.0 beside openai 3.45.0 |
| instructor 1.17.0 | Requires jiter>=0.6.1,<0.15; openai 3.42.1 needs jiter>=0.16 |
The conflict 03.4 also meets: in its own environment, uv falls back to openai 3.3.0 |
This is not a defect report. It is the price of wrapping other people's SDKs: each wrapper's constraints must overlap with every other package's, forever, and the openai and anthropic SDKs both made breaking changes this year. Your own wrapper has the same dependency on the SDKs but no third-party pin in the middle. Use a separate environment (or a separate service) when a library's pins don't fit yours, and say so in the project's README.
13.2 LiteLLM#
What it is. The most widely used wrapper: litellm.completion / acompletion / responses, completion_cost, a Router with fallbacks, retries and cooldowns, and a proxy server (an OpenAI-compatible gateway with virtual keys, budgets and logging). MIT licence; 1.108.0 on 4 November 2026 (the latest on PyPI on 11 November 2026 is 1.109.0).
"""cmp_litellm.py: the comparison task in LiteLLM 1.108.0 (layer 2: local model via Ollama)."""
import litellm
from pydantic import BaseModel
litellm.drop_params = False
API_BASE = "http://localhost:11434"
MODEL = "ollama_chat/qwen2.5:0.5b" # LiteLLM's own "provider/model" naming
class Capital(BaseModel):
city: str
country: str
# 1. plain call
r = litellm.completion(model=MODEL, api_base=API_BASE, max_tokens=60,
messages=[{"role": "user", "content": "Say hello in three words."}])
print("plain :", r.choices[0].message.content.strip(), "| finish:", r.choices[0].finish_reason,
"| usage:", r.usage.prompt_tokens, "+", r.usage.completion_tokens)
# 2. streaming
chunks = litellm.completion(model=MODEL, api_base=API_BASE, max_tokens=30, stream=True,
messages=[{"role": "user", "content": "Count to three."}])
print("stream :", "".join(c.choices[0].delta.content or "" for c in chunks).strip().replace("\n", " "))
# 3. structured output
r = litellm.completion(model=MODEL, api_base=API_BASE, max_tokens=80, response_format=Capital,
messages=[{"role": "user", "content": "Name the capital of France. Give the city and the country."}])
print("struct :", Capital.model_validate_json(r.choices[0].message.content))
# 4. cost: LiteLLM keeps its own price map; a local model is unknown to it
try:
print("cost :", litellm.completion_cost(completion_response=r))
except Exception as exc: # noqa: BLE001
print("cost : raises", type(exc).__name__)
# 5. Router with an ordered fallback: the first deployment is broken on purpose
router = litellm.Router(
model_list=[{"model_name": "primary", "litellm_params": {"model": MODEL, "api_base": "http://localhost:9"}},
{"model_name": "backup", "litellm_params": {"model": MODEL, "api_base": API_BASE}}],
fallbacks=[{"primary": ["backup"]}], num_retries=0)
r = router.completion(model="primary", max_tokens=30, messages=[{"role": "user", "content": "Say hi."}])
print("fallback:", r.choices[0].message.content.strip(), "| served by deployment:", r._hidden_params.get("api_base"))
import importlib.metadata
print("version :", importlib.metadata.version("litellm"))Output (layer 2, in a throwaway environment with litellm==1.108.0 and our pins):
plain : Hello! How can I help you today? | finish: stop | usage: 35 + 10
stream : Sure! Let's count to three. 1. Counting: 0, 1, 2 - 0 -
struct : city='Paris, France' country='France'
cost : 0.0
fallback: Hello! How can I help you today? | served by deployment: http://localhost:11434
version : 1.108.0Strengths. The widest provider coverage of any option here, a single place to see cost (completion_cost knows list prices for many models), the Router with ordered fallbacks (the dead deployment above fails and the backup answers, in six lines), and the proxy for teams that want central keys and budgets across services and languages.
Weaknesses, and the honest comparison with your own wrapper. For many providers LiteLLM makes its own HTTP calls instead of using the official SDK, and for OpenAI and OpenAI-compatible providers it uses the openai SDK (its requires_dist on PyPI names openai<4.0.0,>=2.20.0, quoted at the top of this part). We checked this in LiteLLM 1.108.0's own source: its Anthropic, Vertex AI and Gemini, Bedrock and Ollama integrations import no provider SDK and go through its httpx handlers, while llms/openai/openai.py builds an openai.OpenAI client. (This is a reading of the source, not a statement from LiteLLM's documentation, so "reimplements the provider's API" would be too strong; the accurate claim is the one above.) That is how it covers so many providers, and it is also why it can lag a provider's new feature or drift from its documented behaviour on the routes that do not use an SDK: a bug there is not fixed by upgrading anthropic. Its response objects are OpenAI-shaped, so provider-specific fields (Anthropic's cache usage, Gemini's thought signatures) arrive in LiteLLM's own translation, not as the provider sent them. Its default install is the heaviest of the single-package options here (60 resolved packages vs 35 for the plain SDKs and their helpers, 13.10), and in one test, an optional feature (litellm.responses) failed on a missing mcp package until that was installed (research note, 3 November 2026).
Where each statement above comes from. The version, licence and package counts are PyPI and uv pip compile on 4 November 2026. "Its own HTTP calls for many providers, the openai SDK for OpenAI-style ones" is our reading of LiteLLM 1.108.0's source. The litellm.responses failure on a missing mcp package is an observation from our own research run (3 November 2026) and has not been re-run since. The incident facts in the next box are LiteLLM's own advisory, and the proxy advisories after it are GitHub's list, which we did not analyse.
LiteLLM's proxy has also had security advisories this year. GitHub's list of published advisories for the project shows ten for 2026 on its first page alone, ranging from low to critical severity (an authentication bypass through host-header injection, SSRF, unauthenticated file reads, a privilege-escalation chain), for example GHSA-4xpc-pv4p-pm3w (published 28 May 2026) and GHSA-w4c7-34wj-hqm8 (27 October 2026). We did not analyse them; the point is that a proxy is a server you must keep patched and must not expose to the public internet. Read the advisories page for the version you run, and prefer the proxy only when you have a platform team to operate it.
13.3 Mozilla any-llm#
What it is. any-llm-sdk (Apache-2.0, 1.44.0 as compared here; the latest on PyPI on 11 November 2026 is 1.50.0; Python 3.11 or newer), built on the official provider SDKs where they exist, with completion, acompletion, responses, embedding and list_models, models named "provider:model" (or provider= separately), and a typed exception hierarchy (AnyLLMError, AuthenticationError, ContextLengthExceededError, InsufficientFundsError, GatewayTimeoutError, ContentFilterError, ...). It also has a separate gateway project (its README, as of 8 and 11 November 2026, calls it the Otari Gateway and lists budget management, API-key management, usage analytics and multi-tenant support).
"""cmp_anyllm.py: the comparison task in Mozilla any-llm 1.44.0 (layer 2: local model via Ollama)."""
from any_llm import completion
from pydantic import BaseModel
MODEL = "ollama:qwen2.5:0.5b" # "provider:model"
API_BASE = "http://localhost:11434"
class Capital(BaseModel):
city: str
country: str
r = completion(model=MODEL, api_base=API_BASE, max_tokens=60,
messages=[{"role": "user", "content": "Say hello in three words."}])
print("plain :", r.choices[0].message.content.strip(), "| finish:", r.choices[0].finish_reason,
"| usage:", r.usage.prompt_tokens, "+", r.usage.completion_tokens)
chunks = completion(model=MODEL, api_base=API_BASE, max_tokens=30, stream=True,
messages=[{"role": "user", "content": "Count to three."}])
print("stream :", "".join(c.choices[0].delta.content or "" for c in chunks if c.choices).strip().replace("\n", " "))
r = completion(model=MODEL, api_base=API_BASE, max_tokens=80, response_format=Capital,
messages=[{"role": "user", "content": "Name the capital of France. Give the city and the country."}])
print("struct :", Capital.model_validate_json(r.choices[0].message.content))
import any_llm.exceptions as ex
print("errors :", sorted(n for n in dir(ex) if n.endswith("Error"))[:12])
try:
completion(model="ollama:qwen2.5:0.5b", api_base="http://localhost:9", messages=[{"role": "user", "content": "x"}])
except Exception as exc: # noqa: BLE001
print("down :", type(exc).__module__ + "." + type(exc).__name__)Output (layer 2, any-llm-sdk[ollama]==1.44.0 in its own environment: its anthropic<2 pin means it cannot share one with our pins):
plain : Hello! How can I help you today? | finish: stop | usage: 35 + 10
stream : Sure! Here is the count for three: 1, 2, 3
struct : city='Paris' country='France'
errors : ['AnyLLMError', 'AuthenticationError', 'BatchNotCompleteError', 'ContentFilterError', 'ContentFilterFinishReasonError', 'ContextLengthExceededError', 'GatewayTimeoutError', 'InsufficientFundsError', 'InvalidRequestError', 'LengthFinishReasonError', 'MissingApiKeyError', 'ModelNotFoundError']
down : builtins.ConnectionErrorStrengths. The philosophy matches this lesson's: use the official SDKs so behaviour tracks them, and offer one call shape. Typed errors exist out of the box, and the response is OpenAI-shaped.
Watch for. Only the providers you install an extra for are available (any-llm-sdk[ollama]), and the full [all] set resolves 134 packages. Its error mapping is not total: in our test, an unreachable server raised a plain builtins.ConnectionError, not an AnyLLMError, so except AnyLLMError would have missed it. A wrapper's value is only as good as its error coverage, which is why Part 11 tests every error on every route. Retries, fallback, cost tracking and a capability registry are not part of the call; you add them yourself. Its smaller ecosystem and younger age mean fewer answered questions online than LiteLLM.
13.4 aisuite#
What it is. Andrew Ng's small library (aisuite 0.2.0, MIT per its repository): ai.Client().chat.completions.create(model="provider:model", ...), OpenAI-shaped, with streaming for several providers and, newly, tools run from plain Python functions with max_turns and an Agents API.
"""cmp_aisuite.py: the comparison task in aisuite 0.2.0 (layer 2: local model via Ollama)."""
import aisuite as ai
client = ai.Client(provider_configs={"ollama": {"api_url": "http://localhost:11434"}})
MODEL = "ollama:qwen2.5:0.5b" # "provider:model"
r = client.chat.completions.create(model=MODEL, max_tokens=60,
messages=[{"role": "user", "content": "Say hello in three words."}])
print("plain :", r.choices[0].message.content.strip())
chunks = client.chat.completions.create(model=MODEL, max_tokens=30, stream=True,
messages=[{"role": "user", "content": "Count to three."}])
print("stream :", "".join((c.choices[0].delta.content or "") for c in chunks if c.choices).strip().replace("\n", " "))
print("usage :", getattr(r, "usage", None))
try:
client.chat.completions.create(model=MODEL, response_format={"type": "json_object"}, max_tokens=30,
messages=[{"role": "user", "content": "x"}])
print("struct : accepted a response_format")
except Exception as exc: # noqa: BLE001
print("struct :", type(exc).__name__, str(exc)[:80])Output (layer 2, in a throwaway environment with our SDK pins, which it accepts):
plain : Hello! How can I help you today?
stream : I can do that. 3: 1, 2.
usage : CompletionUsage(completion_tokens=10, prompt_tokens=35, total_tokens=45, completion_tokens_details=None, prompt_tokens_details=None)
struct : accepted a response_formatStrengths. Very small (13 resolved packages for the base install), easy to read, works next to our pins. Weaknesses. No structured-output helper (the response_format argument was accepted without complaint, but we did not verify that anything enforced it), no fallback, retries or cost tracking, and PyPI shows no licence metadata or project URLs for the package (the repository says MIT); the release cadence is unclear. Good for a quick comparison script across providers; thin for production.
13.5 Pydantic AI#
What it is. An agent framework (pydantic-ai-slim 2.66.0, MIT, Python 3.11 or newer) from the Pydantic team: Agent(model, output_type=..., instructions=..., tools=...), many providers including OpenAI, Anthropic, Google, OpenRouter, Ollama and LiteLLM, three output modes (NativeOutput, ToolOutput, PromptedOutput), validation retries, and a FallbackModel. Agents and frameworks belong to Module 08A and Module 08F; here it is judged only as a client.
"""cmp_pydanticai.py: the comparison task in Pydantic AI 2.66.0 (layer 2: local model via Ollama)."""
import asyncio
from pydantic import BaseModel
from pydantic_ai import Agent, NativeOutput
from pydantic_ai.models.fallback import FallbackModel
from pydantic_ai.models.openai import OpenAIChatModel
from pydantic_ai.providers.ollama import OllamaProvider
class Capital(BaseModel):
city: str
country: str
def local(base: str = "http://localhost:11434/v1") -> OpenAIChatModel:
return OpenAIChatModel("qwen2.5:0.5b", provider=OllamaProvider(base_url=base))
async def main() -> None:
agent = Agent(local(), model_settings={"max_tokens": 60})
r = await agent.run("Say hello in three words.")
print("plain :", r.output.strip(), "| usage:", r.usage.input_tokens, "+", r.usage.output_tokens)
async with agent.run_stream("Count to three.") as stream:
text = "".join([chunk async for chunk in stream.stream_text(delta=True)])
print("stream :", text.strip().replace("\n", " "))
structured = Agent(local(), output_type=NativeOutput(Capital), # the provider's schema-constrained mode (not a tool call)
model_settings={"max_tokens": 80})
print("struct :", (await structured.run("Name the capital of France. Give the city and the country.")).output)
# FallbackModel: the first model points at a dead port; the second is the real one
ha = Agent(FallbackModel(local("http://localhost:9/v1"), local()), model_settings={"max_tokens": 30})
r = await ha.run("Say hi.")
print("fallback:", r.output.strip(), "| model that answered:", r.response.model_name)
asyncio.run(main())Output (layer 2, pydantic-ai-slim[openai]==2.66.0 with openai==3.42.1, which installs fine):
plain : Hello! How can I help? | usage: 35 + 8
stream : Sure! Here is the sequence from 1 to 3: 1, 2, 3 Each number represents an integer: - The first number (1) represents one. - The second number (2) represents two. - The third number (3) represents three. If you want me to provide a longer count or something different using this sequence of numerals, please let me know!
struct : city='Paris' country='France'
fallback: Hello! How can I assist you today? | model that answered: qwen2.5:0.5bFallbackModel is the closest thing to our fallback chain. Per its documentation, by default it falls back on ModelAPIError (4xx and 5xx responses, and connection failures or timeouts before the response starts), context-window overflows included, but not on validation errors, which retry the same model. fallback_on lets you supply exception types, exception handlers or response handlers (for example, fall back on finish_reason in ('length', 'content_filter')), with two caveats the docs state: a single response handler replaces the default exception fallback unless you list ModelAPIError too, and response handlers don't work on streamed requests.
Strengths. Type-safe, validated structured output with the three output modes (our own wrapper has one), good observability integration, and fallback. Weaknesses for this use. It is a framework with its own concepts (agents, run contexts, dependencies); for "call a model and get a validated object", that is more than needed. Note the structured-output line: with its default tool-style output, the 0.5B stand-in model exceeded its output-retry limit; NativeOutput (the provider's schema mode) worked, which is the same lesson as 03.4, Part 10: the mode matters more than the library.
13.6 instructor#
What it is. A structured-output library, and only that (instructor 1.17.0, MIT): instructor.from_openai(client, mode=...) (also Anthropic, Gemini and others), then create(response_model=YourModel, max_retries=N); validation failures trigger a re-ask with the error. It has no fallback, no cost tracking, no streaming of plain text as a feature and no capability registry; it is a layer on top of each SDK, so it inherits their quirks.
"""cmp_instructor.py: the comparison task in instructor 1.17.0 (layer 2: local model via Ollama).
instructor does structured output ONLY: no plain-text helper, no fallback, no cost tracking."""
import instructor
import openai
from openai import OpenAI
from pydantic import BaseModel
class Capital(BaseModel):
city: str
country: str
client = instructor.from_openai(OpenAI(base_url="http://localhost:11434/v1", api_key="ollama"),
mode=instructor.Mode.JSON) # JSON mode: Ollama does not enforce strict tools
capital, completion = client.chat.completions.create_with_completion(
model="qwen2.5:0.5b", response_model=Capital, max_retries=3, max_tokens=80,
temperature=0, seed=7, # the 0.5B stand-in is erratic: pin it so the demo repeats
messages=[{"role": "user", "content": "Name the capital of France. Give the city and the country."}])
print("struct :", capital)
print("usage :", completion.usage.prompt_tokens, "+", completion.usage.completion_tokens)
print("openai :", openai.__version__, "(instructor 1.17.0 caps jiter below 0.15, so uv falls back to this openai)")Output (layer 2, instructor==1.17.0 alone, in its own environment; uv falls back to openai 3.3.0 because of the jiter conflict in 13.1):
struct : city='Paris' country='France'
usage : 152 + 17
openai : 3.3.0 (instructor 1.17.0 caps jiter below 0.15, so uv falls back to this openai)The sample sets temperature=0 and a seed: the 0.5B model, asked the same question, sometimes returns a nested object that doesn't fit the schema, and instructor's re-ask (here max_retries=3) is exactly what 03.4, Part 7 builds by hand. Use it when structured extraction is your whole job and you want a mature re-ask loop. Don't use it as your provider abstraction: it abstracts the schema, not the provider. And mind the version conflict: instructor's jiter pin currently forces an old openai, which means older features and bugs in your environment, or a separate one.
13.7 The providers' own OpenAI-compatibility layers#
The cheapest "abstraction" is to point the openai SDK at another vendor's /v1 URL. Each vendor documents what that does and doesn't give you, and none recommends it as the main route.
Gemini (https://generativelanguage.googleapis.com/v1beta/openai/) |
Anthropic (https://api.anthropic.com/v1/) |
Ollama (/v1) |
|
|---|---|---|---|
| Vendor's own status words | "Support for the OpenAI libraries is still in beta while we extend feature support", and "if you aren't already using the OpenAI libraries, we recommend that you call the Gemini API directly" | "primarily intended to test and compare model capabilities, and is not considered a long-term or production-ready solution for most use cases" | A local server's OpenAI-compatible surface |
| Works | Streaming, function calling, images (base64), audio, structured output (beta.chat.completions.parse), embeddings, batch, reasoning_effort, service_tier (priority, flex), model listing |
Chat Completions with tools, streaming, max_tokens, images (image_url), parallel_tool_calls; response_format only as json_schema with strict: true |
Chat Completions (streaming, JSON mode, tools, base64 images) and Responses |
| Does not or silently ignored | Anything not listed is ignored on image generation; file upload/download for batch needs the native client; reasoning_effort cannot combine with thinking_level/thinking_budget |
Prompt caching not supported; strict ignored on tools; reasoning_effort ignored; json_object and text formats are a 400; input_audio and file parts are a 400; n must be 1; system messages hoisted and concatenated; response has no thinking; usage detail fields always empty; most unsupported fields are silently ignored rather than rejected |
No image URLs, no tool_choice, no n, no logprobs; strict ignored; no stored responses |
| Provider-specific settings | Through extra_body: cached_content, thinking_config (and image-generation fields) |
Through extra_body, e.g. thinking: {"type": "enabled", "budget_tokens": N}; thinking: {"type": "adaptive"} is a 400 |
As the underlying model allows |
| Sources | aistudio.google.com/docs/openai | platform.claude.com OpenAI SDK compatibility | docs.ollama.com/api/openai-compatibility |
Read the Anthropic column twice: "most unsupported fields are silently ignored rather than producing errors" is the opposite of the "never silently drop" rule of 1.3. A request that asks for reasoning_effort or a cache and gets neither will not tell you. Our wrapper uses each provider's native API for the production routes and the compatible layer only where the server genuinely is a compatible server (OpenRouter, Ollama and other local servers), in the local and openrouter dialects of 4.3. The Gemini page also contains a few self-inconsistent examples at the time of writing (a nested extra_body, a typo in the batch example), which is its own small argument for the native SDK. Whether vLLM and other servers match the OpenAI surface for tools, streaming usage and errors is something to test with the contract suite, not assume.
13.8 OpenRouter as a hosted abstraction#
02.9, 5.4 introduced it. As an abstraction layer it offers one API key and one bill for hundreds of models, server-side fallbacks, and routing control, with no code of yours in the middle:
modelsfallbacks. Sendextra_body={"models": ["anthropic/claude-haiku-5.5", "openai/gpt-6-luna", "google/gemini-3.8-flash"]}: if the first fails, OpenRouter tries the next. Per its documentation, by default any error can trigger it (context-length validation errors, moderation flags, rate limits, downtime), you are billed for the model that actually answered, and the response'smodelfield says which one that was. That is broader than our policy (it would "fall back" on a content moderation flag), which is a reason to read the docs before relying on it.- Provider routing preferences. Besides the model list, OpenRouter lets a request steer which provider endpoint serves a model, through the
providerobject (OpenRouter's provider-selection guide, opened 8 November 2026):order(provider slugs to try in order),onlyandignore(allow or skip lists),sort(by price, throughput or latency),allow_fallbacks(defaulttrue: backup providers may be used when the first is unavailable),require_parameters(defaultfalse: whentrue, only providers that support every parameter of your request),data_collection(default"allow";"deny"restricts routing to providers that do not store data),zdr(zero-data-retention endpoints only) andmax_price. In this package they travel throughextra={"openrouter": {"extra_body": {"provider": {...}}}}(3.2). Two of them are safety settings rather than tuning:require_parametersis what makes a schema or tool request fail instead of being silently downgraded (5.2), anddata_collection/zdrare how an OpenRouter route honours a data policy that a plainmodelsfallback list would not (02.9, Part 9). - Three endpoints: Chat Completions (primary here), a Responses endpoint (GA but stateless only:
store: trueor aprevious_response_idreturns a 400) and an Anthropic-compatible/api/v1/messagesendpoint, which takes afallbacksparameter (at most 3 model-only entries, not combinable withmodels). Point the Anthropic SDK at it withANTHROPIC_BASE_URL=https://openrouter.ai/api(03.1, 6.6). Whether non-Anthropic models are fully supported on that endpoint is not stated on the OpenRouter pages read in November 2026 (provider selection, model fallbacks, batch), so check the Messages API reference for your model before relying on it. - The trade-offs. OpenRouter is a data processor that sees your prompts and responses (02.9, Part 9), adds a fee, has its own outages and rate limits, and its error shapes differ (402 for credits, errors inside HTTP 200: 03.8, 3.5). Provider-specific features (Anthropic breakpoints, OpenAI cache options) pass through only where OpenRouter documents them.
It composes with this lesson's package rather than replacing it: or-luna and or-haiku are registry entries, and "OpenRouter first, direct provider as the fallback" (or the reverse) is one alias.
One line on the JavaScript world: Vercel's AI SDK is the TypeScript equivalent of this whole part: one generateText / streamText API over per-provider packages. If part of your system is in TypeScript, the same build-vs-buy reasoning applies.
13.8b Gateways in front of your client, Open Responses and agent SDKs#
Part 13 compared libraries you import. Three other developments of the last year change how you choose between them, and each is a pointer more than a new mechanism, because Module 11B and Module 11C own gateways, fallbacks and routing in production.
1. A gateway can sit behind this client. Gateways beyond LiteLLM's proxy and OpenRouter exist in every category of 1.4: self-hosted open-source ones (Portkey's gateway, Helicone's AI Gateway, Kong, Envoy-based routers), hosted ones (Cloudflare AI Gateway, Vercel AI Gateway) and the clouds' own (Azure API Management, Google Apigee, Amazon Bedrock AgentCore Gateway). 11C.3, Part 9 compares them feature by feature and was verified against their official pages in November 2026; do not choose from this lesson. What belongs here is what the client has to do differently when one is in front of it:
| Concern | What to do in this package |
|---|---|
| Who retries | The gateway or the client, never both (8.1). If the gateway retries and fails over, set Policy(max_attempts=1) for those routes and keep the client's job to timeouts, error mapping and logging |
| Which API shape | Most gateways speak OpenAI Chat Completions, and some also Responses or Messages. Point the matching adapter (api: chat, responses or messages) at the gateway's base_url, as the local and openrouter entries already do |
| Model names | They are the gateway's names (an alias you configured there, or provider/model), not the provider's. Put the gateway's name in model:, and keep the gateway's own route table in version control beside models.yaml |
| Credentials | The key is the gateway's virtual or project key, not a provider key: api_key_env names its variable, and extra gateway headers go through headers_env (7.1). The provider keys then live only in the gateway |
| Capabilities | Assume false until you test: a gateway translates, and a translation can drop strict, tool_choice or reasoning controls without telling you (13.7). Add the entry to CASES and run the contract suite (Part 11) |
| Cost | The registry has no price for a gateway route, so Response.cost is None (unknown, never 0) unless you add a row to prices.yaml or the gateway reports its own cost, as OpenRouter does. Compare with the gateway's spend log, not with the provider's list price |
| Identifiers and logs | Keep your own call_id on every request and log the gateway's request ID header if it sends one; a support ticket now has two companies in it |
| Data policy | The gateway is a data processor if it is hosted, and a server you patch if it is not (13.2) |
A sketch of such an entry (a self-hosted proxy on your own network; not run and not in the test suite, so treat it as the starting point of exercise 12 in Exercises, not as a tested configuration). A provider name that DIALECTS does not know falls back to the local dialect (max_tokens, no reasoning controls), which is the conservative choice:
# provider_agnostic/models.yaml: a route through a gateway you operate (illustrative, untested)
gw-fast:
provider: gateway # unknown to DIALECTS: the conservative "local" dialect; also the key for extra={"gateway": {...}}
api: chat
model: fast # the gateway's own alias for the model it routes to
api_key_env: GATEWAY_API_KEY # the gateway's virtual key, not a provider key
base_url_env: GATEWAY_BASE_URL # e.g. an internal https URL: one deployment variable, no code change
headers_env: {X-Team-Id: GATEWAY_TEAM_ID} # only if your gateway needs extra headers: the variable NAME
capabilities: {tools: true, structured_output: false, stream_usage: true,
stop: false, parallel_tool_switch: false, strict_tools: false} # every flag is spelled out; the rest stay false until testedTwo tests in the appendix watch models.yaml itself: one requires every entry to declare stop, parallel_tool_switch and strict_tools (the sketch does), and test_every_registry_entry_has_a_price_or_is_free needs a prices.yaml row for the gateway's provider and model pair, or free: true if the gateway is a local stand-in. The first is why the sketch lists those three flags, the second is a reason to experiment outside the shipped file, as exercise 12 does by building the entry in CASES.
2. "OpenAI-compatible" is being replaced, in part, by a written specification. Open Responses is an open-source specification and ecosystem "for building multi-provider, interoperable LLM interfaces", based on OpenAI's Responses API: it standardises items (the unit of model output and tool use), semantic streaming events and tool use, and ships acceptance tests for validating an API against it. It dates from January 2026: the project's repository, openresponses/openresponses (Apache-2.0), was created on 15 January 2026, and its changelog lists dated specification releases of 15 January and 24 April 2026 (the second added a WebSocket transport for /v1/responses and a POST /v1/responses/compact endpoint). As of November 2026 it is governed by a technical charter adopted on 21 October 2026 under "Open Responses a Series of LF Projects, LLC", with a Technical Steering Committee whose initial maintainers work at OpenAI, Databricks, Amazon, Hugging Face, Ollama, OpenRouter and Ramp, and the charter names the Agentic AI Foundation (AAIF), a directed fund of The Linux Foundation, as the body the TSC chair liaises with. An AWS open-source post dated 22 October 2026 says it "has joined the Agentic AI Foundation (AAIF) as a project", names Ollama, vLLM, OpenRouter and Hugging Face as providers now serving the format, and says Amazon Bedrock has supported the Responses API since December 2025. The post adds that the specification "continues to evolve", and OpenAI's own documentation, not the specification, remains the authority for OpenAI's API. What it means for this package: the Responses adapter of 4.2 is aimed at OpenAI itself, and the local-responses stand-in entry (Part 10) already shows the same adapter talking to a different server. A server that passes the Open Responses acceptance tests is a better candidate for an api: responses entry than one that merely says "compatible", but the capability flags and the contract suite still decide, because passing a specification's tests tells you what a server implements, not how its model behaves. Verify the current version and the list of supporting servers on the project's site before you rely on either.
3. Agent SDKs bring their own model layer. If you adopt an agent framework (Module 08F), it brings a client abstraction of its own, and the question "do we still need ours?" is fair. The OpenAI Agents SDK's models page (as of November 2026; re-opened 11 November) recommends OpenAIResponsesModel, uses OpenAIChatCompletionsModel for providers that do not support Responses, accepts a custom ModelProvider per run or a model object per agent, and offers LiteLLM and any-llm adapters (openai-agents[litellm], openai-agents[any-llm]) that it describes as "best-effort, beta". LangChain's init_chat_model("openai:gpt-6-luna") and Pydantic AI's model classes (13.5) play the same role. The decision rule of 13.11 carries over: those layers normalise what an agent loop needs, not retries, deadlines, cost records, fail-closed redaction or a contract suite. Keep your own types at the application edge, and let the framework sit behind a function that takes your Request.
13.9 Dependency hygiene: the lesson for any library#
The LiteLLM incident was a package-index attack, not a LiteLLM bug, and it works on any popular dependency, including the ones in this lesson. Habits that would have contained it:
| Habit | What it does | How |
|---|---|---|
| Pin exact versions | A new release can't arrive silently | == pins in pyproject.toml or, for learning, a committed lockfile; this module's own commands leave the versions to uv.lock and name a version only for LiteLLM, for the same supply-chain reason |
| Commit the lockfile, install from it | CI and production install exactly what you tested | uv lock, then uv sync --frozen (or --locked) |
| Hash-check where possible | The file you install is the file you reviewed | uv export --format requirements-txt writes hashes; pip install --require-hashes -r requirements.txt enforces them |
| Review upgrades, don't auto-merge them | A human looks at what changed, including new transitive dependencies | A Dependabot or Renovate pull request with a diff of the lockfile; wait a few days before adopting a brand-new release |
| Know what runs at import | .pth files and setup.py run code just by installing |
Be suspicious of a package gaining a .pth file; scan site-packages after an incident |
| Keep secrets out of the build and test environments | A stealer finds nothing to steal | Don't put production keys in CI that merely runs unit tests; this lesson's tests need none (03.10) |
| Least privilege for keys | A stolen key can only do so much | Scoped, per-environment, spend-capped keys (03.1, Part 3); rotation is 03.1, 3.7 |
| Smaller dependency trees | Fewer packages, fewer chances | The own-wrapper option has no package beyond the three SDKs, pydantic and pyyaml |
None of these is specific to LiteLLM, and none of them is free. They are, however, the reason "build" can be the safer answer for a security-sensitive team: your wrapper adds no new third-party package to the trust chain. Key-leak response as a security topic is Module 12.
13.10 The comparison table#
All as of 4 November 2026. "Packages" is the count uv pip compile resolves for the stated install, from libs/count_deps.sh (layer 1); counts depend on the Python version and the extras, and include the SDKs.
own wrapper (openai, anthropic, google-genai, pydantic, pyyaml) 35
litellm==1.108.0 60
any-llm-sdk[ollama]==1.44.0 27
any-llm-sdk[all]==1.44.0 134
aisuite==0.2.0 13
aisuite[all]==0.2.0 114
pydantic-ai-slim[openai]==2.66.0 26
pydantic-ai-slim[openai,anthropic,google]==2.66.0 40
instructor==1.17.0 41| Own wrapper (this lesson) | LiteLLM 1.108.0 | any-llm 1.44.0 | aisuite 0.2.0 | Pydantic AI 2.66.0 | instructor 1.17.0 | OpenRouter | |
|---|---|---|---|---|---|---|---|
| Provider coverage | The 4 providers plus any OpenAI-compatible server | The widest | Many, one extra per provider | A dozen or so (its README lists OpenAI, Anthropic, Google, Mistral, Hugging Face, AWS, Cohere, Ollama, OpenRouter and more) | Dozens, as model classes | A schema layer over several SDKs | Hundreds of models behind one API |
| Fidelity to native features | High for what you normalize; extra and raw for the rest |
Medium: its own HTTP code for many providers, the openai SDK for OpenAI-style ones, OpenAI-shaped output |
High: official SDKs underneath, OpenAI-shaped output | Low to medium | High for the features it models | Inherits the SDK's | Passes through what it documents |
| Streaming | Canonical events, one vocabulary | OpenAI-shaped chunks | OpenAI-shaped chunks | OpenAI-shaped chunks for several providers | stream_text, events |
Partial objects | SSE, OpenAI-shaped |
| Structured output | Native mechanism per route, validated by us | response_format with a model |
response_format with a model |
No helper | Three output modes | Its whole purpose, with re-asks | Per underlying model: check require_parameters |
| Fallback | Ordered chain with a stated policy | Router with fallbacks |
Not built in | No | FallbackModel |
No | models list, server-side |
| Errors | Our hierarchy, retryable, __cause__, request IDs |
Mapped to OpenAI-style exceptions | Typed hierarchy, not total (a raw ConnectionError escaped) |
Provider exceptions | Its own ModelAPIError family |
The SDK's | OpenRouter's own shapes, errors inside HTTP 200 |
| Cost tracking | Per call, from the price table; None when unknown |
completion_cost and the proxy's spend tracking |
Not built in | No | usage() token counts |
Raw usage | usage.cost, per call |
| Dependency weight | 35 packages (the SDKs and pydantic) | 60 | 27 ([ollama]), 134 ([all]) |
13 (base), 114 ([all]) |
26 ([openai]), 40 (three providers) |
41 | None: one HTTP endpoint |
| Installs next to openai 3.42.1 and anthropic 2.4.0? | n/a | Yes (1.108.0); 1.106.6 no | No (anthropic<2) |
Yes | Yes | No (jiter<0.15) |
n/a |
| Security posture | One less package in your trust chain; maintenance is yours | March 2026 PyPI compromise (1.82.7, 1.82.8) and October 2026 compromise (1.107.0); proxy advisories in 2026 | Not audited here | Not audited here | Not audited here | Not audited here | A third party sees your prompts |
| Licence | Yours | MIT | Apache-2.0 | MIT (per repository; PyPI shows none) | MIT | MIT | A commercial service |
13.11 How to choose#
- Two to four providers, mostly text, tools and JSON, and a team that wants to understand every byte: build the thin wrapper. It is about 3,000 lines, and most of the cost was the tests (and the fault-injecting ones are the ones that found the bugs).
- A long tail of providers or models, or you need it working today: LiteLLM's SDK (pinned and lockfile-hashed) or OpenRouter. Accept the lowest common denominator and the dependency.
- Several teams, several languages, central budgets and keys: a gateway (LiteLLM proxy or an internal one) run by a platform team, with your wrapper or the SDK in front of it.
- A gateway already exists in your organisation: keep a thin client in front of it for timeouts, error mapping, cost and redaction, give it one retry owner, and test each gateway route like a new dialect (13.8b).
- Extraction is the whole job: instructor or the provider's own parse helpers; no need for a general abstraction.
- You are building agents: a framework such as Pydantic AI, and read Module 08A first.
- Whatever you pick: put a thin layer of your own types at your application's edge. Libraries change (LiteLLM's response shape, any-llm's pins and errors, instructor's modes), and a thin boundary makes a later swap a one-file change.
Part 14: The migration story#
Deep-dive
A product manager says: "Claude is cheaper for this feature now. Can we switch?" With the wrapper, the code answer is: change an alias in models.yaml. The engineering answer is that you have changed the least important part of the migration. This part is the checklist for everything the wrapper cannot do for you, and it is why Part 1 called "switching looks free" a dangerous illusion.
14.1 What the wrapper handles#
| Concern | How |
|---|---|
| Request shapes, roles, tool-result placement, media parts | Adapters (Part 4) |
| Finish reasons, usage arithmetic, cost | Normalization (5.6, 3.3) |
| Error handling and retry policy | One hierarchy and one policy (Parts 6 and 8) |
| "Will this request be rejected?" | Capability checks (7.3) |
| A known-good test of the plumbing | The contract suite (Part 11) |
14.2 What it cannot handle, and what to do#
| What changes | Why the wrapper can't hide it | What to do |
|---|---|---|
| Prompts | Models respond differently to the same words: instruction-following style, verbosity, formatting habits, how they treat system prompts, what they do with examples. Anthropic's own compatibility page warns that if you have adjusted a prompt extensively, "it's likely to be well-tuned to OpenAI specifically" | Rework and re-test prompts per model; keep a per-model prompt variant where it matters (Module 04) |
| Evaluation | A green contract suite says the plumbing works, not that the answers are good enough. The new model may be better on average and worse on the cases you care about | Run your eval set on the new model before switching, then shadow or canary it (Module 10A, Module 11C) |
| Caching strategy | Cache mechanics, minimum prefix sizes, lifetimes and economics differ per provider (03.7), and the wrapper deliberately doesn't abstract them. A prompt layout that hit OpenAI's automatic cache may not hit Anthropic's, which needs breakpoints | Redo the cache design and measure the hit rate after the switch |
| Limits | Rate limits, context windows, output caps and per-request size limits differ (03.8, Part 9). A job that fit your OpenAI tier may hit a Claude limit on day one | Check the target's limits for your volume; update context_window and max_output_tokens in the registry |
| Token counts and cost | Different tokenizers: the same text is a different number of tokens, and a "cheaper per token" model can cost more per task (02.2). Image and PDF token rules differ too (03.6, Part 3) | Re-measure cost per task with the cost hook, not per token |
| Structured output | Each provider supports a different JSON Schema subset (03.4, Part 4) | Lint your schemas against the target in CI |
| Tool behaviour | Tool-call frequency, argument quality, parallel calls and tool-choice support differ by model | Re-run your tool-use tests; check forced_tool_choice in the registry |
| Refusals and safety | What gets refused or blocked differs, and so do the signals | Check 03.8, Part 10 handling against the target's behaviour on your sensitive inputs |
| Reasoning behaviour | "High effort" is not a unit of thinking; latency and cost move with it | Re-tune reasoning_effort per model (5.5) |
| Latency | Time to first token, tokens per second and tail latency differ | Measure (03.3, Part 12); adjust timeouts (8.2) |
| Data handling and compliance | Retention, regions, zero-data-retention eligibility and the legal agreement are per provider (02.9, Part 9) | A privacy and legal review, not a config change |
| Stored state | Anything held on one provider's servers (Files API files, stored responses, explicit caches, batches) doesn't move | Re-upload or re-create (03.6, 5.8) |
| Stored conversations | Opaque reasoning in saved history can't be replayed to a different provider (5.5) | Accept the degradation, or migrate at a conversation boundary |
14.3 A migration runbook#
- Add the new model as a registry entry and run the contract suite against its adapter (mocks first, then a live smoke test). This finds plumbing problems in minutes.
- Run your eval set on the new route, and compare quality, cost per task and latency, not just quality.
- Fix what the numbers show: prompts, schemas, caching, timeouts,
max_output_tokens. - Shadow or canary: send a small share of real traffic to the new route (or run it silently beside the old one and compare). Traffic splitting and shadowing are Module 11C; at this lesson's level you can do it with two aliases and a deterministic hash of a user ID in your own code.
- Switch the alias, keep the old entry as the fallback for a while, and log
model_keyon every call (Part 9) so you can see which model served what. - Watch cost, error rate and quality for a week, and only then delete the old route.
The best protection against painful migrations is the same as the thesis of the lesson: keep your own types at the boundary, keep provider facts in one file each (a registry, a price table), and test the seams. Then migration is a project measured in days of evaluation, not months of rewriting.
Part 15: Module 03 wrap-up#
15.1 What you now own#
| Lesson | Core skill | The code you now own |
|---|---|---|
| 03.1 First API calls | An LLM call is an HTTP request; clients, keys, versions, the free local stand-in | A project that runs all four providers, the wire-capture and raw-HTTP samples, check_setup |
| 03.2 Messages and conversations | Roles, content parts, history, server-side state | chatfmt.py (the converter), convo_store.py (a conversation store); here: canonical Message and parts |
| 03.3 Streaming | SSE, every provider's events, accumulators, errors in streams, browsers | accumulate.py, sse.py, a FastAPI streaming endpoint; here: StreamParser and Builder |
| 03.4 Structured output | Schemas, helpers, validation, retries | Pydantic schemas, the schema linter, validate-and-retry; here: schemas.py and output_schema |
| 03.5 Tool calling | One round trip per provider, IDs, parallel calls | weather_tools.py (run_tool); here: ToolSpec, ToolCallPart, ToolResultPart |
| 03.6 Images, PDFs and files | Media parts, limits, costs, Files APIs, preprocessing | The preprocessing toolkit and media preflight; here: ImagePart, DocumentPart and capability checks |
| 03.7 Cost and caching | Counting, exact cost, a price table, every caching API | cost_calc.py, prices.yaml, cost_tracker.py; here: provider_agnostic/cost.py and JsonlCostHook |
| 03.8 Errors and retries | Taxonomy, retries, timeouts, backoff, rate limits, HTTP-200 failures | llm_errors.classify(), check_response(), rate_limiter.py, production_call.py; here: the hierarchy and Policy |
| 03.9 Async and batch | Concurrency, rate-aware throughput, Batch APIs | bounded.py (run_bounded), the batch runners and pollers |
| 03.10 Logging, debugging and testing | Seeing the wire, structured logs, mock transports, CI without keys | Test fixtures and logging patterns; here: the fakes and the contract suite |
| 03.11 The provider-agnostic client | Designing the boundary | The provider_agnostic/ package, models.yaml, the contract suite |
15.2 Putting async and batch beside the client#
Lesson 03.9 owns concurrency, and the client already has acomplete() and astream() over the same adapters. The pieces fit directly: pass a closure over client.acomplete(...) to 03.9's run_bounded for a bounded fan-out, and give each provider its own concurrency budget (03.9, 4.7), because the registry tells you which provider every alias lands on. Batch APIs are deliberately not behind the canonical Request: their lifecycle (files, polling, partial results, expiry) differs too much between OpenAI, Anthropic, Gemini and OpenRouter to hide behind one method, and 03.9's runners already share the same reconcile-by-ID idea. If you do build a batch layer, reuse build() to render each canonical request into the provider's batch line, since that is exactly the pure translation the adapters isolate.
15.3 What's next#
Module 04: Prompt & Context Engineering turns from how to call to what to send: system-prompt design, few-shot examples, delimiters and structure, context selection and ordering, templates and versioning. Everything in Module 03 is plumbing that makes those prompts reliable in production: structured output so replies can be parsed, tool calls for actions, streaming for UX, cost tracking so prompts are measured, and a wrapper so a better prompt on a different model is an alias change. After that, Module 05 and Module 06 prepare data and retrieval for RAG, and Module 08A builds the tool loop that this module stops short of.
15.4 The projects#
The Module 03 projects (projects) build on this package (with the OpenAI and Anthropic adapters required and the others optional): the multi-provider streaming chat CLI is LLMClient.stream() plus a conversation store and an alias switch; the structured extractor is output_schema plus validate-and-retry; the provider benchmark runs one task set through several aliases and compares cost, latency and (with simple checks) quality, using the JsonlCostHook records. An optional stretch project, a streaming gateway service, puts astream() behind the FastAPI endpoint from 03.3, Part 11. Start each from the appendix listing below, copy the package, and add only what the project needs.
Common misconceptions#
| Misconception | Reality |
|---|---|
| "A provider-agnostic client means I can switch providers by editing config." | It means the code doesn't change. Prompts, evals, caching, limits, costs and compliance all do (Part 14) |
| "Normalizing finish reasons is safe, so I can drop the raw value." | Normalizing loses information (STOP hides Gemini's stop-sequence-versus-natural-end, an OpenAI refusal arrives as completed). Keep raw_finish_reason beside the enum (3.3) |
| "A wrapper should accept every option every provider has." | A wrapper that tried would be the lowest common denominator or a mess. Normalize the 80%; keep extra and raw for the rest (1.3) |
| "If a provider doesn't support an option, the wrapper should quietly skip it." | Never silently drop an option. Raise before sending (7.3); a quiet drop turns a loud bug into a quality problem |
| "Retry in the wrapper and leave the SDK's retries on, for safety." | Retries multiply: three attempts became nine requests in 8.1. Exactly one layer owns retries |
| "A fallback to a second model is free resilience." | It is an untested model unless you evaluate it, it can't replay opaque reasoning, and a refusal is not a failure to route around (8.4, 5.5) |
| "Any 429 should be retried." | A 429 can mean "out of money" (03.8, 4.2); the wrapper classifies it as QuotaExceeded and goes straight to the next provider |
| "OpenAI-compatible means the same behaviour." | It means the same URL and JSON envelope. Tool choice, streaming usage, structured output and errors differ, and the vendors call their own layers beta or not production-ready (13.7) |
| "If a hook raises, the client should log it and carry on: a hook must never break the call." | True for observers (logging, metrics, cost). False for middleware: a budget gate or redactor that raises must stop the call, or it fails open and sends the unredacted prompt (Part 9) |
| "An HTTP 200 is a success." | Not when the body says failed: OpenAI Responses, Interactions and OpenRouter can answer 200 with an error. Raise it, and retry it when the code is transient (Part 6) |
| "Three attempts of 30 s inside a 90 s deadline is a sane default." | It is exactly the deadline: a provider that hangs uses all of it and the fallback is never tried. Timeouts need their own, smaller budget (8.2) |
"My wrapper can wrap the exception in a generic Exception to keep callers simple." |
Keep the original as __cause__, and keep the provider's request ID, or support tickets become impossible (Part 6) |
| "Mock tests prove it works against the provider." | They prove it handles the documented shapes. Only a live smoke test proves the provider still sends them (11.4) |
| "A well-known library is automatically safe to depend on." | LiteLLM, a widely used one, shipped a credential stealer to PyPI for a short window in March 2026. Pin, lock with hashes, and review upgrades (13.9) |
| "A gateway makes a client unnecessary." | A gateway centralises keys, budgets and routing, but your code still needs timeouts, error mapping, redaction, cost records and one retry owner, and a gateway's translation can drop options like any compatibility layer (13.8b) |
| "The registry's prices and capabilities are facts." | They are facts as of a date. Prices live in one dated table, capabilities in a versioned file, and an audit compares them with the Models APIs (7.4) |
Key takeaways#
- Abstract the 80%, keep an escape hatch for the 20%. Text, tools, JSON, images and PDFs in; text, tool calls, objects, usage, finish reasons and errors out. Provider-specific features go through
extraandraw. - Decide build, buy or gateway with the table in 1.4. Your own wrapper for 2 to 4 providers and full control; a library for breadth; a gateway for convenience or central control; "OpenAI-compatible" for evaluation and local servers.
- Canonical types are Pydantic models with typed parts, a
nativetwin on each part, andNonemeaning unknown. The native twin is how opaque reasoning round-trips on one provider and never leaks to another. - An adapter is pure translation plus thin I/O.
build(),parse()and a stream parser are testable with no network and printable as a wire capture. - Treat each "compatible" server as its own dialect. Differences live in one table, not in scattered
ifstatements. - Normalize the hard parts once: one stream vocabulary (commit on the first content event), a native structured-output mechanism validated by you, call IDs threaded in both directions, reasoning effort per model, usage arithmetic checked against 03.7.
- One hierarchy of errors, each with
retryable, every one raisedfromthe SDK's exception and carrying the provider's request ID. - A registry maps aliases to ordered chains, records capabilities, and refuses before sending. Model choice becomes configuration, and an audit keeps it honest.
- Reliability belongs in one place: SDK retries off, one policy, a per-attempt timeout and a deadline that leaves room for the next model after the primary has hung, a fallback that skips refusals, bad requests and auth errors by default, and an HTTP 200 that says
failedtreated as the error it is. - Hooks fail in opposite directions: observers are contained (and log only the exception type), middleware (
before, andafterwhen opted in) is fail-closed, and every paid-for path (invalid reply, abandoned stream, discarded fallback, broken stream) leaves a record. - Every adapter passes the same contract suite. A new adapter is done when it is in
CASESand the file stays green; mocks for documented shapes, the stand-in for plumbing, a gated live test for the truth. - A fallback loses opaque reasoning and an evaluation, and a migration changes prompts, evals, caching and limits. The wrapper hides the call, not the models.
- A gateway, Open Responses or an agent SDK changes where the abstraction lives, not what you must test. Behind a gateway the client keeps timeouts, error mapping, cost and redaction, and exactly one layer retries; Module 11C owns gateways in production (13.8b).
- Every dependency is a trust decision. Pin, lock with hashes, review upgrades and keep secrets out of builds: the lesson of March 2026 applies to every library in this part, and to the SDKs.
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Provider-agnostic client | A layer that lets application code call several LLM providers through one request and response type |
| Thin wrapper | The design rule: normalize what you use everywhere, keep an escape hatch to provider features, never silently drop an option |
| Leaky abstraction | An abstraction whose hidden differences show through anyway (a "same" parameter that behaves differently) |
| Canonical types | Your own provider-neutral data types (Message, Part, Request, Response, Usage, ...) at the edge of your application |
| Provider adapter | The code that translates canonical types to one provider API and back; here, pure build() / parse() plus thin I/O |
Native part (native twin) |
A part's provider-specific serialization, kept so reasoning items, signatures and call items can be replayed unchanged to the same API |
| Normalized finish reason | One enum that every provider's stop reason maps to, kept beside the provider's raw value |
| Dialect | One OpenAI-compatible server's set of differences (output-cap parameter, reasoning control, usage and cost fields) behind the shared Chat Completions adapter |
| Escape hatch | A way to pass provider-specific fields (Request.extra, keyed by provider) or reach the raw SDK object (Response.raw) |
| Capability registry | A YAML file that maps model aliases to ordered chains and records what each route supports, plus limits |
| Application-level model alias | A role name such as fast or smart that your code uses instead of a provider model ID |
| Fallback chain | An ordered list of models tried in turn when the current one fails with a listed error |
| Contract test suite | One test suite run against every adapter, so they must all behave the same |
| Fail-closed hook | A hook whose failure stops the call instead of being ignored: every before hook, and an after hook with fail_closed = True; the opposite of an observer, which is contained |
| Fault injection | Testing by making a dependency misbehave on purpose (a hung server, a raising hook, a 200 that says failed) with a scripted server and a fake clock |
| Request middleware / response middleware | Hooks that may change the request before it is sent, or the response before it is returned |
| LLM gateway | A proxy or hosted service between your applications and the providers that handles routing, keys, budgets, logging and often retries; Module 11C compares them |
| Open Responses | An open specification, based on OpenAI's Responses API, for multi-provider LLM interfaces: items, streaming events, tool use and acceptance tests |
| Provider routing preferences | OpenRouter's provider request object (order, only, ignore, sort, allow_fallbacks, require_parameters, data_collection, zdr, max_price) that steers which endpoint serves a model |
| Supply-chain attack | Compromising a dependency (for example a package-index release) rather than your own code, as in LiteLLM's March and October 2026 incidents |
| Lockfile with hashes | A file pinning every package to exact versions and checksums, so what you install is what you reviewed |
Exercises#
All of these run against the code in the appendix and need no key.
- Read the wire. Run
demos/s4_wire_capture.py. For each of the six routes, find where the system prompt, the output cap, the tool definition and the "reasoning off" setting went. Then addtool_choice=ForcedTool(name="get_weather")and note the four different spellings. - Extend the contract. Add
assert u.tier == "standard"totest_plain_text_and_usage. Which adapters pass without changes, and where does the tier come from on each provider (service_tieron OpenAI,usage.service_tieron Anthropic, thex-gemini-service-tierheader on Gemini)? - Break the contract on purpose. In
OpenAIResponsesAdapter._finish, mapincompletetoSTOP. Which contract tests fail, and which message tells you why? Then restore it. - A new dialect. Add
vllmtoDIALECTSinopenai_chat.py(copylocal), add a registry entry pointing athttp://localhost:8000/v1, and add it toCASESwith the Chat fake. What does the contract suite say? - Fallback policy. Add a test where the primary returns
Refused-style content andfallback_on_finish={FinishReason.REFUSAL}is set; assert both attempts are logged. Then write the argument, in two sentences, for not turning this on in a customer-support bot. - Break a fix on purpose. In
_is_content, go back to counting everyReasoningDeltaas content. Which test fails, and what does its message say? Do the same withPolicy.max_timeout_attempts = 3anddeadline_s = 90: which test catches it? - A circuit breaker (preview). Write a hook-shaped class that counts consecutive failures per
model_key, and havebefore()reorder the alias chain when the primary has failed five times in a row. Why is this harder than it looks, and why is it Module 11C's topic? - Registry audit. Add a fixture to
test_refresh.pyfor a model that retires in 20 days and one in 90. Confirm severities. Then point the audit at the OpenRouter catalogue (no key needed) and comparecontext_windowfor one model. - Same task, other library. Install LiteLLM 1.108.0 in a throwaway environment (
uv run --with litellm==1.108.0 ...: keep this one pinned, for the supply-chain reason in 03.1) and reproduce 13.2 with a hosted model if you have a key, or the stand-in if not. Note one behaviour that differs from the wrapper (an error type, a field, a default). - Stand-in tests. Start the stand-in, run
pytest -m standin -v -rswith and withoutsource localstack/env.sh, then stop Ollama and run it again. Which tests skip, with what reason each time, and why is "skip" the right outcome for CI without servers? - Dependency hygiene. In a new
uvproject, add the three SDKs, runuv lock, thenuv export --format requirements-txtand find the hashes in the output. Write the one-line CI command that installs from it with hash checking enforced. - A gateway entry. Read the
gw-fastsketch in 13.8b, then add a case toCASESintests/conftest.pythat mirrors its flags:"gateway-chat": (FakeChat(), spec_dict("gateway", "chat", "fast", FakeChat.base_url, structured_output=False, forced_tool_choice=False, images=False, image_urls=False, documents=False, reasoning=False, stop=False, parallel_tool_switch=False, strict_tools=False)). The contract tests talk to the Chat fake, so no gateway or key is involved (spec_dictsuppliesTEST_KEY). Run the suite and list which tests fail or are refused. Hint: start from exercise 4; the failures are your capability flags, not bugs. Then decide which of the eight rows of the 13.8b table your own deployment would have to change, and whatclient.preflight("gw-fast")would report if the sketch were loaded from YAML withGATEWAY_TEAM_IDunset (missing_credentialscounts the variables named inheaders_env).
Check yourself#
- Name three reasons to build a provider-agnostic layer and three reasons not to.
For: resilience (fallback across providers), cost routing, testing (one fake, one contract suite), vendor leverage, one place for logging, cost and retries. Against: lowest-common-denominator features, leaky abstractions, day-one provider features, maintenance burden, the debugging tax, and the false belief that switching is free (Part 1).
- What are the four rules of the thin-wrapper principle?
Normalize the 80% you use everywhere; keep an explicit escape hatch (
extra,raw); never silently drop an unsupported option (raise); never hide the provider's own facts (raw finish reason, request ID, original exception) (1.3). - Why does each canonical
Partcarry anativefield, and when is it replayed or dropped?Some provider output (OpenAI reasoning and call items, Claude thinking blocks with signatures, Gemini thought signatures, OpenRouter
reasoning_details) must go back exactly as received. Thenativetwin stores it, tagged with provider and API; an adapter replays it only when both tags match its own, and drops it otherwise (3.1). - Why is a tool call's
argumentsalways adictin the canonical types, and what happens when the model sent invalid JSON? - Why does
Responsekeepraw_finish_reasonnext to the normalizedfinish_reason?Normalizing loses information (Gemini's
STOPcovers a stop sequence and a natural end; an OpenAI refusal arrives ascompleted). The raw value is the first thing to read when a result surprises you (3.3). - Why must
Response.usageandCost.usdbe able to beNone, and why is "zero" wrong?A broken stream has no usage, and an unpriced model or a missing
usage.costhas no cost. Recording0would make dashboards silently wrong, so unknown isNone(5.6). - Why are the SDK clients built with
max_retries=0? What did the retry-multiplication demo show?So the wrapper is the only retry layer. With the SDK's default two retries beneath a three-attempt loop, one outage produced nine provider requests while the log showed three (8.1).
- Which errors does the default fallback policy not fall back on, and why each?
AuthFailed/PermissionDenied(a configuration bug you must see),ResponseFailedandHookError(permanent: the same request would fail again),BadRequest(a bug on every provider),ContextTooLong(a cascade decision, Module 11B),UnsupportedFeature(nothing was sent), and by default refusals and content filters (a refusal may be the correct answer) (8.4). - A stream fails after 40 words have reached the user. What does
stream()do, and what does the exception carry?It raises the error (no retry, no fallback), because restarting elsewhere would splice two answers together. The exception carries
partial, aResponsebuilt from what arrived, plus the attempts and the provider's request ID (5.1). - Why does the client check capabilities for the whole alias chain before sending the first request?
So a fallback that cannot honour the request fails at the first call, not during an outage when you most need it (7.3).
- Why is Gemini
generate_contentthe wrapper's default Gemini adapter although Google recommends Interactions for new projects?Its SDK retries can be switched off, so the wrapper owns retries; batch and explicit caches live there; and the stand-in cannot run it (hosted-only), so the mock servers test it. Interactions retries by itself and can't be told not to, and has private error classes. Interactions is available as a registry entry for teams that prefer Google's recommended interface (4.5).
- Why is an "OpenAI-compatible" endpoint not a free pass? Give two concrete differences.
It guarantees the URL and JSON envelope, not behaviour. For example: Ollama ignores
strictandtool_choice; Anthropic's layer ignoresreasoning_effortand prompt caching and 400s onjson_object; Gemini's is documented as beta; OpenRouter may answer HTTP 200 with an error body (13.7). - What did the March 2026 LiteLLM incident involve, which versions, and what three habits would have contained it?
On 24 March 2026, versions 1.82.7 and 1.82.8 of
litellmon PyPI carried a credential stealer (1.82.8 also added a.pthfile that runs on every Python start). Pinned exact versions, a lockfile installed with hashes, and reviewing upgrades (plus keeping secrets out of build environments) would have contained it (13.2, 13.9). - What does a contract test suite give you that per-adapter tests don't, and what can it not prove?
- After switching the
fastalias to another provider, name four things that still need work.Prompts, evals, caching strategy, limits, cost per task (tokenizers), structured-output schemas, tool behaviour, refusal handling, latency and timeouts, and data-handling or compliance (14.2).
- A budget-gate hook raises an exception. What happens to the call, and what would have happened in the first version? Why is the answer different for a metrics hook?
The call is stopped and the caller gets the hook's own
LLMError(a gate that raisesQuotaExceeded) or aHookErrorwith the hook's exception as__cause__; nothing is sent and theerrorhooks fire. The first version logged the exception and sent the call anyway, so redaction and budgets were fail-open. A metrics hook is an observer: stopping a user's request because a collector is down would be the wrong trade, so its exceptions are contained and only their type is logged (Part 9). - A provider answers HTTP 200 with
status: "failed"anderror.code: "server_error". What does the client do, and what if the code isinvalid_prompt?server_erroris transient, so the response becomes a retryableServerError, is retried and may fall back; the attempt is loggedok=False.invalid_promptis permanent, so it raises a non-retryableBadRequestonce (Part 6). - Your company runs a gateway that retries and fails over on its own. What do you change in the client's
Policyand the registry, and what doesResponse.costshow for the gateway route?Give the route
Policy(max_attempts=1)so exactly one layer retries (8.1); keep the gateway's own model alias inmodel:, its virtual key inapi_key_envand any extra header inheaders_env, with every capabilityfalseuntil the contract suite shows it works.Response.costisNone(unknown, never0) because the registry has no price for the route, unless you add aprices.yamlrow or the gateway reports its own cost (13.8b).
Further resources#
Provider documentation (verified as of November 2026)
- Gemini API: OpenAI compatibility (beta; the supported-features list and
extra_bodysettings) - Claude API: OpenAI SDK compatibility (the limitations tables)
- Ollama: OpenAI compatibility and Anthropic compatibility
- OpenRouter: model fallbacks, provider selection and its API reference overview
- Open Responses (the specification, its charter and the acceptance tests) and the AWS open-source post on its move to the Agentic AI Foundation (22 October 2026)
- OpenAI Agents SDK: models (model providers and the LiteLLM and any-llm adapters)
Libraries and their security notes
- LiteLLM: documentation, the March 2026 security update and the GitHub security advisories
- any-llm (Mozilla AI), aisuite, Pydantic AI (see its model overview for
FallbackModel), instructor
Design and engineering
- uv documentation: locking, syncing and exporting (lockfiles and hashes)
- pip: hash-checking mode
- Joel Spolsky, "The Law of Leaky Abstractions" (2002): the classic short essay behind 1.2
- Earlier in this module: 03.8 (the error and retry mechanics this client centralizes), 03.10 (testing techniques), and Module 11B and Module 11C (circuit breakers, routing and gateways in production; the gateway comparison is 11C.3, Part 9)
Appendix: the package listing#
This is the whole project, in the order you would create it. Everything runs as shown (the tests in Part 11 are these exact files). Layout:
agnostic-client/
cost_calc.py prices.py prices.yaml # from lesson 03.7
llm_errors.py retry_after.py check_response.py # from lesson 03.8
weather_tools.py # from lesson 03.5 (used by the stand-in tests and demos)
pytest.ini pyproject.toml
localstack/ # the stand-in helper: env.sh
demos/ # the s3-s12 demo scripts shown inline (save each block as demos/<name>.py)
provider_agnostic/
__init__.py py.typed types.py errors.py registry.py schemas.py cost.py redact.py hooks.py client.py refresh.py
models.yaml models.local.yaml
adapters/
__init__.py base.py openai_responses.py openai_chat.py anthropic_messages.py
gemini_generate.py gemini_interactions.py
tests/
__init__.py conftest.py fakes.py test_contract.py test_types_registry.py test_request_contract.py test_wire.py
test_critical_fixes.py test_billing_and_ids.py test_hooks.py test_stream_rules.py
test_fallback_hooks.py test_parity_schemas.py test_refresh.py test_network_guard.py test_standin.pyThree files in that layout are empty and have no listing: provider_agnostic/py.typed, provider_agnostic/adapters/__init__.py and tests/__init__.py (create them with touch; the tests import tests.conftest and tests.fakes, so tests/__init__.py has to exist). provider_agnostic/__init__.py is listed below.
Run it: uv run pytest -rs (the stand-in tests skip, with a stated reason, when the servers are down or env.sh has not been sourced), uv run python -m provider_agnostic.refresh (needs keys for the hosted providers), PYTHONPATH=. uv run python demos/s12_hosted_sample.py (keys; the PYTHONPATH=. also lets the demo import prices, which sits in the project root).
Packaging it#
Until now the package was importable only because pytest.ini says pythonpath = . and you ran from the project root. To use it from the module's projects (or any other folder), make it an installable package. The uv init --bare project has no build backend, so add one in pyproject.toml:
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "agnostic-client" # the DISTRIBUTION name (uv add, pip). The IMPORT name is provider_agnostic, never `llm`
version = "0.1.0"
description = "A thin provider-agnostic LLM client (lesson 03.11)"
requires-python = ">=3.11"
dependencies = [
"openai", "anthropic", "google-genai", # the provider SDKs: upgrade them on purpose, with the suite
"pydantic>=2.14", "pyyaml>=6", "python-dotenv>=1",
]
[dependency-groups]
dev = ["pytest>=9", "pytest-asyncio>=1.4"]
[tool.hatch.build.targets.wheel]
# the package, plus the five modules and a data file it borrows from lessons 03.7 and 03.8
only-include = ["provider_agnostic", "cost_calc.py", "prices.py", "prices.yaml", "llm_errors.py", "retry_after.py", "check_response.py"]Three things to notice. The distribution name (agnostic-client, what uv add and pip call it) and the import name (provider_agnostic) are different on purpose, and neither is llm, which is Simon Willison's package (see the note in Setup). The five single-file modules borrowed from lessons 03.7 and 03.8 are listed in only-include, so they ship as top-level modules next to the package: their names are short (prices, cost_calc) and could collide with another package in a shared environment, so treat this as the lesson-sized way to do it and move them inside the package (and change the imports) for anything you publish. And py.typed marks the package as typed, so a project that depends on it gets its annotations checked.
uv build # dist/agnostic_client-0.1.0-py3-none-any.whl and an sdist
uv pip install dist/*.whl # into any environment; then, from ANY folder:
python -c "import provider_agnostic as p; print(p.__file__)"
uv add --editable ../agnostic-client # or, from a project that builds on itWe built the wheel, installed it into a clean virtual environment and imported it from an unrelated folder (it contained the package, py.typed, both YAML files and the six borrowed files, and Registry.load() and PriceTable.load() found their data files). Registry.load() finds models.yaml next to registry.py, and PriceTable.load() finds prices.yaml next to prices.py, so both survive installation; pass an explicit path to use your own copies.
What "0 errors" means#
The type checks in this lesson run pyright in standard mode with the module's pyrightconfig.json, which switches off the five reportOptional* checks (so plain.usage.uncached_input_tokens type-checks even though usage can be None; the hosted sample guards it anyway). They report 0 errors and 0 warnings on the package and the borrowed modules. (The pyrightconfig.json and the typecheck.sh wrapper are the author's tooling and are not part of the package listing; to repeat the check, uv add --dev pyright, then uv run pyright with reportOptionalMemberAccess, reportOptionalSubscript, reportOptionalIterable, reportOptionalCall and reportOptionalOperand set to "none" in a pyrightconfig.json, which are the five checks meant.) Be clear about what that does not cover. Every adapter boundary is Any by design (parse(raw: Any), feed(event: Any)), because the SDKs' response and event types are large unions and three different libraries' worth of them: pyright cannot tell you that an SDK renamed a field. The wire tests and the contract suite are the only guard against SDK shape drift, which is one more reason to run them on every upgrade. In pyright's strict mode the same package reports about 250 findings, nearly all Unknown types flowing out of those Any boundaries; that is the honest size of the untyped seam.
pytest.ini#
[pytest]
asyncio_mode = auto
asyncio_default_fixture_loop_scope = function
testpaths = tests
markers =
standin: runs against the local stand-in (Ollama); skipped unless it is reachable
live: calls a hosted provider; skipped unless the provider's key is set
pythonpath = .provider_agnostic/__init__.py#
"""provider_agnostic: a thin provider-agnostic client (lesson 03.11). Import from here, not from the submodules."""
from .client import LLMClient, Policy
from .errors import (AuthFailed, BadRequest, ConfigError, ConnectionFailed, ContentBlocked, ContextTooLong, HookError,
LLMError, OutputInvalid, Overloaded, PermissionDenied, QuotaExceeded, RateLimited, Refused,
ResponseFailed, ServerError, Timeout, Truncated, UnsupportedFeature, raise_for_finish)
from .hooks import CallContext, Hook, JsonlCostHook, LoggingHook, MetricsHook, OTelHook, RedactHook
from .redact import hash_user
from .registry import Registry
from .types import (Done, DocumentPart, FinishReason, ForcedTool, ImagePart, Message, Native, ReasoningDelta, ReasoningPart,
Request, Response, TextDelta, TextPart, ToolCallDelta, ToolCallPart, ToolCallStart,
ToolResultPart, ToolSpec, Usage, UsageEvent)
__all__ = [
"LLMClient",
"Policy",
"AuthFailed",
"BadRequest",
"ConfigError",
"ConnectionFailed",
"ContentBlocked",
"ContextTooLong",
"HookError",
"LLMError",
"OutputInvalid",
"Overloaded",
"PermissionDenied",
"QuotaExceeded",
"RateLimited",
"Refused",
"ResponseFailed",
"ServerError",
"Timeout",
"Truncated",
"UnsupportedFeature",
"raise_for_finish",
"CallContext",
"Hook",
"JsonlCostHook",
"LoggingHook",
"MetricsHook",
"OTelHook",
"RedactHook",
"hash_user",
"Registry",
"Done",
"DocumentPart",
"FinishReason",
"ForcedTool",
"ImagePart",
"Message",
"Native",
"ReasoningDelta",
"ReasoningPart",
"Request",
"Response",
"TextDelta",
"TextPart",
"ToolCallDelta",
"ToolCallPart",
"ToolCallStart",
"ToolResultPart",
"ToolSpec",
"Usage",
"UsageEvent",
]provider_agnostic/types.py#
"""provider_agnostic/types.py: the canonical types. Everything else in the package speaks these, and only these.
Design rules (each is explained in lesson 03.11, Part 3):
* Messages hold a LIST of typed parts, because every provider's native format does.
* Every part can carry its provider-native twin (`native`), so reasoning items, thought
signatures and call IDs round-trip untouched when the next request goes to the SAME API.
* Normalizing loses information, so the raw provider value always travels beside the
normalized one (`raw_finish_reason`, `Response.raw`).
* Nothing here imports a provider SDK.
"""
from __future__ import annotations
import enum
import json
import re
from typing import Annotated, Any, Literal
from pydantic import BaseModel, ConfigDict, Field, field_validator
# --------------------------------------------------------------------------- parts
class Native(BaseModel):
"""A provider's own serialization of a part, kept so it can be replayed verbatim."""
provider: str # "openai" | "anthropic" | "gemini" | "openrouter" | "local" ...
api: str # "responses" | "chat" | "messages" | "generate_content" | "interactions"
payload: dict[str, Any]
class _Part(BaseModel):
native: Native | None = None # replayed only when provider AND api match the adapter
class TextPart(_Part):
type: Literal["text"] = "text"
text: str
class ImagePart(_Part):
type: Literal["image"] = "image"
media_type: str # "image/png"
data_b64: str | None = None # inline bytes, base64
url: str | None = None # https URL (not every provider fetches URLs: see capabilities)
detail: Literal["auto", "low", "high"] = "auto" # OpenAI-style hint; others ignore it
class DocumentPart(_Part):
type: Literal["document"] = "document"
media_type: str = "application/pdf"
data_b64: str
filename: str = "document.pdf"
class ToolCallPart(_Part):
type: Literal["tool_call"] = "tool_call"
id: str # the ID the result must echo: opaque, never parsed
name: str
arguments: dict[str, Any] # always a parsed dict: OpenAI's JSON string is parsed once, here
arguments_error: str | None = None # set when the model sent invalid JSON (the raw text is in native)
class ToolResultPart(_Part):
type: Literal["tool_result"] = "tool_result"
call_id: str # == ToolCallPart.id
name: str # Gemini matches results by name as well
content: str
is_error: bool = False
class ReasoningPart(_Part):
"""Opaque reasoning that must round-trip. `text` is a human-readable summary, if the
provider gave one. It is NOT enough to replay: `native` is."""
type: Literal["reasoning"] = "reasoning"
text: str | None = None
Part = Annotated[TextPart | ImagePart | DocumentPart | ToolCallPart | ToolResultPart | ReasoningPart,
Field(discriminator="type")]
class Message(BaseModel):
role: Literal["user", "assistant", "tool"]
parts: list[Part]
@classmethod
def user(cls, text: str) -> "Message":
return cls(role="user", parts=[TextPart(text=text)])
@classmethod
def assistant(cls, text: str) -> "Message":
return cls(role="assistant", parts=[TextPart(text=text)])
@classmethod
def tool_results(cls, *results: ToolResultPart) -> "Message":
return cls(role="tool", parts=list(results))
@property
def text(self) -> str:
return "".join(p.text for p in self.parts if isinstance(p, TextPart))
# --------------------------------------------------------------------------- tools
class ToolSpec(BaseModel):
name: str
description: str
parameters: dict[str, Any] # JSON Schema for the arguments
strict: bool = False # ask the provider to enforce the schema, where it can
@classmethod
def from_model(cls, model: type[BaseModel], *, strict: bool = False) -> "ToolSpec":
"""Name = class name, description = docstring, parameters = the Pydantic JSON Schema."""
return cls(name=model.__name__, description=(model.__doc__ or "").strip(),
parameters=model.model_json_schema(), strict=strict)
class ForcedTool(BaseModel):
name: str
ToolChoice = Literal["auto", "required", "none"] | ForcedTool
Effort = Literal["off", "low", "medium", "high"] # "minimal", "xhigh" and "max" exist on some models: use `extra`
TAG_KEY = re.compile(r"[a-z][a-z0-9_]{0,31}") # metadata keys: lower_snake_case, at most 32 characters
MAX_TAGS = 16
MAX_TAG_VALUE = 128
# --------------------------------------------------------------------------- request
class Request(BaseModel):
"""Everything an application may ask for, in provider-neutral words."""
model_config = ConfigDict(arbitrary_types_allowed=True)
model: str # an ALIAS from models.yaml ("fast"), or a model key
messages: list[Message]
system: str | None = None
max_output_tokens: int | None = None # None = the registry's default for this model
tools: list[ToolSpec] = Field(default_factory=list)
tool_choice: ToolChoice = "auto"
parallel_tool_calls: bool | None = None # None = provider default
output_schema: type[BaseModel] | None = None # structured output
reasoning_effort: Effort | None = None # None = provider default
stop: list[str] = Field(default_factory=list)
metadata: dict[str, str] = Field(default_factory=dict) # app-level labels, e.g. feature, user hash
timeout_s: float | None = None # per attempt; None = the client's policy
extra: dict[str, dict[str, Any]] = Field(default_factory=dict)
# ^ escape hatch, keyed by PROVIDER NAME so a fallback never sends OpenAI-only fields to Gemini:
# extra={"openai": {"service_tier": "flex"}, "openrouter": {"extra_body": {"provider": {"sort": "price"}}}}
# Dicts are MERGED into what the adapter built (extra wins on scalars); model, messages and stream are reserved.
@field_validator("metadata")
@classmethod
def _tags_are_safe_to_log(cls, tags: dict[str, str]) -> dict[str, str]:
"""Metadata lands in every log line and cost record: keep keys boring and values short (lesson 03.10, 4.1)."""
if len(tags) > MAX_TAGS:
raise ValueError(f"at most {MAX_TAGS} metadata tags")
for key, value in tags.items():
if not TAG_KEY.fullmatch(key):
raise ValueError(f"metadata key {key!r} must match {TAG_KEY.pattern}")
if len(value) > MAX_TAG_VALUE:
raise ValueError(f"metadata value for {key!r} is longer than {MAX_TAG_VALUE} characters")
return tags
# --------------------------------------------------------------------------- response
class FinishReason(str, enum.Enum):
STOP = "stop" # natural end or stop sequence
LENGTH = "length" # hit max_output_tokens
CONTEXT_FULL = "context_full" # the context window filled up (Anthropic)
TOOL_CALLS = "tool_calls" # the model wants tools run
CONTENT_FILTER = "content_filter" # a safety system blocked the prompt or the answer
REFUSAL = "refusal" # the model declined
PAUSED = "paused" # Anthropic pause_turn: send it back to continue
ERROR = "error" # failed inside a 200 (status failed, malformed call...)
OTHER = "other" # a value we have no mapping for: look at raw_finish_reason
class Usage(BaseModel):
"""The same numbers as lesson 03.7's `cost_calc.Usage` (the adapters build it by calling `cost_calc.from_*`),
under the field names of 03.7's and 03.10's cost log: uncached_input_tokens EXCLUDES cache reads and writes;
output_tokens INCLUDES reasoning."""
uncached_input_tokens: int = 0 # billed at the plain input rate (03.7's `input`)
cached_input_tokens: int = 0 # cache reads (03.7's `cached_input`)
cache_write_tokens: dict[str, int] = Field(default_factory=dict) # lifetime -> tokens (the logs sum it)
output_tokens: int = 0
reasoning_tokens: int = 0 # informational: already inside output_tokens
tier: str = "standard" # standard | batch | flex | fast | ultrafast | priority (what SERVED the call)
geo: str | None = None # Anthropic inference_geo: priced at a multiplier
regional: bool = False # OpenAI data-residency endpoint: priced at an uplift
web_searches: int = 0 # server-side web searches: billed per 1,000, on top of tokens
grounding_searches: int = 0 # Gemini grounding queries
modality_input: dict[str, int] = Field(default_factory=dict) # uncached input by non-text modality
reported_cost_usd: float | None = None # OpenRouter's usage.cost: trust it over our arithmetic
@property
def total_input_tokens(self) -> int:
"""Every prompt token, however it was billed. `total - cached - written == uncached_input_tokens` (lesson 03.7, 3.1)."""
return self.uncached_input_tokens + self.cached_input_tokens + sum(self.cache_write_tokens.values())
class Cost(BaseModel):
usd: float | None # None = unknown. Never 0 for "we couldn't price it"
source: Literal["computed", "provider", "unknown"]
price_version: str | None = None
class Attempt(BaseModel):
"""One try at one model: what the retry/fallback layers did, for logs and for tests."""
model_key: str
provider: str
api: str
n: int # 1-based attempt number for this model
ok: bool
error_type: str | None = None
status: int | None = None
request_id: str | None = None
latency_ms: int = 0
usage: "Usage | None" = None # set when the attempt got a response, even one we then discarded
cost_usd: float | None = None # ...so a discarded (billed) response is still visible in the totals
class Response(BaseModel):
model_config = ConfigDict(arbitrary_types_allowed=True)
parts: list[Part]
finish_reason: FinishReason
raw_finish_reason: str | None # the provider's own word: "end_turn", "STOP", "incomplete:max_output_tokens"
usage: Usage | None # None = unknown (a broken stream), never a silent zero
cost: Cost | None = None
provider: str
api: str
model_key: str = "" # the registry entry that served it
requested_model: str = "" # what the caller asked for (an alias)
resolved_model: str | None = None # what the provider says it ran: often a dated snapshot
request_id: str | None = None # the PROVIDER's ID for support tickets: the x-request-id header when it sends one
provider_response_id: str | None = None # the ID in the body (resp_..., msg_..., chatcmpl-..., Gemini's responseId)
call_id: str = "" # OUR ID for the whole call, fallbacks included (hooks and logs use it)
latency_ms: int = 0
attempts: list[Attempt] = Field(default_factory=list)
parsed: BaseModel | None = None # set when output_schema was requested and validated
raw: Any = Field(default=None, exclude=True, repr=False) # the SDK's own response object
@property
def text(self) -> str:
return "".join(p.text for p in self.parts if isinstance(p, TextPart))
@property
def tool_calls(self) -> list[ToolCallPart]:
return [p for p in self.parts if isinstance(p, ToolCallPart)]
@property
def reasoning(self) -> str:
return "".join(p.text or "" for p in self.parts if isinstance(p, ReasoningPart))
@property
def message(self) -> Message:
"""The assistant turn, ready to append to the history (natives included)."""
return Message(role="assistant", parts=list(self.parts))
# --------------------------------------------------------------------------- streaming
class TextDelta(BaseModel):
type: Literal["text_delta"] = "text_delta"
text: str
class ReasoningDelta(BaseModel):
type: Literal["reasoning_delta"] = "reasoning_delta"
text: str
class ToolCallStart(BaseModel):
type: Literal["tool_call_start"] = "tool_call_start"
index: int
id: str
name: str
class ToolCallDelta(BaseModel):
type: Literal["tool_call_delta"] = "tool_call_delta"
index: int
arguments_fragment: str # a JSON FRAGMENT: parse only the finished call
class UsageEvent(BaseModel):
type: Literal["usage"] = "usage"
usage: Usage # cumulative: the latest replaces the earlier ones
class Done(BaseModel):
type: Literal["done"] = "done"
response: Response # the fully assembled response, same type as complete()
class StreamError(BaseModel):
type: Literal["error"] = "error"
error_type: str
message: str
retryable: bool
StreamEvent = TextDelta | ReasoningDelta | ToolCallStart | ToolCallDelta | UsageEvent | Done | StreamError
def dumps(model: BaseModel) -> str:
"""Compact JSON for logs and stores (raw is excluded by the field definition)."""
return json.dumps(model.model_dump(mode="json"), separators=(",", ":"))provider_agnostic/errors.py#
"""provider_agnostic/errors.py: one exception hierarchy for all providers.
The hard work (reading 4 SDKs' exceptions) is lesson 03.8's `llm_errors.classify()`. This file maps its
`Kind` onto classes you can `except` on, adds the "successful HTTP 200 that is not a success"
outcomes (Truncated, Refused, ContentBlocked), and client-side errors raised BEFORE any request.
Rule: the original SDK exception is always kept as `__cause__` (`raise ... from exc`).
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
import openai
from check_response import TRANSIENT_FAILED_CODES, Status, check_response # lesson 03.8, Part 10
from llm_errors import CONTEXT_HINTS, Failure, Kind, classify # lesson 03.8, Part 4
if TYPE_CHECKING:
from .types import FinishReason, Response
class LLMError(Exception):
"""Base class. `retryable` says whether the SAME request may succeed if sent again later."""
retryable: bool = False
def __init__(self, message: str, *, provider: str | None = None, status: int | None = None,
code: str | None = None, request_id: str | None = None,
retry_after_s: float | None = None) -> None:
super().__init__(message)
self.message, self.provider, self.status, self.code = message, provider, status, code
self.request_id, self.retry_after_s = request_id, retry_after_s
self.attempts: list = [] # filled by the client: every try that led here
self.partial: "Response | None" = None # streams: what arrived before the failure
self.response: "Response | None" = None # a COMPLETE response that was rejected after it was paid for
def __str__(self) -> str:
bits = [f"{self.provider}" if self.provider else "", f"HTTP {self.status}" if self.status else "",
self.code or "", f"request_id={self.request_id}" if self.request_id else ""]
detail = " ".join(b for b in bits if b)
return f"{self.message} [{detail}]" if detail else self.message # no empty "[]" when there is nothing to add
# ---- transport and server trouble: retry these -----------------------------------------------
class RateLimited(LLMError): retryable = True # 429 that clears with time
class Overloaded(LLMError): retryable = True # 503 / 529: the provider is busy
class ServerError(LLMError): retryable = True # 500 / 502 / 504 / 409
class Timeout(LLMError): retryable = True # we gave up waiting; the call MAY still bill
class ConnectionFailed(LLMError): retryable = True # DNS, TLS, refused, reset
# ---- your side or your account: retrying cannot help ------------------------------------------
class QuotaExceeded(LLMError): pass # credits, spend cap, daily quota (often a 429!)
class AuthFailed(LLMError): pass # 401: wrong or revoked key
class PermissionDenied(LLMError): pass # 403: no access to this model or feature
class BadRequest(LLMError): pass # 400, 404, 413, 422: a bug in the request
class ContextTooLong(BadRequest): pass # trim the input, then try again
# ---- HTTP 200 outcomes you chose to treat as errors ------------------------------------------
class Truncated(LLMError): pass # hit max_output_tokens (or the context window)
class Refused(LLMError): pass # the model declined
class ContentBlocked(LLMError): pass # a safety system blocked the prompt or answer
class ResponseFailed(LLMError): pass # an HTTP 200 whose body says "failed" with a permanent (or no) code
# ---- raised by this package, before or after the call ----------------------------------------
class UnsupportedFeature(LLMError): pass # capability check failed: nothing was sent
class OutputInvalid(LLMError): pass # structured output did not validate (the paid-for reply is on .response)
class ConfigError(LLMError): pass # bad registry, missing key, unknown alias
class HookError(LLMError): pass # a fail-closed hook raised: the call was stopped (cause = the hook's exception)
_BY_KIND: dict[Kind, type[LLMError]] = {
Kind.RATE_LIMITED: RateLimited, Kind.OVERLOADED: Overloaded, Kind.SERVER_ERROR: ServerError,
Kind.TIMEOUT: Timeout, Kind.CONNECTION: ConnectionFailed, Kind.CONFLICT: ServerError,
Kind.QUOTA: QuotaExceeded, Kind.AUTH: AuthFailed, Kind.PERMISSION: PermissionDenied,
Kind.CONTEXT_TOO_LONG: ContextTooLong, Kind.TOO_LARGE: BadRequest, Kind.BAD_REQUEST: BadRequest,
Kind.UNKNOWN: LLMError,
}
def wrap(exc: BaseException, provider: str) -> LLMError:
"""Turn any SDK exception into the matching LLMError. Use as `raise wrap(e, p) from e`."""
if isinstance(exc, LLMError):
return exc
# An `error` object inside an SSE chunk (OpenRouter documents it): the openai SDK raises a plain APIError with no
# HTTP status, and the code is in the body. Read it like an error-in-200 instead of guessing "unknown".
body = getattr(exc, "body", None)
if (type(exc) is openai.APIError and isinstance(body, dict) and isinstance(body.get("code"), int)):
return error_from_body(provider, body)
failure: Failure = classify(exc)
cls = _BY_KIND[failure.kind]
err = cls(failure.message, provider=provider, status=failure.status, code=failure.code,
request_id=failure.request_id, retry_after_s=failure.retry_after)
# x-should-retry (the server's own verdict) can override the class default, per instance
err.retryable = failure.retryable
return err
def raise_for_finish(resp: "Response") -> "Response":
"""Opt-in strictness: turn a bad finish reason into an exception. Returns resp if it is usable.
`retryable` is the class default (False for all of these): the same request would not come back different."""
from .types import FinishReason as F
bad: dict[F, type[LLMError]] = {F.LENGTH: Truncated, F.CONTEXT_FULL: Truncated,
F.CONTENT_FILTER: ContentBlocked, F.REFUSAL: Refused,
F.ERROR: ResponseFailed}
cls = bad.get(resp.finish_reason)
if cls is None:
return resp
err = cls(f"finish_reason={resp.finish_reason.value} (provider said {resp.raw_finish_reason!r})",
provider=resp.provider, request_id=resp.request_id, code=resp.raw_finish_reason)
err.response = resp
raise err
def _context_hint(message: str) -> bool:
return any(h in message.lower() for h in CONTEXT_HINTS) # 03.8's list: it has OpenRouter's wording
def error_from_body(provider: str, error: dict | None, *, request_id: str | None = None) -> LLMError:
"""OpenRouter (and some proxies) can answer HTTP 200 with an `error` object and no `choices`
(lesson 03.8, Part 10). Treat it as the failure it is: the class the same HTTP status would have given.
`error` looks like {"code": 429, "message": ...}. Codes that are not 4xx or 5xx numbers are server trouble."""
error = error or {}
code = error.get("code")
status = code if isinstance(code, int) else None
message = str(error.get("message") or "provider returned an error inside HTTP 200")
cls: type[LLMError] = {429: RateLimited, 502: Overloaded, 503: Overloaded, 529: Overloaded, 408: Timeout,
402: QuotaExceeded, 401: AuthFailed, 403: PermissionDenied}.get(status or 0, ServerError)
if status in (400, 404, 413, 422): # a bug in the request, not the server
cls = ContextTooLong if _context_hint(message) else BadRequest
return cls(message, provider=provider, status=status, code=str(code) if code is not None else None,
request_id=request_id)
_FAILED_CLASS: dict[str, type[LLMError]] = {
"rate_limit_exceeded": RateLimited, "server_is_overloaded": Overloaded, "provider_overloaded": Overloaded,
"service_unavailable": Overloaded, "provider_unavailable": Overloaded, "timeout": Timeout,
"deadline_exceeded": Timeout, "vector_store_timeout": Timeout} # every other TRANSIENT code: ServerError
def error_from_failed(provider: str, code: str | None, message: str | None = None, *,
request_id: str | None = None) -> LLMError:
"""An HTTP 200 whose body says the response FAILED (OpenAI Responses `status: failed`, Interactions `failed`,
an `error` stream event...). Lesson 03.8, Part 10 sorts the codes: transient ones (`server_error`,
`rate_limit_exceeded`...) can succeed on a retry, everything else is permanent. We reuse its table
(TRANSIENT_FAILED_CODES) and only add the step 03.8 does not need: choosing a class you can `except` on."""
c = (code or "").lower()
text = message or f"the provider reported a failed response ({code or 'no error code'})"
cls: type[LLMError]
if c in TRANSIENT_FAILED_CODES:
cls = _FAILED_CLASS.get(c, ServerError)
elif "policy" in c:
cls = ContentBlocked # bio_policy, image_content_policy_violation...
elif c.startswith(("invalid_", "image_", "unsupported_", "empty_", "failed_to_download", "data_residency")):
cls = BadRequest # invalid_prompt, invalid_image_url...
else:
cls = ResponseFailed # cancelled, budget_exceeded, or no code at all
return cls(text, provider=provider, status=200, code=code, request_id=request_id)
def error_message(raw: Any) -> str | None:
"""The provider's own message: `error` (OpenAI Responses) or `errors[0]` (Interactions). On the Interactions stream's
terminal object `errors[0]` is a plain dict, not an object."""
detail = getattr(raw, "error", None) or (getattr(raw, "errors", None) or [None])[0]
return detail.get("message") if isinstance(detail, dict) else getattr(detail, "message", None)
def raise_if_failed(raw: Any, provider: str, request_id: str | None = None) -> None:
"""Raise when an SDK response object is a FAILED outcome. Detection is 03.8's check_response(), as is (it accepts a
whole response and the Interactions stream's terminal object); the message comes from `error_message`."""
outcome = check_response(raw)
if outcome.status is Status.FAILED:
raise error_from_failed(provider, outcome.error_code, error_message(raw), request_id=request_id)provider_agnostic/registry.py#
"""provider_agnostic/registry.py: model aliases, capabilities and the checks that run BEFORE anything is sent."""
from __future__ import annotations
import os
from pathlib import Path
from typing import Any, Literal
import yaml
from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator
from .errors import ConfigError, UnsupportedFeature
from .types import DocumentPart, ForcedTool, ImagePart, Request
DEFAULT_PATH = Path(__file__).with_name("models.yaml")
Api = Literal["responses", "chat", "messages", "generate_content", "interactions"]
# A header with one of these names carries a credential: it must come from the environment (headers_env),
# never from a file you commit. Checked when the registry loads.
_SECRET_HEADER_HINTS = ("authorization", "api-key", "apikey", "token", "secret", "credential", "cookie", "auth")
class _Strict(BaseModel):
"""Unknown keys are an ERROR: a typo such as `capabilites:` must not silently fall back to defaults."""
model_config = ConfigDict(extra="forbid")
class Capabilities(_Strict):
tools: bool = False
forced_tool_choice: bool = False # tool_choice "required" or one named tool
structured_output: bool = False
images: bool = False
image_urls: bool = False # can the provider fetch an https image URL itself?
documents: bool = False # PDFs as input
reasoning: bool = False # accepts a reasoning effort other than "off"
stream_usage: bool = True # reports usage inside a stream
stop: bool = False # honours stop sequences (the Responses API has no such parameter)
parallel_tool_switch: bool = False # can parallel_tool_calls=False be honoured? (Gemini has no switch)
strict_tools: bool = False # does ToolSpec.strict=True actually make the server enforce the schema?
class ModelSpec(_Strict):
key: str = "" # filled in by the loader
provider: str # "openai" | "anthropic" | "gemini" | "openrouter" | "local"
api: Api
model: str # the provider's model ID
api_key_env: str | None = None # the NAME of the variable that holds the key: no key ever appears in a file
key_optional: bool = False # a server that ignores keys (Ollama): use a placeholder when the variable is unset
base_url: str | None = None
base_url_env: str | None = None # an environment variable that overrides base_url (proxies, the local stand-in)
headers: dict[str, str] = Field(default_factory=dict) # NON-secret default headers, e.g. OpenRouter attribution
headers_env: dict[str, str] = Field(default_factory=dict) # header name -> NAME of the variable holding its value (gateways)
free: bool = False # local stand-ins: cost is 0, not "unknown"
context_window: int | None = None
max_output_tokens: int | None = None
default_max_output_tokens: int = 1024
reasoning_off: str | None = None # the lowest setting THIS model accepts
capabilities: Capabilities = Field(default_factory=Capabilities)
@field_validator("headers")
@classmethod
def _no_secrets_in_files(cls, headers: dict[str, str]) -> dict[str, str]:
for name in headers:
if any(h in name.lower() for h in _SECRET_HEADER_HINTS):
raise ValueError(f"header {name!r} looks like a credential: put the variable NAME under headers_env, "
"not the value under headers")
return headers
def resolved_base_url(spec: ModelSpec) -> str | None:
"""env override first, then the file, then None (the SDK's own default / its OPENAI_BASE_URL-style variable)."""
return (os.environ.get(spec.base_url_env) if spec.base_url_env else None) or spec.base_url
def resolve_api_key(spec: ModelSpec) -> str | None:
"""The key for this route, from the environment. A route that needs a key and has none is a ConfigError that
names the variable (and never the value)."""
if not spec.api_key_env:
return None
key = os.environ.get(spec.api_key_env)
if key:
return key
if spec.key_optional:
return "local" # Ollama ignores it; the SDKs just need a non-empty string
raise ConfigError(f"{spec.key}: set {spec.api_key_env} (see lesson 03.1, Part 3)", provider=spec.provider)
def resolve_headers(spec: ModelSpec) -> dict[str, str] | None:
"""Default headers: the literal ones plus those read from the environment (never logged, never dumped)."""
out = dict(spec.headers)
for name, var in spec.headers_env.items():
value = os.environ.get(var)
if not value:
raise ConfigError(f"{spec.key}: set {var} (it fills the {name!r} header)", provider=spec.provider)
out[name] = value
return out or None
class Registry:
def __init__(self, data: dict[str, Any]) -> None:
if not isinstance(data, dict): # an empty file loads as None, a bare list as a list
raise ConfigError(f"the registry must be a mapping with version, aliases and models, got {type(data).__name__}")
unknown = [k for k in data if k not in ("version", "aliases", "models") and not str(k).startswith("x-")]
if unknown:
raise ConfigError(f"unknown top-level key(s) {unknown}: expected version, aliases, models")
if not data.get("version"):
raise ConfigError("the registry needs a `version:` (the date you last checked its values)")
self.version = str(data["version"])
self.models: dict[str, ModelSpec] = {}
models = data.get("models") or {}
if not isinstance(models, dict): # `models: [a, b]` is a YAML typo, not a spec error
raise ConfigError(f"`models:` must be a mapping of entry name to spec, got {type(models).__name__}")
for key, spec in models.items():
if not isinstance(spec, dict): # `models: {x: "oops"}`: {**spec} would raise a raw TypeError
raise ConfigError(f"model entry {key!r}: expected a mapping, got {type(spec).__name__}")
try:
self.models[key] = ModelSpec.model_validate({**spec, "key": key})
except ValidationError as exc: # name the entry: the pydantic path alone says "capabilites"
raise ConfigError(f"model entry {key!r}: {exc.errors()[0]['loc']} {exc.errors()[0]['msg']}") from exc
aliases = data.get("aliases") or {}
if not isinstance(aliases, dict):
raise ConfigError(f"`aliases:` must be a mapping of alias to chain, got {type(aliases).__name__}")
self.aliases: dict[str, list[str]] = {}
for alias, chain in aliases.items():
if not isinstance(chain, list): # `fast: gpt-4o` would otherwise split into characters
raise ConfigError(f"alias {alias!r}: expected a list of model entries, got {type(chain).__name__}")
self.aliases[alias] = list(chain)
for alias, chain in self.aliases.items(): # fail at load time, not at 3 a.m.
if not chain:
raise ConfigError(f"alias {alias!r} has an empty chain")
if len(set(chain)) != len(chain):
raise ConfigError(f"alias {alias!r} lists an entry twice: {chain}")
if alias in self.models:
raise ConfigError(f"{alias!r} is both an alias and a model entry: model={alias!r} would be ambiguous")
for key in chain:
if key not in self.models:
raise ConfigError(f"alias {alias!r} names unknown model entry {key!r}")
@classmethod
def load(cls, path: str | Path = DEFAULT_PATH) -> "Registry":
return cls(yaml.safe_load(Path(path).read_text()))
def chain(self, name: str) -> list[ModelSpec]:
"""An alias gives its ordered chain; a bare entry key gives a chain of one."""
if name in self.aliases:
return [self.models[k] for k in self.aliases[name]]
if name in self.models:
return [self.models[name]]
raise ConfigError(f"unknown model alias {name!r}; known aliases: {sorted(self.aliases)}, "
f"entries: {sorted(self.models)}")
def missing_credentials(self, name: str) -> list[str]:
"""Every variable the WHOLE chain needs that is not set: checked before the first request, so a fallback
whose key is missing is found today and not in the middle of an outage."""
missing: list[str] = []
for spec in self.chain(name):
wanted = [spec.api_key_env] if spec.api_key_env and not spec.key_optional else []
wanted += list(spec.headers_env.values())
missing += [f"{spec.key}: {var}" for var in wanted if not os.environ.get(var)]
return missing
def check_capabilities(req: Request, spec: ModelSpec) -> None:
"""Raise UnsupportedFeature for anything this route cannot do. NEVER silently drop an option."""
caps, where = spec.capabilities, f"{spec.key} ({spec.provider}/{spec.api}/{spec.model})"
def need(ok: bool, what: str) -> None:
if not ok:
raise UnsupportedFeature(f"{where} does not support {what}", provider=spec.provider)
if req.tools:
need(caps.tools, "tools")
if any(t.strict for t in req.tools):
need(caps.strict_tools, "strict tool schemas (the server would not enforce them: set strict=False and validate arguments)")
if isinstance(req.tool_choice, ForcedTool) or req.tool_choice == "required":
need(caps.forced_tool_choice, "forced tool use (use tool_choice='auto')")
if req.parallel_tool_calls is False:
need(caps.parallel_tool_switch, "parallel_tool_calls=False (there is no switch: match results by ID)")
if req.stop:
need(caps.stop, "stop sequences (cut the text yourself, or use a route that has them)")
if req.output_schema is not None:
need(caps.structured_output, "schema-constrained structured output")
if req.reasoning_effort not in (None, "off"):
need(caps.reasoning, f"reasoning_effort={req.reasoning_effort!r}")
for message in req.messages:
for part in message.parts:
if isinstance(part, ImagePart):
need(caps.images, "image input")
if part.url and not part.data_b64:
need(caps.image_urls, "image URLs (send the bytes as data_b64)")
elif isinstance(part, DocumentPart):
need(caps.documents, "document (PDF) input")
if req.max_output_tokens and spec.max_output_tokens and req.max_output_tokens > spec.max_output_tokens:
raise UnsupportedFeature(f"{where}: max_output_tokens={req.max_output_tokens} is above the "
f"model's limit {spec.max_output_tokens}", provider=spec.provider)provider_agnostic/models.yaml#
# models.yaml: the capability registry. One entry per concrete model route; aliases map app-level
# names to an ORDERED chain of entries (first = primary, the rest = fallbacks).
#
# What lives here: facts about WHICH route to call and WHAT it can do.
# What does not: prices. They stay in prices.yaml (lesson 03.7) so there is exactly one place to update.
# Re-check every value against the provider's docs or Models API before relying on it:
# context/output limits from lesson 02.9 (as of November 2026); refresh with `python -m provider_agnostic.refresh`.
version: 2026-11-04
aliases:
fast: [luna, haiku, flash] # cheap and quick; three providers
smart: [sol, sonnet] # harder tasks
vision: [flash, haiku, luna] # image input
cheap-or: [or-luna, or-haiku] # everything through OpenRouter
models:
luna:
provider: openai
api: responses
model: gpt-6-luna
api_key_env: OPENAI_API_KEY
context_window: 1050000 # 02.9: "1.05M", includes the output
max_output_tokens: 128000
default_max_output_tokens: 1024 # OUR default for requests that don't say; not a provider limit
reasoning_off: none # lowest setting this MODEL accepts (02.8, 3.6)
capabilities: {tools: true, forced_tool_choice: true, structured_output: true, images: true,
image_urls: true, documents: true, reasoning: true, stream_usage: true,
stop: false, parallel_tool_switch: true, strict_tools: true} # the Responses API has no stop parameter
luna-chat: # the same model through Chat Completions
provider: openai
api: chat
model: gpt-6-luna
api_key_env: OPENAI_API_KEY
context_window: 1050000
max_output_tokens: 128000
default_max_output_tokens: 1024
reasoning_off: none
capabilities: {tools: true, forced_tool_choice: true, structured_output: true, images: true,
image_urls: true, documents: true, reasoning: true, stream_usage: true,
stop: true, parallel_tool_switch: true, strict_tools: true}
sol:
provider: openai
api: responses
model: gpt-6.1-sol
api_key_env: OPENAI_API_KEY
context_window: 1050000
max_output_tokens: 128000
default_max_output_tokens: 4096 # a reasoning model: leave room to think
reasoning_off: low # always reasons: "none" would be a 400
capabilities: {tools: true, forced_tool_choice: true, structured_output: true, images: true,
image_urls: true, documents: true, reasoning: true, stream_usage: true,
stop: false, parallel_tool_switch: true, strict_tools: true} # the Responses API has no stop parameter
haiku:
provider: anthropic
api: messages
model: claude-haiku-5-5
api_key_env: ANTHROPIC_API_KEY
context_window: 1000000
max_output_tokens: 128000
default_max_output_tokens: 1024
reasoning_off: disabled
capabilities: {tools: true, forced_tool_choice: true, structured_output: true, images: true,
image_urls: true, documents: true, reasoning: true, stream_usage: true,
stop: true, parallel_tool_switch: true, strict_tools: true}
sonnet:
provider: anthropic
api: messages
model: claude-sonnet-5-5
api_key_env: ANTHROPIC_API_KEY
context_window: 1000000
max_output_tokens: 128000
default_max_output_tokens: 4096
reasoning_off: between_tools
capabilities: {tools: true, forced_tool_choice: false, structured_output: true, images: true, # any/tool tool_choice is a 400 on this model
image_urls: true, documents: true, reasoning: true, stream_usage: true,
stop: true, parallel_tool_switch: true, strict_tools: true}
flash:
provider: gemini
api: generate_content # see 4.5: why this and not Interactions is the default
model: gemini-3.8-flash
api_key_env: GEMINI_API_KEY
context_window: 1048576
max_output_tokens: 65536
default_max_output_tokens: 1024
reasoning_off: low # "minimal" is an error on this model
capabilities: {tools: true, forced_tool_choice: true, structured_output: true, images: true,
image_urls: true, documents: true, reasoning: true, stream_usage: true,
stop: true, parallel_tool_switch: false, strict_tools: false} # Gemini has no switch: results are matched by ID or order; no strict flag on this API
flash-interactions:
provider: gemini
api: interactions
model: gemini-3.8-flash
api_key_env: GEMINI_API_KEY
context_window: 1048576
max_output_tokens: 65536
default_max_output_tokens: 1024
reasoning_off: low
capabilities: {tools: true, forced_tool_choice: true, structured_output: true, images: true,
image_urls: true, documents: true, reasoning: true, stream_usage: true,
stop: true, parallel_tool_switch: false, strict_tools: false} # Gemini has no switch: results are matched by ID or order; no strict flag on this API
or-luna:
provider: openrouter
api: chat
model: openai/gpt-6-luna
context_window: 1050000 # OpenRouter's catalogue reports context_length: the audit compares it
headers: {HTTP-Referer: "https://example.com/wrapper-demo", X-OpenRouter-Title: "wrapper demo"}
api_key_env: OPENROUTER_API_KEY
base_url: https://openrouter.ai/api/v1
base_url_env: OPENROUTER_BASE_URL
default_max_output_tokens: 1024
reasoning_off: none
capabilities: {tools: true, forced_tool_choice: true, structured_output: true, images: true,
image_urls: true, documents: true, reasoning: true, stream_usage: true,
stop: true, parallel_tool_switch: true, strict_tools: false} # OpenRouter forwards; the endpoint may not enforce
or-haiku:
provider: openrouter
api: chat
model: anthropic/claude-haiku-5.5 # OpenRouter IDs use dots
context_window: 1000000
headers: {HTTP-Referer: "https://example.com/wrapper-demo", X-OpenRouter-Title: "wrapper demo"}
api_key_env: OPENROUTER_API_KEY
base_url: https://openrouter.ai/api/v1
base_url_env: OPENROUTER_BASE_URL
default_max_output_tokens: 1024
reasoning_off: none
capabilities: {tools: true, forced_tool_choice: true, structured_output: true, images: true,
image_urls: true, documents: true, reasoning: true, stream_usage: true,
stop: true, parallel_tool_switch: true, strict_tools: false} # OpenRouter forwards; the endpoint may not enforceprovider_agnostic/models.local.yaml#
# models.local.yaml: the three API shapes Ollama speaks, pointed at the local stand-in (Ollama alone).
# There is no local Gemini entry: Ollama does not speak Gemini's API (lesson 03.1, 12.4), so generate_content and
# Interactions are hosted-only and tested with mocks.
# Nothing here proves how a hosted model behaves: it proves the wrapper's plumbing.
# Keys: the routes read LOCAL_API_KEY (any non-empty value; unset is fine: Ollama ignores it). They deliberately do NOT
# read OPENAI_API_KEY, ANTHROPIC_API_KEY or GEMINI_API_KEY: a real hosted key in your .env must never be sent to a
# server on localhost.
version: local
aliases:
local: [local-responses, local-chat, local-anthropic]
local-openai: [local-responses, local-chat]
models:
local-responses:
provider: local
api: responses
model: qwen2.5:0.5b
base_url: http://localhost:11434/v1
api_key_env: LOCAL_API_KEY
key_optional: true
free: true
default_max_output_tokens: 200
reasoning_off: none
capabilities: {tools: true, forced_tool_choice: false, structured_output: true, images: false,
documents: false, reasoning: false, stream_usage: true,
stop: false, parallel_tool_switch: false, strict_tools: false} # Ollama ignores strict and tool_choice
local-chat:
provider: local
api: chat
model: qwen2.5:0.5b
base_url: http://localhost:11434/v1
api_key_env: LOCAL_API_KEY
key_optional: true
free: true
default_max_output_tokens: 200
reasoning_off: none
capabilities: {tools: true, forced_tool_choice: false, structured_output: true, images: false,
documents: false, reasoning: false, stream_usage: true,
stop: true, parallel_tool_switch: false, strict_tools: false}
local-anthropic:
provider: local
api: messages
model: qwen2.5:0.5b
base_url: http://localhost:11434
api_key_env: LOCAL_API_KEY
key_optional: true
free: true
default_max_output_tokens: 200
reasoning_off: disabled
capabilities: {tools: true, forced_tool_choice: false, structured_output: false, images: false,
documents: false, reasoning: false, stream_usage: true, # Ollama ignores output_config
stop: true, parallel_tool_switch: false, strict_tools: false}provider_agnostic/schemas.py#
"""provider_agnostic/schemas.py: JSON Schema for tools and structured output, in each provider's dialect.
Lesson 03.4 explains the dialects. The wrapper needs exactly one thing from them: given a Pydantic
model (or a plain schema dict), produce what each provider's strict mode accepts.
"""
from __future__ import annotations
import copy
import inspect
from typing import Any
import anthropic
from pydantic import BaseModel
def openai_strict(schema: type[BaseModel] | dict[str, Any]) -> dict[str, Any]:
"""OpenAI (and OpenRouter, Ollama): every property required, additionalProperties false.
PRIVATE helpers from the openai SDK: `responses.parse()` uses the same ones. They may change in
any release, so tests/test_parity_schemas.py pins their behaviour; revisit it when you upgrade openai."""
from openai.lib._pydantic import _ensure_strict_json_schema, to_strict_json_schema
if inspect.isclass(schema) and issubclass(schema, BaseModel):
return to_strict_json_schema(schema)
root = copy.deepcopy(schema)
return _ensure_strict_json_schema(root, path=(), root=root)
def anthropic_schema(schema: type[BaseModel] | dict[str, Any]) -> dict[str, Any]:
"""Anthropic: PUBLIC `transform_schema` (what messages.parse() uses): drops constraints the grammar
can't enforce into the field descriptions, adds additionalProperties false."""
return anthropic.transform_schema(schema)
def plain_schema(schema: type[BaseModel] | dict[str, Any]) -> dict[str, Any]:
"""Gemini takes the Pydantic schema as it is (response_json_schema / Interactions schema)."""
return schema.model_json_schema() if inspect.isclass(schema) else schema
def schema_name(model: type[BaseModel]) -> str:
return model.__name__provider_agnostic/cost.py#
"""provider_agnostic/cost.py: canonical Usage <-> lesson 03.7's `cost_calc.Usage`, and Usage -> dollars.
The adapters do NOT redo 03.7's arithmetic. They call `cost_calc.from_openai_response`, `from_anthropic`,
`from_gemini`... on the SDK object, which already knows the cached-token convention, fast mode (2x), the geo
multiplier, web-search fees, 12-hour cache writes and every service tier, and convert the result with
`usage_from_cost_calc`. A price table and a calculator that drift from the adapters were the bug; one source is the fix.
"""
from __future__ import annotations
import datetime as dt
import cost_calc # lesson 03.7
from prices import PriceTable # lesson 03.7
from .registry import ModelSpec
from .types import Cost, Usage
def usage_from_cost_calc(u: cost_calc.Usage) -> Usage:
return Usage(uncached_input_tokens=u.input, cached_input_tokens=u.cached_input, cache_write_tokens=dict(u.cache_writes),
output_tokens=u.output, reasoning_tokens=u.reasoning, tier=u.tier, geo=u.geo, regional=u.regional,
web_searches=u.web_searches, grounding_searches=u.grounding_searches,
modality_input=dict(u.modality_input), reported_cost_usd=u.reported_cost)
def to_cost_calc(usage: Usage, spec: ModelSpec) -> cost_calc.Usage:
"""The price table is keyed by the registry's provider and model ID, not by the dated snapshot the provider ran."""
return cost_calc.Usage(provider=spec.provider, model=spec.model, input=usage.uncached_input_tokens,
cached_input=usage.cached_input_tokens, cache_writes=dict(usage.cache_write_tokens),
output=usage.output_tokens, reasoning=usage.reasoning_tokens, tier=usage.tier,
geo=usage.geo, regional=usage.regional, web_searches=usage.web_searches,
grounding_searches=usage.grounding_searches, modality_input=dict(usage.modality_input),
reported_cost=usage.reported_cost_usd)
def price_usage(usage: Usage | None, spec: ModelSpec, table: PriceTable | None) -> Cost:
if usage is None:
return Cost(usd=None, source="unknown")
if spec.free:
return Cost(usd=0.0, source="computed", price_version="free-local")
if table is None:
return Cost(usd=None, source="unknown")
try:
result = cost_calc.price(to_cost_calc(usage, spec), table, dt.date.today())
except (KeyError, ValueError): # no price, a tier the table lacks, or OpenRouter without usage.cost: unknown, NEVER zero
return Cost(usd=None, source="unknown", price_version=table.version)
return Cost(usd=result.usd, source="provider" if usage.reported_cost_usd is not None else "computed",
price_version=table.version)provider_agnostic/redact.py#
"""provider_agnostic/redact.py: a small, fail-closed redactor and a keyed user hash (lesson 03.10, Parts 2 and 4).
Best effort, not a guarantee: regexes only know the shapes listed here (keep them under test, as tests/test_hooks.py
does), and nothing here can look inside an image or a PDF. Lesson 03.10 has the fuller pattern list and the reasoning;
the shapes below are the same families, small enough to read in one go. Module 12 treats data protection properly.
"""
from __future__ import annotations
import hashlib
import hmac
import os
import re
from typing import Any
from .errors import ConfigError
# Credential shapes as of November 2026: OpenAI, Anthropic and OpenRouter (sk-...), Google API keys and OAuth tokens,
# GitHub, AWS access key IDs, bearer tokens and JWTs. Each prefix is a vendor's convention: re-check them.
_CREDENTIALS = re.compile(
r"(?<![A-Za-z0-9_-])(?:sk-(?:ant-|or-v1-|or-|proj-)?[A-Za-z0-9_-]{16,}|AIza[0-9A-Za-z_-]{30,}|ya29\.[A-Za-z0-9_-]{20,}"
r"|gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{30,}|(?:AKIA|ASIA)[0-9A-Z]{16}"
r"|eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,})|(?i:\bbearer\s+[A-Za-z0-9._\-]{12,})")
_KEY_VALUE = re.compile(r"""(?i)\b(password|passwd|secret|api[_-]?key|access[_-]?token|token)(["']?\s*[:=]\s*["']?)([^\s"',;&]{4,})""")
_EMAIL = re.compile(r"\b[\w.+-]+@[\w-]+(?:\.[\w-]+)+\b")
_CARD = re.compile(r"\b\d(?:[ -]?\d){12,18}\b") # long digit runs: card and account numbers
def redact_text(text: str) -> str:
"""Replace credentials, emails and card-like digit runs with a [LABEL]."""
text = _CREDENTIALS.sub("[CREDENTIAL]", text)
text = _KEY_VALUE.sub(lambda m: f"{m.group(1)}{m.group(2)}[SECRET]", text)
return _CARD.sub("[CARD]", _EMAIL.sub("[EMAIL]", text))
def scrub(value: Any) -> Any:
"""Strings inside tool arguments, at any depth."""
if isinstance(value, str):
return redact_text(value)
if isinstance(value, dict):
return {k: scrub(v) for k, v in value.items()}
if isinstance(value, list):
return [scrub(v) for v in value]
return value
def hash_user(user_id: str, *, key: bytes | None = None, purpose: str = "logs-v1") -> str:
"""A KEYED hash for `metadata={"user": hash_user(uid)}`: stable per user, but nobody can rebuild it from a list of
emails without the key. It is the recipe of lesson 03.2, 10.3: HMAC-SHA256 over "purpose:user_id". The default
purpose "logs-v1" is for IDs in your own logs and cost records; the ID you send to a provider
(`extra={"openai": {"safety_identifier": ...}}`) uses purpose="llm-abuse-v1", so the two can't be matched.
The key has NO default: pass it, or set USER_ID_PEPPER (from your secret store, like an API key). A missing key is a
ConfigError, not a quiet fallback to a public one (lesson 03.10, 4.1).
16 hex characters are enough to correlate one user's calls, not collision-proof across billions of users."""
secret = key or os.environ.get("USER_ID_PEPPER", "").encode()
if not secret:
raise ConfigError("hash_user needs a secret key: pass key= or set USER_ID_PEPPER")
return hmac.new(secret, f"{purpose}:{user_id}".encode(), hashlib.sha256).hexdigest()[:16]provider_agnostic/hooks.py#
"""provider_agnostic/hooks.py: extension points. Subclass Hook and override only what you need.
Five moments: before the call (request middleware: may return a changed Request), after each attempt, after a
successful call (response middleware: may return a changed Response), when the call finally fails, and when the
consumer walks away from a stream.
Two kinds of hook, and they fail in opposite directions (lesson 03.11, Part 9):
* OBSERVERS (logging, metrics, cost records): `attempt`, `error`, `abandoned`, and `after` unless you opt in below.
A broken observer must not break the user's request, so the client catches what they raise and logs its TYPE.
* MIDDLEWARE (a budget gate, a redactor, a validator): it exists to STOP or CHANGE the call. `before` is ALWAYS
fail-closed: if it raises, nothing is sent and the caller gets a HookError (or the hook's own LLMError). `after`
is fail-closed for a hook that sets `fail_closed = True`. Swallowing an error here would turn "enforce the budget"
and "redact the prompt" into "try to, if nothing goes wrong".
Hooks are SYNCHRONOUS and run on the caller's thread, or on the event loop inside acomplete()/astream(): slow work
(a network call, a file flush) blocks every other call on that loop. Put it on a queue and return.
"""
from __future__ import annotations
import json
import logging
import os
import threading
from collections import Counter
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Protocol
from .errors import HookError, LLMError
from .redact import redact_text, scrub
from .types import (Attempt, DocumentPart, ImagePart, Message, Part, ReasoningPart, Request, Response, TextPart,
ToolCallPart, ToolResultPart, Usage)
log = logging.getLogger("provider_agnostic")
@dataclass
class CallContext:
call_id: str
alias: str # what the caller asked for
started: float # monotonic clock
tags: dict[str, str] = field(default_factory=dict) # Request.metadata, validated and scrubbed: for YOUR logs only
class Hook:
fail_closed: bool = False # True: an exception in after() stops the call instead of being logged and ignored
def before(self, ctx: CallContext, req: Request) -> Request: # request middleware: ALWAYS fail-closed
return req
def attempt(self, ctx: CallContext, attempt: Attempt) -> None: # every try, ok or not
pass
def after(self, ctx: CallContext, req: Request, resp: Response) -> Response: # response middleware or observer
return resp
def error(self, ctx: CallContext, req: Request, err: LLMError) -> None: # the call failed for good
pass
def abandoned(self, ctx: CallContext, req: Request, partial: Response) -> None: # the consumer stopped reading a stream
pass
# ---------------------------------------------------------------------------------------------------- middleware
class RedactHook(Hook):
"""Request middleware: scrub what you are about to send. Fail-closed in two ways.
* `Hook.before` always is: if this hook raises, the call is stopped, so a bug here can never send the original
text to a provider.
* It is allow-list shaped: it rewrites the part types it knows how to read and REFUSES anything else, including
images and PDFs (it cannot see inside them) unless you say `allow_media=True`. A future part type raises
instead of passing through unexamined.
A rewritten text, tool-result or tool-call part loses its `native` twin: that twin holds the original text
and would be replayed instead. (A `ReasoningPart` keeps its signed `native`: editing it would break the
provider's signature, so only its human-readable `text` summary is scrubbed.)"""
def __init__(self, *, allow_media: bool = False) -> None:
self.allow_media = allow_media
def before(self, ctx: CallContext, req: Request) -> Request:
messages = [Message(role=m.role, parts=[self._part(p) for p in m.parts]) for m in req.messages]
return req.model_copy(update={"messages": messages, "system": redact_text(req.system) if req.system else None})
def _part(self, p: Part) -> Part:
if isinstance(p, TextPart):
clean = redact_text(p.text)
return p if clean == p.text else TextPart(text=clean)
if isinstance(p, ToolResultPart):
clean = redact_text(p.content)
return p if clean == p.content else p.model_copy(update={"content": clean, "native": None})
if isinstance(p, ToolCallPart):
clean_args = scrub(p.arguments)
return p if clean_args == p.arguments else p.model_copy(update={"arguments": clean_args, "native": None})
if isinstance(p, ReasoningPart):
return p.model_copy(update={"text": redact_text(p.text) if p.text else p.text}) # the signed native stays
if isinstance(p, (ImagePart, DocumentPart)) and self.allow_media:
return p
raise HookError(f"RedactHook cannot inspect a {type(p).__name__}: refusing to send it "
"(pass allow_media=True if you accept that images and PDFs are not scrubbed)")
# ---------------------------------------------------------------------------------------------------- observers
def _usage_fields(u: Usage | None) -> dict[str, Any]:
"""The same names as the `Usage` fields (03.7's columns): `uncached_input_tokens` is billed at the plain rate;
there is no bare `input_tokens`. `cache_write_tokens` is the sum over lifetimes here."""
if u is None:
return {"uncached_input_tokens": None, "cached_input_tokens": None, "cache_write_tokens": None,
"total_input_tokens": None, "output_tokens": None, "reasoning_tokens": None}
return {"uncached_input_tokens": u.uncached_input_tokens, "cached_input_tokens": u.cached_input_tokens,
"cache_write_tokens": sum(u.cache_write_tokens.values()), "total_input_tokens": u.total_input_tokens,
"output_tokens": u.output_tokens, "reasoning_tokens": u.reasoning_tokens}
class LoggingHook(Hook):
"""One JSON line per attempt and per call. Logs sizes and IDs, never prompt or answer text.
Your tags live under their own `tags` key, so a tag called `cost_usd` or `event` can never overwrite a real field."""
def attempt(self, ctx: CallContext, attempt: Attempt) -> None:
a = attempt
log.info(json.dumps({"event": "llm_attempt", "call_id": ctx.call_id, "model_key": a.model_key,
"provider": a.provider, "api": a.api, "n": a.n, "ok": a.ok,
"error": a.error_type, "status": a.status, "request_id": a.request_id,
"latency_ms": a.latency_ms, "tags": ctx.tags}))
def after(self, ctx: CallContext, req: Request, resp: Response) -> Response:
log.info(json.dumps({
"event": "llm_call", "call_id": ctx.call_id, "alias": ctx.alias, "model_key": resp.model_key,
"provider": resp.provider, "api": resp.api, "resolved_model": resp.resolved_model,
"finish": resp.finish_reason.value, "raw_finish": resp.raw_finish_reason,
**_usage_fields(resp.usage), "cost_usd": resp.cost.usd if resp.cost else None,
"request_id": resp.request_id, "latency_ms": resp.latency_ms, "attempts": len(resp.attempts),
"tags": ctx.tags}))
return resp
def error(self, ctx: CallContext, req: Request, err: LLMError) -> None:
paid = err.response or err.partial # a billed reply we rejected, or the part of a stream that arrived
log.warning(json.dumps({"event": "llm_call_failed", "call_id": ctx.call_id, "alias": ctx.alias,
"error": type(err).__name__, "status": err.status, "code": err.code,
"request_id": err.request_id, "attempts": len(err.attempts),
**_usage_fields(paid.usage if paid else None),
"cost_usd": paid.cost.usd if paid and paid.cost else None, "tags": ctx.tags}))
def abandoned(self, ctx: CallContext, req: Request, partial: Response) -> None:
log.warning(json.dumps({"event": "llm_stream_abandoned", "call_id": ctx.call_id, "alias": ctx.alias,
"model_key": partial.model_key, "request_id": partial.request_id,
**_usage_fields(partial.usage), "cost_usd": partial.cost.usd if partial.cost else None,
"tags": ctx.tags}))
class JsonlCostHook(Hook):
"""Append one record per call to a JSON Lines file, whatever its outcome (same columns as lesson 03.7's tracker):
`ok`, `invalid` (a reply that failed validation: billed), `failed` (an error, with the partial usage of a broken
stream when it is known) or `abandoned` (the consumer stopped reading). `cost_usd` is null, never 0, when unknown.
The file holds spend, request IDs and user-hash tags, so it is created owner-only: the directory 0700, the file 0600,
from the first byte (os.open with the mode, not write-then-chmod). It rotates to `<name>.1` at `max_bytes` (one
generation: ship the old file to your log store before it is replaced), and `fsync=True` makes each record durable."""
def __init__(self, path: str | Path, *, max_bytes: int = 50_000_000, fsync: bool = False) -> None:
self.path, self.max_bytes, self.fsync, self._lock = Path(path), max_bytes, fsync, threading.Lock()
self.path.parent.mkdir(parents=True, mode=0o700, exist_ok=True)
os.close(self._open()) # create it now: a bad path fails at startup, not mid-call
def _open(self) -> int:
flags = os.O_WRONLY | os.O_CREAT | os.O_APPEND | getattr(os, "O_NOFOLLOW", 0) # never follow a planted symlink
fd = os.open(self.path, flags, 0o600)
if hasattr(os, "fchmod") and os.fstat(fd).st_mode & 0o077: # an older, wider file: tighten it before writing a byte (POSIX only)
os.fchmod(fd, 0o600)
return fd
def _write(self, record: dict[str, Any]) -> None:
line = (json.dumps(record, default=str) + "\n").encode()
with self._lock:
if self.path.exists() and self.path.stat().st_size + len(line) > self.max_bytes:
os.replace(self.path, self.path.with_name(self.path.name + ".1"))
fd = self._open()
try:
os.write(fd, line)
if self.fsync:
os.fsync(fd)
finally:
os.close(fd)
def _record(self, ctx: CallContext, outcome: str, resp: Response | None, err: LLMError | None = None) -> dict[str, Any]:
usage = resp.usage if resp else None
wasted = sum(a.cost_usd or 0.0 for a in (resp.attempts if resp else []) if not a.ok) # discarded, billed replies
return {"call_id": ctx.call_id, "kind": "call", "outcome": outcome, "alias": ctx.alias,
"provider": resp.provider if resp else None, "model_key": resp.model_key if resp else None,
"served_model": resp.resolved_model if resp else None, "api": resp.api if resp else None,
"request_id": (resp.request_id if resp else None) or (err.request_id if err else None),
"tier": usage.tier if usage else None, "batch": bool(usage and usage.tier == "batch"),
"regional": bool(usage and usage.regional), **_usage_fields(usage),
"cost_usd": resp.cost.usd if resp and resp.cost else None,
"cost_source": resp.cost.source if resp and resp.cost else "unknown",
"price_version": resp.cost.price_version if resp and resp.cost else None,
"discarded_cost_usd": wasted or None,
"finish_reason": resp.raw_finish_reason if resp else None,
"error": type(err).__name__ if err else None,
"attempts": len(resp.attempts) if resp else (len(err.attempts) if err else None),
"latency_ms": resp.latency_ms if resp else None, "tags": ctx.tags}
def after(self, ctx: CallContext, req: Request, resp: Response) -> Response:
self._write(self._record(ctx, "ok", resp))
return resp
def error(self, ctx: CallContext, req: Request, err: LLMError) -> None:
paid = err.response or err.partial
self._write(self._record(ctx, "invalid" if err.response is not None else "failed", paid, err))
def abandoned(self, ctx: CallContext, req: Request, partial: Response) -> None:
self._write(self._record(ctx, "abandoned", partial))
class MetricsHook(Hook):
"""In-memory counters. Swap the body for Prometheus, StatsD or OpenTelemetry (Module 11A)."""
def __init__(self) -> None:
self.counts: Counter[str] = Counter()
self.latency_ms_total = 0
self._lock = threading.Lock()
def attempt(self, ctx: CallContext, attempt: Attempt) -> None:
with self._lock:
self.counts[f"attempt.{attempt.model_key}.{'ok' if attempt.ok else attempt.error_type}"] += 1
self.latency_ms_total += attempt.latency_ms
def after(self, ctx: CallContext, req: Request, resp: Response) -> Response:
with self._lock:
self.counts[f"finish.{resp.finish_reason.value}"] += 1
return resp
def error(self, ctx: CallContext, req: Request, err: LLMError) -> None:
with self._lock:
self.counts[f"failed.{type(err).__name__}"] += 1
def abandoned(self, ctx: CallContext, req: Request, partial: Response) -> None:
with self._lock:
self.counts["abandoned"] += 1
class Span(Protocol): # the two methods of an OpenTelemetry span we use
def set_attribute(self, key: str, value: Any, /) -> None: ...
def end(self) -> None: ...
class Tracer(Protocol): # opentelemetry.trace.Tracer, as far as we need it
def start_span(self, name: str, /) -> Span: ...
class OTelHook(Hook):
"""One span per call, with OpenTelemetry's GenAI attribute names (lesson 03.10, 4.7: still marked Development, so
the names can change). Pass `trace.get_tracer("my-app")`. No prompt or answer text goes on the span.
It is an observer: a broken tracer is logged and ignored (it must never stop a call), and the span is closed on
every path: success, failure and an abandoned stream. List it FIRST so the span covers the other hooks."""
def __init__(self, tracer: Tracer) -> None:
self.tracer, self._spans, self._lock = tracer, {}, threading.Lock()
def before(self, ctx: CallContext, req: Request) -> Request:
try:
span = self.tracer.start_span(f"chat {req.model}")
span.set_attribute("gen_ai.operation.name", "chat")
span.set_attribute("gen_ai.request.model", req.model) # the ALIAS; the served model is set at the end
with self._lock:
self._spans[ctx.call_id] = span
except Exception as exc: # an observer inside a fail-closed slot: contain it here
log.warning("OTelHook.before failed: %s", type(exc).__name__)
return req
def _finish(self, ctx: CallContext, attrs: dict[str, Any]) -> None:
with self._lock:
span = self._spans.pop(ctx.call_id, None)
if span is None:
return
for key, value in attrs.items():
if value is not None:
span.set_attribute(key, value)
span.end()
def after(self, ctx: CallContext, req: Request, resp: Response) -> Response:
u = resp.usage
self._finish(ctx, {"gen_ai.provider.name": resp.provider, "gen_ai.response.model": resp.resolved_model,
"gen_ai.response.id": resp.provider_response_id or resp.request_id, "gen_ai.response.finish_reasons": [resp.finish_reason.value],
"gen_ai.usage.input_tokens": u.total_input_tokens if u else None, # the semconv counts ALL input
"gen_ai.usage.output_tokens": u.output_tokens if u else None,
"gen_ai.usage.cache_read.input_tokens": u.cached_input_tokens if u else None})
return resp
def error(self, ctx: CallContext, req: Request, err: LLMError) -> None:
self._finish(ctx, {"error.type": type(err).__name__})
def abandoned(self, ctx: CallContext, req: Request, partial: Response) -> None:
self._finish(ctx, {"error.type": "Abandoned"})provider_agnostic/client.py#
"""provider_agnostic/client.py: the one place that owns retries, timeouts, fallback, cost and hooks.
client = LLMClient(Registry.load(), prices=PriceTable.load(), hooks=[LoggingHook()])
resp = client.complete(Request(model="fast", messages=[Message.user("Hi")]))
Reliability policy (lesson 03.8 explains each number): the SDK clients are built with max_retries=0, so THIS
file is the only retry layer. Fallback moves down the alias chain, after retries on the current model are
used up, and only for errors listed in Policy.fallback_on.
Thread safety: one LLMClient can be shared by threads and by tasks on one event loop (adapters are created under a lock,
the SDK clients are thread-safe). Hooks are synchronous: see hooks.py.
"""
from __future__ import annotations
import asyncio
import logging
import random
import threading
import time
import uuid
from collections.abc import AsyncIterator, Callable, Iterator
from dataclasses import dataclass, field
from typing import Any
from pydantic import ValidationError
from prices import PriceTable # lesson 03.7
from .adapters.anthropic_messages import AnthropicAdapter
from .adapters.base import Adapter, Opened, StreamParser, aclosing, closing
from .adapters.gemini_generate import GeminiGenerateAdapter
from .adapters.gemini_interactions import GeminiInteractionsAdapter
from .adapters.openai_chat import OpenAIChatAdapter
from .adapters.openai_responses import OpenAIResponsesAdapter
from .cost import price_usage
from .errors import (ConfigError, ConnectionFailed, HookError, LLMError, OutputInvalid, Overloaded, QuotaExceeded,
RateLimited, ServerError, Timeout, wrap)
from .hooks import CallContext, Hook
from .redact import redact_text
from .registry import ModelSpec, Registry, check_capabilities
from .types import (Attempt, Done, FinishReason, Message, ReasoningDelta, Request, Response, StreamEvent, TextDelta,
ToolCallDelta, ToolCallStart)
log = logging.getLogger("provider_agnostic")
ADAPTERS: dict[str, type[Adapter]] = {
"responses": OpenAIResponsesAdapter, "chat": OpenAIChatAdapter, "messages": AnthropicAdapter,
"generate_content": GeminiGenerateAdapter, "interactions": GeminiInteractionsAdapter,
}
@dataclass
class Policy:
"""Every number that decides how hard we try, in one place.
The defaults obey one rule, and a test pins it: a provider that HANGS must not be able to use up the deadline.
deadline_s >= (max_timeout_attempts + 1) * attempt_timeout_s
The primary may burn max_timeout_attempts full timeouts, and the next model still gets one whole attempt.
Change one of the three and change the others with it (with a three-model chain and two hung providers, the third
gets only what is left: lower attempt_timeout_s, or raise deadline_s)."""
max_attempts: int = 3 # per model: the first try plus two retries (for errors that come back FAST)
max_timeout_attempts: int = 2 # per model: a timeout cost a whole attempt_timeout_s, so retry it once, then move on
attempt_timeout_s: float = 30.0 # one HTTP attempt (lesson 03.8, Part 6 for per-use-case values)
deadline_s: float = 120.0 # the whole call: waits and fallbacks included
base_s: float = 0.5 # full-jitter backoff: uniform(0, min(cap, base * 2**n))
cap_s: float = 8.0
max_server_wait_s: float = 20.0 # a Retry-After longer than this: stop retrying THIS model
# Errors that move us to the NEXT model once retries on this one are used up. Quota is here because
# retrying the same account can never help, while another provider can. Not here, on purpose:
# BadRequest (a bug), ContextTooLong (that is a cascade, Module 11B), Refused/ContentBlocked (a choice).
fallback_on: tuple[type[LLMError], ...] = (RateLimited, Overloaded, ServerError, Timeout, ConnectionFailed,
QuotaExceeded)
# Finish reasons that also trigger fallback. Empty by default: a refusal may be the right answer.
fallback_on_finish: frozenset[FinishReason] = frozenset()
def _is_content(ev: StreamEvent) -> bool:
"""Content = anything the caller's UI could draw: answer text, REASONING TEXT, or a tool call starting.
An empty reasoning delta draws nothing (Claude 5.x opens a thinking block with one), so it is not content."""
if isinstance(ev, ReasoningDelta):
return bool(ev.text)
return isinstance(ev, (TextDelta, ToolCallStart, ToolCallDelta))
@dataclass
class _Run:
"""The state of ONE call across retries and fallbacks, shared by the sync and async code paths."""
client: "LLMClient"
req: Request
ctx: CallContext
chain: list[ModelSpec]
attempts: list[Attempt] = field(default_factory=list)
model_idx: int = 0
attempt_no: int = 0
timeouts: int = 0 # timeouts on the CURRENT model
@property
def spec(self) -> ModelSpec:
return self.chain[self.model_idx]
def remaining(self) -> float:
return self.client.policy.deadline_s - (self.client.clock() - self.ctx.started)
def timeout(self) -> float:
cap = self.req.timeout_s or self.client.policy.attempt_timeout_s
return max(0.1, min(cap, self.remaining()))
def record(self, *, ok: bool, started: float, err: LLMError | None = None, resp: Response | None = None,
error_type: str | None = None) -> Attempt:
self.attempt_no += 1
if isinstance(err, Timeout):
self.timeouts += 1
cost = price_usage(resp.usage, self.spec, self.client.prices) if resp is not None else None
a = Attempt(model_key=self.spec.key, provider=self.spec.provider, api=self.spec.api, n=self.attempt_no,
ok=ok, error_type=error_type or (type(err).__name__ if err else None),
status=err.status if err else None,
request_id=(err.request_id if err else (resp.request_id if resp else None)),
latency_ms=round((self.client.clock() - started) * 1000),
usage=resp.usage if resp is not None else None, cost_usd=cost.usd if cost else None)
self.attempts.append(a)
self.client._fire("attempt", self.ctx, a)
return a
def decide(self, err: LLMError) -> tuple[str, float]:
"""After a failed attempt: ('retry', wait_s) | ('next', 0) | ('raise', 0)."""
p = self.client.policy
wait = self._wait(err)
can_retry = (err.retryable and self.attempt_no < p.max_attempts and wait is not None
and self.remaining() > wait + 0.1)
if isinstance(err, Timeout): # a hang costs a whole attempt_timeout_s: do not spend the deadline on one model
can_retry = can_retry and self.timeouts < p.max_timeout_attempts
if can_retry and wait is not None:
return "retry", wait
if isinstance(err, p.fallback_on) and self.model_idx + 1 < len(self.chain) and self.remaining() > 0.2:
return "next", 0.0
return "raise", 0.0
def _wait(self, err: LLMError) -> float | None:
p = self.client.policy
if err.retry_after_s is not None:
return None if err.retry_after_s > p.max_server_wait_s else err.retry_after_s + self.client.rng.uniform(0, 0.25)
return self.client.rng.uniform(0, min(p.cap_s, p.base_s * 2 ** (self.attempt_no - 1)))
def advance(self) -> None:
self.model_idx += 1
self.attempt_no = 0
self.timeouts = 0
class _StreamAttempt:
"""One streaming attempt: feeds raw events to the parser and applies the commit rule (lesson 03.11, 5.1).
Events that draw nothing are held back until the first CONTENT event commits the stream, so a retry before that
point never shows the consumer half of a discarded attempt."""
def __init__(self, parser: StreamParser) -> None:
self.parser, self.pending, self.committed = parser, [], False
def feed(self, raw: Any) -> list[StreamEvent]:
if isinstance(raw, Opened): # the HTTP headers: the provider's request ID
self.parser.b.request_id = raw.request_id
return []
out: list[StreamEvent] = []
for ev in self.parser.feed(raw):
if self.committed:
out.append(ev)
elif _is_content(ev):
self.committed = True
out += [*self.pending, ev]
self.pending = []
else:
self.pending.append(ev)
return out
def finish(self, provider: str) -> Response:
if not self.parser.b.ended: # a body that just stops is not an answer
raise ServerError("the stream ended without a terminal event", provider=provider)
return self.parser.finish()
def flush(self) -> list[StreamEvent]:
out, self.pending = self.pending, []
return out
class LLMClient:
def __init__(self, registry: Registry, *, prices: PriceTable | None = None, hooks: list[Hook] | None = None,
policy: Policy | None = None, http_clients: dict[str, dict[str, Any]] | None = None,
sleep: Callable[[float], None] = time.sleep, asleep: Callable[[float], Any] = asyncio.sleep,
clock: Callable[[], float] = time.monotonic, rng: random.Random | None = None) -> None:
self.registry, self.prices, self.hooks = registry, prices, list(hooks or [])
self.policy = policy or Policy()
self.http_clients = http_clients or {} # model key -> {"sync": httpx2.Client, "async": ...}: mock transports
self.sleep, self.asleep, self.clock, self.rng = sleep, asleep, clock, rng or random.Random()
self._adapters: dict[str, Adapter] = {}
self._lock = threading.Lock()
# ---- plumbing --------------------------------------------------------------------------
def adapter(self, spec: ModelSpec) -> Adapter:
"""One adapter per registry entry, created on first use and then reused (SDK clients pool connections).
Created under a lock: two threads racing here would build two SDK clients and leak one."""
with self._lock:
if spec.key not in self._adapters:
cls = ADAPTERS.get(spec.api)
if cls is None:
raise ConfigError(f"{spec.key}: no adapter for api {spec.api!r}")
inj = self.http_clients.get(spec.key, {})
self._adapters[spec.key] = cls(spec, http_client=inj.get("sync"), async_http_client=inj.get("async"))
return self._adapters[spec.key]
def preflight(self, alias: str) -> None:
"""Check the WHOLE chain's credentials now (at startup, in a health check): a fallback whose key is missing
would otherwise be discovered in the middle of the outage it was meant to cover. Raises ConfigError."""
missing = self.registry.missing_credentials(alias)
if missing:
raise ConfigError(f"{alias!r} cannot run: set {', '.join(missing)}")
def _fire(self, name: str, *args: Any) -> None:
"""Observers: a broken one is contained. Log the hook, the method and the exception TYPE only: the message and
the traceback can contain the very text the hook choked on (a prompt, a card number)."""
for h in self.hooks:
try:
getattr(h, name)(*args)
except Exception as exc:
log.warning("observer hook %s.%s failed: %s", type(h).__name__, name, type(exc).__name__)
def _start(self, req: Request) -> _Run:
ctx = CallContext(call_id=uuid.uuid4().hex[:16], alias=req.model, started=self.clock(),
tags={k: redact_text(v) for k, v in req.metadata.items()})
original = req
for h in self.hooks: # request middleware, in order: FAIL-CLOSED
try:
req = h.before(ctx, req)
except LLMError as err: # the hook chose its own error (a budget gate: QuotaExceeded)
raise self._fail_before(ctx, original, err) from None
except Exception as exc: # a bug in the hook: stop the call, never send the original
err = HookError(f"hook {type(h).__name__}.before raised {type(exc).__name__}: nothing was sent",
code="hook_failed")
raise self._fail_before(ctx, original, err) from exc
self.preflight(req.model) # every key the chain needs, before the first request
chain = self.registry.chain(req.model)
for spec in chain: # check the WHOLE chain up front: no half-working fallbacks
check_capabilities(req, spec)
return _Run(self, req, ctx, chain)
def _fail_before(self, ctx: CallContext, req: Request, err: LLMError) -> LLMError:
self._fire("error", ctx, req, err)
return err
def _stamp(self, run: _Run, resp: Response, spec: ModelSpec) -> Response:
"""The fields the client adds to every response: who served it, our IDs, latency, attempts, cost."""
resp.model_key, resp.requested_model, resp.call_id = spec.key, run.req.model, run.ctx.call_id
resp.latency_ms = round((self.clock() - run.ctx.started) * 1000)
resp.attempts = list(run.attempts)
resp.cost = price_usage(resp.usage, spec, self.prices)
return resp
def _finish(self, run: _Run, resp: Response, spec: ModelSpec) -> Response:
"""Everything that happens to a successful response, identically for sync, async and streams."""
self._stamp(run, resp, spec)
schema = run.req.output_schema
if schema is not None and resp.finish_reason is FinishReason.STOP:
try:
resp.parsed = schema.model_validate_json(resp.text)
except ValidationError as exc:
err = OutputInvalid(f"reply did not match {schema.__name__}: {exc.errors()[0]['msg']}",
provider=spec.provider, request_id=resp.request_id)
err.response = resp # the reply was PAID FOR: keep its text, usage and cost reachable
raise err from exc
for h in self.hooks: # response middleware
try:
resp = h.after(run.ctx, run.req, resp)
except Exception as exc:
if not h.fail_closed: # an observer: contain it
log.warning("observer hook %s.after failed: %s", type(h).__name__, type(exc).__name__)
continue
err = exc if isinstance(exc, LLMError) else HookError(
f"hook {type(h).__name__}.after raised {type(exc).__name__}: the response was withheld", code="hook_failed")
err.response = err.response or resp # billed, so it stays visible to the error hooks
raise err from (None if err is exc else exc)
return resp
def _finalize(self, run: _Run, resp: Response, spec: ModelSpec) -> Response:
try:
return self._finish(run, resp, spec)
except LLMError as err: # OutputInvalid or a fail-closed after(): the error hooks must see it
raise self._fail(run, err)
def _fail(self, run: _Run, err: LLMError) -> LLMError:
err.attempts = list(run.attempts)
for paid in (err.partial, err.response): # a broken stream or a rejected reply still cost something
if paid is not None and paid.cost is None:
self._stamp(run, paid, run.spec)
self._fire("error", run.ctx, run.req, err)
return err
def _bad_finish(self, run: _Run, resp: Response) -> bool:
return resp.finish_reason in self.policy.fallback_on_finish and run.model_idx + 1 < len(run.chain)
def _abandon(self, run: _Run, state: _StreamAttempt, started: float) -> None:
"""The consumer stopped reading (break, aclose(), a cancelled task): the provider still bills what it generated.
Record the partial usage, if the provider reported any, so the cancelled stream is not invisible."""
partial = self._stamp(run, state.parser.finish(), run.spec)
run.record(ok=False, started=started, resp=partial, error_type="Abandoned")
partial.attempts = list(run.attempts)
self._fire("abandoned", run.ctx, run.req, partial)
# ---- sync ------------------------------------------------------------------------------
def complete(self, req: Request) -> Response:
run = self._start(req)
while True:
spec, ad = run.spec, self.adapter(run.spec)
started = self.clock()
try:
params = ad.build(run.req)
resp = ad.parse(ad.send(params, run.timeout()))
except Exception as exc:
err = exc if isinstance(exc, LLMError) else wrap(exc, spec.provider)
run.record(ok=False, started=started, err=err)
action, wait = run.decide(err)
if action == "retry":
self.sleep(wait)
continue
if action == "next":
run.advance()
continue
raise self._fail(run, err) from (exc if err is not exc else None) # SDK exception stays as __cause__
if self._bad_finish(run, resp): # discarded for the next model: still billed, still on the record
run.record(ok=False, started=started, resp=resp, error_type=f"FinishFallback:{resp.finish_reason.value}")
run.advance()
continue
run.record(ok=True, started=started, resp=resp)
return self._finalize(run, resp, spec)
def ask(self, model: str, prompt: str, **kwargs: Any) -> Response:
"""The shortest useful call: one user message."""
return self.complete(Request(model=model, messages=[Message.user(prompt)], **kwargs))
def stream(self, req: Request) -> Iterator[StreamEvent]:
"""Yields canonical events, ending with Done(response). Retries and fallback happen only BEFORE the first
content event reaches you: after that, silently switching models would mix two answers (lesson 03.3, 7.5).
Close the generator early (break, `with contextlib.closing(...)`) and the abandoned hook fires."""
run = self._start(req)
state: _StreamAttempt | None = None
started, done = self.clock(), False
try:
while True:
spec, ad = run.spec, self.adapter(run.spec)
started, state = self.clock(), _StreamAttempt(ad.new_stream())
try:
with closing(ad.open_stream(ad.build(run.req), run.timeout())) as raw_events:
for raw in raw_events:
yield from state.feed(raw)
resp = state.finish(spec.provider)
except Exception as exc:
err = exc if isinstance(exc, LLMError) else wrap(exc, spec.provider)
run.record(ok=False, started=started, err=err)
action, wait = run.decide(err)
if state.committed or action == "raise":
err.partial = state.parser.finish() # what arrived before it broke (usage may be None)
raise self._fail(run, err) from (exc if err is not exc else None)
if action == "retry":
self.sleep(wait)
else:
run.advance()
continue
run.record(ok=True, started=started, resp=resp)
yield from state.flush()
done = True # from here on the response is complete
yield Done(response=self._finalize(run, resp, spec))
return
except GeneratorExit: # the consumer walked away
if state is not None and not done:
self._abandon(run, state, started)
raise
# ---- async -----------------------------------------------------------------------------
async def acomplete(self, req: Request) -> Response:
run = self._start(req)
while True:
spec, ad = run.spec, self.adapter(run.spec)
started = self.clock()
try:
params = ad.build(run.req)
resp = ad.parse(await ad.asend(params, run.timeout()))
except Exception as exc:
err = exc if isinstance(exc, LLMError) else wrap(exc, spec.provider)
run.record(ok=False, started=started, err=err)
action, wait = run.decide(err)
if action == "retry":
await self.asleep(wait)
continue
if action == "next":
run.advance()
continue
raise self._fail(run, err) from (exc if err is not exc else None)
if self._bad_finish(run, resp):
run.record(ok=False, started=started, resp=resp, error_type=f"FinishFallback:{resp.finish_reason.value}")
run.advance()
continue
run.record(ok=True, started=started, resp=resp)
return self._finalize(run, resp, spec)
async def astream(self, req: Request) -> AsyncIterator[StreamEvent]:
"""The async twin of stream(). Cancelling the task or calling aclose() fires the abandoned hook."""
run = self._start(req)
state: _StreamAttempt | None = None
started, done = self.clock(), False
try:
while True:
spec, ad = run.spec, self.adapter(run.spec)
started, state = self.clock(), _StreamAttempt(ad.new_stream())
try:
async with aclosing(ad.aopen_stream(ad.build(run.req), run.timeout())) as raw_events:
async for raw in raw_events:
for ev in state.feed(raw):
yield ev
resp = state.finish(spec.provider)
except Exception as exc:
err = exc if isinstance(exc, LLMError) else wrap(exc, spec.provider)
run.record(ok=False, started=started, err=err)
action, wait = run.decide(err)
if state.committed or action == "raise":
err.partial = state.parser.finish()
raise self._fail(run, err) from (exc if err is not exc else None)
if action == "retry":
await self.asleep(wait)
else:
run.advance()
continue
run.record(ok=True, started=started, resp=resp)
for ev in state.flush():
yield ev
done = True
yield Done(response=self._finalize(run, resp, spec))
return
except (GeneratorExit, asyncio.CancelledError):
if state is not None and not done:
self._abandon(run, state, started)
raise
# ---- lifecycle -------------------------------------------------------------------------
def close(self) -> None:
for ad in self._adapters.values():
ad.close()
async def aclose(self) -> None:
for ad in self._adapters.values():
await ad.aclose()
ad.close()
def __enter__(self) -> "LLMClient":
return self
def __exit__(self, *exc: object) -> None:
self.close()
async def __aenter__(self) -> "LLMClient":
return self
async def __aexit__(self, *exc: object) -> None:
await self.aclose()provider_agnostic/refresh.py#
"""provider_agnostic/refresh.py: audit models.yaml against the providers' Models APIs (lesson 03.1, Part 10; 03.11, Part 7).
uv run python -m provider_agnostic.refresh # prints findings; exit code 1 if anything needs a human
Run it from CI on a schedule, not on every request. It never edits the registry: a person reviews the diff.
"""
from __future__ import annotations
import datetime as dt
import os
import sys
from dataclasses import dataclass
from typing import Literal
from dotenv import load_dotenv
from .registry import ModelSpec, Registry
@dataclass
class Live:
"""What a provider's Models API says about one model (None = the API doesn't say)."""
context_window: int | None = None
max_output_tokens: int | None = None
retires_at: str | None = None
@dataclass
class Finding:
level: Literal["error", "warn", "info"]
key: str
message: str
def fetch_live(provider: str) -> dict[str, Live] | None:
"""Layer 4: one list call per provider. Returns None when its key is not set."""
if provider == "openai" and os.getenv("OPENAI_API_KEY"):
from openai import OpenAI
return {m.id: Live(retires_at=getattr(m, "shutdown_date", None) and str(m.shutdown_date))
for m in OpenAI().models.list()}
if provider == "anthropic" and os.getenv("ANTHROPIC_API_KEY"):
import anthropic
return {m.id: Live(m.max_input_tokens, m.max_tokens, m.retires_at.isoformat() if m.retires_at else None)
for m in anthropic.Anthropic().models.list(limit=1000)}
if provider == "gemini" and os.getenv("GEMINI_API_KEY"):
from google import genai
client = genai.Client()
out = {(m.name or "").removeprefix("models/"): Live(m.input_token_limit, m.output_token_limit)
for m in client.models.list(config={"page_size": 100})}
client.close()
return out
if provider == "openrouter": # the catalogue is public: no key needed
from openai import OpenAI
from openai.types import Model
models: list[Model] = list(OpenAI(base_url="https://openrouter.ai/api/v1", api_key="none").models.list())
return {m.id: Live((m.model_extra or {}).get("context_length")) for m in models}
return None
def audit(registry: Registry, live: dict[str, dict[str, Live] | None], today: dt.date | None = None) -> list[Finding]:
"""Layer 1: pure comparison, so it is unit-tested with fixtures."""
today = today or dt.date.today()
findings: list[Finding] = []
for spec in registry.models.values():
if spec.free:
continue
models = live.get(spec.provider)
if models is None:
findings.append(Finding("info", spec.key, f"{spec.provider}: no key (or no listing API), not checked"))
continue
info = models.get(spec.model)
if info is None:
findings.append(Finding("error", spec.key, f"{spec.model!r} is not in {spec.provider}'s model list "
"(renamed, retired, or not enabled for this account)"))
continue
findings += _compare(spec, info, today)
return findings
def _compare(spec: ModelSpec, info: Live, today: dt.date) -> list[Finding]:
out: list[Finding] = []
if info.retires_at:
days = (dt.date.fromisoformat(info.retires_at[:10]) - today).days
out.append(Finding("error" if days < 30 else "warn", spec.key, f"retires {info.retires_at[:10]} ({days} days)"))
for field, ours, theirs in (("context_window", spec.context_window, info.context_window),
("max_output_tokens", spec.max_output_tokens, info.max_output_tokens)):
if ours and theirs and ours != theirs:
out.append(Finding("warn", spec.key, f"{field}: registry says {ours:,}, provider says {theirs:,}"))
return out
def main() -> int:
load_dotenv()
registry = Registry.load()
live: dict[str, dict[str, Live] | None] = {}
failures: list[Finding] = []
for provider in sorted({s.provider for s in registry.models.values()}):
try:
live[provider] = fetch_live(provider)
except Exception as exc: # an audit must not crash because one API is down
live[provider] = None
failures.append(Finding("warn", provider, f"listing failed: {type(exc).__name__}: {str(exc)[:80]}"))
findings = failures + audit(registry, live)
for f in findings:
print(f"{f.level.upper():5s} {f.key:12s} {f.message}")
if not any(f.level != "info" for f in findings):
print("registry matches the providers' model lists")
return 1 if any(f.level == "error" for f in findings) else 0
if __name__ == "__main__":
sys.exit(main())provider_agnostic/adapters/base.py#
"""provider_agnostic/adapters/base.py: what every adapter must provide, plus the pieces they share.
An adapter is split in two on purpose:
* PURE translation (no network): build() canonical Request -> SDK keyword arguments,
parse() SDK response -> canonical Response, and a StreamParser that turns the provider's
stream events into canonical StreamEvents. These are what the contract tests and the
"show the wire" demos call, so they need no mock server and no key.
* THIN I/O: send / asend / open_stream / aopen_stream, a line or two each, owned by one SDK.
"""
from __future__ import annotations
import contextlib
import json
from abc import ABC, abstractmethod
from collections.abc import AsyncIterator, Callable, Iterator, Mapping
from dataclasses import dataclass
from typing import Any
import cost_calc # lesson 03.7: the ONE place that normalizes usage
from ..cost import usage_from_cost_calc
from ..errors import UnsupportedFeature
from ..registry import ModelSpec, resolve_api_key, resolve_headers, resolved_base_url
from ..types import (FinishReason, Native, Part, ReasoningDelta, ReasoningPart, Request, Response, StreamEvent,
TextDelta, TextPart, ToolCallDelta, ToolCallPart, ToolCallStart, Usage, UsageEvent)
@dataclass(frozen=True)
class Opened:
"""The first item every `open_stream()` yields: what the HTTP response HEADERS said, before any event.
Streams used to report the body's object ID (`msg_...`) where `complete()` reported the request ID header,
so the same field meant two things. Now both carry the header when the provider sends one."""
request_id: str | None
def request_id_from(headers: Mapping[str, str] | None) -> str | None:
"""The ID a support ticket needs: x-request-id (OpenAI), request-id (Anthropic), x-generation-id (OpenRouter)."""
lower = {k.lower(): v for k, v in (headers or {}).items()}
return lower.get("x-request-id") or lower.get("request-id") or lower.get("x-generation-id")
@contextlib.contextmanager
def closing(iterator: Any) -> Iterator[Any]:
"""Close a stream iterator when we leave the block, EVEN on an early exit. SDKs type their streams as plain
`Iterator`s although at runtime they are generators with a close(): call it when it is there."""
try:
yield iterator
finally:
if (close := getattr(iterator, "close", None)) is not None:
close()
@contextlib.asynccontextmanager
async def aclosing(iterator: Any) -> AsyncIterator[Any]:
try:
yield iterator
finally:
if (aclose := getattr(iterator, "aclose", None)) is not None:
await aclose()
def usage_or_none(build: Callable[[], cost_calc.Usage]) -> Usage | None:
"""Usage by lesson 03.7's `cost_calc.from_*`, converted to the canonical type. A ValueError (no usage in the
response, or a service tier with no per-token price) means UNKNOWN: None, never a guessed or zero number."""
try:
return usage_from_cost_calc(build())
except ValueError:
return None
RESERVED_EXTRA = {"model", "messages", "input", "contents", "stream"}
def deep_merge(base: dict[str, Any], extra: Mapping[str, Any]) -> dict[str, Any]:
"""`extra` merged INTO what the adapter built: nested dicts merge, anything else is replaced by `extra`.
A shallow `{**params, **extra}` let extra={"output_config": {"effort": "max"}} silently delete the structured-output
`format` the adapter had just put in the same dict."""
out = dict(base)
for key, value in extra.items():
out[key] = deep_merge(out[key], value) if isinstance(out.get(key), dict) and isinstance(value, Mapping) else value
return out
def apply_extra(params: dict[str, Any], req: Request, provider: str, reserved: set[str] = RESERVED_EXTRA) -> dict[str, Any]:
"""The escape hatch: Request.extra[<provider name>], merged, but never allowed to replace the model, the
messages or the stream flag (that would change what the caller asked for without a word)."""
extra = req.extra.get(provider, {})
clash = sorted(reserved & extra.keys())
if clash:
raise UnsupportedFeature(f"Request.extra[{provider!r}] may not set {clash}: use the Request fields", provider=provider)
return deep_merge(params, extra)
def error_result_text(content: str) -> str:
"""OpenAI has no `is_error` marker on a tool result (lesson 03.5, 7.4): the text must say so. A visible, documented
translation, applied only when the caller flagged an error and did not already say so."""
return content if content.lower().startswith("error") else f"Error: {content}"
class Adapter(ABC):
api: str # "responses" | "chat" | "messages" | ...
def __init__(self, spec: ModelSpec, *, http_client: Any = None, async_http_client: Any = None) -> None:
self.spec = spec
self._http_client, self._async_http_client = http_client, async_http_client # for mock transports
self._client: Any = None
self._aclient: Any = None
def sdk_kwargs(self) -> dict[str, Any]:
"""Constructor arguments shared by the openai and anthropic clients. max_retries=0: the wrapper's
client owns retries, so an outage is not multiplied by the SDK's own loop (lesson 03.8, 5.5)."""
return {"api_key": resolve_api_key(self.spec), "base_url": resolved_base_url(self.spec), "max_retries": 0,
"default_headers": resolve_headers(self.spec)}
# ---- pure translation -------------------------------------------------------------------
@abstractmethod
def build(self, req: Request) -> dict[str, Any]:
"""Canonical request -> keyword arguments for the SDK call (stream flag not included)."""
@abstractmethod
def parse(self, raw: Any) -> Response:
"""The SDK's response object -> canonical Response (no cost, latency or attempts yet)."""
@abstractmethod
def new_stream(self) -> "StreamParser":
"""A fresh state machine for one streamed response."""
# ---- thin I/O ---------------------------------------------------------------------------
@abstractmethod
def send(self, params: dict[str, Any], timeout_s: float) -> Any: ...
@abstractmethod
async def asend(self, params: dict[str, Any], timeout_s: float) -> Any: ...
@abstractmethod
def open_stream(self, params: dict[str, Any], timeout_s: float) -> Iterator[Any]: ...
@abstractmethod
def aopen_stream(self, params: dict[str, Any], timeout_s: float) -> AsyncIterator[Any]: ...
def close(self) -> None:
"""Close the SDK clients (sync only; await aclose() for async)."""
if self._client is not None and hasattr(self._client, "close"):
self._client.close()
async def aclose(self) -> None:
if self._aclient is not None and hasattr(self._aclient, "close"):
await self._aclient.close()
class StreamParser(ABC):
"""feed() every raw provider event; finish() once the stream ended. Never raises on unknown events."""
def __init__(self, spec: ModelSpec, api: str) -> None:
self.spec, self.api = spec, api
self.b = Builder()
@abstractmethod
def feed(self, event: Any) -> list[StreamEvent]: ...
def finish(self) -> Response:
return self.b.to_response(provider=self.spec.provider, api=self.api)
class Builder:
"""Assembles the final Response from stream pieces. Handles the traps from lesson 03.3, Part 5:
blocks keyed by index (interleaved text and tool calls), tool arguments as JSON FRAGMENTS parsed once,
finish reason overwritten (never appended), usage replaced (never summed), None = unknown."""
def __init__(self) -> None:
self.blocks: dict[Any, dict[str, Any]] = {}
self.finish_reason: FinishReason | None = None
self.raw_finish_reason: str | None = None
self.usage: Usage | None = None
self.request_id: str | None = None # the HTTP header ID when the provider sends one, else the body ID
self.response_id: str | None = None # the body's own ID (resp_..., msg_..., chatcmpl-...)
self.resolved_model: str | None = None
@property
def ended(self) -> bool:
"""Did the stream reach its terminal event? A stream that just stops is NOT a finished answer."""
return self.finish_reason is not None
def _block(self, key: Any, kind: str) -> dict[str, Any]:
return self.blocks.setdefault(key, {"kind": kind, "text": "", "args": "", "id": None, "name": None,
"native": None})
def text(self, key: Any, s: str) -> TextDelta:
self._block(key, "text")["text"] += s
return TextDelta(text=s)
def reasoning(self, key: Any, s: str) -> ReasoningDelta:
self._block(key, "reasoning")["text"] += s
return ReasoningDelta(text=s)
def tool_start(self, key: Any, call_id: str, name: str, index: int) -> ToolCallStart:
blk = self._block(key, "tool")
blk["id"], blk["name"] = call_id, name
return ToolCallStart(index=index, id=call_id, name=name)
def tool_args(self, key: Any, fragment: str, index: int) -> ToolCallDelta:
self._block(key, "tool")["args"] += fragment
return ToolCallDelta(index=index, arguments_fragment=fragment)
def native(self, key: Any, native: Any, kind: str = "reasoning") -> None:
self._block(key, kind)["native"] = native # the provider's own item, kept for replay
def set_usage(self, usage: Usage) -> UsageEvent:
self.usage = usage # replace, never add: providers send cumulative numbers
return UsageEvent(usage=usage)
def to_response(self, *, provider: str, api: str) -> Response:
parts: list[Part] = []
for key in sorted(self.blocks, key=_order_key):
blk = self.blocks[key]
if blk["kind"] == "text" and blk["text"]:
parts.append(TextPart(text=blk["text"], native=blk["native"]))
elif blk["kind"] == "reasoning":
parts.append(ReasoningPart(text=blk["text"] or None, native=blk["native"]))
elif blk["kind"] == "tool":
args, err = parse_arguments(blk["args"])
native = blk["native"]
if err and native is None: # keep what the model really said: it is replayed, not rewritten
native = Native(provider=provider, api=api, payload={"arguments": blk["args"]})
parts.append(ToolCallPart(id=blk["id"] or "", name=blk["name"] or "", arguments=args,
arguments_error=err, native=native))
# finish_reason None means the stream never reached its terminal event: say so, loudly
finish = self.finish_reason or FinishReason.ERROR
raw = self.raw_finish_reason if self.finish_reason else "stream ended without a terminal event"
return Response(parts=parts, finish_reason=finish, raw_finish_reason=raw, usage=self.usage,
provider=provider, api=api, resolved_model=self.resolved_model,
request_id=self.request_id or self.response_id, provider_response_id=self.response_id)
def _order_key(key: Any) -> tuple[int, int]:
"""Blocks keyed by an integer index (Responses, Anthropic, Interactions) sort by it. The named blocks of the Chat and
`generate_content` streams ("r", "t", ("call", n)) keep the order they were OPENED in (`sorted` is stable): sorting
their names as text put every tool call before the reasoning and text, and call 10 before call 2."""
return (0, key) if isinstance(key, int) else (1, 0)
def parse_arguments(raw: str | dict[str, Any] | None) -> tuple[dict[str, Any], str | None]:
"""Tool arguments -> (dict, error). OpenAI-style JSON strings are parsed here, once, for everyone.
An empty string is legal for a tool with no parameters. Invalid JSON is reported, not raised:
the caller decides (usually: send the error back to the model as a tool result)."""
if isinstance(raw, dict):
return raw, None
if raw is None or not raw.strip():
return {}, None
try:
value = json.loads(raw)
except json.JSONDecodeError as exc:
return {}, f"invalid JSON arguments ({exc.msg} at char {exc.pos})"
return (value, None) if isinstance(value, dict) else ({}, "arguments JSON is not an object")
def data_url(media_type: str, data_b64: str) -> str:
return f"data:{media_type};base64,{data_b64}"provider_agnostic/adapters/openai_responses.py#
"""provider_agnostic/adapters/openai_responses.py: OpenAI Responses API (and Ollama's /v1/responses).
Message shapes: lesson 03.2. Streaming events: 03.3. Tool items: 03.5. Media parts: 03.6.
"""
from __future__ import annotations
import json
from collections.abc import AsyncIterator, Iterator
from typing import Any
import cost_calc # lesson 03.7
import openai
from ..errors import LLMError, error_from_failed, raise_if_failed
from ..registry import ModelSpec
from ..schemas import openai_strict, schema_name
from ..types import (DocumentPart, FinishReason, ForcedTool, ImagePart, Native, Part, ReasoningPart, Request, Response,
StreamEvent, TextPart, ToolCallPart, ToolResultPart)
from .base import (Adapter, Opened, StreamParser, apply_extra, data_url, error_result_text, parse_arguments,
request_id_from, usage_or_none)
class OpenAIResponsesAdapter(Adapter):
api = "responses"
# ---- clients: created once, reused, max_retries=0 because the wrapper owns retries -------
def _make(self, cls: type, http_client: Any) -> Any:
return cls(**self.sdk_kwargs(), http_client=http_client)
@property
def client(self) -> openai.OpenAI:
if self._client is None:
self._client = self._make(openai.OpenAI, self._http_client)
return self._client
@property
def aclient(self) -> openai.AsyncOpenAI:
if self._aclient is None:
self._aclient = self._make(openai.AsyncOpenAI, self._async_http_client)
return self._aclient
# ---- request ---------------------------------------------------------------------------
def build(self, req: Request) -> dict[str, Any]:
spec = self.spec
params: dict[str, Any] = {
"model": spec.model,
"input": self._input_items(req),
"max_output_tokens": req.max_output_tokens or spec.default_max_output_tokens,
"store": False, # stateless: we re-send history (lesson 03.2)
}
if req.system:
params["instructions"] = req.system
if req.tools:
params["tools"] = [{"type": "function", "name": t.name, "description": t.description,
"parameters": openai_strict(t.parameters) if t.strict else t.parameters,
"strict": t.strict} for t in req.tools]
params["tool_choice"] = self._tool_choice(req)
if req.parallel_tool_calls is not None:
params["parallel_tool_calls"] = req.parallel_tool_calls
if req.output_schema is not None:
params["text"] = {"format": {"type": "json_schema", "name": schema_name(req.output_schema),
"schema": openai_strict(req.output_schema), "strict": True}}
if spec.capabilities.reasoning:
effort = spec.reasoning_off if req.reasoning_effort == "off" else req.reasoning_effort
if effort:
params["reasoning"] = {"effort": effort}
# store=False means the server keeps nothing: ask for the encrypted reasoning so we can replay it
params["include"] = ["reasoning.encrypted_content"]
return apply_extra(params, req, spec.provider) # the escape hatch, keyed by provider, deep-merged
@staticmethod
def _tool_choice(req: Request) -> Any:
tc = req.tool_choice
if isinstance(tc, ForcedTool):
return {"type": "function", "name": tc.name}
return tc # "auto" | "required" | "none"
def _native(self, part: Part) -> dict[str, Any] | None:
n = part.native
return n.payload if n and n.provider == self.spec.provider and n.api == self.api else None
def _input_items(self, req: Request) -> list[dict[str, Any]]:
items: list[dict[str, Any]] = []
for m in req.messages:
if m.role == "user":
content: list[dict[str, Any]] = []
for p in m.parts:
if isinstance(p, TextPart):
if p.text: # an empty text part is a 400 on some APIs: omit it
content.append({"type": "input_text", "text": p.text})
elif isinstance(p, ImagePart):
url = p.url if p.url and not p.data_b64 else data_url(p.media_type, p.data_b64 or "")
content.append({"type": "input_image", "image_url": url, "detail": p.detail})
elif isinstance(p, DocumentPart):
content.append({"type": "input_file", "filename": p.filename,
"file_data": data_url(p.media_type, p.data_b64)})
if content:
items.append({"role": "user", "content": content})
elif m.role == "assistant":
text_buf: list[str] = []
def flush() -> None:
if any(text_buf): # a tool-only or reasoning-only turn has no text item
items.append({"role": "assistant", "content": "".join(text_buf)})
text_buf.clear()
for p in m.parts:
if isinstance(p, TextPart):
text_buf.append(p.text)
elif isinstance(p, ReasoningPart):
flush()
if (native := self._native(p)) is not None: # only OUR reasoning can be replayed
items.append(native)
elif isinstance(p, ToolCallPart):
flush()
items.append(self._native(p) or {"type": "function_call", "call_id": p.id,
"name": p.name, "arguments": json.dumps(p.arguments)})
flush()
else: # role == "tool"
for p in m.parts:
if isinstance(p, ToolResultPart):
items.append({"type": "function_call_output", "call_id": p.call_id,
"output": error_result_text(p.content) if p.is_error else p.content}) # no is_error field here
return items
# ---- response --------------------------------------------------------------------------
def parse(self, raw: Any) -> Response:
request_id = getattr(raw, "_request_id", None)
raise_if_failed(raw, self.spec.provider, request_id or raw.id) # HTTP 200 + status "failed" is an ERROR, not a Response
parts: list[Part] = []
refusal = False
for item in raw.output:
if item.type == "message":
for c in item.content:
if c.type == "output_text":
parts.append(TextPart(text=c.text))
elif c.type == "refusal":
refusal = True
parts.append(TextPart(text=c.refusal))
elif item.type == "function_call":
args, err = parse_arguments(item.arguments)
parts.append(ToolCallPart(id=item.call_id, name=item.name, arguments=args, arguments_error=err,
native=Native(provider=self.spec.provider, api=self.api,
payload=item.model_dump(exclude_none=True))))
elif item.type == "reasoning":
summary = "\n".join(s.text for s in item.summary or [])
parts.append(ReasoningPart(text=summary or None,
native=Native(provider=self.spec.provider, api=self.api,
payload=item.model_dump(exclude_none=True))))
finish, raw_finish = self._finish(raw, refusal)
return Response(parts=parts, finish_reason=finish, raw_finish_reason=raw_finish,
usage=usage_or_none(lambda: cost_calc.from_openai_response(raw)), provider=self.spec.provider,
api=self.api, resolved_model=raw.model, request_id=request_id or raw.id,
provider_response_id=raw.id, raw=raw)
@staticmethod
def _finish(raw: Any, refusal: bool) -> tuple[FinishReason, str]:
status = raw.status
reason = raw.incomplete_details.reason if raw.incomplete_details else None
shown = f"{status}:{reason}" if reason else str(status)
if refusal:
return FinishReason.REFUSAL, shown
if status == "incomplete":
return {"max_output_tokens": FinishReason.LENGTH,
"content_filter": FinishReason.CONTENT_FILTER}.get(reason or "", FinishReason.OTHER), shown
if status == "completed": # "failed" and "cancelled" never get here: parse() raised already
has_call = any(i.type == "function_call" for i in raw.output)
return (FinishReason.TOOL_CALLS if has_call else FinishReason.STOP), shown
return FinishReason.OTHER, shown
# ---- streaming -------------------------------------------------------------------------
def new_stream(self) -> StreamParser:
return _ResponsesStream(self.spec, self.api, self)
# ---- I/O ---------------------------------------------------------------------------------
def send(self, params: dict[str, Any], timeout_s: float) -> Any:
return self.client.responses.create(**params, timeout=timeout_s)
async def asend(self, params: dict[str, Any], timeout_s: float) -> Any:
return await self.aclient.responses.create(**params, timeout=timeout_s)
def open_stream(self, params: dict[str, Any], timeout_s: float) -> Iterator[Any]:
with self.client.responses.create(**params, stream=True, timeout=timeout_s) as stream:
yield Opened(request_id_from(stream.response.headers)) # the header ID, before any event
yield from stream
async def aopen_stream(self, params: dict[str, Any], timeout_s: float) -> AsyncIterator[Any]:
async with await self.aclient.responses.create(**params, stream=True, timeout=timeout_s) as stream:
yield Opened(request_id_from(stream.response.headers))
async for event in stream:
yield event
class _ResponsesStream(StreamParser):
def __init__(self, spec: ModelSpec, api: str, adapter: OpenAIResponsesAdapter) -> None:
super().__init__(spec, api)
self.adapter = adapter
def feed(self, event: Any) -> list[StreamEvent]:
t, b, out = event.type, self.b, []
if t == "response.output_item.added":
item = event.item
if item.type == "function_call":
out.append(b.tool_start(event.output_index, item.call_id, item.name, event.output_index))
elif t == "response.output_text.delta":
out.append(b.text(event.output_index, event.delta))
elif t == "response.refusal.delta":
out.append(b.text(event.output_index, event.delta))
elif t == "response.function_call_arguments.delta":
out.append(b.tool_args(event.output_index, event.delta, event.output_index))
elif t == "response.reasoning_summary_text.delta":
out.append(b.reasoning(event.output_index, event.delta))
elif t == "response.output_item.done":
item = event.item
if item.type in ("reasoning", "function_call"): # keep the finished item to replay it later
b.native(event.output_index, Native(provider=self.spec.provider, api=self.api,
payload=item.model_dump(exclude_none=True)), kind="tool" if item.type == "function_call" else "reasoning")
elif t in ("response.completed", "response.incomplete", "response.failed"):
try:
final = self.adapter.parse(event.response) # the terminal event carries the full object
except LLMError as err: # response.failed: the code decides retry or not
err.request_id = err.request_id or b.request_id
raise
b.finish_reason, b.raw_finish_reason = final.finish_reason, final.raw_finish_reason
b.resolved_model, b.response_id = final.resolved_model, final.provider_response_id
if final.usage:
out.append(b.set_usage(final.usage))
elif t == "error": # an `error` event: keep its CODE (rate_limit_exceeded...)
raise error_from_failed(self.spec.provider, getattr(event, "code", None), getattr(event, "message", None),
request_id=b.request_id)
return out # unknown events are ignored by designprovider_agnostic/adapters/openai_chat.py#
"""provider_agnostic/adapters/openai_chat.py: OpenAI Chat Completions, and everything that speaks it.
One class, three "dialects" chosen by spec.provider: "openai", "openrouter" and "local" (Ollama, vLLM and
other OpenAI-compatible servers). "Compatible" means the URL and the JSON envelope match. It does NOT mean
the same parameters, streaming usage, structured output or errors (lesson 03.1, 5.5), so every difference
lives in DIALECTS below instead of in if-statements scattered through the code.
"""
from __future__ import annotations
import json
from collections.abc import AsyncIterator, Iterator
from dataclasses import dataclass
from typing import Any
import cost_calc # lesson 03.7
import openai
from ..errors import error_from_body, error_from_failed
from ..registry import ModelSpec
from ..schemas import openai_strict, schema_name
from ..types import (DocumentPart, FinishReason, ForcedTool, ImagePart, Native, Part, ReasoningPart, Request,
Response, StreamEvent, TextPart, ToolCallPart, ToolResultPart, Usage)
from .base import (Adapter, Opened, StreamParser, apply_extra, data_url, error_result_text, parse_arguments,
request_id_from, usage_or_none)
@dataclass(frozen=True)
class Dialect:
max_tokens_param: str # the output-cap parameter this server honours
reasoning: str # "reasoning_effort" | "openrouter" | "none"
reports_cost: bool = False # OpenRouter puts usage.cost in the response
# Whether a server ENFORCES strict tool schemas is a registry capability (`strict_tools`), not a dialect field:
# it differs per route, and the capability check refuses ToolSpec.strict=True where it would be ignored.
DIALECTS = {
"openai": Dialect("max_completion_tokens", "reasoning_effort"),
"openrouter": Dialect("max_tokens", "openrouter", reports_cost=True),
"local": Dialect("max_tokens", "none"), # Ollama ignores max_completion_tokens
}
_FINISH = {"stop": FinishReason.STOP, "length": FinishReason.LENGTH, "tool_calls": FinishReason.TOOL_CALLS,
"function_call": FinishReason.TOOL_CALLS, "content_filter": FinishReason.CONTENT_FILTER,
"error": FinishReason.ERROR}
class OpenAIChatAdapter(Adapter):
api = "chat"
def __init__(self, spec: ModelSpec, **kw: Any) -> None:
super().__init__(spec, **kw)
self.dialect = DIALECTS.get(spec.provider, DIALECTS["local"])
@property
def client(self) -> openai.OpenAI:
if self._client is None:
self._client = openai.OpenAI(**self.sdk_kwargs(), http_client=self._http_client)
return self._client
@property
def aclient(self) -> openai.AsyncOpenAI:
if self._aclient is None:
self._aclient = openai.AsyncOpenAI(**self.sdk_kwargs(), http_client=self._async_http_client)
return self._aclient
# ---- request ---------------------------------------------------------------------------
def build(self, req: Request) -> dict[str, Any]:
spec, d = self.spec, self.dialect
messages: list[dict[str, Any]] = []
if req.system:
messages.append({"role": "system", "content": req.system})
messages += self._messages(req)
params: dict[str, Any] = {"model": spec.model, "messages": messages,
d.max_tokens_param: req.max_output_tokens or spec.default_max_output_tokens}
if req.stop:
params["stop"] = req.stop
if req.tools:
params["tools"] = [{"type": "function", "function": {
"name": t.name, "description": t.description,
"parameters": openai_strict(t.parameters) if t.strict else t.parameters,
**({"strict": True} if t.strict else {})}} for t in req.tools]
tc = req.tool_choice
params["tool_choice"] = ({"type": "function", "function": {"name": tc.name}}
if isinstance(tc, ForcedTool) else tc)
if req.parallel_tool_calls is not None:
params["parallel_tool_calls"] = req.parallel_tool_calls
if req.output_schema is not None:
params["response_format"] = {"type": "json_schema", "json_schema": {
"name": schema_name(req.output_schema), "schema": openai_strict(req.output_schema),
"strict": True}}
if spec.capabilities.reasoning and req.reasoning_effort:
effort = spec.reasoning_off if req.reasoning_effort == "off" else req.reasoning_effort
if d.reasoning == "reasoning_effort":
params["reasoning_effort"] = effort
elif d.reasoning == "openrouter":
params["extra_body"] = {"reasoning": {"effort": effort}} # OpenRouter-only field: not in the SDK schema
return apply_extra(params, req, spec.provider) # deep-merged: extra_body keeps the reasoning object
def _native(self, part: Part) -> dict[str, Any] | None:
n = part.native
return n.payload if n and n.provider == self.spec.provider and n.api == self.api else None
def _messages(self, req: Request) -> list[dict[str, Any]]:
out: list[dict[str, Any]] = []
for m in req.messages:
if m.role == "user":
content: list[dict[str, Any]] = []
for p in m.parts:
if isinstance(p, TextPart):
if p.text:
content.append({"type": "text", "text": p.text})
elif isinstance(p, ImagePart):
url = p.url if p.url and not p.data_b64 else data_url(p.media_type, p.data_b64 or "")
content.append({"type": "image_url", "image_url": {"url": url, "detail": p.detail}})
elif isinstance(p, DocumentPart):
content.append({"type": "file", "file": {"filename": p.filename,
"file_data": data_url(p.media_type, p.data_b64)}})
if content:
out.append({"role": "user", "content": content})
elif m.role == "assistant":
msg: dict[str, Any] = {"role": "assistant", "content": m.text or None}
calls = []
for p in m.parts:
if isinstance(p, ReasoningPart) and (native := self._native(p)):
msg.update(native) # e.g. OpenRouter's reasoning_details, unchanged
elif isinstance(p, ToolCallPart):
# invalid JSON from the model: replay what it really said, do not rewrite it as "{}"
raw_args = (self._native(p) or {}).get("arguments") if p.arguments_error else None
calls.append({"id": p.id, "type": "function", "function": {
"name": p.name, "arguments": raw_args if isinstance(raw_args, str) else json.dumps(p.arguments)}})
if calls:
msg["tool_calls"] = calls
if msg["content"] or calls: # no text and no calls (refusal-only, cut off while thinking): omit
out.append(msg)
else:
out += [{"role": "tool", "tool_call_id": p.call_id,
"content": error_result_text(p.content) if p.is_error else p.content} # no is_error field here
for p in m.parts if isinstance(p, ToolResultPart)]
return out
# ---- response --------------------------------------------------------------------------
def parse(self, raw: Any) -> Response:
extra = raw.model_extra or {}
if not raw.choices: # OpenRouter: HTTP 200 with only an error body
raise error_from_body(self.spec.provider, extra.get("error"), request_id=raw.id)
choice = raw.choices[0]
msg = choice.message
parts: list[Part] = []
reasoning_extra = {k: v for k, v in (msg.model_extra or {}).items() if k in ("reasoning_details",) and v}
reasoning_text = (msg.model_extra or {}).get("reasoning") or (msg.model_extra or {}).get("reasoning_content")
if reasoning_text or reasoning_extra:
parts.append(ReasoningPart(text=reasoning_text or None, native=Native(
provider=self.spec.provider, api=self.api, payload=reasoning_extra) if reasoning_extra else None))
if msg.content:
parts.append(TextPart(text=msg.content))
for tc in msg.tool_calls or []:
if tc.type != "function":
continue
args, err = parse_arguments(tc.function.arguments)
parts.append(ToolCallPart(id=tc.id, name=tc.function.name, arguments=args, arguments_error=err,
native=Native(provider=self.spec.provider, api=self.api,
payload={"arguments": tc.function.arguments}) if err else None))
finish = FinishReason.REFUSAL if msg.refusal else _FINISH.get(choice.finish_reason or "", FinishReason.OTHER)
if msg.refusal:
parts.append(TextPart(text=msg.refusal))
raw_finish = choice.finish_reason
native_finish = (choice.model_extra or {}).get("native_finish_reason") # OpenRouter keeps the original
if native_finish:
raw_finish = f"{choice.finish_reason}|{native_finish}"
request_id = getattr(raw, "_request_id", None)
if choice.finish_reason == "error": # the provider failed mid-request, inside a 200
raise error_from_failed(self.spec.provider, "server_error",
f"the response ended with finish_reason=error ({native_finish or 'no detail'})",
request_id=request_id or raw.id)
return Response(parts=parts, finish_reason=finish, raw_finish_reason=raw_finish, usage=self._usage(raw),
provider=self.spec.provider, api=self.api, resolved_model=raw.model,
request_id=request_id or raw.id, provider_response_id=raw.id, raw=raw)
def _usage(self, completion: Any) -> Usage | None:
"""03.7's `from_openrouter` / `from_openai_chat` read `.usage`, `.model` and `.service_tier`: a stream CHUNK has
all three, so the same call prices a streamed Chat response at the tier that served it (flex included)."""
if completion.usage is None:
return None
convert = cost_calc.from_openrouter if self.dialect.reports_cost else cost_calc.from_openai_chat
return usage_or_none(lambda: convert(completion))
def new_stream(self) -> StreamParser:
return _ChatStream(self.spec, self.api, self)
# ---- I/O ---------------------------------------------------------------------------------
def send(self, params: dict[str, Any], timeout_s: float) -> Any:
return self.client.chat.completions.create(**params, timeout=timeout_s)
async def asend(self, params: dict[str, Any], timeout_s: float) -> Any:
return await self.aclient.chat.completions.create(**params, timeout=timeout_s)
def open_stream(self, params: dict[str, Any], timeout_s: float) -> Iterator[Any]:
with self.client.chat.completions.create(**params, stream=True, stream_options={"include_usage": True},
timeout=timeout_s) as stream:
yield Opened(request_id_from(stream.response.headers))
yield from stream
async def aopen_stream(self, params: dict[str, Any], timeout_s: float) -> AsyncIterator[Any]:
async with await self.aclient.chat.completions.create(
**params, stream=True, stream_options={"include_usage": True}, timeout=timeout_s) as stream:
yield Opened(request_id_from(stream.response.headers))
async for chunk in stream:
yield chunk
class _ChatStream(StreamParser):
def __init__(self, spec: ModelSpec, api: str, adapter: OpenAIChatAdapter) -> None:
super().__init__(spec, api)
self.adapter = adapter
self._started: set[int] = set()
self._details: list[Any] = []
self._refused = False
def feed(self, event: Any) -> list[StreamEvent]:
chunk = event
b, out = self.b, []
if chunk.usage is not None: # check EVERY chunk: OpenAI's usage chunk has choices == []
usage = self.adapter._usage(chunk)
if usage is not None:
out.append(b.set_usage(usage))
b.resolved_model = chunk.model or b.resolved_model
b.response_id = b.response_id or chunk.id
if (chunk.model_extra or {}).get("error"): # OpenRouter: an error object in the middle of the stream
raise error_from_body(self.spec.provider, chunk.model_extra["error"], request_id=b.request_id or chunk.id)
if not chunk.choices:
return out
choice = chunk.choices[0]
delta = choice.delta
extra = delta.model_extra or {}
if extra.get("reasoning"):
out.append(b.reasoning("r", extra["reasoning"]))
if extra.get("reasoning_details"):
self._details += extra["reasoning_details"] # OpenRouter: keep verbatim, replay unchanged
b.native("r", Native(provider=self.spec.provider, api=self.api,
payload={"reasoning_details": self._details}))
if delta.content:
out.append(b.text("t", delta.content))
for tc in delta.tool_calls or []:
key = ("call", tc.index)
if tc.index not in self._started and (tc.id or (tc.function and tc.function.name)):
self._started.add(tc.index)
out.append(b.tool_start(key, tc.id or "", (tc.function.name if tc.function else "") or "", tc.index))
if tc.function and tc.function.arguments:
out.append(b.tool_args(key, tc.function.arguments, tc.index))
if delta.refusal:
self._refused = True
out.append(b.text("t", delta.refusal))
if choice.finish_reason == "error":
raise error_from_failed(self.spec.provider, "server_error", "the stream ended with finish_reason=error",
request_id=b.request_id or chunk.id)
if choice.finish_reason: # OpenRouter repeats it: overwrite, don't append
b.raw_finish_reason = choice.finish_reason
b.finish_reason = (FinishReason.REFUSAL if self._refused
else _FINISH.get(choice.finish_reason, FinishReason.OTHER))
return outprovider_agnostic/adapters/anthropic_messages.py#
"""provider_agnostic/adapters/anthropic_messages.py: Anthropic Messages API (also Ollama's /v1/messages and OpenRouter's /api/messages).
Message shapes: lesson 03.2 (alternation, tool_result first). Streaming: 03.3. Structured output: 03.4.
Sampling parameters are deliberately absent: API version 2026-10-21 rejects them (lesson 02.5, Part 6).
"""
from __future__ import annotations
from collections.abc import AsyncIterator, Iterator
from types import SimpleNamespace
from typing import Any
import anthropic
import cost_calc # lesson 03.7
from ..registry import ModelSpec
from ..schemas import anthropic_schema
from ..types import (DocumentPart, FinishReason, ForcedTool, ImagePart, Native, Part, ReasoningPart, Request,
Response, StreamEvent, TextPart, ToolCallPart, ToolResultPart)
from .base import Adapter, Opened, StreamParser, apply_extra, request_id_from, usage_or_none
_FINISH = {"end_turn": FinishReason.STOP, "stop_sequence": FinishReason.STOP, "max_tokens": FinishReason.LENGTH,
"model_context_window_exceeded": FinishReason.CONTEXT_FULL, "tool_use": FinishReason.TOOL_CALLS,
"pause_turn": FinishReason.PAUSED, "refusal": FinishReason.REFUSAL}
class AnthropicAdapter(Adapter):
api = "messages"
@property
def client(self) -> anthropic.Anthropic:
if self._client is None:
self._client = anthropic.Anthropic(**self.sdk_kwargs(), http_client=self._http_client)
return self._client
@property
def aclient(self) -> anthropic.AsyncAnthropic:
if self._aclient is None:
self._aclient = anthropic.AsyncAnthropic(**self.sdk_kwargs(), http_client=self._async_http_client)
return self._aclient
# ---- request ---------------------------------------------------------------------------
def build(self, req: Request) -> dict[str, Any]:
spec = self.spec
params: dict[str, Any] = {"model": spec.model, "messages": self._messages(req),
"max_tokens": req.max_output_tokens or spec.default_max_output_tokens}
if req.system:
params["system"] = req.system
if req.stop:
params["stop_sequences"] = req.stop
if req.tools:
params["tools"] = [{"name": t.name, "description": t.description,
"input_schema": anthropic_schema(t.parameters) if t.strict else t.parameters,
**({"strict": True} if t.strict else {})} for t in req.tools]
tc = req.tool_choice
choice: dict[str, Any] = ({"type": "tool", "name": tc.name} if isinstance(tc, ForcedTool)
else {"type": {"auto": "auto", "required": "any", "none": "none"}[tc]})
if req.parallel_tool_calls is False and choice["type"] != "none":
choice["disable_parallel_tool_use"] = True
if choice != {"type": "auto"}:
params["tool_choice"] = choice
output_config: dict[str, Any] = {}
if req.output_schema is not None:
output_config["format"] = {"type": "json_schema", "schema": anthropic_schema(req.output_schema)}
if spec.capabilities.reasoning and req.reasoning_effort: # 02.8, 3.6: depends on the MODEL
if req.reasoning_effort == "off" and spec.reasoning_off in ("disabled", "between_tools"):
params["thinking"] = {"type": spec.reasoning_off} # these modes take no other fields
else:
effort = spec.reasoning_off if req.reasoning_effort == "off" else req.reasoning_effort
params["thinking"] = {"type": "adaptive", "display": "summarized"}
output_config["effort"] = effort
if output_config:
params["output_config"] = output_config
return apply_extra(params, req, spec.provider) # deep-merged: output_config.effort keeps output_config.format
def _native(self, part: Part) -> dict[str, Any] | None:
n = part.native
return n.payload if n and n.provider == self.spec.provider and n.api == self.api else None
def _messages(self, req: Request) -> list[dict[str, Any]]:
out: list[dict[str, Any]] = []
for m in req.messages:
blocks: list[dict[str, Any]] = []
if m.role in ("user", "tool"):
# tool_result blocks must come FIRST in the user message that answers the tool_use
results = [p for p in m.parts if isinstance(p, ToolResultPart)]
blocks += [{"type": "tool_result", "tool_use_id": p.call_id, "content": p.content,
**({"is_error": True} if p.is_error else {})} for p in results]
for p in m.parts:
if isinstance(p, TextPart):
if p.text: # an empty text block is a 400 on the Messages API
blocks.append({"type": "text", "text": p.text})
elif isinstance(p, ImagePart):
src = ({"type": "url", "url": p.url} if p.url and not p.data_b64 else
{"type": "base64", "media_type": p.media_type, "data": p.data_b64})
blocks.append({"type": "image", "source": src})
elif isinstance(p, DocumentPart):
blocks.append({"type": "document", "source": {
"type": "base64", "media_type": p.media_type, "data": p.data_b64}})
role = "user"
else:
role = "assistant"
for p in m.parts:
if isinstance(p, ReasoningPart):
if (native := self._native(p)) is not None: # thinking blocks + signatures, unchanged
blocks.append(native)
elif isinstance(p, TextPart):
if p.text:
blocks.append({"type": "text", "text": p.text})
elif isinstance(p, ToolCallPart):
blocks.append({"type": "tool_use", "id": p.id, "name": p.name, "input": p.arguments})
if not blocks: # nothing to send for this turn: omit it entirely
continue
if out and out[-1]["role"] == role: # the API wants alternating roles: merge neighbours
out[-1]["content"] += blocks
else:
out.append({"role": role, "content": blocks})
return out
# ---- response --------------------------------------------------------------------------
def parse(self, raw: Any) -> Response:
parts: list[Part] = []
for blk in raw.content:
if blk.type == "text":
parts.append(TextPart(text=blk.text))
elif blk.type in ("thinking", "redacted_thinking"):
parts.append(ReasoningPart(
text=getattr(blk, "thinking", None) or None,
native=Native(provider=self.spec.provider, api=self.api, payload=blk.model_dump(exclude_none=True))))
elif blk.type == "tool_use":
parts.append(ToolCallPart(id=blk.id, name=blk.name, arguments=dict(blk.input)))
return Response(parts=parts, finish_reason=_FINISH.get(raw.stop_reason or "", FinishReason.OTHER),
raw_finish_reason=raw.stop_reason, usage=usage_or_none(lambda: cost_calc.from_anthropic(raw)),
provider=self.spec.provider, api=self.api, resolved_model=raw.model,
request_id=getattr(raw, "_request_id", None) or raw.id, provider_response_id=raw.id, raw=raw)
def new_stream(self) -> StreamParser:
return _MessagesStream(self.spec, self.api)
# ---- I/O ---------------------------------------------------------------------------------
def send(self, params: dict[str, Any], timeout_s: float) -> Any:
return self.client.messages.create(**params, timeout=timeout_s)
async def asend(self, params: dict[str, Any], timeout_s: float) -> Any:
return await self.aclient.messages.create(**params, timeout=timeout_s)
def open_stream(self, params: dict[str, Any], timeout_s: float) -> Iterator[Any]:
with self.client.messages.create(**params, stream=True, timeout=timeout_s) as stream:
yield Opened(request_id_from(stream.response.headers)) # the request-id header, before any event
yield from stream
async def aopen_stream(self, params: dict[str, Any], timeout_s: float) -> AsyncIterator[Any]:
async with await self.aclient.messages.create(**params, stream=True, timeout=timeout_s) as stream:
yield Opened(request_id_from(stream.response.headers))
async for event in stream:
yield event
class _MessagesStream(StreamParser):
def __init__(self, spec: ModelSpec, api: str) -> None:
super().__init__(spec, api)
self._start_usage: Any = None
self._model = spec.model
def feed(self, event: Any) -> list[StreamEvent]:
e = event
t, b, out = e.type, self.b, []
if t == "message_start":
self._start_usage, self._model = e.message.usage, e.message.model
b.response_id, b.resolved_model = e.message.id, e.message.model
if (usage := self._usage(e.message.usage)) is not None:
out.append(b.set_usage(usage))
elif t == "content_block_start":
blk = e.content_block
if blk.type == "tool_use":
out.append(b.tool_start(e.index, blk.id, blk.name, e.index))
elif blk.type == "redacted_thinking":
b.native(e.index, Native(provider=self.spec.provider, api=self.api,
payload=blk.model_dump(exclude_none=True)))
elif blk.type == "thinking":
b.reasoning(e.index, "") # open the block; deltas follow
elif t == "content_block_delta":
d = e.delta
if d.type == "text_delta":
out.append(b.text(e.index, d.text))
elif d.type == "thinking_delta":
out.append(b.reasoning(e.index, d.thinking))
elif d.type == "input_json_delta":
out.append(b.tool_args(e.index, d.partial_json, e.index))
elif d.type == "signature_delta": # needed to replay the thinking block
blk = b.blocks[e.index]
blk["signature"] = blk.get("signature", "") + d.signature
elif t == "content_block_stop":
blk = b.blocks.get(e.index)
if blk and blk["kind"] == "reasoning" and blk.get("signature"):
b.native(e.index, Native(provider=self.spec.provider, api=self.api, payload={
"type": "thinking", "thinking": blk["text"], "signature": blk["signature"]}))
elif t == "message_delta":
b.raw_finish_reason = e.delta.stop_reason
b.finish_reason = _FINISH.get(e.delta.stop_reason or "", FinishReason.OTHER)
if (usage := self._usage(self._merged(e.usage))) is not None: # cumulative: replace, never add
out.append(b.set_usage(usage))
return out # ping, message_stop, unknown: ignored
def _usage(self, usage: Any) -> Any:
"""03.7's `from_anthropic` reads `.usage` and `.model` of a Message: a SimpleNamespace is enough to reuse it,
so fast mode, inference_geo, web searches and the 5m/1h cache-write split are priced on streams too."""
return usage_or_none(lambda: cost_calc.from_anthropic(SimpleNamespace(usage=usage, model=self._model))) # type: ignore[arg-type]
def _merged(self, delta: Any) -> Any:
"""message_start has the full usage object (speed, geo, tier); message_delta's numbers are cumulative and win."""
fields = ("input_tokens", "output_tokens", "cache_read_input_tokens", "cache_creation_input_tokens",
"server_tool_use", "output_tokens_details")
changed = {f: getattr(delta, f) for f in fields if getattr(delta, f, None) is not None}
return self._start_usage.model_copy(update=changed) if self._start_usage is not None else deltaprovider_agnostic/adapters/gemini_generate.py#
"""provider_agnostic/adapters/gemini_generate.py: Gemini `generate_content`.
Why this is the wrapper's default Gemini adapter (lesson 03.11, 4.5): its retries can be fully switched
off (models.* makes ONE attempt unless you ask), it is stateless like the other adapters, and it is the API
that has batch and explicit caches. The Interactions adapter sits beside it for teams that want Google's
newer interface.
"""
from __future__ import annotations
import base64
import json
from collections.abc import AsyncIterator, Iterator
from typing import Any
import cost_calc # lesson 03.7
from google import genai
from google.genai import types
from ..registry import ModelSpec, resolve_api_key, resolve_headers, resolved_base_url
from ..schemas import plain_schema
from ..types import (DocumentPart, FinishReason, ForcedTool, ImagePart, Native, Part, ReasoningPart, Request,
Response, StreamEvent, TextPart, ToolCallPart, ToolResultPart, Usage)
from .base import Adapter, StreamParser, aclosing, apply_extra, closing, usage_or_none
_BLOCKED = {"SAFETY", "PROHIBITED_CONTENT", "BLOCKLIST", "SPII", "RECITATION", "IMAGE_SAFETY",
"IMAGE_PROHIBITED_CONTENT", "IMAGE_RECITATION", "LANGUAGE"}
_TOOL_FAILURES = {"MALFORMED_FUNCTION_CALL", "UNEXPECTED_TOOL_CALL", "TOO_MANY_TOOL_CALLS", "OTHER"}
def make_genai_client(adapter: Adapter, retry_options: types.HttpRetryOptions | None = None) -> genai.Client:
"""One genai.Client per adapter, kept alive (a throwaway Client is garbage-collected mid-call: lesson 03.1, 7.5).
No retry_options for models.*: it makes one attempt, and the wrapper owns retries."""
spec = adapter.spec
opts = types.HttpOptions(base_url=resolved_base_url(spec), headers=resolve_headers(spec), retry_options=retry_options,
httpx_client=adapter._http_client, httpx_async_client=adapter._async_http_client)
return genai.Client(api_key=resolve_api_key(spec), http_options=opts)
class GeminiGenerateAdapter(Adapter):
api = "generate_content"
@property
def client(self) -> genai.Client:
if self._client is None:
self._client = make_genai_client(self)
return self._client
# ---- request ---------------------------------------------------------------------------
def build(self, req: Request) -> dict[str, Any]:
spec = self.spec
cfg: dict[str, Any] = {"max_output_tokens": req.max_output_tokens or spec.default_max_output_tokens,
"automatic_function_calling": {"disable": True}} # we run tools; the SDK must not
if req.system:
cfg["system_instruction"] = req.system
if req.stop:
cfg["stop_sequences"] = req.stop
if req.tools:
cfg["tools"] = [{"function_declarations": [
{"name": t.name, "description": t.description, "parameters_json_schema": t.parameters}
for t in req.tools]}]
tc = req.tool_choice
if isinstance(tc, ForcedTool):
fc = {"mode": "ANY", "allowed_function_names": [tc.name]}
else:
fc = {"mode": {"auto": "AUTO", "required": "ANY", "none": "NONE"}[tc]}
cfg["tool_config"] = {"function_calling_config": fc}
if req.output_schema is not None:
cfg["response_mime_type"] = "application/json"
cfg["response_json_schema"] = plain_schema(req.output_schema)
if spec.capabilities.reasoning and req.reasoning_effort:
level = spec.reasoning_off if req.reasoning_effort == "off" else req.reasoning_effort
cfg["thinking_config"] = {"thinking_level": str(level).upper(), "include_thoughts": True}
cfg = apply_extra(cfg, req, spec.provider, reserved=set()) # the extras are GenerateContentConfig fields, merged
return {"model": spec.model, "contents": self._contents(req),
"config": types.GenerateContentConfig.model_validate(cfg)}
def _native(self, part: Part) -> dict[str, Any] | None:
n = part.native
return n.payload if n and n.provider == self.spec.provider and n.api == self.api else None
def _contents(self, req: Request) -> list[types.Content]:
out: list[dict[str, Any]] = []
for m in req.messages:
parts: list[dict[str, Any]] = []
for p in m.parts:
if isinstance(p, TextPart):
if p.text:
parts.append(self._native(p) or {"text": p.text})
elif isinstance(p, ImagePart):
if p.data_b64 is not None:
parts.append({"inline_data": {"mime_type": p.media_type, "data": base64.b64decode(p.data_b64)}})
else: # a public https URL: Gemini fetches it (up to 15 MB, lesson 03.6)
parts.append({"file_data": {"file_uri": p.url, "mime_type": p.media_type}})
elif isinstance(p, DocumentPart):
parts.append({"inline_data": {"mime_type": p.media_type, "data": base64.b64decode(p.data_b64)}})
elif isinstance(p, ReasoningPart):
if (native := self._native(p)) is not None:
parts.append(native)
elif isinstance(p, ToolCallPart):
parts.append(self._native(p) or {"function_call": {"id": p.id or None, "name": p.name,
"args": p.arguments}})
elif isinstance(p, ToolResultPart):
body = {"error": p.content} if p.is_error else {"output": p.content}
parts.append({"function_response": {"id": p.call_id or None, "name": p.name, "response": body}})
if parts: # a Content with no parts is a 400
out.append({"role": "model" if m.role == "assistant" else "user", "parts": parts})
return [types.Content.model_validate(c) for c in out]
# ---- response --------------------------------------------------------------------------
def parse(self, raw: Any) -> Response:
parts, finish, raw_finish = self._parts_and_finish(raw)
return Response(parts=parts, finish_reason=finish, raw_finish_reason=raw_finish,
usage=_usage(raw, self.spec.model, bool(parts)), provider=self.spec.provider, api=self.api,
resolved_model=raw.model_version, request_id=raw.response_id, # Google sends no request-ID header
provider_response_id=raw.response_id, raw=raw)
def _parts_and_finish(self, raw: Any) -> tuple[list[Part], FinishReason, str | None]:
parts: list[Part] = []
cand = raw.candidates[0] if raw.candidates else None
calls = False
for p in (cand.content.parts if cand and cand.content and cand.content.parts else []):
payload = p.model_dump(mode="json", exclude_none=True) # signatures included, base64
native = Native(provider=self.spec.provider, api=self.api, payload=payload)
if p.function_call:
calls = True
parts.append(ToolCallPart(id=p.function_call.id or "", name=p.function_call.name or "",
arguments=dict(p.function_call.args or {}), native=native))
elif p.thought and p.text is not None:
parts.append(ReasoningPart(text=p.text, native=native))
elif p.text is not None:
parts.append(TextPart(text=p.text, native=native if p.thought_signature else None))
name = cand.finish_reason.name if cand and cand.finish_reason else None
if cand is None: # the PROMPT was blocked: no candidate
block = raw.prompt_feedback.block_reason if raw.prompt_feedback else None
return parts, FinishReason.CONTENT_FILTER, f"prompt_blocked:{block.name if block else None}"
if name in _BLOCKED:
return parts, FinishReason.CONTENT_FILTER, name
if name in ("MAX_TOKENS", "CONTINUATION"): # CONTINUATION: stopped at the per-request limit, NOT finished
return parts, FinishReason.LENGTH, name # (the SDK hides it by default: 03.3, 4.5b; you see it with automatic_continuation=False)
if name in _TOOL_FAILURES:
return parts, FinishReason.ERROR, name
if name in ("STOP", None):
return parts, (FinishReason.TOOL_CALLS if calls else FinishReason.STOP), name
return parts, FinishReason.OTHER, name
def new_stream(self) -> StreamParser:
return _GenerateStream(self.spec, self.api, self)
# ---- I/O ---------------------------------------------------------------------------------
@staticmethod
def _with_timeout(params: dict[str, Any], timeout_s: float) -> dict[str, Any]:
cfg = params["config"].model_copy(update={"http_options": types.HttpOptions(timeout=int(timeout_s * 1000))})
return {**params, "config": cfg} # google-genai timeouts are in MILLISECONDS
def send(self, params: dict[str, Any], timeout_s: float) -> Any:
return self.client.models.generate_content(**self._with_timeout(params, timeout_s))
async def asend(self, params: dict[str, Any], timeout_s: float) -> Any:
return await self.client.aio.models.generate_content(**self._with_timeout(params, timeout_s))
def open_stream(self, params: dict[str, Any], timeout_s: float) -> Iterator[Any]:
stream = self.client.models.generate_content_stream(**self._with_timeout(params, timeout_s))
with closing(stream): # the SDK returns a generator: close it, even on an early exit
yield from stream
async def aopen_stream(self, params: dict[str, Any], timeout_s: float) -> AsyncIterator[Any]:
stream = await self.client.aio.models.generate_content_stream(**self._with_timeout(params, timeout_s))
async with aclosing(stream):
async for chunk in stream:
yield chunk
def close(self) -> None:
if self._client is not None:
self._client.close()
async def aclose(self) -> None:
if self._client is not None:
await self._client.aio.aclose()
def _service_tier(raw: Any) -> str | None:
"""Gemini reports the tier that served a call in the `x-gemini-service-tier` RESPONSE HEADER (on the Developer API,
`usage_metadata.traffic_type` is not supported). Lesson 03.7 prices flex and priority from it."""
http = getattr(raw, "sdk_http_response", None)
for name, value in (getattr(http, "headers", None) or {}).items():
if name.lower() == "x-gemini-service-tier":
return value
return None
def _usage(raw: Any, model: str, has_output: bool) -> Usage | None:
"""03.7's `from_gemini`: it knows prompt_token_count includes the cached part and that thoughts are NOT inside
candidates_token_count. One more rule here: usage that is all zeros next to a real answer (a proxy that zeroes it,
for example on streams) is UNKNOWN, not 'free'."""
if raw.usage_metadata is None:
return None
usage = usage_or_none(lambda: cost_calc.from_gemini(raw, model, service_tier=_service_tier(raw)))
if usage is not None and has_output and usage.total_input_tokens == 0 and usage.output_tokens == 0:
return None
return usage
class _GenerateStream(StreamParser):
"""Every chunk is a whole GenerateContentResponse; text arrives in pieces, function calls arrive whole."""
def __init__(self, spec: ModelSpec, api: str, adapter: GeminiGenerateAdapter) -> None:
super().__init__(spec, api)
self.adapter = adapter
self._calls = 0
self._sig: Any = None
self._saw_call = False
def feed(self, event: Any) -> list[StreamEvent]:
chunk = event
b, out = self.b, []
b.response_id = b.response_id or chunk.response_id # Google has no request-ID header: this is the ID
b.resolved_model = chunk.model_version or b.resolved_model
cand = chunk.candidates[0] if chunk.candidates else None
if chunk.usage_metadata: # keep the latest; never sum
here = any(pt.text or pt.function_call for pt in (cand.content.parts if cand and cand.content and cand.content.parts else []))
u = _usage(chunk, self.spec.model, bool(b.blocks) or here) # zeros next to real output = unknown
if u:
out.append(b.set_usage(u))
if cand is None:
if chunk.prompt_feedback and chunk.prompt_feedback.block_reason:
b.finish_reason = FinishReason.CONTENT_FILTER
b.raw_finish_reason = f"prompt_blocked:{chunk.prompt_feedback.block_reason.name}"
return out
for p in (cand.content.parts if cand.content and cand.content.parts else []):
if p.function_call:
key, idx = ("call", self._calls), self._calls
self._calls += 1
self._saw_call = True
out.append(b.tool_start(key, p.function_call.id or "", p.function_call.name or "", idx))
out.append(b.tool_args(key, json.dumps(dict(p.function_call.args or {})), idx))
b.native(key, Native(provider=self.spec.provider, api=self.api,
payload=p.model_dump(mode="json", exclude_none=True)), kind="tool")
elif p.thought and p.text:
out.append(b.reasoning("r", p.text))
elif p.text:
out.append(b.text("t", p.text))
if p.thought_signature: # keep it: replay needs the signed part
self._sig = p.thought_signature
if self._sig:
sig = base64.b64encode(self._sig).decode() if isinstance(self._sig, bytes) else self._sig
b.native("t", Native(provider=self.spec.provider, api=self.api,
payload={"text": b.blocks["t"]["text"], "thought_signature": sig}),
kind="text")
if cand.finish_reason:
parts, finish, raw_finish = self.adapter._parts_and_finish(chunk)
if finish is FinishReason.STOP and self._saw_call:
finish = FinishReason.TOOL_CALLS
b.finish_reason, b.raw_finish_reason = finish, raw_finish
return outprovider_agnostic/adapters/gemini_interactions.py#
"""provider_agnostic/adapters/gemini_interactions.py: Gemini Interactions API, used statelessly (store=False, full input each time).
Google recommends Interactions for new projects. This adapter lets the same canonical request run on it.
Known costs (lesson 03.11, 4.5): the SDK retries Interactions calls by itself and cannot be told not to,
and there is no local stand-in for it (Ollama does not speak Gemini's API), so it is tested with mocks only.
"""
from __future__ import annotations
import json
from collections.abc import AsyncIterator, Iterator
from typing import Any
import cost_calc # lesson 03.7
from google.genai import types
from ..errors import error_from_failed, error_message, raise_if_failed
from ..registry import ModelSpec
from ..schemas import plain_schema
from ..types import (DocumentPart, FinishReason, ForcedTool, ImagePart, Native, Part, ReasoningPart, Request,
Response, StreamEvent, TextPart, ToolCallPart, ToolResultPart, Usage)
from .base import Adapter, StreamParser, apply_extra, usage_or_none
from .gemini_generate import make_genai_client
# "failed", "cancelled" and "budget_exceeded" are ERRORS (raised by fail_if_unfinished), so they are not in this table.
_STATUS = {"completed": FinishReason.STOP, "requires_action": FinishReason.TOOL_CALLS,
"incomplete": FinishReason.LENGTH}
def fail_if_unfinished(interaction: Any, provider: str) -> None:
"""HTTP 200 whose status says the interaction did not produce an answer: an error with the right class.
`failed` and `cancelled` are 03.8's FAILED outcome, detected by check_response() as is (it reads a whole `Interaction`
and the `InteractionSseEventInteraction` a stream ends with; the code in `errors[0]` decides retry or not, `cancelled`
is permanent). The one rule added here is `budget_exceeded`, which 03.8 reports as INCOMPLETE: it has no code and is
permanent for this request, so it is an error too."""
request_id = getattr(interaction, "id", None)
if str(getattr(interaction, "status", "")) == "budget_exceeded":
raise error_from_failed(provider, "budget_exceeded", error_message(interaction), request_id=request_id)
raise_if_failed(interaction, provider, request_id)
class GeminiInteractionsAdapter(Adapter):
api = "interactions"
@property
def client(self) -> Any:
if self._client is None:
# attempts=0 would be rewritten to 1 (a retry!) by the SDK, so the best we can do is to stop
# STATUS retries (599 is never sent); connection errors are still retried once. Lesson 03.8, 5.2.
quiet = types.HttpRetryOptions(attempts=1, http_status_codes=[599])
self._client = make_genai_client(self, retry_options=quiet)
return self._client
# ---- request ---------------------------------------------------------------------------
def build(self, req: Request) -> dict[str, Any]:
spec = self.spec
gen: dict[str, Any] = {"max_output_tokens": req.max_output_tokens or spec.default_max_output_tokens}
if req.stop:
gen["stop_sequences"] = req.stop
if spec.capabilities.reasoning and req.reasoning_effort:
gen["thinking_level"] = spec.reasoning_off if req.reasoning_effort == "off" else req.reasoning_effort
gen["thinking_summaries"] = "auto"
params: dict[str, Any] = {"model": spec.model, "input": self._steps(req), "store": False,
"generation_config": gen}
if req.system:
params["system_instruction"] = req.system
if req.tools:
params["tools"] = [{"type": "function", "name": t.name, "description": t.description,
"parameters": t.parameters} for t in req.tools]
tc = req.tool_choice
gen["tool_choice"] = ({"allowed_tools": {"mode": "any", "tools": [tc.name]}} if isinstance(tc, ForcedTool)
else {"auto": "auto", "required": "any", "none": "none"}[tc])
if req.output_schema is not None:
params["response_format"] = {"type": "text", "mime_type": "application/json",
"schema": plain_schema(req.output_schema)}
return apply_extra(params, req, spec.provider)
def _native(self, part: Part) -> dict[str, Any] | None:
n = part.native
return n.payload if n and n.provider == self.spec.provider and n.api == self.api else None
def _steps(self, req: Request) -> list[dict[str, Any]]:
steps: list[dict[str, Any]] = []
for m in req.messages:
kind = "model_output" if m.role == "assistant" else "user_input"
content: list[dict[str, Any]] = []
for p in m.parts:
if isinstance(p, TextPart):
if p.text:
content.append({"type": "text", "text": p.text})
elif isinstance(p, ImagePart):
content.append({"type": "image", "mime_type": p.media_type,
**({"data": p.data_b64} if p.data_b64 is not None else {"uri": p.url})})
elif isinstance(p, DocumentPart):
content.append({"type": "document", "mime_type": p.media_type, "data": p.data_b64})
else:
if content: # keep the turn's order: text said BEFORE a call stays before it
steps.append({"type": kind, "content": content})
content = []
if isinstance(p, ReasoningPart):
if (native := self._native(p)) is not None: # thought steps (with signature), unchanged
steps.append(native)
elif isinstance(p, ToolCallPart):
steps.append(self._native(p) or {"type": "function_call", "id": p.id, "name": p.name,
"arguments": p.arguments})
elif isinstance(p, ToolResultPart):
steps.append({"type": "function_result", "call_id": p.call_id, "name": p.name,
"result": p.content, "is_error": p.is_error})
if content:
steps.append({"type": kind, "content": content})
return steps
# ---- response --------------------------------------------------------------------------
def parse(self, raw: Any) -> Response:
fail_if_unfinished(raw, self.spec.provider)
parts: list[Part] = []
for step in raw.steps or []:
native = Native(provider=self.spec.provider, api=self.api,
payload=step.model_dump(mode="json", exclude_none=True))
if step.type == "model_output":
parts += [TextPart(text=c.text) for c in step.content or [] if c.type == "text"]
elif step.type == "thought":
summary = " ".join(c.text for c in step.summary or [] if c.type == "text")
parts.append(ReasoningPart(text=summary or None, native=native))
elif step.type == "function_call":
parts.append(ToolCallPart(id=step.id, name=step.name, arguments=dict(step.arguments or {}),
native=native))
status = str(raw.status)
finish = _STATUS.get(status, FinishReason.OTHER)
if finish is FinishReason.STOP and any(isinstance(p, ToolCallPart) for p in parts):
finish = FinishReason.TOOL_CALLS # status stays "completed" with function_call steps
return Response(parts=parts, finish_reason=finish, raw_finish_reason=status,
usage=_usage(raw, self.spec.model, bool(parts)), provider=self.spec.provider, api=self.api,
resolved_model=raw.model, request_id=raw.id, provider_response_id=raw.id, raw=raw)
def new_stream(self) -> StreamParser:
return _InteractionStream(self.spec, self.api)
# ---- I/O ---------------------------------------------------------------------------------
def send(self, params: dict[str, Any], timeout_s: float) -> Any:
return self.client.interactions.create(**params, timeout=timeout_s)
async def asend(self, params: dict[str, Any], timeout_s: float) -> Any:
return await self.client.aio.interactions.create(**params, timeout=timeout_s)
def open_stream(self, params: dict[str, Any], timeout_s: float) -> Iterator[Any]:
with self.client.interactions.create(**params, stream=True, timeout=timeout_s) as stream:
yield from stream
async def aopen_stream(self, params: dict[str, Any], timeout_s: float) -> AsyncIterator[Any]:
stream = await self.client.aio.interactions.create(**params, stream=True, timeout=timeout_s)
async with stream: # closes the HTTP response, even on an early exit
async for event in stream:
yield event
def close(self) -> None:
if self._client is not None:
self._client.close()
async def aclose(self) -> None:
if self._client is not None:
await self._client.aio.aclose()
def _usage(obj: Any, model: str, has_output: bool) -> Usage | None:
"""03.7's `from_gemini_interaction`. It ASSUMES total_input_tokens includes the cached part, as prompt_token_count
does on generate_content (Google does not document it): confirm against your first real responses. All zeros next
to a real answer is unknown, not free."""
if getattr(obj, "usage", obj) is None:
return None
usage = usage_or_none(lambda: cost_calc.from_gemini_interaction(obj, model))
if usage is not None and has_output and usage.total_input_tokens == 0 and usage.output_tokens == 0:
return None
return usage
class _InteractionStream(StreamParser):
def __init__(self, spec: ModelSpec, api: str) -> None:
super().__init__(spec, api)
self._types: dict[int, str] = {}
self._sigs: dict[int, str] = {}
def feed(self, event: Any) -> list[StreamEvent]:
e = event
kind, b, out = e.event_type, self.b, [] # Interactions routes on event_type, not type
if kind == "interaction.created":
iid = getattr(e.interaction, "id", None) if getattr(e, "interaction", None) else None
b.request_id = b.response_id = iid or b.request_id
elif kind == "step.start":
self._types[e.index] = e.step.type
if e.step.type == "function_call":
out.append(b.tool_start(e.index, e.step.id, e.step.name, e.index))
elif kind == "step.delta":
d = e.delta
if d.type == "text":
out.append(b.text(e.index, d.text))
elif d.type == "thought_summary":
text = getattr(d.content, "text", None) if d.content is not None else None
if text:
out.append(b.reasoning(e.index, text))
elif d.type == "thought_signature":
self._sigs[e.index] = d.signature
b.native(e.index, Native(provider=self.spec.provider, api=self.api,
payload={"type": "thought", "signature": d.signature}))
elif d.type == "arguments_delta":
frag = d.arguments if isinstance(d.arguments, str) else json.dumps(d.arguments)
out.append(b.tool_args(e.index, frag, e.index))
elif kind == "interaction.completed":
inter = getattr(e, "interaction", None)
if inter is not None: # no interaction wrapper in the event: assume completed
fail_if_unfinished(inter, self.spec.provider) # failed / cancelled / budget_exceeded: raise
status = str(getattr(inter, "status", None) or "completed")
finish = _STATUS.get(status, FinishReason.OTHER)
if finish is FinishReason.STOP and any(v == "function_call" for v in self._types.values()):
finish = FinishReason.TOOL_CALLS
b.finish_reason, b.raw_finish_reason = finish, status
usage = _usage(inter, self.spec.model, bool(b.blocks)) if inter is not None else None
if usage:
out.append(b.set_usage(usage))
elif kind == "error": # an error event: keep its code
err = getattr(e, "error", None)
raise error_from_failed(self.spec.provider, getattr(err, "code", None), getattr(err, "message", None),
request_id=b.request_id)
return out # status updates and unknown events: ignoredlocalstack/env.sh#
# localstack/env.sh: source this (". localstack/env.sh" or "source localstack/env.sh") to point the
# official SDKs at the local stand-in (Ollama). The keys are dummies: Ollama ignores them, and a real
# hosted key must never reach localhost.
export OPENAI_BASE_URL=http://localhost:11434/v1 OPENAI_API_KEY=ollama-local
export ANTHROPIC_BASE_URL=http://localhost:11434 ANTHROPIC_API_KEY=ollama-local
export GEMINI_API_KEY=ollama-local # a dummy: Gemini has no local route (Ollama does not speak it), so nothing here uses it
export OPENROUTER_API_KEY=ollama-local # a dummy, so nothing picks up a real key by accident
unset GOOGLE_API_KEY GOOGLE_GENAI_USE_VERTEXAI ANTHROPIC_AUTH_TOKEN ANTHROPIC_PROFILE 2>/dev/null || trueOPENAI_BASE_URL is set even though models.local.yaml gives every route an explicit base_url: it is the canary standin_skip_reason() checks to know this file was sourced. To go back to the hosted providers, open a fresh terminal or unset the variables it sets.
demos/#
The demo scripts are the sN_*.py code blocks shown inline through the lesson — each block's docstring names its file. Save each one under demos/ and run it from the project root with PYTHONPATH=. uv run python demos/<name>.py (the PYTHONPATH=. puts the project root on the import path, which the tests.fakes imports need even after the package is installed):
| File | Where it appears |
|---|---|
s3_types_demo.py |
3.5 |
s4_wire_capture.py |
4.6 |
s5_stream_events.py |
5.1 |
s5_reasoning_demo.py |
5.5 |
s6b_failed_in_200_demo.py |
Part 6 (the failed-inside-200 case) |
s6_errors_demo.py |
Part 6 |
s7_registry_demo.py |
7.1 |
s8_retry_multiplication.py |
8.1 |
s8_timeout_fallback_demo.py |
8.2 |
s8_fallback_demo.py |
8.4 |
s9_fail_closed_demo.py |
Part 9 |
s10_standin_demo.py |
Part 10 |
s12_hosted_sample.py |
Part 12 |
tests/conftest.py#
"""tests/conftest.py: one registry-and-client factory shared by every test file."""
from __future__ import annotations
import os
import socket
import urllib.request
from typing import Any
import pytest
from provider_agnostic.client import LLMClient, Policy
from provider_agnostic.registry import Registry
from tests.fakes import (Fake, FakeAnthropic, FakeChat, FakeGemini, FakeInteractions, FakeResponses, Server,
spec_dict)
# case id -> (fake server shape, registry entry). Every contract test runs once per case.
CASES: dict[str, tuple[Fake, dict[str, Any]]] = {
"openai-responses": (FakeResponses(), spec_dict("openai", "responses", "gpt-6-luna", FakeResponses.base_url,
stop=False)), # the Responses API has no stop parameter
"openai-chat": (FakeChat(), spec_dict("openai", "chat", "gpt-6-luna", FakeChat.base_url)),
"openrouter-chat": (FakeChat(openrouter=True),
spec_dict("openrouter", "chat", "openai/gpt-6-luna", FakeChat.base_url)),
"anthropic": (FakeAnthropic(), spec_dict("anthropic", "messages", "claude-haiku-5-5", "https://mock.test")),
"gemini-generate": (FakeGemini(), spec_dict("gemini", "generate_content", "gemini-3.8-flash", FakeGemini.base_url,
parallel_tool_switch=False, strict_tools=False)), # no switch, no strict flag
"gemini-interactions": (FakeInteractions(), spec_dict("gemini", "interactions", "gemini-3.8-flash",
FakeInteractions.base_url,
parallel_tool_switch=False, strict_tools=False)),
}
CASE_IDS = list(CASES)
@pytest.fixture(autouse=True)
def _no_real_network(request: pytest.FixtureRequest, monkeypatch: pytest.MonkeyPatch) -> None:
"""Fail loudly if a test tries to open a real socket. A mock that silently does not intercept would otherwise
send a real request (respx does that to the openai and anthropic SDKs, which use httpx2). Stand-in tests
are the one deliberate exception."""
if request.node.get_closest_marker("standin"):
return
def refuse(self, *args, **kwargs): # type: ignore[no-untyped-def]
raise RuntimeError("test tried to open a real network connection: use the MockTransport fixtures")
monkeypatch.setattr(socket.socket, "connect", refuse)
@pytest.fixture(autouse=True)
def _fake_key(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("TEST_KEY", "sk-test") # an obviously fake placeholder
def registry_for(entries: dict[str, dict[str, Any]], aliases: dict[str, list[str]] | None = None) -> Registry:
return Registry({"version": "test", "models": entries, "aliases": aliases or {}})
def make_registry_client(entries, aliases=None, **kw): # noqa: ANN001, ANN201
return LLMClient(registry_for(entries, aliases), **kw)
def make_client(case: str, replies: list, **policy: Any) -> tuple[LLMClient, Server]:
"""A real LLMClient with a real SDK underneath, talking to a scripted in-process server."""
fake, spec = CASES[case]
server = Server(replies, flavour=fake.flavour)
client = LLMClient(registry_for({"m": spec}), http_clients={"m": server.clients()},
policy=Policy(**policy), sleep=lambda s: None, asleep=_asleep)
return client, server
async def _asleep(_: float) -> None:
return None
OLLAMA_URL = os.environ.get("STANDIN_OLLAMA_URL", "http://localhost:11434") # point it at a closed port to rehearse "server down"
def standin_up() -> bool:
try:
urllib.request.urlopen(f"{OLLAMA_URL}/api/version", timeout=2)
return True
except OSError:
return False
def standin_skip_reason() -> str | None:
"""Why the stand-in tests are skipped, in words that say what to DO. None = they run."""
if not standin_up():
return f"stand-in not reachable (Ollama {OLLAMA_URL}): start it (lesson 03.1, Part 12)"
if not os.environ.get("OPENAI_BASE_URL"):
# a canary, not a route setting: every models.local.yaml entry carries an explicit base_url, so this
# variable does not point the SDKs anywhere — it is proof that `source localstack/env.sh` ran
return "Ollama is up but this shell has not run `source localstack/env.sh` (OPENAI_BASE_URL is unset)"
return Nonetests/fakes.py#
"""tests/fakes.py: fake provider servers for the contract tests (lesson 03.11, Part 11).
Each Fake* class knows one API's JSON shape (copied from the provider's documented response format, trimmed
to the fields the SDK and our adapter read) and returns (status, headers, body) tuples or SSE bodies.
A Server wraps a script of replies behind an httpx2 (openai, anthropic) or httpx (google-genai) MockTransport
and records every request, so tests can assert on the exact bytes the SDK sent.
"""
from __future__ import annotations
import json
from dataclasses import dataclass, field
from typing import Any, Callable
import httpx
import httpx2
Reply = tuple[int, dict[str, str], bytes] # status, headers, body
def js(status: int, body: dict[str, Any], headers: dict[str, str] | None = None) -> Reply:
return status, {"content-type": "application/json", **(headers or {})}, json.dumps(body).encode()
def sse(events: list[tuple[str | None, dict[str, Any] | str]]) -> Reply:
out = ""
for name, data in events:
out += (f"event: {name}\n" if name else "") + f"data: {data if isinstance(data, str) else json.dumps(data)}\n\n"
return 200, {"content-type": "text/event-stream"}, out.encode()
@dataclass
class Server:
"""A scripted server: replies are consumed in order; the last one repeats. Records requests."""
replies: list[Reply | Exception]
flavour: str = "httpx2" # "httpx2" for openai/anthropic, "httpx" for google-genai
requests: list[dict[str, Any]] = field(default_factory=list)
delay: Callable[[], None] | None = None
def _handle(self, request: Any) -> Any:
body = request.content.decode() if request.content else ""
self.requests.append({"method": request.method, "path": request.url.path, "query": str(request.url.query),
"headers": dict(request.headers), "json": json.loads(body) if body.startswith("{") else None})
if self.delay is not None:
self.delay() # fault injection: e.g. advance a fake clock by 30 s
item = self.replies[min(len(self.requests) - 1, len(self.replies) - 1)]
if isinstance(item, Exception):
raise item
status, headers, content = item
lib = httpx2 if self.flavour == "httpx2" else httpx
return lib.Response(status, headers=headers, content=content)
def clients(self) -> dict[str, Any]:
lib = httpx2 if self.flavour == "httpx2" else httpx
transport = lib.MockTransport(self._handle)
return {"sync": lib.Client(transport=transport), "async": lib.AsyncClient(transport=transport)}
@property
def n(self) -> int:
return len(self.requests)
# ---------------------------------------------------------------------------------------------
class Fake:
"""Common interface. Every method returns a Reply (or a list of SSE events for streams)."""
flavour = "httpx2"
base_url = "https://mock.test/v1"
def text(self, text: str = "Hello there", *, inp: int = 20, out: int = 5, cached: int = 8) -> Reply: ...
def tool_call(self, call_id: str = "call_1", name: str = "get_weather",
args: dict[str, Any] | None = None) -> Reply: ...
def truncated(self) -> Reply: ...
def refusal(self) -> Reply: ...
def blocked(self) -> Reply: ...
def error(self, kind: str) -> Reply: ...
def stream_text(self, pieces: list[str], *, inp: int = 20, out: int = 5, cached: int = 8) -> Reply: ...
def stream_tool(self, call_id: str, name: str, fragments: list[str]) -> Reply: ...
def stream_midway_error(self, pieces: list[str]) -> Reply: ...
ARGS = {"city": "Paris", "unit": "celsius"}
class FakeResponses(Fake):
base_url = "https://mock.test/v1"
def _resp(self, status: str, output: list[dict[str, Any]], usage: dict[str, Any] | None = None,
incomplete: str | None = None, service_tier: str = "default", **extra: Any) -> dict[str, Any]:
return {"id": "resp_1", "object": "response", "created_at": 1, "status": status, "model": "gpt-6-luna-2026-05-18",
"output": output, "parallel_tool_calls": True, "tool_choice": "auto", "tools": [], "error": None,
"incomplete_details": {"reason": incomplete} if incomplete else None, "usage": usage,
"service_tier": service_tier, **extra}
@staticmethod
def _usage(inp: int, out: int, cached: int, written_12h: int = 0) -> dict[str, Any]:
details: dict[str, Any] = {"cached_tokens": cached}
if written_12h: # OpenAI's cache-write split by lifetime
details |= {"cache_write_tokens": written_12h, "cache_write_tokens_details": {"ttl_30m_tokens": 0, "ttl_12h_tokens": written_12h}}
return {"input_tokens": inp, "input_tokens_details": details, "output_tokens": out,
"output_tokens_details": {"reasoning_tokens": 2}, "total_tokens": inp + out}
@staticmethod
def _msg(text: str) -> dict[str, Any]:
return {"id": "msg_1", "type": "message", "status": "completed", "role": "assistant",
"content": [{"type": "output_text", "text": text, "annotations": []}]}
def text(self, text="Hello there", *, inp=20, out=5, cached=8, written_12h=0, service_tier="default",
web_searches=0) -> Reply:
extra = {"tool_usage": {"web_search": {"num_requests": web_searches}}} if web_searches else {}
return js(200, self._resp("completed", [self._msg(text)], self._usage(inp, out, cached, written_12h),
service_tier=service_tier, **extra), {"x-request-id": "req_openai_1"})
def tool_call(self, call_id="call_1", name="get_weather", args=None) -> Reply:
item = {"id": "fc_1", "type": "function_call", "call_id": call_id, "name": name,
"arguments": json.dumps(args or ARGS), "status": "completed"}
return js(200, self._resp("completed", [item], self._usage(30, 12, 0)), {"x-request-id": "req_openai_2"})
def truncated(self) -> Reply:
return js(200, self._resp("incomplete", [self._msg("The answer begins")], self._usage(20, 16, 0),
incomplete="max_output_tokens"))
def refusal(self) -> Reply:
item = {"id": "msg_1", "type": "message", "status": "completed", "role": "assistant",
"content": [{"type": "refusal", "refusal": "I can't help with that."}]}
return js(200, self._resp("completed", [item], self._usage(20, 6, 0)))
def blocked(self) -> Reply:
return js(200, self._resp("incomplete", [], self._usage(20, 0, 0), incomplete="content_filter"))
def error(self, kind: str) -> Reply:
h = {"x-request-id": "req_err_1"}
e = lambda msg, typ, code: {"error": {"message": msg, "type": typ, "param": None, "code": code}} # noqa: E731
return {
"rate_limit": js(429, e("Rate limit reached for requests", "requests", "rate_limit_exceeded"), {**h, "retry-after": "1"}),
"overloaded": js(503, e("The server is overloaded", "server_error", "server_is_overloaded"), h),
"server": js(500, e("The server had an error", "server_error", None), h),
"quota": js(429, e("You exceeded your current quota", "insufficient_quota", "insufficient_quota"), h),
"context": js(400, e("This model's maximum context length is 1050000 tokens", "invalid_request_error",
"context_length_exceeded"), h),
"auth": js(401, e("Incorrect API key provided", "invalid_request_error", "invalid_api_key"), h),
"bad_request": js(400, e("Unknown parameter: 'foo'", "invalid_request_error", "unknown_parameter"), h),
}[kind]
def _events(self, extra: list[tuple[str, dict[str, Any]]]) -> list[tuple[str | None, dict[str, Any] | str]]:
return [("response.created", {"type": "response.created", "sequence_number": 0,
"response": self._resp("in_progress", [])})] + extra # type: ignore[return-value]
def stream_text(self, pieces, *, inp=20, out=5, cached=8) -> Reply:
ev: list[tuple[str, dict[str, Any]]] = [
("response.output_item.added", {"type": "response.output_item.added", "sequence_number": 1, "output_index": 0,
"item": {"id": "msg_1", "type": "message", "status": "in_progress",
"role": "assistant", "content": []}})]
for i, p in enumerate(pieces):
ev.append(("response.output_text.delta", {"type": "response.output_text.delta", "sequence_number": 2 + i,
"item_id": "msg_1", "output_index": 0, "content_index": 0,
"delta": p, "logprobs": []}))
ev.append(("response.completed", {"type": "response.completed", "sequence_number": 99,
"response": self._resp("completed", [self._msg("".join(pieces))],
self._usage(inp, out, cached))}))
return sse(self._events(ev))
def stream_tool(self, call_id, name, fragments) -> Reply:
item = {"id": "fc_1", "type": "function_call", "call_id": call_id, "name": name, "arguments": "", "status": "in_progress"}
ev: list[tuple[str, dict[str, Any]]] = [
("response.output_item.added", {"type": "response.output_item.added", "sequence_number": 1, "output_index": 0, "item": item})]
for i, f in enumerate(fragments):
ev.append(("response.function_call_arguments.delta", {
"type": "response.function_call_arguments.delta", "sequence_number": 2 + i, "item_id": "fc_1",
"output_index": 0, "delta": f}))
done = {**item, "arguments": "".join(fragments), "status": "completed"}
ev.append(("response.output_item.done", {"type": "response.output_item.done", "sequence_number": 90,
"output_index": 0, "item": done}))
ev.append(("response.completed", {"type": "response.completed", "sequence_number": 99,
"response": self._resp("completed", [done], self._usage(30, 12, 0))}))
return sse(self._events(ev))
def failed(self, code: str = "server_error", status: str = "failed") -> Reply:
"""HTTP 200 whose body says the response failed (lesson 03.8, Part 10)."""
body = self._resp(status, [], None)
body["error"] = {"code": code, "message": f"the response {status} ({code})"}
return js(200, body, {"x-request-id": "req_failed_1"})
def stream_failed(self, code: str = "server_error") -> Reply:
"""The stream's terminal event is response.failed, with the error object on the response."""
body = self._resp("failed", [], None)
body["error"] = {"code": code, "message": f"the response failed ({code})"}
return sse(self._events([("response.failed", {"type": "response.failed", "sequence_number": 3, "response": body})]))
def stream_error_event(self, code: str = "rate_limit_exceeded") -> Reply:
"""An `error` event BEFORE any text: its code must survive into the exception class."""
return sse(self._events([("error", {"type": "error", "sequence_number": 3, "code": code,
"message": f"stream error ({code})", "param": None})]))
def stream_midway_error(self, pieces) -> Reply:
ev: list[tuple[str, dict[str, Any]]] = [("response.output_text.delta", {
"type": "response.output_text.delta", "sequence_number": 2, "item_id": "msg_1", "output_index": 0,
"content_index": 0, "delta": pieces[0], "logprobs": []}),
("error", {"type": "error", "sequence_number": 3, "code": "server_error", "message": "boom", "param": None})]
return sse(self._events(ev))
class FakeChat(Fake):
"""OpenAI Chat Completions; with openrouter=True also carries usage.cost like OpenRouter does."""
def __init__(self, openrouter: bool = False) -> None:
self.openrouter = openrouter
def _usage(self, inp: int, out: int, cached: int) -> dict[str, Any]:
u: dict[str, Any] = {"prompt_tokens": inp, "completion_tokens": out, "total_tokens": inp + out,
"prompt_tokens_details": {"cached_tokens": cached},
"completion_tokens_details": {"reasoning_tokens": 2}}
if self.openrouter:
u["cost"] = 0.000123
return u
def _body(self, message: dict[str, Any], finish: str, usage: dict[str, Any] | None,
service_tier: str | None = None) -> dict[str, Any]:
return {"id": "gen-or-1" if self.openrouter else "chatcmpl-1", "object": "chat.completion", "created": 1,
"model": "gpt-6-luna-2026-05-18", "choices": [{"index": 0, "message": {"role": "assistant", **message},
"finish_reason": finish}], "usage": usage,
**({"service_tier": service_tier} if service_tier else {})}
def text(self, text="Hello there", *, inp=20, out=5, cached=8, service_tier=None) -> Reply:
return js(200, self._body({"content": text}, "stop", self._usage(inp, out, cached), service_tier),
{"x-request-id": "req_chat_1"})
def tool_call(self, call_id="call_1", name="get_weather", args=None) -> Reply:
msg = {"content": None, "tool_calls": [{"id": call_id, "type": "function",
"function": {"name": name, "arguments": json.dumps(args or ARGS)}}]}
return js(200, self._body(msg, "tool_calls", self._usage(30, 12, 0)), {"x-request-id": "req_chat_2"})
def truncated(self) -> Reply:
return js(200, self._body({"content": "The answer begins"}, "length", self._usage(20, 16, 0)))
def refusal(self) -> Reply:
return js(200, self._body({"content": None, "refusal": "I can't help with that."}, "stop", self._usage(20, 6, 0)))
def blocked(self) -> Reply:
return js(200, self._body({"content": ""}, "content_filter", self._usage(20, 0, 0)))
def error(self, kind: str) -> Reply:
h = {"x-request-id": "req_err_2"}
if self.openrouter and kind == "error_in_200": # OpenRouter: HTTP 200, error object, no choices
return js(200, {"error": {"code": 429, "message": "Provider returned error"}, "user_id": "user_1"})
e = lambda msg, typ, code: {"error": {"message": msg, "type": typ, "param": None, "code": code}} # noqa: E731
or_e = lambda code, msg, meta=None: {"error": {"code": code, "message": msg, **({"metadata": meta} if meta else {})}} # noqa: E731
if self.openrouter:
return {
"rate_limit": js(429, or_e(429, "Rate limit exceeded"), {**h, "retry-after": "1"}),
"overloaded": js(503, or_e(503, "No available model provider"), h),
"server": js(500, or_e(500, "Internal error"), h),
"quota": js(402, or_e(402, "Insufficient credits. Add more using https://openrouter.ai/credits"), h),
"context": js(400, or_e(400, "This endpoint's maximum context length is 200000 tokens. However, you requested about 250000 tokens")),
"auth": js(401, or_e(401, "No auth credentials found"), h),
"bad_request": js(400, or_e(400, "Invalid parameter"), h),
}[kind]
return FakeResponses().error(kind)
def failed(self, **_: Any) -> Reply:
"""A choice that ends with finish_reason "error" (OpenRouter documents it for a provider that failed mid-request)."""
return js(200, self._body({"content": ""}, "error", self._usage(20, 0, 0)), {"x-request-id": "req_failed_2"})
def stream_failed(self, **_: Any) -> Reply:
"""Before any text: an error object and finish_reason "error" in the first chunk."""
return sse([(None, {"error": {"code": 500, "message": "upstream failed"}, "id": "x", "object": "chat.completion.chunk",
"created": 1, "model": "m",
"choices": [{"index": 0, "delta": {"content": ""}, "finish_reason": "error"}]})])
def _chunk(self, delta: dict[str, Any], finish: str | None = None, usage: dict[str, Any] | None = None,
empty_choices: bool = False, service_tier: str | None = None) -> tuple[None, dict[str, Any]]:
return None, {"id": "chatcmpl-1", "object": "chat.completion.chunk", "created": 1, "model": "gpt-6-luna-2026-05-18",
"choices": [] if empty_choices else [{"index": 0, "delta": delta, "finish_reason": finish}],
**({"usage": usage} if usage else {}), **({"service_tier": service_tier} if service_tier else {})}
def stream_text(self, pieces, *, inp=20, out=5, cached=8, service_tier=None) -> Reply:
ev = [self._chunk({"role": "assistant", "content": ""})] + [self._chunk({"content": p}) for p in pieces]
ev.append(self._chunk({}, "stop"))
ev.append(self._chunk({}, usage=self._usage(inp, out, cached), empty_choices=not self.openrouter,
service_tier=service_tier))
return sse(ev + [(None, "[DONE]")])
def stream_tool(self, call_id, name, fragments) -> Reply:
ev = [self._chunk({"role": "assistant", "tool_calls": [{"index": 0, "id": call_id, "type": "function",
"function": {"name": name, "arguments": ""}}]})]
ev += [self._chunk({"tool_calls": [{"index": 0, "function": {"arguments": f}}]}) for f in fragments]
ev.append(self._chunk({}, "tool_calls"))
ev.append(self._chunk({}, usage=self._usage(30, 12, 0), empty_choices=not self.openrouter))
return sse(ev + [(None, "[DONE]")])
def stream_midway_error(self, pieces) -> Reply:
return sse([self._chunk({"content": pieces[0]}),
(None, {"error": {"code": 500, "message": "boom"}, "id": "x", "choices": [{"index": 0, "delta": {"content": ""}, "finish_reason": "error"}]})])
class FakeAnthropic(Fake):
base_url = "https://mock.test"
def _usage(self, inp: int, out: int, cached: int, usage_extra: dict[str, Any] | None = None) -> dict[str, Any]:
return {"input_tokens": inp - cached, "output_tokens": out, "cache_read_input_tokens": cached,
"cache_creation_input_tokens": 0, **(usage_extra or {})}
def _msg(self, content: list[dict[str, Any]], stop: str, usage: dict[str, Any], model: str = "claude-haiku-5-5") -> dict[str, Any]:
return {"id": "msg_01", "type": "message", "role": "assistant", "model": model,
"content": content, "stop_reason": stop, "stop_sequence": None, "usage": usage}
def text(self, text="Hello there", *, inp=20, out=5, cached=8, usage_extra=None, model="claude-haiku-5-5") -> Reply:
return js(200, self._msg([{"type": "text", "text": text}], "end_turn", self._usage(inp, out, cached, usage_extra), model),
{"request-id": "req_anth_1"})
def tool_call(self, call_id="toolu_1", name="get_weather", args=None) -> Reply:
return js(200, self._msg([{"type": "tool_use", "id": call_id, "name": name, "input": args or ARGS}],
"tool_use", self._usage(30, 12, 0)), {"request-id": "req_anth_2"})
def truncated(self) -> Reply:
return js(200, self._msg([{"type": "text", "text": "The answer begins"}], "max_tokens", self._usage(20, 16, 0)))
def refusal(self) -> Reply:
return js(200, self._msg([{"type": "text", "text": "I can't help with that."}], "refusal", self._usage(20, 6, 0)))
def blocked(self) -> Reply:
return self.refusal()
def error(self, kind: str) -> Reply:
h = {"request-id": "req_err_3"}
e = lambda typ, msg: {"type": "error", "error": {"type": typ, "message": msg}, "request_id": "req_err_3"} # noqa: E731
return {
"rate_limit": js(429, e("rate_limit_error", "Number of request tokens has exceeded your rate limit"), {**h, "retry-after": "1"}),
"overloaded": js(529, e("overloaded_error", "Overloaded"), h),
"server": js(500, e("api_error", "Internal server error"), h),
"quota": js(402, e("billing_error", "There is an issue with your billing or payment information."), h),
"context": js(400, e("invalid_request_error", "prompt is too long: 250000 tokens > 200000 maximum"), h),
"auth": js(401, e("authentication_error", "invalid x-api-key"), h),
"bad_request": js(400, e("invalid_request_error", "messages: field required"), h),
}[kind]
def stream_text(self, pieces, *, inp=20, out=5, cached=8, usage_extra=None, model="claude-haiku-5-5") -> Reply:
ev: list[tuple[str | None, dict[str, Any] | str]] = [
("message_start", {"type": "message_start", "message": self._msg([], None, self._usage(inp, 1, cached, usage_extra), model) | {"stop_reason": None}}), # type: ignore[dict-item]
("content_block_start", {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}),
("ping", {"type": "ping"})]
ev += [("content_block_delta", {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": p}}) for p in pieces]
ev += [("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": out}}),
("message_stop", {"type": "message_stop"})]
return sse(ev)
def stream_tool(self, call_id, name, fragments) -> Reply:
ev: list[tuple[str | None, dict[str, Any] | str]] = [
("message_start", {"type": "message_start", "message": self._msg([], None, self._usage(30, 1, 0))}),
("content_block_start", {"type": "content_block_start", "index": 0,
"content_block": {"type": "tool_use", "id": call_id, "name": name, "input": {}}})]
ev += [("content_block_delta", {"type": "content_block_delta", "index": 0,
"delta": {"type": "input_json_delta", "partial_json": f}}) for f in fragments]
ev += [("content_block_stop", {"type": "content_block_stop", "index": 0}),
("message_delta", {"type": "message_delta", "delta": {"stop_reason": "tool_use", "stop_sequence": None},
"usage": {"output_tokens": 12}}),
("message_stop", {"type": "message_stop"})]
return sse(ev)
def stream_midway_error(self, pieces) -> Reply:
return sse([("message_start", {"type": "message_start", "message": self._msg([], None, self._usage(20, 1, 0))}),
("content_block_start", {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}}),
("content_block_delta", {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": pieces[0]}}),
("error", {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}})])
class FakeGemini(Fake):
flavour = "httpx"
base_url = "https://mock.test"
def _usage(self, inp: int, out: int, cached: int) -> dict[str, Any]:
return {"promptTokenCount": inp, "candidatesTokenCount": out, "totalTokenCount": inp + out + 2,
"cachedContentTokenCount": cached, "thoughtsTokenCount": 2}
def _body(self, parts: list[dict[str, Any]], finish: str, usage: dict[str, Any] | None) -> dict[str, Any]:
return {"candidates": [{"content": {"role": "model", "parts": parts}, "finishReason": finish, "index": 0}],
"usageMetadata": usage, "modelVersion": "gemini-3.8-flash", "responseId": "resp_gem_1"}
def text(self, text="Hello there", *, inp=20, out=5, cached=8, service_tier=None) -> Reply:
return js(200, self._body([{"text": text}], "STOP", self._usage(inp, out, cached)),
{"x-gemini-service-tier": service_tier} if service_tier else None)
def tool_call(self, call_id="", name="get_weather", args=None) -> Reply:
fc: dict[str, Any] = {"name": name, "args": args or ARGS}
if call_id:
fc["id"] = call_id
return js(200, self._body([{"functionCall": fc, "thoughtSignature": "c2lnLTE="}], "STOP", self._usage(30, 12, 0)))
def truncated(self) -> Reply:
return js(200, self._body([{"text": "The answer begins"}], "MAX_TOKENS", self._usage(20, 16, 0)))
def refusal(self) -> Reply:
return self.blocked()
def blocked(self) -> Reply:
return js(200, self._body([], "SAFETY", self._usage(20, 0, 0)))
def error(self, kind: str) -> Reply:
e = lambda code, status, msg: {"error": {"code": code, "message": msg, "status": status}} # noqa: E731
return {
"rate_limit": js(429, e(429, "RESOURCE_EXHAUSTED", "Resource has been exhausted (e.g. check quota)")),
"overloaded": js(503, e(503, "UNAVAILABLE", "The model is overloaded. Please try again later.")),
"server": js(500, e(500, "INTERNAL", "An internal error has occurred.")),
"quota": js(429, e(429, "RESOURCE_EXHAUSTED", "You exceeded your current quota, please check your plan and billing details.")),
"context": js(400, e(400, "INVALID_ARGUMENT", "The input token count exceeds the maximum number of tokens allowed 1048576.")),
"auth": js(401, e(401, "UNAUTHENTICATED", "API keys are not supported by this API.")),
"bad_request": js(400, e(400, "INVALID_ARGUMENT", "Invalid JSON payload received.")),
}[kind]
def stream_text(self, pieces, *, inp=20, out=5, cached=8, zero_usage=False) -> Reply:
ev: list[tuple[str | None, dict[str, Any] | str]] = []
for i, p in enumerate(pieces):
last = i == len(pieces) - 1
body = {"candidates": [{"content": {"role": "model", "parts": [{"text": p}]}, "index": 0,
**({"finishReason": "STOP"} if last else {})}], "modelVersion": "gemini-3.8-flash",
"responseId": "resp_gem_1"}
if last: # zero_usage: what a proxy can send on a stream
body["usageMetadata"] = {"promptTokenCount": 0, "candidatesTokenCount": 0, "totalTokenCount": 0} if zero_usage else self._usage(inp, out, cached)
ev.append((None, body))
return sse(ev)
def stream_tool(self, call_id, name, fragments) -> Reply: # Gemini sends the whole call: no fragments
args = json.loads("".join(fragments))
fc: dict[str, Any] = {"name": name, "args": args}
if call_id:
fc["id"] = call_id
return sse([(None, {"candidates": [{"content": {"role": "model", "parts": [{"functionCall": fc}]},
"finishReason": "STOP", "index": 0}], "usageMetadata": self._usage(30, 12, 0),
"responseId": "resp_gem_1", "modelVersion": "gemini-3.8-flash"})])
def stream_midway_error(self, pieces) -> Reply:
# a stream that stops after the first chunk with no finishReason: the "ended without a terminal event" case
return sse([(None, {"candidates": [{"content": {"role": "model", "parts": [{"text": pieces[0]}]}, "index": 0}]})])
class FakeInteractions(Fake):
flavour = "httpx"
base_url = "https://mock.test"
def _usage(self, inp: int, out: int, cached: int) -> dict[str, Any]:
return {"total_input_tokens": inp, "total_output_tokens": out, "total_cached_tokens": cached,
"total_thought_tokens": 2, "total_tokens": inp + out + 2}
def _body(self, steps: list[dict[str, Any]], status: str, usage: dict[str, Any] | None) -> dict[str, Any]:
return {"id": "int_1", "status": status, "model": "gemini-3.8-flash", "steps": steps, "usage": usage}
def text(self, text="Hello there", *, inp=20, out=5, cached=8) -> Reply:
return js(200, self._body([{"type": "model_output", "content": [{"type": "text", "text": text}]}],
"completed", self._usage(inp, out, cached)))
def tool_call(self, call_id="fc_1", name="get_weather", args=None) -> Reply:
return js(200, self._body([{"type": "thought", "signature": "c2lnLTE="},
{"type": "function_call", "id": call_id, "name": name, "arguments": args or ARGS}],
"completed", self._usage(30, 12, 0)))
def truncated(self) -> Reply:
return js(200, self._body([{"type": "model_output", "content": [{"type": "text", "text": "The answer begins"}]}],
"incomplete", self._usage(20, 16, 0)))
def refusal(self) -> Reply:
return js(200, self._body([], "failed", self._usage(20, 0, 0)))
def blocked(self) -> Reply:
return self.refusal()
def error(self, kind: str) -> Reply:
e = lambda status, code, msg: js(status, {"error": {"code": code, "message": msg}}) # noqa: E731
return {
"rate_limit": e(429, "rate_limit_exceeded", "Too many requests"),
"overloaded": e(503, "service_unavailable", "The model is overloaded"),
"server": e(500, "internal", "Internal error"),
"quota": e(429, "quota_exceeded", "Daily quota exceeded"),
"context": e(400, "invalid_request", "The input token count exceeds the maximum number of tokens allowed"),
"auth": e(401, "unauthenticated", "Invalid API key"),
"bad_request": e(400, "invalid_request", "Invalid JSON payload received."),
}[kind]
def stream_text(self, pieces, *, inp=20, out=5, cached=8) -> Reply:
ev: list[tuple[str | None, dict[str, Any] | str]] = [
("interaction.created", {"event_type": "interaction.created", "interaction": {"id": "int_1", "status": "in_progress"}}),
("step.start", {"event_type": "step.start", "index": 0, "step": {"type": "model_output"}})]
ev += [("step.delta", {"event_type": "step.delta", "index": 0, "delta": {"type": "text", "text": p}}) for p in pieces]
ev += [("step.stop", {"event_type": "step.stop", "index": 0}),
("interaction.completed", {"event_type": "interaction.completed",
"interaction": {"id": "int_1", "status": "completed", "usage": self._usage(inp, out, cached)}}),
(None, "[DONE]")]
return sse(ev)
def stream_tool(self, call_id, name, fragments) -> Reply:
ev: list[tuple[str | None, dict[str, Any] | str]] = [
("interaction.created", {"event_type": "interaction.created", "interaction": {"id": "int_1", "status": "in_progress"}}),
("step.start", {"event_type": "step.start", "index": 0,
"step": {"type": "function_call", "id": call_id, "name": name, "arguments": {}}})]
ev += [("step.delta", {"event_type": "step.delta", "index": 0, "delta": {"type": "arguments_delta", "arguments": f}}) for f in fragments]
ev += [("step.stop", {"event_type": "step.stop", "index": 0}),
("interaction.completed", {"event_type": "interaction.completed",
"interaction": {"id": "int_1", "status": "completed", "usage": self._usage(30, 12, 0)}}),
(None, "[DONE]")]
return sse(ev)
def failed(self, code: str | None = "rate_limit_exceeded", status: str = "failed") -> Reply:
body = self._body([], status, self._usage(20, 0, 0))
if code:
body["errors"] = [{"code": code, "message": f"interaction {status} ({code})"}]
return js(200, body)
def stream_failed(self, code: str | None = "rate_limit_exceeded", status: str = "failed") -> Reply:
inter: dict[str, Any] = {"id": "int_1", "status": status, "usage": self._usage(20, 0, 0)}
if code:
inter["errors"] = [{"code": code, "message": f"interaction {status} ({code})"}]
return sse([("interaction.created", {"event_type": "interaction.created", "interaction": {"id": "int_1", "status": "in_progress"}}),
("interaction.completed", {"event_type": "interaction.completed", "interaction": inter}),
(None, "[DONE]")])
def stream_midway_error(self, pieces) -> Reply:
return sse([("step.start", {"event_type": "step.start", "index": 0, "step": {"type": "model_output"}}),
("step.delta", {"event_type": "step.delta", "index": 0, "delta": {"type": "text", "text": pieces[0]}}),
("error", {"event_type": "error", "error": {"code": "gateway_timeout", "message": "boom"}})])
def _stream_headers(cls: type, headers: dict[str, str]) -> None:
"""Real streaming responses carry the same request-ID header as plain ones: add it to every scripted stream."""
for name in ("stream_text", "stream_tool", "stream_midway_error", "stream_failed", "stream_error_event"):
original = getattr(cls, name, None)
if original is None:
continue
def wrapper(self, *a, _orig=original, **k): # type: ignore[no-untyped-def]
status, h, body = _orig(self, *a, **k)
return status, {**h, **headers}, body
setattr(cls, name, wrapper)
_stream_headers(FakeResponses, {"x-request-id": "req_openai_s1"})
_stream_headers(FakeChat, {"x-request-id": "req_chat_s1"})
_stream_headers(FakeAnthropic, {"request-id": "req_anth_s1"})
# One entry per contract case: registry entry key -> (fake, extra model-spec overrides)
def spec_dict(provider: str, api: str, model: str, base_url: str, **caps: bool) -> dict[str, Any]:
capabilities = {"tools": True, "forced_tool_choice": True, "structured_output": True, "images": True,
"image_urls": True, "documents": True, "reasoning": True, "stop": True,
"parallel_tool_switch": True, "strict_tools": True, **caps}
return {"provider": provider, "api": api, "model": model, "base_url": base_url, "api_key_env": "TEST_KEY",
"default_max_output_tokens": 256, "reasoning_off": "none", "capabilities": capabilities}tests/test_contract.py#
"""tests/test_contract.py: the SHARED CONTRACT. Every adapter must pass every test in this file.
A new adapter is "done" when it is added to CASES in conftest.py and this file stays green.
All servers here are mocks (layer 3): the real SDKs run, the network does not.
"""
from __future__ import annotations
import json
import pytest
from provider_agnostic.errors import (AuthFailed, BadRequest, ContextTooLong, LLMError, Overloaded, QuotaExceeded, RateLimited,
ServerError, Timeout, ConnectionFailed, Truncated, Refused, ContentBlocked, raise_for_finish)
from provider_agnostic.types import (Done, FinishReason, Message, Request, TextDelta, ToolCallDelta, ToolCallPart, ToolCallStart,
ToolResultPart, ToolSpec, UsageEvent)
from tests.conftest import CASE_IDS, CASES, make_client
from tests.fakes import ARGS
pytestmark = pytest.mark.parametrize("case", CASE_IDS)
HELLO = Request(model="m", messages=[Message.user("Say hello")])
WEATHER = ToolSpec(name="get_weather", description="Get the weather for a city",
parameters={"type": "object", "properties": {"city": {"type": "string"},
"unit": {"type": "string"}}, "required": ["city"]})
def fake(case: str):
return CASES[case][0]
# ------------------------------------------------------------------ plain responses
def test_plain_text_and_usage(case: str) -> None:
client, server = make_client(case, [fake(case).text("Hello there", inp=20, out=5, cached=8)])
resp = client.complete(HELLO)
assert resp.text == "Hello there"
assert resp.finish_reason is FinishReason.STOP
u = resp.usage
assert u is not None
# the contract: input EXCLUDES the 8 cached tokens, output INCLUDES reasoning, on every provider
assert (u.uncached_input_tokens, u.cached_input_tokens) == (12, 8)
assert u.output_tokens in (5, 7) # Gemini adds its 2 thought tokens to the output count
assert resp.provider == CASES[case][1]["provider"] and resp.requested_model == "m"
assert resp.cost is not None and resp.cost.usd is None # no price table given: unknown, never 0
assert server.n == 1
def test_truncated_is_length_and_raises_on_request(case: str) -> None:
client, _ = make_client(case, [fake(case).truncated()])
resp = client.complete(HELLO)
assert resp.finish_reason is FinishReason.LENGTH
with pytest.raises(Truncated):
raise_for_finish(resp)
def test_refusal_or_block_is_not_stop(case: str) -> None:
if case == "gemini-interactions":
pytest.skip("Google documents no refusal signal for Interactions; a `failed` status is an ERROR (test_critical_fixes.py)")
client, _ = make_client(case, [fake(case).refusal()])
resp = client.complete(HELLO)
assert resp.finish_reason in (FinishReason.REFUSAL, FinishReason.CONTENT_FILTER, FinishReason.ERROR)
with pytest.raises((Refused, ContentBlocked, LLMError)):
raise_for_finish(resp)
def test_raw_finish_reason_is_kept(case: str) -> None:
client, _ = make_client(case, [fake(case).truncated()])
assert client.complete(HELLO).raw_finish_reason # normalizing loses information: the original survives
# ------------------------------------------------------------------ tools
def test_tool_call_parsed_with_dict_arguments(case: str) -> None:
client, _ = make_client(case, [fake(case).tool_call()])
resp = client.complete(Request(model="m", messages=[Message.user("Weather in Paris?")], tools=[WEATHER]))
assert resp.finish_reason is FinishReason.TOOL_CALLS
(call,) = resp.tool_calls
assert call.name == "get_weather" and call.arguments == ARGS # OpenAI's JSON string is a dict here
assert call.arguments_error is None
def test_tool_result_goes_back_with_the_same_id(case: str) -> None:
"""Round trip: the second request must carry the call's ID in this provider's own field."""
client, server = make_client(case, [fake(case).tool_call(), fake(case).text("It is 12 C")])
first = client.complete(Request(model="m", messages=[Message.user("Weather in Paris?")], tools=[WEATHER]))
call = first.tool_calls[0]
history = [Message.user("Weather in Paris?"), first.message,
Message.tool_results(ToolResultPart(call_id=call.id, name=call.name, content='{"temp": 12}'))]
client.complete(Request(model="m", messages=history, tools=[WEATHER]))
wire = json.dumps(server.requests[1]["json"])
assert '{"temp": 12}' in wire.replace('\\"', '"') or "temp" in wire
if call.id: # Gemini generate_content may legitimately have no ID
assert call.id in wire
# ------------------------------------------------------------------ structured output
def test_structured_output_validates_into_the_model(case: str) -> None:
from pydantic import BaseModel
class City(BaseModel):
name: str
country: str
client, server = make_client(case, [fake(case).text('{"name": "Paris", "country": "France"}')])
resp = client.complete(Request(model="m", messages=[Message.user("A French city")], output_schema=City))
assert isinstance(resp.parsed, City) and resp.parsed.name == "Paris"
assert "City" in json.dumps(server.requests[0]["json"]) or "country" in json.dumps(server.requests[0]["json"])
def test_invalid_structured_output_raises_output_invalid(case: str) -> None:
from pydantic import BaseModel
from provider_agnostic.errors import OutputInvalid
class City(BaseModel):
name: str
client, _ = make_client(case, [fake(case).text("not json at all")])
with pytest.raises(OutputInvalid) as info:
client.complete(Request(model="m", messages=[Message.user("A city")], output_schema=City))
assert info.value.__cause__ is not None # the original pydantic error is kept
# ------------------------------------------------------------------ errors
@pytest.mark.parametrize("kind, exc, retryable", [
("rate_limit", RateLimited, True), ("overloaded", Overloaded, True), ("server", ServerError, True),
("quota", QuotaExceeded, False), ("context", ContextTooLong, False), ("auth", AuthFailed, False),
("bad_request", BadRequest, False)])
def test_error_mapping(case: str, kind: str, exc: type[LLMError], retryable: bool) -> None:
if case == "openrouter-chat" and kind == "overloaded":
pytest.skip("covered by the OpenRouter-specific tests")
if case == "gemini-generate" and kind == "quota":
# The one honest exception to the contract: Gemini models.* sends RESOURCE_EXHAUSTED for both "slow down"
# and "out of quota", with nothing in the body to tell them apart (lesson 03.8, 4.2).
exc, retryable = RateLimited, True
client, server = make_client(case, [fake(case).error(kind)], max_attempts=1)
with pytest.raises(exc) as info:
client.complete(HELLO)
err = info.value
assert err.retryable is retryable
assert err.__cause__ is not None # the SDK exception is never swallowed
assert err.provider == CASES[case][1]["provider"]
assert len(err.attempts) == 1 and not err.attempts[0].ok
assert server.n == 1
def test_provider_request_id_survives_on_errors(case: str) -> None:
if case.startswith("gemini"):
pytest.skip("Google sends no request-id header (lesson 03.8, Part 12)")
client, _ = make_client(case, [fake(case).error("server")], max_attempts=1)
with pytest.raises(ServerError) as info:
client.complete(HELLO)
assert info.value.request_id
def test_timeout_and_connection_errors(case: str) -> None:
import httpx
import httpx2
lib = httpx2 if CASES[case][0].flavour == "httpx2" else httpx
client, _ = make_client(case, [lib.ReadTimeout("slow")], max_attempts=1)
with pytest.raises(Timeout) as t:
client.complete(HELLO)
assert t.value.retryable
client, _ = make_client(case, [lib.ConnectError("refused")], max_attempts=1)
with pytest.raises(ConnectionFailed):
client.complete(HELLO)
# ------------------------------------------------------------------ retries: one layer owns them
def test_retries_happen_once_not_multiplied(case: str) -> None:
"""Primary fails twice then succeeds. If the SDK also retried (max_retries=2) we would see 6+ requests."""
f = fake(case)
client, server = make_client(case, [f.error("overloaded") if case != "openrouter-chat" else f.error("server"),
f.error("server"), f.text()], max_attempts=3)
resp = client.complete(HELLO)
assert resp.text == "Hello there"
assert server.n == 3 # exactly: fail, fail, succeed
assert [a.ok for a in resp.attempts] == [False, False, True]
def test_retry_gives_up_after_max_attempts(case: str) -> None:
f = fake(case)
client, server = make_client(case, [f.error("server")], max_attempts=3)
with pytest.raises(ServerError):
client.complete(HELLO)
assert server.n == 3
def test_non_retryable_is_not_retried(case: str) -> None:
client, server = make_client(case, [fake(case).error("bad_request"), fake(case).text()], max_attempts=3)
with pytest.raises(BadRequest):
client.complete(HELLO)
assert server.n == 1
# ------------------------------------------------------------------ streaming
def test_stream_text(case: str) -> None:
client, _ = make_client(case, [fake(case).stream_text(["Hel", "lo ", "there"], inp=20, out=5, cached=8)])
events = list(client.stream(HELLO))
text = "".join(e.text for e in events if isinstance(e, TextDelta))
assert text == "Hello there"
done = events[-1]
assert isinstance(done, Done) and done.response.text == "Hello there"
assert done.response.finish_reason is FinishReason.STOP
assert done.response.usage is not None and done.response.usage.cached_input_tokens == 8
assert any(isinstance(e, UsageEvent) for e in events)
def test_stream_tool_call_fragments_parse_once(case: str) -> None:
pieces = ['{"city": "Pa', 'ris", "unit":', ' "celsius"}']
client, _ = make_client(case, [fake(case).stream_tool("call_9", "get_weather", pieces)])
events = list(client.stream(Request(model="m", messages=[Message.user("Weather?")], tools=[WEATHER])))
done = events[-1]
assert isinstance(done, Done)
(call,) = done.response.tool_calls
assert call.name == "get_weather" and call.arguments == ARGS and call.arguments_error is None
assert done.response.finish_reason is FinishReason.TOOL_CALLS
assert any(isinstance(e, ToolCallStart) for e in events)
if not case.startswith("gemini-generate"): # Gemini sends whole calls: no fragments to see
assert sum(isinstance(e, ToolCallDelta) for e in events) >= 1
def test_stream_error_after_first_text_is_not_retried(case: str) -> None:
"""After the consumer has seen text, silently starting over would splice two answers together."""
client, server = make_client(case, [fake(case).stream_midway_error(["Par"]), fake(case).stream_text(["X"])])
got: list[str] = []
with pytest.raises(LLMError) as info:
for ev in client.stream(HELLO):
if isinstance(ev, TextDelta):
got.append(ev.text)
assert got == ["Par"] and server.n == 1
assert info.value.partial is not None and info.value.partial.text == "Par"
def test_stream_retries_before_first_text(case: str) -> None:
f = fake(case)
client, server = make_client(case, [f.error("overloaded") if case != "openrouter-chat" else f.error("server"),
f.stream_text(["Hi"])])
events = list(client.stream(HELLO))
assert isinstance(events[-1], Done) and events[-1].response.text == "Hi"
assert server.n == 2 and [a.ok for a in events[-1].response.attempts] == [False, True]
# ------------------------------------------------------------------ async mirrors the sync path
async def test_async_complete_and_stream_match_sync(case: str) -> None:
f = fake(case)
client, _ = make_client(case, [f.text("Hello there")])
assert (await client.acomplete(HELLO)).text == "Hello there"
client, _ = make_client(case, [f.stream_text(["Hel", "lo"])])
events = [e async for e in client.astream(HELLO)]
assert isinstance(events[-1], Done) and events[-1].response.text == "Hello"
client, server = make_client(case, [f.error("server"), f.text()], max_attempts=2)
assert (await client.acomplete(HELLO)).text == "Hello there" and server.n == 2
# ------------------------------------------------------------------ the original object stays reachable
def test_raw_response_and_ids(case: str) -> None:
client, _ = make_client(case, [fake(case).text()])
resp = client.complete(HELLO)
assert resp.raw is not None # the escape hatch: provider-native fields live here
assert resp.request_id, "the provider's own ID must reach the caller (support tickets need it)"
assert resp.resolved_model
assert len(resp.call_id) == 16tests/test_types_registry.py#
"""tests/test_types_registry.py: canonical types and the capability registry (layer 1: pure, no network)."""
from __future__ import annotations
import pytest
from pydantic import BaseModel
from provider_agnostic.errors import ConfigError, UnsupportedFeature
from provider_agnostic.registry import Registry, check_capabilities
from provider_agnostic.types import (DocumentPart, FinishReason, ForcedTool, ImagePart, Message, Native, ReasoningPart, Request,
Response, TextPart, ToolCallPart, ToolResultPart, ToolSpec, Usage)
def test_message_round_trips_through_json_with_natives() -> None:
msg = Message(role="assistant", parts=[
ReasoningPart(text="thinking...", native=Native(provider="anthropic", api="messages",
payload={"type": "thinking", "signature": "abc"})),
TextPart(text="Hi"),
ToolCallPart(id="toolu_1", name="get_weather", arguments={"city": "Paris"})])
again = Message.model_validate_json(msg.model_dump_json())
assert again == msg
assert isinstance(again.parts[0], ReasoningPart) and again.parts[0].native is not None # discriminated union
assert msg.text == "Hi"
def test_tool_spec_from_pydantic_model() -> None:
class GetWeather(BaseModel):
"""Get the weather for a city."""
city: str
spec = ToolSpec.from_model(GetWeather)
assert spec.name == "GetWeather" and spec.description == "Get the weather for a city."
assert spec.parameters["properties"]["city"]["type"] == "string"
def test_usage_total_input_counts_every_prompt_token() -> None:
u = Usage(uncached_input_tokens=12, cached_input_tokens=8, cache_write_tokens={"5m": 100}, output_tokens=5)
assert u.total_input_tokens == 120
def test_response_properties() -> None:
r = Response(parts=[ReasoningPart(text="because"), TextPart(text="A"), TextPart(text="B"),
ToolCallPart(id="1", name="t", arguments={})],
finish_reason=FinishReason.TOOL_CALLS, raw_finish_reason="tool_use", usage=None,
provider="anthropic", api="messages")
assert r.text == "AB" and r.reasoning == "because" and len(r.tool_calls) == 1
assert r.message.role == "assistant" and len(r.message.parts) == 4
@pytest.fixture(scope="module")
def reg() -> Registry:
return Registry.load()
def test_registry_loads_and_chains(reg: Registry) -> None:
assert [s.key for s in reg.chain("fast")] == ["luna", "haiku", "flash"]
assert [s.key for s in reg.chain("haiku")] == ["haiku"] # a bare entry key is a chain of one
assert reg.models["flash"].api == "generate_content" and reg.models["flash-interactions"].api == "interactions"
def test_unknown_alias_lists_the_choices(reg: Registry) -> None:
with pytest.raises(ConfigError, match="known aliases"):
reg.chain("nope")
def test_alias_pointing_at_missing_entry_fails_at_load() -> None:
with pytest.raises(ConfigError, match="unknown model entry"):
Registry({"version": "test", "models": {}, "aliases": {"fast": ["ghost"]}})
def test_capability_check_forced_tool_choice_on_sonnet(reg: Registry) -> None:
req = Request(model="sonnet", messages=[Message.user("x")], tools=[ToolSpec(name="t", description="d", parameters={})],
tool_choice=ForcedTool(name="t"))
check_capabilities(req.model_copy(update={"tool_choice": "auto"}), reg.models["sonnet"]) # fine
with pytest.raises(UnsupportedFeature, match="forced tool use"):
check_capabilities(req, reg.models["sonnet"]) # a 400 on the wire
check_capabilities(req, reg.models["haiku"]) # Haiku 5.5 accepts it
def test_capability_check_image_urls_and_documents(reg: Registry) -> None:
url_img = Message(role="user", parts=[ImagePart(media_type="image/png", url="https://example.com/a.png")])
local = Registry.load("provider_agnostic/models.local.yaml")
with pytest.raises(UnsupportedFeature, match="image input"):
check_capabilities(Request(model="m", messages=[url_img]), local.models["local-chat"])
for key in ("haiku", "flash", "luna", "or-luna"):
check_capabilities(Request(model="m", messages=[url_img]), reg.models[key]) # all four fetch https URLs
pdf = Message(role="user", parts=[DocumentPart(data_b64="AAAA")])
with pytest.raises(UnsupportedFeature, match="document"):
check_capabilities(Request(model="m", messages=[pdf]), local.models["local-chat"])
def test_capability_check_structured_output_and_limits() -> None:
local = Registry.load("provider_agnostic/models.local.yaml")
class Out(BaseModel):
x: int
with pytest.raises(UnsupportedFeature, match="structured output"):
check_capabilities(Request(model="m", messages=[Message.user("x")], output_schema=Out), local.models["local-anthropic"])
reg = Registry.load()
with pytest.raises(UnsupportedFeature, match="limit"):
check_capabilities(Request(model="m", messages=[Message.user("x")], max_output_tokens=999_999), reg.models["flash"])
with pytest.raises(UnsupportedFeature, match="reasoning_effort"):
check_capabilities(Request(model="m", messages=[Message.user("x")], reasoning_effort="high"), local.models["local-chat"])
check_capabilities(Request(model="m", messages=[Message.user("x")], reasoning_effort="off"), local.models["local-chat"])
def test_every_registry_entry_has_a_price_or_is_free() -> None:
"""Prices live in prices.yaml (lesson 03.7). A registry entry without one would report cost unknown."""
from prices import PriceTable
table = PriceTable.load()
for path in ("provider_agnostic/models.yaml", "provider_agnostic/models.local.yaml"):
for spec in Registry.load(path).models.values():
if spec.free:
continue
table.model(spec.provider, spec.model) # raises KeyError with a clear messagetests/test_request_contract.py#
"""tests/test_request_contract.py: every canonical Request field is on the wire, or the wrapper refuses (layer 1, no network).
This is the test that makes the thin-wrapper rule "never silently drop an option" TRUE (lesson 03.11, 1.3 and 7.3), plus
the `extra` escape hatch (deep-merged, never allowed to replace the model or the messages) and the registry's own
safety checks (typos, empty chains, credentials, local keys).
"""
from __future__ import annotations
import json
from typing import Any
import pytest
from pydantic import BaseModel
from provider_agnostic.client import ADAPTERS, LLMClient
from provider_agnostic.errors import ConfigError, UnsupportedFeature
from provider_agnostic.registry import Registry, check_capabilities, resolve_headers
from provider_agnostic.types import ForcedTool, Message, Request, ToolCallPart, ToolResultPart, ToolSpec
from tests.conftest import CASE_IDS, CASES, registry_for
from tests.fakes import FakeAnthropic, Server
WEATHER = {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}
class SchemaMark(BaseModel):
field_mark: str
def wire(case: str, req: Request) -> str:
"""The adapter's request, as the JSON text that would go to the SDK."""
spec = Registry({"version": "t", "models": {"m": CASES[case][1]}}).models["m"]
params = ADAPTERS[spec.api](spec).build(req)
return json.dumps(params, default=lambda o: o.model_dump(mode="json", exclude_none=True)).lower()
def sent_or_refused(case: str, req: Request, *needles: str) -> str:
"""Either check_capabilities refuses this field on this route, or the value is on the wire. Never neither."""
spec = Registry({"version": "t", "models": {"m": CASES[case][1]}}).models["m"]
try:
check_capabilities(req, spec)
except UnsupportedFeature:
return "refused"
text = wire(case, req)
assert all(n.lower() in text for n in needles), f"{case}: {needles} silently dropped from {text[:300]}"
return "sent"
CALL = [Message.user("hi")]
TOOL = ToolSpec(name="tool_mark", description="d", parameters=WEATHER)
@pytest.mark.parametrize("case", CASE_IDS)
def test_every_request_field_is_on_the_wire_or_refused(case: str, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("TEST_KEY", "x")
base: dict[str, Any] = {"model": "m", "messages": CALL}
with_tool = {**base, "tools": [TOOL]}
results = {
"system": sent_or_refused(case, Request(**base, system="SYS-MARK"), "SYS-MARK"),
"max_output_tokens": sent_or_refused(case, Request(**base, max_output_tokens=777), "777"),
"stop": sent_or_refused(case, Request(**base, stop=["STOP-MARK"]), "STOP-MARK"),
"tools": sent_or_refused(case, Request(**with_tool), "tool_mark"),
"tool_choice (forced)": sent_or_refused(case, Request(**with_tool, tool_choice=ForcedTool(name="tool_mark")), "tool_mark"),
"tool_choice (required)": sent_or_refused(case, Request(**with_tool, tool_choice="required"), "tool_mark"),
"parallel_tool_calls=False": sent_or_refused(case, Request(**with_tool, parallel_tool_calls=False), "parallel"),
"strict tool": sent_or_refused(case, Request(**base, tools=[TOOL.model_copy(update={"strict": True})]), "strict"),
"output_schema": sent_or_refused(case, Request(**base, output_schema=SchemaMark), "field_mark"),
"reasoning_effort": sent_or_refused(case, Request(**base, reasoning_effort="high"), "high"),
}
assert set(results.values()) <= {"sent", "refused"}
# the answer for the two fields the first version dropped without a word
if case == "openai-responses":
assert results["stop"] == "refused" # responses.create has no `stop`
if case.startswith("gemini"):
assert results["parallel_tool_calls=False"] == "refused" # Gemini has no switch
@pytest.mark.parametrize("case", CASE_IDS)
def test_a_failed_tool_result_is_marked_on_every_route(case: str, monkeypatch: pytest.MonkeyPatch) -> None:
"""is_error has a native field on Anthropic, Gemini and Interactions. On OpenAI routes the TEXT carries it (03.5, 7.4):
translated and visible, not dropped."""
monkeypatch.setenv("TEST_KEY", "x")
history = [Message.user("w?"),
Message(role="assistant", parts=[ToolCallPart(id="c1", name="tool_mark", arguments={"city": "x"})]),
Message.tool_results(ToolResultPart(call_id="c1", name="tool_mark", content="no data for x", is_error=True))]
text = wire(case, Request(model="m", messages=history, tools=[TOOL]))
assert "is_error" in text or "error" in text.replace("no data", "") # a flag, an {"error": ...} body, or "Error: ..."
# ---------------------------------------------------------------------------------------------- extra: merged, not replaced
def build(case: str, req: Request) -> dict[str, Any]:
spec = Registry({"version": "t", "models": {"m": CASES[case][1]}}).models["m"]
return ADAPTERS[spec.api](spec).build(req)
def test_extra_is_deep_merged_so_it_cannot_delete_what_the_adapter_built(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("TEST_KEY", "x")
# Anthropic: the effort override must keep the structured-output format that sits in the same output_config
req = Request(model="m", messages=CALL, output_schema=SchemaMark, reasoning_effort="high",
extra={"anthropic": {"output_config": {"effort": "max"}}})
cfg = build("anthropic", req)["output_config"]
assert cfg["effort"] == "max" and cfg["format"]["type"] == "json_schema"
# OpenAI Responses: asking for reasoning summaries keeps the effort
req = Request(model="m", messages=CALL, reasoning_effort="high", extra={"openai": {"reasoning": {"summary": "auto"}}})
assert build("openai-responses", req)["reasoning"] == {"effort": "high", "summary": "auto"}
# Gemini: a thinking_config override keeps what the adapter set
req = Request(model="m", messages=CALL, reasoning_effort="high", extra={"gemini": {"thinking_config": {"thinking_budget": 2048}}})
thinking = build("gemini-generate", req)["config"].thinking_config
assert thinking.include_thoughts is True and thinking.thinking_budget == 2048
# OpenRouter: extra_body merges with the reasoning object the dialect put there
req = Request(model="m", messages=CALL, reasoning_effort="low", extra={"openrouter": {"extra_body": {"provider": {"sort": "price"}}}})
assert build("openrouter-chat", req)["extra_body"] == {"reasoning": {"effort": "low"}, "provider": {"sort": "price"}}
@pytest.mark.parametrize("case, key", [("openai-responses", "model"), ("openai-responses", "input"), ("openai-responses", "stream"),
("openai-chat", "messages"), ("anthropic", "model"), ("anthropic", "messages")])
def test_extra_may_not_replace_the_model_the_messages_or_the_stream_flag(case: str, key: str, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("TEST_KEY", "x")
provider = CASES[case][1]["provider"]
with pytest.raises(UnsupportedFeature, match="may not set"):
build(case, Request(model="m", messages=CALL, extra={provider: {key: "x"}}))
def test_caching_and_other_extra_recipes_reach_the_wire(monkeypatch: pytest.MonkeyPatch) -> None:
"""The recipes table in the lesson (3.2): every row is a working shape."""
monkeypatch.setenv("TEST_KEY", "x")
a = build("anthropic", Request(model="m", messages=CALL, extra={"anthropic": {"cache_control": {"type": "ephemeral"}}}))
assert a["cache_control"] == {"type": "ephemeral"}
o = build("openai-responses", Request(model="m", messages=CALL, extra={"openai": {
"prompt_cache_key": "support-bot-v3", "safety_identifier": "u-abc", "service_tier": "flex"}}))
assert (o["prompt_cache_key"], o["safety_identifier"], o["service_tier"]) == ("support-bot-v3", "u-abc", "flex")
g = build("gemini-generate", Request(model="m", messages=CALL, extra={"gemini": {"cached_content": "cachedContents/abc"}}))
assert g["config"].cached_content == "cachedContents/abc"
# ---------------------------------------------------------------------------------------------- registry safety
BASE = {"provider": "openai", "api": "chat", "model": "m", "api_key_env": "TEST_KEY"}
def test_a_typo_in_the_registry_is_an_error_not_a_default() -> None:
with pytest.raises(ConfigError, match="capabilites"):
registry_for({"x": {**BASE, "capabilites": {"tools": True}}})
with pytest.raises(ConfigError, match="default_max_output_token"):
registry_for({"x": {**BASE, "default_max_output_token": 5}})
with pytest.raises(ConfigError, match="toolz"):
registry_for({"x": {**BASE, "capabilities": {"toolz": True}}})
with pytest.raises(ConfigError, match="unknown top-level"):
Registry({"version": "t", "modles": {}})
with pytest.raises(ConfigError, match="expected a mapping"):
registry_for({"x": "oops"}) # a YAML scalar where a spec belongs: not a raw TypeError
with pytest.raises(ConfigError, match="`models:`"):
Registry({"version": "t", "models": ["oops"]}) # a YAML list where the models mapping belongs
with pytest.raises(ConfigError, match="the registry must be a mapping"):
Registry(None) # type: ignore[arg-type] # an empty YAML file loads as None: not a raw TypeError
def test_empty_duplicate_and_ambiguous_aliases_fail_at_load() -> None:
entries = {"a": BASE, "b": BASE}
with pytest.raises(ConfigError, match="empty chain"):
registry_for(entries, {"fast": []})
with pytest.raises(ConfigError, match="twice"):
registry_for(entries, {"fast": ["a", "a"]})
with pytest.raises(ConfigError, match="ambiguous"):
registry_for(entries, {"a": ["b"]})
with pytest.raises(ConfigError, match="expected a list"):
registry_for(entries, {"fast": "a"}) # a scalar where a chain belongs: not split into characters
with pytest.raises(ConfigError, match="`aliases:`"):
Registry({"version": "t", "models": {}, "aliases": ["fast"]})
with pytest.raises(ConfigError, match="version"):
Registry({"models": {}})
def test_credentials_never_live_in_the_registry_file() -> None:
with pytest.raises(ConfigError, match="looks like a credential"):
registry_for({"x": {**BASE, "headers": {"X-Portkey-Api-Key": "pk-123"}}})
with pytest.raises(ConfigError, match="looks like a credential"):
registry_for({"x": {**BASE, "headers": {"Authorization": "Bearer abc"}}})
def test_gateway_headers_come_from_the_environment(monkeypatch: pytest.MonkeyPatch) -> None:
spec = registry_for({"x": {**BASE, "headers": {"X-Team": "search"}, "headers_env": {"X-Portkey-Api-Key": "GATEWAY_KEY"}}}).models["x"]
monkeypatch.delenv("GATEWAY_KEY", raising=False)
with pytest.raises(ConfigError, match="GATEWAY_KEY"):
resolve_headers(spec)
monkeypatch.setenv("GATEWAY_KEY", "pk-test")
assert resolve_headers(spec) == {"X-Team": "search", "X-Portkey-Api-Key": "pk-test"}
assert "pk-test" not in repr(spec) and "pk-test" not in spec.model_dump_json() # the value is never in the model
def test_a_missing_fallback_key_is_found_before_the_first_request(monkeypatch: pytest.MonkeyPatch) -> None:
"""Found during the outage, the fallback's ConfigError hid the primary's error. Now it is found at the first call."""
monkeypatch.setenv("PRIMARY_KEY", "x")
monkeypatch.delenv("FALLBACK_KEY", raising=False)
entries = {"p": {**BASE, "api_key_env": "PRIMARY_KEY"}, "f": {**BASE, "api_key_env": "FALLBACK_KEY"}}
server = Server([FakeAnthropic().text()])
client = LLMClient(registry_for(entries, {"fast": ["p", "f"]}), http_clients={"p": server.clients()})
with pytest.raises(ConfigError, match="FALLBACK_KEY"):
client.preflight("fast")
with pytest.raises(ConfigError, match="f: FALLBACK_KEY"):
client.complete(Request(model="fast", messages=CALL))
assert server.n == 0 # nothing was sent: not even to the primary
def test_the_local_registry_never_reads_a_hosted_key(monkeypatch: pytest.MonkeyPatch) -> None:
"""A real OPENAI_API_KEY in .env must not be sent to a server on localhost."""
local = Registry.load("provider_agnostic/models.local.yaml")
hosted = {"OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GEMINI_API_KEY", "GOOGLE_API_KEY", "OPENROUTER_API_KEY"}
assert {s.api_key_env for s in local.models.values()} <= {"LOCAL_API_KEY"}
assert not hosted & {s.api_key_env for s in local.models.values()}
monkeypatch.delenv("LOCAL_API_KEY", raising=False)
from provider_agnostic.registry import resolve_api_key
assert resolve_api_key(local.models["local-chat"]) == "local" # Ollama ignores it: a placeholder is fine
def test_shipped_registries_load_and_every_route_declares_every_capability() -> None:
for path in ("provider_agnostic/models.yaml", "provider_agnostic/models.local.yaml"):
reg = Registry.load(path)
assert reg.models and reg.aliases
for spec in reg.models.values():
assert {"stop", "parallel_tool_switch", "strict_tools"} <= spec.capabilities.model_fields_set, spec.keytests/test_critical_fixes.py#
"""tests/test_critical_fixes.py: three production bugs, each pinned by a test that FAILS on the first version.
The first version of the client passed every happy-path and every fast-error test. These tests inject the faults
that real outages actually produce, with a fake clock and scripted servers (lesson 03.11, Part 8 and Part 9):
C1. a provider that HANGS (every attempt takes the full timeout): the default Policy never reached the fallback;
C2. request middleware that RAISES (a budget gate, a redactor): the call was sent anyway;
C3. an HTTP 200 whose body says "failed": it was returned as a success, never retried, and logged ok=True.
"""
from __future__ import annotations
import logging
import httpx2
import pytest
from provider_agnostic.client import LLMClient, Policy
from provider_agnostic.errors import LLMError, QuotaExceeded
from provider_agnostic.hooks import Hook, MetricsHook
from provider_agnostic.types import Message, Request
from tests.conftest import CASES, make_client, registry_for
from tests.fakes import FakeAnthropic, FakeResponses, Server
HELLO = Request(model="fast", messages=[Message.user("Say hello")])
oa, an = FakeResponses(), FakeAnthropic()
def two_models(primary: Server, secondary: Server, *, hooks: list[Hook] | None = None, clock=None, sleep=None,
**policy) -> LLMClient:
reg = registry_for({"luna": CASES["openai-responses"][1], "haiku": CASES["anthropic"][1]},
{"fast": ["luna", "haiku"]})
extra = {"clock": clock} if clock else {}
return LLMClient(reg, hooks=hooks, policy=Policy(**policy), sleep=sleep or (lambda s: None),
http_clients={"luna": primary.clients(), "haiku": secondary.clients()}, **extra)
# =============================================================================================== C1: a hung provider
def test_hung_primary_falls_back_within_deadline() -> None:
"""Every attempt on the primary takes the whole 30 s timeout. With the DEFAULT policy the fallback must still run."""
now = [0.0]
def hang() -> None:
now[0] += 30.0 # the request waited the full attempt timeout
primary = Server([httpx2.ReadTimeout("no bytes for 30 s")], delay=hang)
secondary = Server([an.text("Hello from Claude")])
client = two_models(primary, secondary, clock=lambda: now[0], sleep=lambda s: now.__setitem__(0, now[0] + s))
resp = client.complete(HELLO)
assert resp.provider == "anthropic" and resp.text == "Hello from Claude"
assert secondary.n == 1, "the fallback was never reached"
assert [(a.model_key, a.error_type) for a in resp.attempts if not a.ok] == [("luna", "Timeout"), ("luna", "Timeout")]
assert now[0] < Policy().deadline_s # and it all fit inside the deadline
def test_default_policy_leaves_room_for_the_next_model() -> None:
p = Policy()
# the primary may spend max_timeout_attempts full timeouts; the next model still needs one full attempt
assert p.deadline_s >= (p.max_timeout_attempts + 1) * p.attempt_timeout_s
# =============================================================================================== C2: fail-closed hooks
class RaisingGate(Hook):
"""A per-user budget gate: raises to block the call."""
def before(self, ctx, req):
raise RuntimeError("user over budget")
CARD = "4111 1111 1111 1111"
class BrokenRedactor(Hook):
"""A redaction hook with a bug: it crashes on the input it was supposed to clean."""
def before(self, ctx, req):
raise ValueError(f"cannot parse {req.messages[0].text!r}") # the message holds the very text we must not leak
def test_a_failing_request_middleware_blocks_the_call() -> None:
server = Server([oa.text()])
seen: list[str] = []
class Spy(Hook):
def error(self, ctx, req, err):
seen.append(type(err).__name__)
client = two_models(server, Server([an.text()]), hooks=[RaisingGate(), Spy()])
with pytest.raises(LLMError) as info:
client.complete(HELLO)
assert server.n == 0, "the call was sent although the budget gate raised"
assert type(info.value).__name__ == "HookError" and isinstance(info.value.__cause__, RuntimeError)
assert seen == ["HookError"] # the error hooks still run: the failure is visible
def test_a_crashing_redactor_never_sends_the_prompt(caplog: pytest.LogCaptureFixture) -> None:
caplog.set_level(logging.DEBUG)
primary, secondary = Server([oa.text()]), Server([an.text()])
client = two_models(primary, secondary, hooks=[BrokenRedactor()])
with pytest.raises(LLMError):
client.complete(Request(model="fast", messages=[Message.user(f"my card is {CARD}")]))
assert primary.n == 0 and secondary.n == 0, "an unredacted prompt reached a provider"
assert CARD not in caplog.text # and the failure log never echoes the text the hook choked on
def test_after_middleware_that_fails_closed_returns_nothing() -> None:
class ResponseRedactor(Hook):
fail_closed = True # this hook changes or validates what the caller gets
def after(self, ctx, req, resp):
raise ValueError("cannot redact")
client = two_models(Server([oa.text()]), Server([an.text()]), hooks=[ResponseRedactor()])
with pytest.raises(LLMError) as info:
client.complete(HELLO)
assert type(info.value).__name__ == "HookError"
assert info.value.response is not None # the call WAS billed: the response stays visible to the error hooks
def test_observer_hooks_still_cannot_break_the_call() -> None:
class Flaky(Hook):
def attempt(self, ctx, attempt):
raise RuntimeError("metrics server down")
def after(self, ctx, req, resp):
raise RuntimeError("log shipper down")
metrics = MetricsHook()
client = two_models(Server([oa.text()]), Server([an.text()]), hooks=[Flaky(), metrics])
assert client.complete(HELLO).text == "Hello there"
assert metrics.counts["attempt.luna.ok"] == 1
def test_a_before_hook_may_raise_its_own_llm_error() -> None:
class Quota(Hook):
def before(self, ctx, req):
raise QuotaExceeded("daily budget used up")
server = Server([oa.text()])
with pytest.raises(QuotaExceeded):
two_models(server, Server([an.text()]), hooks=[Quota()]).complete(HELLO)
assert server.n == 0
# =============================================================================================== C3: failed inside a 200
# (case, fake method, kwargs, class name that must be raised or retried, retryable)
TRANSIENT = [
("openai-responses", {"code": "server_error"}, "ServerError"),
("openai-responses", {"code": "rate_limit_exceeded"}, "RateLimited"),
("openai-responses", {"code": "vector_store_timeout"}, "Timeout"),
("openai-chat", {}, "ServerError"),
("openrouter-chat", {}, "ServerError"),
("gemini-interactions", {"code": "rate_limit_exceeded"}, "RateLimited"),
]
PERMANENT = [
("openai-responses", {"code": "invalid_prompt"}, "BadRequest"),
("openai-responses", {"code": "bio_policy"}, "ContentBlocked"),
("openai-responses", {"status": "cancelled", "code": "server_error"}, "ResponseFailed"),
("gemini-interactions", {"code": None}, "ResponseFailed"),
("gemini-interactions", {"code": None, "status": "cancelled"}, "ResponseFailed"),
("gemini-interactions", {"code": None, "status": "budget_exceeded"}, "ResponseFailed"),
]
def _ids(rows):
return [f"{c}-{k.get('status', 'failed')}-{k.get('code', 'x')}" for c, k, *_ in rows]
@pytest.mark.parametrize("case, kw, cls", TRANSIENT, ids=_ids(TRANSIENT))
def test_failed_status_is_an_error_and_retried(case: str, kw: dict, cls: str) -> None:
fake = CASES[case][0]
client, server = make_client(case, [fake.failed(**kw), fake.text("recovered")], max_attempts=3)
resp = client.complete(Request(model="m", messages=[Message.user("hi")]))
assert resp.text == "recovered" and server.n == 2, "a transient failed-in-200 must be retried"
assert [(a.ok, a.error_type) for a in resp.attempts] == [(False, cls), (True, None)], "the attempt log said ok=True"
@pytest.mark.parametrize("case, kw, cls", PERMANENT, ids=_ids(PERMANENT))
def test_permanent_failed_status_raises_once(case: str, kw: dict, cls: str) -> None:
fake = CASES[case][0]
client, server = make_client(case, [fake.failed(**kw), fake.text("never reached")], max_attempts=3)
with pytest.raises(LLMError) as info:
client.complete(Request(model="m", messages=[Message.user("hi")]))
assert type(info.value).__name__ == cls and not info.value.retryable and server.n == 1
assert [a.ok for a in info.value.attempts] == [False]
STREAM_TRANSIENT = [
("openai-responses", "stream_failed", {"code": "server_error"}, "ServerError"), # response.failed terminal event
("openai-responses", "stream_error_event", {"code": "rate_limit_exceeded"}, "RateLimited"), # error event keeps its code
("openai-chat", "stream_failed", {}, "ServerError"),
("openrouter-chat", "stream_failed", {}, "ServerError"),
("gemini-interactions", "stream_failed", {"code": "rate_limit_exceeded"}, "RateLimited"),
]
@pytest.mark.parametrize("case, method, kw, cls", STREAM_TRANSIENT, ids=[f"{c}-{m}" for c, m, *_ in STREAM_TRANSIENT])
def test_failed_stream_before_content_is_retried(case: str, method: str, kw: dict, cls: str) -> None:
from provider_agnostic.types import Done
fake = CASES[case][0]
client, server = make_client(case, [getattr(fake, method)(**kw), fake.stream_text(["Hi"])], max_attempts=3)
events = list(client.stream(Request(model="m", messages=[Message.user("hi")])))
done = events[-1]
assert isinstance(done, Done) and done.response.text == "Hi" and server.n == 2
assert [(a.ok, a.error_type) for a in done.response.attempts] == [(False, cls), (True, None)]
def test_failed_stream_with_a_permanent_code_raises() -> None:
client, server = make_client("openai-responses", [oa.stream_failed(code="invalid_prompt"), oa.stream_text(["x"])],
max_attempts=3)
with pytest.raises(LLMError) as info:
list(client.stream(Request(model="m", messages=[Message.user("hi")])))
assert type(info.value).__name__ == "BadRequest" and server.n == 1
def test_failed_status_is_also_an_error_on_the_async_path() -> None:
import asyncio
client, server = make_client("openai-responses", [oa.failed(code="server_error"), oa.text("recovered")], max_attempts=3)
resp = asyncio.run(client.acomplete(Request(model="m", messages=[Message.user("hi")])))
assert resp.text == "recovered" and server.n == 2tests/test_billing_and_ids.py#
"""tests/test_billing_and_ids.py: every paid-for call leaves a record, usage and cost come from lesson 03.7, IDs mean one thing.
Layer 3 (real SDKs, scripted servers). The paths covered are the ones the first version sent to the provider, billed,
and then forgot: an invalid reply, an abandoned stream, a discarded fallback reply, a stream that broke half way.
"""
from __future__ import annotations
import contextlib
import json
import logging
import pytest
from pydantic import BaseModel
import cost_calc
from prices import PriceTable
from provider_agnostic.client import LLMClient, Policy
from provider_agnostic.errors import LLMError, OutputInvalid
from provider_agnostic.hooks import Hook, JsonlCostHook, LoggingHook, MetricsHook
from provider_agnostic.types import Done, FinishReason, Message, Request, TextDelta
from tests.conftest import CASES, make_client, registry_for
from tests.fakes import FakeAnthropic, FakeChat, FakeGemini, FakeResponses, Server
PRICES = PriceTable.load()
HELLO = Request(model="m", messages=[Message.user("Say hello")])
oa, an = FakeResponses(), FakeAnthropic()
class City(BaseModel):
name: str
def one_model(case: str, replies: list, *, hooks: list[Hook] | None = None, model: str | None = None, **policy) -> tuple[LLMClient, Server]:
fake, spec = CASES[case]
server = Server(replies, flavour=fake.flavour)
entry = {**spec, **({"model": model} if model else {})}
return LLMClient(registry_for({"m": entry}), prices=PRICES, hooks=hooks, policy=Policy(**policy),
http_clients={"m": server.clients()}, sleep=lambda s: None), server
class Recorder(Hook):
def __init__(self) -> None:
self.seen: list[tuple[str, object]] = []
def attempt(self, ctx, attempt):
self.seen.append(("attempt", attempt))
def error(self, ctx, req, err):
self.seen.append(("error", err))
def abandoned(self, ctx, req, partial):
self.seen.append(("abandoned", partial))
def records(path) -> list[dict]:
return [json.loads(line) for line in path.read_text().splitlines()]
# ---------------------------------------------------------------------------------- M1: billed, so recorded
def test_an_invalid_structured_reply_is_billed_and_visible(tmp_path) -> None:
"""The commonest model failure (invalid JSON) used to leave no error hook, no cost and no text."""
metrics, rec = MetricsHook(), Recorder()
client, _ = one_model("openai-responses", [oa.text("not json at all")], model="gpt-6-luna",
hooks=[metrics, rec, JsonlCostHook(tmp_path / "calls.jsonl")])
with pytest.raises(OutputInvalid) as info:
client.complete(Request(model="m", messages=[Message.user("a city")], output_schema=City))
err = info.value
assert err.response is not None and err.response.text == "not json at all" # the paid-for reply is reachable
assert err.response.usage is not None and err.response.cost is not None and err.response.cost.usd
assert metrics.counts["failed.OutputInvalid"] == 1 and ("error", err) in rec.seen
(record,) = records(tmp_path / "calls.jsonl")
assert record["outcome"] == "invalid" and record["cost_usd"] == err.response.cost.usd
assert record["uncached_input_tokens"] == 12 and record["total_input_tokens"] == 20
def test_a_consumer_that_stops_early_is_recorded(tmp_path) -> None:
"""break / close() raise GeneratorExit, which `except Exception` never saw: the cancelled stream vanished."""
rec, metrics = Recorder(), MetricsHook()
client, server = one_model("anthropic", [an.stream_text(["Hel", "lo ", "there"])],
hooks=[rec, metrics, JsonlCostHook(tmp_path / "calls.jsonl")])
gen = client.stream(HELLO)
first = next(e for e in gen if isinstance(e, TextDelta))
assert first.text == "Hel"
gen.close() # what `break` does when the loop's generator is dropped
(partial,) = [p for kind, p in rec.seen if kind == "abandoned"]
assert partial.text == "Hel" and partial.usage is not None and partial.usage.uncached_input_tokens == 12 # the provider reported it up front
assert partial.cost is not None and partial.cost.usd is not None
assert [a.error_type for a in partial.attempts] == ["Abandoned"]
assert metrics.counts["abandoned"] == 1 and metrics.counts["attempt.m.Abandoned"] == 1
(record,) = records(tmp_path / "calls.jsonl")
assert record["outcome"] == "abandoned" and record["uncached_input_tokens"] == 12
def test_finishing_a_stream_normally_is_not_an_abandon() -> None:
rec = Recorder()
client, _ = one_model("anthropic", [an.stream_text(["Hi"])], hooks=[rec])
events = list(client.stream(HELLO))
assert isinstance(events[-1], Done)
assert not [kind for kind, _ in rec.seen if kind == "abandoned"]
def test_closing_the_stream_after_done_is_not_an_abandon() -> None:
rec = Recorder()
client, _ = one_model("anthropic", [an.stream_text(["Hi"])], hooks=[rec])
gen = client.stream(HELLO)
events = []
for ev in gen:
events.append(ev)
if isinstance(ev, Done):
break
gen.close()
assert not [kind for kind, _ in rec.seen if kind == "abandoned"]
async def test_async_stream_abandoned_by_aclose_is_recorded() -> None:
rec = Recorder()
client, _ = one_model("anthropic", [an.stream_text(["Hel", "lo"])], hooks=[rec])
agen = client.astream(HELLO)
async for ev in agen:
if isinstance(ev, TextDelta):
break
await agen.aclose()
assert [kind for kind, _ in rec.seen].count("abandoned") == 1
def test_a_broken_stream_reports_the_usage_it_did_receive(caplog: pytest.LogCaptureFixture) -> None:
caplog.set_level(logging.WARNING, logger="provider_agnostic")
client, _ = one_model("anthropic", [an.stream_midway_error(["Par"])], hooks=[LoggingHook()])
with pytest.raises(LLMError) as info:
list(client.stream(HELLO))
assert info.value.partial is not None and info.value.partial.usage is not None
logged = [json.loads(r.message) for r in caplog.records if r.message.startswith("{")]
failed = next(line for line in logged if line["event"] == "llm_call_failed")
assert failed["uncached_input_tokens"] == 20 and failed["cost_usd"] is not None # what message_start reported: not null
def test_a_reply_discarded_for_the_fallback_is_still_in_the_totals() -> None:
s1, s2 = Server([oa.refusal()]), Server([an.text("ok")])
reg = registry_for({"luna": {**CASES["openai-responses"][1], "model": "gpt-6-luna"}, "haiku": CASES["anthropic"][1]},
{"fast": ["luna", "haiku"]})
client = LLMClient(reg, prices=PRICES, policy=Policy(fallback_on_finish=frozenset({FinishReason.REFUSAL})),
http_clients={"luna": s1.clients(), "haiku": s2.clients()})
resp = client.complete(Request(model="fast", messages=[Message.user("x")]))
discarded = resp.attempts[0]
assert discarded.error_type == "FinishFallback:refusal" and not discarded.ok
assert discarded.usage is not None and discarded.cost_usd is not None
# ---------------------------------------------------------------------------------- usage and cost come from 03.7
def test_anthropic_fast_mode_geo_web_search_and_1h_writes_are_priced(tmp_path) -> None:
extra = {"speed": "fast", "inference_geo": "us", "server_tool_use": {"web_search_requests": 3},
"cache_creation": {"ephemeral_5m_input_tokens": 0, "ephemeral_1h_input_tokens": 40},
"cache_creation_input_tokens": 40}
for call in ("complete", "stream"):
replies = [an.text(model="claude-opus-5-5", usage_extra=extra)] if call == "complete" else \
[an.stream_text(["Hello"], model="claude-opus-5-5", usage_extra=extra)]
client, _ = one_model("anthropic", replies, model="claude-opus-5-5")
if call == "complete":
resp = client.complete(HELLO)
cc = cost_calc.from_anthropic(resp.raw)
theirs = cost_calc.price(cc, PRICES)
else:
events = list(client.stream(HELLO))
resp = events[-1].response
theirs = None
u = resp.usage
assert u is not None and (u.tier, u.geo, u.web_searches) == ("fast", "us", 3), call
assert u.cache_write_tokens == {"1h": 40}, call # the 1-hour split, not a hard-coded "5m"
assert resp.cost is not None and resp.cost.usd
if theirs is not None:
assert resp.cost.usd == pytest.approx(theirs.usd) # the SAME number 03.7's calculator gives
plain, _ = one_model("anthropic", [an.text(model="claude-opus-5-5")], model="claude-opus-5-5")
base = plain.complete(HELLO).cost
assert base is not None and base.usd and resp.cost.usd > 2 * base.usd # fast mode 2x, geo 1.1x, searches $10 per 1,000
def test_openai_12h_writes_and_ultrafast_are_priced() -> None:
client, _ = one_model("openai-responses", [oa.text(written_12h=6, service_tier="ultrafast", web_searches=2)],
model="gpt-6.1-sol")
resp = client.complete(HELLO)
u = resp.usage
assert u is not None and u.tier == "ultrafast" and u.cache_write_tokens == {"12h": 6} and u.web_searches == 2
theirs = cost_calc.from_openai_response(resp.raw)
theirs.model = "gpt-6.1-sol" # the price table is keyed by the registry's model ID
assert resp.cost is not None and resp.cost.usd == pytest.approx(cost_calc.price(theirs, PRICES).usd)
def test_gemini_service_tier_comes_from_the_response_header() -> None:
client, _ = one_model("gemini-generate", [FakeGemini().text(service_tier="flex"), FakeGemini().text()], model="gemini-3.8-flash")
flex, standard = client.complete(HELLO), client.complete(HELLO)
assert flex.usage is not None and flex.usage.tier == "flex" and standard.usage is not None and standard.usage.tier == "standard"
assert flex.cost is not None and standard.cost is not None and flex.cost.usd == pytest.approx(standard.cost.usd * 0.5)
def test_an_unpriceable_tier_is_unknown_not_zero_and_not_a_crash() -> None:
client, _ = one_model("openai-responses", [oa.text(service_tier="mystery")], model="gpt-6-luna")
resp = client.complete(HELLO)
assert resp.text == "Hello there" and resp.usage is None and resp.cost is not None and resp.cost.usd is None
def test_chat_stream_is_priced_at_the_tier_that_served_it() -> None:
"""The first version read service_tier on plain Chat calls only: a flex stream was priced at the standard rate."""
plain, _ = one_model("openai-chat", [FakeChat().text(service_tier="flex")], model="gpt-6-luna")
streamed, _ = one_model("openai-chat", [FakeChat().stream_text(["Hi"], service_tier="flex")], model="gpt-6-luna")
a = plain.complete(HELLO)
b = list(streamed.stream(HELLO))[-1].response
assert a.usage is not None and b.usage is not None
assert a.usage.tier == b.usage.tier == "flex"
assert a.cost is not None and b.cost is not None and a.cost.usd == pytest.approx(b.cost.usd)
def test_zeroed_gemini_stream_usage_is_unknown_not_free() -> None:
"""A proxy can send usage of all zeros on a stream. Priced as is, that is a $0.00 call."""
client, _ = one_model("gemini-generate", [FakeGemini().stream_text(["Hel", "lo"], zero_usage=True)], model="gemini-3.8-flash")
resp = list(client.stream(HELLO))[-1].response
assert resp.text == "Hello" and resp.usage is None
assert resp.cost is not None and resp.cost.usd is None and resp.cost.source == "unknown"
# ---------------------------------------------------------------------------------- M6: request_id means one thing
IDS = { # case -> (header ID, body ID) for a plain call, and the same for a stream
"openai-responses": (("req_openai_1", "resp_1"), ("req_openai_s1", "resp_1")),
"openai-chat": (("req_chat_1", "chatcmpl-1"), ("req_chat_s1", "chatcmpl-1")),
"openrouter-chat": (("req_chat_1", "gen-or-1"), ("req_chat_s1", "chatcmpl-1")),
"anthropic": (("req_anth_1", "msg_01"), ("req_anth_s1", "msg_01")),
"gemini-generate": (("resp_gem_1", "resp_gem_1"), ("resp_gem_1", "resp_gem_1")), # Google sends no request-ID header
"gemini-interactions": (("int_1", "int_1"), ("int_1", "int_1")),
}
@pytest.mark.parametrize("case", list(IDS))
def test_request_id_is_the_same_kind_of_id_on_complete_and_stream(case: str) -> None:
fake = CASES[case][0]
(plain_req, plain_body), (stream_req, stream_body) = IDS[case]
client, _ = make_client(case, [fake.text()])
resp = client.complete(HELLO)
assert (resp.request_id, resp.provider_response_id) == (plain_req, plain_body)
client, _ = make_client(case, [fake.stream_text(["Hi"])])
done = list(client.stream(HELLO))[-1]
assert isinstance(done, Done)
assert (done.response.request_id, done.response.provider_response_id) == (stream_req, stream_body), \
"streaming used to report the body ID where complete() reported the request-ID header"tests/test_hooks.py#
"""tests/test_hooks.py: the hooks meet lesson 03.10's standard: fail-closed redaction, no key leaks, files created owner-only,
tags that cannot overwrite core fields (layer 1 and 3: no network).
"""
from __future__ import annotations
import json
import logging
import os
import stat
import pytest
from provider_agnostic.client import LLMClient, Policy
from provider_agnostic.errors import ConfigError, HookError
from provider_agnostic.hooks import CallContext, Hook, JsonlCostHook, LoggingHook, OTelHook, RedactHook
from provider_agnostic.redact import hash_user, redact_text
from provider_agnostic.types import (DocumentPart, ImagePart, Message, Native, ReasoningPart, Request, TextPart,
ToolCallPart, ToolResultPart)
from tests.conftest import CASES, registry_for
from tests.fakes import FakeResponses, Server
oa = FakeResponses()
CARD = "4111 1111 1111 1111"
OPENAI_KEY = "sk-proj-" + "a1B2c3D4e5F6g7H8i9J0" # key-SHAPED, not a key
ANTHROPIC_KEY = "sk-ant-api03-" + "Zz9Yy8Xx7Ww6Vv5Uu4Tt3"
GOOGLE_KEY = "AIza" + "SyD" + "0123456789abcdefghijklmnopqrstu"
def client_for(hooks: list[Hook], replies: list | None = None) -> tuple[LLMClient, Server]:
server = Server(replies or [oa.text()])
return LLMClient(registry_for({"luna": CASES["openai-responses"][1]}), hooks=hooks, policy=Policy(),
http_clients={"luna": server.clients()}), server
def sent_body(server: Server) -> str:
return json.dumps(server.requests[0]["json"])
# ------------------------------------------------------------------------------------------------ redaction middleware
def test_redact_hook_removes_credentials_cards_and_emails_before_anything_is_sent() -> None:
client, server = client_for([RedactHook()])
text = f"my card {CARD}, mail ana@example.com, keys {OPENAI_KEY} {ANTHROPIC_KEY} {GOOGLE_KEY}"
client.complete(Request(model="luna", system=f"token={OPENAI_KEY}", messages=[Message.user(text)]))
body = sent_body(server)
for secret in (CARD, "ana@example.com", OPENAI_KEY, ANTHROPIC_KEY, GOOGLE_KEY):
assert secret not in body
assert "[CARD]" in body and "[EMAIL]" in body and "[CREDENTIAL]" in body
def test_redact_hook_is_allow_list_shaped_and_refuses_media_by_default() -> None:
client, server = client_for([RedactHook()])
image = Message(role="user", parts=[TextPart(text="what is this?"), ImagePart(media_type="image/png", data_b64="aGk=")])
with pytest.raises(HookError, match="cannot inspect a ImagePart"):
client.complete(Request(model="luna", messages=[image]))
assert server.n == 0
pdf = Message(role="user", parts=[DocumentPart(data_b64="AAAA")])
with pytest.raises(HookError):
client.complete(Request(model="luna", messages=[pdf]))
client, server = client_for([RedactHook(allow_media=True)]) # a deliberate decision, in code
client.complete(Request(model="luna", messages=[image]))
assert server.n == 1
def test_redact_hook_drops_the_native_twin_that_holds_the_original_text() -> None:
"""A rewritten part keeps no `native`: replaying it would put the unredacted text back on the wire."""
leaky = ToolCallPart(id="c1", name="lookup", arguments={"email": "ana@example.com"},
native=Native(provider="openai", api="responses", payload={"type": "function_call", "call_id": "c1",
"name": "lookup", "arguments": '{"email": "ana@example.com"}'}))
history = [Message.user("find her"), Message(role="assistant", parts=[leaky]),
Message.tool_results(ToolResultPart(call_id="c1", name="lookup", content=f"card {CARD}"))]
client, server = client_for([RedactHook()])
client.complete(Request(model="luna", messages=history))
body = sent_body(server)
assert "ana@example.com" not in body and CARD not in body
# a signed TEXT part (Gemini keeps the thought signature next to the text it signs) behaves the same way: rewritten, so unsigned
twin = lambda text: Native(provider="gemini", api="generate_content", payload={"text": text, "thought_signature": "c2ln"}) # noqa: E731
dirty, clean = TextPart(text="mail ana@example.com", native=twin("mail ana@example.com")), TextPart(text="hello", native=twin("hello"))
out = RedactHook().before(CallContext("c", "m", 0.0), Request(model="m", messages=[Message(role="assistant", parts=[dirty, clean])]))
scrubbed, untouched = out.messages[0].parts
assert isinstance(scrubbed, TextPart) and scrubbed.text == "mail [EMAIL]" and scrubbed.native is None
assert isinstance(untouched, TextPart) and untouched.native is not None # nothing to redact: the signature still replays
def test_redact_hook_keeps_signed_reasoning_replayable() -> None:
reasoning = ReasoningPart(text="thinking about ana@example.com",
native=Native(provider="openai", api="responses",
payload={"type": "reasoning", "id": "rs_1", "encrypted_content": "BLOB"}))
client, server = client_for([RedactHook()])
client.complete(Request(model="luna", messages=[Message.user("q"), Message(role="assistant", parts=[reasoning, TextPart(text="a")]),
Message.user("next")]))
items = server.requests[0]["json"]["input"]
assert any(i.get("encrypted_content") == "BLOB" for i in items) # the opaque item went back unchanged
def test_credential_shapes_are_all_caught() -> None:
shapes = {"openai": OPENAI_KEY, "anthropic": ANTHROPIC_KEY, "google": GOOGLE_KEY,
"openrouter": "sk-or-v1-" + "0123456789abcdef0123456789abcdef", "github": "ghp_" + "A" * 36,
"aws": "AKIA" + "ABCDEFGHIJKLMNOP", "bearer": "Bearer abcdefghijklmnop1234",
"jwt": "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dBjftJeZ4CVPmB92K27uhbUJU1p1r_wW1gFWFOEjXk"}
for name, secret in shapes.items():
assert secret not in redact_text(f"here: {secret} end"), name
assert redact_text("api_key=hunter2hunter2") == "api_key=[SECRET]"
assert redact_text("An ordinary sentence about the weather in Paris.") == "An ordinary sentence about the weather in Paris."
# ------------------------------------------------------------------------------------------------ logs and tags
def test_a_tag_cannot_overwrite_a_core_log_field(caplog: pytest.LogCaptureFixture) -> None:
caplog.set_level(logging.INFO, logger="provider_agnostic")
client, _ = client_for([LoggingHook()])
client.complete(Request(model="luna", messages=[Message.user("hi")],
metadata={"cost_usd": "0", "call_id": "forged", "event": "llm_call", "feature": "demo"}))
lines = [json.loads(r.message) for r in caplog.records if r.message.startswith("{")]
call = next(line for line in lines if line["event"] == "llm_call")
assert call["call_id"] != "forged" and call["call_id"] and call["event"] == "llm_call" # the real fields won
assert call["cost_usd"] != "0"
assert call["tags"] == {"cost_usd": "0", "call_id": "forged", "event": "llm_call", "feature": "demo"} # quarantined under "tags"
def test_metadata_is_validated_and_scrubbed() -> None:
with pytest.raises(ValueError, match="must match"):
Request(model="m", messages=[Message.user("x")], metadata={"Bad Key!": "v"})
with pytest.raises(ValueError, match="longer than"):
Request(model="m", messages=[Message.user("x")], metadata={"note": "x" * 500})
with pytest.raises(ValueError, match="at most"):
Request(model="m", messages=[Message.user("x")], metadata={f"k{i}": "v" for i in range(40)})
seen: list[CallContext] = []
class Spy(Hook):
def before(self, ctx, req):
seen.append(ctx)
return req
client, _ = client_for([Spy()])
client.complete(Request(model="luna", messages=[Message.user("hi")], metadata={"note": f"call me ana@example.com {OPENAI_KEY}"}))
assert "ana@example.com" not in seen[0].tags["note"] and OPENAI_KEY not in seen[0].tags["note"]
def test_hook_failure_logs_never_contain_the_text_the_hook_choked_on(caplog: pytest.LogCaptureFixture) -> None:
caplog.set_level(logging.DEBUG, logger="provider_agnostic")
class Choking(Hook):
def attempt(self, ctx, attempt):
raise ValueError(f"cannot handle {CARD}")
client, _ = client_for([Choking()])
client.complete(Request(model="luna", messages=[Message.user("hi")]))
mine = "\n".join(r.getMessage() for r in caplog.records if r.name == "provider_agnostic")
assert "Choking.attempt failed: ValueError" in mine and CARD not in mine and not any(r.exc_info for r in caplog.records
if r.name == "provider_agnostic")
# ------------------------------------------------------------------------------------------------ the JSONL file
def test_cost_file_is_created_owner_only_in_a_directory_that_is_created(tmp_path) -> None:
target = tmp_path / "logs" / "llm" / "calls.jsonl"
old = os.umask(0o022) # the usual umask: files would default to 0644
try:
hook = JsonlCostHook(target)
client, _ = client_for([hook])
client.complete(Request(model="luna", messages=[Message.user("hi")]))
finally:
os.umask(old)
assert stat.S_IMODE(target.stat().st_mode) == 0o600
assert stat.S_IMODE(target.parent.stat().st_mode) == 0o700 and json.loads(target.read_text())["outcome"] == "ok"
def test_an_existing_wide_file_is_tightened_before_anything_is_written(tmp_path) -> None:
target = tmp_path / "calls.jsonl"
target.write_text("")
target.chmod(0o644)
JsonlCostHook(target)
assert stat.S_IMODE(target.stat().st_mode) == 0o600
def test_cost_file_refuses_to_follow_a_planted_symlink(tmp_path) -> None:
victim = tmp_path / "victim.txt"
victim.write_text("do not touch")
link = tmp_path / "calls.jsonl"
link.symlink_to(victim)
with pytest.raises(OSError):
JsonlCostHook(link)
assert victim.read_text() == "do not touch"
def test_cost_file_rotates_at_its_size_bound(tmp_path) -> None:
hook = JsonlCostHook(tmp_path / "calls.jsonl", max_bytes=1500)
client, _ = client_for([hook], [oa.text()])
for _ in range(6):
client.complete(Request(model="luna", messages=[Message.user("hi")]))
rotated = tmp_path / "calls.jsonl.1"
assert rotated.exists() and (tmp_path / "calls.jsonl").stat().st_size <= 1500
assert stat.S_IMODE(rotated.stat().st_mode) == 0o600
def test_cost_record_uses_the_03_7_token_names_never_a_bare_input_tokens(tmp_path) -> None:
client, _ = client_for([JsonlCostHook(tmp_path / "calls.jsonl")])
client.complete(Request(model="luna", messages=[Message.user("hi")]))
record = json.loads((tmp_path / "calls.jsonl").read_text())
assert {"uncached_input_tokens", "cached_input_tokens", "cache_write_tokens", "total_input_tokens"} <= record.keys()
assert "input_tokens" not in record and "input" not in record
assert record["total_input_tokens"] == record["uncached_input_tokens"] + record["cached_input_tokens"] + record["cache_write_tokens"]
# ------------------------------------------------------------------------------------------------ the keyed hash
def test_hash_user_is_keyed_and_has_no_default_key(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.delenv("USER_ID_PEPPER", raising=False)
with pytest.raises(ConfigError, match="USER_ID_PEPPER"):
hash_user("ana@example.com") # fail closed: no quiet fallback to a public key
a, b = hash_user("ana@example.com", key=b"k1"), hash_user("ana@example.com", key=b"k2")
assert a != b and a == hash_user("ana@example.com", key=b"k1") and len(a) == 16
monkeypatch.setenv("USER_ID_PEPPER", "from-the-secret-store")
assert hash_user("ana@example.com") == hash_user("ana@example.com", key=b"from-the-secret-store")
assert hash_user("ana@example.com", key=b"k1") != hash_user("ana@example.com", key=b"k1", purpose="llm-abuse-v1") # purposes are unlinkable
# ------------------------------------------------------------------------------------------------ OpenTelemetry attributes
class FakeSpan:
def __init__(self, name: str) -> None:
self.name, self.attrs, self.ended = name, {}, False
def set_attribute(self, key, value, /):
self.attrs[key] = value
def end(self):
self.ended = True
class FakeTracer:
def __init__(self) -> None:
self.spans: list[FakeSpan] = []
def start_span(self, name, /):
self.spans.append(FakeSpan(name))
return self.spans[-1]
def test_otel_hook_maps_a_call_to_genai_span_attributes() -> None:
tracer = FakeTracer()
client, _ = client_for([OTelHook(tracer)])
client.complete(Request(model="luna", messages=[Message.user("secret prompt text")]))
(span,) = tracer.spans
assert span.ended and span.attrs["gen_ai.operation.name"] == "chat" and span.attrs["gen_ai.provider.name"] == "openai"
assert span.attrs["gen_ai.request.model"] == "luna" and span.attrs["gen_ai.response.model"] == "gpt-6-luna-2026-05-18"
assert span.attrs["gen_ai.usage.input_tokens"] == 20 and span.attrs["gen_ai.usage.output_tokens"] == 5
assert span.attrs["gen_ai.usage.cache_read.input_tokens"] == 8 and span.attrs["gen_ai.response.finish_reasons"] == ["stop"]
assert "secret prompt text" not in json.dumps(span.attrs) # metadata only: no content on the span
def test_otel_hook_closes_the_span_on_failure_and_a_broken_tracer_cannot_stop_the_call() -> None:
tracer = FakeTracer()
client, _ = client_for([OTelHook(tracer)], [FakeResponses().error("bad_request")])
with pytest.raises(Exception):
client.complete(Request(model="luna", messages=[Message.user("hi")]))
assert tracer.spans[0].ended and tracer.spans[0].attrs["error.type"] == "BadRequest"
class Broken:
def start_span(self, name, /):
raise RuntimeError("collector down")
client, _ = client_for([OTelHook(Broken())])
assert client.complete(Request(model="luna", messages=[Message.user("hi")])).text == "Hello there"
def test_hook_error_message_never_echoes_the_hook_exception() -> None:
class Gate(Hook):
def before(self, ctx, req):
raise ValueError(f"cannot parse {CARD}")
client, _ = client_for([Gate()])
with pytest.raises(HookError) as info:
client.complete(Request(model="luna", messages=[Message.user("hi")]))
assert CARD not in str(info.value) and isinstance(info.value.__cause__, ValueError) # the cause stays for YOU, not for logs
def test_before_is_always_fail_closed_and_after_opts_in() -> None:
assert Hook.fail_closed is False and RedactHook.fail_closed is False # observers by default; before() is closed regardlesstests/test_stream_rules.py#
"""tests/test_stream_rules.py: when a stream commits, and the finish reasons that look finished but are not (layer 3)."""
from __future__ import annotations
import pytest
from provider_agnostic.errors import LLMError
from provider_agnostic.types import Done, FinishReason, Message, ReasoningDelta, Request, TextDelta
from tests.conftest import make_client
from tests.fakes import FakeAnthropic, FakeGemini, js, sse
HELLO = Request(model="m", messages=[Message.user("Say hello")])
an = FakeAnthropic()
def thinking_stream(first_delta: str, then_error: bool) -> tuple[int, dict[str, str], bytes]:
"""Claude 5.x: a thinking block opens with an EMPTY thinking_delta (display defaults to omitted)."""
events = [("message_start", {"type": "message_start", "message": an._msg([], None, an._usage(20, 1, 0)) | {"stop_reason": None}}),
("content_block_start", {"type": "content_block_start", "index": 0, "content_block": {"type": "thinking", "thinking": ""}}),
("content_block_delta", {"type": "content_block_delta", "index": 0, "delta": {"type": "thinking_delta", "thinking": first_delta}})]
if then_error:
events.append(("error", {"type": "error", "error": {"type": "overloaded_error", "message": "Overloaded"}}))
return sse(events)
def test_an_empty_thinking_delta_does_not_commit_the_stream() -> None:
"""The first version counted ANY ReasoningDelta as content, so the empty one committed the stream and the failure that
followed was raised to the user instead of retried."""
ok = an.stream_text(["Hi there"])
client, server = make_client("anthropic", [thinking_stream("", then_error=True), ok], max_attempts=3)
events = list(client.stream(HELLO))
assert isinstance(events[-1], Done) and events[-1].response.text == "Hi there" and server.n == 2
assert not any(isinstance(e, ReasoningDelta) for e in events), "half of the discarded attempt reached the consumer"
assert [(a.ok, a.error_type) for a in events[-1].response.attempts] == [(False, "Overloaded"), (True, None)]
def test_non_empty_reasoning_text_is_content_and_commits() -> None:
client, server = make_client("anthropic", [thinking_stream("Let me think", then_error=True), an.stream_text(["x"])], max_attempts=3)
seen: list[str] = []
with pytest.raises(LLMError):
for ev in client.stream(HELLO):
if isinstance(ev, ReasoningDelta):
seen.append(ev.text)
assert seen == ["Let me think"] and server.n == 1 # the user already saw it: raised, never retried
def test_gemini_continuation_is_not_a_finished_answer() -> None:
"""CONTINUATION = stopped at the per-request limit. The SDK hides it by default (03.3, 4.5b); with
automatic_continuation=False you see it, and it must not read as STOP."""
fake = FakeGemini()
body = fake._body([{"text": "The answer so far"}], "CONTINUATION", fake._usage(20, 16, 0))
client, _ = make_client("gemini-generate", [js(200, body)])
resp = client.complete(HELLO)
assert resp.finish_reason is FinishReason.LENGTH and resp.raw_finish_reason == "CONTINUATION"tests/test_wire.py#
"""tests/test_wire.py: the SAME canonical request, translated by every adapter (layer 1/5: no network at all).
build() is pure, so these tests never start a server. They pin the translation rules the lesson explains.
"""
from __future__ import annotations
import json
import pytest
from pydantic import BaseModel
from provider_agnostic.client import ADAPTERS
from provider_agnostic.registry import Registry
from provider_agnostic.types import (ForcedTool, ImagePart, Message, Native, ReasoningPart, Request, TextPart, ToolCallPart,
ToolResultPart, ToolSpec)
REG = Registry.load()
WEATHER = ToolSpec(name="get_weather", description="Weather for a city",
parameters={"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]})
def build(key: str, req: Request) -> dict:
spec = REG.models[key]
return ADAPTERS[spec.api](spec).build(req)
def dump(obj) -> dict:
"""JSON-safe view: pydantic objects (Gemini) become dicts."""
return json.loads(json.dumps(obj, default=lambda o: o.model_dump(mode="json", exclude_none=True)))
def test_system_and_output_cap_land_in_each_providers_own_place(monkeypatch) -> None:
monkeypatch.setenv("OPENAI_API_KEY", "x"); monkeypatch.setenv("ANTHROPIC_API_KEY", "x")
monkeypatch.setenv("GEMINI_API_KEY", "x"); monkeypatch.setenv("OPENROUTER_API_KEY", "x")
req = Request(model="x", system="Be brief.", max_output_tokens=300, messages=[Message.user("Hi")])
assert build("luna", req)["instructions"] == "Be brief." and build("luna", req)["max_output_tokens"] == 300
chat = build("luna-chat", req)
assert chat["messages"][0] == {"role": "system", "content": "Be brief."} and chat["max_completion_tokens"] == 300
assert "max_completion_tokens" not in build("or-luna", req) and build("or-luna", req)["max_tokens"] == 300 # dialect
a = build("haiku", req)
assert a["system"] == "Be brief." and a["max_tokens"] == 300
g = dump(build("flash", req))
assert g["config"]["system_instruction"] == "Be brief." and g["config"]["max_output_tokens"] == 300
gi = build("flash-interactions", req)
assert gi["system_instruction"] == "Be brief." and gi["generation_config"]["max_output_tokens"] == 300 and gi["store"] is False
def test_tool_choice_vocabularies(monkeypatch) -> None:
for k in ("OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GEMINI_API_KEY", "OPENROUTER_API_KEY"):
monkeypatch.setenv(k, "x")
m = [Message.user("w?")]
req = Request(model="x", messages=m, tools=[WEATHER], tool_choice=ForcedTool(name="get_weather"))
assert build("luna", req)["tool_choice"] == {"type": "function", "name": "get_weather"}
assert build("luna-chat", req)["tool_choice"] == {"type": "function", "function": {"name": "get_weather"}}
assert build("haiku", req)["tool_choice"] == {"type": "tool", "name": "get_weather"}
fc = dump(build("flash", req))["config"]["tool_config"]["function_calling_config"]
assert fc == {"mode": "ANY", "allowed_function_names": ["get_weather"]}
assert build("flash-interactions", req)["generation_config"]["tool_choice"] == {
"allowed_tools": {"mode": "any", "tools": ["get_weather"]}}
required = req.model_copy(update={"tool_choice": "required", "parallel_tool_calls": False})
assert build("luna", required)["tool_choice"] == "required" and build("luna", required)["parallel_tool_calls"] is False
assert build("haiku", required)["tool_choice"] == {"type": "any", "disable_parallel_tool_use": True}
def test_tool_shapes(monkeypatch) -> None:
for k in ("OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GEMINI_API_KEY"):
monkeypatch.setenv(k, "x")
req = Request(model="x", messages=[Message.user("w?")], tools=[WEATHER])
assert build("luna", req)["tools"][0]["name"] == "get_weather" # flat
assert build("luna-chat", req)["tools"][0]["function"]["name"] == "get_weather" # nested
assert build("haiku", req)["tools"][0]["input_schema"]["required"] == ["city"] # input_schema
assert dump(build("flash", req))["config"]["tools"][0]["function_declarations"][0]["name"] == "get_weather"
assert build("flash-interactions", req)["tools"][0] == {"type": "function", "name": "get_weather",
"description": "Weather for a city", "parameters": WEATHER.parameters}
def test_tool_result_placement(monkeypatch) -> None:
for k in ("OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GEMINI_API_KEY", "OPENROUTER_API_KEY"):
monkeypatch.setenv(k, "x")
history = [Message.user("w?"),
Message(role="assistant", parts=[ToolCallPart(id="call_1", name="get_weather", arguments={"city": "Paris"})]),
Message.tool_results(ToolResultPart(call_id="call_1", name="get_weather", content="12C")),
Message.user("Thanks, and tomorrow?")]
req = Request(model="x", messages=history, tools=[WEATHER])
items = build("luna", req)["input"]
assert items[1] == {"type": "function_call", "call_id": "call_1", "name": "get_weather", "arguments": '{"city": "Paris"}'}
assert items[2] == {"type": "function_call_output", "call_id": "call_1", "output": "12C"}
msgs = build("luna-chat", req)["messages"]
assert msgs[2] == {"role": "tool", "tool_call_id": "call_1", "content": "12C"}
a = build("haiku", req)["messages"]
assert [m["role"] for m in a] == ["user", "assistant", "user"] # tool result + next user text MERGED
assert a[2]["content"][0] == {"type": "tool_result", "tool_use_id": "call_1", "content": "12C"} # and it comes FIRST
assert a[2]["content"][1]["type"] == "text"
g = dump(build("flash", req))["contents"]
assert g[2]["parts"][0]["function_response"] == {"name": "get_weather", "response": {"output": "12C"}, "id": "call_1"}
steps = build("flash-interactions", req)["input"]
assert {"type": "function_result", "call_id": "call_1", "name": "get_weather", "result": "12C", "is_error": False} in steps
# text said BEFORE a call stays before it (the first Interactions replay put every text step after every call step)
turn = Message(role="assistant", parts=[TextPart(text="Checking."), ToolCallPart(id="c1", name="get_weather", arguments={"city": "Paris"}),
TextPart(text="Done.")])
steps = build("flash-interactions", Request(model="x", messages=[Message.user("w?"), turn], tools=[WEATHER]))["input"]
assert [s["type"] for s in steps] == ["user_input", "model_output", "function_call", "model_output"]
def test_media_parts(monkeypatch) -> None:
for k in ("OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GEMINI_API_KEY"):
monkeypatch.setenv(k, "x")
img = ImagePart(media_type="image/png", data_b64="aGk=")
req = Request(model="x", messages=[Message(role="user", parts=[TextPart(text="what is this?"), img])])
assert build("luna", req)["input"][0]["content"][1] == {"type": "input_image", "image_url": "data:image/png;base64,aGk=", "detail": "auto"}
assert build("luna-chat", req)["messages"][0]["content"][1]["image_url"]["url"].startswith("data:image/png;base64,")
assert build("haiku", req)["messages"][0]["content"][1] == {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "aGk="}}
assert dump(build("flash", req))["contents"][0]["parts"][1]["inline_data"]["mime_type"] == "image/png"
assert build("flash-interactions", req)["input"][0]["content"][1] == {"type": "image", "mime_type": "image/png", "data": "aGk="}
class Order(BaseModel):
customer: str
quantity: int
def test_structured_output_native_mechanism(monkeypatch) -> None:
for k in ("OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GEMINI_API_KEY"):
monkeypatch.setenv(k, "x")
req = Request(model="x", messages=[Message.user("x")], output_schema=Order)
fmt = build("luna", req)["text"]["format"]
assert fmt["type"] == "json_schema" and fmt["strict"] is True and fmt["schema"]["additionalProperties"] is False
assert build("luna-chat", req)["response_format"]["json_schema"]["name"] == "Order"
assert build("haiku", req)["output_config"]["format"]["type"] == "json_schema"
cfg = dump(build("flash", req))["config"]
assert cfg["response_mime_type"] == "application/json" and cfg["response_json_schema"]["title"] == "Order"
assert build("flash-interactions", req)["response_format"]["mime_type"] == "application/json"
@pytest.mark.parametrize("key, level, expected", [
("luna", "off", {"reasoning": {"effort": "none"}}),
("luna", "high", {"reasoning": {"effort": "high"}}),
("sol", "off", {"reasoning": {"effort": "low"}}), # always reasons: "none" would be a 400
("haiku", "off", {"thinking": {"type": "disabled"}}),
("sonnet", "off", {"thinking": {"type": "between_tools"}}),
("haiku", "high", {"thinking": {"type": "adaptive", "display": "summarized"}, "output_config": {"effort": "high"}}),
])
def test_reasoning_effort_is_per_model_not_per_provider(monkeypatch, key, level, expected) -> None:
"""Lesson 02.8, 3.6, folded in: one app-level setting, translated using the MODEL's row in the registry."""
monkeypatch.setenv("OPENAI_API_KEY", "x"); monkeypatch.setenv("ANTHROPIC_API_KEY", "x")
out = build(key, Request(model="x", messages=[Message.user("x")], reasoning_effort=level))
for k, v in expected.items():
assert out[k] == v
def test_gemini_reasoning_levels(monkeypatch) -> None:
monkeypatch.setenv("GEMINI_API_KEY", "x")
cfg = dump(build("flash", Request(model="x", messages=[Message.user("x")], reasoning_effort="off")))["config"]
assert cfg["thinking_config"] == {"include_thoughts": True, "thinking_level": "LOW"} # "minimal" is an error here
gi = build("flash-interactions", Request(model="x", messages=[Message.user("x")], reasoning_effort="high"))
assert gi["generation_config"]["thinking_level"] == "high"
def test_provider_keyed_extra_never_leaks_to_other_providers(monkeypatch) -> None:
for k in ("OPENAI_API_KEY", "ANTHROPIC_API_KEY", "OPENROUTER_API_KEY"):
monkeypatch.setenv(k, "x")
req = Request(model="x", messages=[Message.user("x")], extra={
"openai": {"service_tier": "flex"}, "openrouter": {"extra_body": {"provider": {"sort": "price"}}}})
assert build("luna", req)["service_tier"] == "flex"
assert "service_tier" not in build("haiku", req)
assert build("or-luna", req)["extra_body"] == {"provider": {"sort": "price"}}
def test_openrouter_reasoning_goes_in_extra_body(monkeypatch) -> None:
monkeypatch.setenv("OPENROUTER_API_KEY", "x")
out = build("or-luna", Request(model="x", messages=[Message.user("x")], reasoning_effort="medium"))
assert out["extra_body"] == {"reasoning": {"effort": "medium"}} and "reasoning_effort" not in out
def test_native_reasoning_replays_only_to_the_same_api(monkeypatch) -> None:
"""Opaque reasoning cannot cross providers: a fallback mid-conversation must DROP it (lesson 03.11, 5.5)."""
for k in ("OPENAI_API_KEY", "ANTHROPIC_API_KEY"):
monkeypatch.setenv(k, "x")
signed = {"type": "thinking", "thinking": "hmm", "signature": "SIG"}
history = [Message.user("q"), Message(role="assistant", parts=[
ReasoningPart(text="hmm", native=Native(provider="anthropic", api="messages", payload=signed)), TextPart(text="a")]),
Message.user("next")]
req = Request(model="x", messages=history)
assert build("haiku", req)["messages"][1]["content"][0] == signed # replayed unchanged
assert build("sonnet", req)["messages"][1]["content"][0] == signed # same provider and API
other = build("luna", req)["input"]
assert all("SIG" not in json.dumps(i) for i in other) # dropped for OpenAI
assert other[1] == {"role": "assistant", "content": "a"}
def test_image_urls_are_translated_not_dropped(monkeypatch) -> None:
for k in ("OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GEMINI_API_KEY"):
monkeypatch.setenv(k, "x")
req = Request(model="x", messages=[Message(role="user", parts=[ImagePart(media_type="image/png", url="https://e.com/a.png")])])
assert build("luna", req)["input"][0]["content"][0]["image_url"] == "https://e.com/a.png"
assert build("haiku", req)["messages"][0]["content"][0]["source"] == {"type": "url", "url": "https://e.com/a.png"}
assert dump(build("flash", req))["contents"][0]["parts"][0]["file_data"]["file_uri"] == "https://e.com/a.png"
assert build("flash-interactions", req)["input"][0]["content"][0]["uri"] == "https://e.com/a.png"
def test_assistant_turns_without_text_never_send_empty_content(monkeypatch) -> None:
"""A tool-only turn, a reply cut off while thinking and a refusal-only turn have no text. Several APIs answer
an empty text block, an empty string or a Content with no parts with a 400, so every adapter must OMIT them."""
for k in ("OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GEMINI_API_KEY"):
monkeypatch.setenv(k, "x")
tool_only = Message(role="assistant", parts=[TextPart(text=""), ToolCallPart(id="c1", name="get_weather", arguments={"city": "Paris"})])
empty = Message(role="assistant", parts=[TextPart(text=""), ReasoningPart(text="hmm")]) # cut off while thinking
history = [Message.user("w?"), tool_only,
Message.tool_results(ToolResultPart(call_id="c1", name="get_weather", content="12C")),
empty, Message.user("and now?")]
req = Request(model="x", messages=history, tools=[WEATHER])
wire = {k: json.dumps(dump(build(k, req)), default=str) for k in ("luna", "luna-chat", "haiku", "flash", "flash-interactions")}
for key, text in wire.items():
assert '"text": ""' not in text and '"content": ""' not in text and '"parts": []' not in text, key
assert [m["role"] for m in build("haiku", req)["messages"]] == ["user", "assistant", "user"] # empty turn dropped, users merged
assert all(m.get("content") != "" for m in build("luna-chat", req)["messages"])
assert all(i.get("content") != "" for i in build("luna", req)["input"])
def test_invalid_tool_arguments_are_replayed_as_the_model_sent_them(monkeypatch) -> None:
"""Rewriting a truncated '{"city": "Pa' as '{}' changes what the model said. The raw string rides in `native`."""
from provider_agnostic.adapters.base import Builder
monkeypatch.setenv("OPENAI_API_KEY", "x")
b = Builder()
b.tool_start(0, "c1", "get_weather", 0)
b.tool_args(0, '{"city": "Pa', 0) # a stream cut off in the middle of the arguments
call = b.to_response(provider="openai", api="chat").tool_calls[0]
assert call.arguments == {} and call.arguments_error and call.native is not None
history = [Message.user("w?"), Message(role="assistant", parts=[call]),
Message.tool_results(ToolResultPart(call_id="c1", name="get_weather", content="bad arguments", is_error=True))]
wire = build("luna-chat", Request(model="x", messages=history, tools=[WEATHER]))["messages"]
assert wire[1]["tool_calls"][0]["function"]["arguments"] == '{"city": "Pa'
assert wire[2]["content"] == "Error: bad arguments" # the OpenAI route marks the error in the text
# the Chat and generate_content streams name their blocks ("r", "t", ("call", n)): they must come out in the order they
# opened (sorting the names as text put every call first, and call 10 before call 2)
b = Builder()
b.reasoning("r", "hmm")
b.text("t", "Checking")
for i in range(12):
b.tool_start(("call", i), f"c{i}", "get_weather", i)
parts = b.to_response(provider="openai", api="chat").parts
assert [type(p).__name__ for p in parts[:2]] == ["ReasoningPart", "TextPart"]
assert [p.id for p in parts[2:] if isinstance(p, ToolCallPart)] == [f"c{i}" for i in range(12)]tests/test_fallback_hooks.py#
"""tests/test_fallback_hooks.py: the reliability policy and the hooks (layer 3: real SDKs, mock servers)."""
from __future__ import annotations
import json
import logging
import pytest
from provider_agnostic.client import LLMClient, Policy
from provider_agnostic.errors import BadRequest, QuotaExceeded, RateLimited, ServerError
from provider_agnostic.hooks import Hook, JsonlCostHook, LoggingHook, MetricsHook
from provider_agnostic.types import FinishReason, Message, Request
from prices import PriceTable
from tests.conftest import CASES, registry_for
from tests.fakes import FakeAnthropic, FakeResponses, Server
HELLO = Request(model="fast", messages=[Message.user("Say hello")])
PRICES = PriceTable.load()
def two_models(primary: list, secondary: list, *, hooks: list[Hook] | None = None, **policy):
"""fast = [luna (OpenAI Responses), haiku (Anthropic Messages)], each behind its own scripted server."""
s1, s2 = Server(primary), Server(secondary)
reg = registry_for({"luna": CASES["openai-responses"][1], "haiku": CASES["anthropic"][1]},
{"fast": ["luna", "haiku"]})
# the registry entries above use fake model IDs for the price lookup, so point them at the real ones
client = LLMClient(reg, prices=PRICES, hooks=hooks, policy=Policy(**policy),
http_clients={"luna": s1.clients(), "haiku": s2.clients()},
sleep=lambda s: None)
return client, s1, s2
oa, an = FakeResponses(), FakeAnthropic()
def test_fallback_after_retries_are_used_up_and_the_log_shows_both(caplog: pytest.LogCaptureFixture) -> None:
caplog.set_level(logging.INFO, logger="provider_agnostic")
client, s1, s2 = two_models([oa.error("overloaded")], [an.text("Hello from Claude", inp=20, out=5, cached=8)],
hooks=[LoggingHook()], max_attempts=2)
resp = client.complete(HELLO)
assert resp.text == "Hello from Claude" and resp.provider == "anthropic" and resp.model_key == "haiku"
assert s1.n == 2 and s2.n == 1 # 2 tries on the primary, then the fallback
assert [(a.model_key, a.n, a.ok, a.error_type) for a in resp.attempts] == [
("luna", 1, False, "Overloaded"), ("luna", 2, False, "Overloaded"), ("haiku", 1, True, None)]
lines = [json.loads(r.message) for r in caplog.records]
assert [l["event"] for l in lines] == ["llm_attempt", "llm_attempt", "llm_attempt", "llm_call"]
assert lines[-1]["provider"] == "anthropic" and lines[-1]["attempts"] == 3
assert resp.cost is not None and resp.cost.source == "computed" and resp.cost.usd is not None
# 12 uncached, 8 cached and 5 output tokens, at Haiku 5.5's rates from prices.yaml (lesson 03.7)
assert resp.cost.usd == pytest.approx(12 * 0.10 / 1e6 + 8 * 0.01 / 1e6 + 5 * 0.50 / 1e6, rel=1e-6)
def test_bad_request_never_falls_back() -> None:
client, s1, s2 = two_models([oa.error("bad_request")], [an.text()])
with pytest.raises(BadRequest):
client.complete(HELLO)
assert s2.n == 0 # a bug in the request is a bug everywhere
def test_quota_falls_back_immediately_without_retrying() -> None:
client, s1, s2 = two_models([oa.error("quota")], [an.text()], max_attempts=3)
resp = client.complete(HELLO)
assert s1.n == 1 and resp.provider == "anthropic" # retrying an empty wallet cannot help
def test_refusal_does_not_trigger_fallback_unless_you_choose_it() -> None:
client, s1, s2 = two_models([oa.refusal()], [an.text()])
resp = client.complete(HELLO)
assert resp.finish_reason is FinishReason.REFUSAL and s2.n == 0 # the refusal is returned, not hidden
client, s1, s2 = two_models([oa.refusal()], [an.text()])
client.policy = Policy(fallback_on_finish=frozenset({FinishReason.REFUSAL})) # a deliberate choice
resp = client.complete(HELLO)
assert resp.provider == "anthropic"
assert [(a.ok, a.error_type) for a in resp.attempts] == [(False, "FinishFallback:refusal"), (True, None)]
assert resp.attempts[0].cost_usd is not None # the discarded reply was billed: its cost is on the record
def test_every_model_fails_raises_the_last_error_with_all_attempts() -> None:
client, s1, s2 = two_models([oa.error("server")], [an.error("rate_limit")], max_attempts=2)
with pytest.raises(RateLimited) as info:
client.complete(HELLO)
assert [a.model_key for a in info.value.attempts] == ["luna", "luna", "haiku", "haiku"]
assert isinstance(info.value.__cause__, Exception) and info.value.__cause__ is not info.value
def test_long_retry_after_skips_straight_to_the_next_model() -> None:
slow = oa.error("rate_limit")
slow = (slow[0], {**slow[1], "retry-after": "300"}, slow[2]) # "come back in 5 minutes"
client, s1, s2 = two_models([slow], [an.text()], max_server_wait_s=20.0)
resp = client.complete(HELLO)
assert s1.n == 1 and resp.provider == "anthropic" # we do not hold a user request for 5 minutes
def test_deadline_stops_the_retry_loop() -> None:
now = [0.0]
s1, s2 = Server([oa.error("server")]), Server([an.text()])
reg = registry_for({"luna": CASES["openai-responses"][1], "haiku": CASES["anthropic"][1]}, {"fast": ["luna", "haiku"]})
client = LLMClient(reg, policy=Policy(max_attempts=10, deadline_s=5.0), http_clients={"luna": s1.clients(), "haiku": s2.clients()},
sleep=lambda s: now.__setitem__(0, now[0] + 4), clock=lambda: now[0])
with pytest.raises(ServerError):
client.complete(HELLO.model_copy(update={"model": "luna"}))
assert s1.n < 10 # the deadline, not the attempt count, ended it
def test_capabilities_of_the_whole_chain_are_checked_before_anything_is_sent() -> None:
from provider_agnostic.errors import UnsupportedFeature
s1, s2 = Server([oa.text()]), Server([an.text()])
cap = {**CASES["anthropic"][1], "capabilities": {**CASES["anthropic"][1]["capabilities"], "forced_tool_choice": False}}
reg = registry_for({"luna": CASES["openai-responses"][1], "haiku": cap}, {"fast": ["luna", "haiku"]})
client = LLMClient(reg, http_clients={"luna": s1.clients(), "haiku": s2.clients()})
from provider_agnostic.types import ForcedTool, ToolSpec
req = Request(model="fast", messages=[Message.user("x")], tool_choice=ForcedTool(name="t"),
tools=[ToolSpec(name="t", description="d", parameters={"type": "object"})])
with pytest.raises(UnsupportedFeature, match="haiku"):
client.complete(req)
assert s1.n == 0 # not even the primary was called
def test_hooks_are_middleware_and_a_broken_hook_cannot_break_the_call(tmp_path, caplog) -> None:
class Stamp(Hook):
def before(self, ctx, req):
return req.model_copy(update={"system": "Be brief."})
def after(self, ctx, req, resp):
resp.parsed = None
return resp
class Broken(Hook):
def attempt(self, ctx, attempt):
raise RuntimeError("metrics server down")
metrics = MetricsHook()
cost_file = tmp_path / "calls.jsonl"
client, s1, s2 = two_models([oa.text()], [an.text()], hooks=[Stamp(), Broken(), metrics, JsonlCostHook(cost_file)])
resp = client.complete(HELLO.model_copy(update={"metadata": {"feature": "demo"}}))
assert s1.requests[0]["json"]["instructions"] == "Be brief." # request middleware changed what was sent
assert resp.text == "Hello there" # ...and the broken hook was contained
assert "observer hook Broken.attempt failed: RuntimeError" in caplog.text # the TYPE is logged, not the message
assert metrics.counts["attempt.luna.ok"] == 1 and metrics.counts["finish.stop"] == 1
record = json.loads(cost_file.read_text())
assert record["tags"] == {"feature": "demo"} and record["cost_usd"] is not None and record["request_id"]
assert record["outcome"] == "ok" and record["uncached_input_tokens"] == 12 and record["total_input_tokens"] == 20
def test_unpriced_models_report_unknown_not_zero(tmp_path) -> None:
reg = registry_for({"x": {**CASES["openai-responses"][1], "model": "gpt-9-imaginary"}})
s = Server([oa.text()])
client = LLMClient(reg, prices=PRICES, http_clients={"x": s.clients()})
resp = client.complete(HELLO.model_copy(update={"model": "x"}))
assert resp.cost is not None and resp.cost.usd is None and resp.cost.source == "unknown"
def test_openrouter_reported_cost_is_trusted() -> None:
from tests.fakes import FakeChat
fake = FakeChat(openrouter=True)
s = Server([fake.text()])
reg = registry_for({"or": CASES["openrouter-chat"][1]})
client = LLMClient(reg, prices=PRICES, http_clients={"or": s.clients()})
resp = client.complete(HELLO.model_copy(update={"model": "or"}))
assert resp.cost is not None and resp.cost.source == "provider" and resp.cost.usd == pytest.approx(0.000123)
def test_openrouter_error_inside_http_200_is_an_error() -> None:
from tests.fakes import FakeChat
fake = FakeChat(openrouter=True)
s = Server([fake.error("error_in_200")])
client = LLMClient(registry_for({"or": CASES["openrouter-chat"][1]}), policy=Policy(max_attempts=1),
http_clients={"or": s.clients()})
with pytest.raises(RateLimited):
client.complete(HELLO.model_copy(update={"model": "or"}))tests/test_parity_schemas.py#
"""tests/test_parity_schemas.py: our usage arithmetic equals lesson 03.7's, and the private-helper pin."""
from __future__ import annotations
import cost_calc
from provider_agnostic.client import ADAPTERS
from provider_agnostic.registry import Registry
from provider_agnostic.schemas import anthropic_schema, openai_strict
from tests.conftest import CASES, make_client
from tests.fakes import FakeChat
from provider_agnostic.types import Message, Request
from pydantic import BaseModel
def canonical_vs_037(case: str, to_037) -> None:
fake = CASES[case][0]
client, _ = make_client(case, [fake.text(inp=1200, out=300, cached=800)])
resp = client.complete(Request(model="m", messages=[Message.user("x")]))
ours, theirs = resp.usage, to_037(resp.raw)
assert (ours.uncached_input_tokens, ours.cached_input_tokens, ours.output_tokens, ours.reasoning_tokens) == (
theirs.input, theirs.cached_input, theirs.output, theirs.reasoning)
def test_usage_matches_cost_calc_for_every_provider() -> None:
canonical_vs_037("openai-responses", cost_calc.from_openai_response)
canonical_vs_037("openai-chat", cost_calc.from_openai_chat)
canonical_vs_037("openrouter-chat", cost_calc.from_openrouter)
canonical_vs_037("anthropic", cost_calc.from_anthropic)
canonical_vs_037("gemini-generate", lambda raw: cost_calc.from_gemini(raw, "gemini-3.8-flash"))
canonical_vs_037("gemini-interactions", lambda raw: cost_calc.from_gemini_interaction(raw.usage, "gemini-3.8-flash"))
class Item(BaseModel):
sku: str
quantity: int
note: str | None = None
def test_openai_strict_helper_pin() -> None:
"""The openai SDK's strict transform is PRIVATE (openai.lib._pydantic). If an upgrade changes it, this fails first."""
schema = openai_strict(Item)
assert schema["additionalProperties"] is False
assert schema["required"] == ["sku", "quantity", "note"] # strict mode: every property is required
as_dict = openai_strict(Item.model_json_schema()) # the dict path used for ToolSpec.strict
assert as_dict["additionalProperties"] is False and as_dict["required"] == schema["required"]
def test_anthropic_transform_schema_is_public_and_stable() -> None:
schema = anthropic_schema(Item)
assert schema["additionalProperties"] is False and schema["required"] == ["sku", "quantity"] # optional stays optionaltests/test_refresh.py#
"""tests/test_refresh.py: the registry audit, with fixtures instead of the Models APIs (layer 1)."""
import datetime as dt
from provider_agnostic.refresh import Live, audit
from provider_agnostic.registry import Registry
def test_audit_finds_missing_drifted_and_retiring_models() -> None:
reg = Registry.load()
live = {
"openai": {"gpt-6-luna": Live(), "gpt-6.1-sol": Live(retires_at="2026-12-01")},
"anthropic": {"claude-haiku-5-5": Live(1_000_000, 64_000)}, # sonnet missing; haiku output limit drifted
"gemini": None, # no key: reported, not an error
"openrouter": {"openai/gpt-6-luna": Live(), "anthropic/claude-haiku-5.5": Live()},
}
found = {(f.key, f.level) for f in audit(reg, live, today=dt.date(2026, 11, 4))}
assert ("sonnet", "error") in found # not in the provider's list
assert ("haiku", "warn") in found # 128,000 vs 64,000
assert ("sol", "error") in found # retires in 27 days: under the 30-day line
assert ("luna", "warn") not in found and ("flash", "info") in found
def test_a_far_off_retirement_is_only_a_warning() -> None:
reg = Registry.load()
live = {"openai": {"gpt-6-luna": Live(retires_at="2027-03-01"), "gpt-6.1-sol": Live()}}
levels = {f.key: f.level for f in audit(reg, live, today=dt.date(2026, 11, 4)) if f.key in ("luna", "sol")}
assert levels == {"luna": "warn"}tests/test_network_guard.py#
"""tests/test_network_guard.py: the safety net under every mock test (layer 1)."""
import socket
import openai
import pytest
def test_a_real_connection_attempt_fails_the_test_run_loudly() -> None:
with pytest.raises(RuntimeError, match="real network connection"):
socket.socket().connect(("127.0.0.1", 9))
def test_an_unmocked_sdk_call_cannot_reach_the_network() -> None:
"""The failure mode this guards against: a mock library that patches httpx but not httpx2 (respx, with the
openai and anthropic SDKs). The default client would then send a REAL request; here it cannot."""
client = openai.OpenAI(api_key="sk-test", base_url="http://127.0.0.1:9/v1", max_retries=0)
with pytest.raises(RuntimeError, match="real network connection"): # the guard's own error, raised through the SDK
client.models.list()tests/test_standin.py#
"""tests/test_standin.py: the same wrapper against a REAL (local) model server (layer 2).
Runs only when Ollama (:11434) is up, and after `. localstack/env.sh`.
It proves the plumbing end to end through the real SDKs. It proves nothing about hosted models: the stand-in
is a 0.5B model, ignores many parameters, and has no Gemini route at all (lesson 03.1, 12.4).
"""
from __future__ import annotations
import pytest
from pydantic import BaseModel
from provider_agnostic.client import LLMClient, Policy
from provider_agnostic.errors import UnsupportedFeature
from provider_agnostic.registry import Registry
from provider_agnostic.types import Done, FinishReason, Message, Request, TextDelta, ToolSpec
from tests.conftest import standin_skip_reason
from weather_tools import GetWeather
SKIP = standin_skip_reason() # the reason names what to do: Ollama down, env.sh not sourced
pytestmark = [pytest.mark.standin, pytest.mark.skipif(SKIP is not None, reason=SKIP or "")]
TEXT_ROUTES = ["local-responses", "local-chat", "local-anthropic"]
@pytest.fixture(scope="module")
def client():
with LLMClient(Registry.load("provider_agnostic/models.local.yaml"), policy=Policy(max_attempts=1, attempt_timeout_s=60)) as c:
yield c
class Capital(BaseModel):
city: str
country: str
@pytest.mark.parametrize("route", TEXT_ROUTES)
def test_plain_call(client: LLMClient, route: str) -> None:
resp = client.complete(Request(model=route, messages=[Message.user("Say hello in three words.")], system="Be brief."))
assert resp.text.strip() and resp.finish_reason is FinishReason.STOP
assert resp.usage is not None and resp.usage.output_tokens > 0
assert resp.cost is not None and resp.cost.usd == 0.0 and resp.provider == "local"
@pytest.mark.parametrize("route", TEXT_ROUTES)
def test_streaming(client: LLMClient, route: str) -> None:
events = list(client.stream(Request(model=route, messages=[Message.user("Count to three.")])))
deltas = [e.text for e in events if isinstance(e, TextDelta)]
assert len(deltas) > 1 and isinstance(events[-1], Done) # many chunks, then one assembled response
assert events[-1].response.text == "".join(deltas)
@pytest.mark.parametrize("route", ["local-responses", "local-chat"])
def test_structured_output(client: LLMClient, route: str) -> None:
resp = client.complete(Request(model=route, messages=[Message.user("Name the capital of France.")],
output_schema=Capital, max_output_tokens=120))
assert isinstance(resp.parsed, Capital) # a 0.5B model fills the schema, right or wrong
def test_a_route_that_cannot_enforce_a_schema_says_so_before_sending(client: LLMClient) -> None:
with pytest.raises(UnsupportedFeature, match="structured output"):
client.complete(Request(model="local-anthropic", messages=[Message.user("x")], output_schema=Capital))
@pytest.mark.parametrize("route", ["local-responses", "local-chat", "local-anthropic"])
def test_tool_call_round_trip(client: LLMClient, route: str) -> None:
tool = ToolSpec.from_model(GetWeather)
req = Request(model=route, messages=[Message.user("What is the weather in Paris in celsius? Use the tool.")],
tools=[tool], max_output_tokens=200)
first = client.complete(req)
if not first.tool_calls:
pytest.skip(f"the 0.5B model did not call the tool on {route} (it sometimes doesn't)")
call = first.tool_calls[0]
assert call.name == "GetWeather" and isinstance(call.arguments, dict)
from provider_agnostic.types import ToolResultPart
history = [*req.messages, first.message,
Message.tool_results(ToolResultPart(call_id=call.id, name=call.name, content='{"temp": 12, "unit": "celsius"}'))]
second = client.complete(req.model_copy(update={"messages": history}))
assert second.text.strip()← 03.10 — Logging, Debugging and Testing LLM Code | Module 03 overview | 03.12 — Minimal Tracing: See What Your First LLM App Did →