OpenRouter Client (Python)
item / server / ai
One OpenRouter chat client on http-retry: fallback models, strict json_schema output, usage.cost, served-model drift warning, fails closed without a key.
- type
- item
- files
- 2
- registry deps
- https://components.automindz.app/r/http-retry.json
- npm deps
- none
- env vars
- OPENROUTER_API_KEY, OPENROUTER_BASE_URL, OPENROUTER_APP_URL, OPENROUTER_APP_NAME
installs
- ~/backend/openrouter.py
- ~/backend/tests/test_openrouter.py
- One default model, overridable per call — five repos disagreed, this picks one
- fallback_models rides OpenRouter's server-side route: fallback; a served model that differs from the requested one logs a WARNING
- Fails closed before any HTTP call without OPENROUTER_API_KEY; the key never appears in an error or a log
result = openrouter.chat([{"role": "user", "content": "Say hi"}]) — result.text, result.usage (prompt_tokens, completion_tokens, cost from OpenRouter's own usage.cost), result.model (what actually served) versus result.requested_model. fallback_models=(...) reroutes server-side around a saturated primary; a served model that differs from the requested one logs a WARNING naming both, so a silent provider swap surfaces. json_schema={"name": ..., "schema": {...}} gives strict structured output in result.parsed (or {"error": ...} on a parse failure, never a swallowed exception). One default model (DEFAULT_MODEL), overridable per call — the five source repos disagreed. Retries and timeout are http_retry's, installed alongside. Requires OPENROUTER_API_KEY; without it chat() raises OpenRouterError before any HTTP call, and the key never appears in an error or a log. OPENROUTER_BASE_URL overrides the host; OPENROUTER_APP_URL / OPENROUTER_APP_NAME become the HTTP-Referer / X-Title attribution headers when set. Move the names the CLI wrote to .env.local into the host env.
Variations
one state per section
No previews for this item yet.
