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): record why the auto-router picked a tier and show it in the logs (#35016)

tin-berri71dfab71772e
diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.py
index 83d6fcc0bee..c2dc7189934 100644
--- a/litellm/litellm_core_utils/litellm_logging.py
+++ b/litellm/litellm_core_utils/litellm_logging.py
@@ -4680,6 +4680,7 @@ class StandardLoggingPayloadSetup:
applied_guardrails=applied_guardrails,
mcp_tool_call_metadata=mcp_tool_call_metadata,
vector_store_request_metadata=vector_store_request_metadata,
+ routing_decision=None,
usage_object=usage_object,
requester_custom_headers=None,
cold_storage_object_key=None,
@@ -5519,6 +5520,7 @@ def get_standard_logging_metadata(
applied_guardrails=None,
mcp_tool_call_metadata=None,
vector_store_request_metadata=None,
+ routing_decision=None,
usage_object=None,
requester_custom_headers=None,
user_api_key_request_route=None,
diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.py
index c6d4ee1120a..bfdc954c9fe 100644
--- a/litellm/proxy/_types.py
+++ b/litellm/proxy/_types.py
@@ -53,6 +53,7 @@ from litellm.types.utils import (
StandardLoggingModelInformation,
StandardLoggingPayloadErrorInformation,
StandardLoggingPayloadStatus,
+ StandardLoggingRoutingDecision,
StandardLoggingVectorStoreRequest,
StandardPassThroughResponseObject,
TextCompletionResponse,
@@ -3311,6 +3312,7 @@ class SpendLogsMetadata(TypedDict):
applied_guardrails: Optional[List[str]]
mcp_tool_call_metadata: Optional[StandardLoggingMCPToolCall]
vector_store_request_metadata: Optional[List[StandardLoggingVectorStoreRequest]]
+ routing_decision: StandardLoggingRoutingDecision | None
guardrail_information: Optional[List[StandardLoggingGuardrailInformation]]
eval_information: Optional[Any]
status: StandardLoggingPayloadStatus
diff --git a/litellm/proxy/litellm_pre_call_utils.py b/litellm/proxy/litellm_pre_call_utils.py
index c40718e41fd..673e73f72fb 100644
--- a/litellm/proxy/litellm_pre_call_utils.py
+++ b/litellm/proxy/litellm_pre_call_utils.py
@@ -150,6 +150,7 @@ _UNTRUSTED_ROOT_CONTROL_FIELDS = (
"applied_guardrails",
"applied_policies",
"policy_sources",
+ "routing_decision",
"pillar_response_headers",
"_guardrail_pipelines",
"_pipeline_managed_guardrails",
@@ -197,6 +198,7 @@ _UNTRUSTED_METADATA_CONTROL_FIELDS = (
"applied_guardrails",
"applied_policies",
"policy_sources",
+ "routing_decision",
"standard_logging_object",
"proxy_server_request",
"secret_fields",
diff --git a/litellm/router.py b/litellm/router.py
index 0234a8f3424..ac00cdbc2b0 100644
--- a/litellm/router.py
+++ b/litellm/router.py
@@ -71,6 +71,7 @@ from litellm.litellm_core_utils.core_helpers import (
_get_parent_otel_span_from_kwargs,
coerce_token_limit,
get_metadata_variable_name_from_kwargs,
+ get_or_create_metadata_bucket,
)
from litellm.litellm_core_utils.coroutine_checker import coroutine_checker
from litellm.litellm_core_utils.credential_accessor import CredentialAccessor
@@ -210,8 +211,10 @@ from litellm.types.utils import (
from litellm.types.utils import ModelInfo
from litellm.types.utils import ModelInfo as ModelMapInfo
from litellm.types.utils import (
+ PROMPT_QUOTING_ROUTING_DECISION_FIELDS,
ModelResponseStream,
StandardLoggingPayload,
+ StandardLoggingRoutingDecision,
Usage,
)
from litellm.utils import (
@@ -11158,6 +11161,7 @@ class Router:
router_strategy = self._select_pre_routing_strategy(model=model, request_kwargs=request_kwargs)
if router_strategy is None:
+ self._record_routing_decision(request_kwargs=request_kwargs, routing_decision=None)
return None
pre_routing_hook_response = await router_strategy.async_pre_routing_hook(
@@ -11167,6 +11171,10 @@ class Router:
input=input,
specific_deployment=specific_deployment,
)
+ self._record_routing_decision(
+ request_kwargs=request_kwargs,
+ routing_decision=(pre_routing_hook_response.routing_decision if pre_routing_hook_response else None),
+ )
# `model` (the alias, e.g. "smart-router") is never the deployment actually
# called - apply the alias's own litellm_params (besides `model` itself,
@@ -11185,6 +11193,68 @@ class Router:
return pre_routing_hook_response
+ @staticmethod
+ def _record_routing_decision(
+ request_kwargs: dict,
+ routing_decision: StandardLoggingRoutingDecision | None,
+ ) -> None:
+ """Make the request's metadata describe THIS routing attempt, and only this one.
+
+ Fallbacks re-enter the hook with the same `request_kwargs`, so an attempt that
+ picks a plain model group after an auto-router group failed must clear the
+ earlier decision; leaving it would attribute the first router's tier and cause
+ to the deployment that actually served the request. Every attempt therefore
+ writes or clears, never just writes.
+ """
+ if routing_decision is None:
+ for bucket in (request_kwargs.get("metadata"), request_kwargs.get("litellm_metadata")):
+ if isinstance(bucket, dict):
+ bucket.pop("routing_decision", None)
+ return
+
+ # `get_or_create_metadata_bucket` is the single owner of "which dict holds
+ # proxy-internal metadata": it picks `litellm_metadata` when present (so the
+ # decision never lands in the `metadata` dict that routes like /v1/messages
+ # forward to the provider) and replaces a non-dict value rather than silently
+ # skipping the write.
+ _, metadata_bucket = get_or_create_metadata_bucket(request_kwargs)
+ metadata_bucket["routing_decision"] = Router._redact_prompt_text_if_needed(
+ request_kwargs=request_kwargs, routing_decision=routing_decision
+ )
+
+ @staticmethod
+ def _redact_prompt_text_if_needed(
+ request_kwargs: Mapping[str, Any],
+ routing_decision: StandardLoggingRoutingDecision,
+ ) -> StandardLoggingRoutingDecision:
+ """Drop verbatim prompt text from the record when message logging is redacted.
+
+ An operator who turns message logging off has said prompt content must not reach
+ the logs, so the fields that quote the prompt (the matched keywords, and the
+ signals that name them) are omitted. Derived values are kept, because a tier, a
+ cause, a score or an escalation flag aggregates the prompt rather than
+ reproducing any of it, and dropping them would leave the row unexplainable for
+ no privacy gain. Applied here rather than in each strategy so a strategy added
+ later cannot bypass it.
+ """
+ from litellm.litellm_core_utils.redact_messages import (
+ should_redact_message_logging,
+ )
+
+ if not should_redact_message_logging(
+ {
+ "litellm_params": request_kwargs,
+ "standard_callback_dynamic_params": request_kwargs.get("standard_callback_dynamic_params"),
+ }
+ ):
+ return routing_decision
+ kept = {
+ field: value
+ for field, value in routing_decision.items()
+ if field not in PROMPT_QUOTING_ROUTING_DECISION_FIELDS
+ }
+ return cast(StandardLoggingRoutingDecision, kept) # cast-ok: dropping optional keys preserves the type
+
def get_available_deployment(
self,
model: str,
diff --git a/litellm/router_strategy/adaptive_router/adaptive_router.py b/litellm/router_strategy/adaptive_router/adaptive_router.py
index ec84eb1decf..e8fcec2667d 100644
--- a/litellm/router_strategy/adaptive_router/adaptive_router.py
+++ b/litellm/router_strategy/adaptive_router/adaptive_router.py
@@ -23,6 +23,7 @@ from litellm._logging import verbose_router_logger
from litellm.litellm_core_utils.prompt_templates.common_utils import (
get_last_user_message,
)
+from litellm.types.utils import StandardLoggingRoutingDecision
from litellm.router_strategy.adaptive_router.bandit import (
BanditCell,
apply_delta,
@@ -193,7 +194,17 @@ class AdaptiveRouter:
if isinstance(kwargs_metadata, dict):
kwargs_metadata[ADAPTIVE_ROUTER_CHOSEN_MODEL_KEY] = chosen_model
- return PreRoutingHookResponse(model=chosen_model, messages=messages)
+ return PreRoutingHookResponse(
+ model=chosen_model,
+ messages=messages,
+ routing_decision=StandardLoggingRoutingDecision(
+ router_model_name=self.router_name,
+ router_type="adaptive",
+ routed_model=chosen_model,
+ cause="bandit",
+ request_type=request_type.value,
+ ),
+ )
# ---- Pick model ------------------------------------------------------
diff --git a/litellm/router_strategy/complexity_router/complexity_router.py b/litellm/router_strategy/complexity_router/complexity_router.py
index 1da8ee68c6e..933c6d170cf 100644
--- a/litellm/router_strategy/complexity_router/complexity_router.py
+++ b/litellm/router_strategy/complexity_router/complexity_router.py
@@ -19,7 +19,7 @@ import asyncio
import random
import re
from collections.abc import Mapping
-from typing import TYPE_CHECKING, Any, Literal, Union, cast
+from typing import TYPE_CHECKING, Any, Literal, NamedTuple, Union, cast
from pydantic import BaseModel
@@ -27,7 +27,12 @@ from litellm._logging import verbose_router_logger
from litellm.constants import RETURN_RAW_MODEL_NAME_METADATA_KEY
from litellm.integrations.custom_logger import CustomLogger
from litellm.llms.base_llm.base_utils import type_to_response_format_param
-from litellm.types.utils import ModelResponse
+from litellm.types.utils import (
+ ModelResponse,
+ RoutingDecisionCause,
+ StandardLoggingRoutingDecision,
+ StandardLoggingRoutingDecisionTierBoundaries,
+)
from .config import (
DEFAULT_CODE_KEYWORDS,
@@ -135,6 +140,27 @@ class DimensionScore:
self.signal = signal
+class KeywordOverride(NamedTuple):
+ """A keyword_tier_rules match: the winning tier and, on the lexical path, the keyword that fired."""
+
+ tier: ComplexityTier
+ matched_keyword: str | None
+
+
+class ClassificationOutcome(NamedTuple):
+ """What the classifier decided and which mechanism actually produced it.
+
+ `cause` reflects the path that ran, not the configured classifier_type: an LLM
+ classifier that fails falls back to the heuristic scorer and reports it.
+ `score` is None on the LLM path, which produces a tier label and no score.
+ """
+
+ tier: ComplexityTier
+ score: float | None
+ signals: tuple[str, ...]
+ cause: Literal["heuristic_scorer", "reasoning_override", "llm_classifier"]
+
+
class ComplexityRouter(CustomLogger):
"""
Complexity router that classifies requests and routes to appropriate models.
@@ -256,6 +282,7 @@ class ComplexityRouter(CustomLogger):
def _score_keyword_match(
self,
text: str,
+ disclosable_text: str,
keywords: list[str],
name: str,
signal_label: str,
@@ -264,6 +291,15 @@ class ComplexityRouter(CustomLogger):
) -> tuple[DimensionScore, int]:
"""Score based on keyword matches using word boundary matching.
+ Scoring reads `text`, which for most dimensions includes the system prompt.
+ The signal names only the terms that also appear in `disclosable_text`, the
+ caller's own message: signals are persisted to the request's spend log, which
+ the caller can read, so naming a term matched solely in the system prompt would
+ let a caller recover configured terms from a prompt it cannot see. Terms it did
+ not supply are reported as a count instead, which explains the score without
+ disclosing anything. `disclosable_text` is required rather than defaulted so a
+ future dimension has to state which text it is willing to quote.
+
Returns:
Tuple of (DimensionScore, match_count) so callers can reuse the count.
"""
@@ -272,18 +308,13 @@ class ComplexityRouter(CustomLogger):
matches = [kw for kw in keywords if self._keyword_matches(text, kw)]
match_count = len(matches)
+ if match_count < low_threshold:
+ return DimensionScore(name, score_none, None), match_count
- if match_count >= high_threshold:
- return (
- DimensionScore(name, score_high, f"{signal_label} ({', '.join(matches[:3])})"),
- match_count,
- )
- if match_count >= low_threshold:
- return (
- DimensionScore(name, score_low, f"{signal_label} ({', '.join(matches[:3])})"),
- match_count,
- )
- return DimensionScore(name, score_none, None), match_count
+ disclosable = [kw for kw in matches if self._keyword_matches(disclosable_text, kw)]
+ detail = ", ".join(disclosable[:3]) if disclosable else f"{match_count} matches"
+ score = score_high if match_count >= high_threshold else score_low
+ return DimensionScore(name, score, f"{signal_label} ({detail})"), match_count
def _score_multi_step(self, text: str) -> DimensionScore:
"""Score based on multi-step patterns."""
@@ -300,8 +331,19 @@ class ComplexityRouter(CustomLogger):
return DimensionScore("questionComplexity", 0, None)
def classify(self, prompt: str, system_prompt: str | None = None) -> tuple[ComplexityTier, float, list[str]]:
+ """Classify a prompt by complexity, discarding which rule decided the tier.
+
+ Kept for callers that only need the tier and score; `_score_and_classify` is the
+ single computation behind both, so the two can never disagree.
"""
- Classify a prompt by complexity.
+ tier, score, signals, _cause = self._score_and_classify(prompt, system_prompt)
+ return tier, score, list(signals)
+
+ def _score_and_classify(
+ self, prompt: str, system_prompt: str | None = None
+ ) -> tuple[ComplexityTier, float, tuple[str, ...], Literal["heuristic_scorer", "reasoning_override"]]:
+ """
+ Classify a prompt by complexity, reporting whether the score chose the tier.
Args:
prompt: The user's prompt/message.
@@ -327,6 +369,7 @@ class ComplexityRouter(CustomLogger):
# Score all dimensions, capturing match counts where needed
code_score, _ = self._score_keyword_match(
full_text,
+ user_text,
self.code_keywords,
"codePresence",
"code",
@@ -334,6 +377,7 @@ class ComplexityRouter(CustomLogger):
(0, 0.5, 1.0),
)
reasoning_score, reasoning_match_count = self._score_keyword_match(
+ user_text,
user_text,
self.reasoning_keywords,
"reasoningMarkers",
@@ -343,6 +387,7 @@ class ComplexityRouter(CustomLogger):
)
technical_score, _ = self._score_keyword_match(
full_text,
+ user_text,
self.technical_keywords,
"technicalTerms",
"technical",
@@ -351,6 +396,7 @@ class ComplexityRouter(CustomLogger):
)
simple_score, _ = self._score_keyword_match(
full_text,
+ user_text,
self.simple_keywords,
"simpleIndicators",
"simple",
@@ -378,48 +424,112 @@ class ComplexityRouter(CustomLogger):
# Check for reasoning override (2+ reasoning markers)
# Reuse match count from _score_keyword_match to avoid scanning twice
if reasoning_match_count >= 2:
- return ComplexityTier.REASONING, weighted_score, signals
+ return ComplexityTier.REASONING, weighted_score, tuple(signals), "reasoning_override"
# Map score to tier
- boundaries = self.config.tier_boundaries
- simple_medium = boundaries.get("simple_medium", 0.15)
- medium_complex = boundaries.get("medium_complex", 0.35)
- complex_reasoning = boundaries.get("complex_reasoning", 0.60)
-
- if weighted_score < simple_medium:
+ boundaries = self._effective_tier_boundaries()
+ if weighted_score < boundaries["simple_medium"]:
tier = ComplexityTier.SIMPLE
- elif weighted_score < medium_complex:
+ elif weighted_score < boundaries["medium_complex"]:
tier = ComplexityTier.MEDIUM
- elif weighted_score < complex_reasoning:
+ elif weighted_score < boundaries["complex_reasoning"]:
tier = ComplexityTier.COMPLEX
else:
tier = ComplexityTier.REASONING
- return tier, weighted_score, signals
+ return tier, weighted_score, tuple(signals), "heuristic_scorer"
+
+ def _effective_tier_boundaries(self) -> StandardLoggingRoutingDecisionTierBoundaries:
+ """The tier boundaries in effect, with the documented defaults filled in.
+
+ Shared by score-to-tier mapping and the per-request routing decision snapshot,
+ so a logged decision always reflects the boundaries that actually applied.
+ """
+ boundaries = self.config.tier_boundaries
+ return StandardLoggingRoutingDecisionTierBoundaries(
+ simple_medium=boundaries.get("simple_medium", 0.15),
+ medium_complex=boundaries.get("medium_complex", 0.35),
+ complex_reasoning=boundaries.get("complex_reasoning", 0.60),
+ )
+
+ def _build_routing_decision(
+ self,
+ *,
+ routed_model: str,
+ cause: RoutingDecisionCause,
+ tier: ComplexityTier | None = None,
+ score: float | None = None,
+ signals: tuple[str, ...] | None = None,
+ matched_keyword: str | None = None,
+ escalation_keyword: str | None = None,
+ escalated: bool = False,
+ classifier_model: str | None = None,
+ ) -> StandardLoggingRoutingDecision:
+ """Assemble the per-request provenance record for this router's decision.
+
+ Optional facts are omitted rather than set to None, so a spend log row only
+ carries the keys that applied to its path. `tier_boundaries` rides with
+ `score` because the score is only interpretable against the boundaries that
+ mapped it to a tier.
+ """
+ decision = StandardLoggingRoutingDecision(
+ router_model_name=self.model_name,
+ router_type="complexity",
+ routed_model=routed_model,
+ cause=cause,
+ )
+ if tier is not None:
+ decision["tier"] = tier.value
+ if score is not None:
+ decision["score"] = score
+ decision["tier_boundaries"] = self._effective_tier_boundaries()
+ if signals:
+ # Stored as a list because this record is serialized to JSON for the spend
+ # log and read back as an array by the dashboard; a sequence type that only
+ # happens to survive the serializer would make the wire shape depend on it.
+ decision["signals"] = list(signals)
+ if matched_keyword is not None:
+ decision["matched_keyword"] = matched_keyword
+ if escalation_keyword is not None:
+ # Two separate facts: the caller asked to escalate, and whether the tier
+ # actually moved. A request that escalates from an already-highest tier has
+ # nowhere to go, so it records the keyword with escalated=False rather than
+ # dropping the ask (which reads as an ordinary route) or claiming a bump
+ # that never happened. Every path reports both the same way.
+ decision["escalation_keyword"] = escalation_keyword
+ decision["escalated"] = escalated
+ if classifier_model is not None:
+ decision["classifier_model"] = classifier_model
+ return decision
async def aclassify(
self,
prompt: str,
system_prompt: str | None = None,
request_kwargs: dict[str, Any] | None = None,
- ) -> tuple[ComplexityTier, float, list[str]]:
+ ) -> ClassificationOutcome:
"""
Classify a prompt by complexity, using the LLM classifier when configured.
Falls back to the local heuristic scorer if classifier_type is "heuristic",
or if the LLM call fails, times out, or returns an unparseable response.
+ The outcome's `cause` reports which path actually classified the request.
"""
if self.config.classifier_type != "llm" or self.config.classifier_llm_config is None:
- return self.classify(prompt, system_prompt)
+ tier, score, signals, cause = self._score_and_classify(prompt, system_prompt)
+ return ClassificationOutcome(tier=tier, score=score, signals=signals, cause=cause)
try:
tier = await self._classify_with_llm(prompt, system_prompt, request_kwargs)
- return tier, 1.0, [f"llm-classifier:{tier.value}"]
+ return ClassificationOutcome(
+ tier=tier, score=None, signals=(f"llm-classifier:{tier.value}",), cause="llm_classifier"
+ )
except Exception as e: # noqa: BLE001 -- external LLM call can fail in many distinct ways (timeout, provider error, validation, parse error); any failure must fall back to the heuristic scorer
verbose_router_logger.warning(
f"ComplexityRouter: LLM classifier failed ({e}), falling back to heuristic scoring"
)
- return self.classify(prompt, system_prompt)
+ tier, score, signals, cause = self._score_and_classify(prompt, system_prompt)
+ return ClassificationOutcome(tier=tier, score=score, signals=signals, cause=cause)
async def _classify_with_llm(
self,
@@ -699,16 +809,16 @@ class ComplexityRouter(CustomLogger):
}
return best_model
- def _escalation_triggered(self, user_message: str) -> bool:
- """Whether the prompt asks to escalate to a stronger model.
+ def _matched_escalation_keyword(self, user_message: str) -> str | None:
+ """The escalation keyword the prompt contains, or None when escalation is off.
Matching is a case-sensitive substring test so the default "LITELLM ESCALATE"
only fires on the deliberate, shouted form and not on incidental lowercase
mentions of the word (e.g. "how do I escalate this ticket").
"""
if not self.escalation_keywords:
- return False
- return any(keyword in user_message for keyword in self.escalation_keywords)
+ return None
+ return next((keyword for keyword in self.escalation_keywords if keyword in user_message), None)
def _tier_for_model(self, model: str) -> ComplexityTier | None:
"""Return the most-severe configured tier whose pool contains this model."""
@@ -746,7 +856,7 @@ class ComplexityRouter(CustomLogger):
return pinned_model
return self.get_model_for_tier(escalated_tier)
- def _lexical_tier_override(self, user_message: str) -> ComplexityTier | None:
+ def _lexical_tier_override(self, user_message: str) -> KeywordOverride | None:
"""When keyword_tier_rules match literally, the most-severe matched tier wins.
Escalating to the highest tier (rather than the first rule in the list) keeps
@@ -757,12 +867,15 @@ class ComplexityRouter(CustomLogger):
if not rules:
return None
text = user_message.lower()
- matched_tiers = [
- rule.tier for rule in rules if any(self._keyword_matches(text, keyword) for keyword in rule.keywords)
+ matches = [
+ KeywordOverride(tier=rule.tier, matched_keyword=matched_keyword)
+ for rule in rules
+ if (matched_keyword := next((kw for kw in rule.keywords if self._keyword_matches(text, kw)), None))
+ is not None
]
- if not matched_tiers:
+ if not matches:
return None
- return max(matched_tiers, key=TIER_SEVERITY_ORDER.index)
+ return max(matches, key=lambda match: TIER_SEVERITY_ORDER.index(match.tier))
def _get_or_create_semantic_routelayer(self) -> SemanticRouter:
"""Build (once) a SemanticRouter with one route per tier, utterances = that tier's keywords."""
@@ -867,7 +980,7 @@ class ComplexityRouter(CustomLogger):
except ValueError:
return None
- async def _resolve_keyword_tier_override(self, user_message: str, request_kwargs: dict) -> ComplexityTier | None:
+ async def _resolve_keyword_tier_override(self, user_message: str, request_kwargs: dict) -> KeywordOverride | None:
"""Resolve a keyword_tier_rule override, semantically or lexically per config.
Returns None (no override -> fall through to the scorer) not only when no rule
@@ -879,12 +992,17 @@ class ComplexityRouter(CustomLogger):
if not self.config.semantic_keyword_matching:
return self._lexical_tier_override(user_message)
try:
- return await self._semantic_tier_override(user_message, request_kwargs)
+ semantic_tier = await self._semantic_tier_override(user_message, request_kwargs)
except Exception as e: # noqa: BLE001 -- embedding call can fail many ways (timeout, provider/network/parse error); any failure must fall back to scoring, never fail the request
verbose_router_logger.warning(
f"ComplexityRouter: semantic keyword matching failed ({e}), falling back to complexity scoring"
)
return None
+ if semantic_tier is None:
+ return None
+ # A semantic match is a similarity hit against the rule's utterances, not a
+ # literal keyword, so there is no single matched keyword to report.
+ return KeywordOverride(tier=semantic_tier, matched_keyword=None)
def _resolve_messages(
self,
@@ -1003,6 +1121,7 @@ class ComplexityRouter(CustomLogger):
pinned_model = await self.litellm_router_instance.cache.async_get_cache(key=cache_key)
if isinstance(pinned_model, str):
routed_model: str | None = pinned_model
+ pin_escalation_keyword: str | None = None
if self.escalation_keywords:
resolved_messages = self._resolve_messages(messages, request_kwargs)
user_message = (
@@ -1010,7 +1129,9 @@ class ComplexityRouter(CustomLogger):
if resolved_messages
else None
)
- if user_message is not None and self._escalation_triggered(user_message):
+ if user_message is not None:
+ pin_escalation_keyword = self._matched_escalation_keyword(user_message)
+ if pin_escalation_keyword is not None:
routed_model = self._escalated_pin(pinned_model)
if routed_model is not None:
# Refresh the TTL on every hit so an active session doesn't lose its
@@ -1028,7 +1149,8 @@ class ComplexityRouter(CustomLogger):
kwargs_metadata = request_kwargs.setdefault("metadata", {})
if isinstance(kwargs_metadata, dict):
kwargs_metadata[ADAPTIVE_ROUTER_CHOSEN_MODEL_KEY] = routed_model
- cause = "session_affinity_escalation" if routed_model != pinned_model else "session_affinity_pin"
+ escalated = routed_model != pinned_model
+ cause: RoutingDecisionCause = "session_affinity_escalation" if escalated else "session_affinity_pin"
verbose_router_logger.info(
f"ComplexityRouter: routing decision cause={cause}, routed_model={routed_model}"
)
@@ -1036,6 +1158,12 @@ class ComplexityRouter(CustomLogger):
return PreRoutingHookResponse(
model=routed_model,
messages=messages if has_original_messages else None,
+ routing_decision=self._build_routing_decision(
+ routed_model=routed_model,
+ cause=cause,
+ escalation_keyword=pin_escalation_keyword,
+ escalated=escalated,
+ ),
)
response = await self._classify_and_route(
@@ -1106,29 +1234,45 @@ class ComplexityRouter(CustomLogger):
return PreRoutingHookResponse(
model=routed_model,
messages=messages if has_original_messages else None,
+ routing_decision=self._build_routing_decision(routed_model=routed_model, cause="default_fallback"),
)
- escalate = self._escalation_triggered(user_message)
+ escalation_keyword = self._matched_escalation_keyword(user_message)
- override_tier = await self._resolve_keyword_tier_override(user_message, request_kwargs)
- if override_tier is not None:
- routed_tier = self._escalate_tier(override_tier) if escalate else override_tier
+ override = await self._resolve_keyword_tier_override(user_message, request_kwargs)
+ if override is not None:
+ routed_tier = self._escalate_tier(override.tier) if escalation_keyword is not None else override.tier
+ keyword_escalated = routed_tier != override.tier
routed_model = await self._pick_model_for_tier(routed_tier, messages, resolved_messages, request_kwargs)
- base_cause = "semantic_keyword_match" if self.config.semantic_keyword_matching else "literal_keyword_match"
- cause = f"{base_cause}+escalation" if escalate else base_cause
+ keyword_cause: RoutingDecisionCause = (
+ "semantic_keyword_match" if self.config.semantic_keyword_matching else "literal_keyword_match"
+ )
verbose_router_logger.info(
- f"ComplexityRouter: routing decision cause={cause}, "
+ f"ComplexityRouter: routing decision cause={keyword_cause}, escalated={keyword_escalated}, "
f"tier={routed_tier.value}, routed_model={routed_model}"
)
return PreRoutingHookResponse(
model=routed_model,
messages=messages if has_original_messages else None,
+ routing_decision=self._build_routing_decision(
+ routed_model=routed_model,
+ cause=keyword_cause,
+ tier=routed_tier,
+ matched_keyword=override.matched_keyword,
+ escalation_keyword=escalation_keyword,
+ escalated=keyword_escalated,
+ ),
)
- tier, score, signals = await self.aclassify(user_message, system_prompt, request_kwargs)
- if escalate:
+ outcome = await self.aclassify(user_message, system_prompt, request_kwargs)
+ tier, score, signals = outcome.tier, outcome.score, outcome.signals
+ classified_tier = tier
+ if escalation_keyword is not None:
tier = self._escalate_tier(tier)
- signals = [*signals, "escalation"]
+ escalated = tier != classified_tier
+ if escalated:
+ signals = (*signals, "escalation")
+ score_repr = f"{score:.3f}" if score is not None else "n/a"
if self.config.adaptive:
routed_model = self._soft_floor_pick(tier, user_message, request_kwargs)
adaptive = self._ensure_adaptive_router()
@@ -1138,18 +1282,33 @@ class ComplexityRouter(CustomLogger):
chosen_key = getattr(self, "_adaptive_chosen_model_key", "adaptive_router_chosen_model")
kwargs_metadata[chosen_key] = routed_model
verbose_router_logger.info(
- f"ComplexityRouter[adaptive]: routing decision cause=complexity_scorer, "
- f"tier={tier.value}, score={score:.3f}, "
+ f"ComplexityRouter[adaptive]: routing decision cause={outcome.cause}, "
+ f"tier={tier.value}, score={score_repr}, "
f"signals={signals}, routed_model={routed_model}"
)
else:
routed_model = await self._pick_model_for_tier(tier, messages, resolved_messages, request_kwargs)
verbose_router_logger.info(
- f"ComplexityRouter: routing decision cause=complexity_scorer, tier={tier.value}, "
- f"score={score:.3f}, signals={signals}, routed_model={routed_model}"
+ f"ComplexityRouter: routing decision cause={outcome.cause}, tier={tier.value}, "
+ f"score={score_repr}, signals={signals}, routed_model={routed_model}"
)
+ classifier_model = (
+ self.config.classifier_llm_config.model
+ if outcome.cause == "llm_classifier" and self.config.classifier_llm_config is not None
+ else None
+ )
return PreRoutingHookResponse(
model=routed_model,
messages=messages if has_original_messages else None,
+ routing_decision=self._build_routing_decision(
+ routed_model=routed_model,
+ cause=outcome.cause,
+ tier=tier,
+ score=score,
+ signals=signals,
+ escalation_keyword=escalation_keyword,
+ escalated=escalated,
+ classifier_model=classifier_model,
+ ),
)
diff --git a/litellm/router_strategy/quality_router/quality_router.py b/litellm/router_strategy/quality_router/quality_router.py
index 15c26f2c278..fd4a91d76bd 100644
--- a/litellm/router_strategy/quality_router/quality_router.py
+++ b/litellm/router_strategy/quality_router/quality_router.py
@@ -23,6 +23,7 @@ from litellm.integrations.custom_logger import CustomLogger
from litellm.router_strategy.complexity_router.complexity_router import (
ComplexityRouter,
)
+from litellm.types.utils import StandardLoggingRoutingDecision
from .config import QualityRouterConfig, RoutingPreferences
@@ -357,6 +358,12 @@ class QualityRouter(CustomLogger):
return PreRoutingHookResponse(
model=self.config.default_model,
messages=messages,
+ routing_decision=StandardLoggingRoutingDecision(
+ router_model_name=self.model_name,
+ router_type="quality",
+ routed_model=self.config.default_model,
+ cause="default_fallback",
+ ),
)
# Try keyword override first — it short-circuits complexity classification.
@@ -380,9 +387,20 @@ class QualityRouter(CustomLogger):
"complexity_tier": None,
},
)
+ routing_decision = StandardLoggingRoutingDecision(
+ router_model_name=self.model_name,
+ router_type="quality",
+ routed_model=routed_model,
+ cause="keyword",
+ matched_keyword=matched_keyword,
+ )
+ keyword_quality_tier = self._model_quality.get(routed_model)
+ if keyword_quality_tier is not None:
+ routing_decision["tier"] = str(keyword_quality_tier)
return PreRoutingHookResponse(
model=routed_model,
messages=messages,
+ routing_decision=routing_decision,
)
# No keyword match → complexity classification flow.
@@ -419,4 +437,13 @@ class QualityRouter(CustomLogger):
return PreRoutingHookResponse(
model=routed_model,
messages=messages,
+ routing_decision=StandardLoggingRoutingDecision(
+ router_model_name=self.model_name,
+ router_type="quality",
+ routed_model=routed_model,
+ cause="quality_tier",
+ tier=str(int(quality_tier)),
+ score=score,
+ signals=list(signals),
+ ),
)
diff --git a/litellm/types/router.py b/litellm/types/router.py
index 28e4a8272e8..837a93367a2 100644
--- a/litellm/types/router.py
+++ b/litellm/types/router.py
@@ -28,7 +28,7 @@ from .completion import CompletionRequest
from .embedding import EmbeddingRequest
from .llms.openai import OpenAIFileObject
from .search import SearchProvider
-from .utils import CustomPricingLiteLLMParams, ModelResponse
+from .utils import CustomPricingLiteLLMParams, ModelResponse, StandardLoggingRoutingDecision
class ConfigurableClientsideParamsCustomAuth(TypedDict):
@@ -839,6 +839,7 @@ class PreRoutingHookResponse(BaseModel):
model: str
messages: Optional[List[Dict[str, Any]]]
+ routing_decision: StandardLoggingRoutingDecision | None = None
_PreRoutingStrategyT_co = TypeVar("_PreRoutingStrategyT_co", covariant=True)
diff --git a/litellm/types/utils.py b/litellm/types/utils.py
index e4dfac48141..9df44c6202c 100644
--- a/litellm/types/utils.py
+++ b/litellm/types/utils.py
@@ -10,6 +10,7 @@ from typing import (
Literal,
Mapping,
Optional,
+ Sequence,
Union,
get_args,
)
@@ -2674,6 +2675,73 @@ class StandardLoggingPromptManagementMetadata(TypedDict):
prompt_integration: str
+class StandardLoggingRoutingDecisionTierBoundaries(TypedDict):
+ """Snapshot of the complexity scorer's tier boundaries at decision time, so a
+ historical spend log row stays explainable after the router config changes."""
+
+ simple_medium: float
+ medium_complex: float
+ complex_reasoning: float
+
+
+RoutingDecisionCause = Literal[
+ "heuristic_scorer",
+ # The scorer found 2+ reasoning markers and forced REASONING regardless of score.
+ # A distinct cause rather than a marker inside `signals`, because it is the fact
+ # that tells a reader the score did NOT choose the tier; encoding it as free text
+ # meant anything that filtered `signals` silently changed what the row claimed.
+ "reasoning_override",
+ "llm_classifier",
+ "literal_keyword_match",
+ "semantic_keyword_match",
+ "session_affinity_pin",
+ "session_affinity_escalation",
+ "default_fallback",
+ "keyword",
+ "quality_tier",
+ "bandit",
+]
+
+
+class StandardLoggingRoutingDecision(TypedDict, total=False):
+ """Per-request provenance for a pre-routing strategy (auto-router) decision."""
+
+ router_model_name: str
+ router_type: Literal["complexity", "adaptive", "quality"]
+ routed_model: str
+ cause: RoutingDecisionCause
+ tier: str
+ request_type: str
+ score: float
+ signals: Sequence[str]
+ matched_keyword: str
+ escalation_keyword: str
+ classifier_model: str
+ escalated: bool
+ tier_boundaries: StandardLoggingRoutingDecisionTierBoundaries
+
+
+# Fields whose values quote the caller's prompt. Dropped when an operator turns message
+# logging off. Every other field aggregates the prompt without reproducing it and is kept,
+# so a redacted row stays explainable. `test_every_routing_decision_field_is_classified`
+# fails if a field is added to the record without being placed in one set or the other.
+PROMPT_QUOTING_ROUTING_DECISION_FIELDS: FrozenSet[str] = frozenset({"signals", "matched_keyword", "escalation_keyword"})
+DERIVED_ROUTING_DECISION_FIELDS: FrozenSet[str] = frozenset(
+ {
+ "router_model_name",
+ "router_type",
+ "routed_model",
+ "cause",
+ "tier",
+ "request_type",
+ "score",
+ "classifier_model",
+ "escalated",
+ "tier_boundaries",
+ }
+)
+
+
class StandardLoggingMetadata(StandardLoggingUserAPIKeyMetadata):
"""
Specific metadata k,v pairs logged to integration for easier cost tracking and prompt management
@@ -2687,6 +2755,7 @@ class StandardLoggingMetadata(StandardLoggingUserAPIKeyMetadata):
prompt_management_metadata: Optional[StandardLoggingPromptManagementMetadata]
mcp_tool_call_metadata: Optional[StandardLoggingMCPToolCall]
vector_store_request_metadata: Optional[List[StandardLoggingVectorStoreRequest]]
+ routing_decision: StandardLoggingRoutingDecision | None
applied_guardrails: Optional[List[str]]
usage_object: Optional[dict]
cold_storage_object_key: Optional[str] # S3/GCS object key for cold storage retrieval
diff --git a/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py b/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py
index 71206687b5c..795a99ec266 100644
--- a/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py
+++ b/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py
@@ -2396,7 +2396,7 @@ class TestSpendLogsPayload:
"model": "gpt-4o",
"user": "",
"team_id": "",
- "metadata": '{"applied_guardrails": [], "batch_models": null, "mcp_tool_call_metadata": null, "vector_store_request_metadata": null, "guardrail_information": null, "compression_savings": null, "usage_object": {"completion_tokens": 20, "prompt_tokens": 10, "total_tokens": 30, "completion_tokens_details": null, "prompt_tokens_details": null}, "model_map_information": {"model_map_key": "gpt-4o", "model_map_value": {"key": "gpt-4o", "max_tokens": 16384, "max_input_tokens": 128000, "max_output_tokens": 16384, "input_cost_per_token": 2.5e-06, "cache_creation_input_token_cost": null, "cache_read_input_token_cost": 1.25e-06, "input_cost_per_character": null, "input_cost_per_token_above_128k_tokens": null, "input_cost_per_token_above_200k_tokens": null, "input_cost_per_query": null, "input_cost_per_second": null, "input_cost_per_audio_token": null, "input_cost_per_token_batches": 1.25e-06, "output_cost_per_token_batches": 5e-06, "output_cost_per_token": 1e-05, "output_cost_per_audio_token": null, "output_cost_per_character": null, "output_cost_per_token_above_128k_tokens": null, "output_cost_per_character_above_128k_tokens": null, "output_cost_per_token_above_200k_tokens": null, "output_cost_per_second": null, "output_cost_per_reasoning_token": null, "output_cost_per_image": null, "output_vector_size": null, "litellm_provider": "openai", "mode": "chat", "supports_system_messages": true, "supports_response_schema": true, "supports_vision": true, "supports_function_calling": true, "supports_tool_choice": true, "supports_assistant_prefill": false, "supports_prompt_caching": true, "supports_audio_input": false, "supports_audio_output": false, "supports_pdf_input": false, "supports_embedding_image_input": false, "supports_native_streaming": null, "supports_web_search": true, "supports_reasoning": false, "search_context_cost_per_query": {"search_context_size_low": 0.03, "search_context_size_medium": 0.035, "search_context_size_high": 0.05}, "tpm": null, "rpm": null, "supported_openai_params": ["frequency_penalty", "logit_bias", "logprobs", "top_logprobs", "max_tokens", "max_completion_tokens", "modalities", "prediction", "n", "presence_penalty", "seed", "stop", "stream", "stream_options", "temperature", "top_p", "tools", "tool_choice", "function_call", "functions", "max_retries", "extra_headers", "parallel_tool_calls", "audio", "response_format", "user"]}}, "additional_usage_values": {"completion_tokens_details": null, "prompt_tokens_details": null}}',
+ "metadata": '{"applied_guardrails": [], "batch_models": null, "mcp_tool_call_metadata": null, "vector_store_request_metadata": null, "routing_decision": null, "guardrail_information": null, "compression_savings": null, "usage_object": {"completion_tokens": 20, "prompt_tokens": 10, "total_tokens": 30, "completion_tokens_details": null, "prompt_tokens_details": null}, "model_map_information": {"model_map_key": "gpt-4o", "model_map_value": {"key": "gpt-4o", "max_tokens": 16384, "max_input_tokens": 128000, "max_output_tokens": 16384, "input_cost_per_token": 2.5e-06, "cache_creation_input_token_cost": null, "cache_read_input_token_cost": 1.25e-06, "input_cost_per_character": null, "input_cost_per_token_above_128k_tokens": null, "input_cost_per_token_above_200k_tokens": null, "input_cost_per_query": null, "input_cost_per_second": null, "input_cost_per_audio_token": null, "input_cost_per_token_batches": 1.25e-06, "output_cost_per_token_batches": 5e-06, "output_cost_per_token": 1e-05, "output_cost_per_audio_token": null, "output_cost_per_character": null, "output_cost_per_token_above_128k_tokens": null, "output_cost_per_character_above_128k_tokens": null, "output_cost_per_token_above_200k_tokens": null, "output_cost_per_second": null, "output_cost_per_reasoning_token": null, "output_cost_per_image": null, "output_vector_size": null, "litellm_provider": "openai", "mode": "chat", "supports_system_messages": true, "supports_response_schema": true, "supports_vision": true, "supports_function_calling": true, "supports_tool_choice": true, "supports_assistant_prefill": false, "supports_prompt_caching": true, "supports_audio_input": false, "supports_audio_output": false, "supports_pdf_input": false, "supports_embedding_image_input": false, "supports_native_streaming": null, "supports_web_search": true, "supports_reasoning": false, "search_context_cost_per_query": {"search_context_size_low": 0.03, "search_context_size_medium": 0.035, "search_context_size_high": 0.05}, "tpm": null, "rpm": null, "supported_openai_params": ["frequency_penalty", "logit_bias", "logprobs", "top_logprobs", "max_tokens", "max_completion_tokens", "modalities", "prediction", "n", "presence_penalty", "seed", "stop", "stream", "stream_options", "temperature", "top_p", "tools", "tool_choice", "function_call", "functions", "max_retries", "extra_headers", "parallel_tool_calls", "audio", "response_format", "user"]}}, "additional_usage_values": {"completion_tokens_details": null, "prompt_tokens_details": null}}',
"cache_key": "Cache OFF",
"spend": 0.00022500000000000002,
"total_tokens": 30,
@@ -2492,7 +2492,7 @@ class TestSpendLogsPayload:
"model": "claude-4-sonnet-20250514",
"user": "",
"team_id": "",
- "metadata": '{"applied_guardrails": [], "batch_models": null, "mcp_tool_call_metadata": null, "vector_store_request_metadata": null, "guardrail_information": null, "compression_savings": null, "usage_object": {"completion_tokens": 503, "prompt_tokens": 2095, "total_tokens": 2598, "completion_tokens_details": null, "prompt_tokens_details": {"audio_tokens": null, "cached_tokens": 0}, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0}, "model_map_information": {"model_map_key": "claude-4-sonnet-20250514", "model_map_value": {"key": "claude-4-sonnet-20250514", "max_tokens": 128000, "max_input_tokens": 200000, "max_output_tokens": 128000, "input_cost_per_token": 3e-06, "cache_creation_input_token_cost": 3.75e-06, "cache_read_input_token_cost": 3e-07, "input_cost_per_character": null, "input_cost_per_token_above_128k_tokens": null, "input_cost_per_token_above_200k_tokens": null, "input_cost_per_query": null, "input_cost_per_second": null, "input_cost_per_audio_token": null, "input_cost_per_token_batches": null, "output_cost_per_token_batches": null, "output_cost_per_token": 1.5e-05, "output_cost_per_audio_token": null, "output_cost_per_character": null, "output_cost_per_token_above_128k_tokens": null, "output_cost_per_character_above_128k_tokens": null, "output_cost_per_token_above_200k_tokens": null, "output_cost_per_second": null, "output_cost_per_image": null, "output_vector_size": null, "litellm_provider": "anthropic", "mode": "chat", "supports_system_messages": null, "supports_response_schema": true, "supports_vision": true, "supports_function_calling": true, "supports_tool_choice": true, "supports_assistant_prefill": true, "supports_prompt_caching": true, "supports_audio_input": false, "supports_audio_output": false, "supports_pdf_input": true, "supports_embedding_image_input": false, "supports_native_streaming": null, "supports_web_search": false, "supports_reasoning": true, "search_context_cost_per_query": null, "tpm": null, "rpm": null, "supported_openai_params": ["stream", "stop", "temperature", "top_p", "max_tokens", "max_completion_tokens", "tools", "tool_choice", "extra_headers", "parallel_tool_calls", "response_format", "user", "reasoning_effort", "thinking"]}}, "additional_usage_values": {"completion_tokens_details": {"accepted_prediction_tokens": null, "audio_tokens": null, "reasoning_tokens": null, "rejected_prediction_tokens": null, "text_tokens": 503, "image_tokens": null}, "prompt_tokens_details": {"audio_tokens": null, "cached_tokens": 0, "text_tokens": null, "image_tokens": null}, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0}}',
+ "metadata": '{"applied_guardrails": [], "batch_models": null, "mcp_tool_call_metadata": null, "vector_store_request_metadata": null, "routing_decision": null, "guardrail_information": null, "compression_savings": null, "usage_object": {"completion_tokens": 503, "prompt_tokens": 2095, "total_tokens": 2598, "completion_tokens_details": null, "prompt_tokens_details": {"audio_tokens": null, "cached_tokens": 0}, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0}, "model_map_information": {"model_map_key": "claude-4-sonnet-20250514", "model_map_value": {"key": "claude-4-sonnet-20250514", "max_tokens": 128000, "max_input_tokens": 200000, "max_output_tokens": 128000, "input_cost_per_token": 3e-06, "cache_creation_input_token_cost": 3.75e-06, "cache_read_input_token_cost": 3e-07, "input_cost_per_character": null, "input_cost_per_token_above_128k_tokens": null, "input_cost_per_token_above_200k_tokens": null, "input_cost_per_query": null, "input_cost_per_second": null, "input_cost_per_audio_token": null, "input_cost_per_token_batches": null, "output_cost_per_token_batches": null, "output_cost_per_token": 1.5e-05, "output_cost_per_audio_token": null, "output_cost_per_character": null, "output_cost_per_token_above_128k_tokens": null, "output_cost_per_character_above_128k_tokens": null, "output_cost_per_token_above_200k_tokens": null, "output_cost_per_second": null, "output_cost_per_image": null, "output_vector_size": null, "litellm_provider": "anthropic", "mode": "chat", "supports_system_messages": null, "supports_response_schema": true, "supports_vision": true, "supports_function_calling": true, "supports_tool_choice": true, "supports_assistant_prefill": true, "supports_prompt_caching": true, "supports_audio_input": false, "supports_audio_output": false, "supports_pdf_input": true, "supports_embedding_image_input": false, "supports_native_streaming": null, "supports_web_search": false, "supports_reasoning": true, "search_context_cost_per_query": null, "tpm": null, "rpm": null, "supported_openai_params": ["stream", "stop", "temperature", "top_p", "max_tokens", "max_completion_tokens", "tools", "tool_choice", "extra_headers", "parallel_tool_calls", "response_format", "user", "reasoning_effort", "thinking"]}}, "additional_usage_values": {"completion_tokens_details": {"accepted_prediction_tokens": null, "audio_tokens": null, "reasoning_tokens": null, "rejected_prediction_tokens": null, "text_tokens": 503, "image_tokens": null}, "prompt_tokens_details": {"audio_tokens": null, "cached_tokens": 0, "text_tokens": null, "image_tokens": null}, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0}}',
"cache_key": "Cache OFF",
"spend": 0.01383,
"total_tokens": 2598,
@@ -2586,7 +2586,7 @@ class TestSpendLogsPayload:
"model": "claude-4-sonnet-20250514",
"user": "",
"team_id": "",
- "metadata": '{"applied_guardrails": [], "batch_models": null, "mcp_tool_call_metadata": null, "vector_store_request_metadata": null, "guardrail_information": null, "compression_savings": null, "usage_object": {"completion_tokens": 503, "prompt_tokens": 2095, "total_tokens": 2598, "completion_tokens_details": null, "prompt_tokens_details": {"audio_tokens": null, "cached_tokens": 0}, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0}, "model_map_information": {"model_map_key": "claude-4-sonnet-20250514", "model_map_value": {"key": "claude-4-sonnet-20250514", "max_tokens": 128000, "max_input_tokens": 200000, "max_output_tokens": 128000, "input_cost_per_token": 3e-06, "cache_creation_input_token_cost": 3.75e-06, "cache_read_input_token_cost": 3e-07, "input_cost_per_character": null, "input_cost_per_token_above_128k_tokens": null, "input_cost_per_token_above_200k_tokens": null, "input_cost_per_query": null, "input_cost_per_second": null, "input_cost_per_audio_token": null, "input_cost_per_token_batches": null, "output_cost_per_token_batches": null, "output_cost_per_token": 1.5e-05, "output_cost_per_audio_token": null, "output_cost_per_character": null, "output_cost_per_token_above_128k_tokens": null, "output_cost_per_character_above_128k_tokens": null, "output_cost_per_token_above_200k_tokens": null, "output_cost_per_second": null, "output_cost_per_image": null, "output_vector_size": null, "litellm_provider": "anthropic", "mode": "chat", "supports_system_messages": null, "supports_response_schema": true, "supports_vision": true, "supports_function_calling": true, "supports_tool_choice": true, "supports_assistant_prefill": true, "supports_prompt_caching": true, "supports_audio_input": false, "supports_audio_output": false, "supports_pdf_input": true, "supports_embedding_image_input": false, "supports_native_streaming": null, "supports_web_search": false, "supports_reasoning": true, "search_context_cost_per_query": null, "tpm": null, "rpm": null, "supported_openai_params": ["stream", "stop", "temperature", "top_p", "max_tokens", "max_completion_tokens", "tools", "tool_choice", "extra_headers", "parallel_tool_calls", "response_format", "user", "reasoning_effort", "thinking"]}}, "additional_usage_values": {"completion_tokens_details": {"accepted_prediction_tokens": null, "audio_tokens": null, "reasoning_tokens": null, "rejected_prediction_tokens": null, "text_tokens": 503, "image_tokens": null}, "prompt_tokens_details": {"audio_tokens": null, "cached_tokens": 0, "text_tokens": null, "image_tokens": null}, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0}}',
+ "metadata": '{"applied_guardrails": [], "batch_models": null, "mcp_tool_call_metadata": null, "vector_store_request_metadata": null, "routing_decision": null, "guardrail_information": null, "compression_savings": null, "usage_object": {"completion_tokens": 503, "prompt_tokens": 2095, "total_tokens": 2598, "completion_tokens_details": null, "prompt_tokens_details": {"audio_tokens": null, "cached_tokens": 0}, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0}, "model_map_information": {"model_map_key": "claude-4-sonnet-20250514", "model_map_value": {"key": "claude-4-sonnet-20250514", "max_tokens": 128000, "max_input_tokens": 200000, "max_output_tokens": 128000, "input_cost_per_token": 3e-06, "cache_creation_input_token_cost": 3.75e-06, "cache_read_input_token_cost": 3e-07, "input_cost_per_character": null, "input_cost_per_token_above_128k_tokens": null, "input_cost_per_token_above_200k_tokens": null, "input_cost_per_query": null, "input_cost_per_second": null, "input_cost_per_audio_token": null, "input_cost_per_token_batches": null, "output_cost_per_token_batches": null, "output_cost_per_token": 1.5e-05, "output_cost_per_audio_token": null, "output_cost_per_character": null, "output_cost_per_token_above_128k_tokens": null, "output_cost_per_character_above_128k_tokens": null, "output_cost_per_token_above_200k_tokens": null, "output_cost_per_second": null, "output_cost_per_image": null, "output_vector_size": null, "litellm_provider": "anthropic", "mode": "chat", "supports_system_messages": null, "supports_response_schema": true, "supports_vision": true, "supports_function_calling": true, "supports_tool_choice": true, "supports_assistant_prefill": true, "supports_prompt_caching": true, "supports_audio_input": false, "supports_audio_output": false, "supports_pdf_input": true, "supports_embedding_image_input": false, "supports_native_streaming": null, "supports_web_search": false, "supports_reasoning": true, "search_context_cost_per_query": null, "tpm": null, "rpm": null, "supported_openai_params": ["stream", "stop", "temperature", "top_p", "max_tokens", "max_completion_tokens", "tools", "tool_choice", "extra_headers", "parallel_tool_calls", "response_format", "user", "reasoning_effort", "thinking"]}}, "additional_usage_values": {"completion_tokens_details": {"accepted_prediction_tokens": null, "audio_tokens": null, "reasoning_tokens": null, "rejected_prediction_tokens": null, "text_tokens": 503, "image_tokens": null}, "prompt_tokens_details": {"audio_tokens": null, "cached_tokens": 0, "text_tokens": null, "image_tokens": null}, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0}}',
"cache_key": "Cache OFF",
"spend": 0.01383,
"total_tokens": 2598,
diff --git a/tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.py b/tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.py
index cc1e2943c8f..c6f2a6f1792 100644
--- a/tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.py
+++ b/tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.py
@@ -2902,3 +2902,17 @@ async def test_compression_savings_survive_to_spend_log_payload_metadata(monkeyp
"tokens_saved": 7000,
"source": "compression_interception",
}
+
+
+def test_no_routing_decision_key_defaults_to_none_in_spend_log_metadata():
+ payload = get_logging_payload(
+ kwargs={
+ "model": "gpt-4o-mini",
+ "litellm_params": {"metadata": {"user_api_key": "test-key"}},
+ },
+ response_obj=litellm.ModelResponse(id="chatcmpl-no-routing-decision", choices=[], usage=litellm.Usage()),
+ start_time=datetime.datetime.now(timezone.utc),
+ end_time=datetime.datetime.now(timezone.utc),
+ )
+ metadata = json.loads(payload["metadata"])
+ assert metadata["routing_decision"] is None
diff --git a/tests/test_litellm/proxy/test_litellm_pre_call_utils.py b/tests/test_litellm/proxy/test_litellm_pre_call_utils.py
index d6c5e9b1b81..e8acd7e6b75 100644
--- a/tests/test_litellm/proxy/test_litellm_pre_call_utils.py
+++ b/tests/test_litellm/proxy/test_litellm_pre_call_utils.py
@@ -671,6 +671,7 @@ async def test_add_litellm_data_to_request_strips_user_control_fields():
"applied_guardrails": ["spoofed"],
"applied_policies": ["spoofed-policy"],
"policy_sources": {"spoofed-policy": "request"},
+ "routing_decision": {"cause": "forged", "routed_model": "spoofed"},
"_guardrail_pipelines": [{"name": "spoofed"}],
"_pipeline_managed_guardrails": ["evaded"],
"safe_user_metadata": "kept",
@@ -681,6 +682,7 @@ async def test_add_litellm_data_to_request_strips_user_control_fields():
"mock_response": "free response",
"mock_tool_calls": [{"id": "call_1"}],
"disable_global_guardrails": True,
+ "routing_decision": {"cause": "forged", "routed_model": "spoofed"},
"metadata": copy.deepcopy(malicious_metadata),
"litellm_metadata": copy.deepcopy(malicious_metadata),
}
@@ -697,6 +699,7 @@ async def test_add_litellm_data_to_request_strips_user_control_fields():
assert "mock_response" not in updated
assert "mock_tool_calls" not in updated
assert "disable_global_guardrails" not in updated
+ assert "routing_decision" not in updated
stripped_keys = {
"disable_global_guardrails",
@@ -710,6 +713,7 @@ async def test_add_litellm_data_to_request_strips_user_control_fields():
"applied_guardrails",
"applied_policies",
"policy_sources",
+ "routing_decision",
"_guardrail_pipelines",
"_pipeline_managed_guardrails",
}
diff --git a/tests/test_litellm/router_strategy/adaptive_router/test_async_pre_routing.py b/tests/test_litellm/router_strategy/adaptive_router/test_async_pre_routing.py
index fb43cf403d6..0a8c230e773 100644
--- a/tests/test_litellm/router_strategy/adaptive_router/test_async_pre_routing.py
+++ b/tests/test_litellm/router_strategy/adaptive_router/test_async_pre_routing.py
@@ -240,3 +240,25 @@ async def test_invalid_min_quality_tier_header_treated_as_none():
assert (
r.pick_model.await_args.kwargs["min_quality_tier"] is None # type: ignore[union-attr]
)
+
+
+async def test_routing_decision_reports_bandit_choice():
+ r = _make_router()
+ r.pick_model = AsyncMock(return_value="smart") # type: ignore[method-assign]
+
+ response = await r.async_pre_routing_hook(
+ model="smart-cheap-router",
+ request_kwargs={},
+ messages=[{"role": "user", "content": "Write a Python function"}],
+ )
+
+ assert response is not None
+ decision = response.routing_decision
+ assert decision is not None
+ assert decision["router_model_name"] == "smart-cheap-router"
+ assert decision["router_type"] == "adaptive"
+ assert decision["cause"] == "bandit"
+ assert decision["routed_model"] == "smart"
+ assert decision["request_type"] == RequestType.CODE_GENERATION.value
+ assert "tier" not in decision
diff --git a/tests/test_litellm/router_strategy/test_complexity_router.py b/tests/test_litellm/router_strategy/test_complexity_router.py
index f31ca32f4c5..e734d8ec876 100644
--- a/tests/test_litellm/router_strategy/test_complexity_router.py
+++ b/tests/test_litellm/router_strategy/test_complexity_router.py
@@ -24,6 +24,7 @@ from litellm.constants import RETURN_RAW_MODEL_NAME_METADATA_KEY
from litellm.router_strategy.complexity_router.complexity_router import (
ComplexityRouter,
DimensionScore,
+ KeywordOverride,
)
from litellm.router_strategy.complexity_router.config import (
DEFAULT_COMPLEXITY_CONFIG,
@@ -1381,21 +1382,27 @@ class TestLLMClassifier:
async def test_aclassify_heuristic_skips_llm_call(self, complexity_router, mock_router_instance):
"""When classifier_type is 'heuristic' (default), aclassify must not call the LLM."""
mock_router_instance.acompletion = AsyncMock()
- tier, score, signals = await complexity_router.aclassify("Hello!")
+ outcome = await complexity_router.aclassify("Hello!")
mock_router_instance.acompletion.assert_not_called()
- assert tier == ComplexityTier.SIMPLE
+ assert outcome.tier == ComplexityTier.SIMPLE
+ assert outcome.cause == "heuristic_scorer"
+ assert outcome.score is not None
@pytest.mark.asyncio
async def test_aclassify_llm_success_routes_by_llm_verdict(self, llm_complexity_router, mock_router_instance):
"""A well-formed structured LLM response should decide the tier directly.
Uses a prompt that heuristic scoring alone would classify as SIMPLE, to prove
- the LLM verdict -- not the heuristic scorer -- is what decided the tier.
+ the LLM verdict -- not the heuristic scorer -- is what decided the tier. The
+ outcome must say so (cause) and must not fabricate a score: the LLM path
+ produces a tier label only.
"""
mock_router_instance.acompletion = AsyncMock(return_value=_llm_response('{"tier": "COMPLEX"}'))
- tier, score, signals = await llm_complexity_router.aclassify("hi")
- assert tier == ComplexityTier.COMPLEX
- assert "llm-classifier:COMPLEX" in signals
+ outcome = await llm_complexity_router.aclassify("hi")
+ assert outcome.tier == ComplexityTier.COMPLEX
+ assert outcome.cause == "llm_classifier"
+ assert outcome.score is None
+ assert "llm-classifier:COMPLEX" in outcome.signals
mock_router_instance.acompletion.assert_awaited_once()
call_kwargs = mock_router_instance.acompletion.call_args.kwargs
assert call_kwargs["model"] == "haiku-classifier"
@@ -1556,9 +1563,13 @@ class TestLLMClassifier:
):
"""A timeout/error from the classifier model must fall back to heuristic scoring."""
mock_router_instance.acompletion = AsyncMock(side_effect=TimeoutError("classifier timed out"))
- tier, score, signals = await llm_complexity_router.aclassify("Hello!")
- assert tier == llm_complexity_router.classify("Hello!")[0]
- assert tier == ComplexityTier.SIMPLE
+ outcome = await llm_complexity_router.aclassify("Hello!")
+ assert outcome.tier == llm_complexity_router.classify("Hello!")[0]
+ assert outcome.tier == ComplexityTier.SIMPLE
+ # The fallback ran the heuristic, and the outcome must say so even though
+ # the configured classifier_type is "llm".
+ assert outcome.cause == "heuristic_scorer"
+ assert outcome.score is not None
@pytest.mark.asyncio
async def test_aclassify_falls_back_to_heuristic_on_unparseable_response(
@@ -1566,8 +1577,9 @@ class TestLLMClassifier:
):
"""Non-JSON or schema-violating output must fall back to heuristic scoring, not raise."""
mock_router_instance.acompletion = AsyncMock(return_value=_llm_response("not json"))
- tier, score, signals = await llm_complexity_router.aclassify("Hello!")
- assert tier == ComplexityTier.SIMPLE
+ outcome = await llm_complexity_router.aclassify("Hello!")
+ assert outcome.tier == ComplexityTier.SIMPLE
+ assert outcome.cause == "heuristic_scorer"
@pytest.mark.asyncio
async def test_aclassify_falls_back_to_heuristic_on_empty_content(
@@ -1575,8 +1587,9 @@ class TestLLMClassifier:
):
"""Empty/None message content (e.g. provider quirk) must fall back, not raise."""
mock_router_instance.acompletion = AsyncMock(return_value=_llm_response(None))
- tier, score, signals = await llm_complexity_router.aclassify("Hello!")
- assert tier == ComplexityTier.SIMPLE
+ outcome = await llm_complexity_router.aclassify("Hello!")
+ assert outcome.tier == ComplexityTier.SIMPLE
+ assert outcome.cause == "heuristic_scorer"
@pytest.mark.asyncio
async def test_pre_routing_hook_uses_llm_classifier_end_to_end(self, llm_complexity_router, mock_router_instance):
@@ -2071,8 +2084,12 @@ class TestLexicalKeywordTierRules:
litellm_router_instance=mock_router_instance,
complexity_router_config=config,
)
- assert router._lexical_tier_override("hi there, please advise") == ComplexityTier.COMPLEX
- assert router._lexical_tier_override("just saying hi") == ComplexityTier.SIMPLE
+ assert router._lexical_tier_override("hi there, please advise") == KeywordOverride(
+ tier=ComplexityTier.COMPLEX, matched_keyword="advise"
+ )
+ assert router._lexical_tier_override("just saying hi") == KeywordOverride(
+ tier=ComplexityTier.SIMPLE, matched_keyword="hi"
+ )
assert router._lexical_tier_override("nothing relevant here") is None
@pytest.mark.asyncio
@@ -2108,7 +2125,9 @@ class TestLexicalKeywordTierRules:
litellm_router_instance=mock_router_instance,
complexity_router_config=config,
)
- assert router._lexical_tier_override("running my k8s cluster") == ComplexityTier.REASONING
+ assert router._lexical_tier_override("running my k8s cluster") == KeywordOverride(
+ tier=ComplexityTier.REASONING, matched_keyword="k8s"
+ )
assert router._lexical_tier_override("what is a k8scluster thing") is None
@@ -2812,7 +2831,7 @@ class TestRoutingDecisionCauseLogging:
request_kwargs={},
messages=[{"role": "user", "content": "What is the boiling point of water at sea level?"}],
)
- assert "routing decision cause=complexity_scorer" in router_log_capture.text
+ assert "routing decision cause=heuristic_scorer" in router_log_capture.text
assert "score=" in router_log_capture.text
assert "cause=literal_keyword_match" not in router_log_capture.text
assert "cause=semantic_keyword_match" not in router_log_capture.text
@@ -3316,9 +3335,9 @@ class TestEscalationKeywords:
assert complexity_router.escalation_keywords == ["LITELLM ESCALATE"]
def test_escalation_triggered_is_case_sensitive(self, complexity_router):
- assert complexity_router._escalation_triggered("please LITELLM ESCALATE now") is True
- assert complexity_router._escalation_triggered("please litellm escalate now") is False
- assert complexity_router._escalation_triggered("how do I escalate this ticket") is False
+ assert complexity_router._matched_escalation_keyword("please LITELLM ESCALATE now") == "LITELLM ESCALATE"
+ assert complexity_router._matched_escalation_keyword("please litellm escalate now") is None
+ assert complexity_router._matched_escalation_keyword("how do I escalate this ticket") is None
def test_escalate_tier_bumps_one_step(self, complexity_router):
assert complexity_router._escalate_tier(ComplexityTier.SIMPLE) == ComplexityTier.MEDIUM
@@ -3559,3 +3578,584 @@ class TestEscalationKeywords:
messages=[{"role": "user", "content": "LITELLM ESCALATE do better"}],
)
assert result.model == "o1-b" # unchanged: no random hop to o1-a / o1-c
+
+
+class TestRoutingDecisionContents:
+ """Every routing path must return a PreRoutingHookResponse carrying a routing_decision
+ that names the mechanism that actually decided, with the facts of that path only."""
+
+ @pytest.mark.asyncio
+ async def test_heuristic_decision_carries_score_signals_and_boundary_snapshot(self, complexity_router):
+ response = await complexity_router.async_pre_routing_hook(
+ model="test-complexity-router",
+ request_kwargs={},
+ messages=[{"role": "user", "content": "Hello!"}],
+ )
+ assert response is not None
+ decision = response.routing_decision
+ assert decision is not None
+ assert decision["router_model_name"] == "test-complexity-router"
+ assert decision["router_type"] == "complexity"
+ assert decision["cause"] == "heuristic_scorer"
+ assert decision["tier"] == "SIMPLE"
+ assert decision["routed_model"] == response.model == "gpt-4o-mini"
+ assert isinstance(decision["score"], float)
+ assert any("short" in signal for signal in decision["signals"])
+ # The snapshot must reflect the CONFIGURED boundaries (the fixture overrides the
+ # 0.15/0.35/0.60 defaults), so a logged row stays truthful after config edits.
+ assert decision["tier_boundaries"] == {
+ "simple_medium": 0.25,
+ "medium_complex": 0.50,
+ "complex_reasoning": 0.75,
+ }
+ assert "escalated" not in decision
+ assert "classifier_model" not in decision
+
+ @pytest.mark.asyncio
+ async def test_llm_classifier_decision_names_judge_and_omits_score(
+ self, llm_complexity_router, mock_router_instance
+ ):
+ mock_router_instance.acompletion = AsyncMock(return_value=_llm_response('{"tier": "REASONING"}'))
+ response = await llm_complexity_router.async_pre_routing_hook(
+ model="test-complexity-router",
+ request_kwargs={},
+ messages=[{"role": "user", "content": "hi"}],
+ )
+ assert response is not None
+ decision = response.routing_decision
+ assert decision is not None
+ assert decision["cause"] == "llm_classifier"
+ assert decision["classifier_model"] == "haiku-classifier"
+ assert decision["tier"] == "REASONING"
+ # The LLM path produces a tier label, not a score: no synthetic score and no
+ # boundary snapshot may appear on these rows.
+ assert "score" not in decision
+ assert "tier_boundaries" not in decision
+
+ @pytest.mark.asyncio
+ async def test_llm_classifier_fallback_decision_reports_heuristic(
+ self, llm_complexity_router, mock_router_instance
+ ):
+ """A failed LLM classifier falls back to the heuristic, and the persisted cause
+ must say heuristic_scorer even though classifier_type is 'llm'."""
+ mock_router_instance.acompletion = AsyncMock(side_effect=TimeoutError("classifier timed out"))
+ response = await llm_complexity_router.async_pre_routing_hook(
+ model="test-complexity-router",
+ request_kwargs={},
+ messages=[{"role": "user", "content": "Hello!"}],
+ )
+ assert response is not None
+ decision = response.routing_decision
+ assert decision is not None
+ assert decision["cause"] == "heuristic_scorer"
+ assert "classifier_model" not in decision
+ assert isinstance(decision["score"], float)
+
+ @pytest.mark.asyncio
+ async def test_keyword_override_decision_carries_matched_keyword(self, mock_router_instance, basic_config):
+ config = {
+ **basic_config,
+ "keyword_tier_rules": [{"keywords": ["deploy to k8s"], "tier": "REASONING"}],
+ }
+ router = ComplexityRouter(
+ model_name="test-complexity-router",
+ litellm_router_instance=mock_router_instance,
+ complexity_router_config=config,
+ )
+ response = await router.async_pre_routing_hook(
+ model="test-complexity-router",
+ request_kwargs={},
+ messages=[{"role": "user", "content": "please deploy to k8s now"}],
+ )
+ assert response is not None
+ decision = response.routing_decision
+ assert decision is not None
+ assert decision["cause"] == "literal_keyword_match"
+ assert decision["matched_keyword"] == "deploy to k8s"
+ assert decision["tier"] == "REASONING"
+ assert "score" not in decision
+
+ @pytest.mark.asyncio
+ async def test_no_user_message_decision_is_default_fallback(self, complexity_router):
+ response = await complexity_router.async_pre_routing_hook(
+ model="test-complexity-router",
+ request_kwargs={},
+ messages=[{"role": "system", "content": "be nice"}],
+ )
+ assert response is not None
+ decision = response.routing_decision
+ assert decision is not None
+ assert decision["cause"] == "default_fallback"
+ assert decision["routed_model"] == response.model
+ assert "tier" not in decision
+
+ @pytest.mark.asyncio
+ async def test_session_pin_decision(self, mock_router_instance, basic_config):
+ mock_router_instance.cache = DualCache()
+ router = ComplexityRouter(
+ model_name="test-complexity-router",
+ litellm_router_instance=mock_router_instance,
+ complexity_router_config={**basic_config, "session_affinity": True},
+ )
+ request_kwargs = {"metadata": {"session_id": "session-decision"}}
+ cache_key = router._get_session_affinity_cache_key("session-decision", request_kwargs)
+ await mock_router_instance.cache.async_set_cache(key=cache_key, value="gpt-4o")
+ response = await router.async_pre_routing_hook(
+ model="test-complexity-router",
+ request_kwargs=request_kwargs,
+ messages=[{"role": "user", "content": "hi again"}],
+ )
+ assert response is not None
+ decision = response.routing_decision
+ assert decision is not None
+ assert decision["cause"] == "session_affinity_pin"
+ assert decision["routed_model"] == "gpt-4o"
+ assert "escalated" not in decision
+
+ @pytest.mark.asyncio
+ async def test_reasoning_override_is_its_own_cause(self, complexity_router):
+ """The override is the fact that the score did NOT choose the tier, so it is a
+ cause rather than a marker inside `signals`; anything that filters signals would
+ otherwise change what the row claims."""
+ response = await complexity_router.async_pre_routing_hook(
+ model="test-complexity-router",
+ request_kwargs={},
+ messages=[{"role": "user", "content": "Let's think step by step and prove the theorem."}],
+ )
+ decision = response.routing_decision
+ assert decision["tier"] == "REASONING"
+ assert decision["cause"] == "reasoning_override"
+ # The score is still recorded, but the cause is what says it did not decide.
+ assert decision["score"] < decision["tier_boundaries"]["complex_reasoning"]
+
+
+class TestSignalsNeverQuoteTheSystemPrompt:
+ """Signals are persisted to the caller-readable spend log, so they may name a matched
+ term only when the caller supplied it. A term matched solely in the system prompt is
+ reported as a count, which still explains the score without letting a caller recover
+ configured terms from a prompt it cannot see."""
+
+ @pytest.mark.asyncio
+ async def test_system_prompt_only_terms_are_reported_as_a_count(self, complexity_router):
+ response = await complexity_router.async_pre_routing_hook(
+ model="test-complexity-router",
+ request_kwargs={},
+ messages=[
+ {"role": "system", "content": "You operate the kubernetes database api for the deployment pipeline."},
+ {"role": "user", "content": "say hi"},
+ ],
+ )
+ assert response is not None
+ signals = response.routing_decision["signals"]
+ joined = " ".join(signals)
+ # The system prompt drove these matches, so no signal may name them.
+ for term in ("kubernetes", "database", "api", "deployment"):
+ assert term not in joined
+ # The match is still reported, as a count, so the score stays explainable.
+ assert any("matches" in signal for signal in signals)
+
+ @pytest.mark.asyncio
+ async def test_terms_the_caller_supplied_are_still_named(self, complexity_router):
+ response = await complexity_router.async_pre_routing_hook(
+ model="test-complexity-router",
+ request_kwargs={},
+ messages=[
+ {"role": "system", "content": "You operate the kubernetes cluster."},
+ {"role": "user", "content": "help me debug the database api timeout in production"},
+ ],
+ )
+ assert response is not None
+ signals = " ".join(response.routing_decision["signals"])
+ # The caller typed these, so quoting them discloses nothing.
+ assert "database" in signals or "api" in signals
+ # It did not type this one.
+ assert "kubernetes" not in signals
+
+ def test_scoring_still_reads_the_system_prompt(self, complexity_router):
+ """Redaction is a disclosure rule, not a scoring change: the system prompt must
+ still count toward the tier exactly as before."""
+ with_system = complexity_router.classify(
+ "say hi", "You operate the kubernetes database api for the deployment pipeline."
+ )
+ without_system = complexity_router.classify("say hi")
+ assert with_system[1] > without_system[1]
+
+
+class TestRoutingDecisionSurvivesToSpendLogOnEveryMetadataShape:
+ """The decision must reach the spend-log row on every request surface.
+
+ `/v1/chat/completions` carries proxy state in `metadata`; `/v1/messages` and the
+ batch-style routes carry it in `litellm_metadata` (so the provider's own `metadata`
+ field stays untouched), and a caller may supply either, both, or neither. Logging
+ snapshots `litellm_metadata` by value (`function_setup`, litellm/utils.py), so a
+ stash written to the wrong bucket, or read after a copy, is dropped silently and
+ only on the surfaces nobody exercised. This drives the real hook and then the real
+ spend-log payload builder for every shape.
+ """
+
+ MODEL_LIST = [
+ {
+ "model_name": "smart-router",
+ "litellm_params": {
+ "model": "auto_router/complexity_router",
+ "complexity_router_config": {
+ "tiers": {"SIMPLE": ["gpt-4o-mini"], "MEDIUM": ["gpt-4o"]},
+ "session_affinity": False,
+ },
+ },
+ },
+ {"model_name": "gpt-4o-mini", "litellm_params": {"model": "openai/gpt-4o-mini"}},
+ {"model_name": "gpt-4o", "litellm_params": {"model": "openai/gpt-4o"}},
+ ]
+
+ @pytest.mark.parametrize(
+ "request_kwargs, expected_bucket",
+ [
+ pytest.param({}, "metadata", id="no-caller-metadata"),
+ pytest.param({"metadata": {"caller_tag": "x"}}, "metadata", id="caller-metadata"),
+ pytest.param({"litellm_metadata": {}}, "litellm_metadata", id="litellm-metadata-seeded"),
+ pytest.param(
+ {"litellm_metadata": {"caller_tag": "x"}}, "litellm_metadata", id="litellm-metadata-with-caller-value"
+ ),
+ pytest.param(
+ {"litellm_metadata": {}, "metadata": {"user_id": "end-user-1"}},
+ "litellm_metadata",
+ id="both-buckets",
+ ),
+ ],
+ )
+ @pytest.mark.asyncio
+ async def test_decision_reaches_the_spend_log_payload(self, request_kwargs, expected_bucket):
+ import datetime
+ import json
+
+ from litellm.proxy.spend_tracking.spend_tracking_utils import get_logging_payload
+
+ router = Router(model_list=self.MODEL_LIST)
+ response = await router.async_pre_routing_hook(
+ model="smart-router",
+ request_kwargs=request_kwargs,
+ messages=[{"role": "user", "content": "Hello!"}],
+ )
+ assert response is not None
+ assert "routing_decision" in request_kwargs[expected_bucket]
+ if expected_bucket == "litellm_metadata" and isinstance(request_kwargs.get("metadata"), dict):
+ # On these routes `metadata` is the provider's own field, forwarded upstream.
+ assert "routing_decision" not in request_kwargs["metadata"]
+
+ # Mirror function_setup: it copies `litellm_metadata` by value into
+ # litellm_params AFTER the router hook has run, so the copy must carry
+ # the decision. Reading the stash any earlier would lose it.
+ litellm_params: Dict = {}
+ if "metadata" in request_kwargs:
+ litellm_params["metadata"] = request_kwargs["metadata"]
+ if isinstance(request_kwargs.get("litellm_metadata"), dict):
+ litellm_params["litellm_metadata"] = request_kwargs["litellm_metadata"].copy()
+
+ payload = get_logging_payload(
+ kwargs={"model": "gpt-4o-mini", "litellm_params": litellm_params},
+ response_obj=litellm.ModelResponse(id="chatcmpl-shape", choices=[], usage=litellm.Usage()),
+ start_time=datetime.datetime.now(datetime.timezone.utc),
+ end_time=datetime.datetime.now(datetime.timezone.utc),
+ )
+ persisted = json.loads(payload["metadata"])["routing_decision"]
+ assert persisted is not None, f"routing_decision dropped for {expected_bucket}"
+ assert persisted["router_model_name"] == "smart-router"
+
+
+class TestRoutingDecisionIsPerAttempt:
+ """The stash must describe the attempt that actually served the request.
+
+ Fallbacks re-enter `async_pre_routing_hook` with the SAME request_kwargs, so a
+ decision left behind by a failed auto-router attempt would be attributed to the
+ plain model group that served the retry, making the spend row claim a tier the
+ request never used. The bucket is also resolved through the shared owner, so a
+ non-dict value in the bucket slot is replaced rather than silently skipped.
+ """
+
+ MODEL_LIST = [
+ {
+ "model_name": "smart-router",
+ "litellm_params": {
+ "model": "auto_router/complexity_router",
+ "complexity_router_config": {
+ "tiers": {"SIMPLE": ["gpt-4o-mini"], "MEDIUM": ["gpt-4o"]},
+ "session_affinity": False,
+ },
+ },
+ },
+ {"model_name": "gpt-4o-mini", "litellm_params": {"model": "openai/gpt-4o-mini"}},
+ {"model_name": "gpt-4o", "litellm_params": {"model": "openai/gpt-4o"}},
+ ]
+
+ @pytest.mark.parametrize(
+ "seed, bucket", [({}, "metadata"), ({"litellm_metadata": {}}, "litellm_metadata")]
+ )
+ @pytest.mark.asyncio
+ async def test_fallback_to_plain_model_group_clears_the_earlier_decision(self, seed, bucket):
+ router = Router(model_list=self.MODEL_LIST)
+ request_kwargs: Dict = dict(seed)
+ messages = [{"role": "user", "content": "Hello!"}]
+
+ await router.async_pre_routing_hook(
+ model="smart-router", request_kwargs=request_kwargs, messages=messages
+ )
+ assert "routing_decision" in request_kwargs[bucket]
+
+ # The fallback attempt reuses the same kwargs and selects no strategy.
+ response = await router.async_pre_routing_hook(
+ model="gpt-4o-mini", request_kwargs=request_kwargs, messages=messages
+ )
+ assert response is None
+ assert "routing_decision" not in request_kwargs[bucket]
+
+ @pytest.mark.parametrize("unusable_bucket", [None, "not-a-dict"])
+ @pytest.mark.asyncio
+ async def test_non_dict_bucket_is_replaced_not_skipped(self, unusable_bucket):
+ """A caller can send `litellm_metadata` as a non-dict (unparsed string, null).
+ Skipping the write there would drop provenance on a successfully routed
+ request with no error, so the shared bucket owner replaces the value."""
+ router = Router(model_list=self.MODEL_LIST)
+ request_kwargs: Dict = {"litellm_metadata": unusable_bucket}
+
+ response = await router.async_pre_routing_hook(
+ model="smart-router",
+ request_kwargs=request_kwargs,
+ messages=[{"role": "user", "content": "Hello!"}],
+ )
+
+ assert response is not None
+ bucket = request_kwargs["litellm_metadata"]
+ assert isinstance(bucket, dict)
+ assert bucket["routing_decision"]["router_model_name"] == "smart-router"
+
+
+class TestRecordRoutingDecision:
+ """Direct coverage of the single recording point, whose contract is write-or-clear:
+ the request's metadata must describe the current attempt and nothing else."""
+
+ DECISION = {"router_model_name": "smart-router", "router_type": "complexity", "routed_model": "gpt-4o-mini"}
+
+ def test_none_clears_a_previous_decision_from_both_buckets(self):
+ request_kwargs: Dict = {
+ "metadata": {"routing_decision": self.DECISION, "keep": 1},
+ "litellm_metadata": {"routing_decision": self.DECISION},
+ }
+ Router._record_routing_decision(request_kwargs=request_kwargs, routing_decision=None)
+ assert "routing_decision" not in request_kwargs["metadata"]
+ assert "routing_decision" not in request_kwargs["litellm_metadata"]
+ assert request_kwargs["metadata"]["keep"] == 1
+
+ def test_none_creates_no_bucket_on_a_request_that_had_none(self):
+ request_kwargs: Dict = {}
+ Router._record_routing_decision(request_kwargs=request_kwargs, routing_decision=None)
+ assert request_kwargs == {}
+
+
+class TestEscalationIsRecordedConsistently:
+ """An escalation keyword records two separate facts on every path: that the caller
+ asked, and whether the tier actually moved. Dropping the ask when there is nowhere
+ higher to go makes a request look like an ordinary route, and reporting a bump that
+ never happened is the opposite error; both must be avoided identically everywhere."""
+
+ CEILING_CONFIG = {
+ "tiers": {"SIMPLE": ["gpt-4o-mini"], "REASONING": ["o1-preview"]},
+ "session_affinity": False,
+ }
+
+ @pytest.mark.asyncio
+ async def test_scorer_path_at_ceiling_keeps_the_keyword_and_reports_no_bump(self, mock_router_instance):
+ router = ComplexityRouter(
+ model_name="test-router",
+ litellm_router_instance=mock_router_instance,
+ complexity_router_config={
+ **self.CEILING_CONFIG,
+ "tier_boundaries": {"simple_medium": -99, "medium_complex": -99, "complex_reasoning": -99},
+ },
+ )
+ response = await router.async_pre_routing_hook(
+ model="test-router",
+ request_kwargs={},
+ messages=[{"role": "user", "content": "LITELLM ESCALATE already at the top"}],
+ )
+ decision = response.routing_decision
+ assert decision["tier"] == "REASONING"
+ assert decision["escalation_keyword"] == "LITELLM ESCALATE"
+ assert decision["escalated"] is False
+
+ @pytest.mark.asyncio
+ async def test_scorer_path_below_ceiling_reports_the_bump(self, complexity_router):
+ response = await complexity_router.async_pre_routing_hook(
+ model="test-router",
+ request_kwargs={},
+ messages=[{"role": "user", "content": "LITELLM ESCALATE what is 2+2"}],
+ )
+ decision = response.routing_decision
+ assert decision["escalation_keyword"] == "LITELLM ESCALATE"
+ assert decision["escalated"] is True
+
+ @pytest.mark.asyncio
+ async def test_session_pin_at_ceiling_still_records_the_ask(self, mock_router_instance):
+ mock_router_instance.cache = DualCache()
+ router = ComplexityRouter(
+ model_name="test-router",
+ litellm_router_instance=mock_router_instance,
+ complexity_router_config={**self.CEILING_CONFIG, "session_affinity": True},
+ )
+ request_kwargs = {"metadata": {"session_id": "session-ceiling"}}
+ cache_key = router._get_session_affinity_cache_key("session-ceiling", request_kwargs)
+ await mock_router_instance.cache.async_set_cache(key=cache_key, value="o1-preview")
+
+ response = await router.async_pre_routing_hook(
+ model="test-router",
+ request_kwargs=request_kwargs,
+ messages=[{"role": "user", "content": "LITELLM ESCALATE go higher"}],
+ )
+ decision = response.routing_decision
+ assert decision["routed_model"] == "o1-preview"
+ assert decision["cause"] == "session_affinity_pin"
+ # Previously the keyword was dropped here, so the row was indistinguishable
+ # from a turn that never asked to escalate.
+ assert decision["escalation_keyword"] == "LITELLM ESCALATE"
+ assert decision["escalated"] is False
+
+ @pytest.mark.asyncio
+ async def test_session_pin_below_ceiling_reports_the_bump(self, mock_router_instance):
+ mock_router_instance.cache = DualCache()
+ router = ComplexityRouter(
+ model_name="test-router",
+ litellm_router_instance=mock_router_instance,
+ complexity_router_config={**self.CEILING_CONFIG, "session_affinity": True},
+ )
+ request_kwargs = {"metadata": {"session_id": "session-below"}}
+ cache_key = router._get_session_affinity_cache_key("session-below", request_kwargs)
+ await mock_router_instance.cache.async_set_cache(key=cache_key, value="gpt-4o-mini")
+
+ response = await router.async_pre_routing_hook(
+ model="test-router",
+ request_kwargs=request_kwargs,
+ messages=[{"role": "user", "content": "LITELLM ESCALATE go higher"}],
+ )
+ decision = response.routing_decision
+ assert decision["cause"] == "session_affinity_escalation"
+ assert decision["escalation_keyword"] == "LITELLM ESCALATE"
+ assert decision["escalated"] is True
+
+ @pytest.mark.asyncio
+ async def test_signals_are_a_json_array_not_a_stringified_tuple(self, complexity_router):
+ """The dashboard maps over `signals`, so the persisted shape has to be an array
+ regardless of how any given serializer treats sequence types."""
+ import json
+
+ from litellm.litellm_core_utils.safe_json_dumps import safe_dumps
+
+ response = await complexity_router.async_pre_routing_hook(
+ model="test-router",
+ request_kwargs={},
+ messages=[{"role": "user", "content": "Hello!"}],
+ )
+ signals = response.routing_decision["signals"]
+ assert isinstance(signals, list)
+ assert isinstance(json.loads(safe_dumps({"d": response.routing_decision}))["d"]["signals"], list)
+
+
+class TestRedactedLoggingDropsPromptText:
+ """An operator who turns message logging off has said prompt content must not reach
+ the logs. The routing decision quotes the prompt in its matched keywords and in the
+ signals that name them, so those are dropped while the derived values that make the
+ row explainable are kept."""
+
+ MODEL_LIST = [
+ {
+ "model_name": "smart-router",
+ "litellm_params": {
+ "model": "auto_router/complexity_router",
+ "complexity_router_config": {
+ "tiers": {"SIMPLE": ["gpt-4o-mini"], "REASONING": ["gpt-4o"]},
+ "session_affinity": False,
+ "keyword_tier_rules": [{"keywords": ["deploy to k8s"], "tier": "REASONING"}],
+ },
+ },
+ },
+ {"model_name": "gpt-4o-mini", "litellm_params": {"model": "openai/gpt-4o-mini"}},
+ {"model_name": "gpt-4o", "litellm_params": {"model": "openai/gpt-4o"}},
+ ]
+
+ MESSAGES = [{"role": "user", "content": "LITELLM ESCALATE please deploy to k8s now"}]
+
+ async def _decision(self, request_kwargs: Dict) -> Dict:
+ router = Router(model_list=self.MODEL_LIST)
+ response = await router.async_pre_routing_hook(
+ model="smart-router", request_kwargs=request_kwargs, messages=self.MESSAGES
+ )
+ assert response is not None
+ return request_kwargs["metadata"]["routing_decision"]
+
+ @pytest.mark.asyncio
+ async def test_prompt_text_is_persisted_when_logging_is_not_redacted(self):
+ decision = await self._decision({})
+ # Control: without redaction the terms are the point of the feature.
+ assert decision["matched_keyword"] == "deploy to k8s"
+ assert decision["escalation_keyword"] == "LITELLM ESCALATE"
+
+ @pytest.mark.asyncio
+ async def test_redaction_drops_quoted_prompt_text_but_keeps_the_explanation(self, monkeypatch):
+ # The usual deployment shape: `litellm_settings: turn_off_message_logging: true`
+ monkeypatch.setattr(litellm, "turn_off_message_logging", True)
+ decision = await self._decision({})
+
+ for field in ("signals", "matched_keyword", "escalation_keyword"):
+ assert field not in decision, f"{field} quotes the prompt and must be dropped"
+ # Nothing here reproduces the prompt, so the row stays explainable.
+ assert decision["cause"] == "literal_keyword_match"
+ assert decision["tier"] == "REASONING"
+ assert decision["routed_model"] == "gpt-4o"
+ assert decision["escalated"] is False
+
+ def test_only_verbatim_prompt_fields_are_classified_as_prompt_text(self, monkeypatch):
+ """The field classification is the whole contract, so pin it directly: anything
+ that quotes the prompt goes, anything derived from it stays."""
+ monkeypatch.setattr(litellm, "turn_off_message_logging", True)
+ full = {
+ "router_model_name": "smart-router",
+ "router_type": "complexity",
+ "routed_model": "gpt-4o",
+ "cause": "literal_keyword_match",
+ "tier": "REASONING",
+ "score": 0.8,
+ "tier_boundaries": {"simple_medium": 0.15, "medium_complex": 0.35, "complex_reasoning": 0.6},
+ "classifier_model": "claude-haiku",
+ "escalated": True,
+ "signals": ["code (python)"],
+ "matched_keyword": "deploy to k8s",
+ "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"}
+
+ @pytest.mark.asyncio
+ async def test_redaction_via_request_header_is_honored(self):
+ request_kwargs: Dict = {"metadata": {"headers": {"x-litellm-enable-message-redaction": True}}}
+ decision = await self._decision(request_kwargs)
+ assert "matched_keyword" not in decision
+ assert decision["cause"] == "literal_keyword_match"
+
+
+def test_every_routing_decision_field_is_classified():
+ """Redaction is derived from a declaration, not a list at the call site, so every
+ field has to be classified as quoting the prompt or aggregating it. A field added
+ without a decision fails here rather than silently shipping unredacted or, worse,
+ being over-redacted and taking a load-bearing fact with it."""
+ from litellm.types.utils import (
+ DERIVED_ROUTING_DECISION_FIELDS,
+ PROMPT_QUOTING_ROUTING_DECISION_FIELDS,
+ StandardLoggingRoutingDecision,
+ )
+
+ declared = set(StandardLoggingRoutingDecision.__annotations__)
+ classified = PROMPT_QUOTING_ROUTING_DECISION_FIELDS | DERIVED_ROUTING_DECISION_FIELDS
+ assert declared == classified, (
+ "classify new routing-decision fields in litellm/types/utils.py: "
+ f"unclassified={declared - classified}, stale={classified - declared}"
+ )
+ assert not (PROMPT_QUOTING_ROUTING_DECISION_FIELDS & DERIVED_ROUTING_DECISION_FIELDS)
diff --git a/tests/test_litellm/router_strategy/test_quality_router.py b/tests/test_litellm/router_strategy/test_quality_router.py
index 01574cb980d..b2e901739da 100644
--- a/tests/test_litellm/router_strategy/test_quality_router.py
+++ b/tests/test_litellm/router_strategy/test_quality_router.py
@@ -1031,3 +1031,53 @@ class TestRouterQualityDeploymentMethods:
)
router.init_quality_router_deployment(deployment)
assert "auto_router/quality_router/test-router" in router.quality_routers
+
+
+class TestRoutingDecisionProvenance:
+ """Every quality-router path must attach a routing_decision to its hook response,
+ including the no-user-message default path that previously recorded nothing."""
+
+ @pytest.mark.asyncio
+ async def test_quality_tier_decision(self, quality_router):
+ resp = await quality_router.async_pre_routing_hook(
+ model="quality-router-test",
+ request_kwargs={},
+ messages=[{"role": "user", "content": "hi"}],
+ )
+ assert resp is not None
+ decision = resp.routing_decision
+ assert decision is not None
+ assert decision["router_model_name"] == "quality-router-test"
+ assert decision["router_type"] == "quality"
+ assert decision["cause"] == "quality_tier"
+ assert decision["routed_model"] == "haiku"
+ assert decision["tier"] == "1"
+ assert isinstance(decision["score"], float)
+
+ @pytest.mark.asyncio
+ async def test_keyword_decision_carries_matched_keyword(self, keyword_router):
+ resp = await keyword_router.async_pre_routing_hook(
+ model="quality-router-test",
+ request_kwargs={},
+ messages=[{"role": "user", "content": "please write python for me"}],
+ )
+ assert resp is not None
+ decision = resp.routing_decision
+ assert decision is not None
+ assert decision["cause"] == "keyword"
+ assert decision["matched_keyword"] == "python"
+ assert decision["routed_model"] == resp.model
+
+ @pytest.mark.asyncio
+ async def test_no_user_message_decision_is_default_fallback(self, quality_router):
+ resp = await quality_router.async_pre_routing_hook(
+ model="quality-router-test",
+ request_kwargs={},
+ messages=[{"role": "system", "content": "You are a helpful assistant."}],
+ )
+ assert resp is not None
+ decision = resp.routing_decision
+ assert decision is not None
+ assert decision["cause"] == "default_fallback"
+ assert decision["routed_model"] == "haiku"
+ assert "tier" not in decision
diff --git a/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailContent.tsx b/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailContent.tsx
index 2752cccce56..e61d614f9a1 100644
--- a/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailContent.tsx
+++ b/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/LogDetailContent.tsx
@@ -12,6 +12,7 @@ import { VectorStoreViewer } from "../VectorStoreViewer";
import { TruncatedValue } from "./TruncatedValue";
import { TokenFlow } from "./TokenFlow";
import { JsonViewer } from "./JsonViewer";
+import { RoutingDecisionCard, type RoutingDecision } from "./RoutingDecisionCard";
import {
formatData,
checkHasMessages,
@@ -137,6 +138,9 @@ export function LogDetailContent({ logEntry, isLoadingDetails = false, accessTok
</Card>
</div>
+ {/* Routing */}
+ <RoutingDecisionCard decision={metadata?.routing_decision as RoutingDecision | undefined} />
+
{/* Metrics */}
<MetricsSection logEntry={logEntry} metadata={metadata} />
diff --git a/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/RoutingDecisionCard.test.tsx b/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/RoutingDecisionCard.test.tsx
new file mode 100644
index 00000000000..99fe20278ea
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/RoutingDecisionCard.test.tsx
@@ -0,0 +1,136 @@
+import React from "react";
+import { render, screen } from "@testing-library/react";
+import { describe, it, expect } from "vitest";
+import { RoutingDecisionCard, type RoutingDecision } from "./RoutingDecisionCard";
+
+const heuristic: RoutingDecision = {
+ router_model_name: "smart-router",
+ router_type: "complexity",
+ routed_model: "claude-sonnet",
+ cause: "heuristic_scorer",
+ tier: "REASONING",
+ score: 0.82,
+ signals: ["long (900 tokens)", "code (python, function)"],
+ tier_boundaries: { simple_medium: 0.15, medium_complex: 0.35, complex_reasoning: 0.6 },
+};
+
+describe("RoutingDecisionCard", () => {
+ it("renders nothing when the request carried no routing decision", () => {
+ const { container } = render(<RoutingDecisionCard decision={undefined} />);
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it("explains a heuristic score against the boundaries that were in effect", () => {
+ render(<RoutingDecisionCard decision={heuristic} />);
+ expect(screen.getByText("smart-router")).toBeInTheDocument();
+ expect(screen.getByText("(Auto-Router v2)")).toBeInTheDocument();
+ expect(screen.getByText("REASONING")).toBeInTheDocument();
+ expect(screen.getByText("Heuristic scorer")).toBeInTheDocument();
+ expect(screen.getByText("0.82")).toBeInTheDocument();
+ expect(screen.getByText("(at or above 0.6, REASONING)")).toBeInTheDocument();
+ expect(screen.getByText("claude-sonnet")).toBeInTheDocument();
+ expect(screen.getByText("long (900 tokens)")).toBeInTheDocument();
+ });
+
+ it("uses the persisted boundary snapshot, not today's defaults", () => {
+ // Same score, boundaries the operator had configured lower: it lands in a
+ // different band, and the card must say so.
+ render(
+ <RoutingDecisionCard
+ decision={{
+ ...heuristic,
+ score: 0.4,
+ tier: "REASONING",
+ tier_boundaries: { simple_medium: 0.1, medium_complex: 0.2, complex_reasoning: 0.3 },
+ }}
+ />,
+ );
+ expect(screen.getByText("(at or above 0.3, REASONING)")).toBeInTheDocument();
+ });
+
+ it("labels a reasoning override and does not claim the score met a boundary", () => {
+ render(
+ <RoutingDecisionCard
+ decision={{
+ ...heuristic,
+ cause: "reasoning_override",
+ score: 0.2,
+ signals: ["reasoning (prove, step-by-step)"],
+ }}
+ />,
+ );
+ expect(screen.getByText("Heuristic, REASONING override (2 or more reasoning markers)")).toBeInTheDocument();
+ expect(screen.getByText("0.20")).toBeInTheDocument();
+ // The score did not decide this tier, so NO band explanation may render at all.
+ // Asserting the absence of one specific band would pass vacuously: 0.20 sits in
+ // the MEDIUM band, so the REASONING wording is absent either way.
+ expect(screen.queryByText(/SIMPLE|MEDIUM|COMPLEX|at or above/)).not.toBeInTheDocument();
+ });
+
+ it("names the judge model on the LLM classifier path and shows no score", () => {
+ render(
+ <RoutingDecisionCard
+ decision={{
+ router_model_name: "llm-router",
+ router_type: "complexity",
+ routed_model: "claude-sonnet",
+ cause: "llm_classifier",
+ tier: "REASONING",
+ classifier_model: "claude-haiku",
+ signals: ["llm-classifier:REASONING"],
+ }}
+ />,
+ );
+ expect(screen.getByText("LLM classifier (claude-haiku)")).toBeInTheDocument();
+ expect(screen.queryByText("Score")).not.toBeInTheDocument();
+ });
+
+ it("shows the keyword that fired a tier rule", () => {
+ render(
+ <RoutingDecisionCard
+ decision={{ ...heuristic, cause: "literal_keyword_match", matched_keyword: "deploy to k8s", score: undefined }}
+ />,
+ );
+ expect(screen.getByText('Keyword match: "deploy to k8s"')).toBeInTheDocument();
+ });
+
+ it("shows the escalation keyword", () => {
+ render(
+ <RoutingDecisionCard decision={{ ...heuristic, escalated: true, escalation_keyword: "LITELLM ESCALATE" }} />,
+ );
+ expect(screen.getByText('Yes, keyword "LITELLM ESCALATE"')).toBeInTheDocument();
+ });
+
+ it("still shows the ask when escalation had nowhere higher to go", () => {
+ // The tier did not move, but the row must not read like a request that never
+ // asked to escalate.
+ render(
+ <RoutingDecisionCard decision={{ ...heuristic, escalated: false, escalation_keyword: "LITELLM ESCALATE" }} />,
+ );
+ expect(screen.getByText('Requested via "LITELLM ESCALATE"; already at the highest tier')).toBeInTheDocument();
+ });
+
+ it("omits the escalation row when no escalation was requested", () => {
+ render(<RoutingDecisionCard decision={heuristic} />);
+ expect(screen.queryByText("Escalated")).not.toBeInTheDocument();
+ });
+
+ it("still shows a ceiling escalation after the keyword is redacted away", () => {
+ // Under message redaction the keyword is gone but `escalated` survives, so the
+ // row must still say an escalation was requested.
+ render(<RoutingDecisionCard decision={{ ...heuristic, escalated: false }} />);
+ expect(screen.getByText("Requested; already at the highest tier")).toBeInTheDocument();
+ });
+
+ it("does not claim the score chose the tier on a redacted override row", () => {
+ // `signals` is gone under redaction; the cause alone must suppress the band.
+ render(<RoutingDecisionCard decision={{ ...heuristic, cause: "reasoning_override", signals: undefined }} />);
+ expect(screen.queryByText(/SIMPLE|MEDIUM|COMPLEX|at or above/)).not.toBeInTheDocument();
+ expect(screen.getByText("Heuristic, REASONING override (2 or more reasoning markers)")).toBeInTheDocument();
+ });
+
+ it("falls back to the raw cause for a value this build does not know", () => {
+ render(<RoutingDecisionCard decision={{ cause: "some_future_cause", routed_model: "m" }} />);
+ expect(screen.getByText("some_future_cause")).toBeInTheDocument();
+ });
+});
diff --git a/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/RoutingDecisionCard.tsx b/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/RoutingDecisionCard.tsx
new file mode 100644
index 00000000000..77813971b78
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/view_logs/LogDetailsDrawer/RoutingDecisionCard.tsx
@@ -0,0 +1,192 @@
+"use client";
+
+import { Waypoints } from "lucide-react";
+
+import { Badge } from "@/components/ui/badge";
+import { cn } from "@/lib/cva.config";
+
+export interface RoutingDecisionTierBoundaries {
+ simple_medium?: number;
+ medium_complex?: number;
+ complex_reasoning?: number;
+}
+
+export interface RoutingDecision {
+ router_model_name?: string;
+ router_type?: string;
+ routed_model?: string;
+ cause?: string;
+ tier?: string;
+ request_type?: string;
+ score?: number;
+ signals?: string[];
+ matched_keyword?: string;
+ escalation_keyword?: string;
+ classifier_model?: string;
+ escalated?: boolean;
+ tier_boundaries?: RoutingDecisionTierBoundaries;
+}
+
+const ROUTER_TYPE_LABELS: Record<string, string> = {
+ complexity: "Auto-Router v2",
+ adaptive: "Adaptive router",
+ quality: "Quality router",
+};
+
+/**
+ * The tier the score alone would have produced, given the boundaries in effect when
+ * the decision was made. Rendered as the bracket that explains a score, so it must
+ * use the snapshot rather than today's config.
+ */
+function describeScoreAgainstBoundaries(score: number, boundaries?: RoutingDecisionTierBoundaries): string | null {
+ if (!boundaries) return null;
+ const {
+ simple_medium: simpleMedium,
+ medium_complex: mediumComplex,
+ complex_reasoning: complexReasoning,
+ } = boundaries;
+ if (simpleMedium === undefined || mediumComplex === undefined || complexReasoning === undefined) return null;
+
+ if (score < simpleMedium) return `below ${simpleMedium}, SIMPLE`;
+ if (score < mediumComplex) return `${simpleMedium} to ${mediumComplex}, MEDIUM`;
+ if (score < complexReasoning) return `${mediumComplex} to ${complexReasoning}, COMPLEX`;
+ return `at or above ${complexReasoning}, REASONING`;
+}
+
+function describeCause(decision: RoutingDecision): string {
+ const { cause, classifier_model: classifierModel, matched_keyword: matchedKeyword } = decision;
+
+ switch (cause) {
+ case "heuristic_scorer":
+ return "Heuristic scorer";
+ case "reasoning_override":
+ return "Heuristic, REASONING override (2 or more reasoning markers)";
+ case "llm_classifier":
+ return classifierModel ? `LLM classifier (${classifierModel})` : "LLM classifier";
+ case "literal_keyword_match":
+ return matchedKeyword ? `Keyword match: "${matchedKeyword}"` : "Keyword match";
+ case "semantic_keyword_match":
+ return "Semantic keyword match";
+ case "session_affinity_pin":
+ return "Pinned to session";
+ case "session_affinity_escalation":
+ return "Escalated from session pin";
+ case "quality_tier":
+ return "Quality tier mapping";
+ case "keyword":
+ return matchedKeyword ? `Keyword match: "${matchedKeyword}"` : "Keyword match";
+ case "bandit":
+ return "Adaptive bandit";
+ case "default_fallback":
+ return "Default model, no route matched";
+ default:
+ return cause ?? "Unknown";
+ }
+}
+
+/**
+ * A request can ask to escalate and get nowhere, when its tier is already the highest
+ * one configured. That row still has to say the caller asked, otherwise it reads as an
+ * ordinary route; it just must not claim a bump that did not happen. Only called when
+ * the request escalated or asked to, so there is no "did not escalate" case.
+ */
+function describeEscalation(escalated: boolean, keyword: string | undefined): string {
+ if (escalated) return keyword ? `Yes, keyword "${keyword}"` : "Yes";
+ return keyword ? `Requested via "${keyword}"; already at the highest tier` : "Requested; already at the highest tier";
+}
+
+function Row({ label, children }: { label: string; children: React.ReactNode }) {
+ return (
+ <div className="flex gap-3 py-1 text-sm">
+ <span className="w-28 shrink-0 text-muted-foreground">{label}</span>
+ <span className="min-w-0 break-words">{children}</span>
+ </div>
+ );
+}
+
+export function RoutingDecisionCard({
+ decision,
+ className,
+}: {
+ decision?: RoutingDecision | null;
+ className?: string;
+}) {
+ if (!decision || !decision.cause) return null;
+
+ const {
+ router_model_name: routerModelName,
+ router_type: routerType,
+ routed_model: routedModel,
+ tier,
+ request_type: requestType,
+ score,
+ signals,
+ escalated,
+ escalation_keyword: escalationKeyword,
+ tier_boundaries: tierBoundaries,
+ } = decision;
+
+ // On an override row the score did not decide the tier, so showing it against a
+ // boundary would claim something untrue. Keyed off the cause rather than a marker
+ // inside `signals`, which redaction can remove.
+ const scoreExplanation =
+ score !== undefined && decision.cause !== "reasoning_override"
+ ? describeScoreAgainstBoundaries(score, tierBoundaries)
+ : null;
+
+ return (
+ <div className={cn("mb-6 w-full max-w-full overflow-hidden rounded-lg bg-white shadow-sm", className)}>
+ <div className="border-b px-4 py-2.5 text-sm font-medium">Routing</div>
+ <div className="px-4 py-3">
+ {routerModelName && (
+ <div className="mb-2 flex items-center gap-2 text-sm font-medium">
+ <Waypoints size={14} aria-hidden />
+ <span>{routerModelName}</span>
+ {routerType && (
+ <span className="font-normal text-muted-foreground">
+ ({ROUTER_TYPE_LABELS[routerType] ?? routerType})
+ </span>
+ )}
+ </div>
+ )}
+
+ {tier && (
+ <Row label="Tier">
+ <Badge variant="secondary" className="font-normal">
+ {tier}
+ </Badge>
+ </Row>
+ )}
+
+ {requestType && <Row label="Request type">{requestType}</Row>}
+
+ <Row label="Decided by">{describeCause(decision)}</Row>
+
+ {score !== undefined && (
+ <Row label="Score">
+ <span className="tabular-nums">{score.toFixed(2)}</span>
+ {scoreExplanation && <span className="ml-2 text-muted-foreground">({scoreExplanation})</span>}
+ </Row>
+ )}
+
+ {routedModel && <Row label="Routed to">{routedModel}</Row>}
+
+ {escalated !== undefined && <Row label="Escalated">{describeEscalation(escalated, escalationKeyword)}</Row>}
+
+ {signals && signals.length > 0 && (
+ <Row label="Signals">
+ <span className="flex flex-wrap gap-1">
+ {signals.map((signal) => (
+ <Badge key={signal} variant="outline" className="font-normal">
+ {signal}
+ </Badge>
+ ))}
+ </span>
+ </Row>
+ )}
+ </div>
+ </div>
+ );
+}
+
+export default RoutingDecisionCard;