页面简介
Cache prompt messages
正文摘录
To save on inference costs, you can enable prompt caching on supported providers and models. Most providers automatically enable prompt caching, but note that some (see Alibaba and Anthropic below) require you to enable it on a per-message basis. When using caching (whether automatically in supported models, or via the cache_control property), OpenRouter uses provider sticky routing to maximize cache hits — see Provider Sticky Routing below for details. Provider Sticky Routing To maximize cache hit rates, OpenRouter uses provider sticky routing to route your subsequent requests to the same provider endpoint after a cached request. This works automatically with both implicit caching (e.g. OpenAI, DeepSeek, Gemini 2.5) and explicit caching (e.g. Anthropic cache_control breakpoints). How it works: After a request that uses prompt caching, OpenRouter remembers which provider served your request. Subsequent requests for the same model are routed to the same provider, keeping your cache warm. Sticky routing only activates when the provider’s cache read pricing is cheaper than regular prompt pricing, ensuring you always benefit from cost savings. If the sticky provider becomes unavailable, OpenRouter automatically falls back to the next-best provider. Sticky routing is not used when you specify a manual provider order via provider.order — in that case, your explicit ordering takes priority. Sticky sessions expire after 60 minutes of inactivity. Each successful request resets the timer. If the sticky provider returns an error, the cache is not updated, allowing the next request to be re-routed. Sticky routing granularity: Sticky routing is tracked at the account level, per model, and per conversation. By default, OpenRouter identifies conversations by hashing the first system (or developer) message and the first non-system message in each request, so requests that share the same opening messages are routed to the same provider. This means different conversations naturally stick to different providers, improving load-balancing and throughput while keeping caches warm within each conversation. Using session_id for sticky sessions For more explicit control over sticky routing, you can pass a session_id in your request. When a session_id is present, OpenRouter uses it directly as the sticky routing key instead of deriving one from message hashing. This is especially useful for multi-turn agentic workflows where the opening messages may change between requests but you still want to route to the same provider. You can provide session_id in two ways: Request body: Include session_id as a top-level field in your request body. If both are provided, the body value takes precedence. Header: Set the x-session-id HTTP header. The session_id must be at most 256 characters. If neither is set, OpenRouter falls back to the OpenAI-style prompt_cache_key request field as the sticky routing key. Clients that already send prompt_cache_key get session-pinned routing without any changes. { "model": "anthropic/claude-sonnet-5.5", "session_id": "my-agent-session-abc123", "messages": [ { "role": "user", "content": "Continue our conversation..." } ] } When session_id is set, sticky routing activates on any successful request — even before cache usage is observed — so that subsequent requests in the same session benefit from prompt caching from the start. Without session_id, sticky routing only activates after a cache hit is detected. When using router models like Auto Router or Pareto Router, sticky routing also reuses the resolved model on a best-effort basis when it remains in the current candidate set, not just the provider. The cache hint is ignored when it falls out of that set, so the router may select a different model on a later turn. See Auto Router — Session Stickiness for details. Grouping requests across modalities Beyond sticky routing, OpenRouter uses session_id to group your requests in the Sessions view on the Logs page. One session_id links requests across conversation turns, retries, and different modalities. This lets you trace a full agent session in one place. This grouping works across the synchronous endpoints, not just chat completions: Chat and Responses: send session_id in the request body, or the x-session-id header. Image generation: send session_id in the request body (overrides x-session-id if both are set), or the x-session-id header. It uses the value only for grouping, so sticky routing does not apply. Embeddings, reranking, speech-to-text, text-to-speech, and video generation: send the x-session-id header. These endpoints do not accept a body session_id. They use the value only for grouping, so sticky routing does not apply to them. The 256-character limit applies to both inputs. Send a consistent x-session-id across a multimodal workflow to group all of those generations under one session. For example, an agent transcribes audio, calls a chat model, then generates an image. The Batch API does not yet group its generations by session_id. Inspecting cache usage To see how much caching saved on each generation, you can: Click the detail button on the Activity page Use the /api/v1/generation API, documented here Check the prompt_tokens_details object in the usage response included with every API response The cache_discount field in the response body will tell you how much the response saved on cache usage. Some providers, like Anthropic, will have a negative discount on cache writes, but a positive discount (which reduces total cost) on cache reads. Usage object fields The usage object in API responses includes detailed cache metrics in the prompt_tokens_details field: { "usage": { "prompt_tokens": 10339, "completion_tokens": 60, "total_tokens": 10399, "prompt_tokens_details": { "cached_tokens": 10318, "cache_write_tokens": 0 } } } The key fields are: cached_tokens: Number of tokens read from the cache (cache hit). When this is greater than zero, you’re benefiting from cached content. cache_write_tokens: Number of tokens written to the cache. This appears on the first request when establishing a new cache entry. Cancelled requests A cancelled stream usually does not get the cache discount. Most providers report cached tokens only at the end of the stream. OpenRouter stops the upstream stream as soon as the client cancels, so you are not billed for output you never receive, and the provider’s final usage never arrives. Without the provider’s cache counts, OpenRouter bills the prompt at the uncached input rate, since that is the best estimate available. OpenAI Caching price changes: Cache writes: no cost on models before the GPT-5.6 family. GPT-5.6 and later charge cache writes at 1.25x the price of the original input pricing, even with automatic caching — no opt-in required. Cache reads: (depending on the model) charged at 0.25x or 0.50x the price of the original input pricing Click here to view OpenAI’s cache pricing per model. Prompt caching with OpenAI is automated and does not require any additional configuration. There is a minimum prompt size of 1024 tokens. On GPT-5.6 and later you can turn caching off per request to avoid the cache-write charge on prompts you will not send again. Click here to read more about OpenAI prompt caching and its limitation. Explicit prompt caching Caching price changes: Cache writes (30-minute TTL, default): charged at 1.25x the price of the original input pricing (same rate as automatic cache writes on GPT-5.6 and later) Cache writes (12-hour TTL): charged at 2.5x the price of the original input pricing Cache reads: charged at the model’s discounted cache read rate, same as automatic caching, regardless of TTL Explicit prompt caching works on both the Chat Completions and Responses APIs, and gives you direct control over cache boundaries instead of relying on OpenAI’s automatic breakpoint placement. Cached prefixes have a minimum 30-minute TTL by default, or 12 hours with "ttl": "12h". See OpenAI’s explicit prompt caching docs for upstream details. OpenAI explicit prompt caching is only supported by OpenAI GPT-5.6 and newer. There are two controls: prompt_cache_breakpoint: placed on an individual text content block (input_text in Responses, text in Chat Completions) to mark the end of a reusable prefix. Everything through that block becomes the candidate cached prefix. Automatic caching remains enabled. prompt_cache_options: placed at the request root. Setting mode to "explicit" disables OpenAI-managed breakpoints so only blocks marked with prompt_cache_breakpoint participate in caching. Use ttl to set the minimum cache lifetime for every breakpoint the request writes: "30m" (default) or "12h". A prompt_cache_breakpoint can carry its own ttl to override the request-level value for that boundary, so a long-lived system prompt can be cached for 12 hours while the rest of the conversation keeps the 30-minute default. Responses API: { "model": "openai/...", "prompt_cache_key": "my-session-key", "prompt_cache_options": { "mode": "explicit", "ttl": "30m" }, "input": [ { "role": "user", "content": [ { "type": "input_text", "text": "<REUSABLE_PREFIX>", "prompt_cache_breakpoint": { "mode": "explicit" } }, { "type": "input_text", "text": "<TASK_SPECIFIC_SUFFIX>" } ] } ] } Chat Completions API: { "model": "openai/...", "prompt_cache_key": "my-session-key", "prompt_cache_options": { "mode": "explicit", "ttl": "30m" }, "messages": [ { "role": "user", "content": [ { "type": "text", "text": "<REUSABLE_PREFIX>", "prompt_cache_breakpoint": { "mode": "explicit" } }, { "type": "text", "text": "<TASK_SPECIFIC_SUFFIX>" } ] } ] } 12-hour TTL for a long-lived system prompt, with the rest of the conversation on the 30-minute default (Chat Completions shown; the Responses API takes the same fields on input_text blocks): { "model": "openai/...", "prompt_cache_options": { "mode": "explicit", "ttl": "30m" }, "messages": [ { "role": "system", "content": [ { "type": "text", "text": "<SHARED_INSTRUCTIONS_AND_