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]

feat(ui): add Test Routing to the auto router create form (#35859)

devin-ai-integration[bot]4781b53e7248
diff --git a/backend/routes/allowlist.py b/backend/routes/allowlist.py
index a0efa19f320..96e224a7dc6 100644
--- a/backend/routes/allowlist.py
+++ b/backend/routes/allowlist.py
@@ -44,6 +44,7 @@ BACKEND_PATH_PREFIXES: tuple[str, ...] = (
"/router/",
"/router_settings",
"/adaptive_router/",
+ "/auto_router/",
"/fallback",
"/fallbacks",
"/cache_settings",
diff --git a/litellm/proxy/management_endpoints/auto_router_endpoints.py b/litellm/proxy/management_endpoints/auto_router_endpoints.py
new file mode 100644
index 00000000000..66fd25e2e79
--- /dev/null
+++ b/litellm/proxy/management_endpoints/auto_router_endpoints.py
@@ -0,0 +1,247 @@
+"""
+AUTO ROUTER MANAGEMENT ENDPOINTS
+
+POST /auto_router/test_routing - Route one prompt through an unsaved complexity-router config
+"""
+
+from typing import TYPE_CHECKING, Annotated, Final
+
+from litellm._logging import verbose_proxy_logger
+from litellm.exceptions import BudgetExceededError
+from litellm.proxy._types import (
+ CommonProxyErrors,
+ LiteLLM_TeamTable,
+ LitellmUserRoles,
+ ProxyErrorTypes,
+ ProxyException,
+ UserAPIKeyAuth,
+)
+from litellm.proxy.auth.auth_checks import (
+ _virtual_key_max_budget_check,
+ can_key_call_resolved_model,
+)
+from litellm.proxy.auth.user_api_key_auth import user_api_key_auth
+from litellm.proxy.litellm_pre_call_utils import LiteLLMProxyRequestSetup
+from litellm.repositories.team_repository import TeamRepository
+from litellm.router_strategy.complexity_router import ComplexityRouter
+from litellm.types.management_endpoints.auto_router_endpoints import (
+ AutoRouterRoutingTestRequest,
+ AutoRouterRoutingTestResponse,
+ RequestComplexityRouterConfig,
+)
+
+if TYPE_CHECKING:
+ from fastapi import APIRouter, Depends, HTTPException, status
+
+ from litellm.router import Router
+else:
+ try:
+ from fastapi import APIRouter, Depends, HTTPException, status
+ except ImportError:
+ # fastapi is only required for proxy, not for SDK usage
+ pass
+
+router: Final = APIRouter()
+
+
+async def _authorize_routing_test(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.
+ """
+ from litellm.proxy.management_endpoints.model_management_endpoints import (
+ ModelManagementAuthChecks,
+ )
+ from litellm.proxy.proxy_server import premium_user, prisma_client
+
+ if user_api_key_dict.user_role == LitellmUserRoles.PROXY_ADMIN:
+ return
+
+ if team_id is None:
+ raise 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."
+ },
+ )
+
+ if prisma_client is None:
+ raise HTTPException(
+ status_code=500,
+ detail={ # mutable-ok: HTTPException detail must be a plain mapping
+ "error": CommonProxyErrors.db_not_connected_error.value
+ },
+ )
+
+ team_row: Final = await TeamRepository(prisma_client).table.find_unique(
+ where={"team_id": team_id}, # mutable-ok: Prisma query filters are dict-shaped
+ )
+ if team_row is None:
+ raise HTTPException(
+ status_code=400,
+ detail={ # mutable-ok: HTTPException detail must be a plain mapping
+ "error": f"Team id={team_id} does not exist in db"
+ },
+ )
+
+ ModelManagementAuthChecks.can_user_make_team_model_call(
+ team_id=team_id,
+ user_api_key_dict=user_api_key_dict,
+ team_obj=LiteLLM_TeamTable.model_validate(team_row.model_dump()),
+ premium_user=premium_user,
+ )
+
+
+def _models_this_test_can_call(config: RequestComplexityRouterConfig) -> tuple[str, ...]:
+ """The models the routing test itself would send a request to, and so spend on.
+
+ Excludes every tier's models: the prompt is never sent to the model it routed to.
+ """
+ return tuple(
+ model
+ for model in (
+ config.classifier_llm_config.model
+ if config.classifier_type == "llm" and config.classifier_llm_config is not None
+ else None,
+ config.embedding_model if config.semantic_keyword_matching else None,
+ )
+ if model is not None
+ )
+
+
+async def _authorize_models_this_test_can_call(
+ config: RequestComplexityRouterConfig,
+ user_api_key_dict: UserAPIKeyAuth,
+ llm_router: "Router",
+) -> None:
+ """Hold a classifier or embedding call to the caller's model access and key budget.
+
+ Those calls go through the router rather than through /v1/chat/completions, so the model
+ checks a real request gets in user_api_key_auth would otherwise be skipped, letting a
+ caller spend on a model their key cannot call, and this route is not an LLM API route, so
+ the key's own budget is not checked either. Test Connection gets both for free by routing
+ its calls through the proxy. Team and member budgets are already enforced on every route.
+ """
+ models: Final = _models_this_test_can_call(config)
+ if not models:
+ return
+
+ from litellm.proxy.proxy_server import proxy_logging_obj
+
+ for model in models:
+ await can_key_call_resolved_model(
+ model=model,
+ llm_model_list=llm_router.model_list,
+ valid_token=user_api_key_dict,
+ llm_router=llm_router,
+ )
+
+ try:
+ await _virtual_key_max_budget_check(
+ valid_token=user_api_key_dict,
+ proxy_logging_obj=proxy_logging_obj,
+ )
+ except BudgetExceededError as e:
+ raise ProxyException(
+ message=e.message,
+ type=ProxyErrorTypes.budget_exceeded,
+ param=None,
+ code=status.HTTP_400_BAD_REQUEST,
+ ) from e
+
+
+ "/auto_router/test_routing",
+ 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=AutoRouterRoutingTestResponse,
+ status_code=status.HTTP_200_OK,
+)
+async def preview_auto_router_routing(
+ data: AutoRouterRoutingTestRequest,
+ user_api_key_dict: Annotated[UserAPIKeyAuth, Depends(user_api_key_auth)],
+) -> AutoRouterRoutingTestResponse:
+ """
+ Route a single prompt through a complexity-router config and report where it landed.
+
+ Answers "which model would this prompt get?" for a config that only exists in a form,
+ so an auto router can be checked before it is created. The prompt is classified by the
+ same pre-routing hook a live request runs, then dropped: nothing is sent to the model it
+ routed to, and no auto router is created. A heuristic config therefore spends nothing, while
+ an `llm` classifier or semantic keyword matching bills its classifier/embedding call to the
+ calling key, like Test Connection does.
+
+ **Example Request:**
+ ```json
+ {
+ "prompt": "think step by step about how to shard this table",
+ "complexity_router_config": {
+ "tiers": {"SIMPLE": ["gpt-4o-mini"], "REASONING": ["o3"]},
+ "classifier_type": "heuristic"
+ }
+ }
+ ```
+ """
+ from litellm.proxy.proxy_server import llm_router
+
+ await _authorize_routing_test(user_api_key_dict=user_api_key_dict, team_id=data.team_id)
+
+ if llm_router is None:
+ raise HTTPException(
+ status_code=500,
+ detail={ # mutable-ok: HTTPException detail must be a plain mapping
+ "error": CommonProxyErrors.no_llm_router.value
+ },
+ )
+
+ await _authorize_models_this_test_can_call(
+ config=data.complexity_router_config,
+ user_api_key_dict=user_api_key_dict,
+ llm_router=llm_router,
+ )
+
+ complexity_router: Final = ComplexityRouter(
+ model_name=data.router_name,
+ litellm_router_instance=llm_router,
+ complexity_router_config=data.complexity_router_config.model_dump(exclude_none=True),
+ default_model=data.default_model,
+ )
+
+ request_kwargs: Final = LiteLLMProxyRequestSetup.add_user_api_key_auth_to_request_metadata(
+ data={"metadata": {}}, # mutable-ok: the request-metadata helper takes and returns request kwargs as a dict
+ user_api_key_dict=user_api_key_dict,
+ _metadata_variable_name="metadata",
+ )
+
+ try:
+ hook_response: Final = await complexity_router.async_pre_routing_hook(
+ model=data.router_name,
+ request_kwargs=request_kwargs,
+ messages=[ # mutable-ok: the routing hook's signature takes a list of message dicts
+ {"role": "user", "content": data.prompt}, # mutable-ok: a message is dict-shaped
+ ],
+ )
+ except Exception as e: # noqa: BLE001 -- surfaces any classifier/plugin failure to the caller as a 400 instead of a 500, since the config under test is caller input
+ verbose_proxy_logger.exception("Auto router routing test failed. Due to error - %s", e)
+ raise HTTPException(
+ status_code=400,
+ detail={ # mutable-ok: HTTPException detail must be a plain mapping
+ "error": f"Could not route this prompt: {e}"
+ },
+ ) from e
+
+ if hook_response is None or hook_response.routing_decision is None:
+ raise HTTPException(
+ status_code=400,
+ detail={ # mutable-ok: HTTPException detail must be a plain mapping
+ "error": "The router made no decision for this prompt. Check that at least one tier has a model."
+ },
+ )
+
+ return AutoRouterRoutingTestResponse(
+ routed_model=hook_response.model,
+ routed_model_configured=hook_response.model in frozenset(llm_router.get_model_names()),
+ routing_decision=hook_response.routing_decision,
+ )
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index fb9c4e67aad..e343d46f872 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -379,6 +379,9 @@ from litellm.proxy.litellm_pre_call_utils import add_litellm_data_to_request
from litellm.proxy.logging_endpoints.callback_logs_endpoints import (
rust_control_plane_router,
)
+from litellm.proxy.management_endpoints.auto_router_endpoints import (
+ router as auto_router_management_router,
+)
from litellm.proxy.management_endpoints.budget_management_endpoints import (
router as budget_management_router,
)
@@ -16457,6 +16460,7 @@ app.include_router(team_callback_router)
app.include_router(budget_management_router)
app.include_router(model_management_router)
app.include_router(model_access_group_management_router)
+app.include_router(auto_router_management_router)
app.include_router(tag_management_router)
app.include_router(workflow_management_router)
app.include_router(memory_router)
diff --git a/litellm/types/management_endpoints/auto_router_endpoints.py b/litellm/types/management_endpoints/auto_router_endpoints.py
new file mode 100644
index 00000000000..2190db4a739
--- /dev/null
+++ b/litellm/types/management_endpoints/auto_router_endpoints.py
@@ -0,0 +1,62 @@
+"""
+Types for auto-router management endpoints
+"""
+
+from typing import Final
+
+from pydantic import BaseModel, Field, field_validator
+
+from litellm.router_strategy.complexity_router.config import ComplexityRouterConfig
+from litellm.types.utils import StandardLoggingRoutingDecision
+
+DEFAULT_ROUTING_TEST_ROUTER_NAME: Final[str] = "auto_router_routing_test"
+
+
+class RequestComplexityRouterConfig(ComplexityRouterConfig):
+ """The part of a complexity-router config a request can carry.
+
+ `plugins` holds live RoutingPlugin objects, which no JSON body can express and which have no
+ OpenAPI schema, so it is closed off here rather than left as an arbitrary-type field.
+ """
+
+ plugins: None = Field(default=None, description="Not settable over HTTP; routing plugins are runtime objects")
+
+
+class AutoRouterRoutingTestRequest(BaseModel):
+ """A single prompt to classify against a complexity-router config that need not be saved yet."""
+
+ prompt: str = Field(description="The prompt to route, as an end user would send it")
+ complexity_router_config: RequestComplexityRouterConfig = Field(
+ description="The complexity router config to route against, in the shape /model/new accepts",
+ )
+ default_model: str | None = Field(
+ default=None,
+ description="Model to route to when no tier resolves, i.e. complexity_router_default_model",
+ )
+ router_name: str = Field(
+ default=DEFAULT_ROUTING_TEST_ROUTER_NAME,
+ description="Name reported as the router in the routing decision. Display only",
+ )
+ team_id: str | None = Field(
+ default=None,
+ description="Team the router is being created for. Required for a team admin, who may only test their own team's routers",
+ )
+
+ @field_validator("prompt")
+ @classmethod
+ def _require_non_blank_prompt(cls, value: str) -> str:
+ if not value.strip():
+ raise ValueError("prompt must not be blank")
+ return value
+
+
+class AutoRouterRoutingTestResponse(BaseModel):
+ """Where one prompt would have been routed, and why."""
+
+ 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",
+ )
+ routing_decision: StandardLoggingRoutingDecision = Field(
+ description="The decision record this request would have written to its log row",
+ )
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.py
new file mode 100644
index 00000000000..6aea2bcb19b
--- /dev/null
+++ b/tests/test_litellm/proxy/management_endpoints/test_auto_router_endpoints.py
@@ -0,0 +1,286 @@
+"""
+Unit tests for auto router management endpoints
+"""
+
+import os
+import sys
+
+import pytest
+from fastapi import HTTPException
+from pydantic import ValidationError
+
+sys.path.insert(0, os.path.abspath("../../../..")) # Adds the parent directory to the system path
+
+from litellm.proxy._types import (
+ LitellmUserRoles,
+ ProxyErrorTypes,
+ ProxyException,
+ UserAPIKeyAuth,
+)
+from litellm.proxy.management_endpoints.auto_router_endpoints import (
+ preview_auto_router_routing,
+)
+from litellm.router import Router
+from litellm.types.utils import Choices, Message, ModelResponse
+from litellm.types.management_endpoints.auto_router_endpoints import (
+ AutoRouterRoutingTestRequest,
+)
+
+ADMIN = UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN, api_key="sk-test", user_id="admin")
+
+TIERS = {
+ "SIMPLE": ["cheap-model"],
+ "MEDIUM": ["mid-model"],
+ "COMPLEX": ["strong-model"],
+ "REASONING": ["reasoning-model"],
+}
+
+
+def _router() -> Router:
+ return Router(
+ model_list=[
+ {"model_name": name, "litellm_params": {"model": "openai/gpt-4o-mini", "api_key": "fake-key"}}
+ for name in ("cheap-model", "mid-model", "strong-model", "reasoning-model")
+ ]
+ )
+
+
+def _request(prompt: str, **config_overrides: object) -> AutoRouterRoutingTestRequest:
+ return AutoRouterRoutingTestRequest.model_validate(
+ {
+ "prompt": prompt,
+ "complexity_router_config": {"tiers": TIERS, "classifier_type": "heuristic", **config_overrides},
+ }
+ )
+
+
+async def _route(prompt: str, monkeypatch: pytest.MonkeyPatch, **config_overrides: object):
+ import litellm.proxy.proxy_server as proxy_server
+
+ monkeypatch.setattr(proxy_server, "llm_router", _router())
+ return await preview_auto_router_routing(
+ data=_request(prompt, **config_overrides),
+ user_api_key_dict=ADMIN,
+ )
+
+
+async def test_simple_prompt_routes_to_the_simple_tier(monkeypatch: pytest.MonkeyPatch):
+ response = await _route("what is 2+2", monkeypatch)
+
+ assert response.routed_model == "cheap-model"
+ assert response.routed_model_configured is True
+ assert response.routing_decision["tier"] == "SIMPLE"
+ assert response.routing_decision["cause"] == "heuristic_scorer"
+ assert response.routing_decision["routed_model"] == "cheap-model"
+ assert "score" in response.routing_decision
+
+
+async def test_reasoning_markers_route_to_the_reasoning_tier(monkeypatch: pytest.MonkeyPatch):
+ response = await _route(
+ "think step by step and explain your reasoning about sharding this table",
+ monkeypatch,
+ )
+
+ assert response.routed_model == "reasoning-model"
+ assert response.routing_decision["tier"] == "REASONING"
+
+
+async def test_keyword_rule_beats_the_heuristic_scorer(monkeypatch: pytest.MonkeyPatch):
+ response = await _route(
+ "what is 2+2",
+ monkeypatch,
+ keyword_tier_rules=[{"keywords": ["2+2"], "tier": "COMPLEX"}],
+ )
+
+ assert response.routed_model == "strong-model"
+ assert response.routing_decision["cause"] == "literal_keyword_match"
+ assert response.routing_decision["matched_keyword"] == "2+2"
+
+
+async def test_escalation_keyword_bumps_the_classified_tier(monkeypatch: pytest.MonkeyPatch):
+ response = await _route("what is 2+2, ultrathink", monkeypatch, escalation_keywords=["ultrathink"])
+
+ assert response.routed_model == "mid-model"
+ assert response.routing_decision["escalated"] is True
+ assert response.routing_decision["escalation_keyword"] == "ultrathink"
+
+
+async def test_tier_model_missing_from_the_proxy_is_reported(monkeypatch: pytest.MonkeyPatch):
+ response = await _route("what is 2+2", monkeypatch, tiers={**TIERS, "SIMPLE": ["never-configured"]})
+
+ assert response.routed_model == "never-configured"
+ assert response.routed_model_configured is False
+
+
+async def test_llm_classifier_call_is_billed_to_the_calling_key(monkeypatch: pytest.MonkeyPatch):
+ import litellm.proxy.proxy_server as proxy_server
+
+ router = _router()
+ calls: list[dict] = []
+
+ async def fake_acompletion(**kwargs):
+ calls.append(kwargs)
+ return ModelResponse(
+ choices=[Choices(message=Message(content='{"tier": "COMPLEX"}'))],
+ model="classifier-model",
+ )
+
+ monkeypatch.setattr(router, "acompletion", fake_acompletion)
+ monkeypatch.setattr(proxy_server, "llm_router", router)
+
+ response = await preview_auto_router_routing(
+ data=_request(
+ "what is 2+2",
+ classifier_type="llm",
+ classifier_llm_config={"model": "classifier-model"},
+ ),
+ user_api_key_dict=ADMIN,
+ )
+
+ assert response.routed_model == "strong-model"
+ assert len(calls) == 1
+ assert calls[0]["metadata"]["user_api_key"] == ADMIN.api_key
+ assert calls[0]["metadata"]["user_api_key_user_id"] == ADMIN.user_id
+
+
+ "config_overrides",
+ [
+ {"classifier_type": "llm", "classifier_llm_config": {"model": "classifier-model"}},
+ {
+ "semantic_keyword_matching": True,
+ "embedding_model": "classifier-model",
+ "keyword_tier_rules": [{"keywords": ["2+2"], "tier": "COMPLEX"}],
+ },
+ ],
+)
+async def test_a_key_that_cannot_call_the_classifier_model_is_rejected_before_it_is_called(
+ monkeypatch: pytest.MonkeyPatch, config_overrides: dict
+):
+ import litellm.proxy.proxy_server as proxy_server
+
+ router = _router()
+ calls: list[dict] = []
+
+ async def fail_if_called(**kwargs):
+ calls.append(kwargs)
+ raise AssertionError("the classifier must not be called by a key that cannot call it")
+
+ monkeypatch.setattr(router, "acompletion", fail_if_called)
+ monkeypatch.setattr(router, "aembedding", fail_if_called)
+ monkeypatch.setattr(proxy_server, "llm_router", router)
+
+ with pytest.raises(ProxyException) as exc_info:
+ await preview_auto_router_routing(
+ data=_request("what is 2+2", **config_overrides),
+ user_api_key_dict=UserAPIKeyAuth(
+ user_role=LitellmUserRoles.PROXY_ADMIN,
+ api_key="sk-restricted",
+ user_id="admin",
+ models=["cheap-model"],
+ ),
+ )
+
+ assert exc_info.value.type == ProxyErrorTypes.key_model_access_denied
+ assert calls == []
+
+
+async def test_a_key_over_its_budget_cannot_run_a_classifier_config(monkeypatch: pytest.MonkeyPatch):
+ import litellm.proxy.proxy_server as proxy_server
+
+ router = _router()
+ calls: list[dict] = []
+
+ async def fail_if_called(**kwargs):
+ calls.append(kwargs)
+ raise AssertionError("an exhausted key must not reach the classifier")
+
+ monkeypatch.setattr(router, "acompletion", fail_if_called)
+ monkeypatch.setattr(proxy_server, "llm_router", router)
+
+ with pytest.raises(ProxyException) as exc_info:
+ await preview_auto_router_routing(
+ data=_request(
+ "what is 2+2",
+ classifier_type="llm",
+ classifier_llm_config={"model": "classifier-model"},
+ ),
+ user_api_key_dict=UserAPIKeyAuth(
+ user_role=LitellmUserRoles.PROXY_ADMIN,
+ api_key="sk-broke",
+ user_id="admin",
+ max_budget=1.0,
+ spend=2.0,
+ ),
+ )
+
+ assert exc_info.value.type == ProxyErrorTypes.budget_exceeded
+ assert calls == []
+
+
+async def test_a_heuristic_config_does_not_need_a_budget(monkeypatch: pytest.MonkeyPatch):
+ import litellm.proxy.proxy_server as proxy_server
+
+ monkeypatch.setattr(proxy_server, "llm_router", _router())
+
+ response = await preview_auto_router_routing(
+ data=_request("what is 2+2"),
+ user_api_key_dict=UserAPIKeyAuth(
+ user_role=LitellmUserRoles.PROXY_ADMIN,
+ api_key="sk-broke",
+ user_id="admin",
+ max_budget=1.0,
+ spend=2.0,
+ models=["cheap-model"],
+ ),
+ )
+
+ assert response.routed_model == "cheap-model"
+
+
+async def test_no_llm_router_on_the_proxy_is_a_500(monkeypatch: pytest.MonkeyPatch):
+ import litellm.proxy.proxy_server as proxy_server
+
+ monkeypatch.setattr(proxy_server, "llm_router", None)
+
+ with pytest.raises(HTTPException) as exc_info:
+ await preview_auto_router_routing(data=_request("what is 2+2"), user_api_key_dict=ADMIN)
+
+ assert exc_info.value.status_code == 500
+
+
+async def test_non_admin_without_a_team_is_rejected(monkeypatch: pytest.MonkeyPatch):
+ import litellm.proxy.proxy_server as proxy_server
+
+ monkeypatch.setattr(proxy_server, "llm_router", _router())
+
+ with pytest.raises(HTTPException) as exc_info:
+ await preview_auto_router_routing(
+ data=_request("what is 2+2"),
+ user_api_key_dict=UserAPIKeyAuth(
+ user_role=LitellmUserRoles.INTERNAL_USER, api_key="sk-user", user_id="user"
+ ),
+ )
+
+ assert exc_info.value.status_code == 403
+
+
+def test_blank_prompt_is_rejected():
+ with pytest.raises(ValidationError):
+ _request(" ")
+
+
+def test_semantic_matching_without_an_embedding_model_is_rejected():
+ with pytest.raises(ValidationError):
+ _request("what is 2+2", semantic_keyword_matching=True)
diff --git a/ui/litellm-dashboard/src/components/add_model/AutoRouterRoutingTest.test.tsx b/ui/litellm-dashboard/src/components/add_model/AutoRouterRoutingTest.test.tsx
new file mode 100644
index 00000000000..200ca51527c
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/add_model/AutoRouterRoutingTest.test.tsx
@@ -0,0 +1,100 @@
+import { renderWithProviders, screen, waitFor } from "../../../tests/test-utils";
+import userEvent from "@testing-library/user-event";
+import { vi } from "vitest";
+import AutoRouterRoutingTest from "./AutoRouterRoutingTest";
+import { testAutoRouterRouting } from "../networking";
+import { ComplexityRouterConfigPayload } from "./build_complexity_router_config";
+
+vi.mock("../networking", () => ({
+ testAutoRouterRouting: vi.fn(),
+}));
+
+const CONFIG = {
+ tiers: { SIMPLE: ["cheap"], MEDIUM: ["mid"], COMPLEX: ["strong"], REASONING: ["o3"] },
+ classifier_type: "heuristic",
+} as unknown as ComplexityRouterConfigPayload;
+
+const Harness = () => (
+ <AutoRouterRoutingTest
+ accessToken="token"
+ config={CONFIG}
+ defaultModel="mid"
+ routerName="my-router"
+ teamId={undefined}
+ />
+);
+
+const expectedRequest = {
+ prompt: "think step by step",
+ complexity_router_config: CONFIG,
+ default_model: "mid",
+ router_name: "my-router",
+};
+
+const successResponse = {
+ status: "success" as const,
+ result: {
+ routed_model: "o3",
+ routed_model_configured: true,
+ routing_decision: {
+ router_model_name: "my-router",
+ router_type: "complexity",
+ routed_model: "o3",
+ cause: "heuristic_scorer",
+ tier: "REASONING",
+ score: 0.91,
+ },
+ },
+};
+
+describe("AutoRouterRoutingTest", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it("cannot send an empty prompt", () => {
+ renderWithProviders(<Harness />);
+
+ expect(screen.getByTestId("auto-router-routing-test-send")).toBeDisabled();
+ });
+
+ it("routes the typed prompt through the config being edited and shows where it landed", async () => {
+ const user = userEvent.setup();
+ vi.mocked(testAutoRouterRouting).mockResolvedValue(successResponse);
+ renderWithProviders(<Harness />);
+
+ await user.type(screen.getByTestId("auto-router-routing-test-prompt"), "think step by step");
+ await user.click(screen.getByTestId("auto-router-routing-test-send"));
+
+ expect(testAutoRouterRouting).toHaveBeenCalledWith("token", expectedRequest);
+ expect(await screen.findByTestId("auto-router-routing-test-routed-model")).toHaveTextContent("o3");
+ expect(screen.getByText("REASONING")).toBeInTheDocument();
+ expect(screen.queryByTestId("auto-router-routing-test-unconfigured")).not.toBeInTheDocument();
+ });
+
+ it("warns when the routed model is not a model group on this proxy", async () => {
+ const user = userEvent.setup();
+ vi.mocked(testAutoRouterRouting).mockResolvedValue({
+ ...successResponse,
+ result: { ...successResponse.result, routed_model_configured: false },
+ });
+ renderWithProviders(<Harness />);
+
+ await user.type(screen.getByTestId("auto-router-routing-test-prompt"), "hello");
+ await user.click(screen.getByTestId("auto-router-routing-test-send"));
+
+ expect(await screen.findByTestId("auto-router-routing-test-unconfigured")).toBeInTheDocument();
+ });
+
+ it("shows why a prompt could not be routed", async () => {
+ const user = userEvent.setup();
+ vi.mocked(testAutoRouterRouting).mockResolvedValue({ status: "error", error: "no tier has a model" });
+ renderWithProviders(<Harness />);
+
+ await user.type(screen.getByTestId("auto-router-routing-test-prompt"), "hello");
+ await user.click(screen.getByTestId("auto-router-routing-test-send"));
+
+ expect(await screen.findByText("no tier has a model")).toBeInTheDocument();
+ await waitFor(() => expect(screen.queryByTestId("auto-router-routing-test-result")).not.toBeInTheDocument());
+ });
+});
diff --git a/ui/litellm-dashboard/src/components/add_model/AutoRouterRoutingTest.tsx b/ui/litellm-dashboard/src/components/add_model/AutoRouterRoutingTest.tsx
new file mode 100644
index 00000000000..f5c4a6735dc
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/add_model/AutoRouterRoutingTest.tsx
@@ -0,0 +1,106 @@
+import React from "react";
+import { TriangleAlert } from "lucide-react";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Textarea } from "@/components/ui/textarea";
+import RoutingDecisionCard from "@/components/view_logs/LogDetailsDrawer/RoutingDecisionCard";
+import { AutoRouterRoutingTestResult, testAutoRouterRouting } from "../networking";
+import { ComplexityRouterConfigPayload } from "./build_complexity_router_config";
+import { buildAutoRouterRoutingTestRequest } from "./build_auto_router_routing_test_request";
+
+interface AutoRouterRoutingTestProps {
+ accessToken: string;
+ config: ComplexityRouterConfigPayload;
+ defaultModel: string | undefined;
+ routerName: string | undefined;
+ teamId: string | undefined;
+}
+
+type TestState =
+ | { status: "idle" }
+ | { status: "running" }
+ | { status: "done"; result: AutoRouterRoutingTestResult }
+ | { status: "failed"; error: string };
+
+const AutoRouterRoutingTest: React.FC<AutoRouterRoutingTestProps> = ({
+ accessToken,
+ config,
+ defaultModel,
+ routerName,
+ teamId,
+}) => {
+ const [prompt, setPrompt] = React.useState<string>("");
+ const [state, setState] = React.useState<TestState>({ status: "idle" });
+
+ const send = async () => {
+ setState({ status: "running" });
+ const params = { prompt, config, defaultModel, routerName, teamId };
+ const request = buildAutoRouterRoutingTestRequest(params);
+ const response = await testAutoRouterRouting(accessToken, request);
+ setState(
+ response.status === "success"
+ ? { status: "done", result: response.result }
+ : { status: "failed", error: response.error },
+ );
+ };
+
+ return (
+ <div className="space-y-3">
+ <p className="text-sm text-muted-foreground">
+ Send a prompt through this router&apos;s classifier to see which model it would pick, and why. The prompt is
+ only classified: nothing is sent to the model it routes to.
+ </p>
+
+ <Textarea
+ value={prompt}
+ onChange={(event) => setPrompt(event.target.value)}
+ placeholder="Paste a prompt an end user would send"
+ rows={4}
+ data-testid="auto-router-routing-test-prompt"
+ />
+
+ <div className="flex justify-end">
+ <Button
+ onClick={send}
+ disabled={prompt.trim().length === 0 || state.status === "running"}
+ data-testid="auto-router-routing-test-send"
+ >
+ {state.status === "running" ? "Routing..." : "Send Test Prompt"}
+ </Button>
+ </div>
+
+ {state.status === "failed" && (
+ <div
+ className="rounded-md border border-destructive/40 bg-destructive/10 p-3 text-sm text-destructive"
+ data-testid="auto-router-routing-test-error"
+ >
+ <p className="font-medium">Could not route this prompt</p>
+ <p>{state.error}</p>
+ </div>
+ )}
+
+ {state.status === "done" && (
+ <div data-testid="auto-router-routing-test-result">
+ <div className="flex items-center gap-2 py-2 text-sm">
+ <span className="text-muted-foreground">Routed to</span>
+ <Badge variant="secondary" data-testid="auto-router-routing-test-routed-model">
+ {state.result.routed_model}
+ </Badge>
+ {!state.result.routed_model_configured && (
+ <span
+ className="flex items-center gap-1 text-amber-600"
+ data-testid="auto-router-routing-test-unconfigured"
+ >
+ <TriangleAlert className="size-3.5" />
+ This proxy has no model group by that name
+ </span>
+ )}
+ </div>
+ <RoutingDecisionCard decision={state.result.routing_decision} />
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default AutoRouterRoutingTest;
diff --git a/ui/litellm-dashboard/src/components/add_model/add_auto_router_tab.test.tsx b/ui/litellm-dashboard/src/components/add_model/add_auto_router_tab.test.tsx
index c1f70bb2ba2..2fa65cba554 100644
--- a/ui/litellm-dashboard/src/components/add_model/add_auto_router_tab.test.tsx
+++ b/ui/litellm-dashboard/src/components/add_model/add_auto_router_tab.test.tsx
@@ -5,6 +5,7 @@ import AddAutoRouterTab from "./add_auto_router_tab";
import NotificationManager from "../molecules/notifications_manager";
import { handleAddAutoRouterSubmit } from "./handle_add_auto_router_submit";
import { getMissingTiersError } from "./build_complexity_router_config";
+import { testAutoRouterRouting } from "../networking";
import { ModelGroup } from "@/components/llm_calls/fetch_models";
// Every model referenced by both bundled family presets. A caller holding all of these can select
@@ -42,6 +43,7 @@ const { mockFetchAvailableModels } = vi.hoisted(() => ({ mockFetchAvailableModel
vi.mock("../networking", () => ({
modelAvailableCall: vi.fn().mockResolvedValue({ data: [] }),
+ testAutoRouterRouting: vi.fn(),
}));
vi.mock("@/components/llm_calls/fetch_models", () => ({
@@ -303,6 +305,80 @@ describe("AddAutoRouterTab", () => {
expect(labels).toEqual(["Anthropic Family", "OpenAI Family", "Custom Configuration"]);
});
+ describe("routing test", () => {
+ it("offers no routing test until the config is complete enough to route", async () => {
+ const actual = await vi.importActual<typeof import("./build_complexity_router_config")>(
+ "./build_complexity_router_config",
+ );
+ vi.mocked(getMissingTiersError).mockImplementation(actual.getMissingTiersError);
+
+ renderWithProviders(<Harness />);
+
+ expect(screen.getByTestId("auto-router-test-routing-btn")).toBeDisabled();
+ });
+
+ it("routes a prompt through the config on screen without creating the router", async () => {
+ const user = userEvent.setup();
+ vi.mocked(getMissingTiersError).mockReturnValue(null);
+ vi.mocked(testAutoRouterRouting).mockResolvedValue({
+ status: "success",
+ result: {
+ routed_model: "claude-opus-5",
+ routed_model_configured: true,
+ routing_decision: { routed_model: "claude-opus-5", tier: "COMPLEX", cause: "literal_keyword_match" },
+ },
+ });
+
+ renderWithProviders(<Harness />);
+ await user.type(screen.getByPlaceholderText(/smart_router/i), "keyword-router");
+ expandDetailedConfiguration();
+ await user.click(screen.getByText("Advanced: Keyword/Semantic Matching"));
+ await user.click(screen.getByRole("button", { name: /add keyword rule/i }));
+ const keywordsField = screen.getByText("Keywords 1").closest("div") as HTMLElement;
+ await user.type(within(keywordsField).getByRole("combobox"), "invoice{enter}");
+
+ await user.click(screen.getByTestId("auto-router-test-routing-btn"));
+ await user.type(await screen.findByTestId("auto-router-routing-test-prompt"), "reconcile this invoice");
+ await user.click(screen.getByTestId("auto-router-routing-test-send"));
+
+ await waitFor(() => expect(testAutoRouterRouting).toHaveBeenCalled());
+ const [accessToken, request] = vi.mocked(testAutoRouterRouting).mock.calls.at(-1)!;
+ expect(accessToken).toBe("token");
+ expect(request.prompt).toBe("reconcile this invoice");
+ expect(request.router_name).toBe("keyword-router");
+ expect(request.complexity_router_config).toMatchObject({
+ keyword_tier_rules: [{ keywords: ["invoice"], tier: "COMPLEX" }],
+ });
+ expect(await screen.findByTestId("auto-router-routing-test-routed-model")).toHaveTextContent("claude-opus-5");
+ expect(handleAddAutoRouterSubmit).not.toHaveBeenCalled();
+ });
+
+ it("forgets the last prompt and result when the modal is reopened", async () => {
+ const user = userEvent.setup();
+ vi.mocked(getMissingTiersError).mockReturnValue(null);
+ vi.mocked(testAutoRouterRouting).mockResolvedValue({
+ status: "success",
+ result: {
+ routed_model: "claude-opus-5",
+ routed_model_configured: true,
+ routing_decision: { routed_model: "claude-opus-5", tier: "COMPLEX", cause: "heuristic_scorer" },
+ },
+ });
+
+ renderWithProviders(<Harness />);
+ await user.click(screen.getByTestId("auto-router-test-routing-btn"));
+ await user.type(await screen.findByTestId("auto-router-routing-test-prompt"), "reconcile this invoice");
+ await user.click(screen.getByTestId("auto-router-routing-test-send"));
+ expect(await screen.findByTestId("auto-router-routing-test-result")).toBeInTheDocument();
+
+ await user.click(screen.getAllByRole("button", { name: /^close$/i }).at(-1)!);
+ await user.click(screen.getByTestId("auto-router-test-routing-btn"));
+
+ expect(await screen.findByTestId("auto-router-routing-test-prompt")).toHaveValue("");
+ expect(screen.queryByTestId("auto-router-routing-test-result")).not.toBeInTheDocument();
+ });
+ });
+
describe("template presets", () => {
// Opens the dropdown once, then waits out the useQuery load: an open antd Select re-renders its
// already-mounted options in place as state changes, so polling only re-reads the DOM here.
diff --git a/ui/litellm-dashboard/src/components/add_model/add_auto_router_tab.tsx b/ui/litellm-dashboard/src/components/add_model/add_auto_router_tab.tsx
index 73c0254fc42..673f0f9e6da 100644
--- a/ui/litellm-dashboard/src/components/add_model/add_auto_router_tab.tsx
+++ b/ui/litellm-dashboard/src/components/add_model/add_auto_router_tab.tsx
@@ -20,6 +20,7 @@ import { KeywordTierRule } from "./KeywordTierRules";
import { DEFAULT_ESCALATION_KEYWORDS } from "./EscalationKeywords";
import { DEFAULT_MATCH_THRESHOLD } from "./SemanticKeywordMatching";
import {
+ BuildComplexityRouterConfigParams,
buildComplexityRouterConfig,
getKeywordTierRulesError,
getMissingTiersError,
@@ -27,6 +28,7 @@ import {
} from "./build_complexity_router_config";
import { buildAutoRouterTestTargets, AutoRouterTestTarget } from "./build_auto_router_test_targets";
import AutoRouterConnectionTest from "./auto_router_connection_test";
+import AutoRouterRoutingTest from "./AutoRouterRoutingTest";
import NotificationManager from "../molecules/notifications_manager";
import {
getAllPresets,
@@ -80,6 +82,9 @@ const isPresetHintAlarming = (availability: PresetAvailability): boolean => avai
// this is resolved once at import time rather than re-called from inside the component every render.
const presets = getAllPresets();
+const resolveDefaultModel = (tiers: ComplexityTiers): string | undefined =>
+ tiers.MEDIUM[0] || tiers.SIMPLE[0] || tiers.COMPLEX[0] || tiers.REASONING[0];
+
// A one-line summary of what's configured, shown when the detailed section is collapsed so a
// caller can see the shape of the config without opening it.
const tierConfigSummary = (tiers: ComplexityTiers): string => {
@@ -126,6 +131,7 @@ const AddAutoRouterTab: React.FC<AddAutoRouterTabProps> = ({
// change it" affordance. A caller can always toggle it manually at any point.
const [detailsExpanded, setDetailsExpanded] = useState<boolean>(false);
+ const [isRoutingTestVisible, setIsRoutingTestVisible] = useState<boolean>(false);
const [isTestModalVisible, setIsTestModalVisible] = useState<boolean>(false);
const [isTestingConnection, setIsTestingConnection] = useState<boolean>(false);
const [connectionTestId, setConnectionTestId] = useState<number>(0);
@@ -224,21 +230,29 @@ const AddAutoRouterTab: React.FC<AddAutoRouterTabProps> = ({
getKeywordTierRulesError(keywordTierRules) ??
getReferencedModelsError(referencedModelsParams, availableModelSet);
+ const complexityRouterConfigParams: BuildComplexityRouterConfigParams = {
+ tiers: complexityRouterConfig.tiers,
+ classifierType: complexityRouterConfig.classifier_type,
+ classifierLlmConfig: complexityRouterConfig.classifier_llm_config,
+ classifierContextWindowSize: complexityRouterConfig.classifier_context_window_size,
+ classifierContextPerTurnChars: complexityRouterConfig.classifier_context_per_turn_chars,
+ classifierContextIncludeAssistantTurns: complexityRouterConfig.classifier_context_include_assistant_turns,
+ sessionAffinity: complexityRouterConfig.session_affinity ?? DEFAULT_SESSION_AFFINITY,
+ customTechnicalKeywords,
+ keywordTierRules,
+ semanticMatchingEnabled,
+ embeddingModel,
+ matchThreshold,
+ escalationKeywords,
+ adaptive: complexityRouterConfig.adaptive ?? false,
+ adaptiveWeights: complexityRouterConfig.adaptive_weights ?? DEFAULT_ADAPTIVE_WEIGHTS,
+ tierDistancePenalty: complexityRouterConfig.tier_distance_penalty ?? DEFAULT_TIER_DISTANCE_PENALTY,
+ adaptiveEligible: complexityRouterConfig.adaptive_eligible ?? "all",
+ returnRawModelName: complexityRouterConfig.return_raw_model_name ?? false,
+ };
+
const submitRecommendedRouter = (name: string) => {
- const {
- tiers,
- classifier_type: classifierType,
- classifier_llm_config: classifierLlmConfig,
- classifier_context_window_size: classifierContextWindowSize,
- classifier_context_per_turn_chars: classifierContextPerTurnChars,
- classifier_context_include_assistant_turns: classifierContextIncludeAssistantTurns,
- session_affinity: sessionAffinity = DEFAULT_SESSION_AFFINITY,
- adaptive = false,
- adaptive_weights: adaptiveWeights = DEFAULT_ADAPTIVE_WEIGHTS,
- tier_distance_penalty: tierDistancePenalty = DEFAULT_TIER_DISTANCE_PENALTY,
- adaptive_eligible: adaptiveEligible = "all",
- return_raw_model_name: returnRawModelName = false,
- } = complexityRouterConfig;
+ const { tiers, classifierType, classifierLlmConfig } = complexityRouterConfigParams;
const missingTiersError = getMissingTiersError(tiers);
if (missingTiersError) {
@@ -278,7 +292,7 @@ const AddAutoRouterTab: React.FC<AddAutoRouterTabProps> = ({
return;
}
- const defaultModel = tiers.MEDIUM[0] || tiers.SIMPLE[0] || tiers.COMPLEX[0] || tiers.REASONING[0];
+ const defaultModel = resolveDefaultModel(tiers);
form.setFieldsValue({
custom_llm_provider: "auto_router",
@@ -290,27 +304,6 @@ const AddAutoRouterTab: React.FC<AddAutoRouterTabProps> = ({
form
.validateFields(requiresTeamScope ? ["auto_router_name", "team_id"] : ["auto_router_name"])
.then((values) => {
- const complexityRouterConfigParams = {
- tiers,
- classifierType,
- classifierLlmConfig,
- classifierContextWindowSize,
- classifierContextPerTurnChars,
- classifierContextIncludeAssistantTurns,
- sessionAffinity,
- customTechnicalKeywords,
- keywordTierRules,
- semanticMatchingEnabled,
- embeddingModel,
- matchThreshold,
- escalationKeywords,
- adaptive,
- adaptiveWeights,
- tierDistancePenalty,
- adaptiveEligible,
- returnRawModelName,
- };
-
const submitValues = {
...values,
auto_router_name: name,
@@ -515,6 +508,15 @@ const AddAutoRouterTab: React.FC<AddAutoRouterTabProps> = ({
<Typography.Link href="https://github.com/BerriAI/litellm/issues">Need Help?</Typography.Link>
</Tooltip>
<div className="space-x-2">
+ <Tooltip title={submitBlockedReason}>
+ <Button
+ data-testid="auto-router-test-routing-btn"
+ disabled={submitBlockedReason !== null}
+ onClick={() => setIsRoutingTestVisible(true)}
+ >
+ Test Routing
+ </Button>
+ </Tooltip>
{
<Button
data-testid="auto-router-test-connect-btn"
@@ -540,6 +542,29 @@ const AddAutoRouterTab: React.FC<AddAutoRouterTabProps> = ({
</Form>
</Card>
+ <Modal
+ title="Test Routing"
+ open={isRoutingTestVisible}
+ destroyOnHidden
+ onCancel={() => setIsRoutingTestVisible(false)}
+ footer={[
+ <Button key="close" onClick={() => setIsRoutingTestVisible(false)}>
+ Close
+ </Button>,
+ ]}
+ width={760}
+ >
+ {isRoutingTestVisible && (
+ <AutoRouterRoutingTest
+ accessToken={accessToken}
+ config={buildComplexityRouterConfig(complexityRouterConfigParams)}
+ defaultModel={resolveDefaultModel(complexityRouterConfig.tiers)}
+ routerName={form.getFieldValue("auto_router_name")}
+ teamId={requiresTeamScope ? form.getFieldValue("team_id") : undefined}
+ />
+ )}
+ </Modal>
+
<Modal
title="Connection Test Results"
open={isTestModalVisible}
diff --git a/ui/litellm-dashboard/src/components/add_model/build_auto_router_routing_test_request.test.ts b/ui/litellm-dashboard/src/components/add_model/build_auto_router_routing_test_request.test.ts
new file mode 100644
index 00000000000..6678a3585c0
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/add_model/build_auto_router_routing_test_request.test.ts
@@ -0,0 +1,41 @@
+import { buildAutoRouterRoutingTestRequest } from "./build_auto_router_routing_test_request";
+import { ComplexityRouterConfigPayload } from "./build_complexity_router_config";
+
+const CONFIG = {
+ tiers: { SIMPLE: ["cheap"], MEDIUM: ["mid"], COMPLEX: ["strong"], REASONING: ["o3"] },
+ classifier_type: "heuristic",
+} as unknown as ComplexityRouterConfigPayload;
+
+const params = {
+ prompt: "what is 2+2",
+ config: CONFIG,
+ defaultModel: "mid",
+ routerName: "my-router",
+ teamId: "team-1",
+};
+
+describe("buildAutoRouterRoutingTestRequest", () => {
+ it("sends the prompt with the config being edited", () => {
+ const request = buildAutoRouterRoutingTestRequest(params);
+
+ expect(request.prompt).toBe("what is 2+2");
+ expect(request.complexity_router_config).toBe(CONFIG);
+ expect(request.default_model).toBe("mid");
+ expect(request.router_name).toBe("my-router");
+ expect(request.team_id).toBe("team-1");
+ });
+
+ it("trims the router name a caller is midway through typing", () => {
+ expect(buildAutoRouterRoutingTestRequest({ ...params, routerName: " my-router " }).router_name).toBe("my-router");
+ });
+
+ it("omits optional fields a caller has not filled in", () => {
+ const blankParams = { ...params, defaultModel: undefined, routerName: " ", teamId: undefined };
+
+ const request = buildAutoRouterRoutingTestRequest(blankParams);
+
+ expect(request).not.toHaveProperty("default_model");
+ expect(request).not.toHaveProperty("router_name");
+ expect(request).not.toHaveProperty("team_id");
+ });
+});
diff --git a/ui/litellm-dashboard/src/components/add_model/build_auto_router_routing_test_request.ts b/ui/litellm-dashboard/src/components/add_model/build_auto_router_routing_test_request.ts
new file mode 100644
index 00000000000..219dcbf6070
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/add_model/build_auto_router_routing_test_request.ts
@@ -0,0 +1,24 @@
+import { AutoRouterRoutingTestRequest } from "../networking";
+import { ComplexityRouterConfigPayload } from "./build_complexity_router_config";
+
+export interface BuildAutoRouterRoutingTestRequestParams {
+ prompt: string;
+ config: ComplexityRouterConfigPayload;
+ defaultModel: string | undefined;
+ routerName: string | undefined;
+ teamId: string | undefined;
+}
+
+export const buildAutoRouterRoutingTestRequest = ({
+ prompt,
+ config,
+ defaultModel,
+ routerName,
+ teamId,
+}: BuildAutoRouterRoutingTestRequestParams): AutoRouterRoutingTestRequest => ({
+ prompt,
+ complexity_router_config: config,
+ ...(defaultModel ? { default_model: defaultModel } : {}),
+ ...(routerName?.trim() ? { router_name: routerName.trim() } : {}),
+ ...(teamId ? { team_id: teamId } : {}),
+});
diff --git a/ui/litellm-dashboard/src/components/networking.tsx b/ui/litellm-dashboard/src/components/networking.tsx
index 558484e8f92..4a9a41d1cbe 100644
--- a/ui/litellm-dashboard/src/components/networking.tsx
+++ b/ui/litellm-dashboard/src/components/networking.tsx
@@ -38,7 +38,14 @@ import type {
CoordinationRedisTestResponse,
} from "@/app/(dashboard)/caching/_components/coordination_redis_settings/types";
import { MCP_TOOLS_PREVIEW_FORBIDDEN_MESSAGE } from "./mcp_tools/constants";
-import { createApiClient, deriveErrorMessage, unwrapProxyErrorMessage } from "@/lib/http/client";
+import type { ComplexityRouterConfigPayload } from "./add_model/build_complexity_router_config";
+import type { RoutingDecision } from "./view_logs/LogDetailsDrawer/RoutingDecisionCard";
+import {
+ createApiClient,
+ deriveErrorMessage,
+ extractProxyErrorMessage,
+ unwrapProxyErrorMessage,
+} from "@/lib/http/client";
import { resolveApiBase } from "@/lib/http/resolveApiBase";
import {
registerAuthHeaderNameGetter,
@@ -2291,6 +2298,39 @@ export const testModelGroupConnection = async (
}
};
+export interface AutoRouterRoutingTestRequest {
+ prompt: string;
+ complexity_router_config: ComplexityRouterConfigPayload;
+ default_model?: string;
+ router_name?: string;
+ team_id?: string;
+}
+
+export interface AutoRouterRoutingTestResult {
+ routed_model: string;
+ routed_model_configured: boolean;
+ routing_decision: RoutingDecision;
+}
+
+export type AutoRouterRoutingTestResponse =
+ | { status: "success"; result: AutoRouterRoutingTestResult }
+ | { status: "error"; error: string };
+
+export const testAutoRouterRouting = async (
+ accessToken: string,
+ request: AutoRouterRoutingTestRequest,
+): Promise<AutoRouterRoutingTestResponse> => {
+ try {
+ const result = await apiClient.post<AutoRouterRoutingTestResult>("/auto_router/test_routing", {
+ accessToken,
+ body: request,
+ });
+ return { status: "success", result };
+ } catch (error) {
+ return { status: "error", error: extractProxyErrorMessage(error) };
+ }
+};
+
// ... existing code ...
export const keyInfoV1Call = async (accessToken: string, key: string) => {
try {
diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.ts
index 9230f694c7b..5a36f551720 100644
--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts
+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts
@@ -760,6 +760,44 @@ export interface paths {
patch?: never;
trace?: never;
};
+ "/auto_router/test_routing": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ /**
+ * Preview Auto Router Routing
+ * @description Route a single prompt through a complexity-router config and report where it landed.
+ *
+ * Answers "which model would this prompt get?" for a config that only exists in a form,
+ * so an auto router can be checked before it is created. The prompt is classified by the
+ * same pre-routing hook a live request runs, then dropped: nothing is sent to the model it
+ * routed to, and no auto router is created. A heuristic config therefore spends nothing, while
+ * an `llm` classifier or semantic keyword matching bills its classifier/embedding call to the
+ * calling key, like Test Connection does.
+ *
+ * **Example Request:**
+ * ```json
+ * {
+ * "prompt": "think step by step about how to shard this table",
+ * "complexity_router_config": {
+ * "tiers": {"SIMPLE": ["gpt-4o-mini"], "REASONING": ["o3"]},
+ * "classifier_type": "heuristic"
+ * }
+ * }
+ * ```
+ */
+ post: operations["preview_auto_router_routing_auto_router_test_routing_post"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/azure/{endpoint}": {
parameters: {
query?: never;
@@ -20801,6 +20839,19 @@ export interface components {
/** Results */
results: components["schemas"]["TagActiveUsersResponse"][];
};
+ /** AdaptiveRouterWeights */
+ AdaptiveRouterWeights: {
+ /**
+ * Cost
+ * @default 0.3
+ */
+ cost: number;
+ /**
+ * Quality
+ * @default 0.7
+ */
+ quality: number;
+ };
/** AddTeamCallback */
AddTeamCallback: {
/** Callback Name */
@@ -21201,6 +21252,53 @@ export interface components {
[key: string]: unknown;
} | null;
};
+ /**
+ * AutoRouterRoutingTestRequest
+ * @description A single prompt to classify against a complexity-router config that need not be saved yet.
+ */
+ AutoRouterRoutingTestRequest: {
+ /** @description The complexity router config to route against, in the shape /model/new accepts */
+ complexity_router_config: components["schemas"]["RequestComplexityRouterConfig"];
+ /**
+ * Default Model
+ * @description Model to route to when no tier resolves, i.e. complexity_router_default_model
+ */
+ default_model?: string | null;
+ /**
+ * Prompt
+ * @description The prompt to route, as an end user would send it
+ */
+ prompt: string;
+ /**
+ * Router Name
+ * @description Name reported as the router in the routing decision. Display only
+ * @default auto_router_routing_test
+ */
+ router_name: string;
+ /**
+ * Team Id
+ * @description Team the router is being created for. Required for a team admin, who may only test their own team's routers
+ */
+ team_id?: string | null;
+ };
+ /**
+ * AutoRouterRoutingTestResponse
+ * @description Where one prompt would have been routed, and why.
+ */
+ AutoRouterRoutingTestResponse: {
+ /**
+ * Routed Model
+ * @description The model group the router picked
+ */
+ routed_model: string;
+ /**
+ * Routed Model Configured
+ * @description Whether routed_model is a model group this proxy actually serves
+ */
+ routed_model_configured: boolean;
+ /** @description The decision record this request would have written to its log row */
+ routing_decision: components["schemas"]["StandardLoggingRoutingDecision"];
+ };
/** BaseLitellmParams */
"BaseLitellmParams-Input": {
/**
@@ -22748,6 +22846,23 @@ export interface components {
/** Enabled */
enabled: boolean;
};
+ /**
+ * ClassifierLLMConfig
+ * @description Configuration for the LLM-based complexity classifier.
+ */
+ ClassifierLLMConfig: {
+ /**
+ * Model
+ * @description Model name (from the router's model_list) to call for classification
+ */
+ model: string;
+ /**
+ * Timeout Ms
+ * @description Timeout budget for the classification call, in milliseconds
+ * @default 3000
+ */
+ timeout_ms: number;
+ };
/**
* CloudZeroExportRequest
* @description Request model for CloudZero export operations
@@ -22880,6 +22995,12 @@ export interface components {
*/
timezone?: string | null;
};
+ /**
+ * ComplexityTier
+ * @description Complexity tiers for routing decisions.
+ * @enum {string}
+ */
+ ComplexityTier: "SIMPLE" | "MEDIUM" | "COMPLEX" | "REASONING";
/**
* ComplianceCheckRequest
* @description Request payload for compliance check endpoints.
@@ -25263,6 +25384,19 @@ export interface components {
/** Tpm Limit Type */
tpm_limit_type?: ("guaranteed_throughput" | "best_effort_throughput" | "dynamic") | null;
};
+ /**
+ * KeywordTierRule
+ * @description A deterministic override: if any keyword matches, route to this tier.
+ */
+ KeywordTierRule: {
+ /**
+ * Keywords
+ * @description Keywords/phrases that trigger this rule (lexical or semantic match)
+ */
+ keywords: string[];
+ /** @description Tier to route to when this rule matches */
+ tier: components["schemas"]["ComplexityTier"];
+ };
/** LakeraCategoryThresholds */
LakeraCategoryThresholds: {
/** Jailbreak */
@@ -31092,6 +31226,173 @@ export interface components {
/** Review Notes */
review_notes?: string | null;
};
+ /**
+ * RequestComplexityRouterConfig
+ * @description The part of a complexity-router config a request can carry.
+ *
+ * `plugins` holds live RoutingPlugin objects, which no JSON body can express and which have no
+ * OpenAPI schema, so it is closed off here rather than left as an arbitrary-type field.
+ */
+ RequestComplexityRouterConfig: {
+ /**
+ * Adaptive
+ * @description Enable adaptive bandit selection with soft complexity floors
+ * @default false
+ */
+ adaptive: boolean;
+ /**
+ * Adaptive Eligible
+ * @description When adaptive=True: 'all' scores every pool model with a tier-distance penalty (soft floors); 'classified_tier' Thompson-samples only inside the classified tier's pool
+ * @default all
+ * @enum {string}
+ */
+ adaptive_eligible: "all" | "classified_tier";
+ /** @description Quality vs cost weights for adaptive selection (used when adaptive=True) */
+ adaptive_weights?: components["schemas"]["AdaptiveRouterWeights"];
+ /**
+ * Classifier Context Include Assistant Turns
+ * @description Include assistant turns in the classifier context window, so difficulty stated by the model rather than by the user stays visible: a plan the assistant calls complex, which the user approves with 'yes', is classified on the work being approved instead of on the word 'yes'. When enabled, classifier_context_window_size counts the last N turns of the conversation across both roles rather than the last N user turns, and assistant text is sent to the classifier model, which may be a different deployment or provider than the routed completion model. Assistant replies share classifier_context_per_turn_chars with user turns, so raise it if replies are truncated before the part that carries the difficulty. Off by default because enabling it shifts tier decisions, and therefore spend, for an already-deployed router. Only applies when classifier_type is 'llm'.
+ * @default false
+ */
+ classifier_context_include_assistant_turns: boolean;
+ /**
+ * Classifier Context Per Turn Chars
+ * @description Maximum character length for each prior turn's text in the classifier context window. Turns exceeding this are truncated. Only applies when classifier_type is 'llm'.
+ * @default 200
+ */
+ classifier_context_per_turn_chars: number;
+ /**
+ * Classifier Context Window Size
+ * @description Number of prior user turns (tool output and harness reminders excluded) to include as context in the LLM classifier prompt, so a follow-up like 'now do the same for the streaming path' is classified against what it refers to. Counts turns of both roles when classifier_context_include_assistant_turns is enabled. These turns are sent to the classifier model, which may be a different deployment or provider than the routed completion model; that call already carries the current user ask and the caller's system prompt in full. Set to 0 to send neither prior turns nor any conversation context beyond the current ask. Only applies when classifier_type is 'llm'.
+ * @default 3
+ */
+ classifier_context_window_size: number;
+ /** @description Configuration for the LLM classifier; required when classifier_type is 'llm' */
+ classifier_llm_config?: components["schemas"]["ClassifierLLMConfig"] | null;
+ /**
+ * Classifier Type
+ * @description Classification strategy: local regex/keyword scoring, or an LLM call
+ * @default heuristic
+ * @enum {string}
+ */
+ classifier_type: "heuristic" | "llm";
+ /**
+ * Code Keywords
+ * @description Keywords indicating code-related content
+ */
+ code_keywords?: string[] | null;
+ /**
+ * Custom Technical Keywords
+ * @description Domain-specific technical keywords appended to the effective base list (technical_keywords if set, otherwise DEFAULT_TECHNICAL_KEYWORDS). Order is preserved; duplicates are removed case-insensitively against the base list and within this list.
+ */
+ custom_technical_keywords?: string[] | null;
+ /**
+ * Default Model
+ * @description Default model to use if tier cannot be determined
+ */
+ default_model?: string | null;
+ /**
+ * Dimension Weights
+ * @description Weights for each scoring dimension
+ */
+ dimension_weights?: {
+ [key: string]: number;
+ };
+ /**
+ * Embedding Model
+ * @description Embedding model (LiteLLM model name) used when semantic_keyword_matching is enabled
+ */
+ embedding_model?: string | null;
+ /**
+ * Escalation Keywords
+ * @description Case-sensitive phrases a user can include to force a bump to the next-higher complexity tier when they aren't satisfied with results (they can force a stronger model, but not choose which one). Defaults to ['LITELLM ESCALATE'] when unset; set to an empty list to disable.
+ */
+ escalation_keywords?: string[] | null;
+ /**
+ * Keyword Tier Rules
+ * @description Rules that force a specific tier when their keywords match the prompt
+ */
+ keyword_tier_rules?: components["schemas"]["KeywordTierRule"][] | null;
+ /**
+ * Match Threshold
+ * @description Minimum cosine similarity for a semantic keyword match
+ * @default 0.5
+ */
+ match_threshold: number;
+ /**
+ * Plugins
+ * @description Not settable over HTTP; routing plugins are runtime objects
+ */
+ plugins?: null;
+ /**
+ * Reasoning Keywords
+ * @description Keywords indicating reasoning-required content
+ */
+ reasoning_keywords?: string[] | null;
+ /**
+ * Return Raw Model Name
+ * @description Return the resolved raw model name in the response model field instead of the client-requested complexity-router alias
+ * @default false
+ */
+ return_raw_model_name: boolean;
+ /**
+ * Semantic Keyword Matching
+ * @description Match keyword_tier_rules by embedding similarity instead of literal text
+ * @default false
+ */
+ semantic_keyword_matching: boolean;
+ /**
+ * Session Affinity
+ * @description When True and a session_id is resolvable on the request, pin the model chosen on the session's first turn and reuse it for every later turn, skipping re-classification. Off by default so every turn is classified on its own merits and routed to the cheapest adequate tier. Set True to keep a multi-turn session on one model, which preserves provider prompt caches and avoids cross-model conversation-history errors.
+ * @default false
+ */
+ session_affinity: boolean;
+ /**
+ * Session Affinity Ttl Seconds
+ * @description TTL for the session affinity pin; refreshed on every cache hit
+ * @default 3600
+ */
+ session_affinity_ttl_seconds: number;
+ /**
+ * Simple Keywords
+ * @description Keywords indicating simple/basic queries
+ */
+ simple_keywords?: string[] | null;
+ /**
+ * Technical Keywords
+ * @description Keywords indicating technical content
+ */
+ technical_keywords?: string[] | null;
+ /**
+ * Tier Boundaries
+ * @description Score boundaries between tiers
+ */
+ tier_boundaries?: {
+ [key: string]: number;
+ };
+ /**
+ * Tier Distance Penalty
+ * @description Score penalty per tier-step away from the classified tier when adaptive=True
+ * @default 0.5
+ */
+ tier_distance_penalty: number;
+ /**
+ * Tiers
+ * @description Mapping of complexity tiers to a model or model pool. A list is randomly picked from when adaptive=False, and used as a soft-floor home pool when adaptive=True
+ */
+ tiers?: {
+ [key: string]: string | string[];
+ };
+ /**
+ * Token Thresholds
+ * @description Token count thresholds for simple/complex classification
+ */
+ token_thresholds?: {
+ [key: string]: number;
+ };
+ } & {
+ [key: string]: unknown;
+ };
/** ResetSpendRequest */
ResetSpendRequest: {
/** Reset To */
@@ -31815,6 +32116,58 @@ export interface components {
*/
total_tokens: number;
};
+ /**
+ * StandardLoggingRoutingDecision
+ * @description Per-request provenance for a pre-routing strategy (auto-router) decision.
+ */
+ StandardLoggingRoutingDecision: {
+ /**
+ * Cause
+ * @enum {string}
+ */
+ cause?: "heuristic_scorer" | "reasoning_override" | "llm_classifier" | "literal_keyword_match" | "semantic_keyword_match" | "session_affinity_pin" | "session_affinity_escalation" | "default_fallback" | "keyword" | "quality_tier" | "bandit";
+ /** Classifier Model */
+ classifier_model?: string;
+ /** Conversation Continuing */
+ conversation_continuing?: boolean;
+ /** Escalated */
+ escalated?: boolean;
+ /** Escalation Keyword */
+ escalation_keyword?: string;
+ /** Matched Keyword */
+ matched_keyword?: string;
+ /** Request Type */
+ request_type?: string;
+ /** Routed Model */
+ routed_model?: string;
+ /** Router Model Name */
+ router_model_name?: string;
+ /**
+ * Router Type
+ * @enum {string}
+ */
+ router_type?: "complexity" | "adaptive" | "quality";
+ /** Score */
+ score?: number;
+ /** Signals */
+ signals?: string[];
+ /** Tier */
+ tier?: string;
+ tier_boundaries?: components["schemas"]["StandardLoggingRoutingDecisionTierBoundaries"];
+ };
+ /**
+ * StandardLoggingRoutingDecisionTierBoundaries
+ * @description Snapshot of the complexity scorer's tier boundaries at decision time, so a
+ * historical spend log row stays explainable after the router config changes.
+ */
+ StandardLoggingRoutingDecisionTierBoundaries: {
+ /** Complex Reasoning */
+ complex_reasoning: number;
+ /** Medium Complex */
+ medium_complex: number;
+ /** Simple Medium */
+ simple_medium: number;
+ };
/**
* SuccessfulKeyUpdate
* @description Successfully updated key with its updated information
@@ -35951,6 +36304,39 @@ export interface operations {
};
};
};
+ preview_auto_router_routing_auto_router_test_routing_post: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody: {
+ content: {
+ "application/json": components["schemas"]["AutoRouterRoutingTestRequest"];
+ };
+ };
+ responses: {
+ /** @description Successful Response */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["AutoRouterRoutingTestResponse"];
+ };
+ };
+ /** @description Validation Error */
+ 422: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["HTTPValidationError"];
+ };
+ };
+ };
+ };
azure_proxy_route_azure__endpoint__get: {
parameters: {
query?: never;