An OpenAI/Anthropic-compatible gateway that routes each request to the best-fit model and tells you, and enforces, the cost before the request runs.
This repository is at Phase 2. The gateway sits in the request path, relays faithfully, and prices every request before it runs. Each inference call returns its estimated cost as response headers — expected, p90, and the hard ceiling max_tokens buys — and once the answer has streamed, the real bill is reconciled against that estimate and both are written to one log row. There is no routing or budget enforcement yet; that is Phase 3.
Today it serves the Anthropic Messages format and forwards to Anthropic, with Claude Code as the client.
$ curl -si localhost:8080/v1/messages -d @request.json ... | grep budgate
x-budgate-input-tokens: 7302
x-budgate-cache-read-tokens: 7288
x-budgate-cost-expected-usd: 0.005828
x-budgate-cost-p90-usd: 0.015728
x-budgate-cost-max-usd: 0.125108
Three levels, cheapest first. Each needs two terminals, both in the repo root.
1. Tests only. No servers, no credentials, no cost.
.\.venv\Scripts\python.exe -m pytest2. Against the mock upstream. Real HTTP, real streaming, still no cost.
# terminal 1
.\.venv\Scripts\python.exe scripts\mock_upstream.py --port 8099
# terminal 2
.\scripts\run_local.ps1 -Mock
# terminal 3, or terminal 1 after the mock is up
.\scripts\verify_gateway.ps1
claude -p "Say hi" --settings .\scripts\claude-settings.local.jsonExpect Hello from the budgate mock upstream. The reply is canned; what you are testing is that a real Claude Code session completes through the gateway.
3. Against real models. Costs money.
run_local.ps1 without -Mock borrows the upstream and credential already in ~/.claude/settings.json, reading them at run time so no second copy of the credential is written anywhere.
# terminal 1
.\scripts\run_local.ps1
# terminal 2
.\scripts\verify_gateway.ps1 -Model "bedrock.anthropic.claude-haiku-4-5"
claude -p "Read pyproject.toml and summarize it in one sentence." --allowedTools "Read" --settings .\scripts\claude-settings.local.jsonThen watch what actually happened:
Get-Content logs\requests.jsonl -Tail 5 | ForEach-Object { $o = $_ | ConvertFrom-Json; "$($o.path) $($o.status) $([math]::Round($o.ttfb_ms))ms $($o.model) est=`$$($o.estimate.expected_usd) actual=`$$($o.actual.cost_usd)" }And score the estimator against the bill:
.\.venv\Scripts\python.exe scripts\cost_report.pyThe model names in scripts/claude-settings.local.json must be ones the upstream accepts: bedrock.anthropic.* for the PwC gateway, plain claude-sonnet-4-6 style names for api.anthropic.com or the mock.
Confirming the gateway is transparent, rather than merely up:
- Streaming is not buffered. In
verify_gateway.ps1, the stream check reports when the first SSE event arrived and when the stream finished. Those two numbers must differ; if they are the same, the gateway buffered the whole response. - Errors pass through unchanged.
curl.exe -s -X POST http://localhost:8080/v1/messages -H "Authorization: Bearer local-dev-token" -H "content-type: application/json" -d '{\"model\":\"trigger-error\",\"max_tokens\":1,\"messages\":[]}'against the mock should return the upstream's own message, not a wrapper. - Nothing is dropped. The mock prints every request it receives, including the
anthropic-betavalues. Compare that line against what Claude Code sent; the lists should match exactly. - The price arrives before the answer.
verify_gateway.ps1reads thex-budgate-cost-*headers off a response and prints them. Headers are sent at the top of a response, so on a streamed request the client knows the cost while the model is still generating.
python -m venv .venv
.\.venv\Scripts\python.exe -m pip install -e ".[dev]"
Copy-Item .env.example .env
# Edit .env: set BUDGATE_ANTHROPIC_API_KEY and pick a BUDGATE_GATEWAY_TOKENS value.
.\.venv\Scripts\python.exe -m budgate.mainIn a second terminal, verify before pointing a real tool at it:
.\scripts\verify_gateway.ps1Then connect Claude Code:
$env:ANTHROPIC_BASE_URL = "http://localhost:8080"
$env:ANTHROPIC_AUTH_TOKEN = "local-dev-token" # must match BUDGATE_GATEWAY_TOKENS
$env:ANTHROPIC_API_KEY = "" # avoids a credential conflict
claudeInside Claude Code, run /status. An Anthropic base URL line showing the gateway confirms traffic is routing through it. Note that ANTHROPIC_BASE_URL is the gateway root, with no /v1 suffix.
The env block of ~/.claude/settings.json takes precedence over shell variables, so on a machine already pointed at a corporate gateway the exports above are silently ignored and requests keep going to the configured gateway. /status shows the wrong base URL and the failure looks like a gateway bug.
Override per-invocation instead of editing the settings file:
# settings.json content, e.g. %TEMP%\budgate-local.settings.json
# { "env": { "ANTHROPIC_BASE_URL": "http://localhost:8080", "ANTHROPIC_AUTH_TOKEN": "local-dev-token" } }
claude --settings "$env:TEMP\budgate-local.settings.json"If the existing settings file also sets ANTHROPIC_DEFAULT_SONNET_MODEL or its Opus and Haiku siblings, override those too. They rewrite the model names Claude Code sends, and names scoped to another gateway will not resolve here.
scripts/mock_upstream.py stands in for api.anthropic.com so the whole path can be exercised without spending tokens:
.\.venv\Scripts\python.exe scripts\mock_upstream.py --port 8099
$env:BUDGATE_UPSTREAM_BASE_URL = "http://127.0.0.1:8099"It emits a realistic SSE stream with deliberate delays between chunks, which is the point: a buffering gateway is indistinguishable from a streaming one when the upstream answers instantly. Send "model": "trigger-error" for a 400, or a prompt containing MOCK_TOOL_USE for a stream ending in a tool call.
Billing moves to your API key. Routing Claude Code through a gateway bypasses a claude.ai subscription login and bills your Anthropic API key at pay-per-token rates instead. A gateway credential variable takes precedence over a saved login; unset it and Claude Code goes back to the subscription.
Two features will not appear in the gateway logs. Fast mode's availability check and the WebFetch domain safety check call api.anthropic.com directly rather than following ANTHROPIC_BASE_URL. Their absence from the logs is expected. On a network that blocks direct egress to api.anthropic.com, fast mode can report a connectivity error while inference through the gateway keeps working.
Never commit your credential. .env is gitignored, and so is logs/. Don't put a gateway token in a project's .claude/settings.json, which is committed and shared.
All settings are read from the environment or .env, prefixed BUDGATE_.
| Variable | Default | Purpose |
|---|---|---|
BUDGATE_ANTHROPIC_API_KEY |
empty | The real provider credential. Held server-side; clients never see it. |
BUDGATE_GATEWAY_TOKENS |
empty | Comma-separated tokens clients must present. Empty disables auth, which the server warns about at startup. |
BUDGATE_UPSTREAM_BASE_URL |
https://api.anthropic.com |
Where requests are forwarded. Can be another Anthropic-format gateway. |
BUDGATE_UPSTREAM_CA_BUNDLE |
unset | Extra CA certs to trust in addition to the defaults, for an upstream behind corporate TLS interception. |
BUDGATE_HOST / BUDGATE_PORT |
127.0.0.1 / 8080 |
Bind address. |
BUDGATE_LOG_PATH |
logs/requests.jsonl |
Per-request reconciliation log. |
BUDGATE_COST_ESTIMATION |
true |
Kill switch for the cost brain. |
BUDGATE_TOKEN_COUNT_MODE |
heuristic |
heuristic counts locally; upstream asks the provider, exactly, at the cost of a round trip per request. |
BUDGATE_TOKEN_COUNT_TIMEOUT_MS |
1500 |
How long upstream mode waits before falling back to the local count. |
BUDGATE_PROMPT_CACHE_TTL_SECONDS |
300 |
Assumed cache lifetime when a request does not specify one. |
BUDGATE_PRICING_PATH |
packaged | Override the rate card without a release. |
BUDGATE_OUTPUT_PRIORS_PATH |
packaged | Override the output-length priors, e.g. a calibrated table. |
Implemented against Anthropic's gateway protocol reference, which specifies the contract between Claude Code and a gateway.
| Endpoint | Notes |
|---|---|
POST /v1/messages |
Inference. Claude Code posts to /v1/messages?beta=true, so the route matches on path and the query is relayed. |
POST /v1/messages/count_tokens |
Optional in the protocol. Serving it keeps Claude Code from spending inference requests on context counting. |
GET /v1/models |
Model discovery, active only when the client sets CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1. Must answer within 3 seconds and must not redirect. |
HEAD /api/hello |
Connection-warming probe Claude Code sends at startup. |
GET /healthz |
Local liveness check, not part of the protocol. |
Credentials are accepted in either Authorization: Bearer or x-api-key, because Claude Code's choice depends on which variable the developer set, and model discovery sends only one of the two.
Every POST /v1/messages is priced before it is dispatched. Nothing else is: counting tokens and listing models buy no inference, so tokenizing them would be latency spent on nothing.
| Header | Meaning |
|---|---|
x-budgate-cost-expected-usd |
Input cost plus the median output length for this task class. |
x-budgate-cost-p90-usd |
The same with a p90 output length: what a long answer costs. |
x-budgate-cost-max-usd |
Input cost plus max_tokens × output rate. |
x-budgate-input-tokens |
Whole prompt, including the tool-use system prompt the provider injects. |
x-budgate-cache-read-tokens / -cache-write-tokens |
How the prompt is expected to split across the cache. |
x-budgate-task-class |
Which output-length prior was applied. |
x-budgate-token-source |
heuristic or upstream — how the input tokens were counted. |
x-budgate-pricing-source |
exact, family_fallback, or unknown. |
The split is the honest part. Input cost is arithmetic: the tokens are already written and the rates are published. Output cost is a forecast, because nobody knows how long an answer is until it exists. Collapsing the two into one figure would hide which half is knowledge, so all three are emitted and only max is a promise.
When a model cannot be priced, the cost headers are omitted rather than set to zero. A zero reads as free.
Anthropic does not publish a tokenizer, so there are two honest options and the gateway offers both.
The default is a local approximation. It is not a BPE implementation; it models what BPE does to the text a coding agent actually sends — identifiers, JSON schemas, diffs, file contents — by counting word, digit, punctuation, and whitespace runs at different rates. Punctuation merges hardest, which is why a tool schema costs far less than its character count suggests. It runs in well under a millisecond and adds no network hop. Against a real BPE tokenizer it lands within about 10% in aggregate on that kind of text.
Setting BUDGATE_TOKEN_COUNT_MODE=upstream asks the provider's own /v1/messages/count_tokens instead, which is exact and free but puts a serial round trip in front of every inference request. That is a real latency tax on something sitting in someone's critical path, so it is opt-in, bounded by a timeout, and falls back to the local estimate rather than failing the request. The provider returns one number for the whole prompt; the gateway redistributes it across blocks using the local proportions, so the cache split still works and the parts still sum to the exact total.
Two things the request body does not show up in either count, both charged on every turn:
- The tool-use system prompt. The provider injects it whenever any tool is present. It is a few hundred tokens, it appears nowhere in the body, and its size depends on the model and on whether
tool_choiceforces a tool. - The tokenizer generation. Claude 4.7 and later use a tokenizer that emits roughly 30% more tokens for identical text at an unchanged per-token rate, so the same prompt genuinely costs about 30% more there. Both are in
pricing.json.
In a coding session this is most of the bill. A cache read costs a tenth of the base input rate and a write costs a quarter more than it, and Claude Code re-sends the whole conversation on every turn — so by the tenth turn, pricing everything as fresh input is wrong by close to an order of magnitude.
The provider does not say in advance whether a prefix is cached, but it can be worked out. The cache is keyed on the exact prompt prefix, so a prefix this gateway has already sent and that has not expired will be a hit. cache.py keeps a digest of each cacheable prefix and its expiry — 16 bytes per entry, LRU-bounded, never the text — and predicts a read for the longest live prefix and a write for the rest.
Two things scope a cache entry beyond the prompt text, and both are in the digest:
- The model. The same conversation sent to Sonnet and then to Opus is two cold caches, not a hit.
tool_choiceand extended thinking. Both change the system prompt the provider prepends, which sits inside every cacheable prefix, so flipping either invalidates the whole conversation's cache.
A prefix is only predicted as cached if it clears the provider's minimum (1024 tokens, 2048 for Haiku); below that the provider ignores the breakpoint and bills the tokens as ordinary input. And a prefix is only recorded after the provider accepted the request, because a rejected one populates nothing.
Output length is forecast from a per-task-class prior. The class is decided by the signal that most determines how long the answer runs, in this order:
| Class | Signal |
|---|---|
micro |
max_tokens ≤ 64. Conversation titles and classifications; the ceiling is a hard bound, so it outranks everything. |
reasoning |
Extended thinking is on. Thinking tokens are billed as output and swamp everything below. |
tool_result |
Tools present, last message carries a tool_result. The continuation of an agent loop. |
tool_use |
Tools present. The turn that opens one. |
chat |
No tools. |
The shipped priors in output_priors.json are seeds, not measurements. Every entry carries samples: 0, which is what says so — to a reader, and to the estimator. Replacing them is what scripts/cost_report.py --calibrate does.
Once a response has streamed to its end, the actual usage is read off it and compared against the estimate. The response body is relayed byte for byte and must stay that way, so the sniffer observes a copy of each chunk as it passes: no buffering, no reframing, and no chunk held back waiting for what follows it. A streamed response reports its input tokens in message_start and its final output count in message_delta; a non-streamed one carries both in the body.
The row is written when the exchange completes, which is also what happens when a client disconnects mid-stream. A request somebody gave up on still cost money and still belongs in the log.
.\.venv\Scripts\python.exe scripts\cost_report.py # score against the bill
.\.venv\Scripts\python.exe scripts\cost_report.py --calibrate # rewrite the priors from what ranThe report separates input error from output error, because they are different problems. Input tokens are written down before the request runs, so a systematic bias there is a calibration fix with a single number behind it — and the report does that arithmetic for you. Output length is a forecast and is allowed to be wrong.
--calibrate only rewrites a prior once it has at least 20 observations in a task class, or 50 for a per-model override. A prior calibrated from four requests is worse than the seed it replaced: it carries the authority of a measurement without the sample behind it.
An early design considered running LiteLLM Proxy and implementing the cost brain as callback hooks. This repository instead owns the gateway directly, matching the architecture diagram, because the hooks that would be needed (async_pre_call_hook) are proxy-only, which would make the cost estimator and budget gate plugins constrained by someone else's request lifecycle rather than first-class code.
The protocol requires forwarding headers and body fields as open lists, not allowlists. Claude Code delivers each new capability as an anthropic-beta header paired with a request body field, and the upstream returns a hard 400 when only one half of the pair arrives. Since the set grows with every Claude Code release, a gateway pinned to the fields it recognizes today breaks on the release that introduces the next one.
That rules LiteLLM's completion() out of the Anthropic-to-Anthropic path. It normalizes through an OpenAI-shaped intermediate with a fixed parameter list, so thinking, context_management, output_config, and tool strict/defer_loading are dropped on re-serialization. So PassthroughDispatcher forwards the request body as the exact bytes received and never decodes and re-encodes it.
LiteLLM remains the right tool for Phase 3, where routing to a non-Anthropic provider makes translation both necessary and correct. src/budgate/dispatch/litellm.py holds that seam, and Dispatcher in src/budgate/dispatch/base.py is the interface both implementations satisfy, so route handlers will not change.
- Streams must relay unbuffered, including pings. Claude Code counts every byte the gateway relays and aborts a stream that goes silent for 300 seconds. During a long thinking pause the upstream's SSE
pingevents and comment lines are the only traffic, so a gateway that filters or buffers them causes aborts that look like provider flakiness. The dispatcher iteratesaiter_raw()rather thanaiter_lines(), which would reframe the stream. - Upstream errors must be relayed verbatim. Claude Code retries some rejections automatically and disables the rejected capability for the rest of the conversation, and that logic matches on the upstream's error wording. Wrapping an upstream error in the gateway's own envelope breaks the recovery path even when the status code is preserved. Errors the gateway itself generates, such as a 401, are shaped like Anthropic errors, which is a different case.
- The
systemarray must pass through in order. Claude Code prepends an attribution block, and Anthropic strips it positionally when it arrives unchanged as the first system block. Reordering the array, prepending another block, or collapsing it to a string defeats the strip, so the block reaches the model and changes the prompt cache key.
Read timeouts are disabled on the upstream connection (read=None) for the same reason as the ping relay: a thinking pause is not a hung connection.
It runs in front of every inference call, which makes it the most dangerous code in the repository. So every failure path degrades instead of raising: an unparseable body, an unknown model, an unreachable token counter, or a bug in pricing costs the client a header, never an answer. BUDGATE_COST_ESTIMATION=false removes it from the path entirely, because otherwise the only way to disable a misbehaving estimator is a redeploy against a gateway someone's agent is mid-session on.
Two consequences follow from the same principle. An unrecognized model prices at the most expensive member of its family rather than the newest, because for something whose purpose is a budget gate, guessing high fails toward refusing an affordable request and guessing low fails toward approving one that blows the budget. And observation of a response is abandoned rather than allowed to consume the process: a missing reconciliation row costs a line in a log, while a gateway that runs out of memory relaying a large response costs someone their session.
Reconciliation could have been implemented by collecting the response body and parsing it at the end. That relays a correct answer and stalls every client, which is exactly the Phase 1 failure this repository was built to avoid. Instead the body iterator is wrapped, and each chunk is scanned and then immediately yielded onward.
The scan happens just before the yield rather than just after. It is a byte scan with no I/O in it, so the delay is not measurable, and the other ordering loses the final chunk whenever a client disconnects — which on a stream abandoned early is the chunk carrying the input token counts. Only message_start and message_delta are parsed, matched as a substring before anything is decoded, so the text deltas that make up the bulk of a stream cost a find and nothing more.
pricing.json carries an as_of date and its source URL, and the gateway logs both at startup. Provider prices change, and a rate card buried in Python is one nobody audits. BUDGATE_PRICING_PATH and BUDGATE_OUTPUT_PRIORS_PATH override the packaged files, so a price change or a freshly calibrated priors table ships without a release.
One JSON line per request at logs/requests.jsonl, written when the exchange completes:
{
"request_id": "a1b2", "ts": 1754899200.1, "path": "/v1/messages", "status": 200,
"ttfb_ms": 412.5, "duration_ms": 8140.2, "stream": true,
"model": "claude-sonnet-4-6", "task_class": "tool_result", "session_id": "sess_01",
"estimate": {
"priced_model": "claude-sonnet-4-6", "pricing_source": "exact",
"token_source": "heuristic", "input_tokens": 7302,
"cache_read_tokens": 7288, "cache_write_tokens": 0,
"input_cost_usd": 0.002228, "output_tokens_expected": 240,
"expected_usd": 0.005828, "p90_usd": 0.015728, "max_usd": 0.125108,
"prior_samples": 0, "elapsed_ms": 3.2
},
"actual": {
"input_tokens": 7431, "cache_read_tokens": 7288, "output_tokens": 312,
"cost_usd": 0.006509,
"delta": {
"input_token_error": -129, "output_token_error": -72,
"input_token_error_pct": -1.74, "output_token_error_pct": -23.08,
"cost_usd": -0.000681, "cost_error_pct": -10.46,
"within_20pct": true, "exceeded_max": false
}
}
}Every field in delta is estimate minus reality, so a positive number always means the estimate was too high. within_20pct is written out rather than left to be derived, because it is the Phase 2 checkpoint itself and a checkpoint you have to recompute to check is one nobody checks.
Prompts and responses are still never logged, only counts, costs, and identifiers — even though Phase 2 reads every message to tokenize it and hashes cache prefixes, which is the most access to prompt content anything in this gateway has. The session_id, agent_id, and parent_agent_id fields come from Claude Code's attribution headers, which the protocol marks consume-only; they let cost be attributed to a session and to parallel subagents.
ttfb_ms measures time to response headers and duration_ms to the last byte.
.\.venv\Scripts\python.exe -m pytestThe suite runs the real app against a fake upstream written at the ASGI level, so a test controls the exact byte chunks the upstream emits. It asserts the properties Phase 1 depends on: streams relay byte-for-byte including pings and comment lines, unknown body fields survive the hop, upstream error status and body arrive unmodified, the client credential is swapped for the provider key and never leaks upstream, and both credential headers authenticate.
Phase 2 adds the cost brain, and re-asserts every one of those Phase 1 properties now that something reads the response. Three areas are worth knowing about:
- The tap is tested by hand, not through the transport. httpx's ASGI transport collects a response body before returning it, so a gateway that buffered and one that relays look identical through it.
TestTheTapdrives the iterator one chunk at a time instead, which is the only way to tell the difference — and the only way to test what happens when a client disconnects halfway. - Chunk boundaries are enumerated, not sampled. A TCP chunk has no relationship to an SSE event boundary, so the usage sniffer is fed the same stream re-split at 1, 2, 3, 7, 64, and 1024 bytes. An event straddling a chunk is the failure a test using realistic chunks would never see.
- The suite is hermetic. An autouse fixture clears every
BUDGATE_*variable, because settings fall back to the environment and a leftover variable in a shell silently changes what is being tested.
Verified against the mock upstream with Claude Code 2.1.210. What a real session produced:
- Streaming is incremental, not buffered. Against an upstream pacing chunks 150ms apart, the first SSE event reached the client at 274ms and the stream completed at 2364ms. A buffering gateway would deliver both at the same moment.
- A full agentic loop completed: model discovery, a background Haiku call, a first Opus turn returning
tool_use, and a second turn carrying thetool_resultback, all under one session ID. - Forwarding verbatim was load-bearing. The real client sent beta values including
thinking-token-count-2026-05-13,prompt-caching-scope-2026-01-05,advisor-tool-2026-03-01,structured-outputs-2025-12-15,effort-2025-11-24, andcontext-1m-2025-08-07. An allowlist assembled from the documentation would have dropped several of them. - Errors reach the client intact. A 400 from the upstream surfaced in Claude Code as
API Error: 400 model: 'trigger-error' is not a recognized model, the upstream's own wording, which is what its retry logic matches on.
One warning is expected and not a gateway fault: claude.ai connectors are disabled because ANTHROPIC_API_KEY or another auth source is set. A gateway credential takes precedence over a saved login by design.
Then repeated against a real provider, with the upstream set to an existing corporate LiteLLM gateway fronting Bedrock. A real Claude Code session read a file through the gateway and answered correctly about its contents, on bedrock.anthropic.claude-sonnet-4-6, with 312 models discovered in 691ms and real token counts from count_tokens. Chaining works because the gateway is transparent: whatever an upstream accepts directly, it accepts through this.
Trust for the upstream connection is pinned to certifi and extended only by BUDGATE_UPSTREAM_CA_BUNDLE, rather than inheriting the ambient default. This is deliberate. SSL_CERT_FILE in the environment silently replaces Python's entire trust store, so a bundle holding only corporate roots makes every upstream that chains to a public CA fail with self-signed certificate in certificate chain. A gateway in the critical path should not inherit trust configuration it cannot verify, and extra certs should add trust rather than replace it, which is what NODE_EXTRA_CA_CERTS means and what passing a bundle to httpx's verify does not do.
The checkpoint has two halves, and they are verified in different places.
The machinery works, verified against the mock. A run through mock_upstream.py produces the estimate headers before the answer, a populated reconciliation log, and a report that scores it. The prompt-cache prediction is visible in the numbers: the same request sent twice moves 7288 tokens from a cache write to a cache read and drops the input cost from $0.030972 to $0.005828, an 81% reduction, which is the dynamic that dominates a real coding session. The same conversation sent to a different model correctly starts cold. Requesting an unpriceable model returns token counts and no cost headers rather than a zero.
The ±20% accuracy claim cannot be checked against the mock, and the report says so rather than pretending. The mock invents usage as characters divided by four, which is nobody's tokenizer, so scoring against it measures the disagreement between two approximations. Judging accuracy needs a real provider:
.\scripts\run_local.ps1 # real upstream, real cost
claude --settings .\scripts\claude-settings.local.json
.\.venv\Scripts\python.exe scripts\cost_report.pyThe report prints the per-task-class error, the share of requests inside ±20%, and — separately — the input-token bias with the exact scale factor that would remove it. --calibrate then replaces the seeded output priors with medians measured from that traffic. Measure again on fresh traffic afterwards: calibrating and scoring on the same requests measures the fit, not the estimator, and will look better than it is.
src/budgate/
config.py settings from env / .env
main.py app factory, lifespan-managed httpx client, estimator assembly
auth.py credential extraction and comparison
relay.py authenticate, estimate, forward, reconcile, log
observability.py the JSONL reconciliation log
routes/ messages, models, health
cost/
catalog.py the rate card and the output priors, and model-name matching
parse.py a request flattened into priceable blocks
tokens.py local token approximation, and the exact upstream counter
cache.py prompt-cache prediction from prefix digests
estimate.py expected / p90 / max, and the response headers
usage.py actual usage read off the response, and the delta
data/ pricing.json, output_priors.json
dispatch/
base.py Dispatcher protocol and UpstreamRequest
passthrough.py byte-faithful streaming relay (Phase 1)
litellm.py Phase 3 seam, not wired
scripts/
verify_gateway.ps1 seven checks, cheapest first
cost_report.py score the estimator, and calibrate the priors from the log
mock_upstream.py a provider stand-in that reports plausible usage
tests/
Phase 3 next: named routing profiles selected through the model field, filter-then-score routing over the candidate set, and a budget gate that downgrades or refuses a request whose expected cost exceeds the policy ceiling. The inputs it needs already exist here — the cost estimate, the max ceiling it can refuse on, and a rate card that covers every candidate model.