The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
feat(complexity_router): add custom_technical_keywords config (#32262)
Mateo Wangf628b41400f3
diff --git a/litellm/router_strategy/complexity_router/complexity_router.py b/litellm/router_strategy/complexity_router/complexity_router.pyindex 9a1d845dd65..4f9135ad9ed 100644--- a/litellm/router_strategy/complexity_router/complexity_router.py+++ b/litellm/router_strategy/complexity_router/complexity_router.py@@ -32,6 +32,14 @@ else:PreRoutingHookResponse = Any+def _append_custom_keywords(base_keywords: list[str], custom_keywords: Optional[list[str]]) -> list[str]:+ if not custom_keywords:+ return base_keywords+ base_lowered = frozenset(keyword.lower() for keyword in base_keywords)+ deduped_custom = {keyword.lower(): keyword for keyword in custom_keywords if keyword.lower() not in base_lowered}+ return [*base_keywords, *deduped_custom.values()]++class DimensionScore:"""Represents a score for a single dimension with optional signal."""@@ -90,7 +98,10 @@ class ComplexityRouter(CustomLogger):# Build effective keyword lists (use config overrides or defaults)self.code_keywords = self.config.code_keywords or DEFAULT_CODE_KEYWORDSself.reasoning_keywords = self.config.reasoning_keywords or DEFAULT_REASONING_KEYWORDS- self.technical_keywords = self.config.technical_keywords or DEFAULT_TECHNICAL_KEYWORDS+ self.technical_keywords = _append_custom_keywords(+ self.config.technical_keywords or DEFAULT_TECHNICAL_KEYWORDS,+ self.config.custom_technical_keywords,+ )self.simple_keywords = self.config.simple_keywords or DEFAULT_SIMPLE_KEYWORDS# Pre-compile regex patterns for efficiencydiff --git a/litellm/router_strategy/complexity_router/config.py b/litellm/router_strategy/complexity_router/config.pyindex a8a21e3f30b..ae04d5fc5d4 100644--- a/litellm/router_strategy/complexity_router/config.py+++ b/litellm/router_strategy/complexity_router/config.py@@ -237,6 +237,15 @@ class ComplexityRouterConfig(BaseModel):default=None,description="Keywords indicating technical content",)+ custom_technical_keywords: Optional[list[str]] = Field(+ default=None,+ 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."+ ),+ )simple_keywords: Optional[List[str]] = Field(default=None,description="Keywords indicating simple/basic queries",diff --git a/tests/test_litellm/router_strategy/test_complexity_router.py b/tests/test_litellm/router_strategy/test_complexity_router.pyindex e68ea863d82..d4a7da86734 100644--- a/tests/test_litellm/router_strategy/test_complexity_router.py+++ b/tests/test_litellm/router_strategy/test_complexity_router.py@@ -22,6 +22,7 @@ from litellm.router_strategy.complexity_router.complexity_router import ()from litellm.router_strategy.complexity_router.config import (DEFAULT_COMPLEXITY_CONFIG,+ DEFAULT_TECHNICAL_KEYWORDS,ComplexityRouterConfig,ComplexityTier,)@@ -468,6 +469,89 @@ class TestConfigOverrides:), f"Expected 'long' signal, got {signals}"+class TestCustomTechnicalKeywords:+ """Test the custom_technical_keywords config option."""++ def test_custom_keywords_appended_to_defaults(self, mock_router_instance):+ """Custom keywords should be appended to the default technical keywords."""+ router = ComplexityRouter(+ model_name="test-router",+ litellm_router_instance=mock_router_instance,+ complexity_router_config={"custom_technical_keywords": ["udp", "kafka"]},+ )+ assert router.technical_keywords == DEFAULT_TECHNICAL_KEYWORDS + ["udp", "kafka"]++ def test_custom_keywords_appended_to_technical_keywords_override(+ self, mock_router_instance+ ):+ """Custom keywords should be appended to a technical_keywords override."""+ router = ComplexityRouter(+ model_name="test-router",+ litellm_router_instance=mock_router_instance,+ complexity_router_config={+ "technical_keywords": ["quantum", "photonics"],+ "custom_technical_keywords": ["udp"],+ },+ )+ assert router.technical_keywords == ["quantum", "photonics", "udp"]++ def test_custom_keywords_deduplicated_case_insensitively(self, mock_router_instance):+ """Duplicates against the base list and within the custom list should be dropped."""+ router = ComplexityRouter(+ model_name="test-router",+ litellm_router_instance=mock_router_instance,+ complexity_router_config={+ "custom_technical_keywords": ["TCP", "udp", "UDP", "kafka"]+ },+ )+ lowered = [kw.lower() for kw in router.technical_keywords]+ assert lowered == [kw.lower() for kw in DEFAULT_TECHNICAL_KEYWORDS] + [+ "udp",+ "kafka",+ ]++ def test_no_custom_keywords_leaves_defaults_unchanged(self, mock_router_instance):+ """Absent or None custom_technical_keywords should leave the keyword list identical."""+ router_absent = ComplexityRouter(+ model_name="test-router",+ litellm_router_instance=mock_router_instance,+ complexity_router_config={"tiers": {"MEDIUM": "gpt-4o"}},+ )+ router_none = ComplexityRouter(+ model_name="test-router",+ litellm_router_instance=mock_router_instance,+ complexity_router_config={"custom_technical_keywords": None},+ )+ assert router_absent.technical_keywords == DEFAULT_TECHNICAL_KEYWORDS+ assert router_none.technical_keywords == DEFAULT_TECHNICAL_KEYWORDS++ def test_prompt_with_only_custom_keywords_scores_technical(+ self, mock_router_instance, basic_config+ ):+ """A prompt matching only custom keywords should score higher on technicalTerms."""+ prompt = "Configure udp multicast between kafka brokers"+ baseline_router = ComplexityRouter(+ model_name="test-router",+ litellm_router_instance=mock_router_instance,+ complexity_router_config=basic_config,+ )+ custom_router = ComplexityRouter(+ model_name="test-router",+ litellm_router_instance=mock_router_instance,+ complexity_router_config={+ **basic_config,+ "custom_technical_keywords": ["UDP", "Kafka"],+ },+ )+ _, baseline_score, baseline_signals = baseline_router.classify(prompt)+ _, custom_score, custom_signals = custom_router.classify(prompt)+ assert not any("technical" in s.lower() for s in baseline_signals)+ assert any(+ "technical" in s.lower() for s in custom_signals+ ), f"Expected technical signal, got {custom_signals}"+ assert custom_score > baseline_score++class TestAsyncPreRoutingHookEdgeCases:"""Test edge cases for async_pre_routing_hook method."""diff --git a/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.test.tsx b/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.test.tsxindex 9fe39a0ad50..5de9ad17208 100644--- a/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.test.tsx+++ b/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.test.tsx@@ -1,4 +1,5 @@-import { renderWithProviders, screen } from "../../../tests/test-utils";+import { renderWithProviders, screen, within } from "../../../tests/test-utils";+import userEvent from "@testing-library/user-event";import { vi } from "vitest";import ComplexityRouterConfig from "./ComplexityRouterConfig";@@ -49,4 +50,41 @@ describe("ComplexityRouterConfig", () => {expect(screen.getByText(/Score 0.35 - 0.60/)).toBeInTheDocument();expect(screen.getByText(/Score > 0.60/)).toBeInTheDocument();});++ it("should render the custom technical keywords field", () => {+ renderWithProviders(<ComplexityRouterConfig modelInfo={mockModelInfo} value={defaultTiers} onChange={vi.fn()} />);+ expect(screen.getByText("Custom Technical Keywords")).toBeInTheDocument();+ });++ it("should display existing custom technical keywords as tags", () => {+ renderWithProviders(+ <ComplexityRouterConfig+ modelInfo={mockModelInfo}+ value={defaultTiers}+ onChange={vi.fn()}+ customTechnicalKeywords={["udp", "kafka"]}+ onCustomTechnicalKeywordsChange={vi.fn()}+ />,+ );+ expect(screen.getByText("udp")).toBeInTheDocument();+ expect(screen.getByText("kafka")).toBeInTheDocument();+ });++ it("should call onCustomTechnicalKeywordsChange when a keyword is entered", async () => {+ const user = userEvent.setup();+ const onCustomTechnicalKeywordsChange = vi.fn();+ renderWithProviders(+ <ComplexityRouterConfig+ modelInfo={mockModelInfo}+ value={defaultTiers}+ onChange={vi.fn()}+ customTechnicalKeywords={[]}+ onCustomTechnicalKeywordsChange={onCustomTechnicalKeywordsChange}+ />,+ );+ const keywordsCard = screen.getByText("Custom Technical Keywords").closest(".ant-card") as HTMLElement;+ const input = within(keywordsCard).getByRole("combobox");+ await user.type(input, "udp,");+ expect(onCustomTechnicalKeywordsChange).toHaveBeenCalledWith(["udp"]);+ });});diff --git a/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.tsx b/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.tsxindex d826f3df32c..5cf97114169 100644--- a/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.tsx+++ b/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.tsx@@ -16,6 +16,8 @@ interface ComplexityRouterConfigProps {modelInfo: ModelGroup[];value: ComplexityTiers;onChange: (tiers: ComplexityTiers) => void;+ customTechnicalKeywords?: string[];+ onCustomTechnicalKeywordsChange?: (keywords: string[]) => void;}const TIER_DESCRIPTIONS: Record<keyof ComplexityTiers, { label: string; description: string; examples: string }> = {@@ -41,7 +43,13 @@ const TIER_DESCRIPTIONS: Record<keyof ComplexityTiers, { label: string; descript},};-const ComplexityRouterConfig: React.FC<ComplexityRouterConfigProps> = ({ modelInfo, value, onChange }) => {+const ComplexityRouterConfig: React.FC<ComplexityRouterConfigProps> = ({+ modelInfo,+ value,+ onChange,+ customTechnicalKeywords,+ onCustomTechnicalKeywordsChange,+}) => {// Prepare model options for dropdownsconst modelOptions = modelInfo.map((model) => ({value: model.model_group,@@ -105,6 +113,33 @@ const ComplexityRouterConfig: React.FC<ComplexityRouterConfigProps> = ({ modelIn<Divider />+ <Card>+ <div className="flex items-center gap-2 mb-2">+ <Text strong style={{ fontSize: 16 }}>+ Custom Technical Keywords+ </Text>+ <Tooltip title="Domain-specific terms appended to the built-in technical keyword list. Prompts containing these terms score higher on the technical dimension and route to more capable models.">+ <InfoCircleOutlined className="text-gray-400" />+ </Tooltip>+ </div>+ <Text type="secondary" style={{ display: "block", marginBottom: 8, fontSize: 12 }}>+ Optional: add terms the built-in list misses (e.g., udp, kafka, terraform)+ </Text>+ <AntdSelect+ mode="tags"+ value={customTechnicalKeywords ?? []}+ onChange={(keywords: string[]) => onCustomTechnicalKeywordsChange?.(keywords)}+ placeholder="Type a keyword and press Enter, or paste a comma-separated list"+ tokenSeparators={[","]}+ open={false}+ suffixIcon={null}+ style={{ width: "100%" }}+ allowClear+ />+ </Card>++ <Divider />+<Card className="bg-gray-50"><Text strong style={{ display: "block", marginBottom: 8 }}>How Classification Worksdiff --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.tsxindex 5c44b260e84..1714cfb3907 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@@ -55,6 +55,8 @@ const AddAutoRouterTab: React.FC<AddAutoRouterTabProps> = ({ form, handleOk, accREASONING: "",});+ const [customTechnicalKeywords, setCustomTechnicalKeywords] = useState<string[]>([]);+useEffect(() => {const fetchModelAccessGroups = async () => {const response = await modelAvailableCall(accessToken, "", "", false, null, true, true);@@ -127,6 +129,7 @@ const AddAutoRouterTab: React.FC<AddAutoRouterTabProps> = ({ form, handleOk, accmodel_type: "complexity_router",complexity_router_config: {tiers: complexityTiers,+ ...(customTechnicalKeywords.length > 0 && { custom_technical_keywords: customTechnicalKeywords }),},model_access_group: currentFormValues.model_access_group,};@@ -280,6 +283,8 @@ const AddAutoRouterTab: React.FC<AddAutoRouterTabProps> = ({ form, handleOk, acconChange={(tiers) => {setComplexityTiers(tiers);}}+ customTechnicalKeywords={customTechnicalKeywords}+ onCustomTechnicalKeywordsChange={setCustomTechnicalKeywords}/></div>) : (