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]

Auth checks on invalid fallback models (#7871)

Krish Dholakiac306c2e0fc58
diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.py
index e7ccfe6f22e..3461952ed6d 100644
--- a/litellm/proxy/_types.py
+++ b/litellm/proxy/_types.py
@@ -6,9 +6,10 @@ from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Union
import httpx
from pydantic import BaseModel, ConfigDict, Field, Json, model_validator
-from typing_extensions import TypedDict
+from typing_extensions import Required, TypedDict
from litellm.types.integrations.slack_alerting import AlertType
+from litellm.types.llms.openai import AllMessageValues
from litellm.types.router import RouterErrors, UpdateRouterConfig
from litellm.types.utils import (
EmbeddingResponse,
@@ -2281,3 +2282,15 @@ class ProxyStateVariables(TypedDict):
UI_TEAM_ID = "litellm-dashboard"
+
+
+class ClientSideFallbackModel(TypedDict, total=False):
+ """
+ Dictionary passed when client configuring input
+ """
+
+ model: Required[str]
+ messages: List[AllMessageValues]
+
+
+ALL_FALLBACK_MODEL_VALUES = Union[str, ClientSideFallbackModel]
diff --git a/litellm/proxy/auth/auth_checks.py b/litellm/proxy/auth/auth_checks.py
index b18c0e342f3..4e39442a98c 100644
--- a/litellm/proxy/auth/auth_checks.py
+++ b/litellm/proxy/auth/auth_checks.py
@@ -34,6 +34,7 @@ from litellm.proxy._types import (
UserAPIKeyAuth,
)
from litellm.proxy.auth.route_checks import RouteChecks
+from litellm.proxy.route_llm_request import route_request
from litellm.proxy.utils import PrismaClient, ProxyLogging, log_db_metrics
from litellm.router import Router
from litellm.types.services import ServiceTypes
@@ -902,6 +903,7 @@ async def can_key_call_model(
from collections import defaultdict
access_groups: Dict[str, List[str]] = defaultdict(list)
+
if llm_router:
access_groups = llm_router.get_model_access_groups(model_name=model)
if (
@@ -934,3 +936,28 @@ async def can_key_call_model(
f"filtered allowed_models: {filtered_models}; valid_token.models: {valid_token.models}"
)
return True
+
+
+async def is_valid_fallback_model(
+ model: str,
+ llm_router: Optional[Router],
+ user_model: Optional[str],
+) -> Literal[True]:
+ """
+ Try to route the fallback model request.
+
+ Validate if it can't be routed.
+
+ Help catch invalid fallback models.
+ """
+ await route_request(
+ data={
+ "model": model,
+ "messages": [{"role": "user", "content": "Who was Alexander?"}],
+ },
+ llm_router=llm_router,
+ user_model=user_model,
+ route_type="acompletion", # route type shouldn't affect the fallback model check
+ )
+
+ return True
diff --git a/litellm/proxy/auth/user_api_key_auth.py b/litellm/proxy/auth/user_api_key_auth.py
index b3c0b17ab4a..8a14504b245 100644
--- a/litellm/proxy/auth/user_api_key_auth.py
+++ b/litellm/proxy/auth/user_api_key_auth.py
@@ -10,7 +10,7 @@ Returns a UserAPIKeyAuth object if the API key is valid
import asyncio
import secrets
from datetime import datetime, timezone
-from typing import Optional
+from typing import Optional, cast
import fastapi
from fastapi import HTTPException, Request, WebSocket, status
@@ -32,6 +32,7 @@ from litellm.proxy.auth.auth_checks import (
get_org_object,
get_team_object,
get_user_object,
+ is_valid_fallback_model,
)
from litellm.proxy.auth.auth_utils import (
_get_request_ip_address,
@@ -880,10 +881,6 @@ async def _user_api_key_auth_builder( # noqa: PLR0915
verbose_proxy_logger.debug(
f"\n new llm router model list {new_model_list}"
)
- if (
- len(valid_token.models) == 0
- ): # assume an empty model list means all models are allowed to be called
- pass
elif (
isinstance(valid_token.models, list)
and "all-team-models" in valid_token.models
@@ -893,8 +890,9 @@ async def _user_api_key_auth_builder( # noqa: PLR0915
pass
else:
model = request_data.get("model", None)
- fallback_models: Optional[List[str]] = request_data.get(
- "fallbacks", None
+ fallback_models = cast(
+ Optional[List[ALL_FALLBACK_MODEL_VALUES]],
+ request_data.get("fallbacks", None),
)
if model is not None:
@@ -908,11 +906,16 @@ async def _user_api_key_auth_builder( # noqa: PLR0915
if fallback_models is not None:
for m in fallback_models:
await can_key_call_model(
- model=m,
+ model=m["model"] if isinstance(m, dict) else m,
llm_model_list=llm_model_list,
valid_token=valid_token,
llm_router=llm_router,
)
+ await is_valid_fallback_model(
+ model=m["model"] if isinstance(m, dict) else m,
+ llm_router=llm_router,
+ user_model=None,
+ )
# Check 2. If user_id for this token is in budget - done in common_checks()
if valid_token.user_id is not None:
diff --git a/litellm/proxy/route_llm_request.py b/litellm/proxy/route_llm_request.py
index c3cd7521d5c..1ff211c20cc 100644
--- a/litellm/proxy/route_llm_request.py
+++ b/litellm/proxy/route_llm_request.py
@@ -50,9 +50,7 @@ async def route_request(
):
"""
Common helper to route the request
-
"""
-
router_model_names = llm_router.model_names if llm_router is not None else []
if "api_key" in data or "api_base" in data:
return getattr(litellm, f"{route_type}")(**data)
diff --git a/tests/local_testing/test_auth_checks.py b/tests/local_testing/test_auth_checks.py
index 741ffbdac01..29ec8653507 100644
--- a/tests/local_testing/test_auth_checks.py
+++ b/tests/local_testing/test_auth_checks.py
@@ -224,3 +224,33 @@ def test_common_checks_import():
)
except Exception as e:
assert CommonProxyErrors.not_premium_user.value in str(e)
+
+
+async def test_is_valid_fallback_model():
+ from litellm.proxy.auth.auth_checks import is_valid_fallback_model
+ from litellm import Router
+
+ router = Router(
+ model_list=[
+ {
+ "model_name": "gpt-3.5-turbo",
+ "litellm_params": {"model": "openai/gpt-3.5-turbo"},
+ }
+ ]
+ )
+
+ try:
+ await is_valid_fallback_model(
+ model="gpt-3.5-turbo", llm_router=router, user_model=None
+ )
+ except Exception as e:
+ pytest.fail(f"Expected is_valid_fallback_model to work, got exception: {e}")
+
+ try:
+ await is_valid_fallback_model(
+ model="gpt-4o", llm_router=router, user_model=None
+ )
+ pytest.fail("Expected is_valid_fallback_model to fail")
+ except Exception as e:
+ assert "Invalid" in str(e)