Metadata-Version: 2.5
Name: ctxcache
Version: 0.4.1
Summary: Embeddable context engine that keeps an AI agent's prompt cache warm and proves it with measurements.
Author-email: Abhranshu <abhranshu@atnms.ai>
License-Expression: Apache-2.0
License-File: LICENSE
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Requires-Python: >=3.10
Requires-Dist: tomli>=1.1.0; python_version < '3.11'
Provides-Extra: anthropic
Requires-Dist: anthropic>=0.30.0; extra == 'anthropic'
Provides-Extra: dev
Requires-Dist: hypothesis>=6.100.0; extra == 'dev'
Requires-Dist: mypy>=1.10.0; extra == 'dev'
Requires-Dist: pytest>=8.0.0; extra == 'dev'
Requires-Dist: ruff>=0.5.0; extra == 'dev'
Provides-Extra: gemini
Requires-Dist: google-genai>=0.1.0; extra == 'gemini'
Provides-Extra: openai
Requires-Dist: openai>=1.0.0; extra == 'openai'
Provides-Extra: otel
Requires-Dist: opentelemetry-api>=1.20.0; extra == 'otel'
Requires-Dist: opentelemetry-sdk>=1.20.0; extra == 'otel'
Description-Content-Type: text/markdown

# CtxCache

```
  ____ _______  ______    _    ____ _   _ _____ 
 / ___|_   _\ \/ / ___|  / \  / ___| | | | ____|
| |     | |  \  / |     / _ \| |   | |_| |  _|  
| |___  | |  /  \ |___ / ___ \ |___|  _  | |___ 
 \____| |_| /_/\_\____/_/   \_\____|_| |_|_____|
```

