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(complexity-router): user-triggered escalation keywords (#33656)

devin-ai-integration[bot]b0a0f11b09f5
diff --git a/litellm/router_strategy/complexity_router/complexity_router.py b/litellm/router_strategy/complexity_router/complexity_router.py
index fa6f14e9b26..695d8b8aeaa 100644
--- a/litellm/router_strategy/complexity_router/complexity_router.py
+++ b/litellm/router_strategy/complexity_router/complexity_router.py
@@ -28,6 +28,7 @@ from litellm.types.utils import ModelResponse
from .config import (
DEFAULT_CODE_KEYWORDS,
+ DEFAULT_ESCALATION_KEYWORDS,
DEFAULT_REASONING_KEYWORDS,
DEFAULT_SIMPLE_KEYWORDS,
DEFAULT_TECHNICAL_KEYWORDS,
@@ -173,6 +174,11 @@ class ComplexityRouter(CustomLogger):
self.config.custom_technical_keywords,
)
self.simple_keywords = self.config.simple_keywords or DEFAULT_SIMPLE_KEYWORDS
+ self.escalation_keywords = (
+ self.config.escalation_keywords
+ if self.config.escalation_keywords is not None
+ else DEFAULT_ESCALATION_KEYWORDS
+ )
# Lazily built on first semantic request and cached for reuse (route
# embeddings are static, only the prompt is embedded per request). The lock
@@ -668,6 +674,53 @@ class ComplexityRouter(CustomLogger):
}
return best_model
+ def _escalation_triggered(self, user_message: str) -> bool:
+ """Whether the prompt asks to escalate to a stronger model.
+
+ Matching is a case-sensitive substring test so the default "LITELLM ESCALATE"
+ only fires on the deliberate, shouted form and not on incidental lowercase
+ mentions of the word (e.g. "how do I escalate this ticket").
+ """
+ if not self.escalation_keywords:
+ return False
+ return any(keyword in user_message for keyword in self.escalation_keywords)
+
+ def _tier_for_model(self, model: str) -> ComplexityTier | None:
+ """Return the most-severe configured tier whose pool contains this model."""
+ pools = self._tier_pools()
+ matched = tuple(ComplexityTier(tier_name) for tier_name, models in pools.items() if model in models)
+ if not matched:
+ return None
+ return max(matched, key=TIER_SEVERITY_ORDER.index)
+
+ def _escalate_tier(self, tier: ComplexityTier) -> ComplexityTier:
+ """Bump a tier one step up to the next-higher configured tier.
+
+ Returns the input tier unchanged when it is already the highest configured
+ tier, so escalation can never route below the model the user would otherwise
+ have received.
+ """
+ configured = frozenset(self.config.tiers)
+ current_index = TIER_SEVERITY_ORDER.index(tier)
+ higher_tiers = tuple(
+ candidate for candidate in TIER_SEVERITY_ORDER[current_index + 1 :] if candidate.value in configured
+ )
+ return higher_tiers[0] if higher_tiers else tier
+
+ def _escalated_pin(self, pinned_model: str) -> str | None:
+ """Bump a session's pinned model to the next-higher configured tier.
+
+ Returns None when the pin no longer maps to any configured tier, signalling
+ a full reclassification instead.
+ """
+ pinned_tier = self._tier_for_model(pinned_model)
+ if pinned_tier is None:
+ return None
+ escalated_tier = self._escalate_tier(pinned_tier)
+ if escalated_tier == pinned_tier:
+ return pinned_model
+ return self.get_model_for_tier(escalated_tier)
+
def _lexical_tier_override(self, user_message: str) -> ComplexityTier | None:
"""When keyword_tier_rules match literally, the most-severe matched tier wins.
@@ -910,29 +963,41 @@ class ComplexityRouter(CustomLogger):
if cache_key is not None:
pinned_model = await self.litellm_router_instance.cache.async_get_cache(key=cache_key)
if isinstance(pinned_model, str):
- # Refresh the TTL on every hit so an active session doesn't lose its
- # pin mid-conversation just because it outlives the original write.
- await self.litellm_router_instance.cache.async_set_cache(
- key=cache_key,
- value=pinned_model,
- ttl=self.config.session_affinity_ttl_seconds,
- )
- if self.config.adaptive:
- from litellm.router_strategy.adaptive_router.config import (
- ADAPTIVE_ROUTER_CHOSEN_MODEL_KEY,
+ routed_model: str | None = pinned_model
+ if self.escalation_keywords:
+ resolved_messages = self._resolve_messages(messages, request_kwargs)
+ user_message = (
+ self._extract_user_message_and_system_prompt(resolved_messages)[0]
+ if resolved_messages
+ else None
+ )
+ if user_message is not None and self._escalation_triggered(user_message):
+ routed_model = self._escalated_pin(pinned_model)
+ if routed_model is not None:
+ # Refresh the TTL on every hit so an active session doesn't lose its
+ # pin mid-conversation just because it outlives the original write.
+ await self.litellm_router_instance.cache.async_set_cache(
+ key=cache_key,
+ value=routed_model,
+ ttl=self.config.session_affinity_ttl_seconds,
+ )
+ if self.config.adaptive:
+ from litellm.router_strategy.adaptive_router.config import (
+ ADAPTIVE_ROUTER_CHOSEN_MODEL_KEY,
+ )
+
+ kwargs_metadata = request_kwargs.setdefault("metadata", {})
+ if isinstance(kwargs_metadata, dict):
+ kwargs_metadata[ADAPTIVE_ROUTER_CHOSEN_MODEL_KEY] = routed_model
+ cause = "session_affinity_escalation" if routed_model != pinned_model else "session_affinity_pin"
+ verbose_router_logger.info(
+ f"ComplexityRouter: routing decision cause={cause}, routed_model={routed_model}"
+ )
+ has_original_messages = messages is not None and len(messages) > 0
+ return PreRoutingHookResponse(
+ model=routed_model,
+ messages=messages if has_original_messages else None,
)
-
- kwargs_metadata = request_kwargs.setdefault("metadata", {})
- if isinstance(kwargs_metadata, dict):
- kwargs_metadata[ADAPTIVE_ROUTER_CHOSEN_MODEL_KEY] = pinned_model
- verbose_router_logger.info(
- f"ComplexityRouter: routing decision cause=session_affinity_pin, routed_model={pinned_model}"
- )
- has_original_messages = messages is not None and len(messages) > 0
- return PreRoutingHookResponse(
- model=pinned_model,
- messages=messages if has_original_messages else None,
- )
response = await self._classify_and_route(
model=model,
@@ -1004,13 +1069,17 @@ class ComplexityRouter(CustomLogger):
messages=messages if has_original_messages else None,
)
+ escalate = self._escalation_triggered(user_message)
+
override_tier = await self._resolve_keyword_tier_override(user_message, request_kwargs)
if override_tier is not None:
- routed_model = await self._pick_model_for_tier(override_tier, messages, resolved_messages, request_kwargs)
- cause = "semantic_keyword_match" if self.config.semantic_keyword_matching else "literal_keyword_match"
+ routed_tier = self._escalate_tier(override_tier) if escalate else override_tier
+ routed_model = await self._pick_model_for_tier(routed_tier, messages, resolved_messages, request_kwargs)
+ base_cause = "semantic_keyword_match" if self.config.semantic_keyword_matching else "literal_keyword_match"
+ cause = f"{base_cause}+escalation" if escalate else base_cause
verbose_router_logger.info(
f"ComplexityRouter: routing decision cause={cause}, "
- f"tier={override_tier.value}, routed_model={routed_model}"
+ f"tier={routed_tier.value}, routed_model={routed_model}"
)
return PreRoutingHookResponse(
model=routed_model,
@@ -1018,6 +1087,9 @@ class ComplexityRouter(CustomLogger):
)
tier, score, signals = await self.aclassify(user_message, system_prompt, request_kwargs)
+ if escalate:
+ tier = self._escalate_tier(tier)
+ signals = [*signals, "escalation"]
if self.config.adaptive:
routed_model = self._soft_floor_pick(tier, user_message, request_kwargs)
adaptive = self._ensure_adaptive_router()
diff --git a/litellm/router_strategy/complexity_router/config.py b/litellm/router_strategy/complexity_router/config.py
index 1f984798970..17c2c287dde 100644
--- a/litellm/router_strategy/complexity_router/config.py
+++ b/litellm/router_strategy/complexity_router/config.py
@@ -162,6 +162,9 @@ DEFAULT_TECHNICAL_KEYWORDS: list[str] = [
# Note: "async", "kubernetes", "docker" are in DEFAULT_CODE_KEYWORDS
]
+DEFAULT_ESCALATION_KEYWORDS: list[str] = ["LITELLM ESCALATE"]
+
+
DEFAULT_SIMPLE_KEYWORDS: list[str] = [
"what is",
"what's",
@@ -339,6 +342,16 @@ class ComplexityRouterConfig(BaseModel):
),
)
+ escalation_keywords: list[str] | None = Field(
+ default=None,
+ 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."
+ ),
+ )
+
# Deterministic keyword -> tier overrides, evaluated before weighted scoring
keyword_tier_rules: list[KeywordTierRule] | None = Field(
default=None,
@@ -400,6 +413,13 @@ class ComplexityRouterConfig(BaseModel):
coerced[key] = item
return coerced
+ @field_validator("escalation_keywords")
+ @classmethod
+ def _normalize_escalation_keywords(cls, value: list[str] | None) -> list[str] | None:
+ if value is None:
+ return None
+ return [stripped for keyword in value if (stripped := keyword.strip())]
+
@model_validator(mode="after")
def _validate_llm_classifier_config(self) -> "ComplexityRouterConfig":
if self.classifier_type == "llm" and self.classifier_llm_config is None:
diff --git a/tests/test_litellm/router_strategy/test_complexity_router.py b/tests/test_litellm/router_strategy/test_complexity_router.py
index 26dc503d50e..280a0fe072a 100644
--- a/tests/test_litellm/router_strategy/test_complexity_router.py
+++ b/tests/test_litellm/router_strategy/test_complexity_router.py
@@ -3119,3 +3119,260 @@ class TestRoutingPlugins:
assert first.model == "gpt-4o-mini"
assert second.model == "gpt-4o-mini"
assert spy.call_count == 2
+
+
+class TestEscalationKeywords:
+ """Test user-triggered escalation: a keyword in the prompt bumps the resolved tier
+ one step higher so a user can force a stronger model when unhappy with results."""
+
+ @staticmethod
+ def _request_kwargs(session_id: str) -> Dict:
+ return {"metadata": {"session_id": session_id}}
+
+ def test_default_escalation_keyword(self, complexity_router):
+ assert complexity_router.escalation_keywords == ["LITELLM ESCALATE"]
+
+ def test_escalation_triggered_is_case_sensitive(self, complexity_router):
+ assert complexity_router._escalation_triggered("please LITELLM ESCALATE now") is True
+ assert complexity_router._escalation_triggered("please litellm escalate now") is False
+ assert complexity_router._escalation_triggered("how do I escalate this ticket") is False
+
+ def test_escalate_tier_bumps_one_step(self, complexity_router):
+ assert complexity_router._escalate_tier(ComplexityTier.SIMPLE) == ComplexityTier.MEDIUM
+ assert complexity_router._escalate_tier(ComplexityTier.MEDIUM) == ComplexityTier.COMPLEX
+ assert complexity_router._escalate_tier(ComplexityTier.COMPLEX) == ComplexityTier.REASONING
+
+ def test_escalate_tier_caps_at_highest_configured(self, complexity_router):
+ assert complexity_router._escalate_tier(ComplexityTier.REASONING) == ComplexityTier.REASONING
+
+ def test_escalate_tier_skips_unconfigured_intermediate(self, mock_router_instance):
+ router = ComplexityRouter(
+ model_name="test-router",
+ litellm_router_instance=mock_router_instance,
+ complexity_router_config={"tiers": {"SIMPLE": "gpt-4o-mini", "REASONING": "o1-preview"}},
+ )
+ assert router._escalate_tier(ComplexityTier.SIMPLE) == ComplexityTier.REASONING
+
+ def test_tier_for_model_returns_most_severe(self, mock_router_instance):
+ router = ComplexityRouter(
+ model_name="test-router",
+ litellm_router_instance=mock_router_instance,
+ complexity_router_config={
+ "tiers": {"SIMPLE": "shared", "COMPLEX": "shared", "REASONING": "top"}
+ },
+ )
+ assert router._tier_for_model("shared") == ComplexityTier.COMPLEX
+ assert router._tier_for_model("top") == ComplexityTier.REASONING
+ assert router._tier_for_model("unknown") is None
+
+ @pytest.mark.asyncio
+ async def test_escalation_bumps_classified_tier(self, mock_router_instance, basic_config):
+ router = ComplexityRouter(
+ model_name="test-router",
+ litellm_router_instance=mock_router_instance,
+ complexity_router_config=basic_config,
+ )
+ # Baseline: this prompt classifies SIMPLE.
+ baseline = await router.async_pre_routing_hook(
+ model="test-model", request_kwargs={}, messages=[{"role": "user", "content": "Hello there!"}]
+ )
+ assert baseline.model == "gpt-4o-mini"
+
+ escalated = await router.async_pre_routing_hook(
+ model="test-model",
+ request_kwargs={},
+ messages=[{"role": "user", "content": "LITELLM ESCALATE Hello there!"}],
+ )
+ assert escalated.model == "gpt-4o" # SIMPLE bumped to MEDIUM
+
+ @pytest.mark.asyncio
+ async def test_lowercase_keyword_does_not_escalate(self, mock_router_instance, basic_config):
+ router = ComplexityRouter(
+ model_name="test-router",
+ litellm_router_instance=mock_router_instance,
+ complexity_router_config=basic_config,
+ )
+ result = await router.async_pre_routing_hook(
+ model="test-model",
+ request_kwargs={},
+ messages=[{"role": "user", "content": "litellm escalate Hello there!"}],
+ )
+ assert result.model == "gpt-4o-mini" # not escalated
+
+ @pytest.mark.asyncio
+ async def test_custom_escalation_keyword(self, mock_router_instance, basic_config):
+ router = ComplexityRouter(
+ model_name="test-router",
+ litellm_router_instance=mock_router_instance,
+ complexity_router_config={**basic_config, "escalation_keywords": ["MAKE IT BETTER"]},
+ )
+ # The default keyword no longer triggers once a custom list is supplied.
+ default = await router.async_pre_routing_hook(
+ model="test-model",
+ request_kwargs={},
+ messages=[{"role": "user", "content": "LITELLM ESCALATE Hello there!"}],
+ )
+ assert default.model == "gpt-4o-mini"
+
+ custom = await router.async_pre_routing_hook(
+ model="test-model",
+ request_kwargs={},
+ messages=[{"role": "user", "content": "MAKE IT BETTER Hello there!"}],
+ )
+ assert custom.model == "gpt-4o"
+
+ @pytest.mark.asyncio
+ async def test_empty_keyword_list_disables_escalation(self, mock_router_instance, basic_config):
+ router = ComplexityRouter(
+ model_name="test-router",
+ litellm_router_instance=mock_router_instance,
+ complexity_router_config={**basic_config, "escalation_keywords": []},
+ )
+ result = await router.async_pre_routing_hook(
+ model="test-model",
+ request_kwargs={},
+ messages=[{"role": "user", "content": "LITELLM ESCALATE Hello there!"}],
+ )
+ assert result.model == "gpt-4o-mini"
+
+ @pytest.mark.asyncio
+ async def test_escalation_caps_at_highest_tier(self, mock_router_instance, basic_config):
+ router = ComplexityRouter(
+ model_name="test-router",
+ litellm_router_instance=mock_router_instance,
+ complexity_router_config=basic_config,
+ )
+ result = await router.async_pre_routing_hook(
+ model="test-model",
+ request_kwargs={},
+ messages=[
+ {
+ "role": "user",
+ "content": "LITELLM ESCALATE Let's think step by step and reason through this carefully.",
+ }
+ ],
+ )
+ assert result.model == "o1-preview" # already REASONING, stays there
+
+ @pytest.mark.asyncio
+ async def test_escalation_bumps_keyword_tier_override(self, mock_router_instance, basic_config):
+ router = ComplexityRouter(
+ model_name="test-router",
+ litellm_router_instance=mock_router_instance,
+ complexity_router_config={
+ **basic_config,
+ "keyword_tier_rules": [{"keywords": ["billing"], "tier": "SIMPLE"}],
+ },
+ )
+ baseline = await router.async_pre_routing_hook(
+ model="test-model", request_kwargs={}, messages=[{"role": "user", "content": "a billing question"}]
+ )
+ assert baseline.model == "gpt-4o-mini"
+
+ escalated = await router.async_pre_routing_hook(
+ model="test-model",
+ request_kwargs={},
+ messages=[{"role": "user", "content": "LITELLM ESCALATE a billing question"}],
+ )
+ assert escalated.model == "gpt-4o" # override SIMPLE bumped to MEDIUM
+
+ @pytest.mark.asyncio
+ async def test_escalation_overrides_session_pin_and_persists(self, mock_router_instance, basic_config):
+ """Mid-session escalation bumps relative to the pinned model (never below it) and
+ the bumped model persists for later turns."""
+ mock_router_instance.cache = DualCache()
+ router = ComplexityRouter(
+ model_name="test-router",
+ litellm_router_instance=mock_router_instance,
+ complexity_router_config={**basic_config, "session_affinity": True},
+ )
+ request_kwargs = self._request_kwargs("session-1")
+ first = await router.async_pre_routing_hook(
+ model="test-model", request_kwargs=request_kwargs, messages=[{"role": "user", "content": "Hello!"}]
+ )
+ assert first.model == "gpt-4o-mini" # pinned SIMPLE
+
+ with patch.object(router, "aclassify", wraps=router.aclassify) as spy_aclassify:
+ escalated = await router.async_pre_routing_hook(
+ model="test-model",
+ request_kwargs=request_kwargs,
+ messages=[{"role": "user", "content": "LITELLM ESCALATE"}],
+ )
+ spy_aclassify.assert_not_called()
+ assert escalated.model == "gpt-4o" # bumped relative to the SIMPLE pin, not reclassified
+
+ # The bump persists: a later ordinary turn stays on the escalated model.
+ later = await router.async_pre_routing_hook(
+ model="test-model", request_kwargs=request_kwargs, messages=[{"role": "user", "content": "thanks"}]
+ )
+ assert later.model == "gpt-4o"
+
+ # Escalating again climbs one more tier.
+ again = await router.async_pre_routing_hook(
+ model="test-model",
+ request_kwargs=request_kwargs,
+ messages=[{"role": "user", "content": "LITELLM ESCALATE still not good"}],
+ )
+ assert again.model == "claude-sonnet-4-20250514" # MEDIUM bumped to COMPLEX
+
+ def test_blank_escalation_keywords_are_stripped(self):
+ """Blank/whitespace-only phrases are dropped so `"" in message` can't escalate
+ every request; surrounding whitespace on real phrases is trimmed."""
+ assert ComplexityRouterConfig(
+ tiers={"SIMPLE": "gpt-4o-mini", "MEDIUM": "gpt-4o"},
+ escalation_keywords=["", " "],
+ ).escalation_keywords == []
+ assert ComplexityRouterConfig(
+ tiers={"SIMPLE": "gpt-4o-mini", "MEDIUM": "gpt-4o"},
+ escalation_keywords=[" LITELLM ESCALATE ", ""],
+ ).escalation_keywords == ["LITELLM ESCALATE"]
+
+ @pytest.mark.asyncio
+ async def test_blank_escalation_keyword_does_not_escalate_everything(
+ self, mock_router_instance, basic_config
+ ):
+ router = ComplexityRouter(
+ model_name="test-router",
+ litellm_router_instance=mock_router_instance,
+ complexity_router_config={**basic_config, "escalation_keywords": [""]},
+ )
+ assert router.escalation_keywords == []
+ result = await router.async_pre_routing_hook(
+ model="test-model",
+ request_kwargs={},
+ messages=[{"role": "user", "content": "Hello there!"}],
+ )
+ assert result.model == "gpt-4o-mini" # not escalated
+
+ def test_escalated_pin_stays_on_same_model_at_ceiling(self, mock_router_instance):
+ """At the highest configured tier escalation keeps the exact pinned model, even
+ when that tier's pool has peers `get_model_for_tier` could randomly pick instead."""
+ router = ComplexityRouter(
+ model_name="test-router",
+ litellm_router_instance=mock_router_instance,
+ complexity_router_config={
+ "tiers": {"SIMPLE": "gpt-4o-mini", "REASONING": ["o1-a", "o1-b", "o1-c"]}
+ },
+ )
+ for pinned in ("o1-a", "o1-b", "o1-c"):
+ assert router._escalated_pin(pinned) == pinned
+
+ @pytest.mark.asyncio
+ async def test_session_escalation_at_ceiling_keeps_multi_model_pin(self, mock_router_instance):
+ mock_router_instance.cache = DualCache()
+ router = ComplexityRouter(
+ model_name="test-router",
+ litellm_router_instance=mock_router_instance,
+ complexity_router_config={
+ "tiers": {"SIMPLE": "gpt-4o-mini", "REASONING": ["o1-a", "o1-b", "o1-c"]},
+ "session_affinity": True,
+ },
+ )
+ cache_key = router._get_session_affinity_cache_key("session-top", {})
+ await mock_router_instance.cache.async_set_cache(key=cache_key, value="o1-b")
+ result = await router.async_pre_routing_hook(
+ model="test-model",
+ request_kwargs=self._request_kwargs("session-top"),
+ messages=[{"role": "user", "content": "LITELLM ESCALATE do better"}],
+ )
+ assert result.model == "o1-b" # unchanged: no random hop to o1-a / o1-c
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 e1f90296770..a2e2ca21d00 100644
--- a/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.test.tsx
+++ b/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.test.tsx
@@ -269,4 +269,22 @@ describe("ComplexityRouterConfig", () => {
);
expect(screen.getAllByText("This tier is required")).toHaveLength(1);
});
+
+ it("renders the escalation keywords section with current keywords when the handler is provided", () => {
+ renderWithProviders(
+ <ComplexityRouterConfig
+ {...baseProps}
+ escalationKeywords={["LITELLM ESCALATE"]}
+ onEscalationKeywordsChange={vi.fn()}
+ />,
+ );
+ fireEvent.click(screen.getByText("Advanced: Escalation Keywords"));
+ expect(screen.getByText("Escalation Keywords")).toBeInTheDocument();
+ expect(screen.getByText("LITELLM ESCALATE")).toBeInTheDocument();
+ });
+
+ it("hides the escalation keywords section when no handler is provided", () => {
+ renderWithProviders(<ComplexityRouterConfig {...baseProps} />);
+ expect(screen.queryByText("Advanced: Escalation Keywords")).not.toBeInTheDocument();
+ });
});
diff --git a/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.tsx b/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.tsx
index 855a1b27df9..8008012a95c 100644
--- a/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.tsx
+++ b/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.tsx
@@ -4,6 +4,7 @@ import React from "react";
import { ModelGroup } from "@/components/llm_calls/fetch_models";
import AdaptiveRoutingConfig from "./AdaptiveRoutingConfig";
import ClassificationMethodConfig from "./ClassificationMethodConfig";
+import EscalationKeywords from "./EscalationKeywords";
import KeywordTierRules, { KeywordTierRule } from "./KeywordTierRules";
import SemanticKeywordMatching from "./SemanticKeywordMatching";
@@ -61,6 +62,8 @@ interface ComplexityRouterConfigProps {
onEmbeddingModelChange?: (model: string) => void;
matchThreshold?: number;
onMatchThresholdChange?: (threshold: number) => void;
+ escalationKeywords?: string[];
+ onEscalationKeywordsChange?: (keywords: string[]) => void;
showValidationErrors?: boolean;
}
@@ -101,6 +104,8 @@ const ComplexityRouterConfig: React.FC<ComplexityRouterConfigProps> = ({
onEmbeddingModelChange = () => {},
matchThreshold = 0.5,
onMatchThresholdChange = () => {},
+ escalationKeywords = [],
+ onEscalationKeywordsChange,
showValidationErrors = false,
}) => {
// Embedding models can't serve a chat-completion role, so they're excluded here.
@@ -213,6 +218,19 @@ const ComplexityRouterConfig: React.FC<ComplexityRouterConfigProps> = ({
),
children: <AdaptiveRoutingConfig value={value} onChange={onChange} />,
},
+ ...(onEscalationKeywordsChange
+ ? [
+ {
+ key: "escalation",
+ label: (
+ <Text strong style={{ color: "#374151" }}>
+ Advanced: Escalation Keywords
+ </Text>
+ ),
+ children: <EscalationKeywords keywords={escalationKeywords} onChange={onEscalationKeywordsChange} />,
+ },
+ ]
+ : []),
...(onKeywordTierRulesChange || onSemanticMatchingEnabledChange
? [
{
diff --git a/ui/litellm-dashboard/src/components/add_model/EscalationKeywords.tsx b/ui/litellm-dashboard/src/components/add_model/EscalationKeywords.tsx
new file mode 100644
index 00000000000..c232eb4c801
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/add_model/EscalationKeywords.tsx
@@ -0,0 +1,45 @@
+import { InfoCircleOutlined } from "@ant-design/icons";
+import { Select as AntdSelect, Tooltip, Typography } from "antd";
+import React from "react";
+
+const { Text } = Typography;
+
+export const DEFAULT_ESCALATION_KEYWORDS = ["LITELLM ESCALATE"];
+
+interface EscalationKeywordsProps {
+ keywords: string[];
+ onChange: (keywords: string[]) => void;
+}
+
+const EscalationKeywords: React.FC<EscalationKeywordsProps> = ({ keywords, onChange }) => {
+ return (
+ <div className="w-full max-w-none">
+ <div className="flex items-center gap-2 mb-1">
+ <Typography.Title level={4} style={{ margin: 0 }}>
+ Escalation Keywords
+ </Typography.Title>
+ <Tooltip title="Case-sensitive phrases a user can include in their message to force a bump to the next-higher complexity tier when they aren't happy with results. They can force a stronger model, but not choose which one.">
+ <InfoCircleOutlined className="text-gray-400" />
+ </Tooltip>
+ </div>
+ <Text type="secondary" style={{ display: "block", marginBottom: 8, fontSize: 12 }}>
+ Optional: when a user message contains one of these phrases, the request is bumped one tier higher than it would
+ otherwise route to. Matching is case-sensitive, so &quot;LITELLM ESCALATE&quot; only fires on the exact, shouted
+ form. Leave empty to disable.
+ </Text>
+ <AntdSelect
+ mode="tags"
+ value={keywords}
+ onChange={onChange}
+ placeholder="e.g., LITELLM ESCALATE"
+ tokenSeparators={[","]}
+ open={false}
+ suffixIcon={null}
+ style={{ width: "100%" }}
+ allowClear
+ />
+ </div>
+ );
+};
+
+export default EscalationKeywords;
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 5122d54db9b..6e7bc49afce 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
@@ -14,6 +14,7 @@ import ComplexityRouterConfig, {
DEFAULT_TIER_DISTANCE_PENALTY,
} from "./ComplexityRouterConfig";
import { KeywordTierRule } from "./KeywordTierRules";
+import { DEFAULT_ESCALATION_KEYWORDS } from "./EscalationKeywords";
import { DEFAULT_MATCH_THRESHOLD } from "./SemanticKeywordMatching";
import {
buildComplexityRouterConfig,
@@ -52,6 +53,7 @@ const AddAutoRouterTab: React.FC<AddAutoRouterTabProps> = ({ form, handleOk, acc
const [semanticMatchingEnabled, setSemanticMatchingEnabled] = useState<boolean>(false);
const [embeddingModel, setEmbeddingModel] = useState<string | undefined>(undefined);
const [matchThreshold, setMatchThreshold] = useState<number>(DEFAULT_MATCH_THRESHOLD);
+ const [escalationKeywords, setEscalationKeywords] = useState<string[]>(DEFAULT_ESCALATION_KEYWORDS);
const [showValidationErrors, setShowValidationErrors] = useState<boolean>(false);
// Semantic router config (existing)
@@ -141,6 +143,7 @@ const AddAutoRouterTab: React.FC<AddAutoRouterTabProps> = ({ form, handleOk, acc
semanticMatchingEnabled,
embeddingModel,
matchThreshold,
+ escalationKeywords,
adaptive,
adaptiveWeights,
tierDistancePenalty,
@@ -316,6 +319,8 @@ const AddAutoRouterTab: React.FC<AddAutoRouterTabProps> = ({ form, handleOk, acc
onEmbeddingModelChange={setEmbeddingModel}
matchThreshold={matchThreshold}
onMatchThresholdChange={setMatchThreshold}
+ escalationKeywords={escalationKeywords}
+ onEscalationKeywordsChange={setEscalationKeywords}
showValidationErrors={showValidationErrors}
/>
</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.ts
index 85a15ffad45..0c9c19d1286 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
@@ -21,6 +21,7 @@ const baseParams: BuildComplexityRouterConfigParams = {
semanticMatchingEnabled: false,
embeddingModel: undefined,
matchThreshold: 0.5,
+ escalationKeywords: ["LITELLM ESCALATE"],
adaptive: false,
adaptiveWeights: { quality: 0.3, cost: 0.7 },
tierDistancePenalty: 0.5,
@@ -28,9 +29,22 @@ const baseParams: BuildComplexityRouterConfigParams = {
};
describe("buildComplexityRouterConfig", () => {
- it("emits only tiers and classifier_type when nothing else is configured", () => {
+ it("emits tiers, classifier_type, and escalation_keywords when nothing else is configured", () => {
const config = buildComplexityRouterConfig(baseParams);
- expect(config).toEqual({ tiers, classifier_type: "heuristic" });
+ expect(config).toEqual({ tiers, classifier_type: "heuristic", escalation_keywords: ["LITELLM ESCALATE"] });
+ });
+
+ it("trims escalation keywords and drops blank entries", () => {
+ const config = buildComplexityRouterConfig({
+ ...baseParams,
+ escalationKeywords: [" LITELLM ESCALATE ", "", " ", "MAKE IT BETTER"],
+ });
+ expect(config.escalation_keywords).toEqual(["LITELLM ESCALATE", "MAKE IT BETTER"]);
+ });
+
+ it("emits an empty escalation_keywords list so clearing the field disables escalation", () => {
+ const config = buildComplexityRouterConfig({ ...baseParams, escalationKeywords: [] });
+ expect(config.escalation_keywords).toEqual([]);
});
it("passes through a tier configured with more than one model as a pool", () => {
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 3c3f21163b3..0b92dc1b02d 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
@@ -16,6 +16,7 @@ export interface BuildComplexityRouterConfigParams {
semanticMatchingEnabled: boolean;
embeddingModel: string | undefined;
matchThreshold: number;
+ escalationKeywords: string[];
adaptive: boolean;
adaptiveWeights: AdaptiveRouterWeights;
tierDistancePenalty: number;
@@ -31,6 +32,7 @@ export interface ComplexityRouterConfigPayload {
semantic_keyword_matching?: boolean;
embedding_model?: string;
match_threshold?: number;
+ escalation_keywords?: string[];
adaptive?: boolean;
adaptive_weights?: AdaptiveRouterWeights;
tier_distance_penalty?: number;
@@ -69,11 +71,13 @@ export const buildComplexityRouterConfig = ({
semanticMatchingEnabled,
embeddingModel,
matchThreshold,
+ escalationKeywords,
adaptive,
adaptiveWeights,
tierDistancePenalty,
adaptiveEligible,
}: 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
// "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)
@@ -88,6 +92,7 @@ export const buildComplexityRouterConfig = ({
...(classifierType === "llm" && classifierLlmConfig && { classifier_llm_config: classifierLlmConfig }),
...(customTechnicalKeywords.length > 0 && { custom_technical_keywords: customTechnicalKeywords }),
...(cleanedKeywordTierRules.length > 0 && { keyword_tier_rules: cleanedKeywordTierRules }),
+ escalation_keywords: cleanedEscalationKeywords,
...(semanticMatchingEnabled && {
semantic_keyword_matching: true,
embedding_model: embeddingModel,