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
refactor(pricing): isolate litellm model resolution (#1936)
JD Davis4210d6e60954
diff --git a/headroom/pricing/litellm_model_resolution.py b/headroom/pricing/litellm_model_resolution.pynew file mode 100644index 000000000..dd1870e8a--- /dev/null+++ b/headroom/pricing/litellm_model_resolution.py@@ -0,0 +1,88 @@+"""Pure LiteLLM model-name resolution rules."""++from __future__ import annotations++from collections.abc import Callable+from dataclasses import dataclass+++@dataclass(frozen=True, slots=True)+class LiteLLMModelPrefixRule:+ """Case-insensitive bare-model prefix mapping to a LiteLLM provider key."""++ model_prefix: str+ provider_prefix: str++ def candidate_for(self, model: str) -> str | None:+ if model.lower().startswith(self.model_prefix):+ return f"{self.provider_prefix}{model}"+ return None+++# Aliases for models removed from LiteLLM's cost database (retired/renamed).+# Maps old model name -> current LiteLLM key that has equivalent pricing.+MODEL_ALIASES: dict[str, str] = {+ # Claude 3.5 Sonnet retired Feb 2026, pricing same as claude-sonnet-4-20250514+ "claude-3-5-sonnet-20241022": "claude-sonnet-4-20250514",+ "claude-3-5-sonnet-20240620": "claude-sonnet-4-20250514",+ # Claude 3 Sonnet retired+ "claude-3-sonnet-20240229": "claude-3-haiku-20240307",+}+++MODEL_PREFIX_RULES: tuple[LiteLLMModelPrefixRule, ...] = (+ LiteLLMModelPrefixRule("claude-", "anthropic/"),+ LiteLLMModelPrefixRule("gpt-", "openai/"),+ LiteLLMModelPrefixRule("o1-", "openai/"),+ LiteLLMModelPrefixRule("o3-", "openai/"),+ LiteLLMModelPrefixRule("o4-", "openai/"),+ LiteLLMModelPrefixRule("gemini-", "google/"),+ LiteLLMModelPrefixRule("minimax-", "minimax/"),+ LiteLLMModelPrefixRule("deepseek-", "deepseek/"),+)+++PRICE_LOOKUP_PROVIDER_PREFIXES: tuple[str, ...] = (+ "openai/",+ "anthropic/",+ "google/",+ "mistral/",+ "deepseek/",+ "minimax/",+)+++def resolution_candidates(model: str) -> tuple[str, ...]:+ """Return ordered LiteLLM keys to try for cost-per-token resolution."""+ candidates = [model]+ candidates.extend(+ candidate+ for rule in MODEL_PREFIX_RULES+ for candidate in (rule.candidate_for(model),)+ if candidate is not None+ )+ alias = MODEL_ALIASES.get(model)+ if alias:+ candidates.append(alias)+ return tuple(dict.fromkeys(candidates))+++def pricing_lookup_candidates(model: str) -> tuple[str, ...]:+ """Return ordered LiteLLM model_cost keys to try for pricing lookup."""+ candidates = [model]+ candidates.extend(f"{prefix}{model}" for prefix in PRICE_LOOKUP_PROVIDER_PREFIXES)+ alias = MODEL_ALIASES.get(model)+ if alias:+ candidates.append(alias)+ return tuple(dict.fromkeys(candidates))+++def resolve_litellm_model_name(+ model: str,+ is_known_model: Callable[[str], bool],+) -> str:+ """Resolve ``model`` to the first candidate accepted by LiteLLM."""+ for candidate in resolution_candidates(model):+ if is_known_model(candidate):+ return candidate+ return modeldiff --git a/headroom/pricing/litellm_pricing.py b/headroom/pricing/litellm_pricing.pyindex dff7c429a..6eb19c30c 100644--- a/headroom/pricing/litellm_pricing.py+++ b/headroom/pricing/litellm_pricing.py@@ -11,6 +11,11 @@ from __future__ import annotationsfrom dataclasses import dataclassfrom typing import Any+from headroom.pricing.litellm_model_resolution import (+ pricing_lookup_candidates,+ resolve_litellm_model_name,+)+# litellm calls `dotenv.load_dotenv()` during its own import, which loads# the project `.env` into `os.environ`. We don't want that side effect —# importing a pricing helper should not silently leak API keys into the@@ -33,16 +38,6 @@ except ImportError:litellm = None # type: ignore[assignment]LITELLM_AVAILABLE = False-# Aliases for models removed from LiteLLM's cost database (retired/renamed).-# Maps old model name -> current LiteLLM key that has equivalent pricing.-_MODEL_ALIASES: dict[str, str] = {- # Claude 3.5 Sonnet retired Feb 2026, pricing same as claude-sonnet-4-20250514- "claude-3-5-sonnet-20241022": "claude-sonnet-4-20250514",- "claude-3-5-sonnet-20240620": "claude-sonnet-4-20250514",- # Claude 3 Sonnet retired- "claude-3-sonnet-20240229": "claude-3-haiku-20240307",-}-_resolved_model_cache: dict[str, str] = {}@@ -62,36 +57,15 @@ def _resolve_litellm_model_uncached(model: str) -> str:"""Uncached resolution — called once per unique model name."""if not LITELLM_AVAILABLE:return model- # Try as-is first- try:- litellm.cost_per_token(model=model, prompt_tokens=1, completion_tokens=0)- return model- except Exception:- pass- # Try with provider prefix- prefixes = {- "claude-": "anthropic/",- "gpt-": "openai/",- "o1-": "openai/",- "o3-": "openai/",- "o4-": "openai/",- "gemini-": "google/",- "minimax-": "minimax/",- "deepseek-": "deepseek/",- }- # Case-insensitive prefix match: MiniMax uses mixed-case model- # names like "MiniMax-M3" (capital M's); we shouldn't require the- # user to lower-case their config to match.- model_lower = model.lower()- for pattern, prefix in prefixes.items():- if model_lower.startswith(pattern):- prefixed = f"{prefix}{model}"- try:- litellm.cost_per_token(model=prefixed, prompt_tokens=1, completion_tokens=0)- return prefixed- except Exception:- break- return model++ def is_known_model(candidate: str) -> bool:+ try:+ litellm.cost_per_token(model=candidate, prompt_tokens=1, completion_tokens=0)+ return True+ except Exception:+ return False++ return resolve_litellm_model_name(model, is_known_model)def _register_minimax_pricing() -> None:@@ -160,21 +134,11 @@ def get_model_pricing(model: str) -> LiteLLMModelPricing | None:return Nonecost_data = litellm.model_cost- # Try exact match first- info = cost_data.get(model)-- # Try common provider prefixes if not found- if info is None:- for prefix in ["openai/", "anthropic/", "google/", "mistral/", "deepseek/"]:- if f"{prefix}{model}" in cost_data:- info = cost_data[f"{prefix}{model}"]- break-- # Try retired/renamed model aliases (LiteLLM removes old model keys over time)- if info is None:- alias = _MODEL_ALIASES.get(model)- if alias:- info = cost_data.get(alias)+ info = None+ for candidate in pricing_lookup_candidates(model):+ info = cost_data.get(candidate)+ if info is not None:+ breakif info is None:return Nonediff --git a/tests/test_pricing_litellm_model_resolution.py b/tests/test_pricing_litellm_model_resolution.pynew file mode 100644index 000000000..50842b7b3--- /dev/null+++ b/tests/test_pricing_litellm_model_resolution.py@@ -0,0 +1,47 @@+from __future__ import annotations++from headroom.pricing.litellm_model_resolution import (+ MODEL_ALIASES,+ LiteLLMModelPrefixRule,+ pricing_lookup_candidates,+ resolution_candidates,+ resolve_litellm_model_name,+)+++def test_prefix_rule_matches_case_insensitively() -> None:+ rule = LiteLLMModelPrefixRule("minimax-", "minimax/")++ assert rule.candidate_for("MiniMax-M3") == "minimax/MiniMax-M3"+ assert rule.candidate_for("gpt-4o") is None+++def test_resolution_candidates_try_bare_then_matching_prefix_then_alias() -> None:+ assert resolution_candidates("gpt-4o") == ("gpt-4o", "openai/gpt-4o")+ assert resolution_candidates("MiniMax-M3") == ("MiniMax-M3", "minimax/MiniMax-M3")++ retired = "claude-3-5-sonnet-20241022"+ assert resolution_candidates(retired) == (+ retired,+ f"anthropic/{retired}",+ MODEL_ALIASES[retired],+ )+++def test_pricing_lookup_candidates_include_provider_prefixes_and_aliases() -> None:+ candidates = pricing_lookup_candidates("claude-3-5-sonnet-20241022")++ assert candidates[0] == "claude-3-5-sonnet-20241022"+ assert "anthropic/claude-3-5-sonnet-20241022" in candidates+ assert "minimax/claude-3-5-sonnet-20241022" in candidates+ assert candidates[-1] == MODEL_ALIASES["claude-3-5-sonnet-20241022"]+++def test_resolve_litellm_model_name_returns_first_known_candidate() -> None:+ known = {"openai/gpt-4o"}++ assert resolve_litellm_model_name("gpt-4o", known.__contains__) == "openai/gpt-4o"+++def test_resolve_litellm_model_name_returns_original_when_unknown() -> None:+ assert resolve_litellm_model_name("mystery-model", lambda _: False) == "mystery-model"