Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

fix(proxy/savings): don't bill fallback rate for free (0-priced) models (#2024)

Abhay Singh6ecbdd6b5273
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 874f799cc..31b44ab2f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -115,6 +115,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
* **proxy/vertex:** route Vertex `publisher=google` (Gemini) requests to the region matching the request path. `vertex_generate_content`, `vertex_stream_generate_content`, and `vertex_count_tokens` discarded the path's `location` and forwarded to the single fixed host from `_api_target(proxy, "vertex")` (default `us-central1`), instead of the region-aware `_vertex_target_for_location` the sibling Anthropic `rawPredict` route already uses. So a request to `.../locations/europe-west1/publishers/google/...` was sent to a `us-central1` host, which Vertex rejects on the region/host mismatch. The three google routes now derive the host from the request's `location` (operator-pinned upstreams are still honored).
* **proxy/anthropic:** give each Anthropic conversation its own session id. `SessionTrackerStore.compute_session_id` derived its fallback id from `model` + system text harvested only from `role:"system"` entries inside `messages` — but Anthropic carries the system prompt as a top-level `body["system"]` field, so genuine Anthropic requests (which never carry `x-headroom-session-id`) collapsed to `md5(model:[])` and every conversation on the same model shared one `PrefixCacheTracker`. That let session-sticky state cross-contaminate: conversation A's sticky `headroom_retrieve`/memory tools and `anthropic-beta` headers were injected into conversation B, and frozen-prefix/compression-cache state mixed across conversations. The Anthropic handler now folds the top-level `system` into the session-id inputs (prepending a synthetic `role:"system"` message used only to derive the id), giving distinct conversations distinct ids.
* **cache/semantic:** key entries by the full-context hash, not the trailing query text. `SemanticCache.put` stored each response under `sha256(query)[:16]` where `query` is only the last user message, and the exact-match branch of `get` returned the slot without checking the stored entry's `messages_hash`. Two requests that share a trailing message ("continue", "yes", "run the tests") but differ in earlier context therefore collided on one slot — the second overwrote the first, and the first's hash then resolved to the second's cached response (wrong data served). Entries are now keyed by `messages_hash` when present, and `get` verifies `entry.messages_hash` before returning.
+* **proxy/savings:** stop billing the $3/M fallback rate for genuinely free models. `_estimate_compression_savings_usd` and `_estimate_input_cost_usd` read `input_cost_per_token` from litellm and used `if not input_cost_per_token: raise`, which treats a legitimate `0.0` (a free / local / vendored-at-0 model that litellm does carry) as "price unavailable" and falls back to `DEFAULT_FALLBACK_INPUT_COST_PER_TOKEN` — fabricating dollar savings/cost for a model that costs nothing. Both now use an explicit `is None` check so a present `0.0` flows through as `$0` while a missing key still falls back.
* **proxy/cost:** value prefix-cache savings with the most-used model's price, not the first-recorded one. `build_prefix_cache_stats` scanned `cost_tracker._tokens_sent_by_model` and broke on the *first* provider-matching model with a price — despite the "most-used model" comment — so a Claude Code session (Sonnet for the main loop, Haiku for titles/subagents) priced all of a provider's cache-read savings at whichever model happened to be recorded first. If Haiku ($0.80/M) came before Sonnet ($3/M), the dashboard understated cache savings ~3.75x (and vice-versa). It now picks the provider-matching, priced model with the highest token volume.
* **proxy/openai:** stop overriding an explicit client `stream_options.include_usage` on the streaming chat path. To count tokens from the trailing usage chunk, the handler set `include_usage: True` unconditionally — including flipping an explicit client `false` to `true`. The upstream then appended a usage-only chunk (`choices: []`) the client never requested, and the common `chunk.choices[0].delta` loop raised `IndexError`. The option is now only filled in when the client left the choice open (no `stream_options`, or a dict without `include_usage`); an explicit `true`/`false` is respected.
* **proxy/openai:** stop PRE_SEND from reintroducing `tools: []` after the direct #728 fix. The OpenAI request handler now mirrors the existing `tools or _original_tools is not None` body-write guard during PRE_SEND write-back, so providers that reject empty tool arrays no longer see a tools field when the client omitted it, while explicit client `tools: []` remains preserved ([#1983](https://github.com/headroomlabs-ai/headroom/issues/1983)).
diff --git a/headroom/proxy/savings_tracker.py b/headroom/proxy/savings_tracker.py
index 0b45d9ccc..927937945 100644
--- a/headroom/proxy/savings_tracker.py
+++ b/headroom/proxy/savings_tracker.py
@@ -209,7 +209,11 @@ def _estimate_compression_savings_usd(model: str, tokens_saved: int) -> float:
resolved = _resolve_litellm_model(model)
info = litellm.model_cost.get(resolved, {})
input_cost_per_token = info.get("input_cost_per_token")
- if not input_cost_per_token:
+ # Distinguish "price unknown" (missing key → fall back) from a model that
+ # is legitimately free (input_cost_per_token == 0.0). `if not ...` treated
+ # a real 0.0 as unavailable and billed the $3/M fallback — phantom savings
+ # for a model that costs nothing.
+ if input_cost_per_token is None:
raise RuntimeError("input cost unavailable")
return float(tokens_saved) * float(input_cost_per_token)
except Exception:
@@ -290,7 +294,9 @@ def _estimate_input_cost_usd(
resolved = _resolve_litellm_model(model)
info = litellm.model_cost.get(resolved, {})
input_cost_per_token = info.get("input_cost_per_token")
- if not input_cost_per_token:
+ # A missing key means the model is unknown → fall back to a blended rate.
+ # A present 0.0 means the model is free and must cost $0, not the fallback.
+ if input_cost_per_token is None:
raise RuntimeError("input cost unavailable")
if use_breakdown:
diff --git a/tests/test_savings_tracker_zero_price.py b/tests/test_savings_tracker_zero_price.py
new file mode 100644
index 000000000..3fc3e91c3
--- /dev/null
+++ b/tests/test_savings_tracker_zero_price.py
@@ -0,0 +1,63 @@
+"""Regression: free (0-priced) models must not be billed the fallback rate.
+
+`_estimate_compression_savings_usd` / `_estimate_input_cost_usd` read
+`input_cost_per_token` from litellm and used `if not input_cost_per_token: raise`,
+which treats a legitimate `0.0` (a free / local / vendored-at-0 model) as "price
+unavailable" and falls back to DEFAULT_FALLBACK_INPUT_COST_PER_TOKEN ($3/M) —
+fabricating savings/cost for a model that costs nothing. A missing key (unknown
+model) must still fall back.
+"""
+
+from __future__ import annotations
+
+import types
+
+from headroom.proxy import savings_tracker as st
+from headroom.proxy.savings_tracker import (
+ DEFAULT_FALLBACK_INPUT_COST_PER_TOKEN,
+ _estimate_compression_savings_usd,
+ _estimate_input_cost_usd,
+)
+
+
+def _fake_litellm(model_cost: dict) -> types.SimpleNamespace:
+ # cost_per_token succeeding makes _resolve_litellm_model return the name as-is.
+ return types.SimpleNamespace(
+ model_cost=model_cost,
+ cost_per_token=lambda **_kw: (0.0, 0.0),
+ )
+
+
+def test_compression_savings_zero_for_free_model(monkeypatch):
+ monkeypatch.setattr(
+ st,
+ "_get_litellm_module",
+ lambda: _fake_litellm({"free-model": {"input_cost_per_token": 0.0}}),
+ )
+ assert _estimate_compression_savings_usd("free-model", 1_000_000) == 0.0
+
+
+def test_compression_savings_falls_back_for_unknown_model(monkeypatch):
+ # Model absent from litellm → input_cost_per_token is None → fall back.
+ monkeypatch.setattr(st, "_get_litellm_module", lambda: _fake_litellm({}))
+ got = _estimate_compression_savings_usd("unknown-model", 1_000_000)
+ assert got == 1_000_000 * DEFAULT_FALLBACK_INPUT_COST_PER_TOKEN
+
+
+def test_compression_savings_uses_real_price_for_paid_model(monkeypatch):
+ price = 3.0 / 1_000_000
+ monkeypatch.setattr(
+ st,
+ "_get_litellm_module",
+ lambda: _fake_litellm({"paid-model": {"input_cost_per_token": price}}),
+ )
+ assert _estimate_compression_savings_usd("paid-model", 1_000_000) == 1_000_000 * price
+
+
+def test_input_cost_zero_for_free_model(monkeypatch):
+ monkeypatch.setattr(
+ st,
+ "_get_litellm_module",
+ lambda: _fake_litellm({"free-model": {"input_cost_per_token": 0.0}}),
+ )
+ assert _estimate_input_cost_usd("free-model", 500_000) == 0.0