Metadata-Version: 2.5
Name: prefixguard
Version: 0.3.0
Summary: Catch prompt-cache misses before you pay for them, and stop them. Works with Claude, GPT, and Gemini.
Project-URL: Homepage, https://github.com/pgstorm148/prefixguard
Project-URL: Issues, https://github.com/pgstorm148/prefixguard/issues
Author: Prakhar Gandhi
License-Expression: MIT
License-File: LICENSE
Keywords: agents,anthropic,cache-hit-rate,context-engineering,deepseek,gemini,kimi,kv-cache,llm,observability,openai,prompt,prompt-caching,prompting,vllm
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: Pytest
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.9
Provides-Extra: dev
Requires-Dist: anthropic>=0.50; extra == 'dev'
Requires-Dist: google-genai>=1.0; extra == 'dev'
Requires-Dist: langchain-anthropic>=0.3; extra == 'dev'
Requires-Dist: openai>=1.60; extra == 'dev'
Requires-Dist: pytest>=7; extra == 'dev'
Provides-Extra: tokens
Requires-Dist: tiktoken>=0.5; extra == 'tokens'
Description-Content-Type: text/markdown

# prefixguard

[![Tests](https://github.com/pgstorm148/prefixguard/actions/workflows/tests.yml/badge.svg)](https://github.com/pgstorm148/prefixguard/actions/workflows/tests.yml)
[![PyPI](https://img.shields.io/pypi/v/prefixguard)](https://pypi.org/project/prefixguard/)
[![License: MIT](https://img.shields.io/pypi/l/prefixguard)](https://github.com/pgstorm148/prefixguard/blob/main/LICENSE)

**Find out what your prompt cache is costing you, then stop paying it.**

Prompt caching matches on exact bytes. Reorder a tool, add a date to the system prompt, or
trim old messages, and everything after that point is written again instead of read. You get
no error, only a larger bill. On current models the gap is wide:

| Model | Read a cached token | Write it again | A miss costs |
|---|---|---|---|
| Claude Fable 5.1 | $0.25 / MTok | $12.50 / MTok | **50x** |
| Claude Opus 5.5 | $0.20 / MTok | $5.00 / MTok | **25x** |
| Claude Sonnet 5.5 | $0.10 / MTok | $2.50 / MTok | **25x** |
| GPT-6.1 Sol | $0.10 / MTok | $2.50 / MTok | **25x** |

## Try it in 30 seconds

```bash
pip install prefixguard
prefixguard demo
```

No API key is needed. To watch your own agent without changing its code:

```bash
prefixguard run my_agent.py
```

```text
CACHE PREFIX BROKEN — session 'auto-1', turn 2
  divergence at system (~token 0)
  reusable   ~0 tokens  (0%)
  re-prefill ~13 tokens

  SYSTEM_MUTATED @ system
    System prompt bytes changed between turns, so everything after it is rewritten.
    First differing character is 0: 'a' became 'b'.
    fix: Keep the system prompt byte-identical for the session. ...

prefixguard: 2 requests, 1 prefix break(s), 0 expiry(ies)
  provider usage: 0 read, 80,000 written, 10 uncached (hit ratio 0%)
  input cost: $0.4000
  avoidable: $0.1920 (measured; prices as of 2026-11-03)
    SYSTEM_MUTATED: $0.1920
```

## Use it the way that fits

| You want to | Use | Code changes |
|---|---|---|
| Check a Python agent once | `prefixguard run my_agent.py` | None |
| Watch a service all the time | `prefixguard.instrument()` | One line |
| Watch any language, or a coding agent | `prefixguard proxy` | None; set a base URL |
| Stop regressions in CI, spending nothing | `@pytest.mark.cache_stable` | One marker |
| Find problems without running anything | `prefixguard scan src/` | None |
| Price a log you already have | `prefixguard audit trace.jsonl` | None |

[INTEGRATIONS.md](INTEGRATIONS.md) walks through each one, with notes for each provider.

```python
import prefixguard

prefixguard.instrument()  # every Anthropic and OpenAI SDK call in this process, from here on
```

That one line covers `create`, `parse`, `stream`, sync, async, and tool runners, plus
frameworks that call the official SDKs. It is tested with LangChain's `ChatAnthropic`, including
streaming.

## Stop the misses

Finding a problem saves nothing until it is fixed, so prefixguard includes the fixes.

```python
from prefixguard import StableWindow, stable_tools

tools = stable_tools(registry.values())     # equal tools always produce equal bytes

window = StableWindow(max_tokens=40_000)    # trims in large steps instead of every turn
response = client.messages.create(messages=window.apply(full_history), tools=tools, ...)
```

A window that slides every turn changes the start of the conversation every turn, so history
is never read from cache. `prefixguard demo` compares the two on one simulated 300-turn
conversation at Opus 5.5 prices:

| Strategy | Cost | Read from cache | History sent, on average |
|---|---|---|---|
| Sliding window | $44.81 | 20% | 34,639 tokens |
| `StableWindow` | $3.38 | 97% | 28,697 tokens |

This models the matching rule with no evictions; it is not a bill. The trade-off is in the last
column: each trim drops more history at once, so the model sees less on average.

`instrument(autofix=True)` sorts tools for you, and `instrument(auto_cache=True)` turns on
automatic caching for Claude requests that have no breakpoint. Both are off by default, because
both change what you send. Automatic caching also adds a write premium on prompts that are
never reused.

## Fail the build instead of the budget

```python
@pytest.mark.cache_stable
def test_agent_loop(client_with_mocked_http):
    run_agent(client_with_mocked_http, ["first question", "second question"])
```

Installing prefixguard registers the marker. The check runs before the HTTP request, so a test
fails with the exact cause and makes no billed call.

## Don't providers report this now?

Partly. Anthropic and OpenAI both added cache diagnostics, and you should use them; prefixguard
reads their results when they are present. They answer a different question:

| | Provider diagnostics | prefixguard |
|---|---|---|
| When you find out | After the request was sent and billed | Before it is sent, or in CI |
| How specific | Which section changed | Which block and character, and its likely cause |
| Key order versus a real edit | Same answer | Reported separately |
| Where it works | Anthropic: Claude API only. OpenAI: Responses API, GPT-5.6+ | Any client, any model |
| Dollar impact | Token estimate | Priced by model, measured from usage when available |
| Fixes | Advice | `StableWindow`, `stable_tools`, `autofix` |

## What it detects

| Cause | What happened |
|---|---|
| `SYSTEM_MUTATED` | The system prompt changed |
| `TOOL_REORDER` | The same tools arrived in a different order |
| `TOOL_SET_CHANGED` | A tool was added or removed |
| `TOOL_SCHEMA_DRIFT` | A tool kept its name but changed content |
| `NON_DETERMINISTIC_SERIALIZATION` | Same content in different bytes, such as key order |
| `HISTORY_REWRITE` | An earlier message was edited |
| `HISTORY_DROP` | Earlier messages were removed |
| `COMPACTION` | History was replaced by a summary (expected, but paid for) |
| `THINKING_DROPPED` | Thinking blocks were not sent back |
| `MODEL_CHANGED` | A router or fallback switched models |
| `PARAM_CHANGED` | `tool_choice`, effort, thinking, and similar settings changed |
| `CACHE_EXPIRED` | The gap between requests outlasted the cache lifetime |
| `NO_CACHE_BREAKPOINT` | Claude was never asked to cache anything |
| `HISTORY_NOT_CACHED` | Breakpoints stop before the conversation |
| `BELOW_MINIMUM` | The prefix is under the model's minimum, so it silently isn't cached |
| `LOOKBACK_EXCEEDED` | One turn added more than the 20 positions a breakpoint can search |
| `TOO_MANY_BREAKPOINTS` | More than Anthropic's limit of 4 |
| `PARALLEL_COLD_START` | Fan-out requests all paid to write the same prefix |
| `FORK_DRIFT` | A sub-agent or new session almost shares a prefix, but not quite |
| `VOLATILE_CONTENT` | A timestamp, UUID, or session id sits in tools or system |
| `UNEXPLAINED_MISS` | The bytes matched but the provider still missed |

## How far to trust the numbers

- **"Measured" means priced from the provider's `usage` fields.** "Estimated" means priced from
  a character-count token estimate. Every figure says which it is.
- **Prices come from provider pricing pages** and go stale. Reports show their date, and
  `prefixguard.register_pricing` overrides any model. An unknown model gets no dollar figure at
  all rather than a guess.
- **Only Anthropic documents its prefix order** (tools, system, messages). The same order is
  assumed elsewhere, so a tool change may be reported as losing more than it did.
- **Matching bytes do not guarantee a hit.** Providers can evict entries at any time, which is
  why usage is compared with the prediction.

## Design notes

- **No required dependencies.** Python 3.9+, standard library only.
- **The guard never calls a provider.** The proxy and your SDK forward your own requests.
- **Requests are unchanged by default.** Only `autofix` and `auto_cache` alter them.
- **A guard failure cannot break your call.** Internal errors are logged once and your request
  continues. Only `strict=True` raises, and it does so on purpose.
- **Prompts stay on your machine.** `PrefixGuard(redact=True)` also keeps them out of reports.
- **Overhead is about 3 ms per call at 16k tokens and 73 ms at 800k**, measured on one laptop.

## License

MIT
