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(router): integrate benchmark calibration and merge staging

Tin Chi Lo82937d996910
diff --cc litellm/router_strategy/complexity_router/README.md
index 6150be571cb,4aa342ea59f..801d5149a24
--- a/litellm/router_strategy/complexity_router/README.md
+++ b/litellm/router_strategy/complexity_router/README.md
@@@ -68,66 -68,6 +68,117 @@@ still resolve to a deployment in `model
- abc
```
+### Capability forecasting
+
+Set `classifier_type: capability` to use
+[NVIDIA NeMo Switchyard's packaged capability classifier](https://github.com/NVIDIA-NeMo/Switchyard/blob/main/crates/libsy/src/prompts/capability-classifier/prompt.md).
+The classifier forecasts the probability that an efficient model completes
+the whole task, identifies the capability-card boundary that applies, and leaves the
+route choice to a deterministic threshold policy
+
+```yaml
+model_list:
+ - model_name: smart-router
+ litellm_params:
+ model: auto_router/complexity_router
+ complexity_router_config:
+ classifier_type: capability
+ classifier_llm_config:
+ model: classifier-model
+ capability_classifier_config:
+ efficient_tier: SIMPLE
+ capable_tier: REASONING
+ base_threshold: 0.5
+ threshold_step: 0.1
+ tiers:
+ SIMPLE:
+ - efficient-model-a
+ - efficient-model-b
+ REASONING: capable-model
+```
+
+The structured classifier verdict contains `crux`, `primary_rule`,
+`capability_boundary`, and `p_solve`. The policy computes the required solve
+probability as follows
+
+- `supported`: `base_threshold`
+- `uncertain` or `unmatched`: `base_threshold + threshold_step`
+- `unsupported`: `base_threshold + 2 * threshold_step`
+
+The efficient tier is selected when `p_solve` is greater than or equal to the
+adjusted threshold. Otherwise the capable tier is selected. A malformed,
+inconsistent, empty, or unavailable verdict always fails closed to the capable
+tier. `base_threshold` is required, `threshold_step` defaults to `0`, and their
+maximum adjusted threshold must not exceed `1`
+
+The classifier receives the packaged Switchyard system prompt, the opening user
+task, and the latest user follow-up when present. Caller system messages,
+assistant turns, and intermediate tool results are not sent. The classifier call
+uses strict JSON Schema output and the existing classifier timeout, circuit
+breaker, attribution, redaction, reasoning-effort, and optional vision settings
+
+`efficient_tier` and `capable_tier` name built-in complexity tiers with configured
+model pools. The forecast still makes one binary quality decision, while the
+ordinary tier pool may contain multiple equivalent deployments. Session affinity,
+keyword overrides, plan-mode floors, modality checks, and other post-classification
+complexity-router controls continue to apply
+
+Routing decisions record the adjusted threshold and the complete valid forecast:
+`classifier_p_solve`, `classifier_capability_boundary`, `classifier_primary_rule`,
+and `classifier_crux`. Prompt redaction removes `classifier_crux` while retaining
+the derived fields needed to audit the decision
+
++#### Calibrating solve probabilities
++
++Supply a fitted monotone logit calibration under `capability_classifier_config`
++to transform the forecast before applying the threshold. Calibration is opt-in;
++without it the router uses the raw probability. Fit coefficients on benchmark
++outcomes from separate training repositories, select thresholds on a validation
++split, and report quality and cost on an untouched evaluation split
++
++```yaml
++capability_classifier_config:
++ efficient_tier: SIMPLE
++ capable_tier: REASONING
++ base_threshold: 0.66
++ threshold_step: 0
++ max_output_tokens: 512
++ response_format: json_object
++ calibration:
++ version: your-benchmark-artifact-v1
++ slope: 1.0
++ intercept: 0.0
++```
++
++The example coefficients are an identity mapping, not a trained calibration.
++The mapping is `sigmoid(slope * logit(clip(p_solve, 1e-6, 1-1e-6)) + intercept)`.
++The slope must be nonnegative, so calibration cannot improve ranking. It can
++make probabilities more accurate and thresholds easier to interpret. The version
++is recorded for auditing; the router does not check whether an artifact matches
++the judge, capability card, efficient solver, or agent harness. Operators must
++keep those aligned and refit when they change
++
++Logs retain `classifier_p_solve` and add `classifier_calibrated_p_solve` and
++`classifier_calibration_version`. `classifier_threshold` is compared to the
++calibrated probability. Invalid verdicts still route to the capable tier
++
++`response_format` defaults to `json_schema`. For endpoints that support JSON
++objects but not strict schemas, `json_object` appends the same schema to the
++unchanged capability prompt and retains strict local validation. Set
++`classifier_llm_config.timeout_ms` to cover the measured judge latency; a local
++judge may need longer than the default 3000 ms. `max_output_tokens` still defaults
++to 4096; 512 is an explicit benchmark setting for a short, non-reasoning judge
++
++For a controlled whole-task benchmark, use `adaptive: false`,
++`session_affinity: true`, and a unique session ID for every task and policy arm.
++Disable keyword, plan-mode, housekeeping, and other optional overrides when
++measuring only the capability policy. When adaptive selection is enabled, it
++cannot select below the capability decision, including a capable-tier fallback
++
++Configure capability forecasting through YAML or the model-management API.
++The dashboard preserves its classifier and calibration on an untouched save;
++it does not provide a capability-card editor
++
### Heuristic v2
Set `classifier_type: heuristic_v2` to classify with the bundled calibrated
diff --cc litellm/router_strategy/complexity_router/__init__.py
index 7627f4e96d0,fa21f2eee10..5447e4e0f6d
--- a/litellm/router_strategy/complexity_router/__init__.py
+++ b/litellm/router_strategy/complexity_router/__init__.py
@@@ -16,7 -16,6 +16,8 @@@ from litellm.router_strategy.complexity
from litellm.router_strategy.complexity_router.config import (
DEFAULT_CLASSIFIER_CONTEXT_WINDOW_SIZE,
DEFAULT_COMPLEXITY_CONFIG,
++ CapabilityCalibrationConfig,
+ CapabilityClassifierConfig,
ClassificationRubric,
ComplexityRouterConfig,
ComplexityTier,
@@@ -29,7 -28,6 +30,8 @@@
__all__ = [
"DEFAULT_CLASSIFIER_CONTEXT_WINDOW_SIZE",
"DEFAULT_COMPLEXITY_CONFIG",
++ "CapabilityCalibrationConfig",
+ "CapabilityClassifierConfig",
"ClassificationRubric",
"ComplexityRouter",
"ComplexityRouterConfig",
diff --cc litellm/router_strategy/complexity_router/capability_classifier.py
index a1b6ef27d75,00000000000..5adf15cfc19
mode 100644,000000..100644
--- a/litellm/router_strategy/complexity_router/capability_classifier.py
+++ b/litellm/router_strategy/complexity_router/capability_classifier.py
@@@ -1,183 -1,0 +1,211 @@@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+"""Capability forecast contract and routing policy adapted from NVIDIA NeMo Switchyard."""
+
++import json
+from collections.abc import Mapping
+from sys import float_info
+from types import MappingProxyType
- from typing import Final, Literal, TypeAlias
++from typing import Final, Literal, NamedTuple, TypeAlias
+
+from pydantic import BaseModel, ConfigDict, Field, StrictFloat, TypeAdapter, model_validator
+
+CapabilityBoundary: TypeAlias = Literal["supported", "uncertain", "unsupported", "unmatched"]
+CapabilityRule: TypeAlias = Literal[
+ "SUP-1",
+ "SUP-2",
+ "SUP-3",
+ "SUP-4",
+ "SUP-5",
+ "UNC-1",
+ "UNC-2",
+ "LIM-1",
+ "LIM-2",
+ "none",
+]
+
+CAPABILITY_CLASSIFIER_SYSTEM_PROMPT: Final = """You are a task-level probability forecaster for a model router. You receive the
+task's opening instruction and, when present, its latest user follow-up, plus
+the qualitative capability card below.
+
+Forecast one binary event:
+
+SUCCESS means that the efficient agent completes the whole task correctly on
+one fresh run under the actual harness, tools, and budget, as judged by the
+final verifier. FAILURE means any other outcome. The two outcomes are
+exhaustive.
+
+Use only evidence in the instruction and the capability card. Do not assume
+hidden repository state, unmentioned tools, validators, documentation, access,
+or future work habits. Do not invent empirical counts, success rates, or base
+rates. The capability card is qualitative evidence, not a measured prior.
+
+# Assessment procedure
+
+1. State the crux: the hardest material requirement for whole-task success.
+2. Select the one capability rule that best describes the crux. Use
+ primary_rule=none and capability_boundary=unmatched when no rule applies.
+ Rule ids are opaque labels. Do not infer a boundary from an id's spelling.
+3. Privately identify the strongest instruction-visible reasons for SUCCESS
+ and FAILURE, then imagine the most likely concrete failure.
+4. Privately consider material unknowns. Missing information should limit
+ extreme estimates, but it is not evidence that p_solve must equal 0.50.
+5. Estimate p_solve last. It is the probability of whole-task SUCCESS, not
+ confidence in this assessment, a route recommendation, or a cost judgment.
+
+Interpret probabilities as natural frequencies. If p_solve is 0.70 for 100
+comparable fresh runs, about 70 should succeed and 30 should fail. Use the full
+range when justified. Reserve 0.00 and 1.00 for outcomes that are logically
+impossible or certain under the visible contract. Supported does not mean 1.00,
+and unsupported does not mean 0.00. The downstream routing threshold is not
+part of this forecast.
+
+# Efficient-agent capability card
+
+The route verbs in this source card are inherited qualitative descriptions.
+They do not ask you to output a route and do not assign a fixed probability to
+any boundary.
+
+- SUP-1 [supported]: Route to the Efficient model when the task provides a complete output contract and a deterministic local validator that covers the material requirements.
+- SUP-2 [supported]: Route to the Efficient model when all required inputs are available, the target environment can be inspected, and correctness can be verified end-to-end without inaccessible external state.
+- SUP-3 [supported]: Route to the Efficient model when mathematical behavior, interfaces, shapes, data types, tolerances, and performance requirements are explicit and exercised by a representative harness.
+- SUP-4 [supported]: Route to the Efficient model when the required mechanism is identified, the relevant search space is bounded, and the success condition is executable. Do not infer this rule merely from the task's technical domain.
+- SUP-5 [supported]: Route to the Efficient model when reconstruction or behavioral reproduction is constrained by an executable reference, parser, format specification, or checker strong enough to distinguish correct from merely plausible output.
+- UNC-1 [uncertain]: Treat the route as uncertain when multiple reasonable interpretations of preprocessing, representation, indexing, naming, or output placement would produce different results and neither the instructions nor a validator resolve the choice.
+- UNC-2 [uncertain]: Treat the route as uncertain when success requires finding every relevant item across heterogeneous inputs or environment state, but the task does not define the search boundary or provide a completeness check.
+- LIM-1 [unsupported]: Prefer the Capable model when correctness depends primarily on extracting precise information from noisy visual, temporal, or rendered media and no machine-checkable extraction or replay mechanism is available.
+- LIM-2 [unsupported]: Prefer the Capable model when success depends on reproducing undocumented reference behavior, hidden intermediate state, or an unknown configuration, and small deviations fail despite satisfying the visible specification.
+
+# Output
+
+Return exactly one JSON object matching the response schema supplied with the
+request. Do not include markdown or commentary.
+
+p_solve must be between 0.00 and 1.00. p_fail is exactly 1.00 - p_solve and
+must not be emitted separately. Do not output recommended_route, confidence,
+abstain, counts, task totals, empirical rates, or any other field."""
+
+_BOUNDARY_STEPS: Final = MappingProxyType(
+ {
+ "supported": 0,
+ "uncertain": 1,
+ "unmatched": 1,
+ "unsupported": 2,
+ }
+)
+
+_RULE_BOUNDARIES: Final = MappingProxyType(
+ {
+ "SUP-1": "supported",
+ "SUP-2": "supported",
+ "SUP-3": "supported",
+ "SUP-4": "supported",
+ "SUP-5": "supported",
+ "UNC-1": "uncertain",
+ "UNC-2": "uncertain",
+ "LIM-1": "unsupported",
+ "LIM-2": "unsupported",
+ "none": "unmatched",
+ }
+)
+
+
+class CapabilityClassifierVerdict(BaseModel):
+ """Strict structured verdict returned by the capability forecaster."""
+
+ model_config = ConfigDict(extra="forbid", frozen=True)
+
+ crux: str = Field(min_length=1)
+ primary_rule: CapabilityRule
+ capability_boundary: CapabilityBoundary
+ p_solve: StrictFloat = Field(ge=0.0, le=1.0)
+
+ @model_validator(mode="after")
+ def _validate_rule_boundary_pair(self) -> "CapabilityClassifierVerdict":
+ if not self.crux.strip():
+ raise ValueError("crux must contain non-whitespace text")
+ expected: Final = _RULE_BOUNDARIES[self.primary_rule]
+ if self.capability_boundary != expected:
+ raise ValueError(
+ f"primary_rule {self.primary_rule!r} requires capability_boundary {expected!r}, "
+ f"got {self.capability_boundary!r}"
+ )
+ return self
+
+ def routing_threshold(self, base_threshold: float, threshold_step: float) -> float:
+ """Required efficient-model solve probability for this boundary."""
+ return base_threshold + _BOUNDARY_STEPS[self.capability_boundary] * threshold_step
+
+ def meets_routing_threshold(self, threshold: float) -> bool:
+ """Inclusive comparison with Switchyard's one-epsilon rounding guard."""
+ return self.p_solve >= threshold or abs(threshold - self.p_solve) <= float_info.epsilon
+
+
++class CapabilityClassifierForecast(NamedTuple):
++ verdict: CapabilityClassifierVerdict
++ threshold: float
++ p_solve: float
++ calibration_version: str | None
++
++ def meets_routing_threshold(self) -> bool:
++ return self.p_solve >= self.threshold or abs(self.threshold - self.p_solve) <= float_info.epsilon
++
++
+_CAPABILITY_CLASSIFIER_RESPONSE_FORMAT_JSON: Final = """{
+ "type": "json_schema",
+ "json_schema": {
+ "name": "CapabilityClassifierDecision",
+ "strict": true,
+ "schema": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["crux", "primary_rule", "capability_boundary", "p_solve"],
+ "properties": {
+ "crux": {"type": "string", "minLength": 1},
+ "primary_rule": {
+ "type": "string",
+ "enum": ["SUP-1", "SUP-2", "SUP-3", "SUP-4", "SUP-5", "UNC-1", "UNC-2", "LIM-1", "LIM-2", "none"]
+ },
+ "capability_boundary": {
+ "type": "string",
+ "enum": ["supported", "uncertain", "unsupported", "unmatched"]
+ },
+ "p_solve": {"type": "number", "minimum": 0.0, "maximum": 1.0}
+ }
+ }
+ }
+}"""
+
+_RESPONSE_FORMAT_ADAPTER: Final = TypeAdapter(Mapping[str, object])
+
+
- def capability_classifier_response_format() -> Mapping[str, object]:
++def capability_classifier_response_format(
++ mode: Literal["json_schema", "json_object"] = "json_schema",
++) -> Mapping[str, object]:
+ """Fresh copy of Switchyard's packaged strict JSON Schema wrapper."""
- return _RESPONSE_FORMAT_ADAPTER.validate_json(_CAPABILITY_CLASSIFIER_RESPONSE_FORMAT_JSON)
++ return (
++ {"type": "json_object"}
++ if mode == "json_object"
++ else _RESPONSE_FORMAT_ADAPTER.validate_json(_CAPABILITY_CLASSIFIER_RESPONSE_FORMAT_JSON)
++ )
++
++
++def capability_classifier_system_prompt(mode: Literal["json_schema", "json_object"]) -> str:
++ if mode == "json_schema":
++ return CAPABILITY_CLASSIFIER_SYSTEM_PROMPT
++ wrapper: Final = _RESPONSE_FORMAT_ADAPTER.validate_python(capability_classifier_response_format()["json_schema"])
++ return (
++ CAPABILITY_CLASSIFIER_SYSTEM_PROMPT
++ + "\n\nReturn exactly one JSON object matching this JSON Schema:\n"
++ + json.dumps(wrapper["schema"], indent=2, sort_keys=True)
++ )
+
+
+def parse_capability_classifier_verdict(content: str) -> CapabilityClassifierVerdict:
+ """Parse raw JSON or the fenced JSON shape tolerated by Switchyard."""
+ text: Final = content.strip()
+ if not text.startswith("```"):
+ return CapabilityClassifierVerdict.model_validate_json(text)
+ unfenced: Final = text.removeprefix("```").removeprefix("json").lstrip("\n\r")
+ return CapabilityClassifierVerdict.model_validate_json(unfenced.removesuffix("```").strip())
diff --cc litellm/router_strategy/complexity_router/complexity_router.py
index 8625cdd9ad3,9deccc9a468..ed523fd6019
--- a/litellm/router_strategy/complexity_router/complexity_router.py
+++ b/litellm/router_strategy/complexity_router/complexity_router.py
@@@ -65,12 -69,6 +70,12 @@@ from litellm.types.utils import
StandardLoggingRoutingDecisionTierBoundaries,
)
+from .capability_classifier import (
- CAPABILITY_CLASSIFIER_SYSTEM_PROMPT,
- CapabilityClassifierVerdict,
++ CapabilityClassifierForecast,
+ capability_classifier_response_format,
++ capability_classifier_system_prompt,
+ parse_capability_classifier_verdict,
+)
from .classification_rubrics import BUSINESS_TIER_CRITERIA, calibration_examples_section
from .config import (
CALIBRATION_EXAMPLES_HEADING,
@@@ -921,33 -998,12 +1007,38 @@@ class ClassificationOutcome(NamedTuple)
"default_model_fallback",
]
classifier_cost: float | None = None
- capability_verdict: CapabilityClassifierVerdict | None = None
- capability_threshold: float | None = None
++ capability_forecast: CapabilityClassifierForecast | None = None
def _with_signal(outcome: ClassificationOutcome, signal: str | None) -> ClassificationOutcome:
return outcome if signal is None else outcome._replace(signals=(*outcome.signals, signal))
+def _with_capability_forecast(
+ decision: StandardLoggingRoutingDecision, outcome: ClassificationOutcome
+) -> StandardLoggingRoutingDecision:
+ """Attach the validated capability verdict and applied threshold to its decision record."""
- verdict: Final = outcome.capability_verdict
- threshold: Final = outcome.capability_threshold
- if verdict is None or threshold is None:
++ forecast: Final = outcome.capability_forecast
++ if forecast is None:
+ return decision
++ verdict: Final = forecast.verdict
+ enriched: Final[StandardLoggingRoutingDecision] = { # mutable-ok: routing decisions are JSON TypedDict records
+ **decision,
+ "classifier_crux": verdict.crux,
+ "classifier_primary_rule": verdict.primary_rule,
+ "classifier_capability_boundary": verdict.capability_boundary,
+ "classifier_p_solve": verdict.p_solve,
- "classifier_threshold": threshold,
++ "classifier_threshold": forecast.threshold,
++ }
++ if forecast.calibration_version is None:
++ return enriched
++ return {
++ **enriched,
++ "classifier_calibrated_p_solve": forecast.p_solve,
++ "classifier_calibration_version": forecast.calibration_version,
+ }
- return enriched
+
+
class _ClassifierCircuitBreaker:
"""Process-local timeout breaker for one complexity-router classifier.
@@@ -1191,12 -1265,8 +1300,15 @@@ class ComplexityRouter(CustomLogger)
self._classifier_system_prompt: str | None = (
self._build_classifier_system_prompt() if llm_classifier_configured else None
)
++ capability_config: Final = self.config.capability_classifier_config
self._classifier_response_format: Mapping[str, object] | None = (
- type_to_response_format_param(_tier_classification_model(self.config.classifier_wire_labels()))
+ (
- capability_classifier_response_format()
++ capability_classifier_response_format(
++ capability_config.response_format if capability_config is not None else "json_schema"
++ )
+ if self.config.classifier_type == "capability"
+ else type_to_response_format_param(_tier_classification_model(self.config.classifier_wire_labels()))
+ )
if llm_classifier_configured
else None
)
@@@ -1222,8 -1292,6 +1334,11 @@@
llm_config: Final = self.config.classifier_llm_config
if llm_config is None:
raise ValueError("classifier_llm_config is not set")
+ if self.config.classifier_type == "capability":
- return CAPABILITY_CLASSIFIER_SYSTEM_PROMPT
++ capability: Final = self.config.capability_classifier_config
++ return capability_classifier_system_prompt(
++ capability.response_format if capability is not None else "json_schema"
++ )
definitions: Final = self.config.tier_definitions
if definitions is not None:
return custom_tier_classification_prompt(
@@@ -1727,69 -1820,6 +1869,66 @@@
)
)
+ async def _capability_classifier_outcome(
+ self,
+ prompt: str,
+ request_kwargs: Mapping[str, object] | None,
+ messages: Sequence[Mapping[str, object]] | None,
+ ) -> ClassificationOutcome:
+ """Forecast efficient-tier success, then apply the deterministic boundary policy."""
+ breaker: Final = self._classifier_circuit_breaker
+ permit: Final = breaker.acquire_permit() if breaker is not None else None
+ if breaker is not None and permit is None:
+ return self._capability_classifier_failure_outcome(
+ "capability classifier circuit is open", signal=_CLASSIFIER_CIRCUIT_OPEN_SIGNAL
+ )
+ try:
- tier, classifier_cost, verdict, threshold = await self._classify_with_capability_llm(
- prompt, request_kwargs, messages
- )
++ tier, classifier_cost, forecast = await self._classify_with_capability_llm(prompt, request_kwargs, messages)
+ if breaker is not None and permit is not None:
+ breaker.record_success(permit)
+ return ClassificationOutcome(
+ tier=tier,
+ score=None,
+ signals=(
- f"capability-boundary:{verdict.capability_boundary}",
- f"capability-rule:{verdict.primary_rule}",
++ f"capability-boundary:{forecast.verdict.capability_boundary}",
++ f"capability-rule:{forecast.verdict.primary_rule}",
+ ),
+ cause="capability_classifier",
+ classifier_cost=classifier_cost,
- capability_verdict=verdict,
- capability_threshold=threshold,
++ capability_forecast=forecast,
+ )
+ except asyncio.CancelledError:
+ if breaker is not None and permit is not None:
+ breaker.record_failure(permit, is_timeout=False)
+ raise
+ except Exception as e: # noqa: BLE001 -- every unavailable or invalid judge verdict must fail closed
+ if breaker is not None and permit is not None:
+ breaker.record_failure(permit, is_timeout=_is_classifier_timeout(e))
+ return self._capability_classifier_failure_outcome(f"capability classifier failed ({e})")
+
+ def _capability_classifier_failure_outcome(self, reason: str, signal: str | None = None) -> ClassificationOutcome:
+ """Fail closed to the configured capable tier without consulting another taxonomy."""
+ capability: Final = self.config.capability_classifier_config
+ if capability is None:
+ raise ValueError("capability_classifier_config is not set")
+ verbose_router_logger.warning(
+ "ComplexityRouter: %s, routing to capable_tier %s", reason, capability.capable_tier
+ )
+ signals: Final = (
+ ("capability-classifier-fallback",)
+ if signal is None
+ else (
+ "capability-classifier-fallback",
+ signal,
+ )
+ )
+ return ClassificationOutcome(
+ tier=ComplexityTier(capability.capable_tier),
+ score=None,
+ signals=signals,
+ cause="capability_classifier_fallback",
+ )
+
async def _llm_classifier_outcome(
self,
prompt: str,
@@@ -2033,117 -2075,82 +2177,171 @@@
{"role": "system", "content": classifier_system_prompt},
{"role": "user", "content": user_content},
]
- content, classifier_cost = await self._call_classifier_model(messages_for_call, request_kwargs)
- response_format: Final = classifier_response_format
- classifier_call_params: Mapping[str, str] = EMPTY_MAPPING
- if llm_config.reasoning_effort is not None:
- classifier_call_params = MappingProxyType({"reasoning_effort": llm_config.reasoning_effort})
++ content, classifier_cost = await self._call_classifier_model(
++ messages_for_call, request_kwargs, encrypted_task=encrypted_task
++ )
+ raw_tier: Final = _LabeledTierClassification.model_validate_json(content).tier
+ tier: Final = self.config.resolve_classified_tier(raw_tier)
+ if tier is None:
+ raise ValueError(f"LLM classifier returned an unrecognized tier: {raw_tier!r}")
+ return tier, classifier_cost
- payload: Final = (
+ async def _classify_with_capability_llm(
+ self,
+ prompt: str,
+ request_kwargs: Mapping[str, object] | None,
+ messages: Sequence[Mapping[str, object]] | None,
- ) -> tuple[ComplexityTier, float | None, CapabilityClassifierVerdict, float]:
++ ) -> tuple[ComplexityTier, float | None, CapabilityClassifierForecast]:
+ """Call the packaged capability forecaster and apply its two-tier policy."""
+ capability: Final = self.config.capability_classifier_config
+ classifier_system_prompt: Final = self._classifier_system_prompt
+ if capability is None or classifier_system_prompt is None:
+ raise ValueError("capability classifier is not configured")
+
+ asks_newest_first: Final = tuple(_iter_human_asks_newest_first(messages or (), self._reminder_markers))
+ opening_task: Final = asks_newest_first[-1] if asks_newest_first else prompt
+ latest_follow_up: Final = asks_newest_first[0] if len(asks_newest_first) > 1 else None
+ task_messages: list[AllMessageValues] = [ # mutable-ok: the latest message gains optional image parts below
+ {"role": "user", "content": opening_task}, # mutable-ok: SDK messages are dict-shaped
+ ]
+ if latest_follow_up is not None:
+ task_messages.append( # mutable-ok: the provider SDK requires a concrete message list
+ {"role": "user", "content": latest_follow_up} # mutable-ok: SDK messages are dict-shaped
+ )
+
+ image_parts: Final = self._classifier_image_parts(messages)
+ if image_parts:
+ latest_text: Final = latest_follow_up or opening_task
+ task_messages[-1] = { # mutable-ok: SDK messages are dict-shaped
+ "role": "user",
+ "content": [ # mutable-ok: multimodal SDK content is a JSON array
+ {"type": "text", "text": latest_text}, # mutable-ok: SDK content parts are dict-shaped
+ *image_parts,
+ ],
+ }
+ messages_for_call: Final[list[AllMessageValues]] = [ # mutable-ok: provider SDK requires a concrete list
+ {"role": "system", "content": classifier_system_prompt}, # mutable-ok: SDK messages are dict-shaped
+ *task_messages,
+ ]
+ content, classifier_cost = await self._call_classifier_model(
+ messages_for_call,
+ request_kwargs,
+ max_output_tokens=capability.max_output_tokens,
++ encrypted_task=_encrypted_classifier_task(
++ request_kwargs, self._reminder_markers_for_request(request_kwargs or EMPTY_MAPPING)
++ ),
+ )
+ verdict: Final = parse_capability_classifier_verdict(content)
+ threshold: Final = verdict.routing_threshold(capability.base_threshold, capability.threshold_step)
++ calibration: Final = capability.calibration
++ forecast: Final = CapabilityClassifierForecast(
++ verdict=verdict,
++ threshold=threshold,
++ p_solve=calibration.calibrate(verdict.p_solve) if calibration is not None else verdict.p_solve,
++ calibration_version=calibration.version if calibration is not None else None,
++ )
+ selected_tier: Final = (
- capability.efficient_tier if verdict.meets_routing_threshold(threshold) else capability.capable_tier
++ capability.efficient_tier if forecast.meets_routing_threshold() else capability.capable_tier
+ )
- return ComplexityTier(selected_tier), classifier_cost, verdict, threshold
++ return ComplexityTier(selected_tier), classifier_cost, forecast
+
+ async def _call_classifier_model(
+ self,
+ messages_for_call: list[AllMessageValues], # mutable-ok: provider SDK requires a concrete message list
+ request_kwargs: Mapping[str, object] | None,
+ max_output_tokens: int | None = None,
++ encrypted_task: Mapping[str, object] | None = None,
+ ) -> tuple[str, float | None]:
+ """Execute one structured classifier call with the router's shared safeguards."""
+ llm_config: Final = self.config.classifier_llm_config
+ response_format: Final = self._classifier_response_format
+ if llm_config is None or response_format is None:
+ raise ValueError("classifier_llm_config is not set")
+
+ request_values: Final = request_kwargs or EMPTY_MAPPING
+ request_metadata = request_values.get("litellm_metadata") or request_values.get("metadata")
+ metadata: Final = { # mutable-ok: SDK metadata kwarg is enriched by the request pipeline
+ **forwarded_internal_call_metadata(request_metadata, AUTOROUTER_CLASSIFIER_CALL_ORIGIN),
+ INTERNAL_CALL_ORIGIN_METADATA_KEY: AUTOROUTER_CLASSIFIER_CALL_ORIGIN,
+ }
- classifier_call_params: dict[str, object] = {} # mutable-ok: optional SDK kwargs are assembled conditionally
- if llm_config.reasoning_effort is not None:
- classifier_call_params["reasoning_effort"] = llm_config.reasoning_effort
- if max_output_tokens is not None:
- classifier_call_params["max_tokens"] = max_output_tokens
++ classifier_call_params: Final = (
++ {"reasoning_effort": llm_config.reasoning_effort} if llm_config.reasoning_effort is not None else {}
++ )
++ classifier_payload: Final = (
+ self._native_classifier_payload(messages_for_call, response_format, encrypted_task)
+ if encrypted_task is not None
+ else MappingProxyType(
+ {"messages": messages_for_call, "response_format": response_format, **classifier_call_params}
+ )
+ )
++ payload: Final = {
++ **classifier_payload,
++ **(
++ {"max_output_tokens" if encrypted_task is not None else "max_tokens": max_output_tokens}
++ if max_output_tokens is not None
++ else {}
++ ),
++ }
proxy_server_request: Final = {
- "body": {
- "model": llm_config.model,
- "messages": messages_for_call,
- "response_format": response_format,
- **classifier_call_params,
- }
+ "originating_request_masked": masked_originating_request(request_kwargs),
+ "body": {"model": llm_config.model, **payload},
}
+ classify: Final = (
+ self.litellm_router_instance.aresponses
+ if encrypted_task is not None
+ else self.litellm_router_instance.acompletion
+ )
classifier_timeout_s: Final[float] = llm_config.timeout_ms / 1000
- response: Final[ModelResponse] = await asyncio.wait_for(
- self.litellm_router_instance.acompletion(
+ response: Final[ModelResponse | ResponsesAPIResponse] = await asyncio.wait_for(
+ classify(
model=llm_config.model,
- messages=messages_for_call,
stream=False,
- response_format=response_format,
timeout=classifier_timeout_s,
num_retries=0,
disable_fallbacks=True,
metadata=metadata,
proxy_server_request=proxy_server_request,
- turn_off_message_logging=turn_off_message_logging,
+ turn_off_message_logging=_effective_turn_off_message_logging(request_kwargs),
- **classifier_call_params,
+ **payload,
**_parent_session_kwargs(request_kwargs),
),
timeout=classifier_timeout_s,
)
- content: Final = response.choices[0].message.content
+ content: Final = (
+ response.output_text if isinstance(response, ResponsesAPIResponse) else response.choices[0].message.content
+ )
if not content:
raise ValueError("LLM classifier returned empty content")
- raw_tier: Final = _LabeledTierClassification.model_validate_json(content).tier
- tier: Final = self.config.resolve_classified_tier(raw_tier)
- if tier is None:
- raise ValueError(f"LLM classifier returned an unrecognized tier: {raw_tier!r}")
- return tier, _response_cost_or_none(response)
+ return content, _response_cost_or_none(response)
+ def _native_classifier_payload(
+ self,
+ messages: list[AllMessageValues], # mutable-ok: existing transformation accepts the SDK message list
+ response_format: Mapping[str, object],
+ encrypted_task: Mapping[str, object],
+ ) -> Mapping[str, object]:
+ from litellm.completion_extras.litellm_responses_transformation.transformation import (
+ LiteLLMResponsesTransformationHandler,
+ )
+
+ transformation: Final = LiteLLMResponsesTransformationHandler()
+ input_items, instructions = transformation.convert_chat_completion_messages_to_responses_api(messages)
+ llm_config: Final = self.config.classifier_llm_config
+ reasoning: Final = (
+ {"reasoning": {"effort": llm_config.reasoning_effort}}
+ if llm_config is not None and llm_config.reasoning_effort is not None
+ else {}
+ )
+ return {
+ "input": [*input_items, encrypted_task],
+ "instructions": instructions,
+ "text": transformation.transform_response_format_to_text_format(dict(response_format)),
+ "store": False,
+ "_require_encrypted_task_support": True,
+ **reasoning,
+ }
+
@staticmethod
def _build_classifier_user_payload(
prompt: str,
@@@ -3816,7 -3965,7 +4156,12 @@@
tier,
ask,
request_kwargs,
-- hard_floor=tier if context_original_tier is not None else plan_floor,
++ hard_floor=(
++ tier
++ if context_original_tier is not None
++ or outcome.cause in ("capability_classifier", "capability_classifier_fallback")
++ else plan_floor
++ ),
hard_ceiling=housekeeping_ceiling,
fit_filter=context_placement.holdable_models if context_placement is not None else None,
)
diff --cc litellm/router_strategy/complexity_router/config.py
index f33028b1c25,1f1b5a5cc4b..7d1a925b270
--- a/litellm/router_strategy/complexity_router/config.py
+++ b/litellm/router_strategy/complexity_router/config.py
@@@ -5,22 -5,21 +5,30 @@@ Contains default keyword lists, weights
All values are configurable via proxy config.yaml.
"""
- from collections.abc import Mapping
+ import math
+ import re
+ import warnings
+ from collections.abc import Iterable, Mapping
from enum import Enum
from types import MappingProxyType
- from typing import Annotated, Final, Literal
+ from typing import Annotated, Final, Literal, NamedTuple
-from pydantic import BaseModel, ConfigDict, Field, SkipValidation, field_serializer, field_validator, model_validator
+from pydantic import (
+ BaseModel,
+ ConfigDict,
+ Field,
+ SkipValidation,
+ StrictFloat,
+ field_serializer,
+ field_validator,
+ model_validator,
+)
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", DeprecationWarning)
+ import sre_constants
+ import sre_parse
+
from litellm.types.llms.openai import REASONING_EFFORT
from litellm.types.router import AdaptiveRouterWeights, ClassifierPlugin, RoutingPlugin
@@@ -578,50 -591,125 +600,197 @@@ class ClassifierLLMConfig(BaseModel)
return self
++class CapabilityCalibrationConfig(BaseModel):
++ model_config = ConfigDict(extra="forbid", frozen=True)
++
++ version: str = Field(min_length=1, max_length=128, pattern=r"^\S(?:.*\S)?$")
++ slope: StrictFloat = Field(ge=0.0, le=20.0, allow_inf_nan=False)
++ intercept: StrictFloat = Field(ge=-20.0, le=20.0, allow_inf_nan=False)
++
++ def calibrate(self, p_solve: float) -> float:
++ clipped: Final = min(max(p_solve, 1e-6), 1.0 - 1e-6)
++ log_odds: Final = self.slope * (math.log(clipped) - math.log1p(-clipped)) + self.intercept
++ return 1.0 / (1.0 + math.exp(-log_odds))
++
++
+class CapabilityClassifierConfig(BaseModel):
+ """Switchyard-compatible probability threshold policy for two model tiers."""
+
+ model_config = ConfigDict(frozen=True)
+
+ efficient_tier: str = Field(
+ description="Tier used when the efficient model's forecasted solve probability meets the adjusted threshold",
+ )
+ capable_tier: str = Field(
+ description=(
+ "Higher, fail-closed tier used below the adjusted threshold or when the classifier verdict is unavailable"
+ ),
+ )
+ base_threshold: StrictFloat = Field(
+ ge=0.0,
+ le=1.0,
+ description="Lowest p_solve that routes a supported task to efficient_tier",
+ )
+ threshold_step: StrictFloat = Field(
+ default=0.0,
+ ge=0.0,
+ description=("Amount added once for uncertain or unmatched verdicts and twice for unsupported verdicts"),
+ )
+ max_output_tokens: int = Field(
+ default=4096,
+ ge=1,
+ description="Maximum completion tokens available to the capability classifier verdict",
+ )
++ calibration: CapabilityCalibrationConfig | None = Field(
++ default=None,
++ description=(
++ "Optional versioned sigmoid calibration fitted for this judge, capability card, efficient model, "
++ "and execution setup. Applies sigmoid(slope * logit(clip(p_solve, 1e-6, 1-1e-6)) + intercept) "
++ "before the threshold policy. Omit to route on the raw forecast."
++ ),
++ )
++ response_format: Literal["json_schema", "json_object"] = Field(
++ default="json_schema",
++ description=(
++ "Use json_object for judges without strict JSON Schema support. This appends the verdict schema "
++ "to the packaged system prompt; both modes validate the returned verdict identically."
++ ),
++ )
+
+ @field_validator("efficient_tier", "capable_tier")
+ @classmethod
+ def _normalize_tier(cls, value: str) -> str:
+ normalized: Final = value.strip()
+ if not normalized:
+ raise ValueError("tier must be non-empty")
+ return normalized
+
+ @model_validator(mode="after")
+ def _validate_threshold_range(self) -> "CapabilityClassifierConfig":
+ if self.base_threshold + 2 * self.threshold_step > 1.0:
+ raise ValueError("base_threshold + 2 * threshold_step must be at most 1")
+ return self
+
+
+ MAX_CUSTOM_PATTERN_REPEAT: Final[int] = 64
+ MAX_CUSTOM_PATTERN_WORK: Final[int] = 2048
+ MAX_CUSTOM_DIMENSIONS_WORK: Final[int] = 8192
+ MAX_CUSTOM_PATTERN_DEPTH: Final[int] = 16
+ CUSTOM_PATTERN_SCAN_CHARS: Final[int] = 2048
+
+ _ATOM_OPCODES: Final = frozenset(
+ {sre_constants.LITERAL, sre_constants.NOT_LITERAL, sre_constants.ANY, sre_constants.IN, sre_constants.CATEGORY}
+ )
+ _REPEAT_OPCODES: Final = frozenset({sre_constants.MAX_REPEAT, sre_constants.MIN_REPEAT})
+
+
+ class _PatternCost(NamedTuple):
+ paths: int
+ steps: int
+
+
+ def _atom_steps(node: object) -> int:
+ if isinstance(node, tuple) and len(node) == 2 and node[0] is sre_constants.IN:
+ return 1 + len(node[1])
+ return 1
+
+
+ def _repeat_cost(argument: object) -> _PatternCost | str:
+ if not isinstance(argument, tuple) or len(argument) != 3:
+ return "unsupported repeat structure"
+ low, high, body = argument
+ if high > MAX_CUSTOM_PATTERN_REPEAT or len(body) != 1 or body[0][0] not in _ATOM_OPCODES:
+ return "requires a single character or class repeated at most 64 times; use {n,m} instead of *, + or {n,}"
+ choices: Final = high - low + 1
+ return _PatternCost(choices, 1 + high * _atom_steps(body[0]) + choices)
+
+
+ def _node_cost(node: object, depth: int) -> _PatternCost | str:
+ if not isinstance(node, tuple) or len(node) != 2:
+ return "unsupported regex structure"
+ opcode, argument = node
+ if opcode in _ATOM_OPCODES or opcode is sre_constants.AT:
+ return _PatternCost(1, _atom_steps(node))
+ if opcode is sre_constants.SUBPATTERN:
+ return _sequence_cost(argument[-1], depth + 1)
+ if opcode is sre_constants.BRANCH:
+ costs: Final = tuple(_sequence_cost(branch, depth + 1) for branch in argument[1])
+ refused: Final = next((cost for cost in costs if isinstance(cost, str)), None)
+ if refused is not None:
+ return refused
+ return _PatternCost(
+ sum(cost.paths for cost in costs if isinstance(cost, _PatternCost)),
+ len(costs) + sum(cost.steps for cost in costs if isinstance(cost, _PatternCost)),
+ )
+ if opcode in _REPEAT_OPCODES:
+ return _repeat_cost(argument)
+ return "contains an unsupported regex construct"
+
+
+ def _sequence_cost(nodes: Iterable[object], depth: int) -> _PatternCost | str:
+ if depth > MAX_CUSTOM_PATTERN_DEPTH:
+ return "nests deeper than 16 levels"
+ costs: Final = tuple(_node_cost(node, depth) for node in nodes)
+ refused: Final = next((cost for cost in costs if isinstance(cost, str)), None)
+ if refused is not None:
+ return refused
+ valid: Final = tuple(cost for cost in costs if isinstance(cost, _PatternCost))
+ # Choices multiply across a sequence; every continuation can execute once per preceding path.
+ total: Final = _PatternCost(
+ math.prod(cost.paths for cost in valid),
+ 1 + sum(cost.steps * math.prod(prior.paths for prior in valid[:index]) for index, cost in enumerate(valid)),
+ )
+ if total.steps > MAX_CUSTOM_PATTERN_WORK:
+ return "exceeds the per-pattern regex work budget"
+ return total
+
+
+ def custom_pattern_work(pattern: str) -> int | str:
+ try:
+ re.compile(pattern, re.IGNORECASE)
+ parsed: Final = sre_parse.parse(pattern, re.IGNORECASE)
+ except (re.error, RecursionError, OverflowError):
+ return "is not a valid regex"
+ cost: Final = _sequence_cost(tuple(parsed), 0)
+ return cost if isinstance(cost, str) else cost.steps
+
+
+ class CustomDimension(BaseModel):
+ model_config = ConfigDict(extra="forbid", frozen=True)
+
+ name: str = Field(min_length=1, max_length=64, pattern=r"^[A-Za-z][A-Za-z0-9_]*$")
+ weight: float = Field(gt=0, le=1, allow_inf_nan=False)
+ keywords: tuple[Annotated[str, Field(min_length=1, max_length=256)], ...] = Field(default=(), max_length=32)
+ patterns: tuple[Annotated[str, Field(min_length=1, max_length=256)], ...] = Field(default=(), max_length=32)
+ scoring_mode: Literal["binary", "match_count"] = Field(
+ default="binary",
+ description=(
+ "'binary' scores 1 when any matcher hits. 'match_count' scores 0.5 when one distinct matcher hits and 1 "
+ "when two or more do; repeated occurrences of one matcher never raise it. Keywords are distinct "
+ "case-insensitively, patterns by source, and a keyword and a pattern are always distinct from each other."
+ ),
+ )
+
+ @model_validator(mode="after")
+ def _validate_matchers(self) -> "CustomDimension":
+ matchers: Final = (*self.keywords, *self.patterns)
+ if not matchers or any(not matcher.strip() for matcher in matchers):
+ raise ValueError("custom dimensions require nonblank keywords and/or patterns")
+ if len(matchers) > 32 or sum(map(len, matchers)) > 4096:
+ raise ValueError("custom dimensions allow at most 32 matchers and 4096 matcher characters each")
+ costs: Final = tuple((pattern, custom_pattern_work(pattern)) for pattern in self.patterns)
+ rejected: Final = tuple(f"pattern {pattern!r} {work}" for pattern, work in costs if isinstance(work, str))
+ if rejected:
+ raise ValueError("custom dimension " + "; ".join(rejected))
+ return self
+
+ def pattern_work(self) -> int:
+ """Combined work estimate of the validated patterns."""
+ return sum(
+ work for work in (custom_pattern_work(pattern) for pattern in self.patterns) if isinstance(work, int)
+ )
+
+
class ComplexityRouterConfig(BaseModel):
"""Configuration for the ComplexityRouter."""
@@@ -1309,66 -1431,27 +1523,87 @@@
)
return self
+ @model_validator(mode="after")
+ def _validate_capability_classifier_config(self) -> "ComplexityRouterConfig":
+ capability: Final = self.capability_classifier_config
+ if self.classifier_type != "capability":
+ if capability is not None:
+ raise ValueError(
+ "capability_classifier_config requires classifier_type 'capability'; otherwise it has no effect"
+ )
+ return self
+ if capability is None:
+ raise ValueError("capability_classifier_config is required when classifier_type is 'capability'")
+ return self
+
+ @model_validator(mode="after")
+ def _validate_capability_classifier_tiers(self) -> "ComplexityRouterConfig":
+ capability: Final = self.capability_classifier_config
+ if self.classifier_type != "capability" or capability is None:
+ return self
+ if self.tier_definitions is not None:
+ raise ValueError(
+ "classifier_type 'capability' uses the built-in tier map and cannot be combined with tier_definitions"
+ )
+ for field, tier in (
+ ("efficient_tier", capability.efficient_tier),
+ ("capable_tier", capability.capable_tier),
+ ):
+ if tier not in self.tier_names():
+ raise ValueError(
+ f"{field} {tier!r} is not an active tier: it must name one of {', '.join(self.tier_names())}"
+ )
+ if not self.tiers.get(tier):
+ raise ValueError(f"{field} {tier!r} has no model configured in tiers")
+ names: Final = self.tier_names()
+ if names.index(capability.capable_tier) <= names.index(capability.efficient_tier):
+ raise ValueError("capable_tier must be a higher tier than efficient_tier")
+ return self
+
+ @model_validator(mode="after")
+ def _validate_capability_classifier_prompt_policy(self) -> "ComplexityRouterConfig":
+ if self.classifier_type != "capability":
+ return self
+ llm_config: Final = self.classifier_llm_config
+ if llm_config is not None and (
+ llm_config.system_prompt is not None or llm_config.classification_rubric is not None
+ ):
+ raise ValueError(
+ "classifier_type 'capability' uses the packaged capability card; classifier_llm_config.system_prompt "
+ "and classification_rubric are not supported"
+ )
+ if self.classification_prompt is not None or self.classification_examples is not None:
+ raise ValueError(
+ "classifier_type 'capability' uses the packaged capability card; classification_prompt and "
+ "classification_examples are not supported"
+ )
+ if self.classifier_fallback != "heuristic":
+ raise ValueError(
+ "classifier_type 'capability' always fails closed to capable_tier; classifier_fallback cannot override it"
+ )
+ return self
+
+ @model_validator(mode="after")
+ def _validate_custom_dimensions(self) -> "ComplexityRouterConfig":
+ if not self.custom_dimensions:
+ return self
+ if self.classifier_type not in ("heuristic", "heuristic_first", "hybrid"):
+ raise ValueError("custom_dimensions requires classifier_type heuristic, heuristic_first or hybrid")
+ names: Final = tuple(dimension.name.casefold() for dimension in self.custom_dimensions)
+ reserved: Final = frozenset(name.casefold() for name in DEFAULT_DIMENSION_WEIGHTS)
+ weighted: Final = frozenset(name.casefold() for name in self.dimension_weights)
+ if len(frozenset(names)) != len(names) or frozenset(names) & reserved:
+ raise ValueError("custom dimension names must be unique and must not shadow built-in dimensions")
+ if frozenset(names) & weighted:
+ raise ValueError("custom dimension weights must be inline, not in dimension_weights")
+ work: Final = sum(dimension.pattern_work() for dimension in self.custom_dimensions)
+ if work > MAX_CUSTOM_DIMENSIONS_WORK:
+ raise ValueError(
+ f"custom_dimensions regex work estimate is {work}; the limit across the router is "
+ f"{MAX_CUSTOM_DIMENSIONS_WORK}"
+ )
+ return self
+
@field_validator("heuristic_first_max_tier", mode="before")
@classmethod
def _coerce_heuristic_first_max_tier(cls, value: object) -> object:
@@@ -1577,10 -1694,10 +1846,10 @@@
)
if duplicated:
raise ValueError(f"tier_definitions names must be unique (case-insensitive): {', '.join(duplicated)}")
- if self.classifier_type in ("heuristic", "heuristic_v2", "heuristic_first", "hybrid"):
+ if self.classifier_type in ("heuristic", "heuristic_v2", "capability", "heuristic_first", "hybrid"):
raise ValueError(
"tier_definitions requires classifier_type 'llm' or 'custom': the heuristic scorer only "
- "produces the four built-in tiers, as does heuristic_v2"
+ "produces the built-in tiers from SIMPLE up, as does heuristic_v2"
)
conflicts: Final = self._tier_definition_conflicts()
if conflicts:
diff --cc litellm/types/utils.py
index 1528cd46c1f,e3ea37dc0c8..150af3ba28d
--- a/litellm/types/utils.py
+++ b/litellm/types/utils.py
@@@ -2939,11 -2966,6 +2970,13 @@@ class StandardLoggingRoutingDecision(Ty
escalation_keyword: str
classifier_model: str
classifier_cost: float
+ classifier_crux: str # writable-ok: added only when a capability verdict is available
+ classifier_primary_rule: str # writable-ok: added only when a capability verdict is available
+ classifier_capability_boundary: str # writable-ok: added only when a capability verdict is available
+ classifier_p_solve: float # writable-ok: added only when a capability verdict is available
++ classifier_calibrated_p_solve: ReadOnly[float]
++ classifier_calibration_version: ReadOnly[str]
+ classifier_threshold: float # writable-ok: added only when a capability verdict is available
escalated: bool
context_escalated: bool # writable-ok: Pydantic warns on ReadOnly TypedDict fields
context_escalation_original_tier: str # writable-ok: Pydantic warns on ReadOnly TypedDict fields
@@@ -2974,10 -2994,6 +3007,12 @@@ DERIVED_ROUTING_DECISION_FIELDS: Final[
"score",
"classifier_model",
"classifier_cost",
+ "classifier_primary_rule",
+ "classifier_capability_boundary",
+ "classifier_p_solve",
++ "classifier_calibrated_p_solve",
++ "classifier_calibration_version",
+ "classifier_threshold",
"escalated",
"context_escalated",
"context_escalation_original_tier",
diff --cc tests/test_litellm/router_strategy/test_complexity_router.py
index 07100af1f52,dba44d1e2e8..09dfc077430
--- a/tests/test_litellm/router_strategy/test_complexity_router.py
+++ b/tests/test_litellm/router_strategy/test_complexity_router.py
@@@ -7,11 -7,17 +7,18 @@@ Tests the rule-based complexity scorin
import asyncio
import json
import logging
++import math
import sys
- from typing import Dict, List
+ import time
+ from collections.abc import AsyncIterator, Mapping
+ from copy import deepcopy
+ from functools import partial
+ from typing import Dict, Final, List, Literal
from unittest.mock import AsyncMock, MagicMock, patch
+ import httpx
import pytest
+ import respx
from pydantic import ValidationError
import litellm
@@@ -39,12 -51,7 +52,13 @@@ from litellm.router_strategy.complexity
classification_system_prompt,
custom_tier_classification_prompt,
)
+from litellm.router_strategy.complexity_router.capability_classifier import (
+ CAPABILITY_CLASSIFIER_SYSTEM_PROMPT,
+ CapabilityClassifierVerdict,
+)
from litellm.router_strategy.complexity_router.config import (
++ CapabilityCalibrationConfig,
+ CapabilityClassifierConfig,
DEFAULT_CLASSIFICATION_RUBRIC,
DEFAULT_CLASSIFIER_CONTEXT_WINDOW_SIZE,
DEFAULT_COMPLEXITY_CONFIG,
@@@ -1953,321 -2361,6 +2368,448 @@@ class TestLLMClassifierConfig
)
+CAPABILITY_TIERS: Dict[str, str] = {
+ "SIMPLE": "efficient-model",
+ "REASONING": "capable-model",
+}
+
+
+def _capability_router_config(**overrides):
+ return {
+ "tiers": dict(CAPABILITY_TIERS),
+ "classifier_type": "capability",
+ "classifier_llm_config": {"model": "judge-model", "timeout_ms": 400},
+ "capability_classifier_config": {
+ "efficient_tier": "SIMPLE",
+ "capable_tier": "REASONING",
+ "base_threshold": 0.5,
+ "threshold_step": 0.1,
+ },
+ **overrides,
+ }
+
+
+def _capability_reply(
+ *,
+ p_solve: float,
+ primary_rule: str = "SUP-1",
+ capability_boundary: str = "supported",
+ crux: str = "complete the requested change",
+) -> str:
+ return json.dumps(
+ {
+ "crux": crux,
+ "primary_rule": primary_rule,
+ "capability_boundary": capability_boundary,
+ "p_solve": p_solve,
+ }
+ )
+
+
+class TestCapabilityClassifierConfig:
++ @pytest.mark.parametrize(
++ "calibration",
++ (
++ {"version": "v1", "slope": -1.0, "intercept": 0.0},
++ {"version": "v1", "slope": float("nan"), "intercept": 0.0},
++ {"version": "v1", "slope": 1.0, "intercept": float("inf")},
++ {"version": "v1", "slope": True, "intercept": 0.0},
++ {"version": " ", "slope": 1.0, "intercept": 0.0},
++ {"version": "v1", "slope": 1.0, "intercept": 0.0, "typo": 1},
++ ),
++ )
++ def test_rejects_invalid_calibration(self, calibration: dict[str, object]) -> None:
++ with pytest.raises(ValidationError):
++ CapabilityCalibrationConfig.model_validate(calibration)
++
++ def test_calibration_round_trip_and_probability_endpoints(self) -> None:
++ calibration: Final = CapabilityCalibrationConfig(version="held-out-v1", slope=0.0, intercept=0.0)
++ config: Final = CapabilityClassifierConfig(
++ efficient_tier="SIMPLE", capable_tier="REASONING", base_threshold=0.6, calibration=calibration
++ )
++ restored: Final = CapabilityClassifierConfig.model_validate_json(config.model_dump_json())
++ assert restored.calibration == calibration
++ assert tuple(calibration.calibrate(p) for p in (0.0, 0.5, 1.0)) == (0.5, 0.5, 0.5)
++ steep: Final = CapabilityCalibrationConfig(version="endpoints", slope=20.0, intercept=-20.0)
++ values: Final = tuple(steep.calibrate(p) for p in (0.0, 0.5, 1.0))
++ assert all(math.isfinite(p) and 0.0 <= p <= 1.0 for p in values)
++ assert values[0] < values[1] < values[2]
++
+ @pytest.mark.parametrize(
+ "patch,error_match",
+ [
+ ({"classifier_llm_config": None}, "classifier_llm_config is required"),
+ ({"capability_classifier_config": None}, "capability_classifier_config is required"),
+ (
+ {
+ "capability_classifier_config": {
+ "efficient_tier": "SIMPLE",
+ "capable_tier": "SIMPLE",
+ "base_threshold": 0.5,
+ }
+ },
+ "must be a higher tier",
+ ),
+ (
+ {
+ "capability_classifier_config": {
+ "efficient_tier": "REASONING",
+ "capable_tier": "SIMPLE",
+ "base_threshold": 0.5,
+ }
+ },
+ "must be a higher tier",
+ ),
+ (
+ {
+ "capability_classifier_config": {
+ "efficient_tier": "MEDIUM",
+ "capable_tier": "REASONING",
+ "base_threshold": 0.5,
+ }
+ },
+ "has no model configured",
+ ),
+ (
+ {
+ "capability_classifier_config": {
+ "efficient_tier": "SIMPLE",
+ "capable_tier": "REASONING",
+ "base_threshold": 0.9,
+ "threshold_step": 0.1,
+ }
+ },
+ r"base_threshold \+ 2 \* threshold_step must be at most 1",
+ ),
+ ({"classifier_fallback": "default_model", "default_model": "fallback"}, "always fails closed"),
+ (
+ {"classifier_llm_config": {"model": "judge-model", "system_prompt": "pick one"}},
+ "uses the packaged capability card",
+ ),
+ ({"classification_examples": "example"}, "uses the packaged capability card"),
+ ],
+ )
+ def test_rejects_incoherent_configuration(self, patch, error_match):
+ with pytest.raises(ValidationError, match=error_match):
+ ComplexityRouterConfig(**{**_capability_router_config(), **patch})
+
+ def test_capability_config_is_rejected_on_other_classifier_types(self):
+ config = _capability_router_config(classifier_type="llm")
+ with pytest.raises(ValidationError, match="requires classifier_type 'capability'"):
+ ComplexityRouterConfig(**config)
+
+ def test_threshold_defaults_match_switchyard(self):
+ config = CapabilityClassifierConfig(efficient_tier=" SIMPLE ", capable_tier=" REASONING ", base_threshold=0.5)
+ assert config.efficient_tier == "SIMPLE"
+ assert config.capable_tier == "REASONING"
+ assert config.threshold_step == 0.0
+ assert config.max_output_tokens == 4096
+
+ def test_classifier_model_is_registered_as_a_dependency(self):
+ assert ComplexityRouterConfig(**_capability_router_config()).uses_llm_classifier is True
+
+
+class TestCapabilityClassifierVerdict:
+ @pytest.mark.parametrize(
+ "primary_rule,capability_boundary",
+ [
+ *((f"SUP-{index}", "supported") for index in range(1, 6)),
+ *((f"UNC-{index}", "uncertain") for index in range(1, 3)),
+ *((f"LIM-{index}", "unsupported") for index in range(1, 3)),
+ ("none", "unmatched"),
+ ],
+ )
+ def test_accepts_every_valid_rule_boundary_pair(self, primary_rule, capability_boundary):
+ verdict = CapabilityClassifierVerdict(
+ crux="the hard part",
+ primary_rule=primary_rule,
+ capability_boundary=capability_boundary,
+ p_solve=0.5,
+ )
+ assert verdict.primary_rule == primary_rule
+ assert verdict.capability_boundary == capability_boundary
+
+ @pytest.mark.parametrize(
+ "payload,error_match",
+ [
+ (
+ {
+ "crux": "x",
+ "primary_rule": "SUP-1",
+ "capability_boundary": "unsupported",
+ "p_solve": 0.5,
+ },
+ "requires capability_boundary",
+ ),
+ (
+ {"crux": " ", "primary_rule": "none", "capability_boundary": "unmatched", "p_solve": 0.5},
+ "non-whitespace",
+ ),
+ (
+ {
+ "crux": "x",
+ "primary_rule": "none",
+ "capability_boundary": "unmatched",
+ "p_solve": 0.5,
+ "recommended_route": "efficient",
+ },
+ "Extra inputs are not permitted",
+ ),
+ (
+ {"crux": "x", "primary_rule": "none", "capability_boundary": "unmatched", "p_solve": True},
+ "valid number",
+ ),
+ ],
+ )
+ def test_rejects_invalid_or_inconsistent_verdicts(self, payload, error_match):
+ with pytest.raises(ValidationError, match=error_match):
+ CapabilityClassifierVerdict.model_validate(payload)
+
+
+class TestCapabilityClassifier:
+ @staticmethod
+ def _router(mock_router_instance, **overrides):
+ return ComplexityRouter(
+ model_name="capability-router",
+ litellm_router_instance=mock_router_instance,
+ complexity_router_config=_capability_router_config(**overrides),
+ )
+
++ @pytest.mark.asyncio
++ @pytest.mark.parametrize("p_solve,expected_model", ((0.95, "capable-model"), (0.98, "efficient-model")))
++ async def test_fitted_probability_controls_routing_and_preserves_raw_score(
++ self, mock_router_instance: MagicMock, p_solve: float, expected_model: str
++ ) -> None:
++ mock_router_instance.acompletion = AsyncMock(return_value=_llm_response(_capability_reply(p_solve=p_solve)))
++ router: Final = self._router(
++ mock_router_instance,
++ capability_classifier_config={
++ "efficient_tier": "SIMPLE",
++ "capable_tier": "REASONING",
++ "base_threshold": 0.66,
++ "threshold_step": 0.1,
++ "calibration": {
++ "version": "qwen3-haiku45-mini-swe-v1",
++ "slope": 0.1482462649948327,
++ "intercept": 0.1895438369492216,
++ },
++ },
++ )
++ result: Final = await router.async_pre_routing_hook(
++ model="capability-router", request_kwargs={}, messages=[{"role": "user", "content": "Fix the issue"}]
++ )
++ assert result is not None and result.model == expected_model
++ decision: Final = result.routing_decision
++ assert decision is not None
++ assert decision["classifier_p_solve"] == p_solve
++ assert decision["classifier_threshold"] == 0.66
++ assert decision["classifier_calibration_version"] == "qwen3-haiku45-mini-swe-v1"
++ assert 0.65 < decision["classifier_calibrated_p_solve"] < 0.69
++ assert (decision["classifier_calibrated_p_solve"] >= 0.66) == (expected_model == "efficient-model")
++
++ @pytest.mark.asyncio
++ @pytest.mark.parametrize("mode", ("json_schema", "json_object"))
++ async def test_response_modes_preserve_the_card_and_validate_the_same_verdict(
++ self, mock_router_instance: MagicMock, mode: str
++ ) -> None:
++ mock_router_instance.acompletion = AsyncMock(return_value=_llm_response(_capability_reply(p_solve=0.8)))
++ router: Final = self._router(
++ mock_router_instance,
++ capability_classifier_config={
++ "efficient_tier": "SIMPLE",
++ "capable_tier": "REASONING",
++ "base_threshold": 0.5,
++ "response_format": mode,
++ },
++ )
++ outcome: Final = await router.aclassify("Fix the issue")
++ assert outcome.tier == ComplexityTier.SIMPLE
++ call: Final = mock_router_instance.acompletion.call_args.kwargs
++ system_prompt: Final = call["messages"][0]["content"]
++ assert call["response_format"]["type"] == mode
++ if mode == "json_object":
++ marker: Final = "\n\nReturn exactly one JSON object matching this JSON Schema:\n"
++ assert system_prompt.startswith(CAPABILITY_CLASSIFIER_SYSTEM_PROMPT + marker)
++ schema: Final = json.loads(system_prompt.split(marker)[1])
++ assert schema["required"] == ["crux", "primary_rule", "capability_boundary", "p_solve"]
++ assert schema["additionalProperties"] is False
++ else:
++ assert system_prompt == CAPABILITY_CLASSIFIER_SYSTEM_PROMPT
++ mock_router_instance.acompletion = AsyncMock(return_value=_llm_response("invalid JSON"))
++ assert (await router.aclassify("Fix another issue")).tier == ComplexityTier.REASONING
++
++ @pytest.mark.asyncio
++ @pytest.mark.parametrize("reply", ("invalid JSON", _capability_reply(p_solve=0.0)))
++ async def test_adaptive_selection_cannot_undo_a_capable_verdict(
++ self, mock_router_instance: MagicMock, reply: str
++ ) -> None:
++ from litellm.router_strategy.adaptive_router.bandit import BanditCell
++ from litellm.types.router import RequestType
++
++ mock_router_instance.acompletion = AsyncMock(return_value=_llm_response(reply))
++ mock_router_instance.model_list = [
++ {"model_name": "efficient-model", "litellm_params": {"input_cost_per_token": 0.000001}},
++ {"model_name": "capable-model", "litellm_params": {"input_cost_per_token": 0.00001}},
++ ]
++ mock_router_instance.model_name_to_deployment_indices = {"efficient-model": [0], "capable-model": [1]}
++ router: Final = self._router(
++ mock_router_instance,
++ adaptive=True,
++ adaptive_eligible="all",
++ adaptive_weights={"quality": 0.0, "cost": 1.0},
++ tier_distance_penalty=0.0,
++ tiers={"SIMPLE": ["efficient-model"], "REASONING": ["capable-model"]},
++ )
++ adaptive: Final = router._ensure_adaptive_router()
++ assert adaptive is not None
++ for model in ("efficient-model", "capable-model"):
++ adaptive._cells[(RequestType.GENERAL, model)] = BanditCell(alpha=20.0, beta=1.0)
++ assert router._soft_floor_pick(ComplexityTier.REASONING, "Fix the issue") == "efficient-model"
++ result: Final = await router.async_pre_routing_hook(
++ model="capability-router", request_kwargs={}, messages=[{"role": "user", "content": "Fix the issue"}]
++ )
++ assert result is not None and result.model == "capable-model"
++ assert result.routing_decision is not None
++ assert result.routing_decision["tier"] == "REASONING"
++
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "p_solve,primary_rule,boundary,expected_tier,expected_threshold",
+ [
+ (0.5, "SUP-1", "supported", ComplexityTier.SIMPLE, 0.5),
+ (0.59, "UNC-1", "uncertain", ComplexityTier.REASONING, 0.6),
+ (0.6, "UNC-1", "uncertain", ComplexityTier.SIMPLE, 0.6),
+ (0.59, "none", "unmatched", ComplexityTier.REASONING, 0.6),
+ (0.69, "LIM-1", "unsupported", ComplexityTier.REASONING, 0.7),
+ (0.7, "LIM-1", "unsupported", ComplexityTier.SIMPLE, 0.7),
+ ],
+ )
+ async def test_boundary_adjusted_threshold_is_inclusive(
+ self, mock_router_instance, p_solve, primary_rule, boundary, expected_tier, expected_threshold
+ ):
+ mock_router_instance.acompletion = AsyncMock(
+ return_value=_llm_response(
+ _capability_reply(p_solve=p_solve, primary_rule=primary_rule, capability_boundary=boundary)
+ )
+ )
+ outcome = await self._router(mock_router_instance).aclassify("do the task")
+ assert outcome.tier == expected_tier
+ assert outcome.cause == "capability_classifier"
- assert outcome.capability_threshold == pytest.approx(expected_threshold)
++ assert outcome.capability_forecast is not None
++ assert outcome.capability_forecast.threshold == pytest.approx(expected_threshold)
+
+ @pytest.mark.asyncio
+ async def test_fenced_json_verdict_is_accepted(self, mock_router_instance):
+ reply = _capability_reply(p_solve=0.8)
+ mock_router_instance.acompletion = AsyncMock(return_value=_llm_response(f"```json\n{reply}\n```"))
+ outcome = await self._router(mock_router_instance).aclassify("do the task")
+ assert outcome.tier == ComplexityTier.SIMPLE
+ assert outcome.cause == "capability_classifier"
+
+ @pytest.mark.asyncio
+ async def test_decimal_rounding_does_not_break_inclusive_threshold(self, mock_router_instance):
+ config = _capability_router_config(
+ capability_classifier_config={
+ "efficient_tier": "SIMPLE",
+ "capable_tier": "REASONING",
+ "base_threshold": 0.1,
+ "threshold_step": 0.1,
+ }
+ )
+ mock_router_instance.acompletion = AsyncMock(
+ return_value=_llm_response(
+ _capability_reply(p_solve=0.3, primary_rule="LIM-1", capability_boundary="unsupported")
+ )
+ )
+ router = ComplexityRouter(
+ model_name="capability-router",
+ litellm_router_instance=mock_router_instance,
+ complexity_router_config=config,
+ )
+ outcome = await router.aclassify("do the task")
- assert outcome.capability_threshold == 0.30000000000000004
++ assert outcome.capability_forecast is not None
++ assert outcome.capability_forecast.threshold == 0.30000000000000004
+ assert outcome.tier == ComplexityTier.SIMPLE
+
+ @pytest.mark.asyncio
+ async def test_call_uses_packaged_prompt_schema_and_opening_plus_latest_user_task(self, mock_router_instance):
+ mock_router_instance.acompletion = AsyncMock(
+ return_value=_llm_response(_capability_reply(p_solve=0.8), response_cost=0.002)
+ )
+ router = self._router(mock_router_instance)
+ messages = [
+ {"role": "system", "content": "Never expose this caller instruction to the judge"},
+ {"role": "user", "content": "Build the feature"},
+ {"role": "assistant", "content": "I need more information"},
+ {"role": "user", "content": "Use the existing API"},
+ ]
+
+ response = await router.async_pre_routing_hook(model="capability-router", request_kwargs={}, messages=messages)
+
+ assert response.model == "efficient-model"
+ call = mock_router_instance.acompletion.call_args.kwargs
+ assert call["messages"] == [
+ {"role": "system", "content": CAPABILITY_CLASSIFIER_SYSTEM_PROMPT},
+ {"role": "user", "content": "Build the feature"},
+ {"role": "user", "content": "Use the existing API"},
+ ]
+ schema = call["response_format"]["json_schema"]["schema"]
+ assert call["response_format"]["json_schema"]["name"] == "CapabilityClassifierDecision"
+ assert call["response_format"]["json_schema"]["strict"] is True
+ assert schema["additionalProperties"] is False
+ assert set(schema["required"]) == {"crux", "primary_rule", "capability_boundary", "p_solve"}
+ assert schema["properties"]["primary_rule"]["enum"] == [
+ "SUP-1",
+ "SUP-2",
+ "SUP-3",
+ "SUP-4",
+ "SUP-5",
+ "UNC-1",
+ "UNC-2",
+ "LIM-1",
+ "LIM-2",
+ "none",
+ ]
+ assert call["max_tokens"] == 4096
+ decision = response.routing_decision
+ assert decision["cause"] == "capability_classifier"
+ assert decision["classifier_model"] == "judge-model"
+ assert decision["classifier_cost"] == 0.002
+ assert decision["classifier_crux"] == "complete the requested change"
+ assert decision["classifier_primary_rule"] == "SUP-1"
+ assert decision["classifier_capability_boundary"] == "supported"
+ assert decision["classifier_p_solve"] == 0.8
+ assert decision["classifier_threshold"] == 0.5
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "reply",
+ [
+ "not json",
+ _capability_reply(p_solve=0.9, primary_rule="SUP-1", capability_boundary="unsupported"),
+ '{"crux":"x","primary_rule":"SUP-1","capability_boundary":"supported","p_solve":0.9,"route":"efficient"}',
+ ],
+ ids=["malformed", "inconsistent-pair", "extra-field"],
+ )
+ async def test_invalid_verdict_fails_closed_to_capable_tier(self, mock_router_instance, reply):
+ mock_router_instance.acompletion = AsyncMock(return_value=_llm_response(reply))
+ outcome = await self._router(mock_router_instance).aclassify("do the task")
+ assert outcome.tier == ComplexityTier.REASONING
+ assert outcome.cause == "capability_classifier_fallback"
+ assert outcome.signals == ("capability-classifier-fallback",)
+
+ @pytest.mark.asyncio
+ async def test_classifier_call_failure_fails_closed_to_capable_model(self, mock_router_instance):
+ mock_router_instance.acompletion = AsyncMock(side_effect=TimeoutError("judge unavailable"))
+ response = await self._router(mock_router_instance).async_pre_routing_hook(
+ model="capability-router",
+ request_kwargs={},
+ messages=[{"role": "user", "content": "do the task"}],
+ )
+ assert response.model == "capable-model"
+ assert response.routing_decision["cause"] == "capability_classifier_fallback"
+
+
CUSTOM_TIER_LABELS: Dict[str, str] = {
"SIMPLE": "Cheap",
"MEDIUM": "Standard",
@@@ -7485,11 -7962,6 +8411,13 @@@ class TestRedactedLoggingDropsPromptTex
"score": 0.8,
"tier_boundaries": {"simple_medium": 0.15, "medium_complex": 0.35, "complex_reasoning": 0.6},
"classifier_model": "claude-haiku",
+ "classifier_crux": "deploy the requested service to k8s",
+ "classifier_primary_rule": "SUP-2",
+ "classifier_capability_boundary": "supported",
+ "classifier_p_solve": 0.8,
++ "classifier_calibrated_p_solve": 0.65,
++ "classifier_calibration_version": "fitted-v1",
+ "classifier_threshold": 0.5,
"escalated": True,
"tier_litellm_params": {"reasoning_effort": "xhigh"},
"signals": ["code (python)"],
@@@ -7497,13 -7969,7 +8425,15 @@@
"escalation_keyword": "LITELLM ESCALATE",
}
kept = Router._redact_prompt_text_if_needed(request_kwargs={}, routing_decision=full)
- assert set(full) - set(kept) == {"signals", "matched_keyword", "escalation_keyword"}
+ assert set(full) - set(kept) == {
+ "signals",
+ "matched_keyword",
+ "escalation_keyword",
+ "classifier_crux",
+ }
+ assert kept["classifier_p_solve"] == 0.8
++ assert kept["classifier_calibrated_p_solve"] == 0.65
++ assert kept["classifier_calibration_version"] == "fitted-v1"
assert kept["tier_litellm_params"] == {"reasoning_effort": "xhigh"}
@pytest.mark.asyncio
@@@ -7544,93 -8021,455 +8485,457 @@@ _CODEX_ENVELOPES: Final =
class TestContextAwareClassifier:
"""Test the new classifier context window and trajectory signals."""
+ @pytest.mark.asyncio
@pytest.mark.parametrize(
- "messages,expected_ask",
+ "request_metadata,forwards_system",
[
- pytest.param(
- [_ASKED, _ANSWERED, {"role": "user", "content": [_TOOL_RESULT]}],
- _ASK,
- id="messages-surface-tool-result-skipped",
- ),
- pytest.param(
- [
- _ASKED,
- _ANSWERED,
- {"role": "user", "content": [{**_TOOL_RESULT, "content": [{"type": "text", "text": "out"}]}]},
- ],
- _ASK,
- id="nested-tool-result-skipped",
- ),
- pytest.param(
- [_ASKED, _ANSWERED, {"role": "tool", "tool_call_id": "x", "content": "out"}],
- _ASK,
- id="chat-completions-tool-role-never-read",
- ),
- pytest.param(
- [_ASKED, _ANSWERED, {"role": "user", "content": [_TOOL_RESULT, {"type": "text", "text": "and now?"}]}],
- "and now?",
- id="ask-riding-with-tool-result-survives",
- ),
- pytest.param(
- [_ASKED, _ANSWERED, {"role": "user", "content": f"{_REMINDER}"}],
- _ASK,
- id="reminder-only-turn-skipped",
- ),
- pytest.param(
- [_ASKED, _ANSWERED, {"role": "user", "content": f"{_REMINDER}\nand now?"}],
- "and now?",
- id="ask-riding-with-reminder-survives",
- ),
- pytest.param(
- [{"role": "user", "content": f"{_REMINDER}and now?{_REMINDER}"}],
- "and now?",
- id="multiple-reminders-stripped",
- ),
- pytest.param(
- [
- {
- "role": "user",
- "content": [{"type": "text", "text": _REMINDER}, {"type": "text", "text": "and now?"}],
- }
- ],
- "and now?",
- id="reminder-in-its-own-content-part",
- ),
- pytest.param(
- [{"role": "user", "content": "why is my <system-reminder> tag stripped?"}],
- "why is my <system-reminder> tag stripped?",
- id="unclosed-tag-in-prose-preserved",
- ),
- pytest.param(
- [{"role": "user", "content": f"I see {_REMINDER} how do I disable it?"}],
- "I see how do I disable it?",
- id="prose-around-quoted-block-survives",
+ ({"metadata": {"user_agent": "claude-cli/2.1.233"}}, False),
+ ({"litellm_metadata": {"user_agent": "claude-code/2.1.233"}}, False),
+ ({"metadata": {"user_agent": "curl/8.7.1"}}, True),
+ ({"litellm_metadata": {}}, True),
+ (
+ {"metadata": {"user_agent": "claude-cli/2.1.233"}, "litellm_metadata": {"user_agent": "curl/8.7.1"}},
+ False,
),
- pytest.param([{"role": "user", "content": _REMINDER}], None, id="plumbing-only-yields-no-ask"),
+ ({"metadata": {"user_agent": "Claude-Code/2.1.233"}}, True),
],
)
- def test_current_ask_is_the_text_a_human_wrote(self, messages, expected_ask):
- """One table for which text becomes the current ask, since every consumer reads only this.
+ async def test_claude_code_classifier_omits_harness_system_prompt(
+ self,
+ llm_classifier_config: dict[str, object],
+ request_metadata: dict[str, object],
+ forwards_system: bool,
+ ) -> None:
+ dependency: Final = MagicMock(acompletion=AsyncMock(return_value=_llm_response('{"tier": "COMPLEX"}')))
+ router: Final = ComplexityRouter(
+ "test-complexity-router",
+ dependency,
+ {
+ **llm_classifier_config,
+ "classifier_context_include_assistant_turns": True,
+ },
+ )
+ messages: Final = [
+ {"role": "user", "content": "Design the retry state machine"},
+ {"role": "assistant", "content": "The design needs a lease and fencing token"},
+ {"role": "user", "content": "Now prove it cannot livelock"},
+ {
+ "role": "system",
+ "content": [{"type": "text", "text": "ENVIRONMENT_CATALOG\nAGENT_CATALOG\nSKILL_CATALOG"}],
+ },
+ ]
+ top_level_system: Final = [{"type": "text", "text": "TOP_LEVEL_HARNESS_SYSTEM"}]
+ claude_kwargs: Final = {
+ "metadata": {"user_agent": "claude-cli/2.1.233"},
+ "system": top_level_system,
+ "proxy_server_request": {"body": {"system": top_level_system}},
+ }
+ compared_kwargs: Final = {
+ **request_metadata,
+ "system": top_level_system,
+ "proxy_server_request": {"body": {"system": top_level_system}},
+ }
+ original_messages: Final = deepcopy(messages)
+ original_kwargs: Final = deepcopy((claude_kwargs, compared_kwargs))
+ results: Final = (
+ await router.async_pre_routing_hook("test-complexity-router", claude_kwargs, messages),
+ await router.async_pre_routing_hook("test-complexity-router", compared_kwargs, messages),
+ )
+
+ assert all(result is not None and result.routing_decision["cause"] == "llm_classifier" for result in results)
+ assert all(result is not None and result.messages == original_messages for result in results)
+ assert messages == original_messages
+ assert (claude_kwargs, compared_kwargs) == original_kwargs
+ calls: Final = tuple(call.kwargs["messages"] for call in dependency.acompletion.await_args_list)
- assert calls[0][0]["content"] == calls[1][0]["content"] == classification_system_prompt(
- router.config.classifier_context_window_size
++ assert (
++ calls[0][0]["content"]
++ == calls[1][0]["content"]
++ == classification_system_prompt(router.config.classifier_context_window_size)
+ )
+ payloads: Final = (calls[0][1]["content"], calls[1][1]["content"])
+ for payload, expected_system in zip(payloads, (False, forwards_system)):
+ assert payload.endswith("Classify this message:\nNow prove it cannot livelock")
+ assert ("ENVIRONMENT_CATALOG" in payload) is expected_system
+ assert ("AGENT_CATALOG" in payload) is expected_system
+ assert ("SKILL_CATALOG" in payload) is expected_system
+ assert "Design the retry state machine" in payload
+ assert "lease and fencing token" in payload
+ assert "TOP_LEVEL_HARNESS_SYSTEM" not in payload
+ assert "Conversation so far: ~35 tokens across the request" in payload
+
+ @pytest.mark.asyncio
+ async def test_claude_code_first_turn_without_context_omits_harness_system_prompt(
+ self, llm_classifier_config: dict[str, object]
+ ) -> None:
+ dependency: Final = MagicMock(acompletion=AsyncMock(return_value=_llm_response('{"tier": "SIMPLE"}')))
+ router: Final = ComplexityRouter(
+ "test-complexity-router",
+ dependency,
+ {**llm_classifier_config, "classifier_context_window_size": 0},
+ )
+ messages: Final = [
+ {"role": "user", "content": "What is two plus two?"},
+ {
+ "role": "system",
+ "content": [{"type": "text", "text": "ENVIRONMENT_CATALOG\nAGENT_CATALOG\nSKILL_CATALOG"}],
+ },
+ ]
+ request_kwargs: Final = {"litellm_metadata": {"user_agent": "claude-code/2.1.233"}}
+ original: Final = deepcopy((messages, request_kwargs))
- Tool output needs no tool-specific parsing: Messages-surface `tool_result` blocks are not text
- parts so the turn flattens to empty, and chat-completions puts it on a `tool` role never read.
- Reminders arrive as ordinary text, so a complete block is stripped and the ask riding with it
- survives; an unclosed tag is not a block and is left alone. A quoted complete block is
- byte-identical to an injected one, so it is stripped too and only the prose survives.
+ result: Final = await router.async_pre_routing_hook("test-complexity-router", request_kwargs, messages)
- The last row is the case reported from both directions. There is no ask to recover, so the
- caller routes to its default model; falling back to the raw turn would put harness text in
- front of escalation keywords and keyword_tier_rules, which force a tier and choose the spend.
- """
- from litellm.router_strategy.complexity_router.complexity_router import _extract_current_ask_and_system_prompt
+ assert result is not None and result.routing_decision["cause"] == "llm_classifier"
+ assert result.messages == messages == original[0]
+ assert request_kwargs == original[1]
+ classifier_messages: Final = dependency.acompletion.call_args.kwargs["messages"]
+ assert classifier_messages[0]["content"] == classification_system_prompt(
+ router.config.classifier_context_window_size
+ )
+ assert classifier_messages[1]["content"].strip() == "Classify this message:\nWhat is two plus two?"
- assert _extract_current_ask_and_system_prompt(messages)[0] == expected_ask
+ @pytest.mark.parametrize(
+ "tail,expected",
+ (
+ ([{"role": "user", "content": [{"type": "text", "text": _CODEX_ENVELOPES[0]}]}], True),
+ ([{"role": "assistant", "content": _CODEX_ENVELOPES[0]}], False),
+ ([{"role": "tool", "content": _CODEX_ENVELOPES[0]}], False),
+ ([{"role": "user", "content": " "}], False),
+ (
+ [{"role": "user", "content": [_TOOL_RESULT, {"type": "text", "text": _CODEX_ENVELOPES[0]}]}],
+ False,
+ ),
+ (
+ [{"role": "user", "content": [{"type": "image_url"}, {"type": "text", "text": _CODEX_ENVELOPES[0]}]}],
+ False,
+ ),
+ ),
+ )
+ def test_only_text_reminder_tails_are_ignored_for_new_asks(
+ self, tail: list[dict[str, object]], expected: bool
+ ) -> None:
+ from litellm.router_strategy.complexity_router.complexity_router import (
+ _CODEX_REMINDER_MARKERS,
+ _newest_turn_is_human_ask,
+ )
- def test_custom_markers_skip_a_reminder_only_follow_up_message(self):
- """A harness using non-default markers, sent as its own trailing message, is still skipped.
+ assert _newest_turn_is_human_ask([_ASKED, *tail], _CODEX_REMINDER_MARKERS) is expected
+ assert _newest_turn_is_human_ask(tail, _CODEX_REMINDER_MARKERS) is False
- Some harnesses (unlike Claude Code, which inlines the reminder alongside the ask in one
- message) send internal context as a separate follow-up user turn using their own markers.
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("new_ask", (_CODEX_NEW_TASK, "Now design cache invalidation"))
+ @pytest.mark.parametrize("responses_api", (False, True))
+ @pytest.mark.parametrize("session_affinity", (False, True))
+ async def test_codex_tail_preserves_new_ask_and_tool_continuation_boundaries(
+ self, new_ask: str, responses_api: bool, session_affinity: bool
+ ) -> None:
+ completion: Final = AsyncMock(
+ side_effect=[_llm_response('{"tier":"SIMPLE"}'), _llm_response('{"tier":"COMPLEX"}')]
+ )
+ router: Final = ComplexityRouter(
+ model_name="router",
+ litellm_router_instance=MagicMock(acompletion=completion, cache=DualCache()),
+ complexity_router_config={
+ "tiers": {"SIMPLE": "simple-model", "COMPLEX": "task-model"},
+ "classifier_type": "llm",
+ "classifier_llm_config": {"model": "classifier-model"},
+ "classification_mode": "user_turn",
+ "session_affinity": session_affinity,
+ "escalation_keywords": [],
+ },
+ )
+ metadata: Final = {"user_agent": "codex-tui", "session_id": "codex-tail-session"}
+ first_messages: Final = [{"role": "user", "content": "Hello"}]
+ tail: Final = [{"role": "user", "content": envelope} for envelope in _CODEX_ENVELOPES]
+ new_messages: Final = [
+ *first_messages,
+ {"role": "assistant", "content": "Hello"},
+ {"role": "user", "content": new_ask},
+ *tail,
+ ]
+ continuation: Final = [
+ *new_messages,
+ {"role": "assistant", "content": "Working on it"},
+ {
+ "role": "user",
+ "content": [
+ {"type": "tool_result", "tool_use_id": "read-cache", "content": "cache source"},
+ {"type": "text", "text": _CODEX_ENVELOPES[0]},
+ ],
+ },
+ *tail,
+ ]
+ results: Final = [
+ await router.async_pre_routing_hook(
+ model="router",
+ request_kwargs=(
+ {"input": messages, "litellm_metadata": {**metadata, "user_api_key_request_route": "/v1/responses"}}
+ if responses_api
+ else {"metadata": metadata}
+ ),
+ messages=None if responses_api else messages,
+ input=messages if responses_api else None,
+ )
+ for messages in (first_messages, new_messages, continuation)
+ ]
+
+ assert [result.model for result in results] == (
+ ["simple-model", "simple-model", "simple-model"]
+ if session_affinity
+ else ["simple-model", "task-model", "task-model"]
+ )
+ assert completion.await_count == (1 if session_affinity else 2)
+ assert results[-1].routing_decision["cause"] == (
+ "session_affinity_pin" if session_affinity else "user_turn_continuation"
+ )
+ if not session_affinity:
+ assert completion.call_args.kwargs["messages"][1]["content"].endswith(f"Classify this message:\n{new_ask}")
+ assert results[1].messages == (None if responses_api else new_messages)
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("envelope", _CODEX_ENVELOPES)
+ @pytest.mark.parametrize("user_agent", (None, "curl/8.7.1", "codexify/1.0"))
+ async def test_non_codex_requests_preserve_tagged_asks(self, envelope: str, user_agent: str | None) -> None:
+ completion: Final = AsyncMock(return_value=_llm_response('{"tier":"COMPLEX"}'))
+ router: Final = ComplexityRouter(
+ model_name="router",
+ litellm_router_instance=MagicMock(acompletion=completion),
+ complexity_router_config={
+ "tiers": {"COMPLEX": "task-model"},
+ "default_model": "fallback-model",
+ "classifier_type": "llm",
+ "classifier_llm_config": {"model": "classifier-model"},
+ "escalation_keywords": [],
+ },
+ )
+
+ response: Final = await router.async_pre_routing_hook(
+ model="router",
+ request_kwargs={"metadata": {"user_agent": user_agent}} if user_agent is not None else {},
+ messages=[{"role": "user", "content": envelope}],
+ )
+
+ assert response is not None
+ assert response.model == "task-model"
+ completion.assert_awaited_once()
+ assert completion.call_args.kwargs["messages"][1]["content"].strip() == f"Classify this message:\n{envelope}"
+
+ @pytest.mark.parametrize("envelope", _CODEX_ENVELOPES)
+ def test_codex_envelopes_preserve_delegated_task_and_prior_context(self, envelope: str) -> None:
+ from litellm.router_strategy.complexity_router.complexity_router import (
+ _CODEX_REMINDER_MARKERS,
+ _extract_current_ask_and_system_prompt,
+ _extract_prior_turns,
+ _newest_turn_ask,
+ _newest_turn_is_human_ask,
+ )
+
+ messages: Final = [
+ {"role": "user", "content": f"{envelope}\nDesign cache invalidation"},
+ {
+ "role": "user",
+ "content": [{"type": "text", "text": envelope}, {"type": "text", "text": _CODEX_NEW_TASK}],
+ },
+ {"role": "developer", "content": "<permissions instructions>developer scope</permissions instructions>"},
+ {"role": "user", "content": envelope},
+ ]
+
+ assert _extract_current_ask_and_system_prompt(messages, _CODEX_REMINDER_MARKERS)[0] == _CODEX_NEW_TASK
+ assert _extract_prior_turns(messages, _CODEX_NEW_TASK, 1, 100, None, False, _CODEX_REMINDER_MARKERS) == (
+ ("user", "Design cache invalidation"),
+ )
+ assert _newest_turn_ask(messages, _CODEX_REMINDER_MARKERS) is None
+ assert _newest_turn_is_human_ask(messages, _CODEX_REMINDER_MARKERS) is False
+ assert _extract_current_ask_and_system_prompt([messages[-1]], _CODEX_REMINDER_MARKERS)[0] is None
+
+ @pytest.mark.parametrize("envelope", _CODEX_ENVELOPES)
+ def test_codex_marker_override_and_incomplete_blocks_preserve_text(self, envelope: str) -> None:
+ from litellm.router_strategy.complexity_router.complexity_router import (
+ _CODEX_REMINDER_MARKERS,
+ _strip_reminder_blocks,
+ )
+
+ incomplete: Final = envelope.rsplit("</", 1)[0]
+ assert _strip_reminder_blocks(f"before {envelope.upper()} after", _CODEX_REMINDER_MARKERS) == "before after"
+ assert _strip_reminder_blocks(incomplete, _CODEX_REMINDER_MARKERS) == incomplete
+ assert _strip_reminder_blocks(envelope) == envelope
+ assert _strip_reminder_blocks(f"<custom>noise</custom>{envelope}", (("<custom>", "</custom>"),)) == envelope
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("responses_api", (False, True))
+ async def test_codex_routing_preserves_original_request(self, responses_api: bool) -> None:
+ completion: Final = AsyncMock(return_value=_llm_response('{"tier":"COMPLEX"}'))
+ router: Final = ComplexityRouter(
+ model_name="codex-router",
+ litellm_router_instance=MagicMock(acompletion=completion),
+ complexity_router_config={
+ "tiers": {"COMPLEX": "task-model", "REASONING": "escalated-model"},
+ "classifier_type": "llm",
+ "classifier_llm_config": {"model": "classifier-model"},
+ "keyword_tier_rules": [{"keywords": ["LITELLM ESCALATE"], "tier": "REASONING"}],
+ },
+ )
+ messages: Final = [
+ {"role": "user", "content": _CODEX_NEW_TASK},
+ {"role": "user", "content": "\n".join(_CODEX_ENVELOPES)},
+ ]
+ original: Final = deepcopy(messages)
+ request_kwargs: Final = (
+ {
+ "input": messages,
+ "litellm_metadata": {"user_api_key_request_route": "/v1/responses", "user_agent": "codex-tui"},
+ }
+ if responses_api
+ else {"metadata": {"user_agent": "codex-tui"}}
+ )
+
+ response: Final = await router.async_pre_routing_hook(
+ model="codex-router",
+ request_kwargs=request_kwargs,
+ messages=None if responses_api else messages,
+ input=messages if responses_api else None,
+ )
+
+ assert response is not None
+ assert response.model == "task-model"
+ completion.assert_awaited_once()
+ assert completion.call_args.kwargs["messages"][1]["content"].strip() == (
+ f"Classify this message:\n{_CODEX_NEW_TASK}"
+ )
+ assert messages == original
+ if responses_api:
+ assert response.messages is None
+ assert request_kwargs["input"] == original
+ else:
+ assert response.messages == original
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("custom_markers", (False, True))
+ async def test_codex_markers_are_request_scoped_and_respect_overrides(self, custom_markers: bool) -> None:
+ completion: Final = AsyncMock(return_value=_llm_response('{"tier":"COMPLEX"}'))
+ router: Final = ComplexityRouter(
+ model_name="router",
+ litellm_router_instance=MagicMock(acompletion=completion),
+ complexity_router_config={
+ "tiers": {"COMPLEX": "task-model"},
+ "classifier_type": "llm",
+ "classifier_llm_config": {"model": "classifier-model"},
+ "classifier_context_window_size": 2,
+ "escalation_keywords": [],
+ **({"reminder_markers": [{"open": "<custom>", "close": "</custom>"}]} if custom_markers else {}),
+ },
+ )
+ envelope: Final = "\n".join(_CODEX_ENVELOPES)
+ prior: Final = f"{envelope}\nDesign cache invalidation"
+ messages: Final = [
+ {"role": "user", "content": prior},
+ {"role": "user", "content": _CODEX_NEW_TASK},
+ {"role": "user", "content": envelope},
+ ]
+ for user_agent in ("codex-tui", "curl/8.7.1", "codex_cli_rs/0.62.0"):
+ response: Final = await router.async_pre_routing_hook(
+ model="router", request_kwargs={"metadata": {"user_agent": user_agent}}, messages=messages
+ )
+ assert response is not None
+ assert response.model == "task-model"
+ payload: Final = completion.call_args.kwargs["messages"][1]["content"]
+ if user_agent.startswith("codex") and not custom_markers:
+ assert payload.endswith(f"Classify this message:\n{_CODEX_NEW_TASK}")
+ assert "Design cache invalidation" in payload
+ assert "LITELLM ESCALATE" not in payload
+ else:
+ assert payload.endswith(f"Classify this message:\n{envelope}")
+ assert prior in payload
+ assert response.messages == messages
+ assert completion.await_count == 3
+
+ @pytest.mark.parametrize(
+ "messages,expected_ask",
+ [
+ pytest.param(
+ [_ASKED, _ANSWERED, {"role": "user", "content": [_TOOL_RESULT]}],
+ _ASK,
+ id="messages-surface-tool-result-skipped",
+ ),
+ pytest.param(
+ [
+ _ASKED,
+ _ANSWERED,
+ {"role": "user", "content": [{**_TOOL_RESULT, "content": [{"type": "text", "text": "out"}]}]},
+ ],
+ _ASK,
+ id="nested-tool-result-skipped",
+ ),
+ pytest.param(
+ [_ASKED, _ANSWERED, {"role": "tool", "tool_call_id": "x", "content": "out"}],
+ _ASK,
+ id="chat-completions-tool-role-never-read",
+ ),
+ pytest.param(
+ [_ASKED, _ANSWERED, {"role": "user", "content": [_TOOL_RESULT, {"type": "text", "text": "and now?"}]}],
+ "and now?",
+ id="ask-riding-with-tool-result-survives",
+ ),
+ pytest.param(
+ [_ASKED, _ANSWERED, {"role": "user", "content": f"{_REMINDER}"}],
+ _ASK,
+ id="reminder-only-turn-skipped",
+ ),
+ pytest.param(
+ [_ASKED, _ANSWERED, {"role": "user", "content": f"{_REMINDER}\nand now?"}],
+ "and now?",
+ id="ask-riding-with-reminder-survives",
+ ),
+ pytest.param(
+ [{"role": "user", "content": f"{_REMINDER}and now?{_REMINDER}"}],
+ "and now?",
+ id="multiple-reminders-stripped",
+ ),
+ pytest.param(
+ [
+ {
+ "role": "user",
+ "content": [{"type": "text", "text": _REMINDER}, {"type": "text", "text": "and now?"}],
+ }
+ ],
+ "and now?",
+ id="reminder-in-its-own-content-part",
+ ),
+ pytest.param(
+ [{"role": "user", "content": "why is my <system-reminder> tag stripped?"}],
+ "why is my <system-reminder> tag stripped?",
+ id="unclosed-tag-in-prose-preserved",
+ ),
+ pytest.param(
+ [{"role": "user", "content": f"I see {_REMINDER} how do I disable it?"}],
+ "I see how do I disable it?",
+ id="prose-around-quoted-block-survives",
+ ),
+ pytest.param([{"role": "user", "content": _REMINDER}], None, id="plumbing-only-yields-no-ask"),
+ ],
+ )
+ def test_current_ask_is_the_text_a_human_wrote(self, messages, expected_ask):
+ """One table for which text becomes the current ask, since every consumer reads only this.
+
+ Tool output needs no tool-specific parsing: Messages-surface `tool_result` blocks are not text
+ parts so the turn flattens to empty, and chat-completions puts it on a `tool` role never read.
+ Reminders arrive as ordinary text, so a complete block is stripped and the ask riding with it
+ survives; an unclosed tag is not a block and is left alone. A quoted complete block is
+ byte-identical to an injected one, so it is stripped too and only the prose survives.
+
+ The last row is the case reported from both directions. There is no ask to recover, so the
+ caller routes to its default model; falling back to the raw turn would put harness text in
+ front of escalation keywords and keyword_tier_rules, which force a tier and choose the spend.
+ """
+ from litellm.router_strategy.complexity_router.complexity_router import _extract_current_ask_and_system_prompt
+
+ assert _extract_current_ask_and_system_prompt(messages)[0] == expected_ask
+
+ def test_custom_markers_skip_a_reminder_only_follow_up_message(self):
+ """A harness using non-default markers, sent as its own trailing message, is still skipped.
+
+ Some harnesses (unlike Claude Code, which inlines the reminder alongside the ask in one
+ message) send internal context as a separate follow-up user turn using their own markers.
Without configuring reminder_markers, that turn does not match the built-in
<system-reminder> constants, never strips to empty, and wins "newest human ask" -- the
harness's internal-context blob gets classified instead of the real question. Configuring
@@@ -12400,55 -13239,575 +13705,571 @@@ class TestHealthFallbackDispatch
@staticmethod
def _router(
- mock_router_instance,
- config,
- ids_by_model,
- cooling=(),
- blocked=(),
- excluded=(),
- raises_for=None,
- health_error=None,
- ):
- """ids_by_model: model group -> deployment ids the router knows.
-
- The fake mirrors the real async_get_healthy_deployments contract, including how it says
- no: BadRequestError for a group with no deployment at all, RouterRateLimitError when every
- deployment is filtered out (cooling, admin-paused, or excluded by a request-scoped policy
- such as tags, team scoping or access groups), a per-model exception via raises_for (the
- RPM verdict), and an unrelated failure via health_error. It records what it was handed so
- tests can prove the probe passes a kwargs copy and forwards the prompt arguments.
- """
- import litellm as litellm_module
+ surface: str = "chat",
+ *,
+ peer: bool = False,
+ session: bool = False,
+ tagged: bool = False,
+ budgeted: bool = False,
+ config: Mapping[str, object] | None = None,
+ ) -> Router:
+ provider: Final = "anthropic/claude-sonnet-5" if surface == "messages" else "openai/gpt-5.6"
+ base_suffix: Final = "" if surface == "messages" else "/v1"
+ return Router(
+ model_list=[
+ {
+ "model_name": "health-router",
+ "litellm_params": {
+ "model": "auto_router/complexity_router",
+ "complexity_router_default_model": (config or {}).get("default_model", "fallback"),
+ "complexity_router_config": {
+ "tiers": {"SIMPLE": ["primary", "peer"] if peer else "primary", "MEDIUM": "primary"},
+ "session_affinity": session,
+ "deployment_affinity": False,
+ "max_tokens_from_tier_model": False,
+ **(config or {}),
+ },
+ },
+ },
+ *[
+ {
+ "model_name": name,
+ "litellm_params": {
+ "model": provider,
+ "api_key": "test-only",
+ "api_base": f"https://{name}.test{base_suffix}",
+ **({"tags": [name]} if tagged else {}),
- **(
- {"max_budget": 1.0, "budget_duration": "1d"}
- if budgeted and name == "primary"
- else {}
- ),
++ **({"max_budget": 1.0, "budget_duration": "1d"} if budgeted and name == "primary" else {}),
+ },
+ "model_info": {"id": f"{name}-id"},
+ }
+ for name in ("primary", "peer", "fallback")
+ ],
+ ],
+ num_retries=0,
+ enable_health_check_routing=True,
+ enable_tag_filtering=tagged,
+ )
- from litellm.types.router import RouterRateLimitError
+ @staticmethod
+ def _unavailable(router: Router, model_id: str, source: Literal["health", "cooldown"]) -> None:
+ if source == "health":
+ router.health_state_cache.set_deployment_health_states(
+ {model_id: {"is_healthy": False, "timestamp": time.time()}}
+ )
+ else:
+ router.cooldown_cache.add_deployment_to_cooldown(
+ model_id=model_id,
+ original_exception=RuntimeError("unavailable"),
+ exception_status=503,
+ cooldown_time=60,
+ )
- probed_kwargs = []
- probed_prompts = []
+ @staticmethod
+ def _http_response(request: httpx.Request) -> httpx.Response:
+ body: Final = json.loads(request.content)
+ text: Final = request.url.host.split(".")[0]
+ payload: Final[Mapping[str, object]]
+ events: Final[tuple[Mapping[str, object], ...]]
+ if request.url.path.endswith("/responses"):
+ from litellm.responses.main import mock_responses_api_response
+
+ payload = mock_responses_api_response(text).model_dump()
+ events = (
+ {"type": "response.created", "response": {**payload, "status": "in_progress"}, "sequence_number": 0},
+ {
+ "type": "response.output_text.delta",
+ "delta": text,
+ "item_id": "msg_test",
+ "output_index": 0,
+ "content_index": 0,
+ "sequence_number": 1,
+ },
+ {"type": "response.completed", "response": payload, "sequence_number": 2},
+ )
+ elif request.url.path.endswith("/messages"):
+ payload = {
+ "id": "msg_test",
+ "type": "message",
+ "role": "assistant",
+ "model": body["model"],
+ "content": [{"type": "text", "text": text}],
+ "stop_reason": "end_turn",
+ "stop_sequence": None,
+ "usage": {"input_tokens": 10, "output_tokens": 1},
+ }
+ events = (
+ {"type": "message_start", "message": {**payload, "content": [], "stop_reason": None}},
+ {"type": "content_block_start", "index": 0, "content_block": {"type": "text", "text": ""}},
+ {"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": text}},
+ {"type": "content_block_stop", "index": 0},
+ {"type": "message_delta", "delta": {"stop_reason": "end_turn"}, "usage": {"output_tokens": 1}},
+ {"type": "message_stop"},
+ )
+ else:
+ payload = {
+ "id": "chatcmpl-test",
+ "object": "chat.completion",
+ "created": 1,
+ "model": body["model"],
+ "choices": [{"index": 0, "message": {"role": "assistant", "content": text}, "finish_reason": "stop"}],
+ "usage": {"prompt_tokens": 10, "completion_tokens": 1, "total_tokens": 11},
+ }
+ events = (
+ {
+ **payload,
+ "object": "chat.completion.chunk",
+ "choices": [{"index": 0, "delta": {"content": text}, "finish_reason": None}],
+ },
+ {
+ **payload,
+ "object": "chat.completion.chunk",
+ "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}],
+ },
+ )
+ if not body.get("stream"):
+ return httpx.Response(200, json=payload)
+ wire: Final = "".join(
+ (f"event: {event['type']}\n" if "type" in event else "") + f"data: {json.dumps(event)}\n\n"
+ for event in events
+ )
+ return httpx.Response(
+ 200,
+ text=wire + ("data: [DONE]\n\n" if "type" not in events[0] else ""),
+ headers={"content-type": "text/event-stream"},
+ )
- async def get_healthy_deployments(
- model, request_kwargs, messages=None, input=None, parent_otel_span=None, **kwargs
- ):
- probed_kwargs.append(request_kwargs)
- probed_prompts.append((messages, input))
- if health_error is not None:
- raise health_error
- if raises_for and model in raises_for:
- raise raises_for[model]
- if not ids_by_model.get(model):
- raise litellm_module.BadRequestError(
- message=f"You passed in model={model}. There are no healthy deployments.",
- model=model,
- llm_provider="",
+ @staticmethod
+ async def _request(router: Router, surface: str, stream: bool, metadata: dict[str, object]) -> str:
+ if surface == "responses":
+ result = await router.aresponses(
+ model="health-router", input="Hello!", stream=stream, litellm_metadata=metadata
+ )
+ elif surface == "messages":
+ result = await router.aanthropic_messages(
+ model="health-router",
+ messages=[{"role": "user", "content": "Hello!"}],
+ max_tokens=32,
+ stream=stream,
+ litellm_metadata=metadata,
+ )
+ else:
+ result = await router.acompletion(
+ model="health-router",
+ messages=[{"role": "user", "content": "Hello!"}],
+ stream=stream,
+ metadata=metadata,
+ )
+ if not stream:
+ payload = result if isinstance(result, dict) else result.model_dump()
+ if surface == "responses":
+ return payload["output"][0]["content"][0]["text"]
+ if surface == "messages":
+ return payload["content"][0]["text"]
+ return payload["choices"][0]["message"]["content"]
+ if surface == "messages":
+ wire: Final = b"".join([chunk async for chunk in result]).decode()
+ events = tuple(json.loads(line[6:]) for line in wire.splitlines() if line.startswith("data: "))
+ assert events[-1]["type"] == "message_stop"
+ return "".join(c["delta"]["text"] for c in events if c["type"] == "content_block_delta")
+ chunks: Final = [chunk.model_dump() async for chunk in result]
+ if surface == "responses":
+ assert chunks[-1]["type"] == "response.completed"
+ return "".join(c["delta"] for c in chunks if c["type"] == "response.output_text.delta")
+ assert chunks[-1]["choices"][0]["finish_reason"] == "stop"
+ return "".join(c["choices"][0]["delta"].get("content") or "" for c in chunks if c["choices"])
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("surface", ["chat", "responses", "messages"])
+ @pytest.mark.parametrize("stream", [False, True])
+ @pytest.mark.parametrize("source", ["health", "cooldown"])
+ async def test_public_call_falls_back_and_recovers(
+ self, surface: str, stream: bool, source: Literal["health", "cooldown"]
+ ) -> None:
+ router: Final = self._router(surface, session=True)
+ self._unavailable(router, "primary-id", source)
+ metadata: Final[dict[str, object]] = {"session_id": "outage"}
+ with respx.mock(assert_all_mocked=True) as upstream:
+ upstream.post(host__regex=r"^(primary|peer|fallback)\.test$").mock(side_effect=self._http_response)
+ assert await self._request(router, surface, stream, metadata) == "fallback"
+ assert metadata["routing_decision"]["cause"] == "health_default_fallback"
+ assert "tier" not in metadata["routing_decision"]
+ assert "health_displaced:primary" in metadata["routing_decision"]["signals"]
+ assert [c.request.url.host for c in upstream.calls] == ["fallback.test"]
+ strategy: Final = router.complexity_routers["health-router"][0].strategy
+ key: Final = strategy._get_session_affinity_cache_key("outage", {})
+ assert await router.cache.async_get_cache(key=key) is None
+ if source == "health":
+ router.health_state_cache.set_deployment_health_states(
+ {"primary-id": {"is_healthy": True, "timestamp": time.time()}}
)
- filtered = (*cooling, *blocked, *excluded)
- healthy = [
- {"model_name": model, "model_info": {"id": i}} for i in ids_by_model[model] if i not in filtered
- ]
- if not healthy:
- raise RouterRateLimitError(
- model=model, cooldown_time=60.0, enable_pre_call_checks=False, cooldown_list=[]
+ else:
+ router.cooldown_cache.cooldown_store.delete_cache(
+ router.cooldown_cache.get_cooldown_cache_key("primary-id")
)
- return healthy
+ recovered: Final[dict[str, object]] = {"session_id": "outage"}
+ assert await self._request(router, surface, stream, recovered) == "primary"
+ assert recovered["routing_decision"]["routed_model"] == "primary"
+ assert [c.request.url.host for c in upstream.calls] == ["fallback.test", "primary.test"]
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("source", ["health", "cooldown"])
+ async def test_partial_group_then_peer_then_default(self, source: Literal["health", "cooldown"]) -> None:
+ router: Final = self._router(peer=True, session=True)
+ router.add_deployment(
+ Deployment(
+ model_name="primary",
+ litellm_params=LiteLLM_Params(
+ model="openai/gpt-5.6", api_key="test-only", api_base="https://primary.test/v1"
+ ),
+ model_info={"id": "primary-sibling-id"},
+ )
+ )
+ strategy: Final = router.complexity_routers["health-router"][0].strategy
+ key: Final = strategy._get_session_affinity_cache_key("precedence", {})
+ await router.cache.async_set_cache(key=key, value={"model": "primary", "tier": "SIMPLE"}, ttl=600)
+ with respx.mock(assert_all_mocked=True) as upstream:
+ upstream.post(host__regex=r"^(primary|peer|fallback)\.test$").mock(side_effect=self._http_response)
+ for model_id, expected, cause in (
+ ("primary-id", "primary", "session_affinity_pin"),
+ ("primary-sibling-id", "peer", "health_failover"),
+ ("peer-id", "fallback", "health_default_fallback"),
+ ):
+ self._unavailable(router, model_id, source)
+ metadata: Final[dict[str, object]] = {"session_id": "precedence"}
+ assert await self._request(router, "chat", False, metadata) == expected
+ assert metadata["routing_decision"]["cause"] == cause
+ assert await router.cache.async_get_cache(key=key) == {"model": "primary", "tier": "SIMPLE"}
+ assert [c.request.url.host for c in upstream.calls] == ["primary.test", "peer.test", "fallback.test"]
+
+ @pytest.mark.asyncio
+ async def test_spent_deployment_budget_falls_back_to_the_default(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """A spent budget leaves the tier with nothing that may serve the request, and the budget
+ filter reports that as a bare ValueError instead of a typed router error. Reading it as
+ capacity skips the recovery and fails the request the recovery exists for."""
+
+ async def _no_sync(*args: object, **kwargs: object) -> None:
+ return None
+
+ monkeypatch.setattr(
+ "litellm.router_strategy.budget_limiter.RouterBudgetLimiting.periodic_sync_in_memory_spend_with_redis",
+ _no_sync,
+ )
+ monkeypatch.setattr(litellm, "callbacks", [])
+ router: Final = self._router(budgeted=True)
+ limiter: Final = router.router_budget_logger
+ assert limiter is not None, "a deployment max_budget must install the budget limiter"
+ await router.cache.async_set_cache(key="deployment_spend:primary-id:1d", value=2.0)
+ with respx.mock(assert_all_mocked=True) as upstream:
+ upstream.post(host__regex=r"^(primary|fallback)\.test$").mock(side_effect=self._http_response)
+ metadata: Final[dict[str, object]] = {}
+ assert await self._request(router, "chat", False, metadata) == "fallback"
+ assert metadata["routing_decision"]["cause"] == "health_default_fallback"
+ assert [c.request.url.host for c in upstream.calls] == ["fallback.test"]
+
+ @pytest.mark.asyncio
+ async def test_concurrent_tag_scopes_keep_fallbacks_request_local(self) -> None:
+ router: Final = self._router(tagged=True)
+ router.add_deployment(
+ Deployment(
+ model_name="fallback",
+ litellm_params=LiteLLM_Params(
+ model="openai/gpt-5.6", api_key="test-only", api_base="https://peer.test/v1", tags=["peer"]
+ ),
+ model_info={"id": "fallback-peer-id"},
+ )
+ )
+ self._unavailable(router, "primary-id", "cooldown")
+ with respx.mock(assert_all_mocked=True) as upstream:
+ upstream.post(host__regex=r"^(peer|fallback)\.test$").mock(side_effect=self._http_response)
+ scopes: Final = tuple({"tags": [name], "session_id": name} for name in ("peer", "fallback"))
+ results: Final = await asyncio.gather(
+ *(self._request(router, "chat", False, metadata) for metadata in scopes)
+ )
+ assert results == ["peer", "fallback"]
+ assert [m["tags"] for m in scopes] == [["peer"], ["fallback"]]
+ assert [m["routing_decision"]["routed_model"] for m in scopes] == ["fallback", "fallback"]
+ assert sorted(c.request.url.host for c in upstream.calls) == ["fallback.test", "peer.test"]
+
+ @pytest.mark.asyncio
+ async def test_probe_preserves_consumed_request_exclusions(self) -> None:
+ router: Final = self._router()
+ self._unavailable(router, "primary-id", "cooldown")
+ kwargs: Final = {"_excluded_deployment_ids": ["fallback-id"], "_target_order": 1}
+ strategy: Final = router.complexity_routers["health-router"][0].strategy
+ response: Final = await strategy.async_pre_routing_hook(
+ model="health-router", messages=[{"role": "user", "content": "Hello!"}], request_kwargs=kwargs
+ )
+ assert response.model == "primary"
+ assert kwargs == {"_excluded_deployment_ids": ["fallback-id"], "_target_order": 1}
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("default_state", ["cooldown", "unconfigured", "same-model"])
+ async def test_unavailable_default_preserves_no_deployment_error(self, default_state: str) -> None:
+ from litellm.types.router import RouterRateLimitError
+
+ router: Final = self._router(config={"default_model": "primary"} if default_state == "same-model" else None)
+ self._unavailable(router, "primary-id", "cooldown")
+ if default_state == "unconfigured":
+ router.delete_deployment(id="fallback-id")
+ elif default_state == "cooldown":
+ self._unavailable(router, "fallback-id", "cooldown")
+ with respx.mock(assert_all_mocked=True) as upstream:
+ with pytest.raises(RouterRateLimitError, match="No deployments available"):
+ await self._request(router, "chat", False, {})
+ assert not upstream.calls
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("plan_active", [False, True])
+ async def test_plan_floor_outage_cannot_use_untiered_default(self, plan_active: bool) -> None:
+ from litellm.types.router import RouterRateLimitError
+
+ router: Final = self._router(
+ config={"tiers": {"SIMPLE": "primary", "MEDIUM": "peer"}, "plan_mode_min_tier": "MEDIUM"}
+ )
+ self._unavailable(router, "primary-id", "cooldown")
+ self._unavailable(router, "peer-id", "cooldown")
+ metadata: Final = {}
+ with respx.mock(assert_all_mocked=True, assert_all_called=False) as upstream:
+ upstream.post(host="fallback.test").mock(side_effect=self._http_response)
+ if plan_active:
+ with pytest.raises(RouterRateLimitError, match="No deployments available"):
+ await router.acompletion(
+ model="health-router",
+ messages=[
+ {"role": "system", "content": "Plan mode is active"},
+ {"role": "user", "content": "Hello!"},
+ ],
+ metadata=metadata,
+ )
+ assert not upstream.calls
+ assert metadata["routing_decision"]["routed_model"] == "peer"
+ assert metadata["routing_decision"]["tier"] == "MEDIUM"
+ else:
+ assert await self._request(router, "chat", False, metadata) == "fallback"
+
+ @pytest.mark.asyncio
+ async def test_default_dispatch_drops_displaced_tier_params(self) -> None:
+ router: Final = self._router(
+ config={"tiers": {"SIMPLE": {"model_name": "primary", "litellm_params": {"max_tokens": 9}}}}
+ )
+ with respx.mock(assert_all_mocked=True) as upstream:
+ upstream.post(host__regex=r"^(primary|fallback)\.test$").mock(side_effect=self._http_response)
+ await router.acompletion(
+ model="health-router", messages=[{"role": "user", "content": "Hello!"}], max_tokens=32
+ )
+ assert json.loads(upstream.calls[-1].request.content)["max_completion_tokens"] == 9
+ self._unavailable(router, "primary-id", "cooldown")
+ await router.acompletion(
+ model="health-router", messages=[{"role": "user", "content": "Hello!"}], max_tokens=32
+ )
+ assert json.loads(upstream.calls[-1].request.content)["max_completion_tokens"] == 32
+ assert upstream.calls[-1].request.url.host == "fallback.test"
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("source", ["health", "cooldown"])
+ async def test_pinned_session_returns_to_primary_after_outage(self, source: Literal["health", "cooldown"]) -> None:
+ router: Final = self._router(session=True)
+ with respx.mock(assert_all_mocked=True) as upstream:
+ upstream.post(host__regex=r"^(primary|fallback)\.test$").mock(side_effect=self._http_response)
+ assert await self._request(router, "chat", False, {"session_id": "pinned"}) == "primary"
+ self._unavailable(router, "primary-id", source)
+ outage: Final[dict[str, object]] = {"session_id": "pinned"}
+ assert await self._request(router, "chat", False, outage) == "fallback"
+ assert outage["routing_decision"]["cause"] == "health_default_fallback"
+ if source == "health":
+ router.health_state_cache.set_deployment_health_states(
+ {"primary-id": {"is_healthy": True, "timestamp": time.time()}}
+ )
+ else:
+ router.cooldown_cache.cooldown_store.delete_cache(
+ router.cooldown_cache.get_cooldown_cache_key("primary-id")
+ )
+ recovered: Final[dict[str, object]] = {"session_id": "pinned"}
+ assert await self._request(router, "chat", False, recovered) == "primary"
+ assert recovered["routing_decision"]["cause"] == "session_affinity_pin"
+ assert [c.request.url.host for c in upstream.calls] == ["primary.test", "fallback.test", "primary.test"]
+
+ @pytest.mark.asyncio
+ async def test_policy_plugin_does_not_escape_to_live_default(self) -> None:
+ from litellm.types.router import RouterRateLimitError, RoutingContext
+
+ class PrimaryOnly:
+ async def run(self, context: RoutingContext) -> RoutingContext:
+ context.candidate_models = [name for name in context.candidate_models if name == "primary"]
+ return context
+
+ router: Final = self._router(peer=True, config={"plugins": [PrimaryOnly()]})
+ self._unavailable(router, "primary-id", "cooldown")
+ with respx.mock(assert_all_mocked=True) as upstream:
+ with pytest.raises(RouterRateLimitError, match="No deployments available"):
+ await self._request(router, "chat", False, {})
+ assert not upstream.calls
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("live_tier", [True, False])
+ @pytest.mark.parametrize("default_fits", [True, False])
+ async def test_context_recovery_precedes_default_with_prechecks_off(
+ self, live_tier: bool, default_fits: bool
+ ) -> None:
+ from litellm.types.router import RouterRateLimitError
+
+ router: Final = self._router(config={"tiers": {"SIMPLE": "primary", "MEDIUM": "peer", "COMPLEX": "large"}})
+ router.add_deployment(
+ Deployment(
+ model_name="large",
+ litellm_params=LiteLLM_Params(
+ model="openai/gpt-5.6", api_key="test-only", api_base="https://large.test/v1"
+ ),
+ model_info={"id": "large-id", "max_input_tokens": 10000},
+ )
+ )
+ for deployment in router.model_list:
+ deployment["model_info"]["max_input_tokens"] = (
+ 10
+ if deployment["model_name"] == "primary"
+ or (deployment["model_name"] == "fallback" and not default_fits)
+ else 10000
+ )
+ self._unavailable(router, "peer-id", "cooldown")
+ if not live_tier:
+ self._unavailable(router, "large-id", "cooldown")
+ assert router.enable_pre_call_checks is False
+ metadata: Final = {}
+ messages: Final = [{"role": "user", "content": "hello " * 100}]
+ with respx.mock(assert_all_mocked=True, assert_all_called=False) as upstream:
+ upstream.post(host__regex=r"^(large|fallback)\.test$").mock(side_effect=self._http_response)
+ if not live_tier and not default_fits:
+ with pytest.raises(RouterRateLimitError, match="No deployments available"):
+ await router.acompletion(model="health-router", messages=messages, metadata=metadata)
+ assert not upstream.calls
+ else:
+ result: Final = await router.acompletion(model="health-router", messages=messages, metadata=metadata)
+ expected: Final = "large" if live_tier else "fallback"
+ assert result.choices[0].message.content == expected
+ assert upstream.calls[-1].request.url.host == f"{expected}.test"
+ assert metadata["routing_decision"].get("tier") == ("COMPLEX" if live_tier else None)
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("live_tier", [True, False])
+ async def test_modality_recovery_precedes_default(self, live_tier: bool) -> None:
+ router: Final = self._router(
+ config={"modality_routing": True, "tiers": {"SIMPLE": "primary", "MEDIUM": "peer", "COMPLEX": "vision"}}
+ )
+ router.add_deployment(
+ Deployment(
+ model_name="vision",
+ litellm_params=LiteLLM_Params(
+ model="openai/gpt-5.6", api_key="test-only", api_base="https://vision.test/v1"
+ ),
+ model_info={"id": "vision-id", "supports_vision": True},
+ )
+ )
+ for deployment in router.model_list:
+ deployment["model_info"]["supports_vision"] = deployment["model_name"] != "primary"
+ self._unavailable(router, "peer-id", "cooldown")
+ if not live_tier:
+ self._unavailable(router, "vision-id", "cooldown")
+ with respx.mock(assert_all_mocked=True) as upstream:
+ upstream.post(host__regex=r"^(vision|fallback)\.test$").mock(side_effect=self._http_response)
+ result: Final = await router.acompletion(
+ model="health-router",
+ messages=[
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "Hello!"},
+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,aGk="}},
+ ],
+ }
+ ],
+ )
+ expected: Final = "vision" if live_tier else "fallback"
+ assert result.choices[0].message.content == expected
+ assert upstream.calls[-1].request.url.host == f"{expected}.test"
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("default_fits", [True, False])
+ async def test_modality_default_must_also_fit_context(self, default_fits: bool) -> None:
+ router: Final = self._router(config={"modality_routing": True, "tiers": {"SIMPLE": "primary"}})
+ for deployment in router.model_list:
+ deployment["model_info"]["supports_vision"] = deployment["model_name"] == "fallback"
+ deployment["model_info"]["max_input_tokens"] = 10000 if default_fits else 10
+ with respx.mock(assert_all_mocked=True, assert_all_called=False) as upstream:
+ upstream.post(host="fallback.test").mock(side_effect=self._http_response)
+ messages: Final = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "hello " * 100},
+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,aGk="}},
+ ],
+ }
+ ]
+ if default_fits:
+ result: Final = await router.acompletion(model="health-router", messages=messages)
+ assert result.choices[0].message.content == "fallback"
+ else:
+ with pytest.raises(litellm.BadRequestError, match="modality_routing is enabled"):
+ await router.acompletion(model="health-router", messages=messages)
+ assert not upstream.calls
+
+
+ class TestTierHealthFailover:
+ """A tier whose decided model group is entirely in cooldown falls back to a live peer."""
+
+ SIMPLE_MESSAGE = [{"role": "user", "content": "Hello!"}]
+ TIERS = {"SIMPLE": ["dead-a", "live-b"], "MEDIUM": "mid", "COMPLEX": "big", "REASONING": "top"}
+
+ @staticmethod
+ def _router(
+ mock_router_instance,
+ config,
+ ids_by_model,
+ cooling=(),
+ blocked=(),
+ excluded=(),
+ raises_for=None,
+ health_error=None,
+ ):
+ """ids_by_model: model group -> deployment ids the router knows.
+
+ The fake mirrors the real async_get_healthy_deployments contract, including how it says
+ no: BadRequestError for a group with no deployment at all, RouterRateLimitError when every
+ deployment is filtered out (cooling, admin-paused, or excluded by a request-scoped policy
+ such as tags, team scoping or access groups), a per-model exception via raises_for (the
+ RPM verdict), and an unrelated failure via health_error. It records what it was handed so
+ tests can prove the probe passes a kwargs copy and forwards the prompt arguments.
+ """
+ import litellm as litellm_module
+
+ from litellm.types.router import RouterRateLimitError
+
+ probed_kwargs = []
+ probed_prompts = []
+
+ async def get_healthy_deployments(
+ model, request_kwargs, messages=None, input=None, parent_otel_span=None, health_check_probe=False
+ ):
+ probed_kwargs.append(request_kwargs)
+ probed_prompts.append((messages, input))
+ if health_error is not None:
+ raise health_error
+ if raises_for and model in raises_for:
+ raise raises_for[model]
+ if not ids_by_model.get(model):
+ raise litellm_module.BadRequestError(
+ message=f"You passed in model={model}. There are no healthy deployments.",
+ model=model,
+ llm_provider="",
+ )
+ filtered = (*cooling, *blocked, *excluded)
+ healthy = [{"model_name": model, "model_info": {"id": i}} for i in ids_by_model[model] if i not in filtered]
+ if not healthy:
+ raise RouterRateLimitError(
+ model=model, cooldown_time=60.0, enable_pre_call_checks=False, cooldown_list=[]
+ )
+ return healthy
mock_router_instance.async_get_healthy_deployments = get_healthy_deployments
mock_router_instance.probed_kwargs = probed_kwargs
diff --cc ui/litellm-dashboard/src/components/add_model/ClassificationMethodConfig.tsx
index 15cfff01766,594c6d022ce..f157481080f
--- a/ui/litellm-dashboard/src/components/add_model/ClassificationMethodConfig.tsx
+++ b/ui/litellm-dashboard/src/components/add_model/ClassificationMethodConfig.tsx
@@@ -429,6 -432,6 +432,15 @@@ const ClassificationMethodConfig: React
});
};
++ if (classifierType === "capability") {
++ return (
++ <p className="text-sm text-muted-foreground">
++ This router uses capability forecasting. Configure its classifier, threshold, and calibration through YAML or
++ the API. Saving preserves those settings
++ </p>
++ );
++ }
++
return (
<>
<ClassifierTypeRadios value={value} classifierType={classifierType} onTypeChange={handleClassifierTypeChange} />
diff --cc ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.tsx
index d7df6ce33bb,97d6739aa22..c005030b68b
--- a/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.tsx
+++ b/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.tsx
@@@ -137,7 -143,7 +143,7 @@@ export interface ClassifierLLMConfig
system_prompt?: string;
}
--export type ClassifierType = "heuristic" | "heuristic_v2" | "llm" | "heuristic_first" | "hybrid";
++export type ClassifierType = "heuristic" | "heuristic_v2" | "llm" | "heuristic_first" | "hybrid" | "capability";
/**
* Whether this router can call classifier_llm_config.model. Mirrors the backend's
@@@ -145,7 -151,7 +151,10 @@@
* control and payload key, so a new chaining type cannot strip knobs the operator set.
*/
export const usesLlmClassifier = (classifierType: ClassifierType): boolean =>
-- classifierType === "llm" || classifierType === "heuristic_first" || classifierType === "hybrid";
++ classifierType === "llm" ||
++ classifierType === "heuristic_first" ||
++ classifierType === "hybrid" ||
++ classifierType === "capability";
export type ClassifierFallback = "heuristic" | "default_model";
@@@ -170,7 -176,7 +179,7 @@@ export const heuristicScoringRoleFor =
classifierType: ClassifierType,
classifierFallback: ClassifierFallback | undefined,
): HeuristicScoringRole => {
-- if (classifierType === "heuristic_v2") return "never";
++ if (classifierType === "heuristic_v2" || classifierType === "capability") return "never";
if (classifierType === "heuristic" || classifierType === "heuristic_first" || classifierType === "hybrid")
return "decides";
return (classifierFallback ?? DEFAULT_CLASSIFIER_FALLBACK) === "heuristic" ? "fallback_only" : "never";
diff --cc ui/litellm-dashboard/src/components/add_model/build_complexity_router_config.ts
index 7769fb832fe,5b53941bc10..822af77e0db
--- 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
@@@ -437,7 -470,7 +470,10 @@@ const classifierWireFields =
>,
): Partial<ComplexityRouterConfigPayload> => ({
...(usesLlmClassifier(effectiveType) &&
-- classifierLlmConfig && { classifier_llm_config: normalizeClassifierLlmConfig(classifierLlmConfig) }),
++ classifierLlmConfig && {
++ classifier_llm_config:
++ effectiveType === "capability" ? classifierLlmConfig : normalizeClassifierLlmConfig(classifierLlmConfig),
++ }),
...(usesLlmClassifier(effectiveType) &&
classifierFallback !== undefined && { classifier_fallback: classifierFallback }),
...(effectiveType === "heuristic_first" &&
diff --cc ui/litellm-dashboard/src/components/edit_auto_router/build_updated_complexity_router_config.test.ts
index 0144dff3498,3899361cd17..82785610646
--- 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
@@@ -116,6 -164,6 +164,32 @@@ const STORED_LLM =
classifier_context_per_turn_chars: 300,
};
++describe("capability classifier configuration", () => {
++ it("preserves the judge and calibrated policy through an untouched dashboard edit", () => {
++ const stored = {
++ tiers: { SIMPLE: ["efficient-model"], REASONING: ["capable-model"] },
++ classifier_type: "capability" as const,
++ classifier_llm_config: { model: "judge", timeout_ms: 30000, temperature: 0 },
++ capability_classifier_config: {
++ efficient_tier: "SIMPLE",
++ capable_tier: "REASONING",
++ base_threshold: 0.66,
++ max_output_tokens: 512,
++ response_format: "json_object",
++ calibration: { version: "fitted-v1", slope: 0.15, intercept: 0.19 },
++ },
++ };
++ const hydrated = hydrateComplexityRouterConfig(stored, null);
++ const saved = buildUpdatedComplexityRouterConfig(stored, hydrated);
++
++ expect(saved.classifier_type).toBe("capability");
++ expect(saved.classifier_llm_config).toEqual(stored.classifier_llm_config);
++ expect(saved.capability_classifier_config).toEqual(stored.capability_classifier_config);
++ expect(saved).not.toHaveProperty("classification_prompt");
++ expect(saved).not.toHaveProperty("custom_dimensions");
++ });
++});
++
describe("buildUpdatedComplexityRouterConfig classifier context window", () => {
it("round-trips an untouched edit without changing the classifier context values", () => {
const formValue = {
diff --cc ui/litellm-dashboard/src/lib/http/schema.d.ts
index 2e7fefb6383,dd455cba44a..47e609372a9
--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts
+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts
@@@ -24763,39 -24809,6 +24809,57 @@@ export interface components
*/
status: "cancelled";
};
++ /** CapabilityCalibrationConfig */
++ CapabilityCalibrationConfig: {
++ /** Intercept */
++ intercept: number;
++ /** Slope */
++ slope: number;
++ /** Version */
++ version: string;
++ };
+ /**
+ * CapabilityClassifierConfig
+ * @description Switchyard-compatible probability threshold policy for two model tiers.
+ */
+ CapabilityClassifierConfig: {
+ /**
+ * Base Threshold
+ * @description Lowest p_solve that routes a supported task to efficient_tier
+ */
+ base_threshold: number;
++ /** @description Optional versioned sigmoid calibration fitted for this judge, capability card, efficient model, and execution setup. Applies sigmoid(slope * logit(clip(p_solve, 1e-6, 1-1e-6)) + intercept) before the threshold policy. Omit to route on the raw forecast. */
++ calibration?: components["schemas"]["CapabilityCalibrationConfig"] | null;
+ /**
+ * Capable Tier
+ * @description Higher, fail-closed tier used below the adjusted threshold or when the classifier verdict is unavailable
+ */
+ capable_tier: string;
+ /**
+ * Efficient Tier
+ * @description Tier used when the efficient model's forecasted solve probability meets the adjusted threshold
+ */
+ efficient_tier: string;
+ /**
+ * Max Output Tokens
+ * @description Maximum completion tokens available to the capability classifier verdict
+ * @default 4096
+ */
+ max_output_tokens: number;
++ /**
++ * Response Format
++ * @description Use json_object for judges without strict JSON Schema support. This appends the verdict schema to the packaged system prompt; both modes validate the returned verdict identically.
++ * @default json_schema
++ * @enum {string}
++ */
++ response_format: "json_schema" | "json_object";
+ /**
+ * Threshold Step
+ * @description Amount added once for uncertain or unmatched verdicts and twice for unsupported verdicts
+ * @default 0
+ */
+ threshold_step: number;
+ };
/** ChatCompletionAnnotation */
ChatCompletionAnnotation: {
/**
@@@ -36176,21 -36410,11 +36463,25 @@@
* Cause
* @enum {string}
*/
- cause?: "heuristic_scorer" | "heuristic_v2" | "reasoning_override" | "llm_classifier" | "capability_classifier" | "heuristic_first_short_circuit" | "hybrid_short_circuit" | "classifier_plugin" | "classifier_fallback" | "capability_classifier_fallback" | "default_model_fallback" | "literal_keyword_match" | "semantic_keyword_match" | "plan_mode" | "housekeeping" | "modality_escalation" | "modality_pin_override" | "health_failover" | "session_affinity_pin" | "session_affinity_escalation" | "user_turn_continuation" | "default_fallback" | "keyword" | "quality_tier" | "bandit";
- cause?: "heuristic_scorer" | "heuristic_v2" | "reasoning_override" | "llm_classifier" | "heuristic_first_short_circuit" | "hybrid_short_circuit" | "classifier_plugin" | "classifier_fallback" | "default_model_fallback" | "literal_keyword_match" | "semantic_keyword_match" | "plan_mode" | "housekeeping" | "modality_escalation" | "modality_pin_override" | "health_failover" | "health_default_fallback" | "session_affinity_pin" | "session_affinity_escalation" | "user_turn_continuation" | "default_fallback" | "keyword" | "quality_tier" | "bandit";
++ cause?: "heuristic_scorer" | "heuristic_v2" | "reasoning_override" | "llm_classifier" | "capability_classifier" | "heuristic_first_short_circuit" | "hybrid_short_circuit" | "classifier_plugin" | "classifier_fallback" | "capability_classifier_fallback" | "default_model_fallback" | "literal_keyword_match" | "semantic_keyword_match" | "plan_mode" | "housekeeping" | "modality_escalation" | "modality_pin_override" | "health_failover" | "health_default_fallback" | "session_affinity_pin" | "session_affinity_escalation" | "user_turn_continuation" | "default_fallback" | "keyword" | "quality_tier" | "bandit";
++ /** Classifier Calibrated P Solve */
++ classifier_calibrated_p_solve?: number;
++ /** Classifier Calibration Version */
++ classifier_calibration_version?: string;
+ /** Classifier Capability Boundary */
+ classifier_capability_boundary?: string;
/** Classifier Cost */
classifier_cost?: number;
+ /** Classifier Crux */
+ classifier_crux?: string;
/** Classifier Model */
classifier_model?: string;
+ /** Classifier P Solve */
+ classifier_p_solve?: number;
+ /** Classifier Primary Rule */
+ classifier_primary_rule?: string;
+ /** Classifier Threshold */
+ classifier_threshold?: number;
/** Context Escalated */
context_escalated?: boolean;
/** Context Escalation Original Tier */