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]

fix(router): add fallback_on_unsupported_params so param rejections can raise instead of falling back (#46350)

Kerry Lub9849f358817
diff --git a/litellm/constants.py b/litellm/constants.py
index 4ac6adaba73..bbf6b8a4f04 100644
--- a/litellm/constants.py
+++ b/litellm/constants.py
@@ -60,6 +60,7 @@ RUNTIME_UPDATABLE_ROUTER_SETTINGS: Final[frozenset[str]] = frozenset(
"enable_tag_filtering",
"tag_routing_prefix",
"optional_pre_call_checks",
+ "fallback_on_unsupported_params",
}
)
ROUTER_SETTINGS_MANAGED_OUTSIDE_CONFIG: Final[frozenset[str]] = frozenset(
diff --git a/litellm/router.py b/litellm/router.py
index 16257775d3f..b38b78b60d9 100644
--- a/litellm/router.py
+++ b/litellm/router.py
@@ -230,6 +230,7 @@ from litellm.router_utils.fallback_event_handlers import (
get_fallback_model_group_for_lookup_groups,
get_pre_routing_selection,
has_unattempted_fallback_target,
+ is_bad_request_without_fallback,
mid_stream_fallback_hop_kwargs,
mid_stream_fallback_snapshot_kwargs,
mid_stream_retry_kwargs,
@@ -1022,6 +1023,7 @@ class Router:
allowed_fails_policy: AllowedFailsPolicy | None = None, # set custom allowed fails policy
cooldown_time: float | None = None, # (seconds) time to cooldown a deployment after failure
disable_cooldowns: bool | None = None,
+ fallback_on_unsupported_params: bool = True,
routing_strategy: RoutingStrategyName = "simple-shuffle",
optional_pre_call_checks: OptionalPreCallChecks | None = None,
routing_strategy_args: dict = {}, # just for latency-based
@@ -1264,6 +1266,7 @@ class Router:
self.cooldown_time = cooldown_time or DEFAULT_COOLDOWN_TIME_SECONDS
self.cooldown_cache = CooldownCache(cache=self.cache, default_cooldown_time=self.cooldown_time)
self.disable_cooldowns = disable_cooldowns
+ self.fallback_on_unsupported_params = fallback_on_unsupported_params
self.enable_health_check_routing = enable_health_check_routing
self.enable_weighted_failover = enable_weighted_failover
self.health_check_ignore_transient_errors = health_check_ignore_transient_errors
@@ -3270,7 +3273,7 @@ class Router:
wrapped_response: Final = FallbackStreamWrapper(stream_with_fallbacks())
# weak, so the generator closing over it does not keep the wrapper out of
# refcount teardown and delay the `finally` that releases the deployment slot
- wrapper_ref: Final = weakref.ref(wrapped_response)
+ wrapper_ref: Final[weakref.ref[FallbackAwareStreamWrapper]] = weakref.ref(wrapped_response)
return wrapped_response
@staticmethod
@@ -3875,7 +3878,7 @@ class Router:
wrapped_response: Final = SyncFallbackStreamWrapper(stream_with_fallbacks())
# weak, for the same reason as the async twin
- wrapper_ref: Final = weakref.ref(wrapped_response)
+ wrapper_ref: Final[weakref.ref[FallbackAwareStreamWrapper]] = weakref.ref(wrapped_response)
return wrapped_response
async def _silent_experiment_acompletion(self, silent_model: str, messages: Sequence[Mapping[str, str]], **kwargs):
@@ -7728,7 +7731,15 @@ class Router:
hop_depth: Final = kwargs.get("fallback_depth")
nested_fallback_hop: Final = isinstance(hop_depth, int) and hop_depth > 0
- if disable_fallbacks is True or original_model_group is None or is_guardrail_intervention(e):
+ unsupported_params_without_fallback: Final = is_bad_request_without_fallback(
+ e, self.fallback_on_unsupported_params
+ )
+ if (
+ disable_fallbacks is True
+ or original_model_group is None
+ or is_guardrail_intervention(e)
+ or unsupported_params_without_fallback
+ ):
raise e
input_kwargs: Final = {
@@ -12802,6 +12813,7 @@ class Router:
"enable_weighted_failover",
"enable_tag_filtering",
"tag_routing_prefix",
+ "fallback_on_unsupported_params",
]
for var in vars_to_include:
diff --git a/litellm/router_utils/fallback_event_handlers.py b/litellm/router_utils/fallback_event_handlers.py
index e1de57c91a0..4c393a7a93b 100644
--- a/litellm/router_utils/fallback_event_handlers.py
+++ b/litellm/router_utils/fallback_event_handlers.py
@@ -222,6 +222,16 @@ def has_unattempted_fallback_target(
return any((key := fallback_attempt_key(target)) is None or key not in attempted for target in fallback_model_group)
+def is_bad_request_without_fallback(exception: Exception, fallback_on_unsupported_params: bool) -> bool:
+ if fallback_on_unsupported_params or not isinstance(exception, litellm.BadRequestError):
+ return False
+ if isinstance(exception, litellm.UnsupportedParamsError):
+ return True
+ if isinstance(exception, (litellm.ContextWindowExceededError, litellm.ContentPolicyViolationError)):
+ return False
+ return exception.status_code == 400 and bool(getattr(exception, "llm_provider", ""))
+
+
def _check_stripped_model_group(model_group: str, fallback_key: str) -> bool:
"""
Handles wildcard routing scenario
@@ -514,7 +524,7 @@ def fallback_lookup_groups(kwargs: Mapping[str, object], model_group: str | None
def _resolved_a_specific_chain(
- fallbacks: list[Any], # mutable-ok: mirrors get_fallback_model_group's contract
+ fallbacks: Sequence[Mapping[str, list[str]]], # mutable-ok: mirrors the fallbacks config shape
result: tuple[list[str] | None, int | None], # mutable-ok: mirrors get_fallback_model_group's contract
) -> bool:
resolved, generic_idx = result
@@ -524,7 +534,7 @@ def _resolved_a_specific_chain(
def get_fallback_model_group_for_lookup_groups(
- fallbacks: list[Any], # mutable-ok: mirrors get_fallback_model_group's contract
+ fallbacks: Sequence[Mapping[str, list[str]]], # mutable-ok: mirrors the fallbacks config shape
lookup_groups: tuple[str, ...],
) -> tuple[list[str] | None, int | None]: # mutable-ok: mirrors get_fallback_model_group's contract
"""
@@ -538,7 +548,10 @@ def get_fallback_model_group_for_lookup_groups(
return next((result for result in results if result[0] is not None), (None, None))
-def get_fallback_model_group(fallbacks: list[Any], model_group: str) -> tuple[list[str] | None, int | None]:
+def get_fallback_model_group(
+ fallbacks: Sequence[Mapping[str, list[str]]], # mutable-ok: mirrors the fallbacks config shape
+ model_group: str,
+) -> tuple[list[str] | None, int | None]: # mutable-ok: mirrors get_fallback_model_group's contract
"""
Returns:
- fallback_model_group: List[str] of fallback model groups. example: ["gpt-4", "gpt-3.5-turbo"]
diff --git a/litellm/types/router.py b/litellm/types/router.py
index 273edf0f913..59b6798bfdc 100644
--- a/litellm/types/router.py
+++ b/litellm/types/router.py
@@ -188,6 +188,7 @@ class UpdateRouterConfig(LiteLLMBaseModel):
weights: RouterWeights | None = None
tag_routing_prefix: str | None = None
optional_pre_call_checks: OptionalPreCallChecks | None = None
+ fallback_on_unsupported_params: bool | None = None
model_config = ConfigDict(protected_namespaces=())
diff --git a/tests/integration/sdk/test_router_unsupported_params_fallback_wire.py b/tests/integration/sdk/test_router_unsupported_params_fallback_wire.py
new file mode 100644
index 00000000000..e7675fb64ee
--- /dev/null
+++ b/tests/integration/sdk/test_router_unsupported_params_fallback_wire.py
@@ -0,0 +1,213 @@
+from __future__ import annotations
+
+import asyncio
+import json
+from collections.abc import Callable, Mapping
+from typing import Final
+
+import pytest
+from integration._support.wire import Reply, Request, Wire, wire_server
+
+import litellm
+from litellm import Router
+
+_MODEL: Final = "gpt-5-wire-unmapped"
+_API_KEY: Final = "synthetic-unsupported-params-key"
+_PROMPT: Final = "which deployment answers when the requested model rejects the request?"
+_CLIENTS: Final = ("sync", "async")
+_PRIMARY_TO_BACKUP: Final = [{"primary": ["backup"]}]
+_UNSUPPORTED_BY_PRIMARY: Final = {"reasoning_effort": "xhigh"}
+
+
+def _answers(text: str) -> Reply:
+ body: Final = {
+ "id": "chatcmpl-bad-request-wire",
+ "object": "chat.completion",
+ "created": 1700000000,
+ "model": _MODEL,
+ "choices": [{"index": 0, "message": {"role": "assistant", "content": text}, "finish_reason": "stop"}],
+ "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
+ }
+ return Reply(body=json.dumps(body).encode())
+
+
+_UPSTREAM_500: Final = Reply(status=500, body=json.dumps({"error": {"message": "overloaded"}}).encode())
+_UPSTREAM_400: Final = Reply(
+ status=400,
+ body=json.dumps({"error": {"message": "Unsupported value: temperature", "type": "invalid_request_error"}}).encode(),
+)
+_UPSTREAM_CONTEXT_WINDOW: Final = Reply(
+ status=400,
+ body=json.dumps(
+ {
+ "error": {
+ "message": "This model's maximum context length is 8192 tokens",
+ "type": "invalid_request_error",
+ "code": "context_length_exceeded",
+ }
+ }
+ ).encode(),
+)
+_UPSTREAM_CONTENT_POLICY: Final = Reply(
+ status=400,
+ body=json.dumps(
+ {
+ "error": {
+ "message": "Your request was rejected",
+ "type": "invalid_request_error",
+ "code": "content_policy_violation",
+ }
+ }
+ ).encode(),
+)
+_BACKUP_ANSWERS: Final = _answers("answered by the backup")
+
+
+def _peer(replies: Mapping[str, Reply]) -> Callable[[Request], Reply]:
+ def respond(request: Request) -> Reply:
+ assert request.method == "POST", request.method
+ deployment, _, route = request.target.lstrip("/").partition("/")
+ assert route == "chat/completions", request.target
+ return replies[deployment]
+
+ return respond
+
+
+def _deployments_hit(wire: Wire) -> tuple[str, ...]:
+ return tuple(request.target.lstrip("/").partition("/")[0] for request in wire.drain())
+
+
+_ALL_DAY_FOR_TEAM_A: Final = (
+ {"start": "00:00", "end": "12:00", "timezone": "UTC", "team_ids": ["team-a"]},
+ {"start": "12:00", "end": "00:00", "timezone": "UTC", "team_ids": ["team-a"]},
+)
+
+
+def _router(wire: Wire, primary_model_info: Mapping[str, object] | None = None, **settings: object) -> Router:
+ return Router(
+ model_list=[
+ {
+ "model_name": "primary",
+ "litellm_params": {"model": f"openai/{_MODEL}", "api_base": f"{wire.url}/primary", "api_key": _API_KEY},
+ "model_info": dict(primary_model_info or {}),
+ },
+ {
+ "model_name": "backup",
+ "litellm_params": {
+ "model": f"openai/{_MODEL}",
+ "api_base": f"{wire.url}/backup",
+ "api_key": _API_KEY,
+ "drop_params": True,
+ },
+ },
+ ],
+ num_retries=0,
+ disable_cooldowns=True,
+ **{"fallbacks": _PRIMARY_TO_BACKUP, **settings},
+ )
+
+
+_MESSAGES: Final = [{"role": "user", "content": _PROMPT}]
+
+
+def _content(response: litellm.ModelResponse) -> str:
+ choice: Final = response.choices[0]
+ assert isinstance(choice, litellm.Choices), choice
+ return str(choice.message.content)
+
+
+async def _acomplete(router: Router, **request: object) -> str:
+ response: Final = await router.acompletion(model="primary", messages=_MESSAGES, **request)
+ assert isinstance(response, litellm.ModelResponse), response
+ return _content(response)
+
+
+def _complete(client: str, router: Router, **request: object) -> str:
+ if client == "async":
+ return asyncio.run(_acomplete(router, **request))
+ response: Final = router.completion(model="primary", messages=_MESSAGES, **request)
+ assert isinstance(response, litellm.ModelResponse), response
+ return _content(response)
+
+
[email protected]("client", _CLIENTS)
+def test_client_side_param_rejection_reaches_the_caller_without_trying_fallbacks(client: str) -> None:
+ with wire_server(_peer({"backup": _BACKUP_ANSWERS})) as wire:
+ router: Final = _router(wire, fallback_on_unsupported_params=False)
+ with pytest.raises(litellm.UnsupportedParamsError, match="reasoning_effort"):
+ _complete(client, router, **_UNSUPPORTED_BY_PRIMARY)
+ assert _deployments_hit(wire) == ()
+
+
[email protected]("client", _CLIENTS)
+def test_client_side_param_rejection_still_falls_back_by_default(client: str) -> None:
+ with wire_server(_peer({"backup": _BACKUP_ANSWERS})) as wire:
+ router: Final = _router(wire)
+ assert _complete(client, router, **_UNSUPPORTED_BY_PRIMARY) == "answered by the backup"
+ assert _deployments_hit(wire) == ("backup",)
+
+
[email protected]("client", _CLIENTS)
+def test_upstream_500_still_falls_back_when_bad_requests_raise(client: str) -> None:
+ with wire_server(_peer({"primary": _UPSTREAM_500, "backup": _BACKUP_ANSWERS})) as wire:
+ router: Final = _router(wire, fallback_on_unsupported_params=False)
+ assert _complete(client, router) == "answered by the backup"
+ assert _deployments_hit(wire) == ("primary", "backup")
+
+
[email protected]("client", _CLIENTS)
+def test_router_raised_400_still_falls_back_when_bad_requests_raise(client: str) -> None:
+ with wire_server(_peer({"backup": _BACKUP_ANSWERS})) as wire:
+ router: Final = _router(
+ wire, primary_model_info={"access_windows": _ALL_DAY_FOR_TEAM_A}, fallback_on_unsupported_params=False
+ )
+ answer: Final = _complete(client, router, metadata={"user_api_key_team_id": "team-b"})
+ assert answer == "answered by the backup"
+ assert _deployments_hit(wire) == ("backup",)
+
+
[email protected]("client", _CLIENTS)
+def test_context_window_error_still_uses_its_own_fallbacks_when_bad_requests_raise(client: str) -> None:
+ with wire_server(_peer({"primary": _UPSTREAM_CONTEXT_WINDOW, "backup": _BACKUP_ANSWERS})) as wire:
+ router: Final = _router(
+ wire, fallback_on_unsupported_params=False, fallbacks=None, context_window_fallbacks=_PRIMARY_TO_BACKUP
+ )
+ assert _complete(client, router) == "answered by the backup"
+ assert _deployments_hit(wire) == ("primary", "backup")
+
+
[email protected]("client", _CLIENTS)
+def test_content_policy_error_still_uses_its_own_fallbacks_when_bad_requests_raise(client: str) -> None:
+ with wire_server(_peer({"primary": _UPSTREAM_CONTENT_POLICY, "backup": _BACKUP_ANSWERS})) as wire:
+ router: Final = _router(
+ wire, fallback_on_unsupported_params=False, fallbacks=None, content_policy_fallbacks=_PRIMARY_TO_BACKUP
+ )
+ assert _complete(client, router) == "answered by the backup"
+ assert _deployments_hit(wire) == ("primary", "backup")
+
+
[email protected]("client", _CLIENTS)
+def test_upstream_400_reaches_the_caller_without_trying_fallbacks(client: str) -> None:
+ with wire_server(_peer({"primary": _UPSTREAM_400, "backup": _BACKUP_ANSWERS})) as wire:
+ router: Final = _router(wire, fallback_on_unsupported_params=False)
+ with pytest.raises(litellm.BadRequestError, match="Unsupported value: temperature"):
+ _complete(client, router)
+ assert _deployments_hit(wire) == ("primary",)
+
+
[email protected]("client", _CLIENTS)
+def test_flag_applied_through_update_settings_stops_fallbacks_on_upstream_400(client: str) -> None:
+ with wire_server(_peer({"primary": _UPSTREAM_400, "backup": _BACKUP_ANSWERS})) as wire:
+ router: Final = _router(wire)
+ router.update_settings(fallback_on_unsupported_params=False)
+ with pytest.raises(litellm.BadRequestError, match="Unsupported value: temperature"):
+ _complete(client, router)
+ assert _deployments_hit(wire) == ("primary",)
+
+
[email protected]("client", _CLIENTS)
+def test_upstream_400_still_falls_back_by_default(client: str) -> None:
+ with wire_server(_peer({"primary": _UPSTREAM_400, "backup": _BACKUP_ANSWERS})) as wire:
+ router: Final = _router(wire)
+ assert _complete(client, router) == "answered by the backup"
+ assert _deployments_hit(wire) == ("primary", "backup")
diff --git a/tests/unit/router_utils/test_fallback_event_handlers.py b/tests/unit/router_utils/test_fallback_event_handlers.py
index febb33aab7d..b353967df3a 100644
--- a/tests/unit/router_utils/test_fallback_event_handlers.py
+++ b/tests/unit/router_utils/test_fallback_event_handlers.py
@@ -29,6 +29,7 @@ from litellm.router_utils.fallback_event_handlers import (
fallback_attempt_key,
get_fallback_model_group,
get_pre_routing_selection,
+ is_bad_request_without_fallback,
log_failure_fallback_event,
log_success_fallback_event,
mid_stream_fallback_snapshot_kwargs,
@@ -1378,9 +1379,7 @@ class TestOrderedFallbackLookupGroups:
"smart-router",
"requested-model",
)
- assert fallback_lookup_groups({"metadata": {"model_group": []}}, "requested-model") == (
- "requested-model",
- )
+ assert fallback_lookup_groups({"metadata": {"model_group": []}}, "requested-model") == ("requested-model",)
def test_fallback_hop_resumes_the_original_groups_chain_last(self):
from litellm.router_utils.fallback_event_handlers import fallback_lookup_groups
@@ -1539,7 +1538,11 @@ def test_mid_stream_retry_kwargs_strips_what_the_retry_wrapper_pops_and_keeps_th
@pytest.mark.parametrize(
"kwargs,expected",
[
- pytest.param({"litellm_metadata": {"attempted_retries": 2}, "metadata": {"attempted_retries": 5}}, 2, id="litellm_metadata-wins"),
+ pytest.param(
+ {"litellm_metadata": {"attempted_retries": 2}, "metadata": {"attempted_retries": 5}},
+ 2,
+ id="litellm_metadata-wins",
+ ),
pytest.param({"metadata": {"attempted_retries": 1}}, 1, id="metadata-bucket"),
pytest.param({"litellm_metadata": {"attempted_retries": "2"}}, 0, id="string-is-not-a-count"),
pytest.param({"litellm_metadata": {"attempted_retries": -1}}, 0, id="negative-is-not-a-count"),
@@ -1566,8 +1569,12 @@ def test_record_retry_attempt_stamps_the_bucket_the_retry_wrapper_reads():
"kwargs,expected",
[
pytest.param({"litellm_metadata": {"attempted_retries": 1, "max_retries": 3}}, 3, id="committed-by-a-retry"),
- pytest.param({"litellm_metadata": {"attempted_retries": 0, "max_retries": 3}}, None, id="stamped-before-any-retry"),
- pytest.param({"litellm_metadata": {"attempted_retries": 1, "max_retries": "3"}}, None, id="string-is-not-a-budget"),
+ pytest.param(
+ {"litellm_metadata": {"attempted_retries": 0, "max_retries": 3}}, None, id="stamped-before-any-retry"
+ ),
+ pytest.param(
+ {"litellm_metadata": {"attempted_retries": 1, "max_retries": "3"}}, None, id="string-is-not-a-budget"
+ ),
pytest.param({"litellm_metadata": {"attempted_retries": 1}}, None, id="no-budget"),
pytest.param({}, None, id="no-bucket"),
],
@@ -1602,6 +1609,7 @@ def _vcr_outcome_gate(request, vcr):
yield
record_vcr_outcome(request, vcr)
+
@pytest.fixture(scope="function")
def setup_and_teardown():
"""
@@ -1622,6 +1630,7 @@ def setup_and_teardown():
loop.close()
asyncio.set_event_loop(None)
+
REFUSAL_RESPONSE: dict[str, Any] = {
"id": "msg_refusal",
"type": "message",
@@ -1647,9 +1656,11 @@ OK_RESPONSE: dict[str, Any] = {
"usage": {"input_tokens": 25, "output_tokens": 2},
}
+
def _sse(event: str, data: dict[str, Any]) -> bytes:
return f"event: {event}\ndata: {json.dumps(data)}\n\n".encode()
+
REFUSAL_STREAM_FRAMES: tuple[bytes, ...] = (
_sse("message_start", {"type": "message_start", "message": {**REFUSAL_RESPONSE, "stop_reason": None}}),
_sse(
@@ -1672,10 +1683,12 @@ OK_STREAM_FRAMES: tuple[bytes, ...] = (
_sse("message_stop", {"type": "message_stop"}),
)
+
def _split_frames_mid_data_line(frames: tuple[bytes, ...]) -> tuple[bytes, ...]:
"""Split each frame's data line in half, modeling a transport chunk boundary."""
return tuple(part for frame in frames for part in (frame[: len(frame) // 2], frame[len(frame) // 2 :]))
+
class _FrameStream(httpx.AsyncByteStream):
def __init__(self, frames: tuple[bytes, ...]) -> None:
self._frames = frames
@@ -1687,6 +1700,7 @@ class _FrameStream(httpx.AsyncByteStream):
async def aclose(self) -> None:
return None
+
class FakeAnthropicUpstream:
"""Intercepts the third-party transport (httpx.AsyncClient.send): refuses on fable
models, answers on others. The router deliberately does not forward caller-injected
@@ -1724,6 +1738,7 @@ class FakeAnthropicUpstream:
return patch("httpx.AsyncClient.send", new=_send)
+
FABLE_TIER = {
"model_name": "fable-tier",
"litellm_params": {"model": "anthropic/claude-fable-5", "api_key": "sk-test"},
@@ -1734,12 +1749,15 @@ OPUS_TARGET = {
"litellm_params": {"model": "anthropic/claude-opus-5", "api_key": "sk-test"},
}
+
def _router(content_policy_fallbacks: list | None) -> Router:
return Router(model_list=[FABLE_TIER, OPUS_TARGET], content_policy_fallbacks=content_policy_fallbacks)
+
async def _collect(stream: AsyncIterator[bytes]) -> bytes:
return b"".join([chunk async for chunk in stream])
+
@pytest.mark.usefixtures("_vcr_outcome_gate", "setup_and_teardown")
@pytest.mark.asyncio
async def test_non_streaming_refusal_with_fallback_row_returns_fallback_response():
@@ -1756,6 +1774,7 @@ async def test_non_streaming_refusal_with_fallback_row_returns_fallback_response
assert len(fake.calls) == 2
assert "claude-opus-5" in fake.calls[1]
+
@pytest.mark.usefixtures("_vcr_outcome_gate", "setup_and_teardown")
@pytest.mark.asyncio
@pytest.mark.parametrize(
@@ -1780,6 +1799,7 @@ async def test_non_streaming_refusal_passes_through_untouched(content_policy_fal
assert response.get("stop_details") == upstream_body.get("stop_details")
assert len(fake.calls) == 1
+
@pytest.mark.usefixtures("_vcr_outcome_gate", "setup_and_teardown")
@pytest.mark.asyncio
async def test_streaming_refusal_with_fallback_row_streams_fallback_frames():
@@ -1796,6 +1816,7 @@ async def test_streaming_refusal_with_fallback_row_streams_fallback_frames():
assert b"text_delta" in body
assert len(fake.calls) == 2
+
@pytest.mark.usefixtures("_vcr_outcome_gate", "setup_and_teardown")
@pytest.mark.asyncio
async def test_streaming_refusal_split_across_chunks_still_falls_back():
@@ -1812,6 +1833,7 @@ async def test_streaming_refusal_split_across_chunks_still_falls_back():
assert b"text_delta" in body
assert len(fake.calls) == 2
+
@pytest.mark.usefixtures("_vcr_outcome_gate", "setup_and_teardown")
@pytest.mark.asyncio
async def test_streaming_refusal_without_fallback_row_passes_frames_through():
@@ -1828,6 +1850,7 @@ async def test_streaming_refusal_without_fallback_row_passes_frames_through():
assert b"stop_details" in body
assert len(fake.calls) == 1
+
@pytest.mark.usefixtures("_vcr_outcome_gate", "setup_and_teardown")
@pytest.mark.asyncio
async def test_streaming_refusal_on_routed_tier_matches_tier_keyed_row_without_inbound_metadata():
@@ -1861,6 +1884,7 @@ async def test_streaming_refusal_on_routed_tier_matches_tier_keyed_row_without_i
assert b"text_delta" in body
assert len(fake.calls) == 2
+
@pytest.mark.usefixtures("_vcr_outcome_gate", "setup_and_teardown")
@pytest.mark.asyncio
async def test_caller_forged_tier_stamp_cannot_pick_the_streaming_fallback_chain():
@@ -1880,6 +1904,7 @@ async def test_caller_forged_tier_stamp_cannot_pick_the_streaming_fallback_chain
assert b'"stop_reason": "refusal"' in body
assert len(fake.calls) == 1
+
@pytest.mark.usefixtures("_vcr_outcome_gate", "setup_and_teardown")
@pytest.mark.asyncio
async def test_tier_stamp_never_reaches_provider_bound_metadata():
@@ -1916,6 +1941,7 @@ async def test_tier_stamp_never_reaches_provider_bound_metadata():
for body in fake.bodies:
assert body.get("metadata") == {"user_id": "u1"}
+
@pytest.mark.usefixtures("_vcr_outcome_gate", "setup_and_teardown")
def test_record_pre_routing_selection_writes_only_the_internal_bucket():
"""The Anthropic request's own metadata field must never carry the tier stamp."""
@@ -1926,6 +1952,7 @@ def test_record_pre_routing_selection_writes_only_the_internal_bucket():
assert kwargs["litellm_metadata"] == {PRE_ROUTING_SELECTED_MODEL_KEY: "tier-x"}
assert kwargs["metadata"] == {"user_id": "u1"}
+
@pytest.mark.usefixtures("_vcr_outcome_gate", "setup_and_teardown")
@pytest.mark.asyncio
@pytest.mark.parametrize("stream", [False, True], ids=["non-streaming", "streaming"])
@@ -1949,6 +1976,7 @@ async def test_generic_only_row_recovers_safeguard_refusal(stream):
assert len(fake.calls) == 2
assert "claude-opus-5" in fake.calls[1]
+
@pytest.mark.usefixtures("_vcr_outcome_gate", "setup_and_teardown")
@pytest.mark.asyncio
async def test_configured_content_policy_list_stays_authoritative_over_generic_rows():
@@ -1967,6 +1995,7 @@ async def test_configured_content_policy_list_stays_authoritative_over_generic_r
assert response["stop_reason"] == "refusal"
assert len(fake.calls) == 1
+
@pytest.mark.usefixtures("_vcr_outcome_gate", "setup_and_teardown")
def test_refusal_fallback_available_arms_on_generic_rows_only_without_content_policy():
router = Router(model_list=[FABLE_TIER, OPUS_TARGET], fallbacks=[{"tier-group": ["opus-target"]}])
@@ -1976,6 +2005,7 @@ def test_refusal_fallback_available_arms_on_generic_rows_only_without_content_po
assert router._refusal_fallback_available("router-group", {}) is False
assert router._refusal_fallback_available("router-group", {"content_policy_fallbacks": [{"other": ["x"]}]}) is False
+
@pytest.mark.usefixtures("_vcr_outcome_gate", "setup_and_teardown")
def test_chat_content_filter_gate_unchanged_by_generic_rows():
"""The generic-row arming is scoped to /v1/messages safeguard refusals; the chat surface's
@@ -1987,6 +2017,7 @@ def test_chat_content_filter_gate_unchanged_by_generic_rows():
assert router._should_raise_content_policy_error(model="fable-tier", response=response, kwargs={}) is False
+
@pytest.mark.usefixtures("_vcr_outcome_gate", "setup_and_teardown")
@pytest.mark.asyncio
@pytest.mark.parametrize("stream", [False, True], ids=["non-streaming", "streaming"])
@@ -2012,6 +2043,7 @@ async def test_disable_fallbacks_returns_the_refusal_instead_of_raising(stream):
assert body["stop_reason"] == "refusal"
assert len(fake.calls) == 1
+
@pytest.mark.usefixtures("_vcr_outcome_gate", "setup_and_teardown")
@pytest.mark.asyncio
async def test_disable_fallbacks_beats_a_content_policy_row_too():
@@ -2032,6 +2064,7 @@ async def test_disable_fallbacks_beats_a_content_policy_row_too():
assert response["stop_reason"] == "refusal"
assert len(fake.calls) == 1
+
@pytest.mark.usefixtures("_vcr_outcome_gate", "setup_and_teardown")
def test_refusal_gate_keys_on_pre_routing_tier_stamp():
router = _router(content_policy_fallbacks=[{"tier-group": ["opus-target"]}])
@@ -2059,6 +2092,7 @@ def test_refusal_gate_keys_on_pre_routing_tier_stamp():
is False
)
+
@pytest.mark.usefixtures("_vcr_outcome_gate", "setup_and_teardown")
def test_has_content_policy_fallback_default_fallbacks_arm():
router = Router(model_list=[OPUS_TARGET], fallbacks=[{"*": ["opus-target"]}])
@@ -2066,6 +2100,7 @@ def test_has_content_policy_fallback_default_fallbacks_arm():
assert router._has_content_policy_fallback("any-group", {}) is True
assert router._has_content_policy_fallback("any-group", {"content_policy_fallbacks": [{"other": ["x"]}]}) is False
+
@pytest.mark.usefixtures("_vcr_outcome_gate", "setup_and_teardown")
def test_get_fallback_model_group_for_lookup_groups_orders_tier_before_requested():
router = _router(content_policy_fallbacks=None)
@@ -2079,6 +2114,7 @@ def test_get_fallback_model_group_for_lookup_groups_orders_tier_before_requested
) == ["backup-b"]
assert router._get_fallback_model_group_for_lookup_groups(fallbacks=fallbacks, lookup_groups=()) is None
+
@pytest.mark.usefixtures("_vcr_outcome_gate", "setup_and_teardown")
def test_refusal_gate_ignores_other_generic_call_types():
router = _router(content_policy_fallbacks=[{"fable-tier": ["opus-target"]}])
@@ -2269,9 +2305,7 @@ async def test_failed_fallbacks_raise_most_recent_exception(function_name):
model="gpt-3.5-turbo",
)
- request_kwargs: Dict[str, Any] = {
- "metadata": {"previous_models": ["gpt-3.5-turbo"]}
- }
+ request_kwargs: Dict[str, Any] = {"metadata": {"previous_models": ["gpt-3.5-turbo"]}}
if function_name == "_aembedding":
request_kwargs["input"] = "hello this is a test for run_async_fallback"
@@ -2323,27 +2357,19 @@ class CustomTestLogger(CustomLogger):
self.success_fallback_events = []
self.failure_fallback_events = []
- async def log_success_fallback_event(
- self, original_model_group, kwargs, original_exception
- ):
+ async def log_success_fallback_event(self, original_model_group, kwargs, original_exception):
print(
"in log_success_fallback_event for original_model_group: ",
original_model_group,
)
- self.success_fallback_events.append(
- (original_model_group, kwargs, original_exception)
- )
+ self.success_fallback_events.append((original_model_group, kwargs, original_exception))
- async def log_failure_fallback_event(
- self, original_model_group, kwargs, original_exception
- ):
+ async def log_failure_fallback_event(self, original_model_group, kwargs, original_exception):
print(
"in log_failure_fallback_event for original_model_group: ",
original_model_group,
)
- self.failure_fallback_events.append(
- (original_model_group, kwargs, original_exception)
- )
+ self.failure_fallback_events.append((original_model_group, kwargs, original_exception))
def create_test_router_2():
@@ -2458,3 +2484,73 @@ async def test_multiple_fallbacks(function_name, respx_mock: respx.MockRouter, m
print(result._hidden_params)
assert result._hidden_params["api_base"] == FAKE_OPENAI_API_BASE
+
+
+def _provider_error(status_code: int) -> httpx.Response:
+ return httpx.Response(status_code=status_code, request=httpx.Request(method="POST", url="https://provider.test"))
+
+
+ ("exception", "stops_fallbacks"),
+ [
+ pytest.param(
+ litellm.BadRequestError(message="Unsupported value: temperature", model="m", llm_provider="openai"),
+ True,
+ id="provider 400",
+ ),
+ pytest.param(
+ litellm.UnsupportedParamsError(
+ message="reasoning_effort is not supported", model="m", llm_provider="openai"
+ ),
+ True,
+ id="client-side rejection",
+ ),
+ pytest.param(
+ litellm.UnsupportedParamsError(message="stop is not supported"),
+ True,
+ id="client-side rejection without a provider",
+ ),
+ pytest.param(
+ litellm.BadRequestError(
+ message="Deployment ptu is reserved for another team", model="ptu", llm_provider=""
+ ),
+ False,
+ id="router-raised 400 keeps falling back",
+ ),
+ pytest.param(
+ litellm.BadRequestError(
+ message="VertexAIException BadRequestError - 403",
+ model="m",
+ llm_provider="vertex_ai",
+ response=_provider_error(403),
+ ),
+ False,
+ id="vertex 403 wrapped as BadRequestError",
+ ),
+ pytest.param(
+ litellm.PaymentRequiredError(message="insufficient credits", model="m", llm_provider="openrouter"),
+ False,
+ id="402",
+ ),
+ pytest.param(
+ litellm.ContextWindowExceededError(message="maximum context length", model="m", llm_provider="openai"),
+ False,
+ id="context window keeps its own fallbacks",
+ ),
+ pytest.param(
+ litellm.ContentPolicyViolationError(message="content_policy_violation", model="m", llm_provider="openai"),
+ False,
+ id="content policy keeps its own fallbacks",
+ ),
+ pytest.param(
+ litellm.InternalServerError(message="overloaded", model="m", llm_provider="openai"),
+ False,
+ id="500 still falls back",
+ ),
+ ],
+)
+def test_is_bad_request_without_fallback_only_stops_on_a_real_400_when_the_flag_is_off(
+ exception: Exception, stops_fallbacks: bool
+) -> None:
+ assert is_bad_request_without_fallback(exception, fallback_on_unsupported_params=False) is stops_fallbacks
+ assert is_bad_request_without_fallback(exception, fallback_on_unsupported_params=True) is False
diff --git a/tests/unit/test_router_retry_policy_update.py b/tests/unit/test_router_retry_policy_update.py
index 48b5194a66e..918d215c89f 100644
--- a/tests/unit/test_router_retry_policy_update.py
+++ b/tests/unit/test_router_retry_policy_update.py
@@ -300,6 +300,21 @@ def test_update_settings_persists_retry_policy_dict():
assert router.retry_policy.TimeoutErrorRetries == 3
+def test_update_settings_fallback_on_unsupported_params_round_trips_through_get_settings():
+ router = _build_router()
+ assert router.get_settings()["fallback_on_unsupported_params"] is True
+
+ router.update_settings(fallback_on_unsupported_params=False)
+
+ assert router.fallback_on_unsupported_params is False
+ assert router.get_settings()["fallback_on_unsupported_params"] is False
+
+
+def test_update_router_config_keeps_fallback_on_unsupported_params_payload():
+ payload = UpdateRouterConfig(fallback_on_unsupported_params=False).model_dump(exclude_none=True)
+ assert payload["fallback_on_unsupported_params"] is False
+
+
def test_update_settings_accepts_retry_policy_object_unchanged():
"""A pre-built ``RetryPolicy`` instance must pass through verbatim so
callers that already constructed one (e.g. tests or programmatic
diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.ts
index 29d659ec1d9..1fd554e37a1 100644
--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts
+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts
@@ -48111,6 +48111,8 @@ export interface components {
cooldown_time?: number | null;
/** Enable Tag Filtering */
enable_tag_filtering?: boolean | null;
+ /** Fallback On Unsupported Params */
+ fallback_on_unsupported_params?: boolean | null;
/** Fallbacks */
fallbacks?: {
[key: string]: unknown;