Skip to content
Closed
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions litellm/router_strategy/complexity_router/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ The weighted sum is mapped to tiers using configurable boundaries:
| COMPLEX | 0.35 - 0.60 | Technical, multi-part requests |
| REASONING | > 0.60 | Chain-of-thought, analysis |

A prompt that matches nothing at all never reaches that table. When no dimension fires, the scorer has no evidence in either direction, so the request goes to `default_tier` (MEDIUM unless you change it) rather than falling through a score of 0.0 into SIMPLE. See [No-Signal Default](#no-signal-default) below.

## Configuration

### Basic Configuration
Expand Down Expand Up @@ -71,6 +73,9 @@ model_list:
simple_medium: 0.15
medium_complex: 0.35
complex_reasoning: 0.60

# Tier for prompts that match nothing at all (default: MEDIUM)
default_tier: MEDIUM

# Token count thresholds
token_thresholds:
Expand Down Expand Up @@ -126,6 +131,23 @@ response = litellm.completion(

## Special Behaviors

### No-Signal Default

The scorer only recognizes what is on its keyword lists, so a prompt can be genuinely hard and still match nothing: a logic puzzle, a business tradeoff, a piece of prose to edit. Every dimension then scores 0, and treating that silence as evidence of simplicity is how unmatched traffic used to end up on the cheapest model.

When no dimension fires, the router returns `default_tier` instead of consulting the boundaries, and logs the classification with `signals=['no-signal']`:

```yaml
complexity_router_config:
default_tier: MEDIUM # SIMPLE | MEDIUM | COMPLEX | REASONING
```

Set `default_tier: SIMPLE` to keep unmatched traffic on the cheapest tier, which is how the router behaved before this setting existed. A `default_tier` you set explicitly has to have a model behind it, either its own non-empty entry in `tiers` or a `default_model`; the config is rejected at load time otherwise, rather than failing on the first unmatched request.

The check is on the individual dimensions, not on the weighted score, because contributions cancel. `"hi, quick python question"` scores zero with three dimensions firing (short prompt, a simple indicator, a code keyword); it has real evidence of being simple and stays SIMPLE. Prompts shorter than the `simple` token threshold or longer than the `complex` one also fire `tokenCount`, so they score normally and are outside this path.

The LLM classifier falls back to this scorer when it times out or errors, so `default_tier` also decides where unmatched traffic lands during a classifier outage.

### Reasoning Override

If 2+ reasoning markers are detected in the user message, the request is automatically routed to the REASONING tier regardless of the weighted score. This ensures complex reasoning tasks get the appropriate model.
Expand Down
34 changes: 32 additions & 2 deletions litellm/router_strategy/complexity_router/complexity_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
DEFAULT_REASONING_KEYWORDS,
DEFAULT_SIMPLE_KEYWORDS,
DEFAULT_TECHNICAL_KEYWORDS,
NO_SIGNAL_MARKER,
TIER_SEVERITY_ORDER,
ComplexityRouterConfig,
ComplexityTier,
Expand Down Expand Up @@ -473,10 +474,27 @@ def classify(self, prompt: str, system_prompt: str | None = None) -> tuple[Compl

def _score_and_classify(
self, prompt: str, system_prompt: str | None = None
) -> tuple[ComplexityTier, float, tuple[str, ...], Literal["heuristic_scorer", "reasoning_override"]]:
) -> tuple[
ComplexityTier,
float,
tuple[str, ...],
Literal["heuristic_scorer", "reasoning_override", "no_signal_default"],
]:
"""
Classify a prompt by complexity, reporting whether the score chose the tier.

When no dimension fires at all, the prompt carries no evidence either way, so
`default_tier` (MEDIUM unless configured otherwise) is returned instead of letting
the score of 0.0 fall through the band mapping into SIMPLE.

That check reads the signals, not the score, and not the individual dimension
scores either. A weighted score of zero does not mean nothing was recognised,
because contributions cancel: "hi, quick python question" comes to zero with three
dimensions firing and is genuinely simple. A dimension scoring zero does not mean
it stayed silent either, since a scorer is free to treat "no match" as a nonzero
baseline or to report a neutral finding; a signal is the one thing a dimension
emits only when it recognised something.

Args:
prompt: The user's prompt/message.
system_prompt: Optional system prompt for context.
Expand Down Expand Up @@ -558,6 +576,9 @@ def _score_and_classify(
if reasoning_match_count >= 2:
return ComplexityTier.REASONING, weighted_score, tuple(signals), "reasoning_override"

if not signals:
return self.config.default_tier, weighted_score, (NO_SIGNAL_MARKER,), "no_signal_default"

# Map score to tier
boundaries = self._effective_tier_boundaries()
if weighted_score < boundaries["simple_medium"]:
Expand Down Expand Up @@ -850,11 +871,20 @@ async def _pick_model_for_tier(
from litellm.types.router import RoutingContext

tier_key = tier.value
candidates = list(self._tier_pools().get(tier_key, []))
if not candidates:
# Distinct from the plugin denial below: nothing was filtered out, the tier was
# never given models. Saying "after routing-plugin filtering" would send an
# operator to read plugin code for what is a gap in `tiers`.
raise ValueError(
f"Tier {tier_key} has no models configured. Routing plugins are configured, so "
f"default_model is not consulted: a model the plugins never vetted must not serve"
)
metadata_key = "litellm_metadata" if "litellm_metadata" in request_kwargs else "metadata"
context = RoutingContext(
raw_messages=raw_messages or [],
structured_messages=resolved_messages or [],
candidate_models=list(self._tier_pools().get(tier_key, [])),
candidate_models=candidates,
metadata=request_kwargs.get(metadata_key) or {},
)
for plugin in self.config.plugins:
Expand Down
41 changes: 41 additions & 0 deletions litellm/router_strategy/complexity_router/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ class ComplexityTier(str, Enum):
DEFAULT_CLASSIFIER_CONTEXT_WINDOW_SIZE: int = 3
DEFAULT_CLASSIFIER_CONTEXT_PER_TURN_CHARS: int = 200

NO_SIGNAL_MARKER: str = "no-signal"


class KeywordTierRule(BaseModel):
"""A deterministic override: if any keyword matches, route to this tier."""
Expand Down Expand Up @@ -269,6 +271,17 @@ class ComplexityRouterConfig(BaseModel):
description="Score boundaries between tiers",
)

default_tier: ComplexityTier = Field(
default=ComplexityTier.MEDIUM,
description=(
"Tier used when no scoring dimension fires, i.e. the prompt matched no keyword, "
"pattern or token-count threshold and the scorer has no evidence either way. "
"When set explicitly it must have a model behind it: a non-empty entry in `tiers`, "
"or `default_model`. "
"Set to SIMPLE to restore the previous behavior of treating unmatched traffic as simple"
),
)
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved

# Token count thresholds
token_thresholds: dict[str, int] = Field(
default_factory=lambda: DEFAULT_TOKEN_THRESHOLDS.copy(),
Expand Down Expand Up @@ -459,6 +472,34 @@ def _validate_llm_classifier_config(self) -> "ComplexityRouterConfig":
raise ValueError("classifier_llm_config is required when classifier_type is 'llm'")
return self

@model_validator(mode="after")
def _validate_default_tier_is_servable(self) -> "ComplexityRouterConfig":
if "default_tier" not in self.model_fields_set:
return self
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
if self.tiers.get(self.default_tier.value):
return self
# default_model rescues this only without plugins. The plugin path never falls back
# to it, since a model the plugins did not vet must not serve, so accepting it here
# would validate a config whose every no-signal request fails at routing time.
if self.default_model and not self.plugins:
return self
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
remedy = (
"Add it to tiers, or name a tier that is configured"
if self.plugins
else "Add it to tiers, name a tier that is configured, or set default_model in complexity_router_config"
)
because = (
"routing plugins are configured, so default_model is not consulted: a model the plugins "
"never vetted must not serve"
if self.plugins
else "the deployment-level complexity_router_default_model does not count here, because "
"falling through to it would serve every no-signal request from a model this tier never names"
)
raise ValueError(
f"default_tier {self.default_tier.value} is not a non-empty entry in tiers "
f"({sorted(self.tiers)}). {remedy}; {because}"
)

@model_validator(mode="after")
def _validate_adaptive_pools(self) -> "ComplexityRouterConfig":
if not self.adaptive:
Expand Down
1 change: 1 addition & 0 deletions litellm/types/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2699,6 +2699,7 @@ class StandardLoggingRoutingDecisionTierBoundaries(TypedDict):
# that tells a reader the score did NOT choose the tier; encoding it as free text
# meant anything that filtered `signals` silently changed what the row claimed.
"reasoning_override",
"no_signal_default",
"llm_classifier",
"literal_keyword_match",
"semantic_keyword_match",
Expand Down
1 change: 1 addition & 0 deletions tests/e2e/router/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
complexity_router_config={
"classifier_type": "llm",
"classifier_llm_config": {"model": "gpt-5.5"},
"default_tier": "SIMPLE",
"tiers": {
"SIMPLE": "gpt-5.5",
"MEDIUM": "claude-haiku-4-5",
Expand Down
10 changes: 7 additions & 3 deletions tests/e2e/router/test_complexity_router_e2e.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,13 @@
below carries none of the heuristic scorer's reasoning/technical/code keywords and
stays short, so heuristic scoring lands it in SIMPLE (openai), but an LLM classifier
reads it as a decision that has to weigh tradeoffs and lands it above SIMPLE
(anthropic). The served deployment is read back from the spend log's `model`, so
anthropic proves the classifier ran and openai proves it silently fell back - the
exact failure before the fix.
(anthropic). The router config pins `default_tier: SIMPLE` to keep that split intact:
a prompt with no scoring signal otherwise abstains to MEDIUM, the same anthropic
backend the LLM arm picks, and the fallback would stop being visible.

The served deployment is read back from the spend log's `model`, so anthropic proves
the classifier ran and openai proves it silently fell back - the exact failure before
the fix.
"""

import pytest
Expand Down
Loading
Loading