PREFIXWISE/ docs
open source · MIT
INTEGRATIONS

Connect Prefixwise wherever your AI calls go.

Every route writes the same ledger and the same report. Prompts are read to fingerprint them and never stored. Pick what you already have.

Just lookingprefixwise demoA coding agent with an API keyprefixwise run -- claudeClaude Code or Codex on a subscriptionprefixwise import claude-codeCalls to Anthropic, OpenAI, Gemini or Azureprefixwise serve --upstream URLPython code using an SDKprefixwise.wrap(client)LiteLLMcallbacks: prefixwise...Envoy, Bifrost, Plano or Portkeygateway → prefixwise servevLLM or SGLang on your own GPUsprefixwise serve --upstream <engine>
Tested liverun against the real service Stand-intested against a local stand-in only Supportedbuilt and tested in code, no live record yet

01Try it

No key, no network

See a scripted agent break its cache three ways, each miss named and priced, then run again with the fixes on. About five seconds.

Tested live
pip install prefixwise
prefixwise demo

# step through it, or use your own key (18 small billed calls)
prefixwise demo --step
prefixwise demo --live --provider anthropic

Needs Python 3.10 or later. Runs against a built-in stand-in; --live uses ANTHROPIC_API_KEY or OPENAI_API_KEY.

02Coding agents

Claude Code, Codex, opencode, your own

Run the agent through a temporary local proxy. It keeps its own key and calls its provider as before; the report prints when it exits.

Tested live
export ANTHROPIC_API_KEY=sk-ant-...
prefixwise run -- claude

# the same, with the proven fixes applied
prefixwise run --optimize -- claude
prefixwise report --session latest

Needs an API key: a Pro or Max sign-in can’t be proxied, so read its logs instead (section 03).

03Logs already on disk

No API key, no setup

Read the logs an agent or gateway already wrote. Nothing is sent anywhere, and re-running adds only new calls.

Tested live
prefixwise import claude-code --since 7d
prefixwise report --ledger prefixwise-claude-code.db

For Pro and Max. Reads ~/.claude/projects read-only, subagents included. Dollars are the API-price value, not what a subscription paid. Checked call by call on a real 10,517-call session.

04Providers, through the proxy

Any language, no code change

Run the proxy in front of a provider and point your client’s base URL at it. Records chat completions, responses and messages, streamed or not.

Tested live
prefixwise serve --upstream https://api.anthropic.com

export ANTHROPIC_BASE_URL=http://127.0.0.1:8080

Messages API, streamed or not. Add --optimize to apply the proven fixes.

Amazon Bedrock goes through the Python wrapper, not the proxy (section 05).

05In your Python code

No proxy, one line

Wrap the client you already use. Calls go straight to the provider; each one is recorded after it returns. Sync and async, streams included.

Tested live
import prefixwise
from anthropic import Anthropic

client = prefixwise.wrap(Anthropic())
with prefixwise.session("fix-bug-42", task_id="fix-bug-42"):
    client.messages.create(model=MODEL, max_tokens=1024, messages=msgs)

messages.create, beta.messages.create and the .stream() helpers. Nothing in the request is changed.

Gemini’s genai.Client is not supported by wrap yet; use the proxy. Set PREFIXWISE_COLLECTOR to send records to a collector instead of ./prefixwise.db.

06LiteLLM

SDK or proxy server

Add one callback. Covers chat completions and the Messages API, so Claude Code routed through LiteLLM is recorded too.

Tested live
import litellm
from prefixwise.litellm_callback import PrefixwiseCallback

litellm.callbacks = [PrefixwiseCallback()]

Session ids come from litellm_session_id or metadata={"session_id": ..., "task_id": ...}.

Tested live: 20 of 20 live conversations named correctly, and 0 false alarms in 71,346 calls of real agent conversations replayed through it.

07Other gateways

Keep your gateway. Put Prefixwise behind it.

Point the gateway's provider address at prefixwise serve, which forwards to the real provider. Each was checked streamed and not, OpenAI and Anthropic formats, against a cache stand-in.

your appyour gatewayprefixwise serveprovider
GatewayWire itSession idStatus
Envoy AI GatewayOPENAI_BASE_URL=http://prefixwise:8080/v1 ANTHROPIC_BASE_URL=http://prefixwise:8080The Prefixwise header passes through.Stand-in
Bifrostconfig.json: network_config.base_url = http://prefixwise:8080, with a virtual keySend x-bf-eh-x-prefixwise-session-id; Bifrost drops the plain header.Stand-in
Planomodel_providers: base_url: http://prefixwise:8080The Prefixwise header passes through.Stand-in
Portkey (open source)x-portkey-custom-host: http://prefixwise:8080/v1 x-portkey-forward-headers: x-prefixwise-session-idForwarded with x-portkey-forward-headers. Non-streamed only: Portkey’s own streaming failed with or without us.Stand-in
LiteLLMUse the callback (section 06)litellm_session_id or metadata.session_idTested live

Self-hosted routers: llm-d, vLLM production-stack, AIBrix and the SGLang model gateway pass the session id through; their routing headers pass by default.

08Your own GPUs

vLLM, SGLang, LMCache, HiCache

Read the engine’s own cache events, so an eviction or a request sent to the wrong replica is confirmed, not guessed.

Tested live
vllm serve MODEL --enable-prefix-caching --enable-prompt-tokens-details \
  --kv-events-config '{"enable_kv_cache_events": true, "publisher": "zmq", "endpoint": "tcp://*:5557"}'

prefixwise serve --upstream http://127.0.0.1:8000

