LLM API Guide

OpenRouter openrouter/auto-code & openrouter/auto: Setup & Prompt Cache Costs

Configure OpenRouter's openrouter/auto-code and openrouter/auto endpoints, restrict candidate models, and prevent mid-session switches from breaking prompt caches.

Summary

  1. openrouter/auto-code routes coding agents across top-tier models (led by GPT-6.1 Sol and Claude Opus 5.5).
  2. Restricting candidate models requires the auto-router plugin, while overriding cost_tier on auto-code requires the jev-router plugin ID.
  3. Switching models mid-session zeroes out your KV prompt cache, turning 0.1x cache reads into full-price prefills or 1.25x cache writes as of 2026-11-10.
  4. Passing an explicit session_id locks both the resolved model and provider for 60 minutes to protect your prompt cache discount as of 2026-11-10.

Setting "model": "openrouter/auto-code" or "model": "openrouter/auto" in an OpenRouter API request hands model selection over to OpenRouter's second-generation routing engine. Instead of relying on static task labels, the router runs a lightweight decision pass that evaluates eleven signals—including codebase context requirements, task difficulty, provider latency, live pricing, and prompt cache status—with a p90 routing overhead of 0.65 seconds (down from 1.96 seconds on the first-generation router).

OpenRouter charges zero markup for either router; you only pay the public token rate of whichever model processes your prompt. However, dropping an automatic router into a multi-turn coding harness like Claude Code, Codex, or OpenHands introduces a billing trap that single-turn benchmarks never show. Every time a router switches your session from one model family to another to save a few cents on list price, it invalidates your existing KV prompt cache. Instead of paying a 90% discounted cache-read rate on your accumulated repository context, you pay full input rates—or a 1.25x cache-write surcharge—to rebuild the context from scratch on the new model.

Below is how openrouter/auto-code and openrouter/auto differ under the hood, how to lock down their candidate model pools without hitting silent config bugs, and what the prompt cache math looks like across a 20-turn coding session.

On this page

openrouter/auto-code vs openrouter/auto: Model Pools and Real Task Costs

Although both endpoints share the same decision engine, they initialize at different price tiers and optimize for different session signals.

openrouter/auto is built for general application traffic, RAG pipelines, and one-off chat prompts. It defaults to a cost-efficient middle tier. In live traffic, roughly 47% of openrouter/auto volume lands on low-cost, high-throughput models such as DeepSeek V4.1 Flash, with the rest spread across mid-sized commercial and open-weight endpoints.

openrouter/auto-code was split out specifically for multi-turn coding agents and IDE harnesses. The previous generation of Auto Router drifted toward ultra-cheap models whose token efficiency looked great on simple prompts but caused high retry loops in repository-level editing. To fix that drift, openrouter/auto-code starts at a higher coding tier, weighs generation speed heavily, and tracks edits, test failures, and repeated compiler errors across turns. When I inspected the live 24-hour routing mix on openrouter/auto-code, three frontier models handled over 96% of all requests: openai/gpt-6.1-sol took 70.4%, anthropic/claude-opus-5.5 took 14.8%, and z-ai/glm-5.3 took 11.0%.

In the official launch benchmarks, OpenRouter highlights that openrouter/auto-code matches Claude Opus 5.5 accuracy across five benchmarks while cutting cost per task by 74% (as of 2026-11-10). That number is accurate, but you have to look at the baseline: auto-code is 74% cheaper than pinning every turn to Claude Opus 5.5, yet it is up to 3.7x more expensive per task than openrouter/auto.

