Optimize
Prompt caching
In short: Prompt caching lets the provider reuse a repeated prompt prefix, billed at the lower cached rate; this page covers Claude breakpoints and checking hits.
On this page
Prompt caching lets the provider reuse its work when many requests start with the same text (a long system prompt, a document, tool definitions, the earlier part of a chat). The reused part is billed at the model’s cached input rate, which is far below the normal input rate.
What are the cached rates?
The cached rate is the lower per-token price each model below charges for the reused part of a prompt.
No models in this list right now. See all models.
Models not in this table bill repeated input at their normal input rate.
How is caching billed?
Caching is billed as cache reads at the cached rate, plus cache writes on Claude only:
- Cache reads: the cached part of the prompt is billed at the cached rate above. The rest of the prompt is billed at the normal input rate, and output as usual.
- Cache writes (Claude only): writing a prefix to Claude’s cache is billed at 1.25 times the input rate for the default 5-minute cache, and 2 times the input rate for the 1-hour cache (
"ttl": "1h"). A write pays for itself after one or two reads. - Other providers do not charge extra for writes. Caching is automatic there, so you only see the discount.
- A cache entry expires after a few minutes without use (about 5 minutes for Claude’s default). Nothing is billed for keeping it.
Your usage page shows the cost of each request with the cached tokens already priced in.
How does automatic caching work on non-Claude models?
With automatic caching, the other providers in the table cache long prompt prefixes on their own, typically once a prompt passes about 1,024 tokens. You do not change anything in the request. To get more hits:
- Put what stays the same first (instructions, documents, tool definitions, examples) and what changes last (the user’s question).
- Keep that prefix byte-for-byte identical: no timestamps, request ids or shuffled examples at the top.
- Send related requests close together; caches expire after a few idle minutes.
- On OpenAI models,
prompt_cache_key(any stable string, for example a user or document id) helps route similar requests to the same cache.
Check usage.prompt_tokens_details.cached_tokens in the response to see how much was a hit:
"usage": {
"prompt_tokens": 5120,
"completion_tokens": 180,
"total_tokens": 5300,
"prompt_tokens_details": { "cached_tokens": 4864 }
}Claude: mark what to cache
You mark what to cache on Claude with cache_control. Claude caches only the prefixes you mark with cache_control, and the marker exists only in Anthropic’s format. Use the Anthropic Messages endpoint and put "cache_control": {"type": "ephemeral"} on the last block of the stable part (a system block, a tool, or a message). Everything up to and including that block is cached.
import anthropic, os
client = anthropic.Anthropic(base_url="https://api.oneaiapikey.com", api_key=os.environ["ONEAIAPIKEY_API_KEY"])
handbook = open("handbook.md").read() # a long document you ask many questions about
def ask(question: str):
return client.messages.create(
model="qwen-qwen3.8-27b:free",
max_tokens=1024,
system=[
{"type": "text", "text": "Answer questions about the company handbook."},
{"type": "text", "text": handbook, "cache_control": {"type": "ephemeral"}}, # cache up to here
],
messages=[{"role": "user", "content": question}],
)
first = ask("How many vacation days do new staff get?")
print(first.usage.cache_creation_input_tokens, "tokens written to the cache")
second = ask("What is the policy on remote work?")
print(second.usage.cache_read_input_tokens, "tokens read from the cache")- Claude only caches prefixes above a minimum length (around 1,024 tokens on most models; shorter prefixes are processed normally and not cached).
- You can set up to four breakpoints, for example one after the tools and one after the documents.
usage.cache_creation_input_tokensis what was written (billed at the write rate),usage.cache_read_input_tokenswhat was read (billed at the cached rate), andusage.input_tokensthe rest.
How do I test my cache hit rate?
To test your cache hit rate, run this script, which sends the same long prefix three times with a different question at the end and prints how much of each prompt was read from the cache. It uses gpt-6-luna:free, the lowest-priced non-Claude model in the table above, so a run costs less than a cent. Swap in the model you plan to use, except Claude: through /v1/chat/completions Claude gets no cache hits (see the warning below), so measure Claude on /v1/messages with the ratio in the list below.
import os, time
from openai import OpenAI
client = OpenAI(base_url="https://api.oneaiapikey.com/v1", api_key=os.environ["ONEAIAPIKEY_API_KEY"])
MODEL = "gpt-6-luna:free"
# A stable prefix of about 2,000 tokens (automatic caching starts around 1,024).
prefix = "You answer questions about a store's policies.\n" + "\n".join(
f"Policy {i}: reply in plain English and cite policy {i} by number." for i in range(1, 121)
)
total_prompt = total_cached = 0
for run in range(1, 4):
r = client.chat.completions.create(
model=MODEL,
max_tokens=16,
messages=[
{"role": "system", "content": prefix}, # identical every time
{"role": "user", "content": f"Question {run}: which policy covers refunds?"},
],
)
details = r.usage.prompt_tokens_details
cached = (details.cached_tokens if details else 0) or 0 # prompt_tokens already includes these
total_prompt += r.usage.prompt_tokens
total_cached += cached
print(f"run {run}: {cached} of {r.usage.prompt_tokens} prompt tokens cached ({cached / r.usage.prompt_tokens:.0%})")
time.sleep(2)
print(f"hit ratio over all runs: {total_cached / total_prompt:.0%}")- Run 1 is normally a miss (0%): it puts the prefix in the cache. Runs 2 and 3 should show most of the prompt as cached.
- The hit ratio is
cached_tokens / prompt_tokens. A ratio near 0 on every run means the prefix changes between requests, is too short, or the model does not cache. - Hits are not guaranteed: a request can land on a server that does not hold the cache yet. Run the script again before drawing conclusions.
- For Claude on
/v1/messages, the ratio iscache_read_input_tokens / (input_tokens + cache_creation_input_tokens + cache_read_input_tokens), sinceinput_tokensthere counts only the uncached rest. - To check one past request instead, look it up by its
X-Request-Id: the reply includes the cached tokens and the discount.
When does caching help?
Caching helps most when many requests share a long, identical prefix; the table shows typical workloads.
| Workload | Benefit |
|---|---|
| Coding agents and long chats (the history is resent every turn) | Large: most of every request is the same prefix. |
| Questions over one long document or codebase | Large, if the document comes first. |
| Many short, unrelated prompts | None: there is nothing to reuse. |
| Batch jobs with a shared instruction block | Moderate, if requests run close together. |
Related
- Cost control: other ways to spend less.
- Models: all rates.