Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

feat: declarative fallback generalizations for unknown models (#29718)

Mateo Wangb76a85882637
diff --git a/litellm/litellm_core_utils/fallback_generalizations.py b/litellm/litellm_core_utils/fallback_generalizations.py
new file mode 100644
index 00000000000..abc171f900a
--- /dev/null
+++ b/litellm/litellm_core_utils/fallback_generalizations.py
@@ -0,0 +1,141 @@
+"""
+Declarative fallback generalizations for unknown / newly-released models.
+
+The ``fallback_generalizations`` block in ``model_prices_and_context_window.json``
+holds an ordered list of rules. Each rule pairs a single case-insensitive regex
+with the metadata to apply when a model name has no exact entry in the cost map.
+The metadata is a partial cost-map entry: ``litellm_provider`` drives provider
+routing, and the remaining fields (``mode``, ``supports_*``, context window,
+pricing, ...) drive ``get_model_info`` / ``supports_*``.
+
+Precedence: rules are evaluated in file order and the first match wins. They are
+consulted only after exact and case-insensitive lookups miss, so an exact entry
+always takes precedence over a rule.
+
+Patterns are matched case-insensitively with ``re.search`` and are not implicitly
+anchored: a rule must include ``^`` and ``$`` (as the shipped rules do) to bind to
+the whole model name, otherwise it matches as a substring. Keeping anchoring in the
+regex makes the rule the single, self-contained source of truth for what it matches.
+
+A rule may set ``extends`` to the ``name`` of another rule to inherit that rule's
+``model_info``; the rule's own ``model_info`` overrides the inherited keys, so a
+narrow rule (for example a version-gated capability flag) carries only its delta
+instead of duplicating the parent's pricing block. Inheritance is resolved once,
+at install time, against each rule's raw (unresolved) ``model_info``; it is a
+single level (a parent that itself extends is not chained).
+
+Any other keys on a rule (for example a free-text ``description`` documenting what
+the regex matches) are ignored by the engine and exist only for the reader.
+
+The compiled-regex list is built once and cached. ``match_fallback_generalization``
+is O(number of rules); callers must only invoke it on a cache miss.
+"""
+
+import re
+from typing import Optional
+
+from litellm._logging import verbose_logger
+
+NAME_FIELD = "name"
+PATTERN_FIELD = "pattern"
+MODEL_INFO_FIELD = "model_info"
+EXTENDS_FIELD = "extends"
+
+
+def _resolve_extends(rules: list) -> list:
+ """Expand ``extends`` inheritance so each rule's ``model_info`` is self-contained.
+
+ A rule with ``extends: <name>`` is rewritten with ``model_info`` set to the parent's
+ ``model_info`` overlaid by its own. Resolution is single-level and uses each rule's
+ raw ``model_info`` as the parent source. Non-dict rules and dangling parents are
+ passed through unchanged.
+ """
+ base_by_name = {
+ rule[NAME_FIELD]: rule[MODEL_INFO_FIELD]
+ for rule in rules
+ if isinstance(rule, dict)
+ and isinstance(rule.get(NAME_FIELD), str)
+ and isinstance(rule.get(MODEL_INFO_FIELD), dict)
+ }
+
+ def resolved(rule: dict) -> dict:
+ parent_name = rule.get(EXTENDS_FIELD)
+ own_info = rule.get(MODEL_INFO_FIELD)
+ parent_info = base_by_name.get(parent_name) if isinstance(parent_name, str) else None
+ if parent_info is None or not isinstance(own_info, dict):
+ return rule
+ return {**rule, MODEL_INFO_FIELD: {**parent_info, **own_info}}
+
+ return [resolved(rule) if isinstance(rule, dict) else rule for rule in rules]
+
+
+class _FallbackGeneralizations:
+ """Holds the active rule list and its lazily-compiled regex cache."""
+
+ def __init__(self) -> None:
+ self.rules: list[dict] = []
+ self._compiled: Optional[list[tuple[re.Pattern, dict]]] = None
+
+ def set_rules(self, rules: Optional[list[dict]]) -> None:
+ self.rules = rules if isinstance(rules, list) else []
+ self._compiled = None
+
+ def _compile(self) -> list[tuple[re.Pattern, dict]]:
+ compiled: list[tuple[re.Pattern, dict]] = []
+ for rule in self.rules:
+ if not isinstance(rule, dict):
+ continue
+ pattern = rule.get(PATTERN_FIELD)
+ model_info = rule.get(MODEL_INFO_FIELD)
+ if not isinstance(pattern, str) or not isinstance(model_info, dict):
+ verbose_logger.warning(
+ "LiteLLM: skipping malformed fallback generalization rule %s (needs string '%s' and dict '%s').",
+ rule.get("name", pattern),
+ PATTERN_FIELD,
+ MODEL_INFO_FIELD,
+ )
+ continue
+ try:
+ compiled.append((re.compile(pattern, re.IGNORECASE), model_info))
+ except re.error as e:
+ verbose_logger.warning(
+ "LiteLLM: skipping fallback generalization rule with invalid regex %r: %s",
+ pattern,
+ e,
+ )
+ return compiled
+
+ def match(self, model: str) -> Optional[dict]:
+ if not model:
+ return None
+ if self._compiled is None:
+ self._compiled = self._compile()
+ for pattern, model_info in self._compiled:
+ if pattern.search(model) is not None:
+ return dict(model_info)
+ return None
+
+
+_registry = _FallbackGeneralizations()
+
+
+def set_fallback_generalizations(rules: Optional[list[dict]]) -> None:
+ """Install the active rule list and invalidate the compiled-regex cache.
+
+ ``extends`` inheritance is resolved here, once, before the rules are stored.
+ Called once when the model cost map is loaded (and again on any reload).
+ """
+ _registry.set_rules(_resolve_extends(rules) if isinstance(rules, list) else rules)
+
+
+def get_fallback_generalization_rules() -> list[dict]:
+ """Return the raw rule list (read-only view for callers/tests)."""
+ return _registry.rules
+
+
+def match_fallback_generalization(model: str) -> Optional[dict]:
+ """Return the ``model_info`` of the first rule whose regex matches ``model``.
+
+ O(number of rules). Only call this once exact lookups have missed.
+ """
+ return _registry.match(model)
diff --git a/litellm/litellm_core_utils/get_llm_provider_logic.py b/litellm/litellm_core_utils/get_llm_provider_logic.py
index 76ca268a883..122d09c855b 100644
--- a/litellm/litellm_core_utils/get_llm_provider_logic.py
+++ b/litellm/litellm_core_utils/get_llm_provider_logic.py
@@ -1,9 +1,11 @@
-import re
from typing import Optional, Tuple, cast
from urllib.parse import urlparse
import litellm
from litellm.constants import REPLICATE_MODEL_NAME_WITH_ID_LENGTH
+from litellm.litellm_core_utils.fallback_generalizations import (
+ match_fallback_generalization,
+)
from litellm.llms.openai_like.json_loader import JSONProviderRegistry
from litellm.secret_managers.main import get_secret, get_secret_str
@@ -69,25 +71,6 @@ def _is_azure_claude_model(model: str) -> bool:
return False
-_CLAUDE_PATTERN = re.compile(r"^claude-[a-z]+-\d+-\d+(?:-\d{8})?$", re.IGNORECASE)
-
-
-def _matches_claude_model_pattern(model: str) -> bool:
- """
- Check if a model string matches the Claude model naming pattern.
-
- Matches patterns like:
- - claude-opus-4-7
- - claude-sonnet-4-6
- - claude-haiku-4-5
- - claude-opus-5-1-20270101 (with optional date suffix)
-
- This allows future Claude models to be routed to the Anthropic provider
- without requiring updates to model_prices_and_context_window.json.
- """
- return _CLAUDE_PATTERN.match(model) is not None
-
-
def handle_cohere_chat_model_custom_llm_provider(
model: str, custom_llm_provider: Optional[str] = None
) -> Tuple[str, Optional[str]]:
@@ -391,9 +374,6 @@ def get_llm_provider(
custom_llm_provider = "anthropic_text"
else:
custom_llm_provider = "anthropic"
- ## anthropic - pattern-based matching for future Claude models
- elif _matches_claude_model_pattern(model):
- custom_llm_provider = "anthropic"
## cohere
elif model in litellm.cohere_models or model in litellm.cohere_embedding_models:
custom_llm_provider = "cohere"
@@ -487,6 +467,15 @@ def get_llm_provider(
custom_llm_provider = "amazon_nova"
elif model.startswith("sap/"):
custom_llm_provider = "sap"
+
+ # Last resort for an otherwise-unknown model: a declarative
+ # fallback-generalization rule (e.g. routes future claude-* to anthropic).
+ # Exact provider matches above always win; this only runs on a miss.
+ if not custom_llm_provider:
+ generalization = match_fallback_generalization(model)
+ if generalization is not None:
+ custom_llm_provider = generalization.get("litellm_provider") or None
+
if not custom_llm_provider:
if litellm.suppress_debug_info is False:
print() # noqa: T201
diff --git a/litellm/litellm_core_utils/get_model_cost_map.py b/litellm/litellm_core_utils/get_model_cost_map.py
index 9126c35f818..4c0a01ad645 100644
--- a/litellm/litellm_core_utils/get_model_cost_map.py
+++ b/litellm/litellm_core_utils/get_model_cost_map.py
@@ -20,6 +20,20 @@ from litellm.constants import (
MODEL_COST_MAP_MAX_SHRINK_RATIO,
MODEL_COST_MAP_MIN_MODEL_COUNT,
)
+from litellm.litellm_core_utils.fallback_generalizations import (
+ set_fallback_generalizations,
+)
+
+FALLBACK_GENERALIZATIONS_KEY = "fallback_generalizations"
+
+# Reserved top-level keys that are not model entries. They must be excluded
+# from the model-count integrity check so a real upstream shrink can't be masked.
+RESERVED_TOP_LEVEL_KEYS = frozenset({"sample_spec", FALLBACK_GENERALIZATIONS_KEY})
+
+
+def _count_model_entries(model_cost: dict) -> int:
+ """Count actual model entries, excluding reserved meta keys."""
+ return sum(1 for key in model_cost if key not in RESERVED_TOP_LEVEL_KEYS)
class GetModelCostMap:
@@ -46,7 +60,7 @@ class GetModelCostMap:
"""Return the number of models in the local backup (cached int)."""
if cls._backup_model_count < 0:
backup = cls.load_local_model_cost_map()
- cls._backup_model_count = len(backup)
+ cls._backup_model_count = _count_model_entries(backup)
return cls._backup_model_count
@staticmethod
@@ -76,7 +90,7 @@ class GetModelCostMap:
max_shrink_ratio: float = MODEL_COST_MAP_MAX_SHRINK_RATIO,
) -> bool:
"""Check 2: model count has not reduced significantly vs backup."""
- fetched_count = len(fetched_map)
+ fetched_count = _count_model_entries(fetched_map)
if fetched_count < min_model_count:
verbose_logger.warning(
@@ -234,6 +248,18 @@ def _expand_model_aliases(model_cost: dict) -> dict:
return model_cost
+def _finalize_model_cost_map(model_cost: dict) -> dict:
+ """Extract fallback generalizations out of the raw map, then expand aliases.
+
+ The ``fallback_generalizations`` block is installed into the generalizations
+ module and removed from the map so it is never treated as a model entry.
+ """
+ raw = model_cost.pop(FALLBACK_GENERALIZATIONS_KEY, None)
+ rules = raw.get("rules") if isinstance(raw, dict) else None
+ set_fallback_generalizations(rules)
+ return _expand_model_aliases(model_cost)
+
+
def get_model_cost_map(url: str) -> dict:
"""
Public entry point — returns the model cost map dict.
@@ -253,7 +279,7 @@ def get_model_cost_map(url: str) -> dict:
_cost_map_source_info.url = None
_cost_map_source_info.is_env_forced = True
_cost_map_source_info.fallback_reason = None
- return _expand_model_aliases(GetModelCostMap.load_local_model_cost_map())
+ return _finalize_model_cost_map(GetModelCostMap.load_local_model_cost_map())
_cost_map_source_info.url = url
_cost_map_source_info.is_env_forced = False
@@ -268,7 +294,7 @@ def get_model_cost_map(url: str) -> dict:
)
_cost_map_source_info.source = "local"
_cost_map_source_info.fallback_reason = f"Remote fetch failed: {str(e)}"
- return _expand_model_aliases(GetModelCostMap.load_local_model_cost_map())
+ return _finalize_model_cost_map(GetModelCostMap.load_local_model_cost_map())
# Validate using cached count (cheap int comparison, no file I/O)
if not GetModelCostMap.validate_model_cost_map(
@@ -281,8 +307,8 @@ def get_model_cost_map(url: str) -> dict:
)
_cost_map_source_info.source = "local"
_cost_map_source_info.fallback_reason = "Remote data failed integrity validation"
- return _expand_model_aliases(GetModelCostMap.load_local_model_cost_map())
+ return _finalize_model_cost_map(GetModelCostMap.load_local_model_cost_map())
_cost_map_source_info.source = "remote"
_cost_map_source_info.fallback_reason = None
- return _expand_model_aliases(content)
+ return _finalize_model_cost_map(content)
diff --git a/litellm/llms/anthropic/common_utils.py b/litellm/llms/anthropic/common_utils.py
index 721fcae4c08..db540e5441d 100644
--- a/litellm/llms/anthropic/common_utils.py
+++ b/litellm/llms/anthropic/common_utils.py
@@ -375,10 +375,10 @@ class AnthropicModelInfo(BaseLLMModelInfo):
def _is_adaptive_thinking_model(model: str) -> bool:
"""Whether ``model`` uses adaptive thinking (``output_config.effort``).
- Sourced solely from the model cost map's ``supports_adaptive_thinking`` flag,
- resolved through provider prefixes. A model that resolves to no mapped entry
- (an unmapped alias or a future release not yet in the map) is treated as
- non-adaptive until a ``fallback_generalizations`` rule covers it.
+ The model cost map is authoritative: an explicit ``supports_adaptive_thinking``
+ entry, or a ``fallback_generalizations`` rule for unknown Claude models. The
+ version gate (>= 4.6, including provider-prefixed Bedrock/Vertex ids that map to
+ no exact entry) lives entirely in that declarative rule, not here.
"""
return AnthropicModelInfo._supports_model_capability(model, "supports_adaptive_thinking")
diff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.json
index b60c6e71867..21132db93cb 100644
--- a/litellm/model_prices_and_context_window_backup.json
+++ b/litellm/model_prices_and_context_window_backup.json
@@ -994,6 +994,7 @@
"bedrock_output_config_effort_ceiling": "high"
},
"anthropic.claude-opus-4-6-v1": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.25e-06,
"cache_creation_input_token_cost_above_1hr": 1e-05,
"cache_read_input_token_cost": 5e-07,
@@ -1025,6 +1026,7 @@
"bedrock_output_config_effort_ceiling": "max"
},
"global.anthropic.claude-opus-4-6-v1": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.25e-06,
"cache_creation_input_token_cost_above_1hr": 1e-05,
"cache_read_input_token_cost": 5e-07,
@@ -1056,6 +1058,7 @@
"bedrock_output_config_effort_ceiling": "max"
},
"us.anthropic.claude-opus-4-6-v1": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.875e-06,
"cache_creation_input_token_cost_above_1hr": 1.1e-05,
"cache_read_input_token_cost": 5.5e-07,
@@ -1087,6 +1090,7 @@
"bedrock_output_config_effort_ceiling": "max"
},
"eu.anthropic.claude-opus-4-6-v1": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.875e-06,
"cache_creation_input_token_cost_above_1hr": 1.1e-05,
"cache_read_input_token_cost": 5.5e-07,
@@ -1118,6 +1122,7 @@
"bedrock_output_config_effort_ceiling": "max"
},
"au.anthropic.claude-opus-4-6-v1": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.875e-06,
"cache_creation_input_token_cost_above_1hr": 1.1e-05,
"cache_read_input_token_cost": 5.5e-07,
@@ -1149,6 +1154,7 @@
"bedrock_output_config_effort_ceiling": "max"
},
"anthropic.claude-opus-4-7": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.25e-06,
"cache_creation_input_token_cost_above_1hr": 1e-05,
"cache_read_input_token_cost": 5e-07,
@@ -1197,6 +1203,7 @@
"supports_output_config": true
},
"global.anthropic.claude-opus-4-7": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.25e-06,
"cache_creation_input_token_cost_above_1hr": 1e-05,
"cache_read_input_token_cost": 5e-07,
@@ -1230,6 +1237,7 @@
"bedrock_output_config_effort_ceiling": "xhigh"
},
"us.anthropic.claude-opus-4-7": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.875e-06,
"cache_creation_input_token_cost_above_1hr": 1.1e-05,
"cache_read_input_token_cost": 5.5e-07,
@@ -1263,6 +1271,7 @@
"bedrock_output_config_effort_ceiling": "xhigh"
},
"eu.anthropic.claude-opus-4-7": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.875e-06,
"cache_creation_input_token_cost_above_1hr": 1.1e-05,
"cache_read_input_token_cost": 5.5e-07,
@@ -1296,6 +1305,7 @@
"bedrock_output_config_effort_ceiling": "xhigh"
},
"au.anthropic.claude-opus-4-7": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.875e-06,
"cache_creation_input_token_cost_above_1hr": 1.1e-05,
"cache_read_input_token_cost": 5.5e-07,
@@ -1461,6 +1471,7 @@
"bedrock_output_config_effort_ceiling": "xhigh"
},
"anthropic.claude-opus-4-8": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.25e-06,
"cache_creation_input_token_cost_above_1hr": 1e-05,
"cache_read_input_token_cost": 5e-07,
@@ -1494,6 +1505,7 @@
"bedrock_output_config_effort_ceiling": "xhigh"
},
"global.anthropic.claude-opus-4-8": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.25e-06,
"cache_creation_input_token_cost_above_1hr": 1e-05,
"cache_read_input_token_cost": 5e-07,
@@ -1527,6 +1539,7 @@
"bedrock_output_config_effort_ceiling": "xhigh"
},
"us.anthropic.claude-opus-4-8": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.875e-06,
"cache_creation_input_token_cost_above_1hr": 1.1e-05,
"cache_read_input_token_cost": 5.5e-07,
@@ -1560,6 +1573,7 @@
"bedrock_output_config_effort_ceiling": "xhigh"
},
"eu.anthropic.claude-opus-4-8": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.875e-06,
"cache_creation_input_token_cost_above_1hr": 1.1e-05,
"cache_read_input_token_cost": 5.5e-07,
@@ -1593,6 +1607,7 @@
"bedrock_output_config_effort_ceiling": "xhigh"
},
"au.anthropic.claude-opus-4-8": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.875e-06,
"cache_creation_input_token_cost_above_1hr": 1.1e-05,
"cache_read_input_token_cost": 5.5e-07,
@@ -1657,6 +1672,7 @@
"supports_minimal_reasoning_effort": true
},
"anthropic.claude-sonnet-4-6": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 3.75e-06,
"cache_creation_input_token_cost_above_1hr": 6e-06,
"cache_read_input_token_cost": 3e-07,
@@ -1687,6 +1703,7 @@
"supports_output_config": true
},
"global.anthropic.claude-sonnet-4-6": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 3.75e-06,
"cache_creation_input_token_cost_above_1hr": 6e-06,
"cache_read_input_token_cost": 3e-07,
@@ -1717,6 +1734,7 @@
"supports_output_config": true
},
"us.anthropic.claude-sonnet-4-6": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 4.125e-06,
"cache_creation_input_token_cost_above_1hr": 6.6e-06,
"cache_read_input_token_cost": 3.3e-07,
@@ -1747,6 +1765,7 @@
"supports_output_config": true
},
"eu.anthropic.claude-sonnet-4-6": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 4.125e-06,
"cache_creation_input_token_cost_above_1hr": 6.6e-06,
"cache_read_input_token_cost": 3.3e-07,
@@ -1777,6 +1796,7 @@
"supports_output_config": true
},
"au.anthropic.claude-sonnet-4-6": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 4.125e-06,
"cache_creation_input_token_cost_above_1hr": 6.6e-06,
"cache_read_input_token_cost": 3.3e-07,
@@ -1807,6 +1827,7 @@
"supports_output_config": true
},
"jp.anthropic.claude-sonnet-4-6": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 4.125e-06,
"cache_creation_input_token_cost_above_1hr": 6.6e-06,
"cache_read_input_token_cost": 3.3e-07,
@@ -2327,6 +2348,7 @@
"supports_output_config": true
},
"azure_ai/claude-opus-4-6": {
+ "supports_adaptive_thinking": true,
"input_cost_per_token": 5e-06,
"output_cost_per_token": 2.5e-05,
"litellm_provider": "azure_ai",
@@ -2356,6 +2378,7 @@
"supports_max_reasoning_effort": true
},
"azure_ai/claude-opus-4-7": {
+ "supports_adaptive_thinking": true,
"input_cost_per_token": 5e-06,
"output_cost_per_token": 2.5e-05,
"litellm_provider": "azure_ai",
@@ -2416,6 +2439,7 @@
"supports_max_reasoning_effort": true
},
"azure_ai/claude-opus-4-8": {
+ "supports_adaptive_thinking": true,
"input_cost_per_token": 5e-06,
"output_cost_per_token": 2.5e-05,
"litellm_provider": "azure_ai",
@@ -2488,6 +2512,7 @@
"supports_vision": true
},
"azure_ai/claude-sonnet-4-6": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 3.75e-06,
"cache_creation_input_token_cost_above_1hr": 6e-06,
"cache_read_input_token_cost": 3e-07,
@@ -18910,6 +18935,7 @@
"supports_output_config": true
},
"github_copilot/claude-opus-4.6-fast": {
+ "supports_adaptive_thinking": true,
"litellm_provider": "github_copilot",
"max_input_tokens": 128000,
"max_output_tokens": 16000,
@@ -28134,6 +28160,7 @@
"supports_vision": true
},
"openrouter/anthropic/claude-sonnet-4.6": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 3.75e-06,
"cache_creation_input_token_cost_above_200k_tokens": 7.5e-06,
"cache_read_input_token_cost": 3e-07,
@@ -28178,6 +28205,7 @@
"supports_output_config": true
},
"openrouter/anthropic/claude-opus-4.6": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.25e-06,
"cache_read_input_token_cost": 5e-07,
"input_cost_per_token": 5e-06,
@@ -28239,6 +28267,7 @@
"supports_vision": true
},
"openrouter/anthropic/claude-opus-4.7": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.25e-06,
"cache_read_input_token_cost": 5e-07,
"input_cost_per_token": 5e-06,
@@ -30168,6 +30197,7 @@
"supports_function_calling": true
},
"perplexity/anthropic/claude-opus-4-6": {
+ "supports_adaptive_thinking": true,
"litellm_provider": "perplexity",
"mode": "responses",
"supports_adaptive_thinking": true,
@@ -30177,6 +30207,7 @@
"supports_output_config": true
},
"perplexity/anthropic/claude-opus-4-7": {
+ "supports_adaptive_thinking": true,
"litellm_provider": "perplexity",
"mode": "responses",
"supports_adaptive_thinking": true,
@@ -33414,6 +33445,7 @@
"supports_output_config": true
},
"vercel_ai_gateway/anthropic/claude-opus-4.6": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.25e-06,
"cache_read_input_token_cost": 5e-07,
"input_cost_per_token": 5e-06,
@@ -34642,6 +34674,7 @@
"supports_output_config": true
},
"vertex_ai/claude-opus-4-6": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.25e-06,
"cache_creation_input_token_cost_above_1hr": 1e-05,
"cache_read_input_token_cost": 5e-07,
@@ -34671,6 +34704,7 @@
"supports_max_reasoning_effort": true
},
"vertex_ai/claude-opus-4-6@default": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.25e-06,
"cache_creation_input_token_cost_above_1hr": 1e-05,
"cache_read_input_token_cost": 5e-07,
@@ -34700,6 +34734,7 @@
"supports_max_reasoning_effort": true
},
"vertex_ai/claude-opus-4-7": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.25e-06,
"cache_creation_input_token_cost_above_1hr": 1e-05,
"cache_read_input_token_cost": 5e-07,
@@ -34730,6 +34765,7 @@
"supports_max_reasoning_effort": true
},
"vertex_ai/claude-opus-4-7@default": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.25e-06,
"cache_creation_input_token_cost_above_1hr": 1e-05,
"cache_read_input_token_cost": 5e-07,
@@ -34820,6 +34856,7 @@
"supports_max_reasoning_effort": true
},
"vertex_ai/claude-opus-4-8": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.25e-06,
"cache_creation_input_token_cost_above_1hr": 1e-05,
"cache_read_input_token_cost": 5e-07,
@@ -34850,6 +34887,7 @@
"supports_max_reasoning_effort": true
},
"vertex_ai/claude-opus-4-8@default": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.25e-06,
"cache_creation_input_token_cost_above_1hr": 1e-05,
"cache_read_input_token_cost": 5e-07,
@@ -34907,6 +34945,7 @@
"supports_vision": true
},
"vertex_ai/claude-sonnet-4-6": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 3.75e-06,
"cache_creation_input_token_cost_above_1hr": 6e-06,
"cache_read_input_token_cost": 3e-07,
@@ -42343,6 +42382,7 @@
}
},
"vertex_ai/claude-sonnet-4-6@default": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 3.75e-06,
"cache_creation_input_token_cost_above_1hr": 6e-06,
"cache_read_input_token_cost": 3e-07,
@@ -43371,5 +43411,40 @@
"supports_assistant_prefill": true,
"supports_reasoning": false,
"source": "https://pinstripes.io/pricing"
- }
+ },
+ "fallback_generalizations": {
+ "rules": [
+ {
+ "name": "anthropic-claude-adaptive-thinking",
+ "pattern": "(?:opus|sonnet|haiku)[-._](?:4[-._](?:[6-9]|[1-9]\\d)(?!\\d)|(?:[5-9]|[1-9]\\d{1,})[-._]\\d{1,2}(?!\\d))",
+ "description": "Claude opus/sonnet/haiku at version 4.6 or higher: 4.6 through 4.99, then any 5.x, 6.x or later major. The minor is capped at two digits so an 8-digit date suffix such as claude-opus-4-20250514 is never read as a >= 4.6 minor. Turns on adaptive thinking for new families with no code change.",
+ "extends": "anthropic-claude",
+ "model_info": {
+ "supports_adaptive_thinking": true
+ }
+ },
+ {
+ "name": "anthropic-claude",
+ "pattern": "^claude-[a-z]+-\\d+[-.]\\d+(?:-\\d{8})?$",
+ "description": "Any Claude family-major-minor id, optionally with an 8-digit date suffix, anchored to the whole name. Version-neutral fallback that gives an unmapped Claude provider routing and baseline capabilities; it carries no pricing, so cost stays on the standard unpriced behavior rather than a guessed number.",
+ "model_info": {
+ "litellm_provider": "anthropic",
+ "mode": "chat",
+ "max_input_tokens": 200000,
+ "max_output_tokens": 64000,
+ "max_tokens": 64000,
+ "supports_function_calling": true,
+ "supports_parallel_function_calling": true,
+ "supports_vision": true,
+ "supports_tool_choice": true,
+ "supports_assistant_prefill": true,
+ "supports_prompt_caching": true,
+ "supports_response_schema": true,
+ "supports_reasoning": true,
+ "supports_pdf_input": true,
+ "supports_system_messages": true
+ }
+ }
+ ]
+ }
}
diff --git a/litellm/utils.py b/litellm/utils.py
index b9e76b6525b..45ce5332f1d 100644
--- a/litellm/utils.py
+++ b/litellm/utils.py
@@ -60,6 +60,9 @@ from litellm._lazy_imports import (
_get_token_counter_new,
)
from litellm._uuid import uuid
+from litellm.litellm_core_utils.fallback_generalizations import (
+ match_fallback_generalization,
+)
from litellm.constants import (
DEFAULT_CHAT_COMPLETION_PARAM_VALUES,
DEFAULT_EMBEDDING_PARAM_VALUES,
@@ -5020,6 +5023,34 @@ class PotentialModelNamesAndCustomLLMProvider(TypedDict):
custom_llm_provider: str
+def _get_model_info_from_generalization(
+ model: str,
+ potential_model_names: PotentialModelNamesAndCustomLLMProvider,
+ custom_llm_provider: Optional[str],
+) -> Optional[tuple[str, dict]]:
+ """Resolve an unmapped model via a declarative fallback-generalization rule.
+
+ Tries the same name candidates as the exact lookups, in the same order, and
+ returns ``(matched_name, model_info)`` for the first candidate whose rule also
+ satisfies the provider constraint. O(number of rules); only call after the
+ exact lookups have missed.
+ """
+ candidates = [
+ potential_model_names["combined_model_name"],
+ model,
+ potential_model_names["combined_stripped_model_name"],
+ potential_model_names["stripped_model_name"],
+ potential_model_names["split_model"],
+ ]
+ for candidate in candidates:
+ generalized_info = match_fallback_generalization(candidate)
+ if generalized_info is not None and _check_provider_match(
+ model_info=generalized_info, custom_llm_provider=custom_llm_provider
+ ):
+ return candidate, generalized_info
+ return None
+
+
def _get_potential_model_names(
model: str, custom_llm_provider: Optional[str]
) -> PotentialModelNamesAndCustomLLMProvider:
@@ -5275,6 +5306,15 @@ def _get_model_info_helper(
):
_model_info = None
+ if _model_info is None:
+ generalization = _get_model_info_from_generalization(
+ model=model,
+ potential_model_names=potential_model_names,
+ custom_llm_provider=custom_llm_provider,
+ )
+ if generalization is not None:
+ key, _model_info = generalization
+
if _model_info is None or key is None:
raise ValueError(
"This model isn't mapped yet. Add it here - https://github.com/BerriAI/litellm/blob/main/model_prices_and_context_window.json"
diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.json
index 452033faf2c..73cefeb7c77 100644
--- a/model_prices_and_context_window.json
+++ b/model_prices_and_context_window.json
@@ -994,6 +994,7 @@
"bedrock_output_config_effort_ceiling": "high"
},
"anthropic.claude-opus-4-6-v1": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.25e-06,
"cache_creation_input_token_cost_above_1hr": 1e-05,
"cache_read_input_token_cost": 5e-07,
@@ -1025,6 +1026,7 @@
"bedrock_output_config_effort_ceiling": "max"
},
"global.anthropic.claude-opus-4-6-v1": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.25e-06,
"cache_creation_input_token_cost_above_1hr": 1e-05,
"cache_read_input_token_cost": 5e-07,
@@ -1056,6 +1058,7 @@
"bedrock_output_config_effort_ceiling": "max"
},
"us.anthropic.claude-opus-4-6-v1": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.875e-06,
"cache_creation_input_token_cost_above_1hr": 1.1e-05,
"cache_read_input_token_cost": 5.5e-07,
@@ -1087,6 +1090,7 @@
"bedrock_output_config_effort_ceiling": "max"
},
"eu.anthropic.claude-opus-4-6-v1": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.875e-06,
"cache_creation_input_token_cost_above_1hr": 1.1e-05,
"cache_read_input_token_cost": 5.5e-07,
@@ -1118,6 +1122,7 @@
"bedrock_output_config_effort_ceiling": "max"
},
"au.anthropic.claude-opus-4-6-v1": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.875e-06,
"cache_creation_input_token_cost_above_1hr": 1.1e-05,
"cache_read_input_token_cost": 5.5e-07,
@@ -1149,6 +1154,7 @@
"bedrock_output_config_effort_ceiling": "max"
},
"anthropic.claude-opus-4-7": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.25e-06,
"cache_creation_input_token_cost_above_1hr": 1e-05,
"cache_read_input_token_cost": 5e-07,
@@ -1197,6 +1203,7 @@
"supports_output_config": true
},
"global.anthropic.claude-opus-4-7": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.25e-06,
"cache_creation_input_token_cost_above_1hr": 1e-05,
"cache_read_input_token_cost": 5e-07,
@@ -1230,6 +1237,7 @@
"bedrock_output_config_effort_ceiling": "xhigh"
},
"us.anthropic.claude-opus-4-7": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.875e-06,
"cache_creation_input_token_cost_above_1hr": 1.1e-05,
"cache_read_input_token_cost": 5.5e-07,
@@ -1263,6 +1271,7 @@
"bedrock_output_config_effort_ceiling": "xhigh"
},
"eu.anthropic.claude-opus-4-7": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.875e-06,
"cache_creation_input_token_cost_above_1hr": 1.1e-05,
"cache_read_input_token_cost": 5.5e-07,
@@ -1296,6 +1305,7 @@
"bedrock_output_config_effort_ceiling": "xhigh"
},
"au.anthropic.claude-opus-4-7": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.875e-06,
"cache_creation_input_token_cost_above_1hr": 1.1e-05,
"cache_read_input_token_cost": 5.5e-07,
@@ -1461,6 +1471,7 @@
"bedrock_output_config_effort_ceiling": "xhigh"
},
"anthropic.claude-opus-4-8": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.25e-06,
"cache_creation_input_token_cost_above_1hr": 1e-05,
"cache_read_input_token_cost": 5e-07,
@@ -1494,6 +1505,7 @@
"bedrock_output_config_effort_ceiling": "xhigh"
},
"global.anthropic.claude-opus-4-8": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.25e-06,
"cache_creation_input_token_cost_above_1hr": 1e-05,
"cache_read_input_token_cost": 5e-07,
@@ -1527,6 +1539,7 @@
"bedrock_output_config_effort_ceiling": "xhigh"
},
"us.anthropic.claude-opus-4-8": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.875e-06,
"cache_creation_input_token_cost_above_1hr": 1.1e-05,
"cache_read_input_token_cost": 5.5e-07,
@@ -1560,6 +1573,7 @@
"bedrock_output_config_effort_ceiling": "xhigh"
},
"eu.anthropic.claude-opus-4-8": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.875e-06,
"cache_creation_input_token_cost_above_1hr": 1.1e-05,
"cache_read_input_token_cost": 5.5e-07,
@@ -1593,6 +1607,7 @@
"bedrock_output_config_effort_ceiling": "xhigh"
},
"au.anthropic.claude-opus-4-8": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.875e-06,
"cache_creation_input_token_cost_above_1hr": 1.1e-05,
"cache_read_input_token_cost": 5.5e-07,
@@ -1657,6 +1672,7 @@
"supports_minimal_reasoning_effort": true
},
"anthropic.claude-sonnet-4-6": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 3.75e-06,
"cache_creation_input_token_cost_above_1hr": 6e-06,
"cache_read_input_token_cost": 3e-07,
@@ -1687,6 +1703,7 @@
"supports_output_config": true
},
"global.anthropic.claude-sonnet-4-6": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 3.75e-06,
"cache_creation_input_token_cost_above_1hr": 6e-06,
"cache_read_input_token_cost": 3e-07,
@@ -1717,6 +1734,7 @@
"supports_output_config": true
},
"us.anthropic.claude-sonnet-4-6": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 4.125e-06,
"cache_creation_input_token_cost_above_1hr": 6.6e-06,
"cache_read_input_token_cost": 3.3e-07,
@@ -1747,6 +1765,7 @@
"supports_output_config": true
},
"eu.anthropic.claude-sonnet-4-6": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 4.125e-06,
"cache_creation_input_token_cost_above_1hr": 6.6e-06,
"cache_read_input_token_cost": 3.3e-07,
@@ -1777,6 +1796,7 @@
"supports_output_config": true
},
"au.anthropic.claude-sonnet-4-6": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 4.125e-06,
"cache_creation_input_token_cost_above_1hr": 6.6e-06,
"cache_read_input_token_cost": 3.3e-07,
@@ -1807,6 +1827,7 @@
"supports_output_config": true
},
"jp.anthropic.claude-sonnet-4-6": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 4.125e-06,
"cache_creation_input_token_cost_above_1hr": 6.6e-06,
"cache_read_input_token_cost": 3.3e-07,
@@ -2327,6 +2348,7 @@
"supports_output_config": true
},
"azure_ai/claude-opus-4-6": {
+ "supports_adaptive_thinking": true,
"input_cost_per_token": 5e-06,
"output_cost_per_token": 2.5e-05,
"litellm_provider": "azure_ai",
@@ -2356,6 +2378,7 @@
"supports_max_reasoning_effort": true
},
"azure_ai/claude-opus-4-7": {
+ "supports_adaptive_thinking": true,
"input_cost_per_token": 5e-06,
"output_cost_per_token": 2.5e-05,
"litellm_provider": "azure_ai",
@@ -2416,6 +2439,7 @@
"supports_max_reasoning_effort": true
},
"azure_ai/claude-opus-4-8": {
+ "supports_adaptive_thinking": true,
"input_cost_per_token": 5e-06,
"output_cost_per_token": 2.5e-05,
"litellm_provider": "azure_ai",
@@ -2488,6 +2512,7 @@
"supports_vision": true
},
"azure_ai/claude-sonnet-4-6": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 3.75e-06,
"cache_creation_input_token_cost_above_1hr": 6e-06,
"cache_read_input_token_cost": 3e-07,
@@ -19071,6 +19096,7 @@
"supports_output_config": true
},
"github_copilot/claude-opus-4.6-fast": {
+ "supports_adaptive_thinking": true,
"litellm_provider": "github_copilot",
"max_input_tokens": 128000,
"max_output_tokens": 16000,
@@ -28295,6 +28321,7 @@
"supports_vision": true
},
"openrouter/anthropic/claude-sonnet-4.6": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 3.75e-06,
"cache_creation_input_token_cost_above_200k_tokens": 7.5e-06,
"cache_read_input_token_cost": 3e-07,
@@ -28339,6 +28366,7 @@
"supports_output_config": true
},
"openrouter/anthropic/claude-opus-4.6": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.25e-06,
"cache_read_input_token_cost": 5e-07,
"input_cost_per_token": 5e-06,
@@ -28400,6 +28428,7 @@
"supports_vision": true
},
"openrouter/anthropic/claude-opus-4.7": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.25e-06,
"cache_read_input_token_cost": 5e-07,
"input_cost_per_token": 5e-06,
@@ -30345,6 +30374,7 @@
"supports_function_calling": true
},
"perplexity/anthropic/claude-opus-4-6": {
+ "supports_adaptive_thinking": true,
"litellm_provider": "perplexity",
"mode": "responses",
"supports_adaptive_thinking": true,
@@ -30354,6 +30384,7 @@
"supports_output_config": true
},
"perplexity/anthropic/claude-opus-4-7": {
+ "supports_adaptive_thinking": true,
"litellm_provider": "perplexity",
"mode": "responses",
"supports_adaptive_thinking": true,
@@ -33591,6 +33622,7 @@
"supports_output_config": true
},
"vercel_ai_gateway/anthropic/claude-opus-4.6": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.25e-06,
"cache_read_input_token_cost": 5e-07,
"input_cost_per_token": 5e-06,
@@ -34819,6 +34851,7 @@
"supports_output_config": true
},
"vertex_ai/claude-opus-4-6": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.25e-06,
"cache_creation_input_token_cost_above_1hr": 1e-05,
"cache_read_input_token_cost": 5e-07,
@@ -34848,6 +34881,7 @@
"supports_max_reasoning_effort": true
},
"vertex_ai/claude-opus-4-6@default": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.25e-06,
"cache_creation_input_token_cost_above_1hr": 1e-05,
"cache_read_input_token_cost": 5e-07,
@@ -34877,6 +34911,7 @@
"supports_max_reasoning_effort": true
},
"vertex_ai/claude-opus-4-7": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.25e-06,
"cache_creation_input_token_cost_above_1hr": 1e-05,
"cache_read_input_token_cost": 5e-07,
@@ -34907,6 +34942,7 @@
"supports_max_reasoning_effort": true
},
"vertex_ai/claude-opus-4-7@default": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.25e-06,
"cache_creation_input_token_cost_above_1hr": 1e-05,
"cache_read_input_token_cost": 5e-07,
@@ -34997,6 +35033,7 @@
"supports_max_reasoning_effort": true
},
"vertex_ai/claude-opus-4-8": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.25e-06,
"cache_creation_input_token_cost_above_1hr": 1e-05,
"cache_read_input_token_cost": 5e-07,
@@ -35027,6 +35064,7 @@
"supports_max_reasoning_effort": true
},
"vertex_ai/claude-opus-4-8@default": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 6.25e-06,
"cache_creation_input_token_cost_above_1hr": 1e-05,
"cache_read_input_token_cost": 5e-07,
@@ -35084,6 +35122,7 @@
"supports_vision": true
},
"vertex_ai/claude-sonnet-4-6": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 3.75e-06,
"cache_creation_input_token_cost_above_1hr": 6e-06,
"cache_read_input_token_cost": 3e-07,
@@ -42578,6 +42617,7 @@
}
},
"vertex_ai/claude-sonnet-4-6@default": {
+ "supports_adaptive_thinking": true,
"cache_creation_input_token_cost": 3.75e-06,
"cache_creation_input_token_cost_above_1hr": 6e-06,
"cache_read_input_token_cost": 3e-07,
@@ -43055,6 +43095,7 @@
"supports_response_schema": true
},
"snowflake/claude-sonnet-4-6": {
+ "supports_adaptive_thinking": true,
"max_tokens": 16384,
"max_input_tokens": 200000,
"max_output_tokens": 16384,
@@ -43606,5 +43647,40 @@
"supports_native_streaming": true,
"supports_system_messages": true,
"supports_tool_choice": true
- }
+ },
+ "fallback_generalizations": {
+ "rules": [
+ {
+ "name": "anthropic-claude-adaptive-thinking",
+ "pattern": "(?:opus|sonnet|haiku)[-._](?:4[-._](?:[6-9]|[1-9]\\d)(?!\\d)|(?:[5-9]|[1-9]\\d{1,})[-._]\\d{1,2}(?!\\d))",
+ "description": "Claude opus/sonnet/haiku at version 4.6 or higher: 4.6 through 4.99, then any 5.x, 6.x or later major. The minor is capped at two digits so an 8-digit date suffix such as claude-opus-4-20250514 is never read as a >= 4.6 minor. Turns on adaptive thinking for new families with no code change.",
+ "extends": "anthropic-claude",
+ "model_info": {
+ "supports_adaptive_thinking": true
+ }
+ },
+ {
+ "name": "anthropic-claude",
+ "pattern": "^claude-[a-z]+-\\d+[-.]\\d+(?:-\\d{8})?$",
+ "description": "Any Claude family-major-minor id, optionally with an 8-digit date suffix, anchored to the whole name. Version-neutral fallback that gives an unmapped Claude provider routing and baseline capabilities; it carries no pricing, so cost stays on the standard unpriced behavior rather than a guessed number.",
+ "model_info": {
+ "litellm_provider": "anthropic",
+ "mode": "chat",
+ "max_input_tokens": 200000,
+ "max_output_tokens": 64000,
+ "max_tokens": 64000,
+ "supports_function_calling": true,
+ "supports_parallel_function_calling": true,
+ "supports_vision": true,
+ "supports_tool_choice": true,
+ "supports_assistant_prefill": true,
+ "supports_prompt_caching": true,
+ "supports_response_schema": true,
+ "supports_reasoning": true,
+ "supports_pdf_input": true,
+ "supports_system_messages": true
+ }
+ }
+ ]
+ }
}
diff --git a/tests/local_testing/conftest.py b/tests/local_testing/conftest.py
index 2bda6f0d22b..d134a7439a8 100644
--- a/tests/local_testing/conftest.py
+++ b/tests/local_testing/conftest.py
@@ -29,9 +29,14 @@ import litellm
# was added on this branch). Backfill any entries that are missing from the
# remote-fetched map so cost-calculator lookups in tests succeed against the
# cassette state the branch is being tested with.
-from litellm.litellm_core_utils.get_model_cost_map import GetModelCostMap
+from litellm.litellm_core_utils.get_model_cost_map import (
+ RESERVED_TOP_LEVEL_KEYS,
+ GetModelCostMap,
+)
for _k, _v in GetModelCostMap.load_local_model_cost_map().items():
+ if _k in RESERVED_TOP_LEVEL_KEYS:
+ continue
litellm.model_cost.setdefault(_k, _v)
from tests._vcr_conftest_common import ( # noqa: E402,F401
diff --git a/tests/local_testing/test_get_llm_provider.py b/tests/local_testing/test_get_llm_provider.py
index 1c041be0949..9ecb639fc3a 100644
--- a/tests/local_testing/test_get_llm_provider.py
+++ b/tests/local_testing/test_get_llm_provider.py
@@ -480,107 +480,94 @@ def test_get_llm_provider_use_proxy_arg_true_with_direct_args():
assert base == arg_api_base # Should use the argument base
-# -------- Tests for Claude model pattern matching ---------
+# -------- Tests for the anthropic-claude fallback generalization rule ---------
-class TestClaudeModelPatternMatching:
- """
- Tests for _matches_claude_model_pattern which routes future Claude models
- to the Anthropic provider without requiring model_prices_and_context_window.json updates.
- """
-
- def test_matches_claude_opus_pattern(self):
- """Test claude-opus-X-Y pattern matching."""
- from litellm.litellm_core_utils.get_llm_provider_logic import (
- _matches_claude_model_pattern,
- )
-
- assert _matches_claude_model_pattern("claude-opus-4-7") is True
- assert _matches_claude_model_pattern("claude-opus-4-9") is True
- assert _matches_claude_model_pattern("claude-opus-5-1") is True
-
- def test_matches_claude_sonnet_pattern(self):
- """Test claude-sonnet-X-Y pattern matching."""
- from litellm.litellm_core_utils.get_llm_provider_logic import (
- _matches_claude_model_pattern,
- )
+def shipped_generalizations():
+ """Install the rules shipped in the bundled backup, then restore.
- assert _matches_claude_model_pattern("claude-sonnet-4-6") is True
- assert _matches_claude_model_pattern("claude-sonnet-5-0") is True
-
- def test_matches_claude_haiku_pattern(self):
- """Test claude-haiku-X-Y pattern matching."""
- from litellm.litellm_core_utils.get_llm_provider_logic import (
- _matches_claude_model_pattern,
- )
-
- assert _matches_claude_model_pattern("claude-haiku-4-5") is True
- assert _matches_claude_model_pattern("claude-haiku-5-0") is True
-
- def test_matches_claude_with_date_suffix(self):
- """Test claude model pattern with date suffix."""
- from litellm.litellm_core_utils.get_llm_provider_logic import (
- _matches_claude_model_pattern,
- )
+ The remote-fetched cost map pinned to ``main`` may not yet carry the rule
+ added on this branch, so these tests install the rule the branch actually
+ ships rather than depending on whatever the live URL returns.
+ """
+ from litellm.litellm_core_utils.fallback_generalizations import (
+ get_fallback_generalization_rules,
+ set_fallback_generalizations,
+ )
+ from litellm.litellm_core_utils.get_model_cost_map import GetModelCostMap
- assert _matches_claude_model_pattern("claude-opus-5-1-20270101") is True
- assert _matches_claude_model_pattern("claude-sonnet-4-7-20260601") is True
- assert _matches_claude_model_pattern("claude-haiku-4-6-20251201") is True
+ previous = list(get_fallback_generalization_rules())
+ backup = GetModelCostMap.load_local_model_cost_map()
+ rules = backup.get("fallback_generalizations", {}).get("rules", [])
+ set_fallback_generalizations(rules)
+ try:
+ yield rules
+ finally:
+ set_fallback_generalizations(previous)
- def test_matches_unknown_tier_name(self):
- """A tier segment we don't know about today should still route to anthropic.
- The pattern intentionally accepts any ``[a-z]+`` tier rather than a
- hard-coded ``opus|sonnet|haiku`` list so a future tier (e.g. a new
- "mini" line) is covered without a code change. This guards against a
- regression back to hard-coded tier names.
- """
- from litellm.litellm_core_utils.get_llm_provider_logic import (
- _matches_claude_model_pattern,
- )
+class TestClaudeModelPatternMatching:
+ """
+ The ``anthropic-claude`` fallback generalization rule routes future Claude
+ models to the Anthropic provider without requiring a
+ model_prices_and_context_window.json entry. These tests exercise the rule
+ end-to-end through ``get_llm_provider`` and ``match_fallback_generalization``.
+ """
- assert _matches_claude_model_pattern("claude-mini-4-5") is True
- assert _matches_claude_model_pattern("claude-neptune-6-0") is True
+ @pytest.mark.parametrize(
+ "model",
+ [
+ "claude-opus-4-9",
+ "claude-opus-5-1",
+ "claude-sonnet-4-6",
+ "claude-sonnet-5-0",
+ "claude-haiku-4-5",
+ "claude-haiku-5-0",
+ "claude-opus-5-1-20270101",
+ "claude-sonnet-4-7-20260601",
+ "claude-haiku-4-6-20251201",
+ # A tier segment we don't know about today still routes: the regex
+ # accepts any [a-z]+ tier rather than a hard-coded opus|sonnet|haiku
+ # list, so a future tier is covered without a code change.
+ "claude-mini-4-5",
+ "claude-neptune-6-0",
+ ],
+ )
+ def test_unknown_claude_routes_to_anthropic(self, model, shipped_generalizations):
+ _, custom_llm_provider, _, _ = litellm.get_llm_provider(model=model)
+ assert custom_llm_provider == "anthropic"
- def test_rejects_non_claude_models(self):
- """Test that non-Claude models are not matched."""
- from litellm.litellm_core_utils.get_llm_provider_logic import (
- _matches_claude_model_pattern,
+ @pytest.mark.parametrize(
+ "model",
+ [
+ "gpt-4",
+ "mistral-large",
+ "llama-3",
+ # Wrong order (variant before name)
+ "claude-4-opus",
+ # Missing version numbers
+ "claude-opus",
+ # Old format (claude-3-opus instead of claude-opus-3)
+ "claude-3-opus-20240229",
+ ],
+ )
+ def test_non_matching_models_do_not_match_rule(
+ self, model, shipped_generalizations
+ ):
+ from litellm.litellm_core_utils.fallback_generalizations import (
+ match_fallback_generalization,
)
- assert _matches_claude_model_pattern("gpt-4") is False
- assert _matches_claude_model_pattern("mistral-large") is False
- assert _matches_claude_model_pattern("llama-3") is False
+ assert match_fallback_generalization(model) is None
- def test_rejects_invalid_claude_patterns(self):
- """Test that invalid Claude model patterns are not matched."""
- from litellm.litellm_core_utils.get_llm_provider_logic import (
- _matches_claude_model_pattern,
+ def test_routing_comes_from_the_rule_not_python(self, shipped_generalizations):
+ """With the rule cleared, an unknown claude must no longer route to
+ anthropic; this guards against re-introducing a hard-coded Python regex."""
+ from litellm.litellm_core_utils.fallback_generalizations import (
+ set_fallback_generalizations,
)
- # Wrong order (variant before name)
- assert _matches_claude_model_pattern("claude-4-opus") is False
- # Missing version numbers
- assert _matches_claude_model_pattern("claude-opus") is False
- # Old format (claude-3-opus instead of claude-opus-3)
- assert _matches_claude_model_pattern("claude-3-opus-20240229") is False
-
- def test_get_llm_provider_future_claude_model(self):
- """Test that get_llm_provider routes future Claude models to anthropic."""
- model, custom_llm_provider, dynamic_api_key, api_base = (
- litellm.get_llm_provider(
- model="claude-opus-4-9",
- )
- )
- assert custom_llm_provider == "anthropic"
- assert model == "claude-opus-4-9"
-
- def test_get_llm_provider_future_claude_model_with_date(self):
- """Test that get_llm_provider routes future Claude models with date suffix."""
- model, custom_llm_provider, dynamic_api_key, api_base = (
- litellm.get_llm_provider(
- model="claude-opus-5-1-20270101",
- )
- )
- assert custom_llm_provider == "anthropic"
- assert model == "claude-opus-5-1-20270101"
+ set_fallback_generalizations([])
+ with pytest.raises(Exception):
+ litellm.get_llm_provider(model="claude-opus-4-9")
diff --git a/tests/test_litellm/litellm_core_utils/test_fallback_generalizations.py b/tests/test_litellm/litellm_core_utils/test_fallback_generalizations.py
new file mode 100644
index 00000000000..410014958b6
--- /dev/null
+++ b/tests/test_litellm/litellm_core_utils/test_fallback_generalizations.py
@@ -0,0 +1,300 @@
+"""
+Tests for the declarative fallback-generalizations mechanism.
+
+Covers both the pure module (litellm.litellm_core_utils.fallback_generalizations)
+and its end-to-end wiring into provider routing (get_llm_provider) and model-info
+resolution (get_model_info / supports_*).
+"""
+
+import os
+import sys
+
+import pytest
+
+sys.path.insert(0, os.path.abspath("../../.."))
+
+import litellm
+from litellm.litellm_core_utils.fallback_generalizations import (
+ get_fallback_generalization_rules,
+ match_fallback_generalization,
+ set_fallback_generalizations,
+)
+
+
+def restore_generalizations():
+ """Save the active rules, let the test install its own, then restore."""
+ previous = list(get_fallback_generalization_rules())
+ try:
+ yield set_fallback_generalizations
+ finally:
+ set_fallback_generalizations(previous)
+
+
+# --------------------------------------------------------------------------- #
+# Pure module behaviour
+# --------------------------------------------------------------------------- #
+
+
+def test_match_returns_model_info_of_first_matching_rule(restore_generalizations):
+ restore_generalizations(
+ [
+ {
+ "name": "first",
+ "pattern": r"^acme-",
+ "model_info": {"litellm_provider": "openai", "tag": "first"},
+ },
+ {
+ "name": "second",
+ "pattern": r"^acme-pro-",
+ "model_info": {"litellm_provider": "anthropic", "tag": "second"},
+ },
+ ]
+ )
+ # Both rules match "acme-pro-1"; first-in-list wins (documented precedence).
+ matched = match_fallback_generalization("acme-pro-1")
+ assert matched is not None
+ assert matched["tag"] == "first"
+
+
+def test_match_is_case_insensitive(restore_generalizations):
+ restore_generalizations(
+ [{"name": "r", "pattern": r"^claude-opus", "model_info": {"ok": True}}]
+ )
+ assert match_fallback_generalization("CLAUDE-OPUS-9-9") == {"ok": True}
+
+
+def test_no_match_returns_none(restore_generalizations):
+ restore_generalizations(
+ [{"name": "r", "pattern": r"^claude-", "model_info": {"ok": True}}]
+ )
+ assert match_fallback_generalization("gpt-4o") is None
+ assert match_fallback_generalization("") is None
+
+
+def test_empty_rules_match_nothing(restore_generalizations):
+ restore_generalizations([])
+ assert match_fallback_generalization("claude-opus-9-9") is None
+
+
+def test_malformed_rules_are_skipped_not_fatal(restore_generalizations):
+ restore_generalizations(
+ [
+ "not-even-a-dict",
+ None,
+ {"name": "no-pattern", "model_info": {"x": 1}},
+ {"name": "bad-info", "pattern": r"^a", "model_info": "not-a-dict"},
+ {"name": "bad-regex", "pattern": r"^claude-(", "model_info": {"x": 1}},
+ {"name": "good", "pattern": r"^claude-", "model_info": {"good": True}},
+ ]
+ )
+ # Non-dict entries and dicts with bad fields are all skipped; the one
+ # valid rule still matches.
+ assert match_fallback_generalization("claude-opus-9-9") == {"good": True}
+
+
+def test_setting_rules_invalidates_compiled_cache(restore_generalizations):
+ restore_generalizations([{"name": "r", "pattern": r"^aaa", "model_info": {"v": 1}}])
+ assert match_fallback_generalization("aaa-1") == {"v": 1}
+ # Re-install different rules; the compiled cache must be rebuilt.
+ set_fallback_generalizations(
+ [{"name": "r", "pattern": r"^bbb", "model_info": {"v": 2}}]
+ )
+ assert match_fallback_generalization("aaa-1") is None
+ assert match_fallback_generalization("bbb-1") == {"v": 2}
+
+
+def test_extends_inherits_parent_and_own_overrides(restore_generalizations):
+ """A rule's ``extends`` pulls in the parent's model_info; its own keys win on conflict,
+ so a narrow rule carries only its delta instead of duplicating the parent."""
+ restore_generalizations(
+ [
+ {
+ "name": "base",
+ "pattern": r"^base-only$",
+ "model_info": {
+ "litellm_provider": "anthropic",
+ "input_cost_per_token": 5e-06,
+ "supports_vision": True,
+ },
+ },
+ {
+ "name": "child",
+ "pattern": r"^kid-",
+ "extends": "base",
+ "model_info": {
+ "supports_adaptive_thinking": True,
+ "supports_vision": False,
+ },
+ },
+ ]
+ )
+ matched = match_fallback_generalization("kid-1")
+ assert matched == {
+ "litellm_provider": "anthropic",
+ "input_cost_per_token": 5e-06,
+ "supports_vision": False,
+ "supports_adaptive_thinking": True,
+ }
+
+
+def test_extends_with_unknown_parent_keeps_own_model_info(restore_generalizations):
+ """A dangling ``extends`` is non-fatal: the rule resolves to its own model_info."""
+ restore_generalizations(
+ [
+ {
+ "name": "orphan",
+ "pattern": r"^orphan-",
+ "extends": "does-not-exist",
+ "model_info": {"litellm_provider": "openai"},
+ }
+ ]
+ )
+ assert match_fallback_generalization("orphan-1") == {"litellm_provider": "openai"}
+
+
+# --------------------------------------------------------------------------- #
+# End-to-end: provider routing + model-info resolution
+# --------------------------------------------------------------------------- #
+
+
+def myco_rule(restore_generalizations):
+ """A self-contained rule carrying provider, pricing, context and capabilities."""
+ restore_generalizations(
+ [
+ {
+ "name": "myco",
+ "pattern": r"^myco-[a-z]+-\d+$",
+ "model_info": {
+ "litellm_provider": "openai",
+ "mode": "chat",
+ "input_cost_per_token": 1e-06,
+ "output_cost_per_token": 2e-06,
+ "max_input_tokens": 12345,
+ "max_output_tokens": 678,
+ "supports_vision": True,
+ "supports_function_calling": True,
+ },
+ }
+ ]
+ )
+ return "myco-fast-1"
+
+
+def test_unknown_model_routes_via_rule(myco_rule):
+ _, provider, _, _ = litellm.get_llm_provider(model=myco_rule)
+ assert provider == "openai"
+
+
+def test_unknown_model_gets_pricing_context_and_capabilities(myco_rule):
+ info = litellm.get_model_info(myco_rule)
+ assert info["litellm_provider"] == "openai"
+ assert info["input_cost_per_token"] == 1e-06
+ assert info["output_cost_per_token"] == 2e-06
+ assert info["max_input_tokens"] == 12345
+ assert info["supports_vision"] is True
+
+
+def test_supports_helper_reads_through_generalization(myco_rule):
+ assert litellm.supports_vision(myco_rule) is True
+ assert litellm.supports_function_calling(myco_rule) is True
+
+
+def test_exact_entry_takes_precedence_over_rule(restore_generalizations):
+ """An exact cost-map entry must win over a rule that also matches it."""
+ restore_generalizations(
+ [
+ {
+ "name": "shadow-gpt4o",
+ "pattern": r"^gpt-4o$",
+ "model_info": {
+ "litellm_provider": "anthropic",
+ "input_cost_per_token": 999.0,
+ },
+ }
+ ]
+ )
+ info = litellm.get_model_info("gpt-4o")
+ # Resolved from the real exact entry, not the shadowing rule.
+ assert info["litellm_provider"] == "openai"
+ assert info["input_cost_per_token"] != 999.0
+
+
+def test_unknown_model_without_matching_rule_still_unmapped(restore_generalizations):
+ restore_generalizations(
+ [
+ {
+ "name": "claude",
+ "pattern": r"^claude-",
+ "model_info": {"litellm_provider": "anthropic"},
+ }
+ ]
+ )
+ with pytest.raises(Exception):
+ litellm.get_model_info("totally-unknown-model-xyz")
+
+
+# --------------------------------------------------------------------------- #
+# Shipped anthropic-claude rule
+# --------------------------------------------------------------------------- #
+
+
+def shipped_cost_map(monkeypatch):
+ """Activate the bundled cost map so the shipped anthropic-claude rule is installed."""
+ original_cost = litellm.model_cost
+ previous_rules = list(get_fallback_generalization_rules())
+ monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True")
+ litellm.model_cost = litellm.get_model_cost_map(url="")
+ litellm.get_model_info.cache_clear()
+ try:
+ yield
+ finally:
+ litellm.model_cost = original_cost
+ litellm.get_model_info.cache_clear()
+ set_fallback_generalizations(previous_rules)
+
+
+def test_shipped_rule_marks_unmapped_high_version_claude_adaptive_without_pricing(
+ shipped_cost_map,
+):
+ """An unmapped Claude >= 4.6 resolves via the version-gated adaptive-thinking rule, which
+ inherits routing and capabilities from the base rule and adds ``supports_adaptive_thinking``.
+ The rule carries no pricing, so cost stays unpriced (zero, not a fabricated number) rather
+ than reporting a confidently-wrong price."""
+ model = "claude-opus-9-9"
+ assert model not in litellm.model_cost
+ info = litellm.get_model_info(model)
+ assert info["litellm_provider"] == "anthropic"
+ assert info["supports_adaptive_thinking"] is True
+ assert info["supports_function_calling"] is True
+ assert not info.get("input_cost_per_token")
+ assert not info.get("output_cost_per_token")
+
+
+def test_shipped_rule_resolves_unmapped_low_version_claude_without_adaptive(shipped_cost_map):
+ """An unmapped Claude < 4.6 falls through to the version-neutral anthropic-claude rule: it
+ gets provider routing and baseline capabilities but no ``supports_adaptive_thinking`` flag,
+ so a sub-4.6 alias such as ``claude-opus-4-0`` resolves yet is never marked adaptive."""
+ model = "claude-opus-4-0"
+ assert model not in litellm.model_cost
+ info = litellm.get_model_info(model)
+ assert info["litellm_provider"] == "anthropic"
+ assert info["supports_function_calling"] is True
+ assert info.get("supports_adaptive_thinking") is None
+ assert not info.get("input_cost_per_token")
+
+
+def test_shipped_adaptive_rule_gates_on_version_not_pricing(shipped_cost_map):
+ """The version-gated ``anthropic-claude-adaptive-thinking`` rule marks an unmapped
+ Claude adaptive only from >= 4.6, including provider-prefixed ids the anchored pricing
+ rule cannot match, while leaving < 4.6 (and the dated Opus 4.0 form) non-adaptive."""
+ from litellm.llms.anthropic.common_utils import AnthropicModelInfo
+
+ adaptive = "us.anthropic.claude-opus-4-9"
+ non_adaptive = "us.anthropic.claude-opus-4-20250514"
+ assert adaptive not in litellm.model_cost
+ assert non_adaptive not in litellm.model_cost
+ assert AnthropicModelInfo._is_adaptive_thinking_model(adaptive) is True
+ assert AnthropicModelInfo._is_adaptive_thinking_model(non_adaptive) is False
diff --git a/tests/test_litellm/litellm_core_utils/test_get_model_cost_map.py b/tests/test_litellm/litellm_core_utils/test_get_model_cost_map.py
new file mode 100644
index 00000000000..924aaa7775d
--- /dev/null
+++ b/tests/test_litellm/litellm_core_utils/test_get_model_cost_map.py
@@ -0,0 +1,182 @@
+"""
+Tests for model-cost-map loading: the model-count integrity check (which must
+count actual model entries, not reserved meta keys) and the extraction of the
+``fallback_generalizations`` block out of the raw map.
+"""
+
+import os
+import sys
+
+import pytest
+
+sys.path.insert(0, os.path.abspath("../../.."))
+
+from litellm.litellm_core_utils.fallback_generalizations import (
+ get_fallback_generalization_rules,
+ match_fallback_generalization,
+ set_fallback_generalizations,
+)
+from litellm.litellm_core_utils.get_model_cost_map import (
+ FALLBACK_GENERALIZATIONS_KEY,
+ GetModelCostMap,
+ _count_model_entries,
+ _finalize_model_cost_map,
+)
+
+
+def _make_models(n: int) -> dict:
+ return {
+ f"model-{i}": {"litellm_provider": "openai", "mode": "chat"} for i in range(n)
+ }
+
+
+def test_count_model_entries_excludes_reserved_keys():
+ m = _make_models(3)
+ m["sample_spec"] = {"foo": "bar"}
+ m[FALLBACK_GENERALIZATIONS_KEY] = {"rules": []}
+ assert _count_model_entries(m) == 3
+
+
+def test_validation_rejects_truly_shrunk_file_even_with_meta_keys():
+ """A file with only a handful of real models must be rejected as corrupt,
+ and the extra meta keys must not inflate the count past the minimum."""
+ shrunk = _make_models(5)
+ shrunk["sample_spec"] = {"foo": "bar"}
+ shrunk[FALLBACK_GENERALIZATIONS_KEY] = {"rules": [{"name": "x"}]}
+
+ assert (
+ GetModelCostMap.validate_model_cost_map(
+ fetched_map=shrunk,
+ backup_model_count=2000,
+ min_model_count=50,
+ )
+ is False
+ )
+
+
+def test_validation_accepts_healthy_file_with_meta_keys():
+ healthy = _make_models(2000)
+ healthy["sample_spec"] = {"foo": "bar"}
+ healthy[FALLBACK_GENERALIZATIONS_KEY] = {"rules": []}
+
+ assert (
+ GetModelCostMap.validate_model_cost_map(
+ fetched_map=healthy,
+ backup_model_count=2000,
+ min_model_count=50,
+ )
+ is True
+ )
+
+
+def test_validation_rejects_significant_shrink_vs_backup():
+ # 600 real models vs a 2000-model backup is below the 50% shrink threshold.
+ shrunk = _make_models(600)
+ shrunk[FALLBACK_GENERALIZATIONS_KEY] = {"rules": []}
+ assert (
+ GetModelCostMap.validate_model_cost_map(
+ fetched_map=shrunk,
+ backup_model_count=2000,
+ min_model_count=50,
+ max_shrink_ratio=0.5,
+ )
+ is False
+ )
+
+
+def test_finalize_pops_key_and_installs_rules():
+ previous = list(get_fallback_generalization_rules())
+ try:
+ raw = _make_models(2)
+ raw[FALLBACK_GENERALIZATIONS_KEY] = {
+ "rules": [
+ {
+ "name": "rule",
+ "pattern": r"^widget-",
+ "model_info": {"litellm_provider": "openai"},
+ }
+ ]
+ }
+ finalized = _finalize_model_cost_map(raw)
+
+ # The reserved key is removed from the returned model map ...
+ assert FALLBACK_GENERALIZATIONS_KEY not in finalized
+ # ... and its rules are installed into the generalizations module.
+ assert match_fallback_generalization("widget-9") == {
+ "litellm_provider": "openai"
+ }
+ finally:
+ set_fallback_generalizations(previous)
+
+
+def test_finalize_with_no_block_clears_rules():
+ previous = list(get_fallback_generalization_rules())
+ try:
+ set_fallback_generalizations(
+ [{"name": "stale", "pattern": r"^x", "model_info": {"a": 1}}]
+ )
+ _finalize_model_cost_map(_make_models(2))
+ assert match_fallback_generalization("x-1") is None
+ finally:
+ set_fallback_generalizations(previous)
+
+
+def test_shipped_backup_carries_the_anthropic_claude_rule():
+ """The bundled backup must ship the anthropic-claude rule so a fresh install
+ (or an offline fallback) routes unknown Claude models without code changes."""
+ backup = GetModelCostMap.load_local_model_cost_map()
+ rules = backup.get(FALLBACK_GENERALIZATIONS_KEY, {}).get("rules", [])
+ names = {r.get("name") for r in rules}
+ assert "anthropic-claude" in names
+
+ rule = next(r for r in rules if r.get("name") == "anthropic-claude")
+ assert rule["model_info"]["litellm_provider"] == "anthropic"
+
+ previous = list(get_fallback_generalization_rules())
+ try:
+ set_fallback_generalizations(rules)
+ matched = match_fallback_generalization("claude-opus-4-9")
+ assert matched is not None and matched["litellm_provider"] == "anthropic"
+ finally:
+ set_fallback_generalizations(previous)
+
+
+def test_shipped_backup_marks_claude_4_6_plus_adaptive_not_4_0():
+ """Adaptive thinking is data, not code. The bundled backup must carry
+ supports_adaptive_thinking on genuine Claude >= 4.6 entries (every provider
+ route) and on the version-gated anthropic-claude-adaptive-thinking rule for
+ unmapped future Claudes, while leaving the dated Claude 4.0 names
+ ("...-4-20250514") unflagged so a date can never be mistaken for a 4.6+ minor
+ version. The version-neutral anthropic-claude pricing rule must not flag it, so
+ an unmapped sub-4.6 name is priced but stays non-adaptive. The adaptive rule must
+ inherit pricing from the pricing rule via ``extends`` and carry only its delta, so
+ the Opus-tier price block is never duplicated across rules."""
+ backup = GetModelCostMap.load_local_model_cost_map()
+
+ rules = backup[FALLBACK_GENERALIZATIONS_KEY]["rules"]
+ pricing_rule = next(r for r in rules if r.get("name") == "anthropic-claude")
+ adaptive_rule = next(
+ r for r in rules if r.get("name") == "anthropic-claude-adaptive-thinking"
+ )
+ assert "supports_adaptive_thinking" not in pricing_rule["model_info"]
+ assert adaptive_rule["model_info"]["supports_adaptive_thinking"] is True
+
+ assert "extends" not in pricing_rule
+ assert adaptive_rule.get("extends") == "anthropic-claude"
+ assert adaptive_rule["model_info"] == {"supports_adaptive_thinking": True}
+
+ for adaptive in [
+ "anthropic.claude-opus-4-8",
+ "vertex_ai/claude-opus-4-6@default",
+ "us.anthropic.claude-sonnet-4-6",
+ "openrouter/anthropic/claude-opus-4.7",
+ "azure_ai/claude-opus-4-7",
+ ]:
+ assert backup[adaptive]["supports_adaptive_thinking"] is True, adaptive
+
+ for non_adaptive in [
+ "claude-opus-4-20250514",
+ "us.anthropic.claude-opus-4-20250514-v1:0",
+ "claude-opus-4-5",
+ ]:
+ assert "supports_adaptive_thinking" not in backup[non_adaptive], non_adaptive
diff --git a/tests/test_litellm/llms/anthropic/chat/test_anthropic_chat_transformation.py b/tests/test_litellm/llms/anthropic/chat/test_anthropic_chat_transformation.py
index 67eb5b12107..852479e81e4 100644
--- a/tests/test_litellm/llms/anthropic/chat/test_anthropic_chat_transformation.py
+++ b/tests/test_litellm/llms/anthropic/chat/test_anthropic_chat_transformation.py
@@ -2443,7 +2443,59 @@ def test_reasoning_effort_maps_to_adaptive_thinking_for_claude_4_6_models():
assert result["output_config"]["effort"] == effort_map[effort]
-def test_get_supported_params_includes_reasoning_for_sonnet_4_6_alias():
+def local_model_cost_map(monkeypatch):
+ original_model_cost = litellm.model_cost
+ monkeypatch.setenv("LITELLM_LOCAL_MODEL_COST_MAP", "True")
+ litellm.model_cost = litellm.get_model_cost_map(url="")
+ litellm.get_model_info.cache_clear()
+ try:
+ yield
+ finally:
+ litellm.model_cost = original_model_cost
+ litellm.get_model_info.cache_clear()
+
+
+ "model, expected",
+ [
+ # explicit cost-map entries, across provider routes / separators / date suffix
+ ("claude-opus-4-8", True),
+ ("anthropic.claude-opus-4-8", True),
+ ("vertex_ai/claude-opus-4-6@default", True),
+ ("openrouter/anthropic/claude-opus-4.7", True),
+ ("us.anthropic.claude-sonnet-4-6", True),
+ ("claude-opus-4-6-20260205", True),
+ # unmapped future models -> anthropic-claude fallback rule
+ ("claude-opus-4-9", True),
+ ("claude-sonnet-5-0", True),
+ # Claude 4.0 (dated): "4-20250514" must not be read as minor 4.20250514
+ ("claude-opus-4-20250514", False),
+ ("us.anthropic.claude-opus-4-20250514-v1:0", False),
+ ("bedrock/invoke/us.anthropic.claude-opus-4-20250514", False),
+ # sub-4.6 and legacy names
+ ("claude-opus-4-5", False),
+ ("claude-sonnet-4-5-20250929", False),
+ ("claude-3-7-sonnet", False),
+ ("claude-3-opus-20240229", False),
+ ("gpt-4o", False),
+ ],
+)
+def test_is_adaptive_thinking_model_is_sourced_from_cost_map(
+ local_model_cost_map, model, expected
+):
+ """Adaptive thinking resolves from the cost map first (an explicit
+ supports_adaptive_thinking entry, or the anthropic-claude fallback rule for unmapped
+ future Claudes), then from a date-safe opus/sonnet/haiku >= 4.6 name version as a
+ fallback for ids the cost map cannot resolve. The dated Claude 4.0 names stay
+ non-adaptive because the date suffix is not read as a minor version, while 4.8/4.9/5.x
+ are covered without a code change."""
+ assert AnthropicConfig._is_adaptive_thinking_model(model) is expected
+
+
+def test_get_supported_params_includes_reasoning_for_sonnet_4_6_alias(
+ local_model_cost_map,
+):
"""Sonnet 4.6 aliases should expose thinking + reasoning_effort in supported params."""
config = AnthropicConfig()
@@ -2453,8 +2505,12 @@ def test_get_supported_params_includes_reasoning_for_sonnet_4_6_alias():
assert "reasoning_effort" in params
-def test_get_supported_params_includes_reasoning_for_sonnet_4_6_dotted_alias():
- """Dotted Sonnet 4.6 aliases should expose thinking + reasoning_effort in supported params."""
+def test_get_supported_params_includes_reasoning_for_sonnet_4_6_dotted_alias(
+ local_model_cost_map,
+):
+ """Dotted Sonnet 4.6 aliases should expose thinking + reasoning_effort in supported
+ params. The anthropic-claude fallback rule accepts a dotted minor (4.6) as well as
+ a dashed one, so an unmapped dotted alias still degrades to adaptive thinking."""
config = AnthropicConfig()
params = config.get_supported_openai_params(model="claude-sonnet-4.6")
diff --git a/tests/test_litellm/llms/anthropic/test_anthropic_common_utils.py b/tests/test_litellm/llms/anthropic/test_anthropic_common_utils.py
index 105867164fd..a2fbb68bbb9 100644
--- a/tests/test_litellm/llms/anthropic/test_anthropic_common_utils.py
+++ b/tests/test_litellm/llms/anthropic/test_anthropic_common_utils.py
@@ -1636,7 +1636,7 @@ class TestClaudeOpus48AdaptiveThinking:
self, local_model_cost_map, model
):
"""Opus 4.6/4.7 and Sonnet 4.6 carry the ``supports_adaptive_thinking`` flag,
- so detection holds purely from the cost map with no name-based version
+ so detection holds purely from the cost map with no version-rule
fallback. Each alias form the Bedrock/anthropic paths see resolves to a flagged
base entry through candidate normalization: provider/region prefixes, a
Bedrock ``-v1:0`` version suffix (stripped fully for 4.7/4.8 keys or to ``-v1``
@@ -1650,15 +1650,66 @@ class TestClaudeOpus48AdaptiveThinking:
@pytest.mark.parametrize(
"model",
[
- "claude-opus-4-9",
- "claude-opus-4-8-some-future-suffix",
"us.anthropic.claude-fable-5-preview",
+ "claude-fable-5-preview",
+ ],
+ )
+ def test_unmapped_aliases_without_parseable_version_stay_non_adaptive(
+ self, local_model_cost_map, model
+ ):
+ """An alias absent from the map, not matched by any ``fallback_generalizations``
+ rule, and without a parseable opus/sonnet/haiku >= 4.6 family version stays
+ non-adaptive. ``fable`` is outside the version-rule family set, so neither the
+ cost map nor the declarative rule marks it adaptive."""
+ import litellm
+ from litellm.llms.anthropic.common_utils import AnthropicModelInfo
+
+ assert model not in litellm.model_cost
+ assert AnthropicModelInfo._is_adaptive_thinking_model(model) is False
+
+ @pytest.mark.parametrize(
+ "model",
+ [
+ "bedrock/invoke/us.anthropic.claude-opus-4-9",
+ "vertex_ai/claude-sonnet-5-0",
+ "us.anthropic.claude-opus-5-2",
+ "us.anthropic.claude-opus-6-1",
+ "claude-opus-5-0",
+ "claude-opus-4-10",
+ "claude-opus-4-8-some-future-suffix",
],
)
- def test_unmapped_aliases_defer_to_cost_map(self, local_model_cost_map, model):
- """Detection is sourced solely from the cost map flag: an alias absent from
- the map (a future release or a preview suffix) is not adaptive until a
- ``fallback_generalizations`` rule (PR #29718) covers it."""
+ def test_adaptive_thinking_version_fallback_for_unmapped_high_versions(
+ self, local_model_cost_map, model
+ ):
+ """Provider-prefixed or suffixed Claude names that resolve to no mapped entry and
+ are not matched by the anchored ``anthropic-claude`` pricing rule still resolve to
+ adaptive when their opus/sonnet/haiku family version is >= 4.6. The version gate is
+ the declarative ``anthropic-claude-adaptive-thinking`` rule, so 5.x, 6.x and any
+ later family are covered with no code change."""
+ import litellm
+ from litellm.llms.anthropic.common_utils import AnthropicModelInfo
+
+ assert model not in litellm.model_cost
+ assert AnthropicModelInfo._is_adaptive_thinking_model(model) is True
+
+ @pytest.mark.parametrize(
+ "model",
+ [
+ "claude-opus-4-0",
+ "us.anthropic.claude-opus-4-0",
+ "bedrock/invoke/us.anthropic.claude-opus-4-5",
+ "us.anthropic.claude-opus-4-20250514",
+ ],
+ )
+ def test_adaptive_thinking_not_detected_for_unmapped_low_versions(
+ self, local_model_cost_map, model
+ ):
+ """Unmapped Claude names below 4.6 stay non-adaptive through the declarative path.
+ The eight-digit dated Opus 4.0 id (``...-4-20250514``) is the date-safety case: the
+ version rule caps the minor at two digits, so the date is not misread as a >= 4.6
+ minor. The anchored pricing rule still resolves these for cost, just without the
+ adaptive flag."""
import litellm
from litellm.llms.anthropic.common_utils import AnthropicModelInfo
diff --git a/tests/test_litellm/test_utils.py b/tests/test_litellm/test_utils.py
index 6fdf22d0416..6f9f26bf6dd 100644
--- a/tests/test_litellm/test_utils.py
+++ b/tests/test_litellm/test_utils.py
@@ -45,6 +45,22 @@ def local_model_cost_map(monkeypatch):
litellm.get_model_info.cache_clear()
+def test_get_model_info_surfaces_supports_adaptive_thinking(local_model_cost_map):
+ """supports_adaptive_thinking must flow through get_model_info like every other
+ capability flag: both from an explicit cost-map entry and from a
+ fallback-generalization rule for an unmapped model. Regression: the field shipped
+ in the JSON but was never declared on ModelInfo nor copied during construction, so
+ get_model_info (and _supports_factory) silently dropped it for any provider-prefixed
+ or unmapped name."""
+ explicit = litellm.get_model_info(model="claude-opus-4-8")
+ assert explicit["supports_adaptive_thinking"] is True
+
+ generalized = litellm.get_model_info(
+ model="claude-opus-4-9", custom_llm_provider="anthropic"
+ )
+ assert generalized["supports_adaptive_thinking"] is True
+
+
def test_check_provider_match_azure_ai_allows_openai_and_azure():
"""
Test that azure_ai provider can match openai and azure models.
@@ -945,6 +961,9 @@ def test_aaamodel_prices_and_context_window_json_is_valid():
actual_json.pop(
"sample_spec", None
) # remove the sample, whose schema is inconsistent with the real data
+ actual_json.pop(
+ "fallback_generalizations", None
+ ) # reserved meta key, not a model entry
# Validate schema
validate(actual_json, INTENDED_SCHEMA)
@@ -1145,9 +1164,7 @@ def test_check_provider_match_none_value_matches_any_provider():
is True
)
# When custom_llm_provider is also None nothing constrains the match.
- assert (
- litellm.utils._check_provider_match({"litellm_provider": None}, None) is True
- )
+ assert litellm.utils._check_provider_match({"litellm_provider": None}, None) is True
def test_get_provider_rerank_config():
@@ -1512,8 +1529,7 @@ class TestProxyFunctionCalling:
assert result is True, "Resolvable model names work with fallback logic"
# Documentation notes:
- print(
- """
+ print("""
PROXY MODEL RESOLUTION BEHAVIOR:
✅ WORKS (with current fallback logic):
@@ -1528,8 +1544,7 @@ class TestProxyFunctionCalling:
💡 SOLUTION: Use LiteLLM proxy server with proper model_list configuration
that maps custom names to underlying models.
- """
- )
+ """)
@pytest.mark.parametrize(
"proxy_model_with_hints,expected_result",
@@ -1891,8 +1906,7 @@ class TestProxyFunctionCalling:
This test provides documentation on how the proxy server configuration
would typically map custom model names to underlying models.
"""
- print(
- """
+ print("""
REAL-WORLD PROXY SERVER CONFIGURATION EXAMPLE:
===============================================
@@ -1945,8 +1959,7 @@ class TestProxyFunctionCalling:
- Consistent request/response format
- Enhanced streaming support for function calls
- """
- )
+ """)
# Verify that direct underlying models work as expected
bedrock_models = [
@@ -2160,8 +2173,7 @@ class TestProxyFunctionCalling:
This test provides documentation on how the proxy server configuration
would typically map custom model names to underlying models.
"""
- print(
- """
+ print("""
REAL-WORLD PROXY SERVER CONFIGURATION EXAMPLE:
===============================================
@@ -2214,8 +2226,7 @@ class TestProxyFunctionCalling:
- Consistent request/response format
- Enhanced streaming support for function calls
- """
- )
+ """)
# Verify that direct underlying models work as expected
bedrock_models = [
@@ -2429,8 +2440,7 @@ class TestProxyFunctionCalling:
This test provides documentation on how the proxy server configuration
would typically map custom model names to underlying models.
"""
- print(
- """
+ print("""
REAL-WORLD PROXY SERVER CONFIGURATION EXAMPLE:
===============================================
@@ -2483,8 +2493,7 @@ class TestProxyFunctionCalling:
- Consistent request/response format
- Enhanced streaming support for function calls
- """
- )
+ """)
# Verify that direct underlying models work as expected
bedrock_models = [