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.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
Fix dashboard cost savings: use model list price, not moving average
chopratejasd7ab580aa3d5
diff --git a/headroom/dashboard/templates/dashboard.html b/headroom/dashboard/templates/dashboard.htmlindex 06dccc98a..68e4f4df7 100644--- a/headroom/dashboard/templates/dashboard.html+++ b/headroom/dashboard/templates/dashboard.html@@ -70,16 +70,16 @@<div><!-- Hero Metrics (reordered: Savings $ -> Tokens Saved % -> Quality Confidence -> Overhead) --><div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">- <!-- Savings ($) - Combined: compression + prefix cache -->+ <!-- Savings ($) - Compression only, priced at model list rate --><div class="bg-surface rounded-lg p-4 border border-border">- <div class="text-xs text-gray-500 uppercase tracking-wide mb-1">Total Savings</div>+ <div class="text-xs text-gray-500 uppercase tracking-wide mb-1">Compression Savings</div><div class="flex items-baseline gap-2"><span class="text-3xl font-light tabular-nums text-emerald-400" x-text="'$' + formatCurrency(stats.cost?.savings_usd || 0)"></span></div><div class="mt-2 text-xs text-gray-500">- <span x-show="stats.cost?.compression_savings_usd > 0 || stats.cost?.cache_savings_usd > 0"- x-text="'$' + formatCurrency(stats.cost?.compression_savings_usd || 0) + ' compress + $' + formatCurrency(stats.cost?.cache_savings_usd || 0) + ' cache'"></span>- <span x-show="!(stats.cost?.compression_savings_usd > 0 || stats.cost?.cache_savings_usd > 0)"+ <span x-show="stats.cost?.savings_usd > 0"+ x-text="formatNumber(stats.tokens?.saved || 0) + ' tokens at model list price'"></span>+ <span x-show="!(stats.cost?.savings_usd > 0)"x-text="formatNumber(stats.requests?.total || 0) + ' requests processed'"></span></div></div>@@ -127,29 +127,30 @@</div></div>- <!-- "Without Headroom" Counterfactual -->- <template x-if="(stats.cost?.cost_without_headroom_usd || 0) > 0">+ <!-- Savings Breakdown -->+ <template x-if="(stats.cost?.savings_usd || 0) > 0 || (stats.cost?.cache_savings_usd || 0) > 0"><div class="bg-surface rounded-lg p-4 border border-border mb-6">- <div class="flex items-center justify-between">+ <div class="text-sm font-medium text-gray-300 mb-3">Savings Breakdown</div>+ <div class="flex items-center gap-8"><div>- <div class="text-sm font-medium text-gray-300 mb-1">Without Headroom</div>- <div class="text-xs text-gray-500 mb-2">Message tokens only — excludes system prompt & tool definitions</div>- <div class="flex items-center gap-8">- <div>- <div class="text-xs text-gray-500 mb-1">Input cost (cache-aware)</div>- <div class="text-2xl font-light tabular-nums text-emerald-400" x-text="'$' + formatCurrency(stats.cost?.cost_with_headroom_usd || 0)"></div>- </div>- <div class="text-gray-500 text-2xl font-light">vs</div>- <div>- <div class="text-xs text-gray-500 mb-1">Input cost without Headroom</div>- <div class="text-2xl font-light tabular-nums text-red-400 line-through decoration-red-400/50" x-text="'$' + formatCurrency(stats.cost?.cost_without_headroom_usd || 0)"></div>- </div>- <div class="ml-auto text-right">- <div class="text-xs text-gray-500 mb-1">Compression saved</div>- <div class="text-2xl font-light tabular-nums text-emerald-400" x-text="'$' + formatCurrency(stats.cost?.compression_savings_usd || 0)"></div>- </div>- </div>+ <div class="text-xs text-gray-500 mb-1">Compression</div>+ <div class="text-2xl font-light tabular-nums text-emerald-400" x-text="'$' + formatCurrency(stats.cost?.compression_savings_usd || 0)"></div>+ <div class="text-xs text-gray-500" x-text="formatNumber(stats.tokens?.saved || 0) + ' tokens removed'"></div></div>+ <template x-if="(stats.cost?.cache_savings_usd || 0) > 0">+ <div>+ <div class="text-xs text-gray-500 mb-1">Prefix Cache Discount</div>+ <div class="text-2xl font-light tabular-nums text-cyan-400" x-text="'$' + formatCurrency(stats.cost?.cache_savings_usd || 0)"></div>+ <div class="text-xs text-gray-500">Provider-native caching</div>+ </div>+ </template>+ <template x-if="(stats.cost?.cli_tokens_avoided || 0) > 0">+ <div>+ <div class="text-xs text-gray-500 mb-1">CLI Filtering (rtk)</div>+ <div class="text-2xl font-light tabular-nums text-violet-400" x-text="formatNumber(stats.cost?.cli_tokens_avoided || 0)"></div>+ <div class="text-xs text-gray-500">tokens avoided</div>+ </div>+ </template></div></div></template>diff --git a/headroom/proxy/server.py b/headroom/proxy/server.pyindex f6fb25a52..e828b16dc 100644--- a/headroom/proxy/server.py+++ b/headroom/proxy/server.py@@ -378,13 +378,16 @@ def _merge_cost_stats(cache_stats: dict,cli_tokens_avoided: int = 0,) -> dict | None:- """Add prefix cache and CLI filtering savings to overall cost stats.+ """Merge compression, cache, and CLI savings into cost stats.- Three savings layers, each on a different scope:- - compression_savings_usd: tokens removed by proxy (SmartCrusher, etc.)- - cache_savings_usd: prefix cache discount from provider- - cli_filtering_savings_usd: tokens avoided by rtk before reaching context- - savings_usd: sum of all (hero metric)+ Each savings layer is reported separately with its own scope:+ - savings_usd: compression savings at model list price (monotonic)+ - cache_savings_usd: prefix cache discount from provider (separate)+ - cli_tokens_avoided: tokens filtered by rtk (token count only, no $ estimate)++ The hero metric (savings_usd) is ONLY compression savings priced at+ the model's published input rate. Cache and CLI are shown separately.+ This avoids the non-monotonic moving-average repricing bug (#83)."""if cost_stats is None:return None@@ -392,25 +395,11 @@ def _merge_cost_stats(cache_net = cache_stats.get("totals", {}).get("net_savings_usd", 0.0)compression_savings = cost_stats.get("savings_usd", 0.0)- # Estimate CLI filtering savings: tokens_avoided * avg input price- # Use the average input price from the cost tracker if available- cli_savings_usd = 0.0- if cli_tokens_avoided > 0 and LITELLM_AVAILABLE:- # Use a conservative estimate: average across models seen- total_input_cost = cost_stats.get("total_input_cost_usd", 0.0)- total_input_tokens = cost_stats.get("total_input_tokens", 0)- if total_input_tokens > 0:- avg_price_per_token = total_input_cost / total_input_tokens- cli_savings_usd = cli_tokens_avoided * avg_price_per_token-return {**cost_stats,- # savings_usd = Headroom's direct savings only (compression + CLI filtering)- # Cache savings are provider-native and reported separately — NOT added here.- "savings_usd": round(compression_savings + cli_savings_usd, 4),+ "savings_usd": round(compression_savings, 4),"compression_savings_usd": round(compression_savings, 4),"cache_savings_usd": round(cache_net, 4),- "cli_filtering_savings_usd": round(cli_savings_usd, 4),"cli_tokens_avoided": cli_tokens_avoided,}@@ -476,18 +465,13 @@ def _build_session_summary(best_compression = best["savings_pct"]best_detail = f"{best['original']:,} → {best['optimized']:,} tokens"- # Cost summary- # cost_with_headroom = what you actually paid (includes cache discounts)- # cost_without_headroom = counterfactual (with extra tokens at avg effective rate)- # compression_savings = cost_without - cost_with (pure Headroom value)- # cache_savings = provider caching discount (reported separately, NOT additive)+ # Cost summary — savings_usd is compression savings at model list price (monotonic)cost_stats = proxy.cost_tracker.stats() if proxy.cost_tracker else {}cost_with = cost_stats.get("cost_with_headroom_usd", 0.0)- cost_without = cost_stats.get("cost_without_headroom_usd", 0.0)+ compression_savings = cost_stats.get("savings_usd", 0.0)cache_net = prefix_cache_stats.get("totals", {}).get("net_savings_usd", 0.0)- compression_savings = round(cost_without - cost_with, 4) if cost_without > cost_with else 0.0- # Total saved = compression savings only (cache is provider-native, not Headroom's)total_saved_usd = round(compression_savings, 2)+ cost_without = cost_with + compression_savingssavings_pct_cost = round(total_saved_usd / cost_without * 100, 1) if cost_without > 0 else 0.0# Primary models used@@ -1313,30 +1297,18 @@ class CostTracker:cost_with_headroom += model_costtotal_billed_input_tokens += billed_tokens- # Compression counterfactual: value removed tokens at the effective average- # $/input token observed in this tracker (actual spend / billed input tokens),- # not at uncached list price — aligns savings $ with real billing mix (cache- # reads, writes, uncached). Fallback to list-price-per-removed-token when- # there is no billable traffic yet.- if total_billed_input_tokens > 0:- avg_price_per_input_token = cost_with_headroom / total_billed_input_tokens- cost_without_headroom = cost_with_headroom + total_saved * avg_price_per_input_token- else:- cost_without_headroom = 0.0- for model in self._tokens_saved_by_model:- saved = self._tokens_saved_by_model[model]- sent = self._tokens_sent_by_model.get(model, 0)- cr = self._api_cache_read_by_model.get(model, 0)- cw = self._api_cache_write_by_model.get(model, 0)- uncached_tk = self._api_uncached_by_model.get(model, 0)- prices = self._get_cache_prices(model)- if prices:- cr_price, cw_price, uncached_price = prices- if cr + cw + uncached_tk > 0:- model_cost = cr * cr_price + cw * cw_price + uncached_tk * uncached_price- else:- model_cost = sent * uncached_price- cost_without_headroom += model_cost + saved * uncached_price+ # Compression savings: price saved tokens at the model's list input price.+ # This is simple, monotonic, and transparent — each saved token is valued+ # at the published $/token rate for its model. Not affected by cache mix.+ savings_usd = 0.0+ for model in self._tokens_saved_by_model:+ saved = self._tokens_saved_by_model[model]+ if saved <= 0:+ continue+ prices = self._get_cache_prices(model)+ if prices:+ _cr_price, _cw_price, uncached_price = prices+ savings_usd += saved * uncached_pricereturn {"total_tokens_saved": total_saved,@@ -1344,8 +1316,7 @@ class CostTracker:"total_input_cost_usd": round(cost_with_headroom, 4),"per_model": per_model,"cost_with_headroom_usd": round(cost_with_headroom, 4),- "cost_without_headroom_usd": round(cost_without_headroom, 4),- "savings_usd": round(cost_without_headroom - cost_with_headroom, 4),+ "savings_usd": round(savings_usd, 4),}diff --git a/tests/test_cost_tracker_counterfactual.py b/tests/test_cost_tracker_counterfactual.pyindex 3f15e3b1c..2e3ff1c2d 100644--- a/tests/test_cost_tracker_counterfactual.py+++ b/tests/test_cost_tracker_counterfactual.py@@ -1,7 +1,7 @@-"""Tests for CostTracker compression counterfactual (avg $/input token).+"""Tests for CostTracker savings calculation.-Unit tests use LiteLLM pricing only (no network).-Optional live test calls Anthropic once when ANTHROPIC_API_KEY is set (loads .env).+Savings are computed at model list price: saved_tokens * input_cost_per_token.+This is simple, monotonic, and transparent."""from __future__ import annotations@@ -11,7 +11,7 @@ from pathlib import Pathimport pytest-# Load .env for live test (same pattern as test_compression_summary_integration.py)+# Load .env for live test_env_path = Path(__file__).resolve().parent.parent / ".env"if _env_path.exists():for line in _env_path.read_text().splitlines():@@ -24,13 +24,13 @@ if _env_path.exists():pytest.importorskip("litellm")-def test_savings_is_saved_times_average_effective_price_per_token():- """savings_usd = total_tokens_saved * (cost_with / billed_input_tokens)."""+def test_savings_at_list_price():+ """savings_usd = tokens_saved * model list input price."""from headroom.proxy.server import CostTrackerct = CostTracker()model = "claude-sonnet-4-20250514"- # Heavy cache reads + some uncached — average $/token should be well below list price+ct.record_tokens(model,tokens_saved=100_000,@@ -40,93 +40,75 @@ def test_savings_is_saved_times_average_effective_price_per_token():uncached_tokens=50_000,)stats = ct.stats()- cost_with = stats["cost_with_headroom_usd"]- billed = 900_000 + 50_000- avg = cost_with / billed- expected_savings = 100_000 * avg+ # Savings should be 100k tokens * list input price (NOT affected by cache mix)+ import litellm++ resolved = ct._resolve_litellm_model(model)+ info = litellm.model_cost.get(resolved, {})+ list_price = info.get("input_cost_per_token", 0)++ expected = 100_000 * list_priceassert stats["total_tokens_saved"] == 100_000- assert abs(stats["savings_usd"] - expected_savings) < 0.01- assert abs(stats["cost_without_headroom_usd"] - (cost_with + expected_savings)) < 0.01+ assert abs(stats["savings_usd"] - expected) < 0.001-def test_fallback_list_price_when_no_billed_tokens():- """If API never reported billable breakdown, fall back to list price on saved."""+def test_savings_monotonic():+ """Adding more saved tokens always increases savings_usd."""from headroom.proxy.server import CostTrackerct = CostTracker()model = "claude-sonnet-4-20250514"- ct.record_tokens(- model,- tokens_saved=10_000,- tokens_sent=0,- cache_read_tokens=0,- cache_write_tokens=0,- uncached_tokens=0,- )++ ct.record_tokens(model, tokens_saved=10_000, tokens_sent=5_000)+ stats1 = ct.stats()++ ct.record_tokens(model, tokens_saved=10_000, tokens_sent=5_000)+ stats2 = ct.stats()++ assert stats2["savings_usd"] >= stats1["savings_usd"]+ assert stats2["total_tokens_saved"] == 20_000+++def test_savings_zero_when_no_tokens_saved():+ """No tokens saved → savings_usd is 0."""+ from headroom.proxy.server import CostTracker++ ct = CostTracker()+ model = "claude-sonnet-4-20250514"++ ct.record_tokens(model, tokens_saved=0, tokens_sent=5_000)stats = ct.stats()- # No billed tokens → fallback path uses saved * uncached list price- assert stats["cost_with_headroom_usd"] == 0.0++ assert stats["savings_usd"] == 0+ assert stats["total_tokens_saved"] == 0+++def test_multi_model_savings():+ """Savings across multiple models use each model's own list price."""+ from headroom.proxy.server import CostTracker++ ct = CostTracker()++ ct.record_tokens("claude-sonnet-4-20250514", tokens_saved=50_000, tokens_sent=10_000)+ ct.record_tokens("claude-haiku-4-5-20251001", tokens_saved=50_000, tokens_sent=10_000)++ stats = ct.stats()++ # Haiku is cheaper than Sonnet, so same tokens saved → different $+ assert stats["total_tokens_saved"] == 100_000assert stats["savings_usd"] > 0- assert stats["cost_without_headroom_usd"] == stats["savings_usd"]+ # Verify per-model breakdown exists+ assert len(stats["per_model"]) == 2- not os.environ.get("ANTHROPIC_API_KEY"),- reason="ANTHROPIC_API_KEY not set — skipping live Anthropic test",-)-def test_live_anthropic_usage_roundtrip_with_cost_tracker():- """One real Messages call; feed usage into CostTracker and verify accounting."""- import httpx+def test_no_cost_without_headroom_field():+ """cost_without_headroom_usd should NOT be in stats (removed to avoid confusion)."""from headroom.proxy.server import CostTracker- api_key = os.environ["ANTHROPIC_API_KEY"]- model = "claude-sonnet-4-20250514"- resp = httpx.post(- "https://api.anthropic.com/v1/messages",- headers={- "x-api-key": api_key,- "anthropic-version": "2023-06-01",- "content-type": "application/json",- },- json={- "model": model,- "max_tokens": 32,- "messages": [{"role": "user", "content": "Reply with exactly: ok"}],- },- timeout=60.0,- )- resp.raise_for_status()- data = resp.json()- assert "usage" in data, "Anthropic response should include usage"- usage = data.get("usage") or {}- cr = int(usage.get("cache_read_input_tokens") or 0)- cw_tok = int(usage.get("cache_creation_input_tokens") or 0)- unc = int(usage.get("input_tokens") or 0)-- saved = 25_000- sent = 12_000ct = CostTracker()- ct.record_tokens(- model,- tokens_saved=saved,- tokens_sent=sent,- cache_read_tokens=cr,- cache_write_tokens=cw_tok,- uncached_tokens=unc,- )+ ct.record_tokens("claude-sonnet-4-20250514", tokens_saved=10_000, tokens_sent=5_000)stats = ct.stats()- cost_with = stats["cost_with_headroom_usd"]- cost_without = stats["cost_without_headroom_usd"]- savings = stats["savings_usd"]- assert abs((cost_without - cost_with) - savings) < 0.001-- # Average-price path: billed input tokens got a non-zero LiteLLM cost- billed = cr + cw_tok + unc if (cr + cw_tok + unc) > 0 else sent- if cost_with > 1e-6 and billed > 0:- expected = saved * (cost_with / billed)- assert abs(savings - expected) < 0.05- else:- # Fallback path (no billable token cost computed) — still self-consistent above- assert savings >= 0++ assert "cost_without_headroom_usd" not in stats