--enable-prompt-tokens-details is required, or every call looks like a miss. The engine and its events are detected. Run live.

pip install "prefixwise[engines]" for KV events. GET /engine shows the event stream’s health.

09Catch it in CI

Before a change ships

Run your agent’s test scenarios against a local stand-in, with no API calls. The build fails when a change would break reuse.

Tested live
prefixwise check -- pytest tests/agent_scenarios

# also fail on edited history, instructions or parameters
prefixwise check --strict -- pytest tests/agent_scenarios

Fails (exit 2) on tools sent in a new order, changing instructions, misplaced cache markers and edited tool results. Exit 1 when nothing was checked.

10Turn on the fixes

Proxy, run, or vLLM middleware

Fixes rewrite a request before it is sent, and step aside if the provider rejects the change. Each one predicts its saving from your own traffic first, so you know what it is worth before turning it on.

Tested live
prefixwise serve --upstream https://api.anthropic.com --optimize
prefixwise run --optimize -- claude

# what each would save on your traffic
prefixwise fixes

Turns on every fix with a live proof behind it, today tool ordering and, on Anthropic, cache markers. A new proven fix joins without a flag change.

prefixwise fixes ranks them by what your ledger says each would save, and whether placed cache markers have paid for themselves.

11Sessions, tasks and prices

Sharper answers from what you already know

Optional headers tell Prefixwise which calls belong together and what they were for. They are stripped before the request is forwarded.

Tested live
X-Prefixwise-Session-Id: fix-bug-42
X-Prefixwise-Agent-Id: support-agent-v3
X-Prefixwise-Compaction-Event: 1
X-Prefixwise-Fork-Of: fix-bug-41
X-Prefixwise-Cache-Ttl: 3600

Without a session, Claude Code’s and Codex’s own ids are used, then x-session-id or an end-user id. Compaction and fork headers turn an unexplained miss into a named, legitimate one.

12Fleet and data out

Many machines, one ledger, your own tools.
CollectorOne ledger for many proxies, wrappers and middleware. Records go over HTTP, up to 1,000 a batch.
prefixwise collect --port 8081
prefixwise serve --collector http://collector:8081
PREFIXWISE_COLLECTOR=http://collector:8081 python app.py
Several collectorsA Redis stream shared out by partition. Needs Redis 7 and the [log] extra.
prefixwise collect --log redis://redis:6379/0 --partitions 0-7
prefixwise collect --log redis://redis:6379/0 --partitions 8-15
SinksCopy every row to a file or ClickHouse as it is written. Repeatable, on serve and collect.
--sink file:///var/log/prefixwise/rows.jsonl
--sink clickhouse://user:pass@host:8123/db.table
Prometheus and GrafanaRequests, tokens, cost and avoidable cost by provider, model and cause. A dashboard and alert rules ship in deploy/.
GET /metrics
deploy/grafana/prefixwise.json
deploy/prometheus/prefixwise-rules.yml
OpenTelemetryGenAI spans with the cause and avoidable cost added, never prompt text. Wrap and LiteLLM use your app’s own tracer.
pip install "prefixwise[otel]"
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 \
  prefixwise serve --upstream https://api.anthropic.com --otel
HTTP API and exportSummaries, breakdowns, sessions and findings as JSON; rows out as JSONL or CSV.
GET /api/v1/summary
GET /api/v1/breakdown?by=cause
prefixwise export --format csv --since 7d -o rows.csv

13Privacy and security

Prompt text never leaves the process.
What is storedFingerprints of each part of a call, token counts, causes, prices and your own session, task and agent labels. Never prompt text or API keys. Exports never include the fingerprints.
prefixwise export --format jsonl -o rows.jsonl
Keyed fingerprintsSet a long random key so a short or predictable message cannot be guessed from its fingerprint.
PREFIXWISE_HMAC_KEY=<long random string>
Beyond localhostListens on 127.0.0.1 by default. To serve a team, require a token; with an API key set it refuses to listen wider without one.
PREFIXWISE_AUTH_TOKEN=<token>
# clients send X-Prefixwise-Token
RetentionAbout 450 bytes per call. Delete old rows on a schedule.
prefixwise prune --older-than 30d

Found a vulnerability? See SECURITY.md.

14Command reference

prefixwise demoA scripted agent breaks its cache three ways; each miss named and priced.
prefixwise run -- CMDRun an agent through a temporary proxy; report when it exits. --optimize applies the fixes.
prefixwise import SOURCERead claude-code, codex or gateway logs into their own ledger.
prefixwise serveThe proxy, for an API or a vLLM / SGLang server.
prefixwise reportSummary, causes and fixes; --session for one conversation turn by turn; --share for a pasteable block.
prefixwise fixesFixes ranked by what your own traffic says each would save.
prefixwise check -- CMDCI gate on a local stand-in; exit 2 when a change breaks reuse.
prefixwise explain FILESDiagnose saved request bodies offline; --diff shows what changed.
prefixwise pricesThe dated price table in use. Override with PREFIXWISE_PRICES.
prefixwise request IDOne ledger row, by the X-Prefixwise-Request-Id response header.
prefixwise task IDMark a task a success or failure, for cost per successful task.
prefixwise exportRows as JSONL or CSV, or a --baseline file for check.
prefixwise pruneDelete rows older than an age, for retention.
prefixwise collectA collector: one ledger for many machines.

Worked examples: eight real scenarios, from a bill that jumped to gating prompt changes in CI. Every command takes --help. Install extras: [engines] for KV events, [otel] for OpenTelemetry, [log] for the Redis record log.