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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix: resolve merge conflicts with main
Chesarsfa1b1de99e5c
diff --cc litellm/litellm_core_utils/get_model_cost_map.pyindex a3e4429dfaa,7679358bbc6..2930a9ef5de--- a/litellm/litellm_core_utils/get_model_cost_map.py+++ b/litellm/litellm_core_utils/get_model_cost_map.py@@@ -8,41 -8,237 +8,252 @@@ export LITELLM_LOCAL_MODEL_COST_MAP=Tru```"""+ import jsonimport os+from pathlib import Path++ from importlib.resources import files+ from typing import Dict, List, Optional+import httpx+ from litellm import verbose_logger+ from litellm.constants import (+ MODEL_COST_MAP_MAX_SHRINK_RATIO,+ MODEL_COST_MAP_MIN_MODEL_COUNT,+ )- def _load_local_model_cost_map() -> dict:- """Load model cost map from local filesystem.- Tries to load from:- 1. Package resources (production, after pip install)- 2. Project root (development)+ class GetModelCostMap:"""- import json+ Handles fetching, validating, and loading the model cost map.- # Try loading from package resources (production)- try:- import importlib.resources- with importlib.resources.files("litellm").joinpath(- "model_prices_and_context_window.json"- ).open("r") as f:- return json.load(f)- except (FileNotFoundError, ModuleNotFoundError):- pass+ Only the backup model *count* is cached (a single int). The full+ backup dict is never held in memory — it is only parsed when it+ needs to be *returned* as a fallback.+ """++ _backup_model_count: int = -1 # -1 = not yet loaded++ @staticmethod+ def load_local_model_cost_map() -> dict:- """Load the local backup model cost map bundled with the package."""- content = json.loads(- files("litellm")- .joinpath("model_prices_and_context_window_backup.json")- .read_text(encoding="utf-8")- )- return content++ """Load the local model cost map.++++ Tries to load from:++ 1. Package resources (production, after pip install)++ 2. Project root (development)++ """++ try:++ content = json.loads(++ files("litellm")++ .joinpath("model_prices_and_context_window.json")++ .read_text(encoding="utf-8")++ )++ return content++ except (FileNotFoundError, ModuleNotFoundError):++ pass+- # Try loading from project root (development)- try:+ current_dir = Path(__file__).parent.parent.parent+ model_cost_map_path = current_dir / "model_prices_and_context_window.json"+ with open(model_cost_map_path, "r") as f:+ return json.load(f)- except FileNotFoundError:- raise FileNotFoundError(- "Could not find model_prices_and_context_window.json in package or project root"- )++ @classmethod+ def _get_backup_model_count(cls) -> int:+ """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)+ return cls._backup_model_count++ @staticmethod+ def _check_is_valid_dict(fetched_map: dict) -> bool:+ """Check 1: fetched map is a non-empty dict."""+ if not isinstance(fetched_map, dict):+ verbose_logger.warning(+ "LiteLLM: Fetched model cost map is not a dict (type=%s). "+ "Falling back to local backup.",+ type(fetched_map).__name__,+ )+ return False++ if len(fetched_map) == 0:+ verbose_logger.warning(+ "LiteLLM: Fetched model cost map is empty. "+ "Falling back to local backup.",+ )+ return False++ return True++ @classmethod+ def _check_model_count_not_reduced(+ cls,+ fetched_map: dict,+ backup_model_count: int,+ min_model_count: int = MODEL_COST_MAP_MIN_MODEL_COUNT,+ 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)++ if fetched_count < min_model_count:+ verbose_logger.warning(+ "LiteLLM: Fetched model cost map has only %d models (minimum=%d). "+ "This may indicate a corrupted upstream file. "+ "Falling back to local backup.",+ fetched_count,+ min_model_count,+ )+ return False++ if (+ backup_model_count > 0+ and fetched_count < backup_model_count * max_shrink_ratio+ ):+ verbose_logger.warning(+ "LiteLLM: Fetched model cost map shrank significantly "+ "(fetched=%d, backup=%d, threshold=%.0f%%). "+ "This may indicate a corrupted upstream file. "+ "Falling back to local backup.",+ fetched_count,+ backup_model_count,+ max_shrink_ratio * 100,+ )+ return False++ return True++ @classmethod+ def validate_model_cost_map(+ cls,+ fetched_map: dict,+ backup_model_count: int,+ min_model_count: int = MODEL_COST_MAP_MIN_MODEL_COUNT,+ max_shrink_ratio: float = MODEL_COST_MAP_MAX_SHRINK_RATIO,+ ) -> bool:+ """+ Validate the integrity of a fetched model cost map.++ Runs each check in order and returns False on the first failure.++ Checks:+ 1. ``_check_is_valid_dict`` -- fetched map is a non-empty dict.+ 2. ``_check_model_count_not_reduced`` -- model count meets minimum+ and has not shrunk >``max_shrink_ratio`` vs backup.++ Returns True if all checks pass, False otherwise.+ """+ if not cls._check_is_valid_dict(fetched_map):+ return False++ if not cls._check_model_count_not_reduced(+ fetched_map=fetched_map,+ backup_model_count=backup_model_count,+ min_model_count=min_model_count,+ max_shrink_ratio=max_shrink_ratio,+ ):+ return False++ return True++ @staticmethod+ def fetch_remote_model_cost_map(url: str, timeout: int = 5) -> dict:+ """+ Fetch the model cost map from a remote URL.++ Returns the parsed JSON dict. Raises on network/parse errors+ (caller is expected to handle).+ """+ response = httpx.get(url, timeout=timeout)+ response.raise_for_status()+ return response.json()+++ class ModelCostMapSourceInfo:+ """Tracks the source of the currently loaded model cost map."""++ source: str = "local" # "local" or "remote"+ url: Optional[str] = None+ is_env_forced: bool = False+ fallback_reason: Optional[str] = None+++ # Module-level singleton tracking the source of the current cost map+ _cost_map_source_info = ModelCostMapSourceInfo()+++ def get_model_cost_map_source_info() -> dict:+ """+ Return metadata about where the current model cost map was loaded from.++ Returns a dict with:+ - source: "local" or "remote"+ - url: the remote URL attempted (or None for local-only)+ - is_env_forced: True if LITELLM_LOCAL_MODEL_COST_MAP=True forced local usage+ - fallback_reason: human-readable reason if remote failed and local was used+ """+ return {+ "source": _cost_map_source_info.source,+ "url": _cost_map_source_info.url,+ "is_env_forced": _cost_map_source_info.is_env_forced,+ "fallback_reason": _cost_map_source_info.fallback_reason,+ }+++ def _expand_model_aliases(model_cost: dict) -> dict:+ """+ Expand ``aliases`` lists in model cost entries into top-level entries.++ Each alias gets a reference to the **same** dict object as the canonical+ entry (zero memory overhead). The ``aliases`` key is removed from the+ entry so downstream code never sees it.++ If an alias collides with an existing canonical entry the alias is+ skipped and a warning is logged.+ """+ aliases_to_add: Dict[str, dict] = {}+ keys_with_aliases: List[str] = []++ for model_name, model_info in model_cost.items():+ aliases: Optional[list] = model_info.get("aliases")+ if aliases is None:+ continue+ keys_with_aliases.append(model_name)+ if not isinstance(aliases, list):+ verbose_logger.warning(+ "LiteLLM model alias field for '%s' is not a list (got %s) — skipping.",+ model_name,+ type(aliases).__name__,+ )+ continue+ if not aliases:+ continue+ for alias in aliases:+ if alias in model_cost:+ verbose_logger.warning(+ "LiteLLM model alias conflict: alias '%s' (from '%s') "+ "already exists as a canonical entry — skipping.",+ alias,+ model_name,+ )+ continue+ if alias in aliases_to_add:+ verbose_logger.warning(+ "LiteLLM model alias conflict: alias '%s' (from '%s') "+ "was already claimed by another entry — skipping.",+ alias,+ model_name,+ )+ continue+ aliases_to_add[alias] = model_info # same dict reference++ # Remove the ``aliases`` key from entries so it doesn't pollute model info+ for key in keys_with_aliases:+ model_cost[key].pop("aliases", None)++ model_cost.update(aliases_to_add)+ return model_costdef get_model_cost_map(url: str) -> dict:diff --cc tests/test_litellm/test_deepseek_model_metadata.pyindex 00000000000,4900af5d97d..36814b00300mode 000000,100644..100644--- a/tests/test_litellm/test_deepseek_model_metadata.py+++ b/tests/test_litellm/test_deepseek_model_metadata.py@@@ -1,0 -1,180 +1,189 @@@+ """+ Regression tests for #20885 – ``supports_response_schema`` (and related+ capability flags) must be consistent between the bare model-name entry+ (e.g. ``deepseek-chat``) and the provider-prefixed entry+ (e.g. ``deepseek/deepseek-chat``) in the model-cost map.++ The bug caused ``supports_response_schema("deepseek/deepseek-chat")`` to+ return ``False`` even though the canonical ``deepseek-chat`` entry has the+ field set to ``True``.+ """++ import json+ import os+ import sys++ sys.path.insert(+ 0, os.path.abspath("../..")+ ) # Adds the parent directory to the system path++ import litellm+ from litellm.utils import (+ _supports_factory,+ supports_response_schema,+ )+++ # ---------------------------------------------------------------------------+ # Data-level tests – verify the JSON files are in sync+ # ---------------------------------------------------------------------------+++ def _load_backup_json() -> dict:- """Load the backup JSON directly from disk."""- backup_path = os.path.join(++ """Load the model cost JSON directly from disk."""++ # Try project root first (development)++ root_path = os.path.join(++ os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),++ "model_prices_and_context_window.json",++ )++ if os.path.exists(root_path):++ with open(root_path, encoding="utf-8") as f:++ return json.load(f)++ # Fallback to package resources (production)++ pkg_path = os.path.join(+ os.path.dirname(litellm.__file__),- "model_prices_and_context_window_backup.json",++ "model_prices_and_context_window.json",+ )- with open(backup_path, encoding="utf-8") as f:++ with open(pkg_path, encoding="utf-8") as f:+ return json.load(f)+++ class TestDeepSeekModelCostEntries:+ """Verify that provider-prefixed DeepSeek entries contain the same+ capability flags as their bare-name counterparts in the JSON files."""++ def test_deepseek_chat_supports_response_schema_in_backup(self):+ data = _load_backup_json()+ entry = data.get("deepseek/deepseek-chat", {})+ assert entry.get("supports_response_schema") is True++ def test_deepseek_reasoner_supports_response_schema_in_backup(self):+ data = _load_backup_json()+ entry = data.get("deepseek/deepseek-reasoner", {})+ assert entry.get("supports_response_schema") is True++ def test_deepseek_chat_supports_system_messages_in_backup(self):+ data = _load_backup_json()+ entry = data.get("deepseek/deepseek-chat", {})+ assert entry.get("supports_system_messages") is True++ def test_deepseek_reasoner_supports_system_messages_in_backup(self):+ data = _load_backup_json()+ entry = data.get("deepseek/deepseek-reasoner", {})+ assert entry.get("supports_system_messages") is True++ def test_deepseek_chat_max_input_tokens_matches_bare_in_backup(self):+ data = _load_backup_json()+ bare = data.get("deepseek-chat", {})+ prefixed = data.get("deepseek/deepseek-chat", {})+ assert prefixed.get("max_input_tokens") == bare.get("max_input_tokens")++ def test_deepseek_reasoner_max_output_tokens_matches_bare_in_backup(self):+ data = _load_backup_json()+ bare = data.get("deepseek-reasoner", {})+ prefixed = data.get("deepseek/deepseek-reasoner", {})+ assert prefixed.get("max_output_tokens") == bare.get("max_output_tokens")++ def test_main_json_deepseek_chat_supports_response_schema(self):+ main_path = os.path.join(+ os.path.dirname(os.path.dirname(litellm.__file__)),+ "model_prices_and_context_window.json",+ )+ with open(main_path, encoding="utf-8") as f:+ data = json.load(f)+ entry = data.get("deepseek/deepseek-chat", {})+ assert entry.get("supports_response_schema") is True++ def test_main_json_deepseek_reasoner_supports_response_schema(self):+ main_path = os.path.join(+ os.path.dirname(os.path.dirname(litellm.__file__)),+ "model_prices_and_context_window.json",+ )+ with open(main_path, encoding="utf-8") as f:+ data = json.load(f)+ entry = data.get("deepseek/deepseek-reasoner", {})+ assert entry.get("supports_response_schema") is True+++ # ---------------------------------------------------------------------------+ # API-level tests – verify supports_response_schema returns True+ # ---------------------------------------------------------------------------+++ class TestSupportsResponseSchemaDeepSeek:+ """All calling conventions for DeepSeek should return True for+ ``supports_response_schema``."""++ def test_provider_slash_model(self):+ assert supports_response_schema(model="deepseek/deepseek-chat") is True++ def test_explicit_provider(self):+ assert (+ supports_response_schema(+ model="deepseek-chat", custom_llm_provider="deepseek"+ )+ is True+ )++ def test_reasoner_provider_slash_model(self):+ assert supports_response_schema(model="deepseek/deepseek-reasoner") is True++ def test_reasoner_explicit_provider(self):+ assert (+ supports_response_schema(+ model="deepseek-reasoner", custom_llm_provider="deepseek"+ )+ is True+ )+++ # ---------------------------------------------------------------------------+ # Fallback-logic test – bare model entry used when prefixed is incomplete+ # ---------------------------------------------------------------------------+++ class TestBareModelFallback:+ """When a provider-prefixed entry is missing a capability flag, the+ ``_supports_factory`` fallback should consult the bare model-name+ entry in ``litellm.model_cost``."""++ def test_fallback_uses_bare_entry(self):+ """Temporarily remove ``supports_response_schema`` from the prefixed+ entry and verify the fallback still returns True."""+ key = "deepseek/deepseek-chat"+ original = litellm.model_cost.get(key, {}).get("supports_response_schema")+ try:+ # Simulate the pre-fix state: field missing from prefixed entry+ if key in litellm.model_cost:+ litellm.model_cost[key].pop("supports_response_schema", None)+ result = _supports_factory(+ model="deepseek-chat",+ custom_llm_provider="deepseek",+ key="supports_response_schema",+ )+ assert result is True+ finally:+ # Restore+ if key in litellm.model_cost and original is not None:+ litellm.model_cost[key]["supports_response_schema"] = original++ def test_no_fallback_when_explicitly_false(self):+ """If the prefixed entry explicitly sets a capability to ``False``,+ the fallback must NOT override it."""+ key = "deepseek/deepseek-reasoner"+ # After the data fix, deepseek/deepseek-reasoner has+ # supports_function_calling=false (matching the bare entry).+ # Explicitly set it to False to test the guard.+ original = litellm.model_cost.get(key, {}).get("supports_function_calling")+ try:+ if key in litellm.model_cost:+ litellm.model_cost[key]["supports_function_calling"] = False+ result = _supports_factory(+ model="deepseek-reasoner",+ custom_llm_provider="deepseek",+ key="supports_function_calling",+ )+ assert result is False+ finally:+ if key in litellm.model_cost and original is not None:+ litellm.model_cost[key]["supports_function_calling"] = original