Install with Codex or Claude Copy this prompt, paste it into Codex, Claude, or another assistant, and let it review the skill page and install it for you.
A direct command skips the review prompt. Inspect the source before running it.
Designed for Claude Code, also compatible with Codex and OpenClaw
OpenRouter SDK Patterns
Overview
Build production-grade OpenRouter client wrappers using the OpenAI SDK. The OpenAI Python/TypeScript SDKs work natively with OpenRouter by changing base_url to https://openrouter.ai/api/v1. This skill covers typed wrappers, retry strategies, middleware, and reusable patterns.
Prerequisites
An OpenRouter API key (sk-or-v1-...) exported as OPENROUTER_API_KEY — see the openrouter-install-auth skill for setup
Python 3.8+ with the OpenAI SDK plus requests (used for the /auth/key credits check and /generation cost lookups), or Node.js 18+ with the OpenAI SDK
Optional: tenacity if you want the custom retry decorator beyond the SDK's built-in backoff
An app name and URL to send as HTTP-Referer / X-Title default headers for dashboard attribution
Instructions
Start from the Python: Production Client Wrapper (or the TypeScript variant): point the OpenAI SDK at base_url="https://openrouter.ai/api/v1", read OPENROUTER_API_KEY from the environment, and set the HTTP-Referer / X-Title default headers in the constructor.
Return typed results from every call — the CompletionResult dataclass/interface captures content, the served model, prompt_tokens/completion_tokens, generation_id, and latency_ms.
Tune the SDK's built-in retries per the Retry Strategy section (max_retries, timeout in the constructor); add the tenacity decorator only when you need retry behavior beyond the SDK's 429/5xx/connection handling.
Layer cross-cutting concerns via the Middleware Pattern — with_cost_tracking queries GET /api/v1/generation?id= after each request and accumulates a session cost total.
Surface remaining credits and rate limits with check_credits(), which calls GET /api/v1/auth/key with the same key.
Map SDK exceptions using the Error Handling table, then apply the Enterprise Considerations (single central wrapper, dependency injection for tests, SLA-based ).
from functools import wraps
from typing importCallabledefwith_cost_tracking(fn: Callable) -> Callable:
"""Middleware that logs cost per request."""
total_cost = {"value": 0.0}
@wraps(fn)defwrapper(*args, **kwargs):
result = fn(*args, **kwargs)
# Query generation cost asynchronouslyimport requests
gen = requests.get(
f"https://openrouter.ai/api/v1/generation?id={result.id}",
headers={"Authorization": f"Bearer {args[0].api_key}"},
).json()
cost = float(gen.get("data", {}).get("total_cost", 0))
total_cost["value"] += cost
log.info(f"Request cost: ${cost:.6f} | Session total: ${total_cost['value']:.4f}")
return result
wrapper.total_cost = total_cost
return wrapper
Output
A typed CompletionResult per call: content, the model that actually served the request, prompt_tokens/completion_tokens, the gen-...generation_id, and latency_ms
A structured log line per request, e.g. [openai/gpt-4o-mini] 12+87 tokens, 843.2ms
Cost-tracking middleware output: per-request cost plus a running session total, e.g. Request cost: $0.000123 | Session total: $0.0045
A credits dict from check_credits() with usage and limit data from /api/v1/auth/key
Examples
Instantiate the wrapper once and make a typed call: