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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
feat(proxy): add POST /auto_router/validate_complexity_router_config to dry-run the complexity-router write gate (#37409)
tin-berri135f234e8959
diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.pyindex 6f352b73290..05fc6e07176 100644--- a/litellm/proxy/_types.py+++ b/litellm/proxy/_types.py@@ -832,6 +832,10 @@ class LiteLLMRoutes(enum.Enum):# Team guardrail submissions - endpoint scopes results to caller's teams (non-admin)"/guardrails/submissions","/guardrails/submissions/{guardrail_id}",+ # Auto-router dry runs - both gate like the /model/new write they rehearse:+ # proxy admin, or team admin naming their own team via team_id+ "/auto_router/test_routing",+ "/auto_router/validate_complexity_router_config",] # routes that manage their own allowed/disallowed logic## Org Admin Routes ##diff --git a/litellm/proxy/management_endpoints/auto_router_endpoints.py b/litellm/proxy/management_endpoints/auto_router_endpoints.pyindex 0112ad1f6ed..d47bd7fa311 100644--- a/litellm/proxy/management_endpoints/auto_router_endpoints.py+++ b/litellm/proxy/management_endpoints/auto_router_endpoints.py@@ -2,6 +2,7 @@AUTO ROUTER MANAGEMENT ENDPOINTSPOST /auto_router/test_routing - Route one prompt through an unsaved complexity-router config+POST /auto_router/validate_complexity_router_config - Dry-run the complexity-router write gate without saving"""from collections.abc import Mapping, Sequence@@ -43,6 +44,8 @@ from litellm.types.management_endpoints.auto_router_endpoints import (AutoRouterCacheStats,AutoRouterRoutingTestRequest,AutoRouterRoutingTestResponse,+ ComplexityRouterConfigValidationRequest,+ ComplexityRouterConfigValidationResponse,RequestComplexityRouterConfig,ShadowEvalDirection,ShadowEvalJobKeyResponse,@@ -130,12 +133,13 @@ async def _query_raw(prisma_client: "PrismaClient", query: str, *args: object) -return await prisma_client.db.query_raw(query, *args)-async def _authorize_routing_test(user_api_key_dict: UserAPIKeyAuth, team_id: str | None) -> None:+async def _authorize_router_dry_run(user_api_key_dict: UserAPIKeyAuth, team_id: str | None) -> None:"""Allow exactly the callers who could create this router.- Routing a prompt can spend money (an `llm` classifier config calls its classifier, a- semantic config embeds the prompt), so this is gated like a write rather than a read:- a proxy admin, or a team admin naming their own team, matching /model/new.+ Both dry runs are gated like the write they rehearse rather than as reads: a proxy+ admin, or a team admin naming their own team, matching /model/new. Routing a test+ prompt can also spend money (an `llm` classifier config calls its classifier, a+ semantic config embeds the prompt), so a read-level gate would be too loose anyway."""from litellm.proxy.management_endpoints.model_management_endpoints import (ModelManagementAuthChecks,@@ -149,7 +153,7 @@ async def _authorize_routing_test(user_api_key_dict: UserAPIKeyAuth, team_id: straise HTTPException(status_code=403,detail={ # mutable-ok: HTTPException detail must be a plain mapping to keep this route's {"error": ...} response shape- "error": f"User does not have permission to test an auto router. Your role={user_api_key_dict.user_role}. Test as a PROXY_ADMIN, or as a team admin by specifying a team_id."+ "error": f"User does not have permission to dry-run an auto router. Your role={user_api_key_dict.user_role}. Call as a PROXY_ADMIN, or as a team admin by specifying a team_id."},)@@ -238,6 +242,35 @@ async def _authorize_models_this_test_can_call() from e+ "/auto_router/validate_complexity_router_config",+ tags=["model management"], # mutable-ok: fastapi's decorator signature types tags as a list+ dependencies=[Depends(user_api_key_auth)], # mutable-ok: fastapi's decorator signature types dependencies as a list+ response_model=ComplexityRouterConfigValidationResponse,+ status_code=status.HTTP_200_OK,+)+async def validate_complexity_router_config(+ data: ComplexityRouterConfigValidationRequest,+ user_api_key_dict: Annotated[UserAPIKeyAuth, Depends(user_api_key_auth)],+) -> ComplexityRouterConfigValidationResponse:+ """+ Validate a complexity-router config without saving it.++ Runs the same check every write path runs (the router's own pydantic model), so a form can+ show the backend's exact verdict while the operator is still editing rather than after a+ rejected save. Gated exactly like the save it rehearses: a proxy admin, or a team admin+ naming their own team. Nothing is created, routed, or billed.+ """+ await _authorize_router_dry_run(user_api_key_dict=user_api_key_dict, team_id=data.team_id)++ from litellm.router_utils.auto_router_model_naming import (+ validate_complexity_router_config_write,+ )++ error: Final = validate_complexity_router_config_write(data.complexity_router_config)+ return ComplexityRouterConfigValidationResponse(valid=error is None, error=error)++@router.post("/auto_router/test_routing",tags=["model management"], # mutable-ok: fastapi's decorator signature types tags as a list@@ -270,9 +303,17 @@ async def preview_auto_router_routing(}```"""- from litellm.proxy.proxy_server import llm_router+ from litellm.proxy.proxy_server import (+ general_settings,+ llm_router,+ prisma_client,+ proxy_logging_obj,+ user_api_key_cache,+ user_model,+ )+ from litellm.proxy.utils import get_available_models_for_user- await _authorize_routing_test(user_api_key_dict=user_api_key_dict, team_id=data.team_id)+ await _authorize_router_dry_run(user_api_key_dict=user_api_key_dict, team_id=data.team_id)if llm_router is None:raise HTTPException(@@ -327,9 +368,19 @@ async def preview_auto_router_routing(},)+ available_models: Final = await get_available_models_for_user(+ user_api_key_dict=user_api_key_dict,+ llm_router=llm_router,+ general_settings=general_settings,+ user_model=user_model,+ prisma_client=prisma_client,+ proxy_logging_obj=proxy_logging_obj,+ team_id=data.team_id,+ user_api_key_cache=user_api_key_cache,+ )return AutoRouterRoutingTestResponse(routed_model=hook_response.model,- routed_model_configured=hook_response.model in frozenset(llm_router.get_model_names()),+ routed_model_configured=hook_response.model in frozenset(available_models),routing_decision=hook_response.routing_decision,)diff --git a/litellm/types/management_endpoints/auto_router_endpoints.py b/litellm/types/management_endpoints/auto_router_endpoints.pyindex 63c93e0f268..d68d1dc9625 100644--- a/litellm/types/management_endpoints/auto_router_endpoints.py+++ b/litellm/types/management_endpoints/auto_router_endpoints.py@@ -27,6 +27,22 @@ class RequestComplexityRouterConfig(ComplexityRouterConfig):)+class ComplexityRouterConfigValidationRequest(BaseModel):+ """A complexity-router config to validate without saving, so a form can surface the+ backend's own verdict inline instead of a raw 400 at write time."""++ complexity_router_config: Mapping[str, object]+ team_id: str | None = Field(+ default=None,+ description="Team the router is being created for. Required for a team admin, who may only validate their own team's routers",+ )+++class ComplexityRouterConfigValidationResponse(BaseModel):+ valid: bool+ error: str | None = None++class AutoRouterRoutingTestRequest(BaseModel):"""A single prompt to classify against a complexity-router config that need not be saved yet."""@@ -60,7 +76,7 @@ class AutoRouterRoutingTestResponse(BaseModel):routed_model: str = Field(description="The model group the router picked")routed_model_configured: bool = Field(- description="Whether routed_model is a model group this proxy actually serves",+ description="Whether routed_model is a model group available to the caller, scoped to team_id when given. Never confirms models the caller could not use",)routing_decision: StandardLoggingRoutingDecision = Field(description="The decision record this request would have written to its log row",diff --git a/tests/test_litellm/proxy/auth/test_route_checks.py b/tests/test_litellm/proxy/auth/test_route_checks.pyindex 21511c74154..aa9e5349c87 100644--- a/tests/test_litellm/proxy/auth/test_route_checks.py+++ b/tests/test_litellm/proxy/auth/test_route_checks.py@@ -3379,3 +3379,52 @@ def test_organization_daily_activity_not_granted_by_org_admin_request_data_brancroute="/organization/daily/activity",allowed_routes=LiteLLMRoutes.org_admin_only_routes.value,)+++ "user_role",+ [+ LitellmUserRoles.INTERNAL_USER.value,+ LitellmUserRoles.INTERNAL_USER_VIEW_ONLY.value,+ LitellmUserRoles.PROXY_ADMIN_VIEW_ONLY.value,+ LitellmUserRoles.TEAM.value,+ ],+)+ "dry_run_route",+ ["/auto_router/test_routing", "/auto_router/validate_complexity_router_config"],+)+def test_auto_router_dry_runs_share_model_new_audience(user_role, dry_run_route):+ """The dry runs serve whoever can draft a save on /model/new, no one else: a role+ must get the same allow-or-403 from both layers' route check, or the form's+ pre-save call 403s for an operator whose save would have been accepted."""++ def outcome(route: str) -> str:+ user_obj = LiteLLM_UserTable(+ user_id="test_user",+ user_email="[email protected]",+ user_role=user_role,+ )+ valid_token = UserAPIKeyAuth(+ user_id="test_user",+ user_role=user_role,+ )+ request = MagicMock(spec=Request)+ request.query_params = {}+ try:+ RouteChecks.non_proxy_admin_allowed_routes_check(+ user_obj=user_obj,+ _user_role=user_role,+ route=route,+ request=request,+ valid_token=valid_token,+ request_data={},+ )+ return "allowed"+ except HTTPException:+ return "rejected"++ assert outcome(dry_run_route) == outcome("/model/new")+ # Anchor so parity cannot be satisfied by both routes 403ing for everyone+ if user_role == LitellmUserRoles.INTERNAL_USER.value:+ assert outcome(dry_run_route) == "allowed"diff --git a/tests/test_litellm/proxy/management_endpoints/test_auto_router_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_auto_router_endpoints.pyindex 3fd023552f5..c901696e108 100644--- a/tests/test_litellm/proxy/management_endpoints/test_auto_router_endpoints.py+++ b/tests/test_litellm/proxy/management_endpoints/test_auto_router_endpoints.py@@ -5,6 +5,7 @@ Unit tests for auto router management endpointsimport osimport sysfrom pathlib import Path+from typing import Finalimport pytestfrom fastapi import HTTPException@@ -1188,6 +1189,149 @@ async def test_stop_shadow_eval_stops_every_unstopped_leg_and_rejects_non_runninassert forbidden.value.status_code == 403+async def test_validate_config_returns_the_write_gates_verdict_without_saving():+ """The dry-run endpoint must agree with the write gate exactly, so a form showing its+ verdict inline can never pass a config the save would then reject."""+ from litellm.proxy.management_endpoints.auto_router_endpoints import (+ validate_complexity_router_config,+ )+ from litellm.types.management_endpoints.auto_router_endpoints import (+ ComplexityRouterConfigValidationRequest,+ )++ valid = await validate_complexity_router_config(+ ComplexityRouterConfigValidationRequest(+ complexity_router_config={+ "tiers": {"CASUAL": "m1", "AUDIT": "m2"},+ "tier_definitions": [+ {"name": "CASUAL", "description": "casual chat"},+ {"name": "AUDIT", "description": "security audits"},+ ],+ "fallback_tier": "AUDIT",+ "classifier_type": "llm",+ "classifier_llm_config": {"model": "clf"},+ }+ ),+ ADMIN,+ )+ assert valid.valid is True+ assert valid.error is None++ rejected = await validate_complexity_router_config(+ ComplexityRouterConfigValidationRequest(+ complexity_router_config={+ "tiers": {"CASUAL": "m1", "AUDIT": "m2"},+ "tier_definitions": [+ {"name": "CASUAL", "description": "casual chat"},+ {"name": "AUDIT", "description": "security\naudits"},+ ],+ "fallback_tier": "AUDIT",+ "classifier_type": "llm",+ "classifier_llm_config": {"model": "clf"},+ }+ ),+ ADMIN,+ )+ assert rejected.valid is False+ assert rejected.error is not None and "newline" in rejected.error+++async def test_routing_test_never_confirms_models_the_caller_cannot_use(monkeypatch: pytest.MonkeyPatch):+ """routed_model_configured must not be an existence oracle for the whole proxy: a team+ admin probing a guessed global model name reads False unless the named team could+ actually use that model, and True once the team grants it."""+ from litellm.proxy import proxy_server++ def _team_prisma(team_id: str, models: list[str]) -> MagicMock:+ row_data = {+ "team_id": team_id,+ "members_with_roles": [{"role": "admin", "user_id": "team-admin"}],+ "models": models,+ }+ team_row = MagicMock()+ team_row.model_dump.return_value = row_data+ team_row.dict.return_value = row_data+ prisma = MagicMock()+ prisma.db.litellm_teamtable.find_unique = AsyncMock(return_value=team_row)+ return prisma++ def _request(team_id: str) -> AutoRouterRoutingTestRequest:+ return AutoRouterRoutingTestRequest.model_validate(+ {+ "prompt": "what is 2+2",+ "complexity_router_config": {"tiers": TIERS, "classifier_type": "heuristic"},+ "team_id": team_id,+ }+ )++ monkeypatch.setattr(proxy_server, "premium_user", True)+ monkeypatch.setattr(proxy_server, "llm_router", _router())++ team_admin: Final = UserAPIKeyAuth(+ user_role=LitellmUserRoles.INTERNAL_USER, api_key="sk-team", user_id="team-admin"+ )++ monkeypatch.setattr(proxy_server, "prisma_client", _team_prisma("team-probe", models=["mid-model"]))+ probing = await preview_auto_router_routing(data=_request("team-probe"), user_api_key_dict=team_admin)+ assert probing.routed_model == "cheap-model"+ assert probing.routed_model_configured is False++ monkeypatch.setattr(proxy_server, "prisma_client", _team_prisma("team-grant", models=["cheap-model"]))+ granted = await preview_auto_router_routing(data=_request("team-grant"), user_api_key_dict=team_admin)+ assert granted.routed_model == "cheap-model"+ assert granted.routed_model_configured is True+++async def test_validate_config_gates_like_the_write_it_rehearses(monkeypatch: pytest.MonkeyPatch):+ """A caller who could not save the router must not get the dry run either: matching+ /model/new, a team admin passes only when naming their own team, and a caller who is+ neither proxy admin nor team admin is rejected before validation runs."""+ from litellm.proxy import proxy_server+ from litellm.proxy.management_endpoints.auto_router_endpoints import (+ validate_complexity_router_config,+ )+ from litellm.types.management_endpoints.auto_router_endpoints import (+ ComplexityRouterConfigValidationRequest,+ )++ config: Final = {"tiers": {"SIMPLE": "m1"}, "classifier_type": "heuristic"}++ with pytest.raises(HTTPException) as forbidden:+ await validate_complexity_router_config(+ ComplexityRouterConfigValidationRequest(complexity_router_config=config), VIEWER+ )+ assert forbidden.value.status_code == 403++ team_row: Final = MagicMock()+ team_row.model_dump.return_value = {+ "team_id": "team-1",+ "members_with_roles": [{"role": "admin", "user_id": "team-admin"}],+ }+ prisma: Final = MagicMock()+ prisma.db.litellm_teamtable.find_unique = AsyncMock(return_value=team_row)+ monkeypatch.setattr(proxy_server, "prisma_client", prisma)+ monkeypatch.setattr(proxy_server, "premium_user", True)++ team_admin: Final = UserAPIKeyAuth(+ user_role=LitellmUserRoles.INTERNAL_USER, api_key="sk-team", user_id="team-admin"+ )+ verdict = await validate_complexity_router_config(+ ComplexityRouterConfigValidationRequest(complexity_router_config=config, team_id="team-1"),+ team_admin,+ )+ assert verdict.valid is True++ with pytest.raises(HTTPException) as not_their_team:+ await validate_complexity_router_config(+ ComplexityRouterConfigValidationRequest(complexity_router_config=config, team_id="team-1"),+ UserAPIKeyAuth(user_role=LitellmUserRoles.INTERNAL_USER, api_key="sk-other", user_id="someone-else"),+ )+ assert not_their_team.value.status_code == 403++def test_every_shadow_eval_sql_constant_speaks_naive_utc():"""The tables store naive UTC wall time (prisma's convention), so SQL-side time must beNOW() AT TIME ZONE 'utc' and python-side params must cast ::timestamp; a bare NOW() or adiff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.tsindex 70ebc4f39a7..b3bda191933 100644--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts@@ -945,6 +945,31 @@ export interface paths {patch?: never;trace?: never;};+ "/auto_router/validate_complexity_router_config": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ get?: never;+ put?: never;+ /**+ * Validate Complexity Router Config+ * @description Validate a complexity-router config without saving it.+ *+ * Runs the same check every write path runs (the router's own pydantic model), so a form can+ * show the backend's exact verdict while the operator is still editing rather than after a+ * rejected save. Gated exactly like the save it rehearses: a proxy admin, or a team admin+ * naming their own team. Nothing is created, routed, or billed.+ */+ post: operations["validate_complexity_router_config_auto_router_validate_complexity_router_config_post"];+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };"/azure/{endpoint}": {parameters: {query?: never;@@ -22058,7 +22083,7 @@ export interface components {routed_model: string;/*** Routed Model Configured- * @description Whether routed_model is a model group this proxy actually serves+ * @description Whether routed_model is a model group available to the caller, scoped to team_id when given. Never confirms models the caller could not use*/routed_model_configured: boolean;/** @description The decision record this request would have written to its log row */@@ -23773,6 +23798,29 @@ export interface components {*/timezone?: string | null;};+ /**+ * ComplexityRouterConfigValidationRequest+ * @description A complexity-router config to validate without saving, so a form can surface the+ * backend's own verdict inline instead of a raw 400 at write time.+ */+ ComplexityRouterConfigValidationRequest: {+ /** Complexity Router Config */+ complexity_router_config: {+ [key: string]: unknown;+ };+ /**+ * Team Id+ * @description Team the router is being created for. Required for a team admin, who may only validate their own team's routers+ */+ team_id?: string | null;+ };+ /** ComplexityRouterConfigValidationResponse */+ ComplexityRouterConfigValidationResponse: {+ /** Error */+ error?: string | null;+ /** Valid */+ valid: boolean;+ };/*** ComplexityScorerDefaults* @description The complexity router's shipped heuristic scorer defaults.@@ -38165,6 +38213,39 @@ export interface operations {};};};+ validate_complexity_router_config_auto_router_validate_complexity_router_config_post: {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ requestBody: {+ content: {+ "application/json": components["schemas"]["ComplexityRouterConfigValidationRequest"];+ };+ };+ responses: {+ /** @description Successful Response */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["ComplexityRouterConfigValidationResponse"];+ };+ };+ /** @description Validation Error */+ 422: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["HTTPValidationError"];+ };+ };+ };+ };azure_proxy_route_azure__endpoint__get: {parameters: {query?: never;