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(proxy)!: drop router_settings_override before routing and apply it on every branch (#47257)

Avani Prajapatie0d903b971fe
diff --git a/litellm/proxy/route_llm_request.py b/litellm/proxy/route_llm_request.py
index 8bab7215b17..e16e14c8d54 100644
--- a/litellm/proxy/route_llm_request.py
+++ b/litellm/proxy/route_llm_request.py
@@ -2,13 +2,14 @@ import asyncio
from collections.abc import Mapping
from dataclasses import dataclass
from types import MappingProxyType
-from typing import TYPE_CHECKING, Any, Final, Literal
+from typing import TYPE_CHECKING, Annotated, Any, Final, Literal
import httpx
from fastapi import HTTPException, status
-from pydantic import TypeAdapter, ValidationError
+from pydantic import BeforeValidator, TypeAdapter, ValidationError
import litellm
+from litellm.litellm_core_utils.core_helpers import normalize_drop_params
from litellm.proxy._types import ProxyException, UserAPIKeyAuth
from litellm.router_utils.common_utils import is_proxy_admin_request
@@ -38,6 +39,21 @@ else:
LitellmRouter = Any
+_PER_REQUEST_ROUTER_SETTINGS: Final = (
+ "fallbacks",
+ "context_window_fallbacks",
+ "content_policy_fallbacks",
+ "num_retries",
+ "timeout",
+ "model_group_retry_policy",
+ "routing_strategy",
+ "enable_tag_filtering",
+)
+_ROUTER_ONLY_SETTINGS: Final = frozenset(
+ ("fallbacks", "context_window_fallbacks", "content_policy_fallbacks", "model_group_retry_policy")
+)
+
+
def _route_user_config_request(data: dict, route_type: str):
"""Route a request using the user-provided router config."""
router_config: Final = data.pop("user_config")
@@ -204,6 +220,18 @@ REQUIRED_ONE_OF_BODY_PARAMS_BY_ROUTE: Final[Mapping[str, tuple[str, str]]] = Map
)
JSON_OBJECT_ADAPTER: Final[TypeAdapter[dict[str, object]]] = TypeAdapter(dict[str, object])
+_OPTIONAL_JSON_OBJECT_ADAPTER: Final[TypeAdapter[Mapping[str, object] | None]] = TypeAdapter(
+ Mapping[str, object] | None
+)
+
+
+def _none_unless_json_object(value: object) -> object:
+ return value if isinstance(value, Mapping) else None
+
+
+_JSON_OBJECT_OR_DROPPED_ADAPTER: Final[TypeAdapter[Mapping[str, object] | None]] = TypeAdapter(
+ Annotated[Mapping[str, object] | None, BeforeValidator(_none_unless_json_object)]
+)
class ProxyMissingRequiredParamError(ProxyException):
@@ -596,6 +624,43 @@ RouteType = Literal[
]
+def _merge_router_settings_override(
+ data: dict[str, object], # mutable-ok: route_request mutates the shared request body in place
+) -> frozenset[str]:
+ data.pop("enable_tag_filtering", None)
+ drop_params: Final = litellm.drop_params is True or normalize_drop_params(data.get("drop_params")) is True
+ router_settings_override_adapter: Final = (
+ _JSON_OBJECT_OR_DROPPED_ADAPTER if drop_params else _OPTIONAL_JSON_OBJECT_ADAPTER
+ )
+ try:
+ router_settings_override: Final = router_settings_override_adapter.validate_python(
+ data.pop("router_settings_override", None)
+ )
+ except ValidationError:
+ raise ProxyException(
+ message="router_settings_override must be a JSON object.",
+ type="invalid_request_error",
+ param="router_settings_override",
+ code=status.HTTP_400_BAD_REQUEST,
+ ) from None
+ if "user_config" in data and data["user_config"] is None:
+ data.pop("user_config")
+ user_config: Final = _JSON_OBJECT_OR_DROPPED_ADAPTER.validate_python(data.get("user_config"))
+ router_settings_from_override: Final = MappingProxyType(
+ {
+ key: router_settings_override[key]
+ for key in _PER_REQUEST_ROUTER_SETTINGS
+ if router_settings_override.get(key) is not None
+ and key not in data
+ and (user_config is None or key not in user_config)
+ }
+ if router_settings_override is not None
+ else {}
+ )
+ data.update(router_settings_from_override)
+ return _ROUTER_ONLY_SETTINGS.intersection(router_settings_from_override)
+
+
async def route_request(
data: dict,
llm_router: LitellmRouter | None,
@@ -606,12 +671,14 @@ async def route_request(
"""
Common helper to route the request
"""
+ router_only_settings_from_override: Final = _merge_router_settings_override(data) # pyright: ignore[reportUnknownArgumentType] # route_request takes an untyped dict body
try:
return await _route_request_single_attempt(
data=data,
llm_router=llm_router,
user_model=user_model,
route_type=route_type,
+ router_only_settings_from_override=router_only_settings_from_override,
user_api_key_dict=user_api_key_dict,
)
except (ProxyModelNotFoundError, ProxyMissingParamWithoutLoadedModelError) as e:
@@ -634,6 +701,7 @@ async def route_request(
llm_router=proxy_server.llm_router,
user_model=user_model,
route_type=route_type,
+ router_only_settings_from_override=router_only_settings_from_override,
user_api_key_dict=user_api_key_dict,
)
@@ -643,6 +711,7 @@ async def _route_request_single_attempt( # noqa: ANN202 # returns unawaited pr
llm_router: LitellmRouter | None,
user_model: str | None,
route_type: RouteType,
+ router_only_settings_from_override: frozenset[str],
user_api_key_dict: UserAPIKeyAuth | None = None,
):
raise_if_required_body_param_missing(route_type=route_type, data=data, llm_router=llm_router)
@@ -651,9 +720,14 @@ async def _route_request_single_attempt( # noqa: ANN202 # returns unawaited pr
raise_if_mock_testing_params_disallowed(data, allowed=mock_testing_params_allowed())
- data.pop("enable_tag_filtering", None)
- if "user_config" in data and data["user_config"] is None:
- data.pop("user_config") # pyright: ignore[reportUnknownMemberType] # route_request takes an untyped dict body
+ def direct_litellm_kwargs() -> Mapping[str, object]:
+ return MappingProxyType(
+ {
+ key: value
+ for key, value in JSON_OBJECT_ADAPTER.validate_python(data).items()
+ if key not in router_only_settings_from_override
+ }
+ )
team_id: Final = get_team_id_from_data(data)
router_model_names: Final = llm_router.model_names if llm_router is not None else []
@@ -668,7 +742,7 @@ async def _route_request_single_attempt( # noqa: ANN202 # returns unawaited pr
if llm_router is not None:
return getattr(llm_router, f"{route_type}")(**data)
else:
- return getattr(litellm, f"{route_type}")(**data)
+ return getattr(litellm, f"{route_type}")(**direct_litellm_kwargs())
elif (
route_type == "acompletion"
@@ -687,34 +761,6 @@ async def _route_request_single_attempt( # noqa: ANN202 # returns unawaited pr
elif "user_config" in data:
return _route_user_config_request(data, route_type)
- elif "router_settings_override" in data:
- # Apply per-request router settings overrides from key/team config
- # Instead of creating a new Router (expensive), merge settings into kwargs
- # The Router already supports per-request overrides for these settings
- override_settings: Final = data.pop("router_settings_override")
-
- # Settings that the Router accepts as per-request kwargs
- # These override the global router settings for this specific request
- per_request_settings: Final = [
- "fallbacks",
- "context_window_fallbacks",
- "content_policy_fallbacks",
- "num_retries",
- "timeout",
- "model_group_retry_policy",
- "routing_strategy",
- "enable_tag_filtering",
- ]
-
- for key in per_request_settings:
- if override_settings.get(key) is not None and key not in data:
- data[key] = override_settings[key]
-
- # Use main router with overridden kwargs
- if llm_router is not None:
- return getattr(llm_router, f"{route_type}")(**data)
- else:
- return getattr(litellm, f"{route_type}")(**data)
elif llm_router is not None:
_raise_if_model_fully_blocked(llm_router=llm_router, model_name=data.get("model"), team_id=team_id)
# Evals API: always route to litellm directly (not through router)
@@ -755,7 +801,7 @@ async def _route_request_single_attempt( # noqa: ANN202 # returns unawaited pr
# If we can't get deployment creds, continue without them
pass
- return getattr(litellm, f"{route_type}")(**data)
+ return getattr(litellm, f"{route_type}")(**direct_litellm_kwargs())
# Skip model-based routing for container operations
if route_type in [
"acreate_container",
@@ -806,7 +852,7 @@ async def _route_request_single_attempt( # noqa: ANN202 # returns unawaited pr
"aingest",
] and (data.get("model") is None or data.get("model") == ""):
# These endpoints don't need a model, use custom_llm_provider directly
- return getattr(litellm, f"{route_type}")(**data)
+ return getattr(litellm, f"{route_type}")(**direct_litellm_kwargs())
if "model" not in data:
raise ProxyMissingRequiredParamError(
@@ -845,7 +891,7 @@ async def _route_request_single_attempt( # noqa: ANN202 # returns unawaited pr
# Check wildcards before checking deployment_names
# Priority: 1. Exact model_name match, 2. Wildcard match, 3. deployment_names match
if llm_router.router_general_settings.pass_through_all_models:
- return getattr(litellm, f"{route_type}")(**data)
+ return getattr(litellm, f"{route_type}")(**direct_litellm_kwargs())
elif llm_router.default_deployment is not None or len(llm_router.pattern_router.patterns) > 0:
return getattr(llm_router, f"{route_type}")(**data)
elif data["model"] in llm_router.deployment_names:
@@ -897,7 +943,7 @@ async def _route_request_single_attempt( # noqa: ANN202 # returns unawaited pr
return getattr(llm_router, f"{route_type}")(**data)
except Exception:
# If router fails (e.g., model not found in router), fall back to direct call
- return getattr(litellm, f"{route_type}")(**data)
+ return getattr(litellm, f"{route_type}")(**direct_litellm_kwargs())
elif _is_a2a_agent_model(data.get("model", "")):
from litellm.proxy.agent_endpoints.a2a_routing import (
route_a2a_agent_request,
@@ -909,7 +955,7 @@ async def _route_request_single_attempt( # noqa: ANN202 # returns unawaited pr
# Fall through to raise exception below if result is None
elif user_model is not None or route_type == "allm_passthrough_route":
- return getattr(litellm, f"{route_type}")(**data)
+ return getattr(litellm, f"{route_type}")(**direct_litellm_kwargs())
# if no route found then it's a bad request
route_name: Final = ROUTE_ENDPOINT_MAPPING.get(route_type, route_type)
diff --git a/tests/unit/proxy/test_route_llm_request.py b/tests/unit/proxy/test_route_llm_request.py
index 4e4e2f23950..8928b79bcd4 100644
--- a/tests/unit/proxy/test_route_llm_request.py
+++ b/tests/unit/proxy/test_route_llm_request.py
@@ -1,4 +1,6 @@
+import contextlib
import httpx
+import json
import litellm
import pytest
import respx
@@ -10,7 +12,8 @@ from unittest.mock import MagicMock
from fastapi import HTTPException
-from litellm.proxy.route_llm_request import ProxyModelNotFoundError, route_request
+from litellm.proxy.route_llm_request import JSON_OBJECT_ADAPTER, ProxyModelNotFoundError, route_request
+from litellm.types.router import RouterGeneralSettings
@pytest.mark.parametrize(
@@ -390,7 +393,6 @@ async def test_route_request_with_router_settings_override():
"timeout": 30,
"model_group_retry_policy": {"gpt-3.5-turbo": {"RateLimitErrorRetries": 3}},
"routing_strategy": "least-busy",
- # This setting should be ignored (not in per_request_settings list)
"model_group_alias": {"alias": "real_model"},
},
}
@@ -437,12 +439,12 @@ async def test_route_request_with_router_settings_override_no_router():
litellm.acompletion = mock_completion
try:
- response = await route_request(data, None, None, "acompletion")
+ response = await route_request(data, None, "gpt-3.5-turbo", "acompletion")
assert response == "success"
# Verify litellm.acompletion was called with merged settings
call_kwargs = mock_completion.call_args[1]
- assert call_kwargs["fallbacks"] == [{"gpt-3.5-turbo": ["gpt-4"]}]
+ assert "fallbacks" not in call_kwargs
assert call_kwargs["num_retries"] == 3
finally:
litellm.acompletion = original_acompletion
@@ -1039,6 +1041,408 @@ async def test_route_request_override_enable_tag_filtering_beats_body_value():
assert call_kwargs["enable_tag_filtering"] is True
+_PROXY_DEPLOYMENT_BASE: Final = "https://proxy-deployment.example/v1"
+_HELLO_MESSAGES: Final = ({"role": "user", "content": "Hello"},)
+
+
+def _chat_completion_response(model: str) -> httpx.Response:
+ return httpx.Response(
+ 200,
+ json={
+ "id": "chatcmpl-1",
+ "object": "chat.completion",
+ "created": 1,
+ "model": model,
+ "choices": [{"index": 0, "message": {"role": "assistant", "content": "hi"}, "finish_reason": "stop"}],
+ "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
+ },
+ )
+
+
+def _proxy_router_with_two_model_groups() -> litellm.Router:
+ return litellm.Router(
+ model_list=[
+ {
+ "model_name": model,
+ "litellm_params": {
+ "model": f"openai/{model}",
+ "api_key": "sk-proxy",
+ "api_base": _PROXY_DEPLOYMENT_BASE,
+ },
+ }
+ for model in ("gpt-3.5-turbo", "gpt-4")
+ ],
+ num_retries=0,
+ )
+
+
+ "extra_body, upstream_base",
+ [
+ pytest.param({"api_key": "sk-from-pre-call-hook"}, _PROXY_DEPLOYMENT_BASE, id="clientside-api-key"),
+ pytest.param(
+ {"api_base": "https://clientside.example/v1"}, "https://clientside.example/v1", id="clientside-api-base"
+ ),
+ pytest.param({"model": "gpt-3.5-turbo,gpt-4"}, _PROXY_DEPLOYMENT_BASE, id="comma-separated-batch"),
+ pytest.param({"drop_params": True}, _PROXY_DEPLOYMENT_BASE, id="drop-params"),
+ pytest.param(
+ {
+ "user_config": {
+ "model_list": [
+ {
+ "model_name": "gpt-3.5-turbo",
+ "litellm_params": {
+ "model": "openai/gpt-3.5-turbo",
+ "api_key": "sk-user-config",
+ "api_base": "https://user-config.example/v1",
+ },
+ }
+ ],
+ }
+ },
+ "https://user-config.example/v1",
+ id="user-config",
+ ),
+ ],
+)
+async def test_route_request_never_forwards_router_settings_override(
+ monkeypatch: pytest.MonkeyPatch, extra_body: dict[str, object], upstream_base: str
+) -> None:
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+ data: Final = {
+ "model": "gpt-3.5-turbo",
+ "messages": list(_HELLO_MESSAGES),
+ "router_settings_override": {"num_retries": 2, "timeout": None},
+ **extra_body,
+ }
+
+ with respx.mock(assert_all_called=False) as respx_mock:
+ primary: Final = respx_mock.post(f"{upstream_base}/chat/completions", json__model="gpt-3.5-turbo").mock(
+ side_effect=[
+ httpx.Response(500, json={"error": {"message": "boom"}}),
+ _chat_completion_response("gpt-3.5-turbo"),
+ ]
+ )
+ respx_mock.post(f"{upstream_base}/chat/completions", json__model="gpt-4").mock(
+ return_value=_chat_completion_response("gpt-4")
+ )
+ response: Final = await (await route_request(data, _proxy_router_with_two_model_groups(), None, "acompletion"))
+
+ primary_response: Final = response[0] if isinstance(response, list) else response
+ sent_bodies: Final = [json.loads(call.request.content) for call in primary.calls]
+ assert not [body for body in sent_bodies if "router_settings_override" in body], sent_bodies
+ assert primary_response._hidden_params["additional_headers"]["x-litellm-max-retries"] == 2, (
+ primary_response._hidden_params
+ )
+
+
[email protected]("extra_body", [{}, {"api_key": "sk-from-pre-call-hook"}], ids=["router", "clientside-api-key"])
+async def test_route_request_treats_null_router_settings_override_as_absent(
+ monkeypatch: pytest.MonkeyPatch, extra_body: dict[str, str]
+) -> None:
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+ data: Final = {
+ "model": "gpt-3.5-turbo",
+ "messages": list(_HELLO_MESSAGES),
+ "router_settings_override": None,
+ **extra_body,
+ }
+
+ with respx.mock(assert_all_called=False) as respx_mock:
+ upstream: Final = respx_mock.post(f"{_PROXY_DEPLOYMENT_BASE}/chat/completions").mock(
+ return_value=_chat_completion_response("gpt-3.5-turbo")
+ )
+ response: Final = await (await route_request(data, _proxy_router_with_two_model_groups(), None, "acompletion"))
+
+ assert response.choices[0].message.content == "hi", response
+ assert "router_settings_override" not in json.loads(upstream.calls.last.request.content)
+
+
+ "global_drop_params, extra_body",
+ [
+ pytest.param(False, {}, id="drop-params-off"),
+ pytest.param(False, {"drop_params": False}, id="request-drop-params-false"),
+ ],
+)
[email protected]("override", ["fallbacks", ["num_retries"], 3])
+async def test_route_request_rejects_non_object_router_settings_override(
+ monkeypatch: pytest.MonkeyPatch, global_drop_params: bool, extra_body: dict[str, bool | str], override: object
+) -> None:
+ from litellm.proxy._types import ProxyException
+
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+ monkeypatch.setattr(litellm, "drop_params", global_drop_params)
+ data: Final = {
+ "model": "gpt-3.5-turbo",
+ "messages": list(_HELLO_MESSAGES),
+ "router_settings_override": override,
+ **extra_body,
+ }
+
+ with respx.mock(assert_all_called=False) as respx_mock:
+ upstream: Final = respx_mock.post(f"{_PROXY_DEPLOYMENT_BASE}/chat/completions").mock(
+ return_value=_chat_completion_response("gpt-3.5-turbo")
+ )
+ with pytest.raises(ProxyException) as exc_info:
+ await route_request(data, _proxy_router_with_two_model_groups(), None, "acompletion")
+
+ assert exc_info.value.code == "400"
+ assert exc_info.value.param == "router_settings_override"
+ assert upstream.call_count == 0
+
+
+ "global_drop_params, extra_body",
+ [
+ pytest.param(False, {"drop_params": True}, id="request-drop-params"),
+ pytest.param(True, {}, id="global-drop-params"),
+ pytest.param(True, {"drop_params": False}, id="global-drop-params-with-request-false"),
+ pytest.param(False, {"drop_params": "true"}, id="request-drop-params-string"),
+ ],
+)
[email protected]("override", ["fallbacks", ["num_retries"], 3])
+async def test_route_request_drops_non_object_router_settings_override_under_drop_params(
+ monkeypatch: pytest.MonkeyPatch, global_drop_params: bool, extra_body: dict[str, bool | str], override: object
+) -> None:
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+ monkeypatch.setattr(litellm, "drop_params", global_drop_params)
+ data: Final = {
+ "model": "gpt-3.5-turbo",
+ "messages": list(_HELLO_MESSAGES),
+ "router_settings_override": override,
+ **extra_body,
+ }
+
+ with respx.mock(assert_all_called=False) as respx_mock:
+ upstream: Final = respx_mock.post(f"{_PROXY_DEPLOYMENT_BASE}/chat/completions").mock(
+ return_value=_chat_completion_response("gpt-3.5-turbo")
+ )
+ response: Final = await (await route_request(data, _proxy_router_with_two_model_groups(), None, "acompletion"))
+
+ assert response.choices[0].message.content == "hi", response
+ assert upstream.call_count == 1
+ assert "router_settings_override" not in json.loads(upstream.calls.last.request.content)
+
+
+ "user_config_settings, expected_upstream_calls",
+ [
+ pytest.param({}, 2, id="key-setting-fills-unset-user-config-setting"),
+ pytest.param({"num_retries": 0}, 1, id="user-config-setting-beats-key-setting"),
+ ],
+)
+async def test_route_request_user_config_router_settings_beat_key_settings(
+ monkeypatch: pytest.MonkeyPatch, user_config_settings: dict[str, int], expected_upstream_calls: int
+) -> None:
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+ user_config_base: Final = "https://user-config.example/v1"
+ data: Final = {
+ "model": "gpt-3.5-turbo",
+ "messages": list(_HELLO_MESSAGES),
+ "router_settings_override": {"num_retries": 1},
+ "user_config": {
+ **user_config_settings,
+ "model_list": [
+ {
+ "model_name": "gpt-3.5-turbo",
+ "litellm_params": {
+ "model": "openai/gpt-3.5-turbo",
+ "api_key": "sk-user-config",
+ "api_base": user_config_base,
+ },
+ }
+ ],
+ },
+ }
+
+ with respx.mock(assert_all_called=False) as respx_mock:
+ upstream: Final = respx_mock.post(f"{user_config_base}/chat/completions").mock(
+ side_effect=[
+ httpx.Response(500, json={"error": {"message": "boom"}}),
+ _chat_completion_response("gpt-3.5-turbo"),
+ ]
+ )
+ with contextlib.suppress(litellm.InternalServerError):
+ await (await route_request(data, _proxy_router_with_two_model_groups(), None, "acompletion"))
+
+ assert upstream.call_count == expected_upstream_calls
+
+
+ "extra_body",
+ [
+ pytest.param({}, id="no-key-settings"),
+ pytest.param({"router_settings_override": {"num_retries": 2}}, id="key-settings"),
+ ],
+)
+async def test_route_request_refuses_blocked_model_whether_or_not_key_has_router_settings(
+ extra_body: dict[str, dict[str, int]],
+) -> None:
+ router: Final = litellm.Router(
+ model_list=[
+ {
+ "model_name": "gpt-3.5-turbo",
+ "litellm_params": {"model": "openai/gpt-3.5-turbo", "api_key": "sk-proxy"},
+ "model_info": {"blocked": True},
+ }
+ ],
+ )
+ data: Final = {"model": "gpt-3.5-turbo", "messages": list(_HELLO_MESSAGES), **extra_body}
+
+ with pytest.raises(litellm.PermissionDeniedError):
+ await route_request(data, router, None, "acompletion")
+
+
+ "credential",
+ [
+ pytest.param({"api_key": "sk-from-pre-call-hook"}, id="clientside-api-key"),
+ pytest.param({"api_base": _PROXY_DEPLOYMENT_BASE}, id="clientside-api-base"),
+ ],
+)
+ "fallback_field, upstream_error",
+ [
+ pytest.param("fallbacks", httpx.Response(500, json={"error": {"message": "boom"}}), id="fallbacks"),
+ pytest.param(
+ "context_window_fallbacks",
+ httpx.Response(
+ 400,
+ json={
+ "error": {
+ "message": "This model's maximum context length is 16385 tokens",
+ "code": "context_length_exceeded",
+ }
+ },
+ ),
+ id="context-window-fallbacks",
+ ),
+ pytest.param(
+ "content_policy_fallbacks",
+ httpx.Response(
+ 400,
+ json={
+ "error": {
+ "message": "Your request was rejected by the content filter",
+ "type": "invalid_request_error",
+ "code": "content_policy_violation",
+ }
+ },
+ ),
+ id="content-policy-fallbacks",
+ ),
+ ],
+)
+async def test_route_request_applies_override_fallbacks_when_request_carries_credentials(
+ monkeypatch: pytest.MonkeyPatch,
+ credential: dict[str, str],
+ fallback_field: str,
+ upstream_error: httpx.Response,
+) -> None:
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+ data: Final = {
+ "model": "gpt-3.5-turbo",
+ "messages": list(_HELLO_MESSAGES),
+ "router_settings_override": {fallback_field: [{"gpt-3.5-turbo": ["gpt-4"]}]},
+ **credential,
+ }
+
+ with respx.mock(assert_all_called=False) as respx_mock:
+ respx_mock.post(f"{_PROXY_DEPLOYMENT_BASE}/chat/completions", json__model="gpt-3.5-turbo").mock(
+ return_value=upstream_error
+ )
+ fallback: Final = respx_mock.post(f"{_PROXY_DEPLOYMENT_BASE}/chat/completions", json__model="gpt-4").mock(
+ return_value=_chat_completion_response("gpt-4")
+ )
+ response: Final = await (await route_request(data, _proxy_router_with_two_model_groups(), None, "acompletion"))
+
+ assert fallback.call_count == 1, [str(call.request.url) for call in respx_mock.calls]
+ assert "router_settings_override" not in json.loads(fallback.calls.last.request.content)
+ assert response.choices[0].message.content == "hi", response
+
+
+ "router_only_setting",
+ [
+ pytest.param({"model_group_retry_policy": {"gpt-4": {"TimeoutErrorRetries": 1}}}, id="model-group-retry-policy"),
+ pytest.param({"context_window_fallbacks": [{"gpt-4": ["gpt-3.5-turbo"]}]}, id="context-window-fallbacks"),
+ pytest.param({"content_policy_fallbacks": [{"gpt-4": ["gpt-3.5-turbo"]}]}, id="content-policy-fallbacks"),
+ ],
+)
+async def test_route_request_keeps_router_only_override_settings_out_of_pass_through_provider_body(
+ monkeypatch: pytest.MonkeyPatch, router_only_setting: dict[str, object]
+) -> None:
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+ monkeypatch.setenv("OPENAI_API_KEY", "sk-pass-through")
+ monkeypatch.delenv("OPENAI_BASE_URL", raising=False)
+ monkeypatch.delenv("OPENAI_API_BASE", raising=False)
+ router: Final = litellm.Router(
+ model_list=[
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {"model": "openai/gpt-4", "api_key": "sk-proxy", "api_base": _PROXY_DEPLOYMENT_BASE},
+ }
+ ],
+ router_general_settings=RouterGeneralSettings(pass_through_all_models=True),
+ )
+ data: Final = {
+ "model": "openai/gpt-pass-through",
+ "messages": list(_HELLO_MESSAGES),
+ "router_settings_override": router_only_setting,
+ }
+
+ with respx.mock(assert_all_called=True) as respx_mock:
+ upstream: Final = respx_mock.post("https://api.openai.com/v1/chat/completions").mock(
+ return_value=_chat_completion_response("gpt-pass-through")
+ )
+ await (await route_request(data, router, None, "acompletion"))
+
+ assert set(router_only_setting).isdisjoint(JSON_OBJECT_ADAPTER.validate_json(upstream.calls.last.request.content))
+
+
+async def test_route_request_keeps_key_fallbacks_out_of_pass_through_provider_body(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+ monkeypatch.setenv("OPENAI_API_KEY", "sk-pass-through")
+ monkeypatch.delenv("OPENAI_BASE_URL", raising=False)
+ monkeypatch.delenv("OPENAI_API_BASE", raising=False)
+ router: Final = litellm.Router(
+ model_list=[
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {"model": "openai/gpt-4", "api_key": "sk-proxy", "api_base": _PROXY_DEPLOYMENT_BASE},
+ }
+ ],
+ router_general_settings=RouterGeneralSettings(pass_through_all_models=True),
+ )
+ data: Final = {
+ "model": "openai/gpt-pass-through",
+ "messages": list(_HELLO_MESSAGES),
+ "router_settings_override": {"fallbacks": [{"gpt-4": ["gpt-4"]}], "num_retries": 0},
+ }
+
+ with respx.mock(assert_all_called=True) as respx_mock:
+ upstream: Final = respx_mock.post("https://api.openai.com/v1/chat/completions").mock(
+ return_value=httpx.Response(500, json={"error": {"message": "upstream down"}})
+ )
+ with pytest.raises(litellm.InternalServerError):
+ await (await route_request(data, router, None, "acompletion"))
+
+ provider_bodies: Final = tuple(JSON_OBJECT_ADAPTER.validate_json(call.request.content) for call in upstream.calls)
+ assert provider_bodies and all("gpt-4" not in body for body in provider_bodies), provider_bodies
+
+
@pytest.mark.parametrize(
"route_type, param, route",
[
@@ -1524,6 +1928,54 @@ async def test_route_request_read_through_recovers_model_created_on_sibling_repl
assert table.find_many_wheres[0] == {"model_name": model_name}
+def _tagged_db_model_row(model_name: str, tag: str, order: int) -> SimpleNamespace:
+ return SimpleNamespace(
+ model_id=f"{model_name}-{tag}-id",
+ model_name=model_name,
+ litellm_params={
+ "model": "openai/gpt-4o",
+ "api_key": "fake",
+ "mock_response": f"{tag}-deployment",
+ "tags": [tag],
+ "order": order,
+ },
+ model_info={},
+ blocked=False,
+ )
+
+
+async def test_route_request_read_through_retry_keeps_key_tag_filtering(monkeypatch: pytest.MonkeyPatch) -> None:
+ import litellm.proxy.proxy_server as proxy_server
+
+ model_name: Final = "sibling-replica-model-for-key-with-tag-filtering"
+ router: Final = litellm.Router(
+ model_list=[{"model_name": "some-other-model", "litellm_params": {"model": "openai/gpt-4o", "api_key": "fake"}}]
+ )
+ fake_prisma, _ = _fake_prisma_client_with_models(
+ [_tagged_db_model_row(model_name, "free", order=1), _tagged_db_model_row(model_name, "paid", order=2)]
+ )
+ monkeypatch.setattr(proxy_server, "prisma_client", fake_prisma)
+ monkeypatch.setattr(proxy_server, "store_model_in_db", True)
+ monkeypatch.setattr(proxy_server, "llm_router", router)
+
+ response: Final = await (
+ await route_request(
+ {
+ "model": model_name,
+ "messages": [{"role": "user", "content": "hi"}],
+ "metadata": {"tags": ["paid"]},
+ "router_settings_override": {"enable_tag_filtering": True},
+ },
+ router,
+ None,
+ "acompletion",
+ )
+ )
+
+ assert response.choices[0].message.content == "paid-deployment"
+
+
@pytest.mark.asyncio
async def test_route_request_unknown_model_raises_and_hits_db_once_within_ttl(monkeypatch):
import litellm