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]

merge: litellm_internal_staging into litellm_cost_map_background_retries

kerry7d5283269236
diff --cc litellm/litellm_core_utils/get_model_cost_map.py
index 4118cd3420e,cdc4810ff04..90ff696f926
--- a/litellm/litellm_core_utils/get_model_cost_map.py
+++ b/litellm/litellm_core_utils/get_model_cost_map.py
@@@ -12,10 -13,9 +13,10 @@@ import hashli
import json
import os
import random
+import threading
import time
from collections.abc import Awaitable, Callable
- from dataclasses import dataclass
+ from dataclasses import dataclass, replace
from datetime import datetime, timezone
from importlib.resources import files
from typing import Final, Protocol
@@@ -480,70 -514,12 +530,75 @@@ def _finalize_model_cost_map(model_cost
return _expand_model_aliases(model_cost)
+ def _finalize_loaded_model_cost_map(loaded: ModelCostMapReloaded) -> ModelCostMapReloaded:
+ _cost_map_source_info.source_revision = loaded.revision
+ _cost_map_source_info.etag = loaded.etag
+ return replace(loaded, model_cost_map=_finalize_model_cost_map(loaded.model_cost_map))
+
+
+def adopt_model_cost_map(
+ new_model_cost_map: dict, # mutable-ok: public API preserves the mutable cost-map contract
+) -> int:
+ import litellm
+ from litellm import utils
+
+ litellm.model_cost = new_model_cost_map
+ utils._invalidate_model_cost_lowercase_map() # pyright: ignore[reportPrivateUsage] # required cache invalidation
+ litellm.add_known_models(model_cost_map=new_model_cost_map)
+ fetched_model_count: Final = len(new_model_cost_map) if new_model_cost_map else 0
+ utils.reapply_runtime_model_cost_registrations()
+ return fetched_model_count
+
+
+def _continue_remote_fetch_in_background(
+ url: str,
+ timeout: int,
+ max_attempts: int,
+ sleep: Callable[[float], None],
+ rng: random.Random,
+ client: _SyncGetClient,
+ first_outcome: _FetchAttemptRetryable,
+ apply: Callable[[dict], object], # mutable-ok: injected callback receives the mutable cost-map dict
+) -> None:
+ try:
+ result: Final = _fetch_remote_model_cost_map_with_retry_sync(
+ url=url,
+ timeout=timeout,
+ max_attempts=max_attempts,
+ sleep=sleep,
+ rng=rng,
+ client=client,
+ initial_outcome=first_outcome,
+ )
+ if isinstance(result, ModelCostMapReloadUnavailable):
+ verbose_logger.warning(
+ "LiteLLM: Failed to fetch remote model cost map from %s after %d attempts; keeping local backup",
+ url,
+ max_attempts,
+ )
+ return
+ backup_model_count: Final = GetModelCostMap._get_backup_model_count() # pyright: ignore[reportPrivateUsage] # integrity cache
+ if not GetModelCostMap.validate_model_cost_map(
+ fetched_map=result.model_cost_map,
+ backup_model_count=backup_model_count,
+ ):
+ verbose_logger.warning(
+ "LiteLLM: Fetched model cost map failed integrity check. Keeping local backup. url=%s",
+ url,
+ )
+ _cost_map_source_info.fallback_reason = "Remote data failed integrity validation"
+ return
- finalized_map: Final = _finalize_model_cost_map(result.model_cost_map)
+ _litellm_import_complete.wait()
- apply(finalized_map)
++ apply(_finalize_loaded_model_cost_map(result).model_cost_map)
+ _cost_map_source_info.source = "remote"
+ _cost_map_source_info.url = url
+ _cost_map_source_info.is_env_forced = False
+ _cost_map_source_info.fallback_reason = None
+ _cost_map_source_info.loaded_at = datetime.now(timezone.utc)
+ except Exception as e:
+ verbose_logger.warning("LiteLLM: Background model cost map retry failed: %s", e)
+
+
def get_model_cost_map(
url: str,
timeout: int = 5,
@@@ -582,35 -553,14 +637,37 @@@
_cost_map_source_info.url = url
_cost_map_source_info.is_env_forced = False
- result: Final = _fetch_remote_model_cost_map_with_retry_sync(
- url=url,
- timeout=timeout,
- max_attempts=max_attempts,
- sleep=sleep,
- rng=rng if rng is not None else random.Random(),
- client=client if client is not None else httpx,
- )
+ fetch_client: Final = client if client is not None else httpx
+ fetch_rng: Final = rng if rng is not None else random.Random()
+ first_outcome: Final = _attempt_fetch_sync(client=fetch_client, url=url, timeout=timeout)
+ if isinstance(first_outcome, _FetchAttemptRetryable):
+ verbose_logger.warning(
+ "LiteLLM: model cost map fetch attempt 1/%d failed: %s; "
+ "using local backup while retrying in the background",
+ max_attempts,
+ first_outcome.reason,
+ )
+ _cost_map_source_info.source = "local"
+ _cost_map_source_info.fallback_reason = f"Remote fetch failed: {first_outcome.reason}"
- local_map: Final = _finalize_model_cost_map(GetModelCostMap.load_local_model_cost_map())
++ local_map: Final = _finalize_loaded_model_cost_map(
++ GetModelCostMap.load_local_model_cost_map_with_revision()
++ ).model_cost_map
+ if max_attempts > 1:
+ start_background(
+ lambda: _continue_remote_fetch_in_background(
+ url=url,
+ timeout=timeout,
+ max_attempts=max_attempts,
+ sleep=sleep,
+ rng=fetch_rng,
+ client=fetch_client,
+ first_outcome=first_outcome,
+ apply=apply,
+ )
+ )
+ return local_map
+
+ result: Final = first_outcome
if isinstance(result, ModelCostMapReloadUnavailable):
verbose_logger.warning(
"LiteLLM: Failed to fetch remote model cost map from %s: %s. Falling back to local backup.",
diff --cc tests/test_litellm/litellm_core_utils/test_get_model_cost_map.py
index dce1a431f13,0495440c51c..e39658a8f37
--- 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
@@@ -20,7 -20,8 +20,9 @@@ from litellm.litellm_core_utils.get_mod
GetModelCostMap,
_count_model_entries,
_finalize_model_cost_map,
+ adopt_model_cost_map,
+ get_model_cost_map_provenance,
+ git_blob_id,
)
@@@ -30,8 -33,20 +32,18 @@@ def _load_root_cost_map() -> dict
return json.load(f)
+ def _bundled_blob_id() -> str:
+ path = os.path.join(os.path.dirname(__file__), "../../../litellm/model_prices_and_context_window_backup.json")
+ with open(path, "rb") as f:
+ return git_blob_id(f.read())
+
+
+ def test_git_blob_id_is_what_git_hash_object_prints():
+ assert git_blob_id(b'{"gpt-5.4-mini": {"mode": "chat"}}\n') == "18b9a8381e13a3b38a2128f184f631f95829e987"
+
+
def _make_models(n: int) -> dict:
- return {
- f"model-{i}": {"litellm_provider": "openai", "mode": "chat"} for i in range(n)
- }
+ return {f"model-{i}": {"litellm_provider": "openai", "mode": "chat"} for i in range(n)}
def test_count_model_entries_excludes_reserved_keys():
@@@ -300,8 -317,9 +312,7 @@@ def test_get_model_cost_map_stamps_load
from litellm.litellm_core_utils import get_model_cost_map as module
- monkeypatch.setattr(module._cost_map_source_info, "loaded_at", None)
- client, _calls = _mock_client(
- [httpx.Response(200, content=_real_map_bytes())], client_cls=httpx.Client
- )
+ client, _calls = _mock_client([httpx.Response(200, content=_real_map_bytes())], client_cls=httpx.Client)
before = datetime.now(timezone.utc)
module.get_model_cost_map(url="https://example.invalid/cost_map.json", client=client)
@@@ -697,3 -665,49 +770,51 @@@ def test_boot_load_respects_local_env_o
)
assert len(cost_map) > 100
assert get_model_cost_map_source_info()["is_env_forced"] is True
+
+
+ def test_boot_load_records_the_blob_id_of_the_bytes_served_and_the_fetch_etag():
+ body = _real_map_bytes()
+ client, _ = _mock_client([httpx.Response(200, headers={"ETag": 'W/"boot"'}, content=body)], client_cls=httpx.Client)
+
+ get_model_cost_map(url=_URL, sleep=_SyncSleepRecorder(), rng=random.Random(0), client=client)
+
+ source = get_model_cost_map_source_info()
+ assert source["source"] == "remote"
+ assert source["etag"] == 'W/"boot"'
+ assert source["source_revision"] == git_blob_id(body)
+ assert source["loaded_at"] is not None
+
+
+ def test_boot_load_fallback_to_the_backup_reports_its_blob_id_and_drops_the_remote_etag():
+ remote, _ = _mock_client(
+ [httpx.Response(200, headers={"ETag": 'W/"boot"'}, content=_real_map_bytes())], client_cls=httpx.Client
+ )
+ get_model_cost_map(url=_URL, sleep=_SyncSleepRecorder(), rng=random.Random(0), client=remote)
+ failing, _ = _mock_client([httpx.Response(404)], client_cls=httpx.Client)
+
+ get_model_cost_map(url=_URL, sleep=_SyncSleepRecorder(), rng=random.Random(0), client=failing)
+
+ source = get_model_cost_map_source_info()
+ assert source["source"] == "local"
+ assert source["etag"] is None
+ assert source["source_revision"] == _bundled_blob_id()
+
+
+ def test_boot_load_that_fails_the_integrity_check_reports_the_backup_not_the_rejected_fetch():
+ remote, _ = _mock_client(
+ [httpx.Response(200, headers={"ETag": 'W/"boot"'}, content=_real_map_bytes())], client_cls=httpx.Client
+ )
+ get_model_cost_map(url=_URL, sleep=_SyncSleepRecorder(), rng=random.Random(0), client=remote)
+ shrunk_body = b'{"gpt-5.4-mini": {"mode": "chat", "input_cost_per_token": 1e-06, "output_cost_per_token": 2e-06}}'
- shrunk, _ = _mock_client([httpx.Response(200, headers={"ETag": 'W/"shrunk"'}, content=shrunk_body)], client_cls=httpx.Client)
++ shrunk, _ = _mock_client(
++ [httpx.Response(200, headers={"ETag": 'W/"shrunk"'}, content=shrunk_body)], client_cls=httpx.Client
++ )
+
+ get_model_cost_map(url=_URL, sleep=_SyncSleepRecorder(), rng=random.Random(0), client=shrunk)
+
+ source = get_model_cost_map_source_info()
+ assert source["source"] == "local"
+ assert source["fallback_reason"] == "Remote data failed integrity validation"
+ assert source["etag"] is None
+ assert source["source_revision"] == _bundled_blob_id()
+ assert source["source_revision"] != git_blob_id(shrunk_body)