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
fix(complexity_router): review hardening - blank keywords, router registry eviction, edit-modal controls
Abhimanyu Kapur952127647c10
diff --git a/litellm/proxy/dev_config.yaml b/litellm/proxy/dev_config.yamlindex 65a4b8e7cbf..4e9c710d446 100644--- a/litellm/proxy/dev_config.yaml+++ b/litellm/proxy/dev_config.yaml@@ -33,6 +33,12 @@ model_list:model: anthropic/claude-sonnet-5api_key: os.environ/ANTHROPIC_API_KEY+ # ---------- Embeddings (for complexity router semantic keyword matching) ----------+ - model_name: voyage-4-large+ litellm_params:+ model: voyage/voyage-4-large+ api_key: os.environ/VOYAGE_API_KEY+# ---------- Bedrock Invoke ----------- model_name: bedrock-invoke-haiku-4-5litellm_params:diff --git a/litellm/proxy/management_endpoints/model_management_endpoints.py b/litellm/proxy/management_endpoints/model_management_endpoints.pyindex 23a3b3ce4f2..18d95d4e083 100644--- a/litellm/proxy/management_endpoints/model_management_endpoints.py+++ b/litellm/proxy/management_endpoints/model_management_endpoints.py@@ -1138,6 +1138,8 @@ async def delete_model(if deleted_name is not None and deleted_model.startswith("auto_router/"):llm_router.auto_routers.pop(deleted_name, None)llm_router.complexity_routers.pop(deleted_name, None)+ llm_router.adaptive_routers.pop(deleted_name, None)+ llm_router.quality_routers.pop(deleted_name, None)# Runs after the row delete so the sibling check sees post-delete state.if model_params.model_info.team_id is not None:@@ -1741,12 +1743,15 @@ async def clear_cache():for model_id in db_model_ids:llm_router.delete_deployment(id=model_id)- # Clear only DB-backed auto/complexity routers, keyed by model_name, so the reload- # below rebuilds them fresh. A blanket .clear() would also drop config-defined+ # Clear only DB-backed auto-router-family entries, keyed by model_name, so the+ # reload below rebuilds them fresh. A blanket .clear() would also drop config-defined# routers, which are never re-added below (add_deployment only reloads DB models),# leaving them permanently unroutable until a full proxy restart for every tenant.# Restrict to deployments whose model is actually an auto_router/* so a config- # router that merely shares a model_name with a regular DB model isn't evicted.+ # router that merely shares a model_name with a regular DB model isn't evicted. The+ # auto_router/ prefix also covers quality_router/ and adaptive_router/, so pop the+ # name from every router registry (no-op where absent); missing quality/adaptive+ # entries would otherwise make init raise "already exists" on reload and abort it.db_router_names = {model.get("model_name")for model in current_models@@ -1756,6 +1761,8 @@ async def clear_cache():for model_name in db_router_names:llm_router.auto_routers.pop(model_name, None)llm_router.complexity_routers.pop(model_name, None)+ llm_router.adaptive_routers.pop(model_name, None)+ llm_router.quality_routers.pop(model_name, None)# Reload only DB modelsawait proxy_config.add_deployment(prisma_client=prisma_client, proxy_logging_obj=proxy_logging_obj)diff --git a/litellm/router_strategy/complexity_router/config.py b/litellm/router_strategy/complexity_router/config.pyindex 9901ae6f813..125de6f7489 100644--- a/litellm/router_strategy/complexity_router/config.py+++ b/litellm/router_strategy/complexity_router/config.py@@ -40,9 +40,15 @@ class KeywordTierRule(BaseModel):)@model_validator(mode="after")- def _validate_non_empty_keywords(self) -> "KeywordTierRule":- if not any(keyword.strip() for keyword in self.keywords):+ def _normalize_keywords(self) -> "KeywordTierRule":+ # Strip and drop blank keywords. An empty/whitespace keyword is a routing foot-gun:+ # _keyword_matches treats "" / " " as a substring that matches essentially every+ # prompt, so a single stray blank would silently force this rule's tier for all+ # traffic. Require at least one real keyword to remain.+ cleaned = [stripped for keyword in self.keywords if (stripped := keyword.strip())]+ if not cleaned:raise ValueError("keyword_tier_rules entries must contain at least one non-empty keyword")+ self.keywords = cleanedreturn selfdiff --git a/tests/test_litellm/proxy/management_endpoints/test_model_management_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_model_management_endpoints.pyindex d9b5745807a..8c6bdefedae 100644--- a/tests/test_litellm/proxy/management_endpoints/test_model_management_endpoints.py+++ b/tests/test_litellm/proxy/management_endpoints/test_model_management_endpoints.py@@ -588,6 +588,48 @@ class TestClearCachePreservesConfigRouters:# The DB model isn't a router, so the same-named config router must be left intact.assert "shared-name" in mock_router.complexity_routers+ @pytest.mark.asyncio+ async def test_db_quality_and_adaptive_routers_are_evicted(self):+ """The auto_router/ prefix also covers quality_router/ and adaptive_router/. Their+ registry entries must be popped too, or reload's init raises 'already exists'+ (quality) or leaves a stale entry (adaptive).+ """+ from litellm.proxy.management_endpoints.model_management_endpoints import clear_cache++ mock_router = MagicMock()+ mock_router.model_list = [+ {+ "model_name": "q1",+ "model_info": {"id": "db-q", "db_model": True},+ "litellm_params": {"model": "auto_router/quality_router/q1"},+ },+ {+ "model_name": "a1",+ "model_info": {"id": "db-a", "db_model": True},+ "litellm_params": {"model": "auto_router/adaptive_router/a1"},+ },+ ]+ mock_router.delete_deployment = MagicMock(return_value=True)+ mock_router.auto_routers = {}+ mock_router.complexity_routers = {}+ mock_router.quality_routers = {"q1": MagicMock()}+ mock_router.adaptive_routers = {"a1": MagicMock()}++ mock_config = MagicMock()+ mock_config.add_deployment = AsyncMock(return_value=True)++ with (+ patch("litellm.proxy.proxy_server.llm_router", mock_router),+ patch("litellm.proxy.proxy_server.proxy_config", mock_config),+ patch("litellm.proxy.proxy_server.prisma_client", MagicMock()),+ patch("litellm.proxy.proxy_server.proxy_logging_obj", MagicMock()),+ patch("litellm.proxy.proxy_server.verbose_proxy_logger"),+ ):+ await clear_cache()++ assert "q1" not in mock_router.quality_routers+ assert "a1" not in mock_router.adaptive_routers+class TestDeleteModelClearsRouterRegistry:"""delete_model must evict the deleted deployment from the auto/complexity router maps,diff --git a/tests/test_litellm/router_strategy/test_complexity_router.py b/tests/test_litellm/router_strategy/test_complexity_router.pyindex fdc12b6f25b..12a8a47e1f1 100644--- a/tests/test_litellm/router_strategy/test_complexity_router.py+++ b/tests/test_litellm/router_strategy/test_complexity_router.py@@ -1836,6 +1836,18 @@ class TestSemanticConfigValidation:with pytest.raises(ValidationError):ComplexityRouterConfig(keyword_tier_rules=[{"keywords": [" ", ""], "tier": "SIMPLE"}])+ def test_keyword_tier_rule_strips_and_drops_blank_keywords(self):+ """Blank keywords mixed with real ones are dropped (not kept), and survivors trimmed.++ A stray "" would otherwise match-all in _keyword_matches and silently force this+ tier for every request.+ """+ config = ComplexityRouterConfig(+ keyword_tier_rules=[{"keywords": ["", " deploy to k8s ", " ", "kubernetes"], "tier": "REASONING"}]+ )+ assert config.keyword_tier_rules is not None+ assert config.keyword_tier_rules[0].keywords == ["deploy to k8s", "kubernetes"]+class _StubEncoder:"""Minimal stand-in for LiteLLMRouterEncoder.aencode_queries, capturing the kwargs it was called with."""diff --git a/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.test.tsx b/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.test.tsxindex 5bfcd94398d..a433808085b 100644--- a/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.test.tsx+++ b/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.test.tsx@@ -143,6 +143,16 @@ describe("ComplexityRouterConfig", () => {expect(screen.getByText("No keyword tier overrides configured")).toBeInTheDocument();});+ it("hides the keyword-tier and semantic sections when their change handlers are absent (edit modal)", () => {+ // The edit-auto-router modal renders ComplexityRouterConfig without these handlers;+ // the sections must stay hidden rather than render interactive-but-dead controls.+ renderWithProviders(<ComplexityRouterConfig modelInfo={mockModelInfo} value={defaultValue} onChange={vi.fn()} />);+ expect(screen.queryByText("Keyword Tier Overrides")).not.toBeInTheDocument();+ expect(screen.queryByText("Semantic keyword matching")).not.toBeInTheDocument();+ // Core tier config still renders.+ expect(screen.getByText("Complexity Tier Configuration")).toBeInTheDocument();+ });+it("should call onKeywordTierRulesChange with a new rule when 'Add keyword rule' is clicked", async () => {const user = userEvent.setup();const onKeywordTierRulesChange = vi.fn();diff --git a/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.tsx b/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.tsxindex ae2e03e576f..555648db8ad 100644--- a/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.tsx+++ b/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.tsx@@ -77,9 +77,9 @@ const ComplexityRouterConfig: React.FC<ComplexityRouterConfigProps> = ({customTechnicalKeywords,onCustomTechnicalKeywordsChange,keywordTierRules = [],- onKeywordTierRulesChange = () => {},+ onKeywordTierRulesChange,semanticMatchingEnabled = false,- onSemanticMatchingEnabledChange = () => {},+ onSemanticMatchingEnabledChange,embeddingModel,onEmbeddingModelChange = () => {},matchThreshold = 0.5,@@ -302,21 +302,30 @@ const ComplexityRouterConfig: React.FC<ComplexityRouterConfigProps> = ({</ul></Card>- <Divider />-- <KeywordTierRules rules={keywordTierRules} onChange={onKeywordTierRulesChange} />+ {/* Keyword-tier and semantic sections only render when their change handlers are+ wired (the add-router flow). The edit-auto-router modal doesn't pass them yet, so+ they stay hidden there rather than rendering interactive-but-dead controls. */}+ {onKeywordTierRulesChange && (+ <>+ <Divider />+ <KeywordTierRules rules={keywordTierRules} onChange={onKeywordTierRulesChange} />+ </>+ )}- <Divider />-- <SemanticKeywordMatching- enabled={semanticMatchingEnabled}- onEnabledChange={onSemanticMatchingEnabledChange}- embeddingModel={embeddingModel}- onEmbeddingModelChange={onEmbeddingModelChange}- matchThreshold={matchThreshold}- onMatchThresholdChange={onMatchThresholdChange}- modelInfo={modelInfo}- />+ {onSemanticMatchingEnabledChange && (+ <>+ <Divider />+ <SemanticKeywordMatching+ enabled={semanticMatchingEnabled}+ onEnabledChange={onSemanticMatchingEnabledChange}+ embeddingModel={embeddingModel}+ onEmbeddingModelChange={onEmbeddingModelChange}+ matchThreshold={matchThreshold}+ onMatchThresholdChange={onMatchThresholdChange}+ modelInfo={modelInfo}+ />+ </>+ )}</div>);};diff --git a/ui/litellm-dashboard/src/components/add_model/build_complexity_router_config.test.ts b/ui/litellm-dashboard/src/components/add_model/build_complexity_router_config.test.tsindex 250b7d13a5b..3c252646b57 100644--- a/ui/litellm-dashboard/src/components/add_model/build_complexity_router_config.test.ts+++ b/ui/litellm-dashboard/src/components/add_model/build_complexity_router_config.test.ts@@ -99,6 +99,29 @@ describe("buildComplexityRouterConfig", () => {expect(config.custom_technical_keywords).toBeUndefined();expect(config.keyword_tier_rules).toBeUndefined();});++ it("trims keywords and drops rules left empty, so unfilled rows never 400 the backend", () => {+ const params: BuildComplexityRouterConfigParams = {+ ...baseParams,+ keywordTierRules: [+ { id: "r1", keywords: [" deploy to k8s ", "", " "], tier: "REASONING" },+ { id: "r2", keywords: [], tier: "COMPLEX" }, // seeded by "Add keyword rule", never filled+ { id: "r3", keywords: [" "], tier: "SIMPLE" }, // whitespace only+ ],+ };+ const config = buildComplexityRouterConfig(params);+ // r1 keeps only its real keyword (trimmed); r2 and r3 are dropped entirely.+ expect(config.keyword_tier_rules).toEqual([{ keywords: ["deploy to k8s"], tier: "REASONING" }]);+ });++ it("omits keyword_tier_rules entirely when every rule is empty", () => {+ const params: BuildComplexityRouterConfigParams = {+ ...baseParams,+ keywordTierRules: [{ id: "r1", keywords: ["", " "], tier: "COMPLEX" }],+ };+ const config = buildComplexityRouterConfig(params);+ expect(config.keyword_tier_rules).toBeUndefined();+ });});describe("getSemanticConfigError", () => {diff --git a/ui/litellm-dashboard/src/components/add_model/build_complexity_router_config.ts b/ui/litellm-dashboard/src/components/add_model/build_complexity_router_config.tsindex 00cc19cde0c..82ea4f8c12f 100644--- a/ui/litellm-dashboard/src/components/add_model/build_complexity_router_config.ts+++ b/ui/litellm-dashboard/src/components/add_model/build_complexity_router_config.ts@@ -54,17 +54,25 @@ export const buildComplexityRouterConfig = ({semanticMatchingEnabled,embeddingModel,matchThreshold,-}: BuildComplexityRouterConfigParams): ComplexityRouterConfigPayload => ({- tiers,- classifier_type: classifierType,- ...(classifierType === "llm" && classifierLlmConfig && { classifier_llm_config: classifierLlmConfig }),- ...(customTechnicalKeywords.length > 0 && { custom_technical_keywords: customTechnicalKeywords }),- ...(keywordTierRules.length > 0 && {- keyword_tier_rules: keywordTierRules.map((rule) => ({ keywords: rule.keywords, tier: rule.tier })),- }),- ...(semanticMatchingEnabled && {- semantic_keyword_matching: true,- embedding_model: embeddingModel,- match_threshold: matchThreshold,- }),-});+}: BuildComplexityRouterConfigParams): ComplexityRouterConfigPayload => {+ // Trim keywords and drop empty ones; drop any rule left with no keywords. Clicking+ // "Add keyword rule" seeds a rule with an empty keywords list, so without this an+ // unfilled row (common in the heuristic flow, where getSemanticConfigError doesn't run)+ // would ship keyword_tier_rules the backend validator rejects with a 400.+ const cleanedKeywordTierRules = keywordTierRules+ .map((rule) => ({ keywords: rule.keywords.map((k) => k.trim()).filter(Boolean), tier: rule.tier }))+ .filter((rule) => rule.keywords.length > 0);++ return {+ tiers,+ classifier_type: classifierType,+ ...(classifierType === "llm" && classifierLlmConfig && { classifier_llm_config: classifierLlmConfig }),+ ...(customTechnicalKeywords.length > 0 && { custom_technical_keywords: customTechnicalKeywords }),+ ...(cleanedKeywordTierRules.length > 0 && { keyword_tier_rules: cleanedKeywordTierRules }),+ ...(semanticMatchingEnabled && {+ semantic_keyword_matching: true,+ embedding_model: embeddingModel,+ match_threshold: matchThreshold,+ }),+ };+};