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]

chore: merge origin/litellm_internal_staging into litellm_lit_7022_azure_ai_passthrough_config

mateo-berri614b1513658a
diff --cc litellm/llms/azure_ai/chat/transformation.py
index 4c0a2e1f546,039c462b38a..00e1c1e25ba
--- a/litellm/llms/azure_ai/chat/transformation.py
+++ b/litellm/llms/azure_ai/chat/transformation.py
@@@ -14,11 -15,9 +14,12 @@@ from litellm.litellm_core_utils.prompt_
filter_value_from_dict,
)
from litellm.llms.azure.common_utils import BaseAzureLLM
-from litellm.llms.azure_ai.common_utils import is_foundry_model_inference_base
+from litellm.llms.azure_ai.common_utils import (
+ api_key_header_for_base,
+ is_foundry_model_inference_base,
+)
from litellm.llms.base_llm.chat.transformation import LiteLLMLoggingObj
+ from litellm.llms.openai.chat.gpt_5_transformation import OpenAIGPT5Config
from litellm.llms.openai.common_utils import drop_params_from_unprocessable_entity_error
from litellm.llms.openai.openai import OpenAIConfig
from litellm.llms.xai.chat.transformation import XAIChatConfig
diff --cc tests/test_litellm/test_router.py
index 0f4e199694d,eed34c79a06..4f60377ea8d
--- a/tests/test_litellm/test_router.py
+++ b/tests/test_litellm/test_router.py
@@@ -12394,475 -13158,920 +13181,963 @@@ class TestTierParamsTheTargetAccepts
def force_local_model_cost(self, monkeypatch):
from litellm.litellm_core_utils.get_model_cost_map import GetModelCostMap
- monkeypatch.setattr(litellm, "model_cost", GetModelCostMap.load_local_model_cost_map())
+ monkeypatch.setattr(litellm, "model_cost", GetModelCostMap.load_local_model_cost_map())
+
+ @staticmethod
+ def _router(model: str) -> litellm.Router:
+ return litellm.Router(
+ model_list=[{"model_name": "tiered", "litellm_params": {"model": model, "api_key": "sk-x"}}]
+ )
+
+ def test_drops_a_param_no_deployment_declares(self):
+ router = self._router("novita/moonshotai/kimi-k3")
+
+ accepted = router._tier_params_the_target_accepts("tiered", {"reasoning_effort": "max"}, {})
+
+ assert accepted == {}
+
+ def test_keeps_a_param_the_deployment_declares(self):
+ router = self._router("fireworks_ai/kimi-k3")
+
+ accepted = router._tier_params_the_target_accepts("tiered", {"reasoning_effort": "max"}, {})
+
+ assert accepted == {"reasoning_effort": "max"}
+
+ @pytest.mark.parametrize(
+ "control, value",
+ [
+ ("api_base", "https://example.invalid"),
+ ("api_key", "sk-tier"),
+ ("base_url", "https://example.invalid"),
+ ("timeout", 30),
+ ("default_headers", {"x-tier": "1"}),
+ ("organization", "org-tier"),
+ ("deployment_id", "dep-tier"),
+ ],
+ )
+ def test_keeps_credentials_and_transport_controls(self, control, value):
+ """These are not chat completion params, so get_optional_params never compares them against
+ a provider's supported list. Filtering on "is this an OpenAI param" would discard the
+ configuration the request needs while never touching what the provider would reject."""
+ router = self._router("novita/moonshotai/kimi-k3")
+
+ accepted = router._tier_params_the_target_accepts("tiered", {control: value, "reasoning_effort": "max"}, {})
+
+ assert accepted == {control: value}
+
+ @pytest.mark.parametrize(
+ "control, value",
+ [
+ ("additional_drop_params", ["seed"]),
+ ("drop_params", True),
+ ("allowed_openai_params", ["seed"]),
+ ("api_version", "2024-02-01"),
+ ("metadata", {"tier": "complex"}),
+ ],
+ )
+ def test_keeps_litellm_controls_the_provider_never_lists(self, control, value):
+ """No provider lists a litellm control among its supported params, so "no deployment
+ declares it" means litellm consumes it, not that the target refuses it. Dropping
+ drop_params or additional_drop_params would silently disable the operator's sanitization."""
+ router = self._router("novita/moonshotai/kimi-k3")
+
+ accepted = router._tier_params_the_target_accepts("tiered", {control: value, "reasoning_effort": "max"}, {})
+
+ assert accepted == {control: value}
+
+ def test_tier_allowlist_protects_the_param_it_names(self):
+ """allowed_openai_params is the documented escape hatch for an incomplete supported-params
+ list, and request-time validation extends the supported list with it, so a param the tier
+ both sets and allowlists would never 400 and must not be dropped."""
+ router = self._router("novita/moonshotai/kimi-k3")
+
+ accepted = router._tier_params_the_target_accepts(
+ "tiered", {"reasoning_effort": "max", "allowed_openai_params": ["reasoning_effort"]}, {}
+ )
+
+ assert accepted == {"reasoning_effort": "max", "allowed_openai_params": ["reasoning_effort"]}
+
+ def test_request_allowlist_protects_the_param_it_names(self):
+ router = self._router("novita/moonshotai/kimi-k3")
+
+ accepted = router._tier_params_the_target_accepts(
+ "tiered", {"reasoning_effort": "max"}, {"allowed_openai_params": ["reasoning_effort"]}
+ )
+
+ assert accepted == {"reasoning_effort": "max"}
+
+ def test_allowlist_protects_only_the_params_it_names(self):
+ router = self._router("novita/moonshotai/kimi-k3")
+
+ accepted = router._tier_params_the_target_accepts(
+ "tiered", {"reasoning_effort": "max", "allowed_openai_params": ["seed"]}, {}
+ )
+
+ assert accepted == {"allowed_openai_params": ["seed"]}
+
+ def test_declared_param_allowlist_ignores_malformed_declarations(self):
+ """A str is iterable, so without the type guard a YAML scalar mistake like
+ allowed_openai_params: reasoning_effort would allowlist single characters."""
+ assert litellm.Router._declared_param_allowlist({"allowed_openai_params": ["reasoning_effort", 3]}) == frozenset(
+ {"reasoning_effort"}
+ )
+ assert litellm.Router._declared_param_allowlist({"allowed_openai_params": "reasoning_effort"}) == frozenset()
+ assert litellm.Router._declared_param_allowlist({}) == frozenset()
+
+ def test_deployment_accepts_param_honors_deployment_allowlist(self):
+ deployment = {
+ "model_name": "x",
+ "litellm_params": {"model": "novita/moonshotai/kimi-k3", "allowed_openai_params": ["reasoning_effort"]},
+ }
+
+ assert litellm.Router._deployment_accepts_param(deployment, "x", "reasoning_effort") is True
+
+ def test_keeps_a_token_ceiling_the_provider_spells_differently(self):
+ """petals lists max_tokens but not max_completion_tokens. A tier ceiling in the unsupported
+ spelling is a cost bound: dropping it would let a caller's larger max_tokens through where
+ today the mismatch fails loudly."""
+ router = self._router("petals/petals-team/StableBeluga2")
+
+ accepted = router._tier_params_the_target_accepts(
+ "tiered", {"max_completion_tokens": 100, "reasoning_effort": "max"}, {}
+ )
+
+ assert accepted == {"max_completion_tokens": 100}
+
+ def test_keeps_extra_headers_even_when_the_provider_omits_it(self):
+ """Several providers leave extra_headers out of their supported params, so the filter would
+ drop it. Headers carry auth and tenancy, so sending fewer than the operator configured is
+ worse than the error they already get."""
+ router = self._router("ai21/jamba-1.5-mini")
+
+ accepted = router._tier_params_the_target_accepts(
+ "tiered", {"extra_headers": {"x-tenant": "acme"}, "reasoning_effort": "max"}, {}
+ )
+
+ assert accepted == {"extra_headers": {"x-tenant": "acme"}}
+
+ def test_keeps_a_param_any_deployment_in_the_group_declares(self):
+ """Routing has not picked a deployment yet, so one capable member keeps the param alive."""
+ router = litellm.Router(
+ model_list=[
+ {"model_name": "tiered", "litellm_params": {"model": "novita/moonshotai/kimi-k3", "api_key": "k"}},
+ {"model_name": "tiered", "litellm_params": {"model": "fireworks_ai/kimi-k3", "api_key": "k"}},
+ ]
+ )
+
+ accepted = router._tier_params_the_target_accepts("tiered", {"reasoning_effort": "max"}, {})
+
+ assert accepted == {"reasoning_effort": "max"}
+
+ def test_deployment_accepts_param_honors_base_model(self):
+ """An azure deployment named after the deployment rather than the model carries the real
+ model in base_model, and request-time mapping resolves capability through it, so the filter
+ has to ask the same question or it drops a param the deployment accepts."""
+ by_model_info = {
+ "model_name": "x",
+ "litellm_params": {"model": "azure/my-gpt5-deploy"},
+ "model_info": {"base_model": "azure/gpt-5"},
+ }
+ by_litellm_params = {
+ "model_name": "x",
+ "litellm_params": {"model": "azure/my-gpt5-deploy", "base_model": "azure/gpt-5"},
+ }
+ without_hint = {"model_name": "x", "litellm_params": {"model": "azure/my-gpt5-deploy"}}
+
+ assert litellm.Router._deployment_accepts_param(by_model_info, "x", "reasoning_effort") is True
+ assert litellm.Router._deployment_accepts_param(by_litellm_params, "x", "reasoning_effort") is True
+ assert litellm.Router._deployment_accepts_param(without_hint, "x", "reasoning_effort") is False
+
+ def test_deployment_accepts_param_reads_the_provider(self):
+ deployment = {"model_name": "x", "litellm_params": {"model": "fireworks_ai/kimi-k3"}}
+
+ assert litellm.Router._deployment_accepts_param(deployment, "x", "reasoning_effort") is True
+
+ def test_deployment_accepts_param_is_false_when_the_provider_omits_it(self):
+ deployment = {"model_name": "x", "litellm_params": {"model": "novita/moonshotai/kimi-k3"}}
+
+ assert litellm.Router._deployment_accepts_param(deployment, "x", "reasoning_effort") is False
+
+ @pytest.mark.parametrize(
+ "deployment",
+ [{"model_name": "x"}, {"model_name": "x", "litellm_params": {}}, {"model_name": "x", "litellm_params": {"model": "not-a-real-provider/nope"}}],
+ )
+ def test_deployment_accepts_param_fails_open(self, deployment):
+ """An unresolvable deployment must not be the reason a param is dropped."""
+ assert litellm.Router._deployment_accepts_param(deployment, "x", "reasoning_effort") is True
+
+ @pytest.mark.parametrize(
+ "litellm_params",
+ [
+ {"model": "github_copilot/gpt-4o"},
+ {"model": "chatgpt/gpt-5"},
+ {"model": "gpt-4o", "custom_llm_provider": "github_copilot"},
+ ],
+ )
+ def test_deployment_accepts_param_never_asks_a_provider_whose_lookup_authenticates(
+ self, litellm_params, monkeypatch
+ ):
+ """Resolving github_copilot or chatgpt runs their OAuth device flow, so a capability
+ question asked from the routing path can freeze the event loop for minutes waiting on a
+ human. The deployment counts as accepting everything, and the lookup is never made: an
+ exception-based sentinel cannot prove that, because the filter swallows exceptions into
+ the same keep answer."""
+ lookups: list = []
+
+ def _record(*args, **kwargs):
+ lookups.append((args, kwargs))
+ raise RuntimeError("provider resolution must not run for an authenticating provider")
+
+ monkeypatch.setattr(litellm, "get_llm_provider", _record)
+ deployment = {"model_name": "x", "litellm_params": litellm_params}
+
+ assert litellm.Router._deployment_accepts_param(deployment, "x", "reasoning_effort") is True
+ assert lookups == []
+
+ def test_keeps_everything_for_an_unknown_group(self):
+ """An unresolvable target must never narrow what the request already did."""
+ router = self._router("fireworks_ai/kimi-k3")
+
+ accepted = router._tier_params_the_target_accepts("no-such-group", {"reasoning_effort": "max"}, {})
+
+ assert accepted == {"reasoning_effort": "max"}
+
+
+ @pytest.mark.asyncio
+ async def test_router_aspeech_without_voice_dispatches_ref_audio_cloning(respx_mock, monkeypatch):
+ import base64
+
+ monkeypatch.setenv("MISTRAL_API_KEY", "sk-mistral-test")
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+ audio_bytes = b"RIFFfake-wav-bytes"
+ respx_mock.post("https://api.mistral.ai/v1/audio/speech").respond(
+ json={"audio_data": base64.b64encode(audio_bytes).decode()}
+ )
+ router = Router(
+ model_list=[
+ {
+ "model_name": "voxtral-tts",
+ "litellm_params": {"model": "mistral/voxtral-mini-tts-2603"},
+ }
+ ]
+ )
+
+ response = await router.aspeech(model="voxtral-tts", input="clone me", ref_audio="ZmFrZQ==")
- @staticmethod
- def _router(model: str) -> litellm.Router:
- return litellm.Router(
- model_list=[{"model_name": "tiered", "litellm_params": {"model": model, "api_key": "sk-x"}}]
- )
+ request_body = json.loads(respx_mock.calls.last.request.content)
+ assert request_body == {"model": "voxtral-mini-tts-2603", "input": "clone me", "ref_audio": "ZmFrZQ=="}
+ assert response.content == audio_bytes
- def test_drops_a_param_no_deployment_declares(self):
- router = self._router("novita/moonshotai/kimi-k3")
- accepted = router._tier_params_the_target_accepts("tiered", {"reasoning_effort": "max"}, {})
+ @pytest.mark.asyncio
+ async def test_router_aspeech_without_voice_keeps_deployment_default_voice(respx_mock, monkeypatch):
+ import base64
- assert accepted == {}
+ monkeypatch.setenv("MISTRAL_API_KEY", "sk-mistral-test")
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+ audio_bytes = b"RIFFfake-wav-bytes"
+ respx_mock.post("https://api.mistral.ai/v1/audio/speech").respond(
+ json={"audio_data": base64.b64encode(audio_bytes).decode()}
+ )
+ router = Router(
+ model_list=[
+ {
+ "model_name": "voxtral-tts",
+ "litellm_params": {"model": "mistral/voxtral-mini-tts-2603", "voice": "en_paul_neutral"},
+ }
+ ]
+ )
- def test_keeps_a_param_the_deployment_declares(self):
- router = self._router("fireworks_ai/kimi-k3")
+ await router.aspeech(model="voxtral-tts", input="use my default")
- accepted = router._tier_params_the_target_accepts("tiered", {"reasoning_effort": "max"}, {})
+ request_body = json.loads(respx_mock.calls.last.request.content)
+ assert request_body["voice_id"] == "en_paul_neutral"
- assert accepted == {"reasoning_effort": "max"}
- @pytest.mark.parametrize(
- "control, value",
- [
- ("api_base", "https://example.invalid"),
- ("api_key", "sk-tier"),
- ("base_url", "https://example.invalid"),
- ("timeout", 30),
- ("default_headers", {"x-tier": "1"}),
- ("organization", "org-tier"),
- ("deployment_id", "dep-tier"),
- ],
+ @pytest.mark.asyncio
+ async def test_router_aspeech_request_voice_overrides_deployment_default(respx_mock, monkeypatch):
+ import base64
+
+ monkeypatch.setenv("MISTRAL_API_KEY", "sk-mistral-test")
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+ audio_bytes = b"RIFFfake-wav-bytes"
+ respx_mock.post("https://api.mistral.ai/v1/audio/speech").respond(
+ json={"audio_data": base64.b64encode(audio_bytes).decode()}
+ )
+ router = Router(
+ model_list=[
+ {
+ "model_name": "voxtral-tts",
+ "litellm_params": {"model": "mistral/voxtral-mini-tts-2603", "voice": "en_paul_neutral"},
+ }
+ ]
)
- def test_keeps_credentials_and_transport_controls(self, control, value):
- """These are not chat completion params, so get_optional_params never compares them against
- a provider's supported list. Filtering on "is this an OpenAI param" would discard the
- configuration the request needs while never touching what the provider would reject."""
- router = self._router("novita/moonshotai/kimi-k3")
- accepted = router._tier_params_the_target_accepts("tiered", {control: value, "reasoning_effort": "max"}, {})
+ await router.aspeech(model="voxtral-tts", input="override me", voice="gb_oliver_neutral")
- assert accepted == {control: value}
+ request_body = json.loads(respx_mock.calls.last.request.content)
+ assert request_body["voice_id"] == "gb_oliver_neutral"
- @pytest.mark.parametrize(
- "control, value",
- [
- ("additional_drop_params", ["seed"]),
- ("drop_params", True),
- ("allowed_openai_params", ["seed"]),
- ("api_version", "2024-02-01"),
- ("metadata", {"tier": "complex"}),
- ],
- )
- def test_keeps_litellm_controls_the_provider_never_lists(self, control, value):
- """No provider lists a litellm control among its supported params, so "no deployment
- declares it" means litellm consumes it, not that the target refuses it. Dropping
- drop_params or additional_drop_params would silently disable the operator's sanitization."""
- router = self._router("novita/moonshotai/kimi-k3")
- accepted = router._tier_params_the_target_accepts("tiered", {control: value, "reasoning_effort": "max"}, {})
+ class TestRequestReasoningEffortOverride:
+ def test_drop_effort_from_nested_carrier_preserves_other_nested_values(self):
+ params: dict[str, object] = {"output_config": {"effort": "high", "format": "json"}}
- assert accepted == {control: value}
+ litellm.Router._pop_effort_from_nested_carrier(params, "output_config")
- def test_tier_allowlist_protects_the_param_it_names(self):
- """allowed_openai_params is the documented escape hatch for an incomplete supported-params
- list, and request-time validation extends the supported list with it, so a param the tier
- both sets and allowlists would never 400 and must not be dropped."""
- router = self._router("novita/moonshotai/kimi-k3")
+ assert params == {"output_config": {"format": "json"}}
- accepted = router._tier_params_the_target_accepts(
- "tiered", {"reasoning_effort": "max", "allowed_openai_params": ["reasoning_effort"]}, {}
- )
+ @pytest.mark.parametrize("metadata_key", ["metadata", "litellm_metadata"])
+ def test_is_classifier_internal_call_recognizes_both_metadata_carriers(self, metadata_key):
+ kwargs = {metadata_key: {"internal_call_origin": "autorouter_classifier"}}
- assert accepted == {"reasoning_effort": "max", "allowed_openai_params": ["reasoning_effort"]}
+ assert litellm.Router._is_classifier_internal_call(kwargs) is True
+ assert litellm.Router._is_classifier_internal_call({metadata_key: {}}) is False
- def test_request_allowlist_protects_the_param_it_names(self):
- router = self._router("novita/moonshotai/kimi-k3")
+ def test_removes_every_deployment_native_effort_carrier_without_mutating_shared_config(self):
+ extra_body: dict[str, object] = {
+ "reasoning_effort": "high",
+ "thinking": {"type": "enabled"},
+ "output_config": {"effort": "high", "format": "json"},
+ "reasoning": {"effort": "high", "summary": "detailed"},
+ "provider_option": True,
+ }
+ deployment_params: dict[str, object] = {
+ "model": "bedrock/converse/anthropic.claude-3-7-sonnet",
+ "thinking": {"type": "enabled", "budget_tokens": 2048},
+ "output_config": {"effort": "high", "format": {"type": "json_schema"}},
+ "reasoning": {"effort": "high", "summary": "auto"},
+ "extra_body": extra_body,
+ }
- accepted = router._tier_params_the_target_accepts(
- "tiered", {"reasoning_effort": "max"}, {"allowed_openai_params": ["reasoning_effort"]}
+ sanitized = litellm.Router._deployment_params_with_request_reasoning_override(
+ deployment_params, {"reasoning_effort": "low"}
)
- assert accepted == {"reasoning_effort": "max"}
+ assert sanitized == {
+ "model": "bedrock/converse/anthropic.claude-3-7-sonnet",
+ "output_config": {"format": {"type": "json_schema"}},
+ "reasoning": {"summary": "auto"},
+ "extra_body": {
+ "output_config": {"format": "json"},
+ "reasoning": {"summary": "detailed"},
+ "provider_option": True,
+ },
+ }
+ assert deployment_params["thinking"] == {"type": "enabled", "budget_tokens": 2048}
+ assert deployment_params["output_config"] == {"effort": "high", "format": {"type": "json_schema"}}
+ assert extra_body["reasoning_effort"] == "high"
- def test_allowlist_protects_only_the_params_it_names(self):
- router = self._router("novita/moonshotai/kimi-k3")
+ @pytest.mark.parametrize("request_kwargs", [{}, {"reasoning_effort": None}])
+ def test_omitted_override_preserves_deployment_defaults(self, request_kwargs):
+ deployment_params = {
+ "model": "deepseek/deepseek-reasoner",
+ "thinking": {"type": "enabled"},
+ "output_config": {"effort": "high"},
+ }
- accepted = router._tier_params_the_target_accepts(
- "tiered", {"reasoning_effort": "max", "allowed_openai_params": ["seed"]}, {}
+ assert (
+ litellm.Router._deployment_params_with_request_reasoning_override(deployment_params, request_kwargs)
+ == deployment_params
)
- assert accepted == {"allowed_openai_params": ["seed"]}
+ @pytest.mark.asyncio
+ async def test_280_concurrent_overrides_never_mutate_or_leak_through_shared_deployment_params(self):
+ deployment_params = {
+ "model": "fireworks_ai/accounts/fireworks/models/kimi-k2-thinking",
+ "thinking": {"type": "enabled"},
+ "output_config": {"effort": "high", "format": "json"},
+ "extra_body": {"reasoning_effort": "high", "tenant": "shared"},
+ }
+ efforts = ("none", "minimal", "low", "medium", "high", "xhigh", "max")
- def test_declared_param_allowlist_ignores_malformed_declarations(self):
- """A str is iterable, so without the type guard a YAML scalar mistake like
- allowed_openai_params: reasoning_effort would allowlist single characters."""
- assert litellm.Router._declared_param_allowlist({"allowed_openai_params": ["reasoning_effort", 3]}) == frozenset(
- {"reasoning_effort"}
+ results = await asyncio.gather(
+ *(
+ asyncio.to_thread(
+ litellm.Router._deployment_params_with_request_reasoning_override,
+ deployment_params,
+ {"reasoning_effort": efforts[index % len(efforts)]},
+ )
+ for index in range(280)
+ )
)
- assert litellm.Router._declared_param_allowlist({"allowed_openai_params": "reasoning_effort"}) == frozenset()
- assert litellm.Router._declared_param_allowlist({}) == frozenset()
- def test_deployment_accepts_param_honors_deployment_allowlist(self):
- deployment = {
- "model_name": "x",
- "litellm_params": {"model": "novita/moonshotai/kimi-k3", "allowed_openai_params": ["reasoning_effort"]},
+ assert all("thinking" not in result for result in results)
+ assert all(result["output_config"] == {"format": "json"} for result in results)
+ assert all(result["extra_body"] == {"tenant": "shared"} for result in results)
+ assert deployment_params["thinking"] == {"type": "enabled"}
+ assert deployment_params["output_config"] == {"effort": "high", "format": "json"}
+ assert deployment_params["extra_body"] == {"reasoning_effort": "high", "tenant": "shared"}
+
+ @pytest.mark.parametrize(
+ ("metadata", "should_drop"),
+ [({"internal_call_origin": "autorouter_classifier"}, True), ({}, False)],
+ ids=["classifier", "ordinary-request"],
+ )
+ def test_only_classifier_calls_drop_effort_for_an_unsupported_fallback(self, metadata, should_drop):
+ router = litellm.Router(model_list=[])
+ body: dict[str, object] = {"model": "classifier", "reasoning_effort": "low"}
+ kwargs: dict[str, object] = {
+ "reasoning_effort": "low",
+ "metadata": metadata,
+ "proxy_server_request": {"body": body},
+ }
+ deployment: DeploymentTypedDict = {
+ "model_name": "fallback",
+ "litellm_params": {"model": "openai/gpt-4o-mini"},
}
- assert litellm.Router._deployment_accepts_param(deployment, "x", "reasoning_effort") is True
+ router._drop_unsupported_classifier_reasoning_effort(deployment, "fallback", kwargs)
+
+ assert ("reasoning_effort" not in kwargs) is should_drop
+ assert ("reasoning_effort" not in body) is should_drop
+
+
+ class TestPreRoutingTierDrivesFallbacks:
+ """#38832: a complexity/auto router picks a tier behind the router name, but fallback
+ lookup stayed on the router name, so the tier's configured chain never ran and a
+ provider failure on the tier's first hop was returned to the client."""
+
+ class _TierRouter(litellm.Router):
+ async def async_pre_routing_hook(
+ self, model, request_kwargs, messages=None, input=None, specific_deployment=False
+ ):
+ from litellm.types.router import PreRoutingHookResponse
+
+ if model == "smart-router":
+ return PreRoutingHookResponse(model="tier1", messages=messages)
+ return None
+
+ @classmethod
+ def _router(cls, fallbacks) -> "litellm.Router":
+ return cls._TierRouter(
+ model_list=[
+ {
+ "model_name": "smart-router",
+ "litellm_params": {"model": "openai/gpt-4o-mini", "api_key": "sk-x"},
+ },
+ {
+ "model_name": "tier1",
+ "litellm_params": {
+ "model": "openai/gpt-4o-mini",
+ "api_key": "sk-x",
+ "mock_response": "litellm.RateLimitError",
+ },
+ },
+ {
+ "model_name": "backup-a",
+ "litellm_params": {
+ "model": "openai/gpt-4o-mini",
+ "api_key": "sk-x",
+ "mock_response": "from backup-a",
+ },
+ },
+ {
+ "model_name": "backup-b",
+ "litellm_params": {
+ "model": "openai/gpt-4o-mini",
+ "api_key": "sk-x",
+ "mock_response": "from backup-b",
+ },
+ },
+ {
+ "model_name": "failing-backup",
+ "litellm_params": {
+ "model": "openai/gpt-4o-mini",
+ "api_key": "sk-x",
+ "mock_response": "litellm.RateLimitError",
+ },
+ },
+ {
+ "model_name": "plain",
+ "litellm_params": {
+ "model": "openai/gpt-4o-mini",
+ "api_key": "sk-x",
+ "mock_response": "litellm.RateLimitError",
+ },
+ },
+ ],
+ fallbacks=fallbacks,
+ num_retries=0,
+ )
- def test_keeps_a_token_ceiling_the_provider_spells_differently(self):
- """petals lists max_tokens but not max_completion_tokens. A tier ceiling in the unsupported
- spelling is a cost bound: dropping it would let a caller's larger max_tokens through where
- today the mismatch fails loudly."""
- router = self._router("petals/petals-team/StableBeluga2")
+ @pytest.mark.asyncio
+ async def test_the_selected_tier_fallback_chain_runs(self):
+ router = self._router([{"tier1": ["backup-a"]}])
- accepted = router._tier_params_the_target_accepts(
- "tiered", {"max_completion_tokens": 100, "reasoning_effort": "max"}, {}
+ response = await router.acompletion(
+ model="smart-router", messages=[{"role": "user", "content": "hi"}]
)
- assert accepted == {"max_completion_tokens": 100}
+ assert response.choices[0].message.content == "from backup-a"
- def test_keeps_extra_headers_even_when_the_provider_omits_it(self):
- """Several providers leave extra_headers out of their supported params, so the filter would
- drop it. Headers carry auth and tenancy, so sending fewer than the operator configured is
- worse than the error they already get."""
- router = self._router("ai21/jamba-1.5-mini")
+ @pytest.mark.asyncio
+ async def test_a_chain_keyed_on_the_router_name_is_not_used(self):
+ """The router name has no chain of its own, so nothing should rescue this call."""
+ router = self._router([{"tier2": ["backup-a"]}])
- accepted = router._tier_params_the_target_accepts(
- "tiered", {"extra_headers": {"x-tenant": "acme"}, "reasoning_effort": "max"}, {}
- )
+ with pytest.raises(litellm.RateLimitError):
+ await router.acompletion(model="smart-router", messages=[{"role": "user", "content": "hi"}])
- assert accepted == {"extra_headers": {"x-tenant": "acme"}}
+ @pytest.mark.asyncio
+ async def test_a_chain_keyed_on_the_router_name_rescues_when_no_tier_chain_exists(self):
+ """The documented contract: configs keyed on the requested name keep working behind auto-routers."""
+ router = self._router([{"smart-router": ["backup-a"]}])
- def test_keeps_a_param_any_deployment_in_the_group_declares(self):
- """Routing has not picked a deployment yet, so one capable member keeps the param alive."""
- router = litellm.Router(
- model_list=[
- {"model_name": "tiered", "litellm_params": {"model": "novita/moonshotai/kimi-k3", "api_key": "k"}},
- {"model_name": "tiered", "litellm_params": {"model": "fireworks_ai/kimi-k3", "api_key": "k"}},
- ]
- )
+ response = await router.acompletion(model="smart-router", messages=[{"role": "user", "content": "hi"}])
- accepted = router._tier_params_the_target_accepts("tiered", {"reasoning_effort": "max"}, {})
+ assert response.choices[0].message.content == "from backup-a"
- assert accepted == {"reasoning_effort": "max"}
+ @pytest.mark.asyncio
+ async def test_the_tier_chain_wins_over_the_router_name_chain(self):
+ router = self._router([{"tier1": ["backup-a"]}, {"smart-router": ["backup-b"]}])
- def test_deployment_accepts_param_honors_base_model(self):
- """An azure deployment named after the deployment rather than the model carries the real
- model in base_model, and request-time mapping resolves capability through it, so the filter
- has to ask the same question or it drops a param the deployment accepts."""
- by_model_info = {
- "model_name": "x",
- "litellm_params": {"model": "azure/my-gpt5-deploy"},
- "model_info": {"base_model": "azure/gpt-5"},
- }
- by_litellm_params = {
- "model_name": "x",
- "litellm_params": {"model": "azure/my-gpt5-deploy", "base_model": "azure/gpt-5"},
- }
- without_hint = {"model_name": "x", "litellm_params": {"model": "azure/my-gpt5-deploy"}}
+ response = await router.acompletion(model="smart-router", messages=[{"role": "user", "content": "hi"}])
- assert litellm.Router._deployment_accepts_param(by_model_info, "x", "reasoning_effort") is True
- assert litellm.Router._deployment_accepts_param(by_litellm_params, "x", "reasoning_effort") is True
- assert litellm.Router._deployment_accepts_param(without_hint, "x", "reasoning_effort") is False
+ assert response.choices[0].message.content == "from backup-a"
- def test_deployment_accepts_param_reads_the_provider(self):
- deployment = {"model_name": "x", "litellm_params": {"model": "fireworks_ai/kimi-k3"}}
+ @pytest.mark.asyncio
+ async def test_a_request_without_a_pre_routing_hook_still_uses_its_own_group(self):
+ router = self._router([{"tier1": ["backup-a"]}])
- assert litellm.Router._deployment_accepts_param(deployment, "x", "reasoning_effort") is True
+ response = await router.acompletion(
+ model="tier1", messages=[{"role": "user", "content": "hi"}]
+ )
- def test_deployment_accepts_param_is_false_when_the_provider_omits_it(self):
- deployment = {"model_name": "x", "litellm_params": {"model": "novita/moonshotai/kimi-k3"}}
+ assert response.choices[0].message.content == "from backup-a"
- assert litellm.Router._deployment_accepts_param(deployment, "x", "reasoning_effort") is False
+ @pytest.mark.asyncio
+ async def test_a_caller_cannot_pick_the_chain_by_sending_the_selection(self):
+ """The metadata bucket carries caller-supplied keys, so only the hook may set the tier."""
+ router = self._router([{"tier1": ["backup-a"]}])
- @pytest.mark.parametrize(
- "deployment",
- [{"model_name": "x"}, {"model_name": "x", "litellm_params": {}}, {"model_name": "x", "litellm_params": {"model": "not-a-real-provider/nope"}}],
- )
- def test_deployment_accepts_param_fails_open(self, deployment):
- """An unresolvable deployment must not be the reason a param is dropped."""
- assert litellm.Router._deployment_accepts_param(deployment, "x", "reasoning_effort") is True
+ with pytest.raises(litellm.RateLimitError):
+ await router.acompletion(
+ model="plain",
+ messages=[{"role": "user", "content": "hi"}],
+ metadata={"pre_routing_selected_model": "tier1"},
+ )
- @pytest.mark.parametrize(
- "litellm_params",
- [
- {"model": "github_copilot/gpt-4o"},
- {"model": "chatgpt/gpt-5"},
- {"model": "gpt-4o", "custom_llm_provider": "github_copilot"},
- ],
- )
- def test_deployment_accepts_param_never_asks_a_provider_whose_lookup_authenticates(
- self, litellm_params, monkeypatch
- ):
- """Resolving github_copilot or chatgpt runs their OAuth device flow, so a capability
- question asked from the routing path can freeze the event loop for minutes waiting on a
- human. The deployment counts as accepting everything, and the lookup is never made: an
- exception-based sentinel cannot prove that, because the filter swallows exceptions into
- the same keep answer."""
- lookups: list = []
+ @pytest.mark.asyncio
+ async def test_each_fallback_hop_resolves_its_own_chain(self):
+ """The second hop must key off the group it is running, not the tier that failed."""
+ router = self._router([{"tier1": ["failing-backup"]}, {"failing-backup": ["backup-b"]}])
- def _record(*args, **kwargs):
- lookups.append((args, kwargs))
- raise RuntimeError("provider resolution must not run for an authenticating provider")
+ response = await router.acompletion(model="smart-router", messages=[{"role": "user", "content": "hi"}])
- monkeypatch.setattr(litellm, "get_llm_provider", _record)
- deployment = {"model_name": "x", "litellm_params": litellm_params}
+ assert response.choices[0].message.content == "from backup-b"
- assert litellm.Router._deployment_accepts_param(deployment, "x", "reasoning_effort") is True
- assert lookups == []
- def test_keeps_everything_for_an_unknown_group(self):
- """An unresolvable target must never narrow what the request already did."""
- router = self._router("fireworks_ai/kimi-k3")
+ @pytest.mark.asyncio
+ async def test_prompt_management_factory_marks_injection_for_every_deployment(monkeypatch):
+ """The factory stamps a provisional deployment's model_info into kwargs before the
+ prompt pass runs, then routes on the returned model, so any deployment can end up
+ billed. An injection recorded there must carry the every-deployment sentinel, never
+ the provisional deployment's id, or a differently-billed deployment loses the credit."""
+ import time
- accepted = router._tier_params_the_target_accepts("no-such-group", {"reasoning_effort": "max"}, {})
+ from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLogging
- assert accepted == {"reasoning_effort": "max"}
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "cached-claude",
+ "litellm_params": {
+ "model": "anthropic_cache_control_hook/claude-sonnet-5",
+ "prompt_id": "cache-points",
+ },
+ "model_info": {"id": "provisional-dep"},
+ }
+ ]
+ )
+ captured: dict = {}
+ async def _capture_acompletion(**kwargs):
+ captured.update(kwargs)
+ return litellm.ModelResponse()
- class TestRequestReasoningEffortOverride:
- def test_drop_effort_from_nested_carrier_preserves_other_nested_values(self):
- params: dict[str, object] = {"output_config": {"effort": "high", "format": "json"}}
+ monkeypatch.setattr(litellm, "acompletion", _capture_acompletion)
+ logging_obj = LiteLLMLogging(
+ model="cached-claude",
+ messages=[{"role": "user", "content": "hi"}],
+ stream=False,
+ call_type="acompletion",
+ start_time=time.time(),
+ litellm_call_id="lit-6445",
+ function_id="f",
+ )
+ await router.acompletion(
+ model="cached-claude",
+ messages=[
+ {"role": "system", "content": "a static system prompt"},
+ {"role": "user", "content": "hi"},
+ ],
+ cache_control_injection_points=[{"location": "message", "role": "system"}],
+ litellm_logging_obj=logging_obj,
+ )
+ bucket = captured.get("litellm_metadata") or captured["metadata"]
+ assert captured["model_info"]["id"] == "provisional-dep"
+ assert bucket["litellm_gateway_injected_cache"] == ""
- litellm.Router._pop_effort_from_nested_carrier(params, "output_config")
- assert params == {"output_config": {"format": "json"}}
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "retry_policy,upstream_status,error_type,expected_upstream_calls",
+ [
+ ({"ServiceUnavailableErrorRetries": 0}, 503, litellm.ServiceUnavailableError, 1),
+ ({"ServiceUnavailableErrorRetries": 1}, 503, litellm.ServiceUnavailableError, 2),
+ ({"InternalServerErrorRetries": 0}, 500, litellm.InternalServerError, 1),
+ ({"DefaultRetries": 0}, 502, litellm.BadGatewayError, 1),
+ ({"DefaultRetries": 0, "ServiceUnavailableErrorRetries": 1}, 503, litellm.ServiceUnavailableError, 2),
+ ({"ServiceUnavailableErrorRetries": 0}, 502, litellm.BadGatewayError, 3),
+ ({"BadRequestErrorRetries": 2}, 400, litellm.BadRequestError, 3),
+ ],
+ )
+ async def test_router_retry_policy_controls_upstream_attempt_count(
+ monkeypatch: pytest.MonkeyPatch, retry_policy, upstream_status, error_type, expected_upstream_calls
+ ):
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "gpt-5.6",
+ "litellm_params": {
+ "model": "openai/gpt-5.6",
+ "api_key": "sk-fake",
+ "api_base": "https://retry-policy.local/v1",
+ },
+ }
+ ],
+ num_retries=2,
+ retry_policy=retry_policy,
+ disable_cooldowns=True,
+ )
- @pytest.mark.parametrize("metadata_key", ["metadata", "litellm_metadata"])
- def test_is_classifier_internal_call_recognizes_both_metadata_carriers(self, metadata_key):
- kwargs = {metadata_key: {"internal_call_origin": "autorouter_classifier"}}
+ with respx.mock(assert_all_called=True) as respx_mock:
+ upstream = respx_mock.post("https://retry-policy.local/v1/chat/completions").mock(
+ return_value=httpx.Response(
+ upstream_status,
+ headers={"retry-after": "0"},
+ json={"error": {"message": "model is down", "type": "server_error"}},
+ )
+ )
+ with pytest.raises(error_type):
+ await router.acompletion(model="gpt-5.6", messages=[{"role": "user", "content": "hi"}])
- assert litellm.Router._is_classifier_internal_call(kwargs) is True
- assert litellm.Router._is_classifier_internal_call({metadata_key: {}}) is False
+ assert upstream.call_count == expected_upstream_calls
- def test_removes_every_deployment_native_effort_carrier_without_mutating_shared_config(self):
- extra_body: dict[str, object] = {
- "reasoning_effort": "high",
- "thinking": {"type": "enabled"},
- "output_config": {"effort": "high", "format": "json"},
- "reasoning": {"effort": "high", "summary": "detailed"},
- "provider_option": True,
- }
- deployment_params: dict[str, object] = {
- "model": "bedrock/converse/anthropic.claude-3-7-sonnet",
- "thinking": {"type": "enabled", "budget_tokens": 2048},
- "output_config": {"effort": "high", "format": {"type": "json_schema"}},
- "reasoning": {"effort": "high", "summary": "auto"},
- "extra_body": extra_body,
- }
- sanitized = litellm.Router._deployment_params_with_request_reasoning_override(
- deployment_params, {"reasoning_effort": "low"}
++async def test_generic_call_keeps_the_deployment_name_of_an_azure_ai_model_on_an_azure_openai_host(monkeypatch):
++ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
++ router = litellm.Router(
++ model_list=[
++ {
++ "model_name": "aoai-gpt",
++ "litellm_params": {
++ "model": "azure_ai/gpt-5.4-mini",
++ "api_base": "https://my-resource.openai.azure.com",
++ "api_key": "deployment-key",
++ },
++ }
++ ]
++ )
++
++ with respx.mock(assert_all_called=True) as respx_mock:
++ upstream = respx_mock.post(host="my-resource.openai.azure.com", path__regex=r"^/openai/.*responses$").mock(
++ return_value=httpx.Response(
++ 200,
++ json={
++ "id": "resp_1",
++ "object": "response",
++ "created_at": 1,
++ "status": "completed",
++ "model": "gpt-5.4-mini",
++ "output": [
++ {
++ "type": "message",
++ "id": "msg_1",
++ "role": "assistant",
++ "status": "completed",
++ "content": [{"type": "output_text", "text": "hi", "annotations": []}],
++ }
++ ],
++ },
++ )
+ )
++ await router.aresponses(model="aoai-gpt", input="hi")
+
- assert sanitized == {
- "model": "bedrock/converse/anthropic.claude-3-7-sonnet",
- "output_config": {"format": {"type": "json_schema"}},
- "reasoning": {"summary": "auto"},
- "extra_body": {
- "output_config": {"format": "json"},
- "reasoning": {"summary": "detailed"},
- "provider_option": True,
- },
- }
- assert deployment_params["thinking"] == {"type": "enabled", "budget_tokens": 2048}
- assert deployment_params["output_config"] == {"effort": "high", "format": {"type": "json_schema"}}
- assert extra_body["reasoning_effort"] == "high"
-
- @pytest.mark.parametrize("request_kwargs", [{}, {"reasoning_effort": None}])
- def test_omitted_override_preserves_deployment_defaults(self, request_kwargs):
- deployment_params = {
- "model": "deepseek/deepseek-reasoner",
- "thinking": {"type": "enabled"},
- "output_config": {"effort": "high"},
- }
++ assert json.loads(upstream.calls.last.request.content)["model"] == "gpt-5.4-mini"
+
- assert (
- litellm.Router._deployment_params_with_request_reasoning_override(deployment_params, request_kwargs)
- == deployment_params
- )
+
- @pytest.mark.asyncio
- async def test_280_concurrent_overrides_never_mutate_or_leak_through_shared_deployment_params(self):
- deployment_params = {
- "model": "fireworks_ai/accounts/fireworks/models/kimi-k2-thinking",
- "thinking": {"type": "enabled"},
- "output_config": {"effort": "high", "format": "json"},
- "extra_body": {"reasoning_effort": "high", "tenant": "shared"},
- }
- efforts = ("none", "minimal", "low", "medium", "high", "xhigh", "max")
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "retry_policy,upstream_error",
+ [
+ (
+ {"BadRequestErrorRetries": 2},
+ {
+ "message": "This model's maximum context length is 16385 tokens",
+ "type": "invalid_request_error",
+ "code": "context_length_exceeded",
+ },
+ ),
+ (
+ {"ContentPolicyViolationErrorRetries": 2},
+ {
+ "message": "Your request was rejected as a result of our safety system",
+ "type": "invalid_request_error",
+ "code": "content_policy_violation",
+ },
+ ),
+ ],
+ )
+ async def test_router_retry_policy_400_retries_on_sibling_deployment(
+ monkeypatch: pytest.MonkeyPatch, retry_policy, upstream_error
+ ):
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "gpt-5.6",
+ "litellm_params": {
+ "model": "openai/gpt-5.6",
+ "api_key": "sk-fake",
+ "api_base": "https://rejecting.local/v1",
+ "weight": 1,
+ },
+ "model_info": {"id": "rejecting"},
+ },
+ {
+ "model_name": "gpt-5.6",
+ "litellm_params": {
+ "model": "openai/gpt-5.6",
+ "api_key": "sk-fake",
+ "api_base": "https://accepting.local/v1",
+ "weight": 0,
+ },
+ "model_info": {"id": "accepting"},
+ },
+ ],
+ num_retries=2,
+ retry_policy=retry_policy,
+ disable_cooldowns=True,
+ )
- results = await asyncio.gather(
- *(
- asyncio.to_thread(
- litellm.Router._deployment_params_with_request_reasoning_override,
- deployment_params,
- {"reasoning_effort": efforts[index % len(efforts)]},
- )
- for index in range(280)
+ with respx.mock(assert_all_called=True) as respx_mock:
+ rejecting = respx_mock.post("https://rejecting.local/v1/chat/completions").mock(
+ return_value=httpx.Response(400, json={"error": upstream_error})
+ )
+ accepting = respx_mock.post("https://accepting.local/v1/chat/completions").mock(
+ return_value=httpx.Response(
+ 200,
+ json={
+ "id": "chatcmpl-lit-7036",
+ "object": "chat.completion",
+ "created": 1,
+ "model": "gpt-5.6",
+ "choices": [
+ {"index": 0, "message": {"role": "assistant", "content": "hi back"}, "finish_reason": "stop"}
+ ],
+ "usage": {"prompt_tokens": 1, "completion_tokens": 2, "total_tokens": 3},
+ },
)
)
+ response = await router.acompletion(model="gpt-5.6", messages=[{"role": "user", "content": "hi"}])
- assert all("thinking" not in result for result in results)
- assert all(result["output_config"] == {"format": "json"} for result in results)
- assert all(result["extra_body"] == {"tenant": "shared"} for result in results)
- assert deployment_params["thinking"] == {"type": "enabled"}
- assert deployment_params["output_config"] == {"effort": "high", "format": "json"}
- assert deployment_params["extra_body"] == {"reasoning_effort": "high", "tenant": "shared"}
+ assert rejecting.call_count == 1
+ assert accepting.call_count == 1
+ assert response.choices[0].message.content == "hi back"
+ assert response._hidden_params["additional_headers"]["x-litellm-attempted-retries"] == 1
- @pytest.mark.parametrize(
- ("metadata", "should_drop"),
- [({"internal_call_origin": "autorouter_classifier"}, True), ({}, False)],
- ids=["classifier", "ordinary-request"],
- )
- def test_only_classifier_calls_drop_effort_for_an_unsupported_fallback(self, metadata, should_drop):
- router = litellm.Router(model_list=[])
- body: dict[str, object] = {"model": "classifier", "reasoning_effort": "low"}
- kwargs: dict[str, object] = {
- "reasoning_effort": "low",
- "metadata": metadata,
- "proxy_server_request": {"body": body},
- }
- deployment: DeploymentTypedDict = {
- "model_name": "fallback",
- "litellm_params": {"model": "openai/gpt-4o-mini"},
- }
- router._drop_unsupported_classifier_reasoning_effort(deployment, "fallback", kwargs)
+ _UPSTREAM_400 = {"message": "upstream refused this request", "type": "invalid_request_error", "code": "bad_request"}
- assert ("reasoning_effort" not in kwargs) is should_drop
- assert ("reasoning_effort" not in body) is should_drop
+ def _retry_skip_deployment(deployment_id, host, litellm_params=None, model_info=None):
+ return {
+ "model_name": "gpt-5.6",
+ "litellm_params": {
+ "model": "openai/gpt-5.6",
+ "api_key": "sk-fake",
+ "api_base": f"https://{host}.local/v1",
+ **(litellm_params or {}),
+ },
+ "model_info": {"id": deployment_id, **(model_info or {})},
+ }
- class TestPreRoutingTierDrivesFallbacks:
- """#38832: a complexity/auto router picks a tier behind the router name, but fallback
- lookup stayed on the router name, so the tier's configured chain never ran and a
- provider failure on the tier's first hop was returned to the client."""
- class _TierRouter(litellm.Router):
- async def async_pre_routing_hook(
- self, model, request_kwargs, messages=None, input=None, specific_deployment=False
- ):
- from litellm.types.router import PreRoutingHookResponse
+ @pytest.mark.parametrize(
+ "status_code,failed_deployment_id,already_skipped,expected",
+ [
+ (400, "rejecting", None, ("rejecting",)),
+ (403, "rejecting", None, ("rejecting",)),
+ (400, "second", ("first",), ("first", "second")),
+ (400, "first", ("first",), ("first",)),
+ (429, "rejecting", None, ()),
+ (503, "rejecting", None, ()),
+ (408, "rejecting", None, ()),
+ (400, None, None, ()),
+ (None, "rejecting", None, ()),
+ ("400", "rejecting", None, ()),
+ (400, "second", 7, ("second",)),
+ (400, "second", "first", ("second",)),
+ (400, "second", ["first"], ("second",)),
+ (400, "second", ("first", 7), ("first", "second")),
+ ],
+ )
+ def test_router_deployment_ids_to_skip_on_retry(status_code, failed_deployment_id, already_skipped, expected):
+ exception = Exception("upstream refused this request")
+ exception.status_code = status_code
+ exception.failed_deployment_id = failed_deployment_id
- if model == "smart-router":
- return PreRoutingHookResponse(model="tier1", messages=messages)
- return None
+ assert litellm.Router._deployment_ids_to_skip_on_retry(exception, already_skipped) == expected
- @classmethod
- def _router(cls, fallbacks) -> "litellm.Router":
- return cls._TierRouter(
- model_list=[
- {
- "model_name": "smart-router",
- "litellm_params": {"model": "openai/gpt-4o-mini", "api_key": "sk-x"},
- },
- {
- "model_name": "tier1",
- "litellm_params": {
- "model": "openai/gpt-4o-mini",
- "api_key": "sk-x",
- "mock_response": "litellm.RateLimitError",
- },
- },
- {
- "model_name": "backup-a",
- "litellm_params": {
- "model": "openai/gpt-4o-mini",
- "api_key": "sk-x",
- "mock_response": "from backup-a",
- },
- },
- {
- "model_name": "backup-b",
- "litellm_params": {
- "model": "openai/gpt-4o-mini",
- "api_key": "sk-x",
- "mock_response": "from backup-b",
- },
- },
- {
- "model_name": "failing-backup",
- "litellm_params": {
- "model": "openai/gpt-4o-mini",
- "api_key": "sk-x",
- "mock_response": "litellm.RateLimitError",
- },
- },
- {
- "model_name": "plain",
- "litellm_params": {
- "model": "openai/gpt-4o-mini",
- "api_key": "sk-x",
- "mock_response": "litellm.RateLimitError",
- },
- },
- ],
- fallbacks=fallbacks,
- num_retries=0,
- )
- @pytest.mark.asyncio
- async def test_the_selected_tier_fallback_chain_runs(self):
- router = self._router([{"tier1": ["backup-a"]}])
+ @pytest.mark.parametrize(
+ "value,expected",
+ [
+ (("first", "second"), ("first", "second")),
+ ((), ()),
+ (("first", 7, None, "second"), ("first", "second")),
+ (None, ()),
+ (7, ()),
+ ("first", ()),
+ (["first"], ()),
+ ({"first": True}, ()),
+ (object(), ()),
+ ],
+ )
+ def test_router_as_retry_skipped_deployment_ids_keeps_only_a_tuple_of_strings(value, expected):
+ from litellm.router import _as_retry_skipped_deployment_ids
- response = await router.acompletion(
- model="smart-router", messages=[{"role": "user", "content": "hi"}]
- )
+ assert _as_retry_skipped_deployment_ids(value) == expected
- assert response.choices[0].message.content == "from backup-a"
- @pytest.mark.asyncio
- async def test_a_chain_keyed_on_the_router_name_is_not_used(self):
- """The router name has no chain of its own, so nothing should rescue this call."""
- router = self._router([{"tier2": ["backup-a"]}])
+ @pytest.mark.parametrize(
+ "deployment_ids,skipped,expected",
+ [
+ (["rejecting", "sibling"], ("rejecting",), ["sibling"]),
+ (["rejecting"], ("rejecting",), ["rejecting"]),
+ (["rejecting", "sibling"], ("rejecting", "sibling"), ["rejecting", "sibling"]),
+ (["rejecting", "sibling"], (), ["rejecting", "sibling"]),
+ (["rejecting", "sibling"], None, ["rejecting", "sibling"]),
+ (["rejecting", "sibling"], ("absent",), ["rejecting", "sibling"]),
+ (["rejecting", "sibling"], 7, ["rejecting", "sibling"]),
+ (["rejecting", "sibling"], "rejecting", ["rejecting", "sibling"]),
+ (["rejecting", "sibling"], ["rejecting"], ["rejecting", "sibling"]),
+ (["rejecting", "sibling"], {"rejecting": True}, ["rejecting", "sibling"]),
+ (["rejecting", "sibling"], ("rejecting", 7), ["sibling"]),
+ ],
+ )
+ @pytest.mark.asyncio
+ async def test_router_healthy_deployments_keep_the_last_candidate_a_retry_skipped(deployment_ids, skipped, expected):
+ router = litellm.Router(
+ model_list=[_retry_skip_deployment(deployment_id, deployment_id) for deployment_id in deployment_ids],
+ disable_cooldowns=True,
+ )
+ request_kwargs = {"_retry_skipped_deployment_ids": skipped}
- with pytest.raises(litellm.RateLimitError):
- await router.acompletion(model="smart-router", messages=[{"role": "user", "content": "hi"}])
+ healthy_deployments = await router.async_get_healthy_deployments(model="gpt-5.6", request_kwargs=request_kwargs)
- @pytest.mark.asyncio
- async def test_a_chain_keyed_on_the_router_name_rescues_when_no_tier_chain_exists(self):
- """The documented contract: configs keyed on the requested name keep working behind auto-routers."""
- router = self._router([{"smart-router": ["backup-a"]}])
+ assert sorted(deployment["model_info"]["id"] for deployment in healthy_deployments) == sorted(expected)
+ assert "_retry_skipped_deployment_ids" not in request_kwargs
- response = await router.acompletion(model="smart-router", messages=[{"role": "user", "content": "hi"}])
- assert response.choices[0].message.content == "from backup-a"
+ @pytest.mark.parametrize("client_supplied", [7, "rejecting", ["rejecting"], {"rejecting": True}, object()])
+ @pytest.mark.asyncio
+ async def test_router_retry_policy_400_keeps_upstream_error_when_a_client_forges_the_skip_list(
+ monkeypatch: pytest.MonkeyPatch, client_supplied
+ ):
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+ router = litellm.Router(
+ model_list=[_retry_skip_deployment("rejecting", "rejecting"), _retry_skip_deployment("sibling", "sibling")],
+ num_retries=2,
+ retry_policy={"BadRequestErrorRetries": 2},
+ disable_cooldowns=True,
+ )
- @pytest.mark.asyncio
- async def test_the_tier_chain_wins_over_the_router_name_chain(self):
- router = self._router([{"tier1": ["backup-a"]}, {"smart-router": ["backup-b"]}])
+ with respx.mock as respx_mock:
+ respx_mock.post("https://rejecting.local/v1/chat/completions").mock(
+ return_value=httpx.Response(400, json={"error": _UPSTREAM_400})
+ )
+ respx_mock.post("https://sibling.local/v1/chat/completions").mock(
+ return_value=httpx.Response(400, json={"error": _UPSTREAM_400})
+ )
+ with pytest.raises(litellm.BadRequestError) as raised:
+ await router.acompletion(
+ model="gpt-5.6",
+ messages=[{"role": "user", "content": "hi"}],
+ _retry_skipped_deployment_ids=client_supplied,
+ )
- response = await router.acompletion(model="smart-router", messages=[{"role": "user", "content": "hi"}])
+ assert "upstream refused this request" in str(raised.value)
- assert response.choices[0].message.content == "from backup-a"
- @pytest.mark.asyncio
- async def test_a_request_without_a_pre_routing_hook_still_uses_its_own_group(self):
- router = self._router([{"tier1": ["backup-a"]}])
+ @pytest.mark.asyncio
+ async def test_router_retry_policy_400_keeps_upstream_error_on_order_fallback_hop(monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+ router = litellm.Router(
+ model_list=[
+ _retry_skip_deployment("order1", "order1", litellm_params={"order": 1}),
+ _retry_skip_deployment("order2", "order2", litellm_params={"order": 2}),
+ ],
+ num_retries=2,
+ retry_policy={"BadRequestErrorRetries": 2},
+ disable_cooldowns=True,
+ )
- response = await router.acompletion(
- model="tier1", messages=[{"role": "user", "content": "hi"}]
+ with respx.mock as respx_mock:
+ order1 = respx_mock.post("https://order1.local/v1/chat/completions").mock(
+ return_value=httpx.Response(400, json={"error": _UPSTREAM_400})
)
+ order2 = respx_mock.post("https://order2.local/v1/chat/completions").mock(
+ return_value=httpx.Response(400, json={"error": _UPSTREAM_400})
+ )
+ with pytest.raises(litellm.BadRequestError) as raised:
+ await router.acompletion(model="gpt-5.6", messages=[{"role": "user", "content": "hi"}])
- assert response.choices[0].message.content == "from backup-a"
+ assert "upstream refused this request" in str(raised.value)
+ assert "No deployments available" not in str(raised.value)
+ assert order1.call_count >= 1
+ assert order2.call_count >= 1
- @pytest.mark.asyncio
- async def test_a_caller_cannot_pick_the_chain_by_sending_the_selection(self):
- """The metadata bucket carries caller-supplied keys, so only the hook may set the tier."""
- router = self._router([{"tier1": ["backup-a"]}])
- with pytest.raises(litellm.RateLimitError):
+ @pytest.mark.asyncio
+ async def test_router_retry_policy_400_keeps_upstream_error_when_tags_narrow_the_group(
+ monkeypatch: pytest.MonkeyPatch,
+ ):
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+ router = litellm.Router(
+ model_list=[
+ _retry_skip_deployment(
+ "tagged", "tagged", litellm_params={"tags": ["free"]}, model_info={"enable_tag_filtering": True}
+ ),
+ _retry_skip_deployment("untagged", "untagged", model_info={"enable_tag_filtering": True}),
+ ],
+ num_retries=2,
+ retry_policy={"BadRequestErrorRetries": 2},
+ disable_cooldowns=True,
+ )
+
+ with respx.mock as respx_mock:
+ tagged = respx_mock.post("https://tagged.local/v1/chat/completions").mock(
+ return_value=httpx.Response(400, json={"error": _UPSTREAM_400})
+ )
+ untagged = respx_mock.post("https://untagged.local/v1/chat/completions").mock(
+ return_value=httpx.Response(400, json={"error": _UPSTREAM_400})
+ )
+ with pytest.raises(litellm.BadRequestError) as raised:
await router.acompletion(
- model="plain",
+ model="gpt-5.6",
messages=[{"role": "user", "content": "hi"}],
- metadata={"pre_routing_selected_model": "tier1"},
+ metadata={"tags": ["free"]},
)
- @pytest.mark.asyncio
- async def test_each_fallback_hop_resolves_its_own_chain(self):
- """The second hop must key off the group it is running, not the tier that failed."""
- router = self._router([{"tier1": ["failing-backup"]}, {"failing-backup": ["backup-b"]}])
-
- response = await router.acompletion(model="smart-router", messages=[{"role": "user", "content": "hi"}])
-
- assert response.choices[0].message.content == "from backup-b"
+ assert "upstream refused this request" in str(raised.value)
+ assert "No deployments available" not in str(raised.value)
+ assert tagged.call_count == 3
+ assert untagged.call_count == 0
@pytest.mark.asyncio