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(providers): isolate resolved Anthropic context limits (#4593)
emme1t51258ef14a98
diff --git a/headroom/providers/anthropic.py b/headroom/providers/anthropic.pyindex 1370f0463..5ed71c2a2 100644--- a/headroom/providers/anthropic.py+++ b/headroom/providers/anthropic.py@@ -811,6 +811,10 @@ class AnthropicProvider(Provider):if context_limits:self._context_limits.update(context_limits)+ # Dynamically resolved limits belong to an exact model id. Keep them+ # separate from the configured entries used for release/alias matching.+ self._context_limit_cache: dict[str, int] = {}+@propertydef name(self) -> str:return "anthropic"@@ -856,6 +860,8 @@ class AnthropicProvider(Provider):# Check explicit and loaded limitsif model in self._context_limits:return self._context_limits[model]+ if model in self._context_limit_cache:+ return self._context_limit_cache[model]# Releases and aliases of a known id (e.g. "claude-3-5-sonnet" matches# "claude-3-5-sonnet-20241022"); see `_is_release_of`.@@ -871,11 +877,11 @@ class AnthropicProvider(Provider):if info:if "max_input_tokens" in info and info["max_input_tokens"] is not None:limit = int(info["max_input_tokens"])- self._context_limits[model] = limit+ self._context_limit_cache[model] = limitreturn limitif "max_tokens" in info and info["max_tokens"] is not None:limit = int(info["max_tokens"])- self._context_limits[model] = limit+ self._context_limit_cache[model] = limitreturn limitexcept Exception as e:logger.debug(f"LiteLLM get_model_info failed for {model}: {e}")@@ -886,20 +892,20 @@ class AnthropicProvider(Provider):limit = cast(int, _PATTERN_DEFAULTS[tier]["context"])self._warn_unknown_model(model, limit, f"inferred from '{tier}' tier")# Cache for future calls- self._context_limits[model] = limit+ self._context_limit_cache[model] = limitreturn limit# Fallback for unknown Claude modelsif model.startswith("claude"):limit = cast(int, _UNKNOWN_CLAUDE_DEFAULT["context"])self._warn_unknown_model(model, limit, "using default Claude limit")- self._context_limits[model] = limit+ self._context_limit_cache[model] = limitreturn limit# Non-Claude model - use conservative defaultlimit = 128000self._warn_unknown_model(model, limit, "unknown provider, using conservative default")- self._context_limits[model] = limit+ self._context_limit_cache[model] = limitreturn limitdef _warn_unknown_model(self, model: str, limit: int, reason: str) -> None:@@ -916,7 +922,7 @@ class AnthropicProvider(Provider):def supports_model(self, model: str) -> bool:"""Check if this provider supports the given model."""model = sanitize_anthropic_model_id(model)- if model in self._context_limits:+ if model in self._context_limits or model in self._context_limit_cache:return True# Check prefix matches - support all Claude modelsreturn model.startswith("claude")diff --git a/tests/test_providers/test_anthropic.py b/tests/test_providers/test_anthropic.pyindex 37f122bb7..78fc0e21b 100644--- a/tests/test_providers/test_anthropic.py+++ b/tests/test_providers/test_anthropic.py@@ -3,6 +3,73 @@import pytest+class TestContextLimitCache:+ @pytest.mark.parametrize("metadata_field", ["max_input_tokens", "max_tokens"])+ @pytest.mark.parametrize(+ ("first", "second", "metadata", "expected"),+ [+ ("gpt-4", "gpt-4-turbo", {"gpt-4": 8192, "gpt-4-turbo": 128000}, (8192, 128000)),+ ("gpt-4-turbo", "gpt-4", {"gpt-4": 8192, "gpt-4-turbo": 128000}, (128000, 8192)),+ ("gateway", "gateway-large", {"gateway-large": 1000000}, (128000, 1000000)),+ ("gateway", "gateway-unknown", {"gateway": 64000}, (64000, 128000)),+ (+ "claude-future-sonnet",+ "claude-future-sonnet-extended",+ {"claude-future-sonnet-extended": 1000000},+ (200000, 1000000),+ ),+ ("gateway", "gateway-sonnet", {}, (128000, 200000)),+ (+ "claude-future",+ "claude-future-long",+ {"claude-future-long": 640000},+ (200000, 640000),+ ),+ (+ "gateway-20260101",+ "gateway",+ {"gateway-20260101": 64000, "gateway": 128000},+ (64000, 128000),+ ),+ ],+ )+ def test_each_model_keeps_its_own_resolved_limit(+ self, monkeypatch, first, second, metadata, expected, metadata_field+ ):+ import headroom.providers.anthropic as anthropic_module++ lookups = []++ def get_model_info(model):+ lookups.append(model)+ return {metadata_field: metadata[model]} if model in metadata else None++ monkeypatch.setattr(+ anthropic_module, "_get_litellm_clients", lambda: (None, get_model_info)+ )+ provider = anthropic_module.AnthropicProvider(warn=False)++ assert (provider.get_context_limit(first), provider.get_context_limit(second)) == expected+ assert (provider.get_context_limit(first), provider.get_context_limit(second)) == expected+ assert lookups == [first, second]+ assert provider.supports_model(first)+ assert provider.supports_model(second)++ def test_configured_aliases_and_1m_suffix_keep_their_limits(self, monkeypatch):+ import headroom.providers.anthropic as anthropic_module++ monkeypatch.setattr(anthropic_module, "_get_litellm_clients", lambda: (None, None))+ provider = anthropic_module.AnthropicProvider(+ context_limits={"gateway": 64000, "gateway-exact": 96000}, warn=False+ )++ assert provider.get_context_limit("gateway-20260101") == 64000+ assert provider.get_context_limit("gateway-exact") == 96000+ assert provider.get_context_limit("gateway[1m]") == 1000000+ assert provider.get_context_limit("gateway") == 64000+ assert provider.get_context_limit("claude-sonnet-4-5-20250929") == 200000++class TestAnthropicModelSanitization:def test_sanitize_model_id_removes_ansi_escape_sequences(self):from headroom.providers.anthropic import sanitize_anthropic_model_id