Benchmark openrouter/auto-code (Score / Cost per Task as of 2026-11-10) openrouter/auto Medium Tier (Score / Cost per Task) Pinning anthropic/claude-opus-5.5 (Score / Cost per Task) Legacy Auto Router (Score / Cost per Task)
Deep SWE 74.3% / $1.98 69.0% / $0.57 70.5% / $7.76 64.6% / $1.37
SWE-Atlas QA 62.5% / $0.66 59.7% / $0.36 55.6% / $2.45 44.0% / $0.12
Terminal Bench 4.0 50.0% / $4.96 45.7% / $1.33 53.1% / $22.60 28.3% / $0.61
τ³-bench Banking 52.6% / $0.60 53.1% / $0.60 — 13.7% / $0.087
MMMU Pro Vision 82.3% / $0.025 80.1% / $0.020 — 74.4% / $0.006

Notice that "cost per task" includes failed edits and agent retries. A cheap model that fails unit tests twice can easily cost more per solved issue than a higher-tier model that passes on the first attempt. If you want to see how OpenRouter's pass-through billing and credit deductions work before running agent loops, check my breakdown of how much OpenRouter costs compared to direct APIs. Also keep in mind one regional limitation: openrouter/auto-code does not currently support EU in-region routing, so workloads with strict EU data residency rules must use openrouter/auto with region constraints instead.

How to Restrict Candidate Models and Avoid the cost_tier Trap

Both routers accept standard OpenAI Chat Completions, OpenAI Responses, and Anthropic Messages payloads, supporting context windows up to 2,000,000 tokens (bounded by whichever underlying model is chosen). Because you do not know in advance which model will answer, you should always read the top-level model field in the JSON response to log what actually ran.

If you want to see why the router picked a specific model, pass the header X-OpenRouter-Metadata: enabled. The response will include an openrouter_metadata.pipeline object listing resolved_models (the filtered pool), candidates (the specific models and reasoning effort levels scored for that turn), and reason (the exact selection rationale).

Filtering Models with allowed_models and excluded_models

In production, leaving the router open to all 600+ catalog models is rarely what you want—especially if your tool definitions are tuned for Anthropic and OpenAI schemas. You can restrict the candidate pool using the auto-router plugin inside the plugins array:

json
{
  "model": "openrouter/auto-code",
  "messages": [
    {
      "role": "user",
      "content": "Add exponential backoff to fetchUser in src/api/users.ts"
    }
  ],
  "plugins": [
    {
      "id": "auto-router",
      "allowed_models": [
        "anthropic/*",
        "openai/gpt-6.1-sol",
        "z-ai/glm-5.3"
      ],
      "excluded_models": [
        "openai/gpt-4o",
        "anthropic/claude-3-5-haiku*"
      ]
    }
  ]
}

Both arrays support * wildcards and act as hard filters. excluded_models always takes precedence over allowed_models. If your filter rules intersect with zero available models—or if your workspace guardrails and zero-data-retention (ZDR) policies eliminate the remaining matches—OpenRouter will reject the call immediately with an HTTP 404 error telling you to widen allowed_models or relax excluded_models.

The cost_tier Silent Ignore Bug (auto-router vs jev-router)

One configuration pitfall caught me off guard when testing openrouter/auto-code. On the general openrouter/auto endpoint, you can pass "cost_tier": "low" (out of low, medium, high, xhigh, and max) inside the auto-router plugin to force the router back toward cheap models.

If you pass "cost_tier" inside {"id": "auto-router"} while calling openrouter/auto-code, OpenRouter silently ignores the parameter because auto-code pins its own dedicated coding tier. To override the cost tier on openrouter/auto-code, you have to target the underlying engine plugin ID, jev-router, instead:

json
{
  "model": "openrouter/auto-code",
  "messages": [
    {
      "role": "user",
      "content": "Rename the userId parameter to accountId across this file."
    }
  ],
  "plugins": [
    {
      "id": "jev-router",
      "cost_tier": "medium"
    }
  ]
}

Remember that cost_tier selects a pricing band rather than enforcing a hard spending ceiling. Also remove legacy parameters like pin_model and cost_quality_tradeoff from older configs; the second-generation router ignores both without throwing a warning. To enforce a hard ceiling per million tokens, combine the router with OpenRouter's provider.max_price object.

The Hidden Prompt Cache Cost of Mid-Session Model Switching

Evaluating a router on single-turn prompts makes dynamic switching look like pure savings: send hard architecture prompts to Claude Opus 5.5 or GPT-6.1 Sol, and route simple file edits or test runs to a model that costs five times less.

In a coding agent, however, turns are not independent. Every turn sends the system prompt, MCP tool schemas, file trees, and the entire history of previous tool calls and test outputs. When I traced a 20-turn coding session that finished with a modest 10,135-token context window, the cumulative input sent across all 20 requests totaled 111,871 prompt tokens. The agent scanned the growing conversation history roughly 11 times.

Modern API economics rely on prefix KV caching to make that 11x repetition affordable. When you stay on one model and one provider, the provider stores the key-value tensors of your prompt prefix in GPU memory. On subsequent turns, you only pay full price for the newly appended tokens at the end of the array.

On Anthropic's pricing schedule, the spread between a warm cache and a cold cache is massive:

  • Standard uncached input: 1.0x base price
  • 5-minute Cache Write: 1.25x base price (a 25% surcharge to populate the cache)
  • Cache Read: 0.1x base price (a 90% discount on previously cached tokens)

I covered how these cache tiers interact with OpenAI's automatic prefix caching and 272K context cliffs in my comparison of Claude vs GPT coding bills at the same list price. When you introduce a dynamic router that switches models mid-session, two physical constraints break that discount:

First, a KV cache is bound to the exact model weights, layer dimensions, and tokenizer that generated it. A cache built by anthropic/claude-opus-5.5 on Turns 1 through 7 cannot be read by openai/gpt-6.1-sol or a cheaper Haiku-class model on Turn 8. When the router switches to a model that is 5x cheaper on Turn 8 to handle a trivial syntax fix, that cheaper model starts with a 0% cache hit rate. It must execute a full-price cold prefill across all 4,395 tokens accumulated during the first seven turns.

Second, switching back compounds the penalty. Suppose the cheaper model handles Turns 8 through 14, adding another 3,820 tokens of tool outputs and diffs, and then Turn 15 hits a failing test that causes the router to switch back to anthropic/claude-opus-5.5. Even if your initial 5-minute cache from Turn 7 has not expired, Claude has never seen Turns 8 through 14. It must run a cold prefill—and pay the 1.25x Cache Write fee—on all 3,820 intermediate tokens at frontier rates.

To see the exact dollar impact, here is the token and billing breakdown across that same 20-turn coding session (10,135 final tokens, 111,871 cumulative prompt tokens) under five routing strategies, normalized to frontier input pricing:

Routing Strategy Full-Price Prefill Tokens Session Cache Hit Rate Total Input Bill (Cents) Cost vs Sticky Baseline What Happened Under the Hood
Frontier Sticky Baseline (Single Model) 10,191 tokens 90.9% 11.45¢ 1.00x Only ~479 new incremental tokens are prefilled per turn; 90.9% of tokens bill at 0.1x cache read.
Gateway Alternating (Odd Turn Frontier / Even Turn 5x Cheaper) 19,855 tokens 82.2% 10.00¢ 0.87x Switching every turn nearly doubles cold prefill tokens (1.9x), shrinking a theoretical 40% price cut down to 13%.
Phase Routing (Switch Only Twice at Task Boundaries) 17,455 tokens 84.4% 8.10¢ 0.71x Cheap model handles initial file exploration; frontier model locks in for implementation. Saves 29%.
Frontier Cache-Blind (Provider/Model Jumps Every Turn) 111,871 tokens 0.0% 55.94¢ 4.88x Every turn triggers a full cold prefill across the entire history, multiplying the input bill nearly 5x.
Efficient Sticky (Single 5x Cheaper Model All 20 Turns) 10,191 tokens 90.9% 2.29¢ 0.20x Theoretical floor if a small model could pass every coding test without retries.

Look closely at the Gateway Alternating row vs the Cache-Blind row. Even a single poorly timed switch mid-session forces thousands of cached tokens back into full-price prefill territory. If a router switches models or hops across unpinned upstream providers without preserving cache affinity, your input bill can spike up to 4.88x higher than simply pinning a single frontier model from Turn 1.

You also pay a latency tax on every switch. At a 12,000-token context length, a warm cache hit returns its first token (TTFT) in 60 to 95 milliseconds, whereas a cold prefill takes around 287 milliseconds—a 3x to 4.8x slowdown that turns into multi-second pauses once your repository context climbs past 100,000 tokens.

Production Setup: Locking Sessions and Preserving Cache Discounts

OpenRouter engineered openrouter/auto-code to avoid naive per-turn ping-ponging. When an agent hits a test failure or tool error, auto-code raises the current model's reasoning_effort (thinking budget) before it considers abandoning the model and its warm cache. During beta testing, this restraint kept openrouter/auto-code on the same model for roughly 9 out of every 10 agent turns.

However, relying on message-fingerprint heuristics alone is risky when coding harnesses inject dynamic system reminders, timestamps, or git status blocks that alter the prompt structure. To guarantee that openrouter/auto-code picks an optimal model on Turn 1 and sticks to both that model and the same physical upstream provider for the rest of your task, apply three rules in your client configuration:

  1. Pass an explicit session_id on every turn: Including "session_id" in the request body (or x-session-id in the HTTP headers, up to 256 characters) activates OpenRouter's sticky routing for both model resolution and provider selection. The stickiness window lasts 60 minutes and resets its timer on every successful request.
  2. Restrict allowed_models to cache-compatible frontier coding models: Narrow the pool so that if a catastrophic loop does force a fallback switch, it lands on a model you trust rather than a random quantized host.
  3. Cap runaway prices with provider.max_price: Because cost_tier is only a soft band, set explicit input and output price ceilings inside the provider object.

Here is the complete production payload I use when wiring openrouter/auto-code into an automated coding agent loop:

json
{
  "model": "openrouter/auto-code",
  "session_id": "repo-refactor-pr-4092",
  "messages": [
    {
      "role": "system",
      "content": "You are an autonomous TypeScript refactoring agent. Run tests after each edit."
    },
    {
      "role": "user",
      "content": "Migrate the payment webhook handler in src/webhooks/stripe.ts to the new signature verifier."
    }
  ],
  "plugins": [
    {
      "id": "auto-router",
      "allowed_models": [
        "openai/gpt-6.1-sol",
        "anthropic/claude-opus-5.5",
        "anthropic/claude-sonnet-5.5"
      ]
    }
  ],
  "provider": {
    "require_parameters": true,
    "max_price": {
      "prompt": 15.0,
      "completion": 75.0
    }
  }
}

If your agent architecture genuinely needs a cheap model for file discovery and a heavy reasoning model for debugging, do not alternate models inside the same conversation array. Instead, keep your primary agent session locked to a single session_id and spawn an isolated subagent with a fresh session_id and a trimmed prompt for the heavy reasoning step. The subagent runs its task and returns a short summary back to the main agent, keeping the main agent's 100K-token prompt cache intact.

When you want to enforce phase-based routing, isolate team budgets, or manage provider fallbacks at the gateway layer without rewriting agent code, you can route your harnesses through SeedRouter. And if you are testing openrouter/auto-code inside local CLI tools like OpenAI Codex or Claude Code and need to swap Base URLs, switch model IDs, or diagnose HTTP 400 and 404 filter errors without hand-editing JSON dotfiles, use our free open-source LLM API Config GUI to configure and test your endpoints in one click.

Sources and checks

  1. openrouter/auto
  2. openrouter/auto-code
  3. official launch benchmarks