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 remote-tracking branch 'origin/litellm_internal_staging' into litellm_fix_v1_models_alias_resolution

michelligabriele93b15ed42834
diff --cc litellm/proxy/utils.py
index f891c85320a,00ccad33b6d..d38938fface
--- a/litellm/proxy/utils.py
+++ b/litellm/proxy/utils.py
@@@ -7587,47 -7979,35 +8061,52 @@@ def create_model_info_response
"owned_by": provider,
}
- try:
- model_cost_info: ModelInfo | None = get_model_info(model_id)
- except Exception as e:
- verbose_proxy_logger.debug(
- "create_model_info_response: cost map lookup failed for %s: %s",
- model_id,
- e,
+ listing_info: Final = llm_router.get_model_listing_info(model_id) if llm_router is not None else None
+
+ # One entry per distinct model behind the listed name; (None,) when the router knows
+ # nothing about it, so the listed name is resolved on its own as before.
+ deployment_models: Final[tuple[str | None, ...]] = (
+ listing_info.cost_map_keys if listing_info is not None and listing_info.cost_map_keys else (None,)
+ )
+ listed_info: Final = _safe_get_model_info(model_id, get_model_info)
+ candidate_sets: Final = tuple(
+ _resolve_listing_model_info(
+ deployment_model=deployment_model,
+ listed_model=model_id,
+ listed_info=listed_info,
+ get_model_info=get_model_info,
)
- model_cost_info = None
+ for deployment_model in deployment_models
+ )
+
+ max_input_tokens: int | None = _group_token_limit(candidate_sets, "max_input_tokens")
+ max_output_tokens: int | None = _group_token_limit(candidate_sets, "max_output_tokens")
+ mode: Final = next(
+ (
+ m
+ for m in (
+ cast("Mapping[str, object]", info).get("mode") # cast-ok: an entry need not carry "mode"
+ for candidates in candidate_sets
+ for info in candidates
+ )
+ if isinstance(m, str)
+ ),
+ None,
+ )
+ if mode is not None:
+ base["mode"] = mode
- max_input_tokens: int | None = None
- max_output_tokens: int | None = None
- if model_cost_info is not None:
- max_input_tokens = coerce_token_limit(model_cost_info.get("max_input_tokens"))
- max_output_tokens = coerce_token_limit(model_cost_info.get("max_output_tokens"))
- mode: Final = model_cost_info.get("mode")
- if isinstance(mode, str):
- base["mode"] = mode
+ if listing_info is not None:
+ if listing_info.max_input_tokens is not None:
+ max_input_tokens = listing_info.max_input_tokens
+ if listing_info.max_output_tokens is not None:
+ max_output_tokens = listing_info.max_output_tokens
+ if llm_router is not None:
- configured_input, configured_output = llm_router.get_configured_token_limits(model_id)
- if configured_input is not None:
- max_input_tokens = configured_input
- if configured_output is not None:
- max_output_tokens = configured_output
+ configured_mode: Final = llm_router.get_configured_mode(model_id)
+ if isinstance(configured_mode, str):
+ base["mode"] = configured_mode
+
if max_input_tokens is not None:
base["max_input_tokens"] = max_input_tokens
if max_output_tokens is not None:
diff --cc tests/test_litellm/proxy/test_proxy_utils.py
index 90e7431a22d,b78ec7dcff6..1287cf23157
--- a/tests/test_litellm/proxy/test_proxy_utils.py
+++ b/tests/test_litellm/proxy/test_proxy_utils.py
@@@ -945,11 -943,50 +946,52 @@@ def test_create_model_info_response_use
assert response["max_output_tokens"] == 8000
+ def test_create_model_info_response_uses_deployment_mode_for_auto_router():
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "claude-sonnet",
+ "litellm_params": {"model": "openai/gpt-4o-mini", "api_key": "test-key"},
+ },
+ {
+ "model_name": "claude-auto",
+ "litellm_params": {
+ "model": "auto_router/complexity_router",
+ "complexity_router_config": {
+ "tiers": {
+ "SIMPLE": "claude-sonnet",
+ "MEDIUM": "claude-sonnet",
+ "COMPLEX": "claude-sonnet",
+ }
+ },
+ "complexity_router_default_model": "claude-sonnet",
+ },
+ "model_info": {
+ "mode": "chat",
+ "max_input_tokens": 1_000_000,
+ "max_output_tokens": 128_000,
+ },
+ },
+ ]
+ )
+
+ response = create_model_info_response(
+ model_id="claude-auto",
+ provider="openai",
+ llm_router=router,
+ get_model_info=_raise_unmapped,
+ )
+
+ assert response["mode"] == "chat"
+ assert response["max_input_tokens"] == 1_000_000
+ assert response["max_output_tokens"] == 128_000
+
+
def test_create_model_info_response_deployment_limits_override_cost_map():
router = MagicMock()
- router.get_configured_token_limits.return_value = (200000, None)
+ router.get_model_listing_info.return_value = DeploymentModelListingInfo(
+ cost_map_keys=("gpt-4o",), max_input_tokens=200000, max_output_tokens=None
+ )
response = create_model_info_response(
model_id="gpt-4o",
@@@ -1933,117 -1960,81 +2013,197 @@@ async def test_proxy_only_error_5xx_kee
assert "test_proxy_utils" in captured["async_traceback"]
+def test_create_model_info_response_resolves_alias_to_deployment_model():
+ """A public model name that is not itself a cost-map key must not be resolved through
+ the fallback-generalization rules: `bedrock-claude-opus-5` matches the generic
+ claude-family baseline (200k/64k) by substring, while the deployment it fronts really
+ accepts 1M/128k. Regression for the /v1/models alias resolution introduced in v1.94.0."""
+ from litellm import Router
+
+ saved_model_cost = dict(litellm.model_cost)
+ try:
+ router = Router(
+ model_list=[
+ {
+ "model_name": "bedrock-claude-opus-5",
+ "litellm_params": {
+ "custom_llm_provider": "bedrock",
+ "model": "bedrock/eu.anthropic.claude-opus-5",
+ },
+ "model_info": {"base_model": "eu.anthropic.claude-opus-5"},
+ }
+ ]
+ )
+
+ response = create_model_info_response(
+ model_id="bedrock-claude-opus-5", provider="openai", llm_router=router
+ )
+ finally:
+ litellm.model_cost.clear()
+ litellm.model_cost.update(saved_model_cost)
+
+ assert response["max_input_tokens"] == 1000000
+ assert response["max_output_tokens"] == 128000
+
+
+def test_create_model_info_response_keeps_exact_alias_over_generalized_deployment_model():
+ """Mirror of the alias bug: when the deployment points at a custom backend name that
+ only matches a generalization rule, the listed name's exact cost-map entry is the
+ better answer and must win."""
+ from litellm import Router
+
+ saved_model_cost = dict(litellm.model_cost)
+ try:
+ router = Router(
+ model_list=[
+ {
+ "model_name": "claude-opus-5",
+ "litellm_params": {
+ "custom_llm_provider": "bedrock",
+ "model": "bedrock/my-claude-opus-5-provisioned",
+ },
+ }
+ ]
+ )
+
+ response = create_model_info_response(
+ model_id="claude-opus-5", provider="openai", llm_router=router
+ )
+ finally:
+ litellm.model_cost.clear()
+ litellm.model_cost.update(saved_model_cost)
+
+ assert response["max_input_tokens"] == 1000000
+
+
+def test_create_model_info_response_falls_back_to_alias_for_opaque_deployment_name():
+ """An Azure deployment named after the resource rather than the model has no cost-map
+ entry; the listed name still does, and must keep answering."""
+ from litellm import Router
+
+ saved_model_cost = dict(litellm.model_cost)
+ try:
+ router = Router(
+ model_list=[
+ {
+ "model_name": "gpt-4o",
+ "litellm_params": {"model": "azure/my-gpt4o-deployment"},
+ }
+ ]
+ )
+
+ response = create_model_info_response(
+ model_id="gpt-4o", provider="openai", llm_router=router
+ )
+ finally:
+ litellm.model_cost.clear()
+ litellm.model_cost.update(saved_model_cost)
+
+ assert response["max_input_tokens"] == 128000
+ assert response["max_output_tokens"] == 16384
+
+
+def test_create_model_info_response_resolves_mode_through_deployment_model():
+ """`mode` is derived from the same lookup, so an aliased embedding deployment
+ currently reports no mode at all; it must report `embedding`."""
+ from litellm import Router
+
+ saved_model_cost = dict(litellm.model_cost)
+ try:
+ router = Router(
+ model_list=[
+ {
+ "model_name": "my-embeddings",
+ "litellm_params": {"model": "openai/text-embedding-3-small"},
+ }
+ ]
+ )
+
+ response = create_model_info_response(
+ model_id="my-embeddings", provider="openai", llm_router=router
+ )
+ finally:
+ litellm.model_cost.clear()
+ litellm.model_cost.update(saved_model_cost)
+
+ assert response["mode"] == "embedding"
++
++
+ @pytest.mark.parametrize(
+ "key_metadata, team_metadata, expected_to_run",
+ [
+ ({"guardrails": ["key-scoped-guardrail"]}, None, True),
+ ({}, {"guardrails": ["key-scoped-guardrail"]}, True),
+ ({"guardrails": ["some-other-guardrail"]}, None, False),
+ ({}, None, False),
+ ],
+ )
+ def test_convert_mcp_to_llm_format_carries_key_and_team_guardrails(key_metadata, team_metadata, expected_to_run):
+ proxy_logging = ProxyLogging(user_api_key_cache=DualCache())
+ guardrail = CustomGuardrail(guardrail_name="key-scoped-guardrail", event_hook="pre_mcp_call", default_on=False)
+ kwargs = {
+ "name": "ask_question",
+ "arguments": {"question": "hello"},
+ "server_name": "deepwiki",
+ "user_api_key_auth": UserAPIKeyAuth(metadata=key_metadata, team_metadata=team_metadata),
+ }
+ request_obj = proxy_logging._create_mcp_request_object_from_kwargs(kwargs)
+
+ with patch( # test-quality-ok: the key-guardrail premium gate reads this proxy_server module global and has no injection seam
+ "litellm.proxy.proxy_server.premium_user", True
+ ):
+ synthetic = proxy_logging._convert_mcp_to_llm_format(request_obj, kwargs)
+
+ assert guardrail.should_run_guardrail(synthetic, GuardrailEventHooks.pre_mcp_call) is expected_to_run
+
+
+ class _TracebackRecordingLogger(CustomLogger):
+ def __init__(self) -> None:
+ super().__init__()
+ self.received_traceback: str | None = None
+
+ async def async_post_call_failure_hook(
+ self,
+ request_data: dict,
+ original_exception: Exception,
+ user_api_key_dict: UserAPIKeyAuth,
+ traceback_str: str | None = None,
+ ) -> HTTPException | None:
+ self.received_traceback = traceback_str
+ return None
+
+
+ @pytest.mark.asyncio
+ async def test_post_call_failure_hook_redacts_traceback_before_callbacks(monkeypatch):
+ """A pass-through upstream failure hands the hook the httpx traceback, whose
+ message quotes the upstream URL with the provider key in its query string.
+ Every callback, custom loggers included, must receive it redacted."""
+ import traceback
+ from unittest.mock import AsyncMock, patch
+
+ import httpx
+
+ provider_key = "AIza" + "S" * 35
+ upstream_url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini:generateContent?key={provider_key}"
+ response = httpx.Response(400, request=httpx.Request("POST", upstream_url))
+ try:
+ response.raise_for_status()
+ except httpx.HTTPStatusError:
+ upstream_traceback = traceback.format_exc()
+ assert provider_key in upstream_traceback
+
+ recorder = _TracebackRecordingLogger()
+ monkeypatch.setattr(litellm, "callbacks", [recorder])
+ proxy_logging_obj = ProxyLogging(user_api_key_cache=DualCache())
+ proxy_logging_obj.alert_types = []
+ with patch.object(proxy_logging_obj, "update_request_status", new=AsyncMock()):
+ await proxy_logging_obj.post_call_failure_hook(
+ request_data={"metadata": {}},
+ original_exception=HTTPException(status_code=400, detail="Upstream passthrough request failed with status 400"),
+ user_api_key_dict=UserAPIKeyAuth(),
+ traceback_str=upstream_traceback,
+ )
+
+ assert recorder.received_traceback is not None
+ assert provider_key not in recorder.received_traceback
+ assert "REDACTED" in recorder.received_traceback
diff --cc tests/test_litellm/test_router.py
index eba9a85feb6,d59d72a094e..468ca606c0f
--- a/tests/test_litellm/test_router.py
+++ b/tests/test_litellm/test_router.py
@@@ -5460,448 -8198,45 +8198,243 @@@ def test_get_configured_token_limits_co
router = litellm.Router(
model_list=[
{
- "model_name": "claude-sonnet-4",
- "litellm_params": {
- "model": "anthropic/claude-sonnet-4-20250514",
- "api_key": "fake-key",
- },
- "model_info": {
- "id": "custom-pricing-id",
- "input_cost_per_token": 0.0003,
- "output_cost_per_token": 0.0015,
- },
- },
- ],
- )
-
- kwargs: dict = {}
- deployment = router.get_deployment_by_model_group_name(
- model_group_name="claude-sonnet-4"
- )
- router._update_kwargs_with_deployment(
- deployment=deployment, kwargs=kwargs, function_name="generic_api_call"
+ "model_name": "quoted-limits-model",
+ "litellm_params": {"model": "openai/some-unmapped-model"},
+ "model_info": {"max_input_tokens": "32000", "max_output_tokens": "8000"},
+ }
+ ]
)
- assert "litellm_metadata" in kwargs
- model_info = kwargs["litellm_metadata"]["model_info"]
- assert model_info["id"] == "custom-pricing-id"
- assert model_info["input_cost_per_token"] == 0.0003
- assert model_info["output_cost_per_token"] == 0.0015
-
+ assert router.get_configured_token_limits("quoted-limits-model") == (32000, 8000)
- def test_update_kwargs_with_deployment_model_info_in_metadata():
- """For acompletion (function_name=None), model_info goes to metadata.
- /chat/completions uses acompletion which stores model_info under metadata.
- """
++def test_get_model_listing_info_prefers_base_model_over_litellm_params_model():
++ """The cost-map key comes from base_model when set, so a deployment pointing at an
++ opaque backend name still resolves the real catalog entry."""
+ router = litellm.Router(
+ model_list=[
+ {
- "model_name": "claude-sonnet-4",
- "litellm_params": {
- "model": "anthropic/claude-sonnet-4-20250514",
- "api_key": "fake-key",
- },
- "model_info": {
- "id": "custom-pricing-id",
- "input_cost_per_token": 0.0003,
- "output_cost_per_token": 0.0015,
- },
- },
- ],
- )
-
- kwargs: dict = {}
- deployment = router.get_deployment_by_model_group_name(
- model_group_name="claude-sonnet-4"
- )
- router._update_kwargs_with_deployment(
- deployment=deployment, kwargs=kwargs, function_name=None
++ "model_name": "bedrock-claude-opus-5",
++ "litellm_params": {"model": "bedrock/eu.anthropic.claude-opus-5"},
++ "model_info": {"base_model": "eu.anthropic.claude-opus-5"},
++ }
++ ]
+ )
+
- assert "metadata" in kwargs
- model_info = kwargs["metadata"]["model_info"]
- assert model_info["id"] == "custom-pricing-id"
- assert model_info["input_cost_per_token"] == 0.0003
- assert model_info["output_cost_per_token"] == 0.0015
-
++ info = router.get_model_listing_info("bedrock-claude-opus-5")
++ assert info is not None
++ assert info.cost_map_keys == ("eu.anthropic.claude-opus-5",)
+
- def test_combine_fallback_usage():
- """Test that _combine_fallback_usage merges partial and fallback usage."""
- from litellm.router import Router
- from litellm.types.utils import Usage
+
- # Create a stream chunk with usage
- chunk = litellm.ModelResponseStream(
- id="test",
- model="gpt-4o",
- choices=[],
- usage=Usage(prompt_tokens=10, completion_tokens=5, total_tokens=15),
++def test_get_model_listing_info_falls_back_to_litellm_params_model():
++ router = litellm.Router(
++ model_list=[
++ {
++ "model_name": "bedrock-claude-opus-5",
++ "litellm_params": {"model": "bedrock/eu.anthropic.claude-opus-5"},
++ }
++ ]
+ )
+
- # Call _combine_fallback_usage with no extra usage
- Router._combine_fallback_usage(chunk, None)
- assert chunk.usage is not None
- assert chunk.usage.prompt_tokens == 10
- assert chunk.usage.completion_tokens == 5
- assert chunk.usage.total_tokens == 15
-
++ info = router.get_model_listing_info("bedrock-claude-opus-5")
++ assert info is not None
++ assert info.cost_map_keys == ("bedrock/eu.anthropic.claude-opus-5",)
+
- @pytest.mark.asyncio
- async def test_acompletion_streaming_iterator_does_not_log_success_on_terminal_failure():
- """A mid-stream failure with no successful fallback raises and is logged as
- a failure, so the router must never dispatch it as a success. Partial-spend
- recovery for the failure row happens in the streaming handler, not here, so
- this guards only against reintroducing a success log for a failed stream.
- """
- from litellm.exceptions import MidStreamFallbackError
- from litellm.types.utils import Delta, StreamingChoices, Usage
+
++def test_get_model_listing_info_ignores_blank_base_model():
++ """A base_model set to an empty string is absent, not a cost-map key."""
+ router = litellm.Router(
+ model_list=[
+ {
- "model_name": "gpt-4",
- "litellm_params": {"model": "gpt-4", "api_key": "fake-key-1"},
- },
- ],
- set_verbose=True,
- )
-
- error = MidStreamFallbackError(
- message="Connection lost",
- model="gpt-4",
- llm_provider="openai",
- generated_content="The Roman Empire began when",
++ "model_name": "bedrock-claude-opus-5",
++ "litellm_params": {"model": "bedrock/eu.anthropic.claude-opus-5"},
++ "model_info": {"base_model": ""},
++ }
++ ]
+ )
+
- def _make_interrupted_model_response():
- partial_chunk = litellm.ModelResponseStream(
- id="chatcmpl-partial-1",
- created=1742056047,
- model="gpt-4",
- object="chat.completion.chunk",
- choices=[
- StreamingChoices(
- finish_reason=None,
- index=0,
- delta=Delta(content="The Roman Empire began when", role="assistant"),
- )
- ],
- usage=Usage(prompt_tokens=17, completion_tokens=9, total_tokens=26),
- )
-
- class _RaisingStream:
- def __init__(self):
- self.index = 0
- self.chunks = [partial_chunk]
-
- def __aiter__(self):
- return self
-
- async def __anext__(self):
- if self.index == 0:
- self.index += 1
- return partial_chunk
- raise error
-
- stream = _RaisingStream()
- logging_obj = MagicMock()
- logging_obj.dispatch_success_handlers = AsyncMock()
- logging_obj.model_call_details = {}
- setattr(stream, "model", "gpt-4")
- setattr(stream, "custom_llm_provider", "openai")
- setattr(stream, "logging_obj", logging_obj)
- return stream, logging_obj
++ info = router.get_model_listing_info("bedrock-claude-opus-5")
++ assert info is not None
++ assert info.cost_map_keys == ("bedrock/eu.anthropic.claude-opus-5",)
+
- messages = [{"role": "user", "content": "Hello"}]
- initial_kwargs = {"model": "gpt-4", "stream": True}
+
- # Terminal path: no successful fallback -> the error propagates and the
- # router never dispatches a success for the failed stream.
- model_response, logging_obj = _make_interrupted_model_response()
- with patch.object(
- router,
- "async_function_with_fallbacks_common_utils",
- new=AsyncMock(side_effect=error),
- ):
- result = await router._acompletion_streaming_iterator(
- model_response=model_response,
- messages=messages,
- initial_kwargs=dict(initial_kwargs),
- )
- collected = []
- async def _drain():
- async for chunk in result:
- collected.append(chunk)
++def test_get_model_listing_info_returns_none_for_unknown_name():
++ router = litellm.Router(
++ model_list=[
++ {
++ "model_name": "no-limits-model",
++ "litellm_params": {"model": "openai/some-unmapped-model"},
++ }
++ ]
++ )
+
- with pytest.raises(MidStreamFallbackError):
- await _drain()
++ assert router.get_model_listing_info("not-a-real-model") is None
+
- assert len(collected) == 1
- logging_obj.dispatch_success_handlers.assert_not_called()
+
- # Mid-stream errors with generated content are now re-raised immediately;
- # no continuation-prompt fallback is attempted. Success handlers must
- # still not be dispatched in this path.
- model_response, logging_obj = _make_interrupted_model_response()
++def test_get_model_listing_info_carries_configured_limits():
++ router = litellm.Router(
++ model_list=[
++ {
++ "model_name": "my-custom-model",
++ "litellm_params": {"model": "openai/some-unmapped-model"},
++ "model_info": {"max_input_tokens": 32000, "max_output_tokens": 8000},
++ }
++ ]
++ )
+
- with patch.object(
- router,
- "async_function_with_fallbacks_common_utils",
- new=AsyncMock(),
- ) as mock_fallback:
- result = await router._acompletion_streaming_iterator(
- model_response=model_response,
- messages=messages,
- initial_kwargs=dict(initial_kwargs),
- )
- collected = []
- async def _drain():
- async for chunk in result:
- collected.append(chunk)
++ info = router.get_model_listing_info("my-custom-model")
++ assert info is not None
++ assert (info.max_input_tokens, info.max_output_tokens) == (32000, 8000)
+
- with pytest.raises(MidStreamFallbackError):
- await _drain()
+
- assert len(collected) == 1, "only the partial chunk before the error"
- mock_fallback.assert_not_called()
- logging_obj.dispatch_success_handlers.assert_not_called()
++def test_widest_configured_limit_ignores_absent_and_malformed_values():
++ model_infos = (
++ {"max_input_tokens": 32000},
++ {},
++ {"max_input_tokens": "not-a-number"},
++ {"max_input_tokens": "128000"},
++ {"max_output_tokens": 4096},
++ )
+
++ assert litellm.Router._widest_configured_limit(model_infos, "max_input_tokens") == 128000
++ assert litellm.Router._widest_configured_limit(model_infos, "max_output_tokens") == 4096
++ assert litellm.Router._widest_configured_limit((), "max_input_tokens") is None
+
- @pytest.mark.asyncio
- async def test_team_scoped_model_fallback():
- """
- Test that fallback works correctly for team-scoped models.
+
- When a team-scoped model fails and the fallback model is also team-scoped,
- the router should find the fallback deployment by matching team_public_model_name.
- """
++def test_get_model_listing_info_dedupes_interchangeable_deployments():
++ """The ordinary group is N deployments of one model, so it yields exactly one key."""
+ router = litellm.Router(
+ model_list=[
+ {
- "model_name": "team-a-primary-internal",
- "litellm_params": {"model": "gpt-3.5-turbo", "api_key": "fake"},
- "model_info": {
- "team_id": "team-a",
- "team_public_model_name": "primary-model",
- },
++ "model_name": "gpt-4o",
++ "litellm_params": {"model": "openai/gpt-4o", "api_key": "sk-a"},
+ },
+ {
- "model_name": "team-a-fallback-internal",
- "litellm_params": {
- "model": "gpt-4",
- "api_key": "fake",
- "mock_response": "fallback success from team-a",
- },
- "model_info": {
- "team_id": "team-a",
- "team_public_model_name": "fallback-model",
- },
++ "model_name": "gpt-4o",
++ "litellm_params": {"model": "openai/gpt-4o", "api_key": "sk-b"},
+ },
- ],
- fallbacks=[{"primary-model": ["fallback-model"]}],
- )
-
- response = await router.acompletion(
- model="primary-model",
- messages=[{"role": "user", "content": "Hello"}],
- metadata={"user_api_key_team_id": "team-a"},
- mock_testing_fallbacks=True,
++ ]
+ )
- assert response is not None
- assert response.choices[0].message.content == "fallback success from team-a"
+
++ info = router.get_model_listing_info("gpt-4o")
++ assert info is not None
++ assert info.cost_map_keys == ("openai/gpt-4o",)
+
- @pytest.mark.asyncio
- async def test_team_scoped_model_fallback_to_global():
- """
- Test that a team-scoped model can fall back to a global (non-team) model.
+
- Global models (no team_id on deployment) should be accessible as fallback
- targets for team-scoped requests.
- """
++def test_get_model_listing_info_collects_every_model_in_a_mixed_group():
+ router = litellm.Router(
+ model_list=[
+ {
- "model_name": "team-a-primary-internal",
- "litellm_params": {"model": "gpt-3.5-turbo", "api_key": "fake"},
- "model_info": {
- "team_id": "team-a",
- "team_public_model_name": "primary-model",
- },
++ "model_name": "house-claude",
++ "litellm_params": {"model": "anthropic/claude-3-haiku-20240307"},
+ },
+ {
- "model_name": "global-fallback",
- "litellm_params": {
- "model": "gpt-4",
- "api_key": "fake",
- "mock_response": "global fallback success",
- },
++ "model_name": "house-claude",
++ "litellm_params": {"model": "bedrock/eu.anthropic.claude-opus-5"},
+ },
- ],
- fallbacks=[{"primary-model": ["global-fallback"]}],
++ ]
+ )
+
- response = await router.acompletion(
- model="primary-model",
- messages=[{"role": "user", "content": "Hello"}],
- metadata={"user_api_key_team_id": "team-a"},
- mock_testing_fallbacks=True,
++ info = router.get_model_listing_info("house-claude")
++ assert info is not None
++ assert info.cost_map_keys == (
++ "anthropic/claude-3-haiku-20240307",
++ "bedrock/eu.anthropic.claude-opus-5",
+ )
- assert response is not None
- assert response.choices[0].message.content == "global fallback success"
-
+
- @pytest.mark.asyncio
- async def test_team_scoped_model_fallback_cross_team_blocked():
- """
- Test that cross-team fallback is correctly blocked.
+
- When team-a's model fails and the fallback target is scoped to team-b,
- the router should NOT use it (team isolation).
- """
++def test_get_model_listing_info_reports_widest_configured_limits_in_a_mixed_group():
++ """Matches how get_model_group_info aggregates for the Admin UI, so the two agree."""
+ router = litellm.Router(
+ model_list=[
+ {
- "model_name": "team-a-primary-internal",
- "litellm_params": {"model": "gpt-3.5-turbo", "api_key": "fake"},
- "model_info": {
- "team_id": "team-a",
- "team_public_model_name": "primary-model",
- },
++ "model_name": "house-model",
++ "litellm_params": {"model": "openai/some-unmapped-model"},
++ "model_info": {"max_input_tokens": 32000, "max_output_tokens": 4096},
+ },
+ {
- "model_name": "team-b-fallback-internal",
- "litellm_params": {
- "model": "gpt-4",
- "api_key": "fake",
- "mock_response": "team-b response - should not reach here",
- },
- "model_info": {
- "team_id": "team-b",
- "team_public_model_name": "fallback-model",
- },
++ "model_name": "house-model",
++ "litellm_params": {"model": "openai/another-unmapped-model"},
++ "model_info": {"max_input_tokens": 128000, "max_output_tokens": 16384},
+ },
- ],
- fallbacks=[{"primary-model": ["fallback-model"]}],
++ ]
+ )
+
- with pytest.raises(litellm.InternalServerError):
- await router.acompletion(
- model="primary-model",
- messages=[{"role": "user", "content": "Hello"}],
- metadata={"user_api_key_team_id": "team-a"},
- mock_testing_fallbacks=True,
- )
++ info = router.get_model_listing_info("house-model")
++ assert info is not None
++ assert (info.max_input_tokens, info.max_output_tokens) == (128000, 16384)
+
+
- def test_get_all_deployments_with_team_id():
- """
- Test that _get_all_deployments with team_id can find deployments
- by team_public_model_name when the model_name is not in the index.
- """
++def test_get_model_listing_info_reads_base_model_from_litellm_params():
++ """base_model resolution mirrors get_router_model_info, which also accepts it there."""
+ router = litellm.Router(
+ model_list=[
+ {
- "model_name": "internal-team-deployment",
- "litellm_params": {"model": "gpt-4", "api_key": "fake"},
- "model_info": {
- "team_id": "team-x",
- "team_public_model_name": "gpt-4",
++ "model_name": "azure-deployment",
++ "litellm_params": {
++ "model": "azure/my-azure-deployment-name",
++ "base_model": "azure/gpt-4o",
++ "api_key": "sk-a",
++ "api_base": "https://example.openai.azure.com",
+ },
- },
- ],
++ }
++ ]
+ )
+
- # Without team_id: "gpt-4" is not in the model_name index (internal name is different)
- deployments = router._get_all_deployments(model_name="gpt-4")
- assert len(deployments) == 0
-
- # With correct team_id: should find via O(n) scan matching team_public_model_name
- deployments = router._get_all_deployments(model_name="gpt-4", team_id="team-x")
- assert len(deployments) == 1
- assert deployments[0]["model_name"] == "internal-team-deployment"
-
- # With wrong team_id: should find nothing
- deployments = router._get_all_deployments(model_name="gpt-4", team_id="team-y")
- assert len(deployments) == 0
-
++ info = router.get_model_listing_info("azure-deployment")
++ assert info is not None
++ assert info.cost_map_keys == ("azure/gpt-4o",)
+
- def test_multiregion_team_deployments_unique_model_names():
- """
- Simulates athenahealth's exact setup: unique model_names per deployment,
- same team_public_model_name, multiple regions.
+
- Verifies that _get_all_deployments returns ALL regional deployments
- for a team when queried by team_public_model_name.
- """
++def test_get_model_listing_info_skips_wildcard_pattern_matching():
+ router = litellm.Router(
+ model_list=[
+ {
- "model_name": "metis-claude-us-east-1",
- "litellm_params": {
- "model": "bedrock/anthropic.claude-3-sonnet",
- "aws_region_name": "us-east-1",
- "api_key": "fake",
- },
- "model_info": {
- "team_id": "metis-team",
- "team_public_model_name": "claude-sonnet",
- },
- },
- {
- "model_name": "metis-claude-us-west-2",
- "litellm_params": {
- "model": "bedrock/anthropic.claude-3-sonnet",
- "aws_region_name": "us-west-2",
- "api_key": "fake",
- },
- "model_info": {
- "team_id": "metis-team",
- "team_public_model_name": "claude-sonnet",
- },
- },
- ],
++ "model_name": "bedrock/*",
++ "litellm_params": {"model": "bedrock/*"},
++ "model_info": {"max_input_tokens": 12345},
++ }
++ ]
+ )
+
- # "claude-sonnet" is NOT in the model_name index
- assert "claude-sonnet" not in router.model_names
++ with patch.object(
++ router.pattern_router, "route", side_effect=AssertionError("pattern route called")
++ ):
++ assert (
++ router.get_model_listing_info("bedrock/anthropic.claude-3-5-sonnet-20240620-v1:0")
++ is None
++ )
+
- # Without team_id: returns nothing (no model_name="claude-sonnet" in index, no O(n) scan)
- deployments = router._get_all_deployments(model_name="claude-sonnet")
- assert len(deployments) == 0
+
- # With team_id: O(n) scan finds BOTH regional deployments
- deployments = router._get_all_deployments(
- model_name="claude-sonnet", team_id="metis-team"
+ def test_get_configured_mode_reads_deployment_model_info():
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "tts-model",
+ "litellm_params": {"model": "openai/some-unmapped-tts-model"},
+ "model_info": {"mode": "audio_speech"},
+ }
+ ]
)
- assert len(deployments) == 2
- deployment_names = {d["model_name"] for d in deployments}
- assert deployment_names == {"metis-claude-us-east-1", "metis-claude-us-west-2"}
- # Each deployment has a unique ID (critical for cooldown/retry to work)
- deployment_ids = {d["model_info"]["id"] for d in deployments}
- assert (
- len(deployment_ids) == 2
- ), "Each deployment must have a unique ID for cooldown tracking"
+ assert router.get_configured_mode("tts-model") == "audio_speech"
- # Wrong team: returns nothing
- deployments = router._get_all_deployments(
- model_name="claude-sonnet", team_id="other-team"
+
+ def test_get_configured_mode_returns_none_for_unset_or_unknown():
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "no-mode-model",
+ "litellm_params": {"model": "openai/some-unmapped-model"},
+ }
+ ]
)
- assert len(deployments) == 0
+ assert router.get_configured_mode("no-mode-model") is None
+ assert router.get_configured_mode("not-a-real-model") is None
- @pytest.mark.asyncio
- async def test_multiregion_team_failover_between_regions():
- """
- Simulates athenahealth's multiregion failover scenario:
- - Two Bedrock deployments (us-east-1 and us-west-2) with unique model_names
- - Same team_public_model_name ("claude-sonnet")
- - Primary region fails → router should failover to second region
- This is the exact scenario Sean Glover from athenahealth will demonstrate.
- """
+ def test_get_configured_mode_skips_wildcard_pattern_matching():
router = litellm.Router(
model_list=[
{