openrouter
robotsix_llmio.openrouter
OpenRouter transport layer (model-family agnostic).
The model/provider (which import pydantic-ai and thus opentelemetry) are loaded
lazily via PEP 562 __getattr__ so importing the lightweight transient
helpers does not drag in pydantic-ai/OTel at module load.
OpenRouterAPIError
Bases: RobotsixLLMIOError
Error from the OpenRouter client (HTTP, auth, malformed response).
AsyncOpenRouterClient
Async OpenRouter REST client for per-key usage and account credits.
Hits the OpenRouter public REST API with Bearer-auth. Creates a fresh,
timeout-bounded httpx2.AsyncClient per request (stateless per-call
pattern, matches the sync OpenRouterKeyCostSource).
fetch_key_usage
async
fetch_key_usage()
Current cumulative usage of the authenticating key.
Hits GET {base_url}/auth/key.
Raises OpenRouterAPIError on transport or HTTP errors.
fetch_credits
async
fetch_credits()
Account-level credit balance.
Hits GET {base_url}/credits. Returns a dict with keys
total_credits, total_usage, and remaining (each
rounded to 6 decimal places).
Raises OpenRouterAPIError on transport or HTTP errors.
OpenRouterDeepseekModel
Bases: OpenRouterModel
OpenRouter model pinned to DeepSeek, with a per-tier reasoning policy and
the thinking-mode reasoning_content round-trip.
The provider stamps reasoning_setting and provider_routing per tier
after construction (e.g. {"effort": "xhigh"} for the capable tier or
{"enabled": False} for the cheap tier); sensible defaults (reasoning on
at xhigh, DeepSeek preferred with fallbacks under the capable-tier price
ceiling) apply if unset. The round-trip is active on every tier except the
disabled one, derived from reasoning_setting (no separate flag needed).
OpenRouterDeepseekProvider
Bases: OpenRouterProvider
OpenRouter preferring DeepSeek, with per-level reasoning + routing policy.
Routing defaults keep DeepSeek first (prompt-cache warmth) but allow OpenRouter to fall back to another provider under a price ceiling, so a single upstream's outage cannot block every request. Override per tier from config, e.g.::
{"level2": {"model": "openrouter-deepseek/deepseek-v4-pro",
"provider_kwargs": {"max_price_prompt": 1.0,
"max_price_completion": 2.0,
"ignore_providers": ["SomeProvider"]}}}
The routing knobs (preferred_provider, max_price_*,
ignore_providers, allow_fallbacks) apply to EVERY model served
through this provider — explicit values are always honoured, and only
the defaults differ by model family (DeepSeek-derived ceilings and
ignore list for deepseek/*, no routing constraints otherwise). The
reasoning policy and the reasoning_content round-trip stay
DeepSeek-specific.
OpenRouterModel
Bases: OpenAIChatModel
OpenAIChatModel that opts into OpenRouter usage accounting, emits
usage.cost onto the active OTel span, and annotates the stable request
prefix with cache_control markers for prompt caching. No pin, no
reasoning policy.
OpenRouterProvider
Bases: LLMProvider
Builds cost-instrumented OpenRouter models from a model name.
Subclasses MAY override :meth:_model_class / :meth:_post_build_model
to add provider-family quirks (pin, reasoning policy, …).
new_model
new_model(*, model=None, level=0)
Build a model, returning (model, http_client).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
str | None
|
The concrete model name (e.g.
|
None
|
level
|
int
|
Capability level (1, 2, 3) forwarded to
:meth: |
0
|
The returned http_client is the timeout-configured client backing
the model; the caller owns closing it.
KeyUsage
dataclass
An OpenRouter key's CUMULATIVE (lifetime) usage, from auth/key.
usage is total USD spent on this key since creation; limit is the
credit ceiling (None = unlimited). Cumulative, not windowed — a
per-day per-key cost is the consumer's daily snapshot diff.
OpenRouterKeyCostSource
Per-KEY cumulative usage from OpenRouter's GET /api/v1/auth/key.
Reads the usage of the authenticating inference key (not the account
total). Two uses: (1) per-project reconciliation when each project has its
own key — snapshot fetch_key_usage daily and diff to get a window's
spend; (2) an isolated live test — read usage, make a known call, read the
delta. Credentials passed in explicitly; reads no env vars.
fetch_key_usage
fetch_key_usage()
Current cumulative usage of the authenticating key.
Raises OpenRouterAPIError on transport or HTTP errors.
OpenRouterProviderCostSource
Provider-billed cost from OpenRouter's activity API.
Implements :class:~robotsix_llmio.core.provider_cost.ProviderCostSource.
fetch_provider_cost
fetch_provider_cost(window)
Sum OpenRouter's billed spend across every UTC day window covers.
Raises OpenRouterAPIError on transport or HTTP errors rather than
silently returning zero (a silent zero would read as "all spend
unlogged").
is_deepseek_reasoning_400
is_deepseek_reasoning_400(exc)
Recognise DeepSeek's reasoning-content 400.
DeepSeek's capable tier runs in thinking mode and rejects assistant
tool_calls turns that lack reasoning_content with HTTP 400
("The reasoning_content in the thinking mode must be passed back to
the API."). That is an infrastructure hiccup — the layer already
injects reasoning content, so a re-run almost always succeeds.
Matched on status 400 plus the distinctive reasoning_content +
thinking mode markers, so it does NOT catch genuine schema/request
400s.
is_openrouter_transient
is_openrouter_transient(exc)
Core transient set OR an OpenRouter upstream-failure signature (mid-stream provider error, upstream provider's 402, or DeepSeek reasoning-400), walking the cause/context chain for the latter.
is_openrouter_upstream_error
is_openrouter_upstream_error(exc)
Recognise OpenRouter's finish_reason='error' upstream-failure
signature.
When the provider behind OpenRouter errors mid-stream, OpenRouter returns
a completion with finish_reason: "error". The OpenAI SDK then raises a
pydantic ValidationError because "error" isn't in its
finish_reason literal set. That's an upstream hiccup, not a bug in the
prompt/schema — a re-run almost always succeeds, so ride it out.
Matched by the exception type name plus the distinctive finish_reason
+ 'error' markers, so it does NOT catch genuine structured-output
validation failures (those don't mention finish_reason). Two type
names qualify: the raw pydantic ValidationError, and pydantic-ai's
UnexpectedModelBehavior — since pydantic-ai wraps the response
validation failure as UnexpectedModelBehavior("Invalid response from
openrouter chat completions endpoint: 1 validation error for
ChatCompletion choices.0.finish_reason … input_value='error'") without
chaining the original, the type-only check let every such hiccup
surface as a hard agent failure (observed 2026-08-28: mill's document
stage gave up on a ticket for exactly this).
is_openrouter_upstream_payment_error
is_openrouter_upstream_payment_error(exc)
Recognise a 402 raised by the upstream provider, not by our account.
OpenRouter reports two very different things as HTTP 402:
- our own OpenRouter credits are exhausted — a real billing failure that must surface immediately, since retrying cannot help; and
- the upstream provider OpenRouter routed to has no balance of its own. The
body then carries
"Provider returned error"withmetadata.provider_nameset andmetadata.is_byok: False— meaning it is OpenRouter's account with that provider, nothing to do with ours.
Only the second is transient: a retry lets OpenRouter route to one of the
other providers serving the same model. Observed 2026-07-29, when the
DeepSeek upstream ran dry and every deepseek/* request 402'd while ~17
other providers were healthy.
Matched on the provider_name + is_byok markers rather than the
status alone, so a genuine "your account is out of credits" 402 (which
carries neither) still fails fast. The body reaches us either as a Python
dict repr ('is_byok': False, via ModelHTTPError) or as raw JSON
("is_byok":false), so quotes/spacing are normalised before matching.
record_openrouter_cost
record_openrouter_cost(response)
Copy usage.cost (+ tokens + cache details + gen_ai attrs) onto the
current OTel span. No-op without a cost, a recording span, or OpenTelemetry.
Also emits an INFO-level log line summarising the cached vs. uncached input token split so the prompt-caching win is directly measurable in logs.