Tokenminning with OpenRouter
OpenRouter is a unified LLM gateway — not an IDE. Cline, Aider, OpenCode, and custom agents send requests through your OpenRouter API key. Waste shows up as frontier defaults, missing fallbacks, unstable prefixes (no cache hits), and shared keys without caps.
Work through the steps below in order. For the general technique stack, see Where to start. Pair this guide with your editor guide — OpenRouter forwards what clients send.
Quick checklist
- OpenRouter Activity — spend by model and API key.
- Set per-key spending limits and workspace budgets.
- Put cheap models first in fallback arrays — routing.
- Stabilize system prompts for prefix caching.
- Log
usage—cached_tokensconfirms cache hits. - Enforce org guardrails before production traffic.
Typical impact: 50–90% routing routine steps to haiku-tier; 10–30% from cache-aware prefixes; caps prevent runaway agent loops.
How to reduce OpenRouter spending
1. Measure first
Open openrouter.ai/activity . Filter by API key and model. Export CSV weekly. For one expensive generation, call GET /api/v1/generation?id=... to reconcile token breakdown.
2. Cap spend
Create separate API keys per tool (dev, CI, prod). Set a spending limit on each key at creation. For teams, use workspace budgets and org guardrails .
→ Activity & keys · Guardrails
3. Route cheap
Set a haiku-tier primary model and a capable model in the models fallback array. Add provider.sort: "price" for cost-sensitive loops. Avoid openrouter/auto and :nitro unless you have budget for unpredictable tiers.
4. Cache prefixes
Stabilize system prompts and tool schemas across turns. Read usage.prompt_tokens_details.cached_tokens after turn 3+. Set a stable session_id for sticky provider routing. Enable response caching for identical requests.
5. Trim upstream bloat
OpenRouter forwards what clients send — trim in each tool:
| Tool | Guide |
|---|---|
| OpenCode | MCP, context |
| Cline | Tokenminning in Cline |
| Aider | Tokenminning in Aider |
6. Guardrail in production
Use model allowlists, workspace isolation, and the Batch API for offline eval workloads. Wire the MCP server during development to check live model prices before you ship defaults.
How OpenRouter bills
Provider token cost + small platform fee. Prepay credits or invoice billing.
Each request: model, optional models fallbacks, optional provider sort (price / throughput / latency).
Response usage includes prompt/completion tokens, cached_tokens, cache_write_tokens, and cost. Failed fallbacks are not billed.
Guides
| Guide | What you’ll learn |
|---|---|
| Activity & keys | Dashboard, exports, per-key caps, billing truth |
| Guardrails | Workspace budgets, model allowlists, batch workloads |
| Prompt caching | Prefix caching, cached_tokens, cache_control, session_id |
| Model routing | Fallback arrays, cheap defaults, sort: price |
Connect your stack
Point any OpenAI-compatible client at https://openrouter.ai/api/v1:
import { OpenRouter } from "@openrouter/sdk";
const client = new OpenRouter({
apiKey: process.env.OPENROUTER_API_KEY,
});
const completion = await client.chat.send({
model: "anthropic/claude-haiku-4-20250514",
messages: [{ role: "user", content: "Summarize this diff." }],
});See the OpenRouter quickstart for Python, curl, and Agent SDK patterns.
Troubleshooting
| Symptom | Fix |
|---|---|
| Bill spike overnight | Lower key cap; haiku-only on that key — routing |
| Always billed for expensive model | Primary is frontier; set haiku first in models |
High cost, cached_tokens always zero | Stabilize prefix — caching |
| Context length errors | Add larger model as second models entry |
| Usage mismatch vs client | OpenRouter Activity is billing truth — activity |
When gateway tuning is not enough, instrument production agents with per-feature tags and Context hygiene runtime caps.
Anti-patterns
| Anti-pattern | Why it fails |
|---|---|
openrouter/auto on every call | Unpredictable tier mix |
| One key for CI + dev without caps | Overnight agent loops |
| Editing system prompt every turn | cached_tokens stays zero |
| Double gateway (OpenRouter + another proxy) | Latency and fees stack |
| Pareto / Fusion routers without a budget | Multi-model deliberation multiplies cost |