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(cost-map): support s3:// URIs for LITELLM_MODEL_COST_MAP_URL (#46972)

Kerry Lu40efc6e07e25
diff --git a/litellm/litellm_core_utils/get_model_cost_map.py b/litellm/litellm_core_utils/get_model_cost_map.py
index fee48cca0cf..6e3769260cc 100644
--- a/litellm/litellm_core_utils/get_model_cost_map.py
+++ b/litellm/litellm_core_utils/get_model_cost_map.py
@@ -17,6 +17,7 @@ import random
import sys
import threading
import time
+import urllib.parse
from collections.abc import Awaitable, Callable, Mapping
from dataclasses import dataclass, replace
from datetime import datetime, timezone
@@ -24,11 +25,11 @@ from importlib.resources import files
from itertools import chain
from pathlib import Path
from types import MappingProxyType
-from typing import Final, Protocol
+from typing import Final, Protocol, cast # noqa: TID251 # adapts boto3 and botocore's dynamic client responses
import httpx
from pydantic import ConfigDict, TypeAdapter
-from typing_extensions import ReadOnly, TypedDict
+from typing_extensions import NotRequired, ReadOnly, TypedDict
from litellm import verbose_logger
from litellm.constants import (
@@ -266,6 +267,19 @@ class _SyncGetClient(Protocol):
def get(self, url: str, *, timeout: float | None = None) -> httpx.Response: ...
+class _S3Body(Protocol):
+ def read(self) -> bytes: ...
+
+
+class _S3GetObjectResponse(TypedDict):
+ Body: ReadOnly[_S3Body]
+ ETag: NotRequired[ReadOnly[str]]
+
+
+class _S3Client(Protocol):
+ def get_object(self, *, Bucket: str, Key: str) -> _S3GetObjectResponse: ...
+
+
_FetchAttemptOutcome = ModelCostMapReloaded | ModelCostMapReloadUnavailable | _FetchAttemptRetryable
@@ -276,6 +290,20 @@ def _default_reload_client() -> _AsyncGetClient:
return get_async_httpx_client(llm_provider=httpxSpecialProvider.ModelCostMap)
+def _default_s3_client(timeout: int) -> _S3Client:
+ import boto3
+ from botocore.config import Config
+
+ return cast( # cast-ok: boto3's generic client factory does not expose its generated S3 response type
+ _S3Client,
+ boto3.client( # pyright: ignore[reportUnknownMemberType] # generic factory returns Unknown service clients
+ "s3",
+ region_name=os.getenv("AWS_REGION_NAME") or None,
+ config=Config(connect_timeout=timeout, read_timeout=timeout, retries={"total_max_attempts": 1}),
+ ),
+ )
+
+
def _classify_fetch_error(error: httpx.HTTPError | httpx.InvalidURL, url: str) -> _FetchAttemptOutcome:
reason: Final = f"{type(error).__name__} fetching {url}: {error}"
if isinstance(error, (httpx.InvalidURL, httpx.UnsupportedProtocol)):
@@ -283,7 +311,41 @@ def _classify_fetch_error(error: httpx.HTTPError | httpx.InvalidURL, url: str) -
return _FetchAttemptRetryable(reason=reason, retry_after_seconds=None)
+def _classify_fetch_content(content: bytes, url: str, etag: str | None) -> _FetchAttemptOutcome:
+ try:
+ parsed: Final[object] = json.loads(content)
+ except ValueError as e:
+ return ModelCostMapReloadUnavailable(reason=f"invalid JSON from {url}: {e}")
+ if not isinstance(parsed, dict):
+ return ModelCostMapReloadUnavailable(reason=f"expected a JSON object from {url}, got {type(parsed).__name__}")
+ model_cost_map: Final = cast( # cast-ok: JSON object keys are strings by definition
+ dict[str, object], parsed
+ )
+ return ModelCostMapReloaded(model_cost_map=model_cost_map, revision=git_blob_id(content), etag=etag)
+
+
+def _attempt_fetch_s3(url: str, timeout: int) -> _FetchAttemptOutcome:
+ from botocore.exceptions import BotoCoreError, ClientError
+
+ parts: Final = urllib.parse.urlsplit(url)
+ bucket: Final = parts.netloc
+ key: Final = parts.path.lstrip("/")
+ if not bucket or not key:
+ return ModelCostMapReloadUnavailable(reason=f"invalid S3 URL {url}: expected s3://bucket/key")
+
+ try:
+ client: Final = _default_s3_client(timeout)
+ response: Final = client.get_object(Bucket=bucket, Key=key)
+ content: Final = response["Body"].read()
+ except (BotoCoreError, ClientError) as error:
+ return ModelCostMapReloadUnavailable(reason=f"S3 {type(error).__name__} fetching {url}: {error}")
+ return _classify_fetch_content(content, url, response.get("ETag"))
+
+
async def _attempt_fetch(client: _AsyncGetClient, url: str, timeout: int) -> _FetchAttemptOutcome:
+ parts: Final = urllib.parse.urlsplit(url)
+ if parts.scheme == "s3":
+ return await asyncio.to_thread(_attempt_fetch_s3, url, timeout)
try:
response: Final = await client.get(url, timeout=timeout)
except (httpx.HTTPError, httpx.InvalidURL) as e:
@@ -292,6 +354,9 @@ async def _attempt_fetch(client: _AsyncGetClient, url: str, timeout: int) -> _Fe
def _attempt_fetch_sync(client: _SyncGetClient, url: str, timeout: int) -> _FetchAttemptOutcome:
+ parts: Final = urllib.parse.urlsplit(url)
+ if parts.scheme == "s3":
+ return _attempt_fetch_s3(url, timeout)
try:
response: Final = client.get(url, timeout=timeout)
except (httpx.HTTPError, httpx.InvalidURL) as e:
@@ -307,15 +372,7 @@ def _classify_fetch_response(response: httpx.Response, url: str) -> _FetchAttemp
)
if response.is_error:
return ModelCostMapReloadUnavailable(reason=f"HTTP {response.status_code} from {url}")
- try:
- parsed: Final = response.json()
- except ValueError as e:
- return ModelCostMapReloadUnavailable(reason=f"invalid JSON from {url}: {e}")
- if not isinstance(parsed, dict):
- return ModelCostMapReloadUnavailable(reason=f"expected a JSON object from {url}, got {type(parsed).__name__}")
- return ModelCostMapReloaded(
- model_cost_map=parsed, revision=git_blob_id(response.content), etag=response.headers.get("etag")
- )
+ return _classify_fetch_content(response.content, url, response.headers.get("etag"))
def _next_retry_wait(
diff --git a/tests/unit/litellm_core_utils/test_get_model_cost_map.py b/tests/unit/litellm_core_utils/test_get_model_cost_map.py
index cf713d3684e..0256ecf24ed 100644
--- a/tests/unit/litellm_core_utils/test_get_model_cost_map.py
+++ b/tests/unit/litellm_core_utils/test_get_model_cost_map.py
@@ -10,7 +10,9 @@ import sys
import threading
from typing import Final
+import boto3
import pytest
+from typing_extensions import NotRequired, ReadOnly, TypedDict
from litellm.litellm_core_utils.fallback_generalizations import (
get_fallback_generalization_rules,
@@ -519,6 +521,47 @@ from tests._vcr_conftest_common import install_live_call_probe, record_vcr_outco
from unittest.mock import MagicMock, patch
+class _FakeS3Body:
+ def __init__(self, content: bytes) -> None:
+ self.content: Final = content
+
+ def read(self) -> bytes:
+ return self.content
+
+
+class _FakeS3GetObjectResponse(TypedDict):
+ Body: ReadOnly[_FakeS3Body]
+ ETag: NotRequired[ReadOnly[str]]
+
+
+class _FakeS3Client:
+ def __init__(self, content: bytes) -> None:
+ self.content: Final = content
+ self.calls: list[tuple[str, str]] = []
+
+ def get_object(self, *, Bucket: str, Key: str) -> _FakeS3GetObjectResponse:
+ self.calls.append((Bucket, Key))
+ return {"Body": _FakeS3Body(self.content), "ETag": '"fake-etag"'}
+
+
+def test_get_model_cost_map_fetches_s3_catalog(monkeypatch: pytest.MonkeyPatch) -> None:
+ from litellm.litellm_core_utils import get_model_cost_map as module
+
+ source_info = module._cost_map_source_info
+ for name in ("source", "url", "is_env_forced", "fallback_reason", "loaded_at", "source_revision", "etag"):
+ monkeypatch.setattr(source_info, name, getattr(source_info, name))
+
+ s3_content: Final = _make_models(GetModelCostMap.get_backup_model_count())
+ s3_client: Final = _FakeS3Client(json.dumps(s3_content).encode())
+ monkeypatch.setattr(boto3, "client", lambda *args, **kwargs: s3_client)
+
+ cost_map: Final = get_model_cost_map("s3://my-bucket/prices/model_prices.json")
+
+ assert cost_map == s3_content
+ assert s3_client.calls == [("my-bucket", "prices/model_prices.json")]
+ assert get_model_cost_map_source_info()["source"] == "remote"
+
+
class _SyncSleepRecorder:
"""Injected in place of time.sleep so the boot path's waits are asserted without delay."""
@@ -955,6 +998,14 @@ class TestGetModelCostMapFallback:
assert result.keys() == _backup_keys()
assert source["source"] == "local"
+ def test_should_fallback_when_fetched_json_is_not_object(self, monkeypatch):
+ result, fetches, source = _fetch_with_single_outcome(monkeypatch, httpx.Response(200, content=b"[]"))
+
+ assert fetches == 1
+ assert result.keys() == _backup_keys()
+ assert source["source"] == "local"
+ assert source["fallback_reason"] == f"Remote fetch failed: expected a JSON object from {_URL}, got list"
+
def test_should_fallback_when_fetched_map_shrinks_dramatically(self, monkeypatch):
"""When upstream returns far fewer models than backup, should fall back."""
tiny_map = {f"model-{i}": {"litellm_provider": "test"} for i in range(11)}