Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

fix(ui): reject an auto-router keyword rule left empty instead of dropping it (#35705)

tin-berricb8c734dbe74
diff --git a/litellm/proxy/management_endpoints/model_management_endpoints.py b/litellm/proxy/management_endpoints/model_management_endpoints.py
index 50109b02189..475c5813cdd 100644
--- a/litellm/proxy/management_endpoints/model_management_endpoints.py
+++ b/litellm/proxy/management_endpoints/model_management_endpoints.py
@@ -61,6 +61,7 @@ from litellm.repositories.team_repository import TeamRepository
from litellm.router import Router
from litellm.router_utils.auto_router_model_naming import (
STRATEGY_ROUTER_PARAM_FIELDS,
+ validate_complexity_router_config_write,
validate_strategy_router_model_write,
)
from litellm.types.proxy.management_endpoints.model_management_endpoints import (
@@ -117,11 +118,20 @@ def _strategy_router_write_violation(
An auto-router deployment's ``litellm_params.model`` (``auto_router/...``) is
the discriminator the router loads it by; a write that mangles it makes the
router drop the deployment silently under ``ignore_invalid_deployments``.
- Only writes that supply ``litellm_params.model`` are judged, against the
- merged (stored + incoming) params, so partial patches and restores of an
- already-corrupted row stay legal. Returns the violation, or None.
+ Only writes that supply ``litellm_params.model`` are judged on the naming
+ contract, against the merged (stored + incoming) params, so partial patches
+ and restores of an already-corrupted row stay legal. A config is judged only
+ when the write carries one, for the same reason: a rename must not be held
+ hostage by a stored config it does not touch. Returns the violation, or None.
"""
- if incoming_params is None or incoming_params.model is None:
+ if incoming_params is None:
+ return None
+ config_violation = validate_complexity_router_config_write(
+ complexity_router_config=incoming_params.complexity_router_config
+ )
+ if config_violation is not None:
+ return config_violation
+ if incoming_params.model is None:
return None
present_fields = frozenset(
field
diff --git a/litellm/router_utils/auto_router_model_naming.py b/litellm/router_utils/auto_router_model_naming.py
index b89e1c154f0..51a3f127b29 100644
--- a/litellm/router_utils/auto_router_model_naming.py
+++ b/litellm/router_utils/auto_router_model_naming.py
@@ -62,12 +62,42 @@ def classify_strategy_router_model(model: str) -> StrategyRouterKind | None:
return "semantic"
+def validate_complexity_router_config_write(complexity_router_config: Mapping[str, object] | None) -> str | None:
+ """Reject a complexity config the router would refuse to build a deployment from.
+
+ Parsed with the router's own ``ComplexityRouterConfig`` rather than a copy of
+ its rules, so the boundary rejects exactly what the load would. Plugins are
+ resolved from dotted paths only on the config.yaml path, so a written config
+ reaches this function in the same shape the load hands to the same model.
+ Judged on the config alone: a patch may write one without naming a model, and
+ the stored model is encrypted at rest, so it cannot be classified here.
+ """
+ from pydantic import ValidationError
+
+ from litellm.router_strategy.complexity_router.config import ComplexityRouterConfig
+
+ if complexity_router_config is None:
+ return None
+ try:
+ _ = ComplexityRouterConfig.model_validate(complexity_router_config)
+ except ValidationError as exc:
+ first = exc.errors()[0]
+ location = ".".join(str(part) for part in first.get("loc", ())) or "complexity_router_config"
+ return (
+ f"complexity_router_config is invalid at {location}: {first.get('msg', 'invalid value')}. "
+ "The router would drop this deployment at load time, so the write is rejected instead."
+ )
+ return None
+
+
def validate_strategy_router_model_write(model: str, present_fields: frozenset[str]) -> str | None:
"""Check that writing ``model`` leaves a deployment the router can load.
``present_fields`` is the set of strategy-router param fields that are
non-None on the deployment after the write (stored fields merged with the
incoming ones). Returns a human-readable violation, or None when coherent.
+ A config's contents are ``validate_complexity_router_config_write``'s to
+ judge, since a write may carry one without naming a model at all.
"""
kind = classify_strategy_router_model(model)
if kind is None:
diff --git a/tests/test_litellm/proxy/management_endpoints/test_model_management_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_model_management_endpoints.py
index 8dbf38555b3..95405a3b016 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
@@ -3477,6 +3477,140 @@ class TestStrategyRouterWriteValidation:
is None
)
+ def test_create_with_empty_keyword_rule_rejected(self):
+ """LIT-5133: the router refuses to build a rule with no keyword, but only at load time.
+ Without this the row is written, dropped on reload, and the caller gets a 500 plus a
+ deployment that can never come back."""
+ from litellm.proxy.management_endpoints.model_management_endpoints import (
+ _strategy_router_write_violation,
+ )
+
+ violation = _strategy_router_write_violation(
+ incoming_params=LiteLLM_Params(
+ model="auto_router/complexity_router",
+ complexity_router_default_model="gpt-4o-mini",
+ complexity_router_config={
+ "tiers": {"SIMPLE": ["gpt-4o-mini"]},
+ "keyword_tier_rules": [{"keywords": [], "tier": "COMPLEX"}],
+ },
+ ),
+ existing_params=None,
+ )
+ assert violation is not None
+ assert "complexity_router_config is invalid" in violation
+ assert "keyword_tier_rules" in violation
+
+ def test_patch_that_only_renames_does_not_judge_the_stored_config(self):
+ """Only a config the write actually carries is judged. A row stored before this validation
+ existed is already unloadable, and holding its rename hostage would break the restore path
+ this function documents; the repair is a write that supplies a good config."""
+ from litellm.proxy.management_endpoints.model_management_endpoints import (
+ _strategy_router_write_violation,
+ )
+ from litellm.types.router import updateLiteLLMParams
+
+ stored_bad = LiteLLM_Params(
+ model="auto_router/complexity_router",
+ complexity_router_config={
+ "tiers": {"SIMPLE": ["gpt-4o-mini"]},
+ "keyword_tier_rules": [{"keywords": [" "], "tier": "COMPLEX"}],
+ },
+ )
+ assert (
+ _strategy_router_write_violation(
+ incoming_params=updateLiteLLMParams(model="auto_router/complexity_router"),
+ existing_params=stored_bad,
+ )
+ is None
+ )
+
+ def test_incoming_config_replaces_stored_rather_than_merging(self):
+ """The field is written wholesale, so a good incoming config must clear a bad stored one."""
+ from litellm.proxy.management_endpoints.model_management_endpoints import (
+ _strategy_router_write_violation,
+ )
+ from litellm.types.router import updateLiteLLMParams
+
+ stored_bad = LiteLLM_Params(
+ model="auto_router/complexity_router",
+ complexity_router_config={
+ "tiers": {"SIMPLE": ["gpt-4o-mini"]},
+ "keyword_tier_rules": [{"keywords": [], "tier": "COMPLEX"}],
+ },
+ )
+ assert (
+ _strategy_router_write_violation(
+ incoming_params=updateLiteLLMParams(
+ model="auto_router/complexity_router",
+ complexity_router_config={
+ "tiers": {"SIMPLE": ["gpt-4o-mini"]},
+ "keyword_tier_rules": [{"keywords": ["invoice"], "tier": "COMPLEX"}],
+ },
+ ),
+ existing_params=stored_bad,
+ )
+ is None
+ )
+
+ def test_config_only_patch_is_judged_without_a_model_in_the_payload(self):
+ """A patch may carry a config and no model, which is what a caller updating only the
+ routing rules sends. That path skipped the naming contract, so it has to be judged on the
+ config alone against the stored model, or it overwrites a working router with one that
+ cannot load and takes it out of service."""
+ from litellm.proxy.management_endpoints.model_management_endpoints import (
+ _strategy_router_write_violation,
+ )
+ from litellm.types.router import updateLiteLLMParams
+
+ violation = _strategy_router_write_violation(
+ incoming_params=updateLiteLLMParams(
+ complexity_router_config={
+ "tiers": {"SIMPLE": ["gpt-4o-mini"]},
+ "keyword_tier_rules": [{"keywords": [], "tier": "COMPLEX"}],
+ }
+ ),
+ existing_params=self._stored_complexity_params(),
+ )
+ assert violation is not None
+ assert "complexity_router_config is invalid" in violation
+
+ def test_config_only_patch_with_a_loadable_config_is_allowed(self):
+ from litellm.proxy.management_endpoints.model_management_endpoints import (
+ _strategy_router_write_violation,
+ )
+ from litellm.types.router import updateLiteLLMParams
+
+ assert (
+ _strategy_router_write_violation(
+ incoming_params=updateLiteLLMParams(
+ complexity_router_config={
+ "tiers": {"SIMPLE": ["gpt-4o-mini"]},
+ "keyword_tier_rules": [{"keywords": ["invoice"], "tier": "COMPLEX"}],
+ }
+ ),
+ existing_params=self._stored_complexity_params(),
+ )
+ is None
+ )
+
+ def test_config_only_patch_is_judged_on_the_config_alone(self):
+ """The stored model is encrypted at rest, so a patch that names no model cannot be
+ classified from the row. An unloadable config is rejected on its own merits instead,
+ which is also the only reading that closes the path regardless of what is stored."""
+ from litellm.proxy.management_endpoints.model_management_endpoints import (
+ _strategy_router_write_violation,
+ )
+ from litellm.types.router import updateLiteLLMParams
+
+ violation = _strategy_router_write_violation(
+ incoming_params=updateLiteLLMParams(
+ complexity_router_config={"keyword_tier_rules": [{"keywords": [], "tier": "COMPLEX"}]}
+ ),
+ existing_params=LiteLLM_Params(model="c2VjcmV0-encrypted-at-rest"),
+ )
+ assert violation is not None
+ assert "complexity_router_config is invalid" in violation
+
def test_create_semantic_router_missing_embedding_rejected(self):
from litellm.proxy.management_endpoints.model_management_endpoints import (
_strategy_router_write_violation,
diff --git a/tests/test_litellm/router_utils/test_auto_router_model_naming.py b/tests/test_litellm/router_utils/test_auto_router_model_naming.py
index ca290caac0b..73c9742876c 100644
--- a/tests/test_litellm/router_utils/test_auto_router_model_naming.py
+++ b/tests/test_litellm/router_utils/test_auto_router_model_naming.py
@@ -2,6 +2,7 @@ import pytest
from litellm.router_utils.auto_router_model_naming import (
classify_strategy_router_model,
+ validate_complexity_router_config_write,
validate_strategy_router_model_write,
)
@@ -75,3 +76,74 @@ def test_validate_rejects_incoherent_writes(model, present_fields, expected_frag
)
def test_validate_accepts_coherent_writes(model, present_fields):
assert validate_strategy_router_model_write(model=model, present_fields=present_fields) is None
+
+
+VALID_TIERS = {
+ "SIMPLE": ["gpt-4o-mini"],
+ "MEDIUM": ["gpt-4o-mini"],
+ "COMPLEX": ["gpt-4o"],
+ "REASONING": ["gpt-4o"],
+}
+
+
+ "keyword_tier_rules,expected_fragment",
+ [
+ ([{"keywords": [], "tier": "COMPLEX"}], "at least 1 item"),
+ ([{"keywords": [" "], "tier": "COMPLEX"}], "non-empty keyword"),
+ (
+ [{"keywords": ["invoice"], "tier": "MEDIUM"}, {"keywords": [], "tier": "COMPLEX"}],
+ "at least 1 item",
+ ),
+ ],
+)
+def test_validate_rejects_unloadable_complexity_config(keyword_tier_rules, expected_fragment):
+ """A rule with no keyword makes ComplexityRouterConfig unbuildable, so the row must never be
+ written: without this the deployment is persisted, dropped at load, and the caller gets a 500."""
+ violation = validate_complexity_router_config_write(
+ complexity_router_config={
+ "tiers": VALID_TIERS,
+ "classifier_type": "heuristic",
+ "keyword_tier_rules": keyword_tier_rules,
+ }
+ )
+ assert violation is not None
+ assert "complexity_router_config is invalid" in violation
+ assert expected_fragment in violation
+
+
+ "complexity_router_config",
+ [
+ {"tiers": VALID_TIERS, "classifier_type": "heuristic"},
+ {
+ "tiers": VALID_TIERS,
+ "classifier_type": "heuristic",
+ "keyword_tier_rules": [{"keywords": ["invoice", "refund"], "tier": "MEDIUM"}],
+ },
+ # extra="allow" on the model, so an unrecognised key is not this gate's business
+ {"tiers": VALID_TIERS, "classifier_type": "heuristic", "some_future_key": "value"},
+ ],
+)
+def test_validate_accepts_loadable_complexity_config(complexity_router_config):
+ assert validate_complexity_router_config_write(complexity_router_config=complexity_router_config) is None
+
+
+def test_naming_check_ignores_the_config_entirely():
+ """The naming contract and the config's contents are separate questions with separate owners;
+ a write may carry a config without naming a model, so neither can stand in for the other."""
+ violation = validate_strategy_router_model_write(
+ model="auto_router/complexity_router", present_fields=frozenset()
+ )
+ assert violation is not None
+ assert "requires" in violation
+
+
+def test_config_check_ignores_the_model_entirely():
+ assert validate_complexity_router_config_write(complexity_router_config=None) is None
+ assert (
+ validate_complexity_router_config_write(
+ complexity_router_config={"tiers": VALID_TIERS, "keyword_tier_rules": [{"keywords": [], "tier": "COMPLEX"}]}
+ )
+ is not None
+ )
diff --git a/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.test.tsx b/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.test.tsx
index 319cc7b6fbf..4e585748090 100644
--- a/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.test.tsx
+++ b/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.test.tsx
@@ -310,6 +310,26 @@ describe("ComplexityRouterConfig", () => {
expect(newRules[0]).toMatchObject({ keywords: [], tier: "COMPLEX" });
});
+ // The dropdown is closed, so antd has nothing for Enter to select and the word would only land
+ // on blur. Submitting used to provide that blur; it no longer can while the row reads as empty.
+ it("commits a typed keyword on Enter, with the dropdown closed", async () => {
+ const user = userEvent.setup();
+ const onKeywordTierRulesChange = vi.fn();
+ renderWithProviders(
+ <ComplexityRouterConfig
+ {...baseProps}
+ keywordTierRules={[{ id: "rule-1", keywords: [], tier: "COMPLEX" }]}
+ onKeywordTierRulesChange={onKeywordTierRulesChange}
+ />,
+ );
+ fireEvent.click(screen.getByText("Advanced: Keyword/Semantic Matching"));
+
+ const field = screen.getByText("Keywords 1").closest("div") as HTMLElement;
+ await user.type(within(field).getByRole("combobox"), "invoice{enter}");
+
+ expect(onKeywordTierRulesChange).toHaveBeenCalledWith([{ id: "rule-1", keywords: ["invoice"], tier: "COMPLEX" }]);
+ });
+
it("should render an existing keyword tier rule and remove it when the delete button is clicked", async () => {
const user = userEvent.setup();
const onKeywordTierRulesChange = vi.fn();
diff --git a/ui/litellm-dashboard/src/components/add_model/KeywordTierRules.tsx b/ui/litellm-dashboard/src/components/add_model/KeywordTierRules.tsx
index 4f647c710f2..69cc45a53cd 100644
--- a/ui/litellm-dashboard/src/components/add_model/KeywordTierRules.tsx
+++ b/ui/litellm-dashboard/src/components/add_model/KeywordTierRules.tsx
@@ -2,6 +2,8 @@ import { DeleteOutlined, InfoCircleOutlined, PlusOutlined } from "@ant-design/ic
import { Button, Card, Empty, Select as AntdSelect, Tooltip, Typography } from "antd";
import React from "react";
+import { emptyKeywordTierRuleIndexes } from "./complexity_router_keywords";
+
const { Text } = Typography;
export type ComplexityTier = "SIMPLE" | "MEDIUM" | "COMPLEX" | "REASONING";
@@ -24,7 +26,36 @@ const TIER_OPTIONS: { value: ComplexityTier; label: string }[] = [
{ value: "REASONING", label: "Reasoning" },
];
+// A row exists only because the caller asked for it, so it reports its own gap straight away
+// rather than waiting for a submit; the submit button is disabled while one is outstanding, so
+// there is no failed attempt left to surface it.
const KeywordTierRules: React.FC<KeywordTierRulesProps> = ({ rules, onChange }) => {
+ const emptyRuleIndexes = new Set(emptyKeywordTierRuleIndexes(rules));
+ const [drafts, setDrafts] = React.useState<Record<string, string>>({});
+
+ const setDraft = (id: string, text: string) => setDrafts((current) => ({ ...current, [id]: text }));
+
+ // The dropdown is kept closed, which leaves antd nothing for Enter to select, so a typed keyword
+ // would only become a tag on blur. Submitting used to supply that blur; the button is disabled
+ // while the row reads as empty, so Enter has to commit the word itself or the row cannot be filled.
+ const commitDraft = (rule: KeywordTierRule) => {
+ const keyword = (drafts[rule.id] ?? "").trim();
+ if (!keyword) return;
+ updateRule(rule.id, { keywords: [...rule.keywords, keyword] });
+ setDraft(rule.id, "");
+ };
+
+ const commitDraftOnEnter = (rule: KeywordTierRule) => (event: React.KeyboardEvent<HTMLElement>) => {
+ if (event.key !== "Enter") return;
+ event.preventDefault();
+ commitDraft(rule);
+ };
+
+ const replaceKeywords = (rule: KeywordTierRule) => (keywords: string[]) => {
+ updateRule(rule.id, { keywords });
+ setDraft(rule.id, "");
+ };
+
const addRule = () => {
onChange([...rules, { id: `${Date.now()}`, keywords: [], tier: "COMPLEX" }]);
};
@@ -73,14 +104,24 @@ const KeywordTierRules: React.FC<KeywordTierRulesProps> = ({ rules, onChange })
<AntdSelect
mode="tags"
value={rule.keywords}
- onChange={(keywords: string[]) => updateRule(rule.id, { keywords })}
+ onChange={replaceKeywords(rule)}
+ searchValue={drafts[rule.id] ?? ""}
+ onSearch={(text) => setDraft(rule.id, text)}
+ onInputKeyDown={commitDraftOnEnter(rule)}
+ onBlur={() => commitDraft(rule)}
placeholder="e.g., invoice, refund, billing"
tokenSeparators={[","]}
open={false}
suffixIcon={null}
style={{ width: "100%" }}
allowClear
+ status={emptyRuleIndexes.has(index) ? "error" : undefined}
/>
+ {emptyRuleIndexes.has(index) && (
+ <Text type="danger" style={{ fontSize: 12 }}>
+ At least one keyword is required
+ </Text>
+ )}
</div>
<div style={{ width: 220 }}>
<Text strong style={{ display: "block", marginBottom: 8 }}>
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 f7cc9a1deae..8879844c24a 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
@@ -1,4 +1,4 @@
-import { renderWithProviders, screen, waitFor } from "../../../tests/test-utils";
+import { renderWithProviders, screen, waitFor, within } from "../../../tests/test-utils";
import userEvent from "@testing-library/user-event";
import { vi } from "vitest";
import AddAutoRouterTab from "./add_auto_router_tab";
@@ -52,14 +52,22 @@ describe("AddAutoRouterTab", () => {
vi.clearAllMocks();
});
- it("flags every mandatory field when Add Auto Router is clicked with nothing filled", async () => {
+ // Nothing is filled in, so there is nothing to submit. The button reports that itself instead of
+ // accepting a click and answering with a toast.
+ it("offers no submit at all until every tier has a model", async () => {
+ renderWithProviders(<Harness />);
+
+ expect(screen.getByRole("button", { name: /add auto router/i })).toBeDisabled();
+ });
+
+ it("still flags the router name once the config no longer blocks the submit", async () => {
const user = userEvent.setup();
+ vi.mocked(getMissingTiersError).mockReturnValue(null);
renderWithProviders(<Harness />);
await user.click(screen.getByRole("button", { name: /add auto router/i }));
expect(await screen.findByText("Auto router name is required")).toBeInTheDocument();
- expect(screen.getAllByText("This tier is required")).toHaveLength(4);
expect(NotificationManager.fromBackend).toHaveBeenCalledWith("Please enter an Auto Router Name");
});
@@ -97,6 +105,83 @@ describe("AddAutoRouterTab", () => {
expect(vi.mocked(handleAddAutoRouterSubmit).mock.calls.at(-1)?.[0]).toMatchObject({ team_id: "team-1" });
});
+ // LIT-5133: "Add keyword rule" seeds a row with no keywords, and the semantic toggle that used
+ // to be the only thing checking them is off by default. The row was dropped on the way to the
+ // payload, so the create succeeded and the caller's rule was gone with nothing said about it.
+ it("takes the submit away while a keyword rule is left empty", async () => {
+ const user = userEvent.setup();
+ vi.mocked(getMissingTiersError).mockReturnValue(null);
+
+ renderWithProviders(<Harness />);
+
+ await user.type(screen.getByPlaceholderText(/smart_router/i), "keyword-router");
+ await user.click(screen.getByText("Advanced: Keyword/Semantic Matching"));
+ await user.click(screen.getByRole("button", { name: /add keyword rule/i }));
+
+ expect(screen.getByRole("button", { name: /add auto router/i })).toBeDisabled();
+ // The row says so on its own; there is no failed submit left to surface it.
+ expect(await screen.findByText("At least one keyword is required")).toBeInTheDocument();
+ expect(handleAddAutoRouterSubmit).not.toHaveBeenCalled();
+ });
+
+ it("gives the submit back once that keyword rule is filled", async () => {
+ const user = userEvent.setup();
+ vi.mocked(getMissingTiersError).mockReturnValue(null);
+
+ renderWithProviders(<Harness />);
+
+ await user.type(screen.getByPlaceholderText(/smart_router/i), "keyword-router");
+ await user.click(screen.getByText("Advanced: Keyword/Semantic Matching"));
+ await user.click(screen.getByRole("button", { name: /add keyword rule/i }));
+ expect(screen.getByRole("button", { name: /add auto router/i })).toBeDisabled();
+
+ await user.type(
+ within(screen.getByText("Keywords 1").closest("div") as HTMLElement).getByRole("combobox"),
+ "invoice{enter}",
+ );
+
+ expect(screen.getByRole("button", { name: /add auto router/i })).toBeEnabled();
+ expect(screen.queryByText("At least one keyword is required")).not.toBeInTheDocument();
+ });
+
+ it("marks only the offending keyword row, leaving a filled one alone", async () => {
+ const user = userEvent.setup();
+ vi.mocked(getMissingTiersError).mockReturnValue(null);
+
+ renderWithProviders(<Harness />);
+
+ await user.type(screen.getByPlaceholderText(/smart_router/i), "keyword-router");
+ await user.click(screen.getByText("Advanced: Keyword/Semantic Matching"));
+ await user.click(screen.getByRole("button", { name: /add keyword rule/i }));
+ await user.type(
+ within(screen.getByText("Keywords 1").closest("div") as HTMLElement).getByRole("combobox"),
+ "invoice{enter}",
+ );
+ await user.click(screen.getByRole("button", { name: /add keyword rule/i }));
+
+ expect(await screen.findAllByText("At least one keyword is required")).toHaveLength(1);
+ expect(screen.getByRole("button", { name: /add auto router/i })).toBeDisabled();
+ });
+
+ it("creates the router once that keyword rule is filled in", async () => {
+ const user = userEvent.setup();
+ vi.mocked(getMissingTiersError).mockReturnValue(null);
+
+ renderWithProviders(<Harness />);
+
+ await user.type(screen.getByPlaceholderText(/smart_router/i), "keyword-router");
+ 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.getByRole("button", { name: /add auto router/i }));
+
+ await waitFor(() => expect(handleAddAutoRouterSubmit).toHaveBeenCalled());
+ expect(vi.mocked(handleAddAutoRouterSubmit).mock.calls.at(-1)?.[0]).toMatchObject({
+ complexity_router_config: { keyword_tier_rules: [{ keywords: ["invoice"], tier: "COMPLEX" }] },
+ });
+ });
+
it("blocks the submit when a team admin has not picked a team", async () => {
const user = userEvent.setup();
vi.mocked(getMissingTiersError).mockReturnValue(null);
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 ea75bd8e283..ae90d42ba8a 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
@@ -18,6 +18,7 @@ import { DEFAULT_ESCALATION_KEYWORDS } from "./EscalationKeywords";
import { DEFAULT_MATCH_THRESHOLD } from "./SemanticKeywordMatching";
import {
buildComplexityRouterConfig,
+ getKeywordTierRulesError,
getMissingTiersError,
getSemanticConfigError,
} from "./build_complexity_router_config";
@@ -95,6 +96,11 @@ const AddAutoRouterTab: React.FC<AddAutoRouterTabProps> = ({
label: model_group,
}));
+ // Why the submit is unavailable, or null when it is available. The button reads this to disable
+ // itself and to say what is missing, so the two can never give different answers.
+ const submitBlockedReason =
+ getMissingTiersError(complexityRouterConfig.tiers) ?? getKeywordTierRulesError(keywordTierRules);
+
const submitRecommendedRouter = (name: string) => {
const {
tiers,
@@ -124,6 +130,13 @@ const AddAutoRouterTab: React.FC<AddAutoRouterTabProps> = ({
return;
}
+ const keywordRulesError = getKeywordTierRulesError(keywordTierRules);
+ if (keywordRulesError) {
+ setShowValidationErrors(true);
+ NotificationManager.fromBackend(keywordRulesError);
+ return;
+ }
+
const semanticError = getSemanticConfigError({ semanticMatchingEnabled, embeddingModel, keywordTierRules });
if (semanticError) {
setShowValidationErrors(true);
@@ -310,14 +323,17 @@ const AddAutoRouterTab: React.FC<AddAutoRouterTabProps> = ({
Test Connection
</Button>
}
- <Button
- type="primary"
- onClick={() => {
- handleAutoRouterSubmit();
- }}
- >
- Add Auto Router
- </Button>
+ <Tooltip title={submitBlockedReason}>
+ <Button
+ type="primary"
+ disabled={submitBlockedReason !== null}
+ onClick={() => {
+ handleAutoRouterSubmit();
+ }}
+ >
+ Add Auto Router
+ </Button>
+ </Tooltip>
</div>
</div>
</Form>
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.ts
index 9d784b57903..4cbe54ad4a6 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
@@ -1,5 +1,6 @@
import {
buildComplexityRouterConfig,
+ getKeywordTierRulesError,
getMissingTiersError,
getSemanticConfigError,
BuildComplexityRouterConfigParams,
@@ -183,7 +184,7 @@ describe("buildComplexityRouterConfig", () => {
expect(config.keyword_tier_rules).toBeUndefined();
});
- it("trims keywords and drops rules left empty, so unfilled rows never 400 the backend", () => {
+ it("trims keywords but keeps rules left empty, so a dropped row can never pass for a saved one", () => {
const params: BuildComplexityRouterConfigParams = {
...baseParams,
keywordTierRules: [
@@ -193,17 +194,13 @@ describe("buildComplexityRouterConfig", () => {
],
};
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();
+ // getKeywordTierRulesError blocks this submit; r2 and r3 survive here so the backend rejects
+ // them loudly rather than the caller's rows vanishing on a successful save.
+ expect(config.keyword_tier_rules).toEqual([
+ { keywords: ["deploy to k8s"], tier: "REASONING" },
+ { keywords: [], tier: "COMPLEX" },
+ { keywords: [], tier: "SIMPLE" },
+ ]);
});
it("omits adaptive fields when adaptive is disabled even if weights linger in state", () => {
@@ -318,22 +315,57 @@ describe("getSemanticConfigError", () => {
).toMatch(/keyword tier rule/i);
});
- it("errors when a rule has no non-empty keywords", () => {
- const emptyRule = { id: "r2", keywords: ["", " "], tier: "SIMPLE" as const };
+ it("returns null when enabled with both an embedding model and rules", () => {
expect(
- getSemanticConfigError({
- semanticMatchingEnabled: true,
- embeddingModel: "voyage-3-5",
- keywordTierRules: [emptyRule],
- }),
- ).toMatch(/at least one keyword/i);
+ getSemanticConfigError({ semanticMatchingEnabled: true, embeddingModel: "voyage-3-5", keywordTierRules: [rule] }),
+ ).toBeNull();
});
+});
- it("returns null when enabled with both an embedding model and rules", () => {
+describe("getKeywordTierRulesError", () => {
+ it("returns null when every rule carries a keyword", () => {
expect(
- getSemanticConfigError({ semanticMatchingEnabled: true, embeddingModel: "voyage-3-5", keywordTierRules: [rule] }),
+ getKeywordTierRulesError([
+ { id: "r1", keywords: ["invoice"], tier: "MEDIUM" },
+ { id: "r2", keywords: ["deploy to k8s"], tier: "REASONING" },
+ ]),
).toBeNull();
});
+
+ it("returns null when there are no rules at all, since the section is optional", () => {
+ expect(getKeywordTierRulesError([])).toBeNull();
+ });
+
+ // The whole point of the ticket: the semantic toggle is off by default, and an unfilled row
+ // used to be discarded silently on an otherwise successful create.
+ it("rejects a row left empty while semantic matching is off", () => {
+ expect(getKeywordTierRulesError([{ id: "r1", keywords: [], tier: "COMPLEX" }])).toBe(
+ "Add at least one keyword to keyword rule(s): 1",
+ );
+ });
+
+ it.each([
+ ["whitespace only", [" "]],
+ ["blank strings, as an unfilled row between filled ones leaves behind", ["", " ", ""]],
+ ])("treats %s as empty rather than as a keyword", (_label, keywords) => {
+ expect(getKeywordTierRulesError([{ id: "r1", keywords, tier: "SIMPLE" }])).toMatch(/keyword rule\(s\): 1/);
+ });
+
+ // Row numbers have to survive rules that are fine, or the message points at the wrong input.
+ it("names each offending row by its position among all rules", () => {
+ expect(
+ getKeywordTierRulesError([
+ { id: "r1", keywords: ["invoice"], tier: "MEDIUM" },
+ { id: "r2", keywords: [], tier: "COMPLEX" },
+ { id: "r3", keywords: ["billing"], tier: "SIMPLE" },
+ { id: "r4", keywords: [" "], tier: "REASONING" },
+ ]),
+ ).toBe("Add at least one keyword to keyword rule(s): 2, 4");
+ });
+
+ it("keeps a keyword whose surrounding whitespace is the only thing trimmed", () => {
+ expect(getKeywordTierRulesError([{ id: "r1", keywords: [" invoice "], tier: "MEDIUM" }])).toBeNull();
+ });
});
describe("buildComplexityRouterConfig assistant turns", () => {
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.ts
index cd6c697b377..dcec58479a6 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
@@ -1,5 +1,5 @@
import { KeywordTierRule } from "./KeywordTierRules";
-import { serializeKeywordTierRules } from "./complexity_router_keywords";
+import { emptyKeywordTierRuleIndexes, serializeKeywordTierRules } from "./complexity_router_keywords";
import {
AdaptiveEligible,
AdaptiveRouterWeights,
@@ -58,6 +58,12 @@ export const getMissingTiersError = (tiers: ComplexityTiers): string | null => {
return `Select a model for the following tier(s): ${missing.join(", ")}`;
};
+export const getKeywordTierRulesError = (keywordTierRules: KeywordTierRule[]): string | null => {
+ const emptyRows = emptyKeywordTierRuleIndexes(keywordTierRules);
+ if (emptyRows.length === 0) return null;
+ return `Add at least one keyword to keyword rule(s): ${emptyRows.map((index) => index + 1).join(", ")}`;
+};
+
export const getSemanticConfigError = ({
semanticMatchingEnabled,
embeddingModel,
@@ -68,8 +74,6 @@ export const getSemanticConfigError = ({
if (!semanticMatchingEnabled) return null;
if (!embeddingModel) return "Select an embedding model to use semantic keyword matching";
if (keywordTierRules.length === 0) return "Add at least one keyword tier rule to use semantic keyword matching";
- if (keywordTierRules.some((rule) => !rule.keywords.some((keyword) => keyword.trim())))
- return "Every keyword tier rule needs at least one keyword";
return null;
};
@@ -94,7 +98,6 @@ export const buildComplexityRouterConfig = ({
returnRawModelName,
}: BuildComplexityRouterConfigParams): ComplexityRouterConfigPayload => {
const cleanedEscalationKeywords = escalationKeywords.map((keyword) => keyword.trim()).filter(Boolean);
- // Trim keywords and drop empty ones; drop any rule left with no keywords. Clicking
const cleanedKeywordTierRules = serializeKeywordTierRules(keywordTierRules);
return {
diff --git a/ui/litellm-dashboard/src/components/add_model/complexity_router_keywords.ts b/ui/litellm-dashboard/src/components/add_model/complexity_router_keywords.ts
index 9cfdaed4e23..6fe93cddae3 100644
--- a/ui/litellm-dashboard/src/components/add_model/complexity_router_keywords.ts
+++ b/ui/litellm-dashboard/src/components/add_model/complexity_router_keywords.ts
@@ -19,13 +19,19 @@ const asKeywords = (value: unknown): string[] =>
: [];
/**
- * Drop the React-only id, trim keywords, and discard rules left empty. "Add keyword rule"
- * seeds a row with no keywords, and the backend validator rejects those with a 400.
+ * Drop the React-only id and trim keywords, leaving one entry per rule. A rule left empty stays
+ * empty rather than disappearing, so getKeywordTierRulesError can name the row it came from.
*/
export const serializeKeywordTierRules = (rules: KeywordTierRule[]): StoredKeywordTierRule[] =>
- rules
- .map((rule) => ({ keywords: asKeywords(rule.keywords).filter(Boolean), tier: rule.tier }))
- .filter((rule) => rule.keywords.length > 0);
+ rules.map((rule) => ({ keywords: asKeywords(rule.keywords).filter(Boolean), tier: rule.tier }));
+
+/**
+ * Positions of the rules left without a keyword, as indexes into the caller's own array. The
+ * submit-time message and the inline error on the row both read this, so the row the message
+ * names is always the row that lights up.
+ */
+export const emptyKeywordTierRuleIndexes = (rules: KeywordTierRule[]): number[] =>
+ serializeKeywordTierRules(rules).flatMap((rule, index) => (rule.keywords.length === 0 ? [index] : []));
export const hydrateKeywordTierRules = (value: unknown): KeywordTierRule[] => {
if (!Array.isArray(value)) return [];
diff --git a/ui/litellm-dashboard/src/components/edit_auto_router/build_updated_complexity_router_config.test.ts b/ui/litellm-dashboard/src/components/edit_auto_router/build_updated_complexity_router_config.test.ts
index 971c833a0de..818dcd1f648 100644
--- a/ui/litellm-dashboard/src/components/edit_auto_router/build_updated_complexity_router_config.test.ts
+++ b/ui/litellm-dashboard/src/components/edit_auto_router/build_updated_complexity_router_config.test.ts
@@ -54,13 +54,16 @@ describe("buildUpdatedComplexityRouterConfig keyword matching", () => {
expect(result.keyword_tier_rules).toEqual([{ keywords: ["chargeback"], tier: "COMPLEX" }]);
});
- it("drops a rule left empty rather than shipping one the backend 400s on", () => {
+ // getKeywordTierRulesError blocks this save, so the builder never runs on a real edit. Keeping
+ // the rule here means that if a caller ever reaches it anyway, the stored rules are replaced by
+ // something the backend rejects out loud rather than by silence that reads as a clean save.
+ it("keeps a rule left empty rather than quietly dropping the caller's row", () => {
const result = buildUpdatedComplexityRouterConfig(STORED, FORM_VALUE, undefined, {
...hydratedState,
keywordTierRules: [{ id: "new-1", keywords: [" "], tier: "SIMPLE" }],
});
- expect(result.keyword_tier_rules).toBeUndefined();
+ expect(result.keyword_tier_rules).toEqual([{ keywords: [], tier: "SIMPLE" }]);
});
it("removes the semantic trio when the toggle is turned off", () => {
diff --git a/ui/litellm-dashboard/src/components/edit_auto_router/edit_auto_router_modal.test.tsx b/ui/litellm-dashboard/src/components/edit_auto_router/edit_auto_router_modal.test.tsx
index c0806befa52..3976e4c1381 100644
--- a/ui/litellm-dashboard/src/components/edit_auto_router/edit_auto_router_modal.test.tsx
+++ b/ui/litellm-dashboard/src/components/edit_auto_router/edit_auto_router_modal.test.tsx
@@ -118,6 +118,80 @@ describe("EditAutoRouterModal keyword matching", () => {
await waitFor(() => expect(NotificationsManager.fromBackend).toHaveBeenCalled());
expect(modelPatchUpdateCall).not.toHaveBeenCalled();
});
+
+ // LIT-5133, edit side. Semantic matching is off here on purpose: it used to be the only thing
+ // that checked a rule for keywords, so with it on this save was already blocked and the test
+ // would pass without the fix. Off, the unfilled row was dropped and the save reported success.
+ it("blocks a save that adds a keyword rule and leaves it empty", async () => {
+ const user = userEvent.setup();
+ renderWithProviders(
+ <EditAutoRouterModal
+ isVisible
+ onCancel={vi.fn()}
+ onSuccess={vi.fn()}
+ modelData={{
+ ...MODEL_DATA,
+ litellm_params: {
+ ...MODEL_DATA.litellm_params,
+ complexity_router_config: {
+ ...STORED_CONFIG,
+ semantic_keyword_matching: false,
+ embedding_model: undefined,
+ },
+ },
+ }}
+ accessToken="token"
+ userRole="Admin"
+ />,
+ );
+
+ await screen.findByText(/Escalation Keywords/i);
+ fireEvent.click(screen.getByText("Advanced: Keyword/Semantic Matching"));
+ await user.click(screen.getByRole("button", { name: /add keyword rule/i }));
+
+ // The modal renders the same controls as the create form, so it owes the same treatment:
+ // the row says what is missing and the save is not offered while it is.
+ expect(await screen.findByText("At least one keyword is required")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: /save changes/i })).toBeDisabled();
+ expect(modelPatchUpdateCall).not.toHaveBeenCalled();
+ });
+
+ it("gives the save back once the added keyword rule is filled", async () => {
+ const user = userEvent.setup();
+ renderWithProviders(
+ <EditAutoRouterModal
+ isVisible
+ onCancel={vi.fn()}
+ onSuccess={vi.fn()}
+ modelData={{
+ ...MODEL_DATA,
+ litellm_params: {
+ ...MODEL_DATA.litellm_params,
+ complexity_router_config: {
+ ...STORED_CONFIG,
+ semantic_keyword_matching: false,
+ embedding_model: undefined,
+ },
+ },
+ }}
+ accessToken="token"
+ userRole="Admin"
+ />,
+ );
+
+ await screen.findByText(/Escalation Keywords/i);
+ fireEvent.click(screen.getByText("Advanced: Keyword/Semantic Matching"));
+ await user.click(screen.getByRole("button", { name: /add keyword rule/i }));
+ expect(screen.getByRole("button", { name: /save changes/i })).toBeDisabled();
+
+ await user.type(
+ within(screen.getByText("Keywords 2").closest("div") as HTMLElement).getByRole("combobox"),
+ "chargeback{enter}",
+ );
+
+ expect(screen.getByRole("button", { name: /save changes/i })).toBeEnabled();
+ expect(screen.queryByText("At least one keyword is required")).not.toBeInTheDocument();
+ });
});
describe("EditAutoRouterModal classifier context window", () => {
diff --git a/ui/litellm-dashboard/src/components/edit_auto_router/edit_auto_router_modal.tsx b/ui/litellm-dashboard/src/components/edit_auto_router/edit_auto_router_modal.tsx
index a70fc31d6fe..2c58cd70cb9 100644
--- a/ui/litellm-dashboard/src/components/edit_auto_router/edit_auto_router_modal.tsx
+++ b/ui/litellm-dashboard/src/components/edit_auto_router/edit_auto_router_modal.tsx
@@ -1,12 +1,12 @@
import React, { useEffect, useState } from "react";
-import { Modal, Form, Button, Select as AntdSelect } from "antd";
+import { Modal, Form, Button, Select as AntdSelect, Tooltip } from "antd";
import { Text, TextInput } from "@tremor/react";
import { modelAvailableCall, modelPatchUpdateCall } from "../networking";
import { fetchAvailableModels, ModelGroup } from "@/components/llm_calls/fetch_models";
import RouterConfigBuilder from "../add_model/RouterConfigBuilder";
import { normalizeTierModels } from "../add_model/complexity_router_tiers";
import { isComplexityRouter } from "../add_model/auto_router_strategies";
-import { getSemanticConfigError } from "../add_model/build_complexity_router_config";
+import { getKeywordTierRulesError, getSemanticConfigError } from "../add_model/build_complexity_router_config";
import { KeywordTierRule } from "../add_model/KeywordTierRules";
import { DEFAULT_MATCH_THRESHOLD } from "../add_model/SemanticKeywordMatching";
import { hydrateKeywordTierRules, serializeKeywordTierRules } from "../add_model/complexity_router_keywords";
@@ -118,8 +118,8 @@ export const buildUpdatedComplexityRouterConfig = (
}),
...(value.return_raw_model_name && { return_raw_model_name: true }),
...(keywordMatching && {
- // Mirrors buildComplexityRouterConfig: rules only when non-empty (the backend rejects
- // an empty rule with a 400), escalation keywords always, semantic trio only when on.
+ // Mirrors buildComplexityRouterConfig: the key only when there is a rule to write,
+ // escalation keywords always, semantic trio only when on.
...(storedKeywordRules.length > 0 && { keyword_tier_rules: storedKeywordRules }),
escalation_keywords: keywordMatching.escalationKeywords.map((k) => k.trim()).filter(Boolean),
...(keywordMatching.semanticMatchingEnabled && {
@@ -145,6 +145,7 @@ const EditAutoRouterModal: React.FC<EditAutoRouterModalProps> = ({
const [modelInfo, setModelInfo] = useState<ModelGroup[]>([]);
const [showCustomDefaultModel, setShowCustomDefaultModel] = useState<boolean>(false);
const [showCustomEmbeddingModel, setShowCustomEmbeddingModel] = useState<boolean>(false);
+ const [showValidationErrors, setShowValidationErrors] = useState<boolean>(false);
const [routerConfig, setRouterConfig] = useState<any>(null);
const [customTechnicalKeywords, setCustomTechnicalKeywords] = useState<string[]>([]);
const [keywordTierRules, setKeywordTierRules] = useState<KeywordTierRule[]>([]);
@@ -158,6 +159,15 @@ const EditAutoRouterModal: React.FC<EditAutoRouterModalProps> = ({
});
const isComplexityRouterModel = isComplexityRouter(modelData?.litellm_params);
+ // Mirrors the create form: the button says why it is unavailable and disables on the same
+ // answer. Tiers use this modal's own rule, which allows a partly filled router, so an edit that
+ // is legal today stays legal.
+ const submitBlockedReason = !isComplexityRouterModel
+ ? null
+ : (Object.values(complexityRouterConfig.tiers).every((models) => models.length === 0)
+ ? "Please select at least one model for a complexity tier"
+ : null) ?? getKeywordTierRulesError(keywordTierRules);
+
useEffect(() => {
if (isVisible && modelData) {
initializeForm();
@@ -295,24 +305,29 @@ const EditAutoRouterModal: React.FC<EditAutoRouterModalProps> = ({
if (isComplexityRouterModel) {
const { tiers, classifier_type, classifier_llm_config } = complexityRouterConfig;
if (Object.values(tiers).every((models) => models.length === 0)) {
+ setShowValidationErrors(true);
NotificationsManager.fromBackend("Please select at least one model for a complexity tier");
return;
}
if (classifier_type === "llm" && !classifier_llm_config?.model) {
+ setShowValidationErrors(true);
NotificationsManager.fromBackend("Please select a classifier model, or switch back to Heuristic");
return;
}
- // Same guard the create form applies (add_auto_router_tab.tsx). The backend rejects
- // semantic_keyword_matching without an embedding model or keyword rules
- // (complexity_router/config.py), so without this a save fails as a raw 400 instead of
- // an inline message.
-
- // Same guard the create form applies (add_auto_router_tab.tsx). The backend rejects
- // semantic_keyword_matching without an embedding model or keyword rules
- // (complexity_router/config.py), so without this a save fails as a raw 400 instead of
- // an inline message.
+ // Same guards the create form applies (add_auto_router_tab.tsx). The backend rejects a
+ // keyword rule with no keyword, and semantic_keyword_matching without an embedding model
+ // or keyword rules (complexity_router/config.py), so without these a save fails as a raw
+ // 400 instead of an inline message.
+ const keywordRulesError = getKeywordTierRulesError(keywordTierRules);
+ if (keywordRulesError) {
+ setShowValidationErrors(true);
+ NotificationsManager.fromBackend(keywordRulesError);
+ return;
+ }
+
const semanticError = getSemanticConfigError({ semanticMatchingEnabled, embeddingModel, keywordTierRules });
if (semanticError) {
+ setShowValidationErrors(true);
NotificationsManager.fromBackend(semanticError);
return;
}
@@ -410,9 +425,11 @@ const EditAutoRouterModal: React.FC<EditAutoRouterModalProps> = ({
<Button key="cancel" onClick={onCancel}>
Cancel
</Button>,
- <Button key="submit" loading={loading} onClick={handleSubmit}>
- Save Changes
- </Button>,
+ <Tooltip key="submit" title={submitBlockedReason}>
+ <Button loading={loading} disabled={submitBlockedReason !== null} onClick={handleSubmit}>
+ Save Changes
+ </Button>
+ </Tooltip>,
]}
width={1000}
destroyOnHidden
@@ -436,6 +453,7 @@ const EditAutoRouterModal: React.FC<EditAutoRouterModalProps> = ({
/* Complexity Router Configuration */
<div className="w-full">
<ComplexityRouterConfig
+ showValidationErrors={showValidationErrors}
modelInfo={modelInfo}
value={complexityRouterConfig}
onChange={(config) => {