Prefixwise
Your agent resends its whole conversation every turn, and one changed byte near the top means the provider charges full price for everything after it. Prefixwise tells you which block changed, what it cost, and fixes the common causes for you.
Prompt caching: a provider keeps the start of a prompt it has just seen, and charges about a tenth of the input price to read it again, as long as that start is byte-for-byte the same. Prefixwise is for multi-turn agents on the Anthropic, OpenAI and Gemini APIs, vLLM and SGLang. A single-shot call has nothing to reuse and nothing for it to find.
Providers and engines report how many tokens missed the prompt cache, not why. Prefixwise sits between your agent and the model and does four things:
- Identify. One named cause for every request, with its evidence, its cost and its fix.
- Fix. --optimize repairs the request before it is sent. Only fixes that passed a replay against live models.
- Prevent. prefixwise check fails CI when a code change would break the cache.
- Auto-detect. It recognises vLLM and SGLang behind a URL and, when the engine publishes KV events, subscribes to them on its own.
It stores hashes and counts, never your prompts (one exception: an Anthropic message thread's conversation is held in the edge's memory for at most an hour after its last use, never written or sent anywhere; SECURITY.md). No dependencies, Python 3.10 or newer, MIT. Alpha: the verdicts are tested (see Results); the command line may still change between minor versions.
Try it
pip install prefixwise
prefixwise demo
prefixwise demo needs no key and no network. A scripted agent breaks the cache three ways against a built-in mock provider, each miss is named and priced, and the same agent runs again with the fixes on. About five seconds. Then, on your own traffic, start from what you have:
| You have | Run |
|---|---|
| Claude Code or Codex already used on this machine | prefixwise import claude-code (or import codex ): reads the logs on disk, no key, nothing leaves the machine |
| An agent and an API key | prefixwise run -- claude (or codex , opencode , your own command), then prefixwise report --session latest for the session turn by turn |
| The same, and you want the fixes applied | prefixwise run --optimize -- claude |
An agent finds the proxy through ANTHROPIC_BASE_URL or OPENAI_BASE_URL, which prefixwise run sets for it; prefixwise serve prints the two values to set by hand. An agent signed in with a subscription cannot be routed through a proxy: use import.
What you see
A real run against the Anthropic API (Claude Sonnet 4.6): an eight-turn agent whose tool list comes back in another order on turn 4 and returns on turn 6 (the run, with the agent).
$ prefixwise run --ledger before.db -- python agent.py
8 requests, 26,932 prompt tokens, 75% served from cache. Cost $0.0356.
Avoidable: 3,375 tokens ($0.0116), 12.5% of prompt tokens. Fix these, biggest first:
1. The same tools were sent in a different order or format (2 requests, 3,375 tokens, $0.0116).
Fix: Send tools in a fixed order with deterministic serialization (or let the proxy do it: prefixwise serve --fix canonical_tools).
Prefixwise can do it for you: prefixwise run --fix canonical_tools (proven)
Expected misses (not waste): 1 x first request of a session or a new conversation: nothing of its own to reuse yet.
(The output is cut to the lines about the miss, and was recorded on 0.11; the record has all of it, and today's report adds where the bill went and what fixing the misses would bring.) prefixwise report --ledger before.db --session latest shows where it happened:
Session run-20261110-010636: 8 requests, 26,932 prompt tokens, cache hit rate 74.6%, 3,375 avoidable, cost $0.0356 (claude-sonnet-4-6)
turn prompt cached hit cause first changed cost avoidable avoidable $
---- ------ ------ ----- ---------------- ------------- ------- --------- -----------
1 3,286 0 0.0% first_write - $0.0125 0 $0.0000
2 3,309 3,283 99.2% none messages[8] $0.0017 0 $0.0000
3 3,332 3,306 99.2% none messages[10] $0.0016 0 $0.0000
4 3,355 0 0.0% tool_reserialize tools[0] $0.0132 3,329 $0.0115
5 3,378 3,352 99.2% none messages[14] $0.0019 0 $0.0000
6 3,401 3,329 97.9% tool_reserialize tools[0] $0.0016 46 $0.0002
7 3,424 3,398 99.2% none messages[18] $0.0020 0 $0.0000
8 3,447 3,421 99.2% none messages[20] $0.0013 0 $0.0000
"first changed" is the block where the prompt stopped matching the previous request, counted over the whole prompt: tools, then system, then messages. Turn 4 paid for the whole prompt again. Turn 6 went back to the first order and read 3,329 tokens, the prefix turn 3 had written under that order: the older entry was still cached.
With --optimize, same agent and same prompts:
| before | with --optimize | |
|---|---|---|
| Served from cache | 74.6% | 87.1% |
| Cost of the run | $0.0356 | $0.0250 |
| Avoidable tokens | 3,375 | 0 |
Results
Every number is from a live run against real models, and each links to its record. The full table is in the guide.
| Claim | Result |
|---|---|
| Agrees with Anthropic's own miss reason | 32 of 32 misses Anthropic named ( 1 , 2 ) |
| Names injected changes at scale, on real agent trajectories | 1,772 of 1,772 seen, 0 named as another cause, 0 false alarms on 3,622 turns that only appended, on vLLM and SGLang with real Claude Code trajectories and generated conversations ( records ) |
| Names injected causes on open models | 120 of 120 on vLLM, vLLM + LMCache and SGLang ( vLLM , LMCache and SGLang ) |
| Tells an engine eviction from everything else | 5 of 5 , confirmed from KV events ( vLLM , SGLang ); a prefix LMCache or HiCache restored counted as a hit 5 of 5 , through the proxy and inside vLLM ( record , inside vLLM ) |
| The tool-order fix saves what was predicted | 99.9% on Claude, 97.5% on vLLM, task success flat (one of 60 turns changed on Qwen3-4B) ( record ) |
| The cache-marker fix pays for itself | 106.8% of predicted savings, prompt cost down 85.6% with the write surcharge included, task success flat ( record ) |
| Agrees with labels computed from text, on a public trace of real agents | 252,549 of 252,549 turns that only appended read as unchanged, 9,840 of 9,844 that changed read as changed, 3,981 of 3,981 model or provider switches matched: two weeks of the FreeInference agentic trace (269,348 requests, hashes only), against the authors' own labels ( record ) |
| Works through LiteLLM, Claude Code's /v1/messages route included | 20 of 20 live conversations right on the Anthropic API (16 with an injected change, each named; 4 with none, no false cause), through LiteLLM's SDK and its proxy server; real Claude Code through the proxy server recorded on every call (7 of 7); 0 false alarms in 71,346 calls of real agent conversations replayed through LiteLLM (600 of them live on the Anthropic and OpenAI APIs), from GitHub and eight Hugging Face datasets, every injected change named or shown at no cost where anything was cacheable ( Hugging Face , more datasets and Claude Code , live , all LiteLLM tests ) |
| Works with real agents | Claude Code, Codex, opencode, the Anthropic and OpenAI SDKs ( record , opencode ) |
| Costs almost nothing | 2 to 4 ms per request at 2k tokens, 12 to 23 ms at 120k (streamed to unstreamed), about 100 requests/s per process on 4 CPUs; 33,358 requests in a soak, 0 errors ( record ) |
Ways in
All write the same kind of ledger and print the same report. An import keeps its own ledger file (prefixwise-claude-code.db, prefixwise-codex.db, prefixwise-gateway.db), so read it with prefixwise report --ledger <that file>.
| You have | Do this |
|---|---|
| An agent you run from a terminal | prefixwise run -- <your command> |
| A service, several agents, or a gateway | prefixwise serve --upstream https://api.anthropic.com , and point clients at it |
| Your own vLLM server | vllm serve <model> ... --middleware prefixwise.PrefixwiseMiddleware : no proxy, no port change ( docs/VLLM.md ) |
| vLLM with LMCache | the same --middleware flag, or prefixwise serve --upstream <url> in front, which detects the engine ( docs/LMCACHE.md ) |
| SGLang, with or without HiCache | prefixwise serve --upstream <url> in front; it detects the engine ( docs/SGLANG.md ) |
| Your own Python code | client = prefixwise.wrap(Anthropic()) (or OpenAI, Google Cloud's AnthropicVertex , Azure's AzureOpenAI and AnthropicFoundry , or a Bedrock runtime client) |
| Azure OpenAI, or Claude in Microsoft Foundry | prefixwise serve --upstream https://<resource>.openai.azure.com (Claude in Foundry: https://<resource>.services.ai.azure.com ), with each deployment's zone in PREFIXWISE_AZURE_DEPLOYMENTS ( docs/GUIDE.md ); not yet run against a live Azure resource |
| Gemini, on the Gemini API or Vertex AI | prefixwise serve --upstream https://generativelanguage.googleapis.com (Vertex AI: https://<location>-aiplatform.googleapis.com ), and point the client's base URL at it; your own Google key or token is passed, never PREFIXWISE_API_KEY ( docs/GUIDE.md ); not yet run against Google's live API, and its cache rules are provisional |
| LiteLLM (also Claude Code through a LiteLLM proxy, and Gemini models through LiteLLM) | litellm.callbacks = [PrefixwiseCallback()] , or callbacks: prefixwise.litellm_callback.prefixwise_callback in the proxy server's config |
| Claude Code or Codex on a subscription | prefixwise import claude-code / prefixwise import codex |
| A gateway's request log (JSON Lines) | prefixwise import gateway --path requests.jsonl : yesterday's traffic, the live proxy's verdicts, nothing changed in production |
Identify
Nineteen causes, each marked as waste or as a legitimate miss. The ones people meet most:
| Cause | What happened | Fix |
|---|---|---|
| tool_reserialize | The same tools, in another order or with other bytes | --optimize does it, or sort them yourself |
| volatile_system | A timestamp or id in the system prompt changed | Move it to the latest user message |
| history_edit | Earlier messages were rewritten | Append, do not rewrite; compact at task boundaries |
| breakpoint_misplaced | Anthropic: no cache_control , or one that stays too early | --optimize places them, or add one on the last message |
| ttl_expired | The gap since the last turn outlived the cache | A longer TTL, if the reads pay for it |
| evicted | A self-hosted engine dropped the session's blocks | More KV memory, or an offload tier |
Beyond the report: prefixwise explain --diff a.json b.json shows what changed between two requests, prefixwise fixes ranks fixes by the tokens they would save, and every non-streaming response carries an X-Prefixwise-Cause header (for a stream, look the request up by its id). All causes and details: guide.
Fix
--optimize (on serve and run, or PREFIXWISE_OPTIMIZE=1 for the vLLM middleware) applies every fix that has passed a replay against a live model. A fix earns its place by realising at least half of what Prefixwise predicted with task success flat.
- canonical_tools sorts the tool list and each tool's keys, so a list that drifts between turns stops breaking the cache.
- auto_breakpoints (Anthropic's API only) adds cache_control markers to a request that has none, once the same prefix was seen within the cache window. A one-shot request never pays for a write nobody reads, and a client's own markers are never touched.
- cache_key (OpenAI's own models; recommended, not yet proven, so --optimize leaves it off) sends a prompt_cache_key per session, a hash of its session id. Measured live: without the key, OpenAI's Responses API read under half of the cached prefix (or reported no usage) on 93 of 132 turns replaying four real Claude Code conversations through LiteLLM (5 of 116 on Chat Completions), and in a probe of one conversation alone it read nothing on most turns; with the key, the prefix was read on 3 of 3. OpenAI documents that it routes requests to a cache machine by the start of the prompt, combined with this key, which is the likely reason. A key the client set is never touched.
Off by default. If the upstream rejects a request carrying markers Prefixwise placed, the client's original is sent instead; canonical_tools changes only the order of tools and keys. prefixwise fixes says whether a fix paid off on your traffic. Fixes that would change what the model reads, such as moving a timestamp, stay advice.
Prevent
prefixwise check -- pytest tests/agent_scenarios # exit 2 on a cache regression
The command is whatever runs your agent; it gets the mock's address in ANTHROPIC_BASE_URL and OPENAI_BASE_URL. A run in which no request got a verdict exits 1 ("nothing checked"), not 0; --allow-empty (or the Action's allow-empty: true) is for a job that may run no scenario.
The costly regressions pass every functional test: a tool list built from a set, a timestamp added to the system prompt, a marker moved. prefixwise check runs your agent's scenarios against a local mock provider, with no API calls, and fails on four: tools in a changed order, a volatile system prompt, a misplaced marker, a mutated tool result. As a GitHub Action:
- uses: tejachavali/[email protected]
with:
command: pytest tests/agent_scenarios
Details, allow-lists and baselines: guide.
Self-hosted engines
On vLLM and SGLang, with pip install "prefixwise[engines]" and the engine publishing its KV-cache events, Prefixwise reads them, so an eviction is confirmed and not inferred, and a prefix that LMCache or HiCache restored from CPU memory is labelled host_restored: a hit the GPU alone would have missed. It also names what a chat template costs, such as a reasoning model recomputing its previous answer every turn. Step by step: vLLM, LMCache, SGLang, how the engine join works.
In production
Prometheus metrics with an alert rule and a Grafana dashboard (docs), OpenTelemetry spans (docs), an HTTP API (docs), a collector for several proxies, and sinks to JSONL or ClickHouse (architecture). Measured overhead is 3 ms per request at 2k tokens.
Limits
- One traffic shape per proof. canonical_tools was proven on Claude Haiku 5.5 and Qwen3-4B, auto_breakpoints on Haiku 5.5 only; both on scripted multi-turn sessions seconds apart, not an agent's own traffic.
- OpenAI's own verdict is unchecked. Its diagnostics answered unavailable on every call we made. Prefixwise still classifies OpenAI traffic.
- A change is located per block, not per token. An edit at the end of a long system prompt is reported for the whole block.
- Long sessions and many agents at once are less tested than short ones.
- Dollars need a price. Models in the dated table are priced; others show a dash until you add rates.
- Ollama and llama.cpp report no cached tokens (most builds): Prefixwise names every change to the prompt, but cannot tell a hit from a miss there, and says so.
- API keys only. An agent signed in with a subscription cannot be routed through a proxy; use prefixwise import for those.
The full list, with what was and was not verified live: guide.
More
- The full guide: every way in, every cause, the command and environment reference, production notes.
- How it decides: the decision procedure, the evidence behind each cause, and the invariants the tests check.
- Use cases, data and metrics, architecture, changelog, security.
- Working on Prefixwise: pip install -e ".[dev]" && python -m pytest tests -q. Read docs/WORKLOG.md first.
MIT. See LICENSE.