[![CI](https://github.com/jishmisc28/ctxcache/actions/workflows/ci.yml/badge.svg)](https://github.com/jishmisc28/ctxcache/actions)
[![PyPI version](https://img.shields.io/pypi/v/ctxcache.svg)](https://pypi.org/project/ctxcache/)
[![License](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](LICENSE)
[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)

**CtxCache** is an open source Python library that keeps an AI agent's prompt cache warm — in-process, not a gateway — and proves the bill with measurements. Every number on this page is tagged in [`docs/CLAIMS.md`](docs/CLAIMS.md). What is not proven is in [`docs/LIMITS.md`](docs/LIMITS.md).

## Proof video

LIVE, one Kimi K3 session: the standing document, no-cache vs cached cost, the break when the document changes, and the receipt — **paid $0.95546138** against **$2.22368850** uncached (**saved $1.26822712**). Source: [`bench/live/2026-11-12-broad.json`](bench/live/2026-11-12-broad.json).

[`bench/live/2026-11-12-tools.json`](bench/live/2026-11-12-tools.json) is the tool session: one tool description changed, and the cache-read count on that turn stayed high.

LIVE, 2026-11-30, the same short prompt 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`](bench/live/2026-11-30-model-proof.json). This run cost **$0.00525445**.

LIVE, the same day, one new clock on a Haiku 5.5 prompt: `safe` cost **$0.00124700** and read 0 cached tokens. `optimize` moved the clock and cost **$0.00035128**, with 4,728 tokens read from cache. That call cost **$0.00089572** less. Claude Code had already turned caching on. Receipt: [`bench/live/2026-11-30-haiku-claude-code.json`](bench/live/2026-11-30-haiku-claude-code.json).

![CtxCache measured proof](docs/media/ctxcache-cost-proof-preview.gif)

[Full MP4 (~81s)](docs/media/ctxcache-cost-proof.mp4) · [Release download](https://github.com/jishmisc28/ctxcache/releases/download/proof-video/ctxcache-cost-proof.mp4) · [Live session write-up](docs/REPORT.md)

An embeddable context engine that keeps an AI agent's prompt cache warm and proves it with measurements.

Agent loops break provider caches on later turns when a timestamp sits in the system prompt, tool definitions change order, JSON key order changes, or the history is rewritten. CtxCache wraps the client you already have, records the break, and can put the stable prefix back.

CtxCache wraps your existing LLM client in-process, measures cache behavior, restores stable prefix layouts, protects against regressions in CI, and traces every cache break to its exact root cause.

---

## Highlights

- **In process.** Pure Python. Requires Python 3.10+ (`tomli` on 3.10 only). No gateway.
- **SIM, not a bill.** The frozen simulator report is a **42.0%** input-cost reduction across 4 frameworks × 2 providers on 20 tasks. Source: [`docs/REPORT.md`](docs/REPORT.md) (2026-10-19).
- **SIM calibration.** Held-out read-share error in that same report is **0.00 points MAE**. That fit is not a forecast of a future provider bill.
- **MICROBENCH.** `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`](docs/CLAIMS.md).
- **15 break causes** in `src/ctxcache/data/breaks.yaml`. Cold starts, minimum length, and TTL expiry are not labeled as your bug.

---

## Installation

```bash
pip install ctxcache
```

Run this first. No API key and no network. The prices are the simulator, not a provider bill.

```bash
ctxcache demo
```

A CI job can run `ctxcache check` the same way, with no API key. The workflow file is [`examples/github-action/workflow.yml`](examples/github-action/workflow.yml).

The same offline prices, four named cases:

```bash
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:
```bash
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.

```python
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 can set `prompt_cache_key`. It does not write Anthropic `cache_control` blocks.

```python
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).

```python
client = ctxcache.wrap(Anthropic(), mode="optimize")
```

---

## Framework Integrations

CtxCache integrates into modern agent frameworks with minimal setup (claim C-10):

### LangGraph / LangChain
```python
from ctxcache.integrations.langgraph import CtxCacheMiddleware

# Intercept and stabilize state inside your graph node
middleware = CtxCacheMiddleware(mode="safe")
processed_state = middleware(state)
```

### Pydantic AI
```python
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
```python
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:
```bash
ctxcache report --session "session-prod-worker-1"
```

### `ctxcache diagnose`
Analyze root causes of cache breaks in a JSONL trace file:
```bash
ctxcache diagnose ./traces/session.jsonl
```

### `ctxcache replay`
Replay recorded JSONL traces through the deterministic cache simulator under `observe`, `safe`, and `optimize` policies:
```bash
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:
```bash
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:
```bash
ctxcache bench --report
```

---

## Core Invariants

CtxCache strictly enforces 13 formal invariants verified on every commit:

1. **`INV-01` (Byte-Identical Passthrough):** `observe` mode sends byte-identical requests.
2. **`INV-02` (Content Equivalence):** `safe` mode modifies no message or tool text.
3. **`INV-03` (Deterministic Fingerprints):** Message SHA-256 fingerprints are deterministic across processes and Python versions.
4. **`INV-04` (Append-Only History):** No already-sent message is mutated except via explicit compaction events.
5. **`INV-05` (Action Reporting):** Every layout relocation and ordering restoration is recorded and reported.
6. **`INV-06` (Exact Token Accounting):** `read + write + uncached == total_input` strictly reconciles for Anthropic, OpenAI, and Gemini.
7. **`INV-07` (Fail-Open):** Any internal error passes original requests through unmodified and records `ctxcache_error`.
8. **`INV-08` (Zero Network Exfiltration):** No outbound network calls except to wrapped LLM providers and optional OTLP endpoints.
9. **`INV-09` (Privacy by Default):** Prompt content is never stored in ledgers, spans, or logs (`record=True` required for debug traces).
10. **`INV-10` (Honest Attribution):** TTL expiry, provider cold-starts, and below-minimum length are never attributed as user breaks.
11. **`INV-11` (Planner Limits):** Hard limit of 4 breakpoints per request; 1-hour entries precede 5-minute entries.
12. **`INV-12` (Memory Integrity):** Facts are superseded temporally (`valid_to`, `superseded_by`), never overwritten; mid-session writes never mutate the active session prefix cache.
13. **`INV-13` (Exact Financial Arithmetic):** All monetary costs and ratios use Python `Decimal`, never float.

---

## License

Apache-2.0. See [LICENSE](LICENSE) for details.
