CtxCache
CtxCache wraps the LLM client you already have, in process. It records how much of each prompt was served from cache, names the break when a prefix changes, and can put a stable layout back. It is not a proxy. Every number on this page is in docs/CLAIMS.md. What is not proven is in docs/LIMITS.md.
pip install ctxcache
ctxcache demo
The demo needs no API key and no network. The prices it prints are SIM, from the simulator, not a provider bill.
From a clone, the test command is:
pip install -e ".[dev]"
pytest -q -m "not contract"
Measured without the wrapper
These calls did not go through ctxcache.wrap, or the provider cache was set by something else.
One Kimi K3 session paid $0.95546138 against $2.22368850 uncached. Receipt: bench/live/2026-11-12-broad.json. The tool session is bench/live/2026-11-12-tools.json.
The same short prompt, sent twice: Nova Micro, Nova Lite, Nova Pro, and Kimi K3 returned a cache read on the second call. gpt-oss returned no cache field, and both of those calls cost $0.00014265. A clock on the first line of the Nova Micro prompt dropped the read to 0. Receipt: bench/live/2026-11-30-model-proof.json. This run cost $0.00525445.
A new clock left in the system prompt, then the same clock after optimize moved it. Claude Code had already turned caching on. The library's share of this table is the move.
| Model | Clock left in place | Clock moved | Less |
|---|---|---|---|
| Haiku 5.5 | $0.00124700 | $0.00035128 | $0.00089572 |
| Sonnet 5.5 | $0.0152880 | $0.0062605 | $0.0090275 |
| Opus 5.5 | $0.0305200 | $0.0124810 | $0.0180390 |
| Fable 5.2 | $0.0609920 | $0.0244330 | $0.0365590 |
Receipts: bench/live/2026-11-30-haiku-claude-code.json, bench/live/2026-12-01-claude-models.json. The twelve Sonnet, Opus, and Fable calls cost $0.2850687 together.
On Codex, gpt-6-luna, gpt-5.6-terra, and gpt-5.6-luna kept the same cached-token count when a clock was added to the user text. Receipt: bench/live/2026-12-01-codex-models.json.
A later Sonnet pair put cache_control on the dict. claude -p takes a plain string, so the marker never left. The API recorded 0 tokens on the 5-minute tier and read 2,806 tokens from the CLI's own 1-hour cache on both calls. The pair cost $0.0084532. Receipt: bench/live/2026-12-01-sonnet-marker.json.
SIM
The frozen simulator report is a 42.0% input-cost reduction across 4 frameworks × 2 providers on 20 tasks. Source: docs/REPORT.md. Held-out read-share error in that report is 0.00 points MAE. That fit is not a forecast of a provider bill.
tests/test_perf.py checks that safe-mode work at about 50,000 tokens stays under 2 ms p50 and 5 ms p99. A status note recorded 0.66 ms p50 and 1.08 ms p99 on one machine with GC off. See docs/CLAIMS.md.
There are 15 break causes in src/ctxcache/data/breaks.yaml. Cold starts, minimum length, and TTL expiry are not labeled as your bug.
Also
A CI job can run ctxcache check with no API key. The workflow file is examples/github-action/workflow.yml.
The same offline prices, four named cases:
ctxcache scenarios
ctxcache scenarios --html ctxcache-scenarios.html
On Amazon Bedrock the Chat Completions URL that answers is https://bedrock-runtime.us-east-1.amazonaws.com/openai/v1/chat/completions, and the gpt-oss-120b id is openai.gpt-oss-120b-1:0. On 2 Nov 2026 two identical 1,699-token prompts came back with no cached-token field. Optimize mode still moves a clock out of the system message. It does not invent a cache discount the provider did not report.
Nova Micro on the Converse API did return a cache read. Through ctxcache.wrap in observe mode, the second identical call reported 3,601 cached input tokens and 6 uncached tokens. The priced Nova calls are the 2026-11-30 receipt above.
Optional provider and integration extras:
pip install "ctxcache[anthropic,openai,gemini,langchain,pydantic-ai,openai-agents,otel]"
Operating Modes
CtxCache operates in three explicit modes configured via ctxcache.wrap(client, mode=...):
1. observe Mode (Byte-Identical Passthrough)
Passes all requests to the underlying provider byte-for-byte with zero modifications (claim C-03). Records request fingerprints, traces, and exact token economics (read, write, uncached) to a local SQLite ledger (~/.ctxcache/ledger.sqlite) and optional JSONL traces.
import ctxcache
from anthropic import Anthropic
client = ctxcache.wrap(Anthropic(), mode="observe")
# Byte-identical request execution with transparent telemetry
response = client.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=1024,
messages=[{"role": "user", "content": "Analyze system logs."}],
)
2. safe Mode (Content-Equivalent Stabilization)
Adds, removes, or modifies no prompt or tool text (claim C-04). Restores the first-seen tool order. On OpenAI it sets prompt_cache_key only when you pass session_id. Callers who omit it do not share one key. On Anthropic it writes one cache_control marker on the system block. The system words stay the same. Observe writes neither.
client = ctxcache.wrap(Anthropic(), mode="safe")
3. optimize Mode (Active Context Engineering)
Performs structured context layout optimizations:
- Volatile Relocation: Moves timestamps and runtime identifiers from the system prefix to the user turn. This is a layout change. It is not the 42.0% SIM figure and not the Kimi receipt.
- Large Output Offloading: Stores tool outputs exceeding 2,000 tokens in a local blob store and passes a deterministic handle stub, keeping the prefix stable when frameworks resend full tool outputs.
- Planned History Compaction: Compares the one-time summary rewrite penalty against expected remaining turns ($k^* \approx 8.0$ calls) to compact history only when it yields net cost savings (claim C-09).
client = ctxcache.wrap(Anthropic(), mode="optimize")
Framework Integrations
CtxCache integrates into modern agent frameworks with minimal setup (claim C-10):
LangGraph / LangChain
from ctxcache.integrations.langgraph import CtxCacheMiddleware
# Intercept and stabilize state inside your graph node
middleware = CtxCacheMiddleware(mode="safe")
processed_state = middleware(state)
Pydantic AI
from anthropic import Anthropic
from pydantic_ai.models.anthropic import AnthropicModel
from ctxcache.integrations.pydantic_ai import wrap_pydantic_ai_client
# Wrap client before passing to Pydantic AI model
wrapped_client = wrap_pydantic_ai_client(Anthropic(), mode="optimize")
model = AnthropicModel("claude-3-5-sonnet-20241022", anthropic_client=wrapped_client)
OpenAI Agents SDK
from openai import OpenAI
from ctxcache.integrations.openai_agents import set_default_openai_client
# Set wrapped client as default for all Agents SDK workflows
set_default_openai_client(OpenAI())
CLI & Tooling
ctxcache report
Inspect aggregated cache performance, read share, and exact input dollar savings for a session from the SQLite ledger:
ctxcache report --session "session-prod-worker-1"
ctxcache diagnose
Analyze root causes of cache breaks in a JSONL trace file:
ctxcache diagnose ./traces/session.jsonl
ctxcache replay
Replay recorded JSONL traces through the deterministic cache simulator under observe, safe, and optimize policies:
ctxcache replay ./traces/session.jsonl
ctxcache guard
Protect against prompt cache regressions in CI test suites. Fails if a code commit introduces user-caused prefix breaks:
ctxcache guard --baseline ./traces/baseline.jsonl --run "pytest tests/agent/"
ctxcache bench --report
Reproduce the frozen Cache Efficiency Report v1 across all 20 pre-registered tasks:
ctxcache bench --report
Core Invariants
CtxCache strictly enforces 13 formal invariants verified on every commit:
INV-01(Byte-Identical Passthrough):observemode sends byte-identical requests.INV-02(Content Equivalence):safemode modifies no message or tool text.INV-03(Deterministic Fingerprints): Message SHA-256 fingerprints are deterministic across processes and Python versions.INV-04(Append-Only History): No already-sent message is mutated except via explicit compaction events.INV-05(Action Reporting): Every layout relocation and ordering restoration is recorded and reported.INV-06(Exact Token Accounting):read + write + uncached == total_inputstrictly reconciles for Anthropic, OpenAI, and Gemini.INV-07(Fail-Open): Any internal error passes original requests through unmodified and recordsctxcache_error.INV-08(Zero Network Exfiltration): No outbound network calls except to wrapped LLM providers and optional OTLP endpoints.INV-09(Privacy by Default): Prompt content is never stored in ledgers, spans, or logs (record=Truerequired for debug traces).INV-10(Honest Attribution): TTL expiry, provider cold-starts, and below-minimum length are never attributed as user breaks.INV-11(Planner Limits): Hard limit of 4 breakpoints per request; 1-hour entries precede 5-minute entries.INV-12(Memory Integrity): Facts are superseded temporally (valid_to,superseded_by), never overwritten; mid-session writes never mutate the active session prefix cache.INV-13(Exact Financial Arithmetic): All monetary costs and ratios use PythonDecimal, never float.
License
Apache-2.0. See LICENSE for details.
Metadata
Release files for ctxcache 0.4.3
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| ctxcache-0.4.3.tar.gz | 2.0 MB | With provenance | Details for ctxcache-0.4.3.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| ctxcache-0.4.3-py3-none-any.whl | Python 3 | none | any | Details for ctxcache-0.4.3-py3-none-any.whl |
Total release size: 2.1 MB
Release files / ctxcache-0.4.3.tar.gz
| Download URL | ctxcache-0.4.3.tar.gz |
|---|---|
| Size | 2.0 MB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
c5fa926cd41a544f79d2b96b728e7ca9c70665b3fa0a70ac2e86d6b309409ac1
|
|
BLAKE2b-256 checksum How to use checksums |
e38c228db89acbf69a6c6bb3d6a1e210bb56f9e562604adf5158888785617da7
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.
Transparency logRelease files / ctxcache-0.4.3-py3-none-any.whl
| Download URL | ctxcache-0.4.3-py3-none-any.whl |
|---|---|
| Size | 77.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
f53a234aeb4c327a6de19f6be36934c0f34c25234cbbc61db89e1d8fe13beb05
|
|
BLAKE2b-256 checksum How to use checksums |
9e1f1da2ed2f686228d69cac2abdf7bd640a25d4b26c318cd923fe50f8c6fc62
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.
Transparency logSecurity for ctxcache 0.4.3
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for ctxcache-0.4.3.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.