Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

feat(complexity_router): custom classifier plugins via classifier_type 'custom' (#37249)

tin-berri1f4acbb9241c
diff --git a/litellm/constants.py b/litellm/constants.py
index e73fba1cc9f..39a49e55f0d 100644
--- a/litellm/constants.py
+++ b/litellm/constants.py
@@ -1,5 +1,6 @@
import os
import sys
+from types import MappingProxyType
from typing import Final, Literal
from litellm.litellm_core_utils.env_utils import get_env_int, get_env_int_or_none
@@ -1764,3 +1765,7 @@ PTU_LAPSED_ALERT_LIMIT: Final[int] = 10
# one run delete a charge another just wrote. A stale row is hours old and a concurrent
# one is seconds old, so a few minutes separates them.
PTU_PRUNE_SKEW_GRACE_SECONDS: Final[int] = 300
+
+# Shared read-only empty mapping, for defaulting optional Mapping parameters without
+# constructing a fresh mutable dict at each call site.
+EMPTY_MAPPING: Final = MappingProxyType({})
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index 5d4a306a73e..d8fe7fce78f 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -657,6 +657,7 @@ from litellm.types.proxy.model_deprecation import (
)
from litellm.types.realtime import RealtimeQueryParams
from litellm.types.router import (
+ ClassifierPlugin,
DeploymentTypedDict,
RouterGeneralSettings,
RoutingPlugin,
@@ -4034,17 +4035,70 @@ def resolve_complexity_router_plugins(
) -> None:
"""
Resolves `complexity_router_config["plugins"]` dotted-path strings to live
- instances in place, via `resolve_routing_plugins`.
+ instances in place, via `resolve_routing_plugins`, and
+ `complexity_router_config["classifier_plugin"]` via `resolve_classifier_plugin`.
"""
plugin_paths: Final = complexity_router_config.get("plugins")
- if not isinstance(plugin_paths, list):
+ if isinstance(plugin_paths, list):
+ complexity_router_config["plugins"] = resolve_routing_plugins(
+ plugin_paths=plugin_paths,
+ config_file_path=config_file_path,
+ source_label=f"complexity_router_config.plugins on model {model_name!r}",
+ )
+
+ classifier_plugin_path: Final = complexity_router_config.get("classifier_plugin")
+ if isinstance(classifier_plugin_path, str):
+ resolved_classifier: Final = resolve_classifier_plugin(
+ plugin_path=classifier_plugin_path,
+ config_file_path=config_file_path,
+ source_label=f"complexity_router_config.classifier_plugin on model {model_name!r}",
+ )
+ complexity_router_config["classifier_plugin"] = resolved_classifier # rebind-ok: out-param, resolved in place
+
+
+def pin_complexity_router_model_id(model: dict) -> None: # mutable-ok: out-param, model_info is stamped in place
+ """
+ Stamps `model_info.id` from the raw litellm_params before plugin resolution swaps
+ dotted-path strings for live instances. `_delete_deployment` re-reads the raw config
+ and re-hashes these params to decide which ids the config wants served; an id the
+ Router derived from the resolved params would never match that hash, so the reconcile
+ would evict every plugin-bearing deployment one sync after startup.
+ """
+ litellm_params: Final = model.get("litellm_params")
+ if not isinstance(litellm_params, dict) or not isinstance(litellm_params.get("complexity_router_config"), dict):
return
+ model_info = model.get("model_info")
+ if not isinstance(model_info, dict):
+ model_info = {} # mutable-ok: fresh model_info stamped onto the raw yaml model dict
+ model["model_info"] = model_info # rebind-ok: out-param, stamped in place
+ if model_info.get("id") is None:
+ model_info["id"] = litellm.Router.generate_model_id(
+ model_group=model.get("model_name", ""),
+ litellm_params=litellm_params,
+ )
- complexity_router_config["plugins"] = resolve_routing_plugins(
- plugin_paths=plugin_paths,
- config_file_path=config_file_path,
- source_label=f"complexity_router_config.plugins on model {model_name!r}",
- )
+
+def resolve_classifier_plugin(
+ plugin_path: str,
+ config_file_path: str | None,
+ source_label: str,
+) -> ClassifierPlugin:
+ """
+ Resolves a classifier-plugin dotted path to a live `ClassifierPlugin` instance, with the
+ same load-time interface check `resolve_routing_plugins` applies to routing plugins: a
+ sync `def classify` passes the runtime_checkable isinstance and would only fail on the
+ first classified request, so reject it here where the error names the config key.
+ """
+ resolved: Final = get_instance_fn(value=plugin_path, config_file_path=config_file_path)
+ if not isinstance(resolved, ClassifierPlugin) or not inspect.iscoroutinefunction(
+ getattr(resolved, "classify", None)
+ ):
+ raise ValueError(
+ f"{source_label} entry {plugin_path!r} resolved to {resolved!r}, which does not "
+ "implement the ClassifierPlugin interface (an async `classify(context)` method). Fix "
+ "the referenced module before starting the proxy."
+ )
+ return resolved
def _swap_in_model_cost_map(new_model_cost_map: dict) -> int:
@@ -5266,6 +5320,7 @@ class ProxyConfig:
for k, v in model["litellm_params"].items():
if isinstance(v, str) and v.startswith("os.environ/"):
model["litellm_params"][k] = get_secret(v)
+ pin_complexity_router_model_id(model)
complexity_router_config = model["litellm_params"].get("complexity_router_config")
if isinstance(complexity_router_config, dict):
resolve_complexity_router_plugins(
@@ -5663,7 +5718,7 @@ class ProxyConfig:
model_id = model.get("model_info", {}).get("id", None)
if model_id is None:
## else - generate stable id's ##
- model_id = llm_router._generate_model_id(
+ model_id = llm_router.generate_model_id(
model_group=model["model_name"],
litellm_params=model["litellm_params"],
)
diff --git a/litellm/router.py b/litellm/router.py
index 8b9c4b0db1a..ba77dc40abc 100644
--- a/litellm/router.py
+++ b/litellm/router.py
@@ -3193,7 +3193,7 @@ class Router:
function_name=function_name,
)
model_group: Final = kwargs.get(metadata_variable_name, {}).get("model_group")
- _model_id: Final = self._generate_model_id(model_group=model_group, litellm_params=dynamic_litellm_params)
+ _model_id: Final = self.generate_model_id(model_group=model_group, litellm_params=dynamic_litellm_params)
original_model_id: Final = model_info.get("id")
model_info["id"] = _model_id
model_info["original_model_id"] = original_model_id
@@ -7570,13 +7570,14 @@ class Router:
@staticmethod
def _json_default_stable_id(value: object) -> str:
- """json.dumps default= for _generate_model_id: plain str() on an arbitrary
+ """json.dumps default= for generate_model_id: plain str() on an arbitrary
object (e.g. a RoutingPlugin instance) falls back to object.__repr__'s
`<module.Class object at 0x...>`, so the hash -- and deployment id -- would
change every restart. Use the class name instead, stable across restarts."""
return f"{type(value).__module__}.{type(value).__qualname__}"
- def _generate_model_id(self, model_group: str, litellm_params: dict):
+ @staticmethod
+ def generate_model_id(model_group: str, litellm_params: dict) -> str: # mutable-ok: hashed read-only
"""
Helper function to consistently generate the same id for a deployment
@@ -7591,14 +7592,14 @@ class Router:
if isinstance(k, str):
parts.append(k)
elif isinstance(k, dict):
- parts.append(json.dumps(k, default=self._json_default_stable_id))
+ parts.append(json.dumps(k, default=Router._json_default_stable_id))
else:
parts.append(str(k))
if isinstance(v, str):
parts.append(v)
elif isinstance(v, dict):
- parts.append(json.dumps(v, default=self._json_default_stable_id))
+ parts.append(json.dumps(v, default=Router._json_default_stable_id))
else:
parts.append(str(v))
@@ -8192,7 +8193,7 @@ class Router:
# check if model info has id
if "id" not in _model_info:
- _id = self._generate_model_id(_model_name, _litellm_params)
+ _id = self.generate_model_id(_model_name, _litellm_params)
_model_info["id"] = _id
if _litellm_params.get("organization", None) is not None and isinstance(
@@ -9750,7 +9751,7 @@ class Router:
if model_id is None:
model_name = model.get("model_name", "")
litellm_params = model.get("litellm_params", {})
- model_id = self._generate_model_id(model_name, litellm_params)
+ model_id = self.generate_model_id(model_name, litellm_params)
# Update the model_info in the original list
if "model_info" not in model:
model["model_info"] = {}
diff --git a/litellm/router_strategy/complexity_router/complexity_router.py b/litellm/router_strategy/complexity_router/complexity_router.py
index c829e6d9442..d16063b9bd4 100644
--- a/litellm/router_strategy/complexity_router/complexity_router.py
+++ b/litellm/router_strategy/complexity_router/complexity_router.py
@@ -26,8 +26,9 @@ from typing import TYPE_CHECKING, Any, Final, Literal, NamedTuple, cast
from pydantic import BaseModel, create_model
from litellm._logging import verbose_router_logger
-from litellm.constants import RETURN_RAW_MODEL_NAME_METADATA_KEY
+from litellm.constants import EMPTY_MAPPING, RETURN_RAW_MODEL_NAME_METADATA_KEY
from litellm.integrations.custom_logger import CustomLogger
+from litellm.litellm_core_utils.core_helpers import get_metadata_variable_name_from_kwargs
from litellm.litellm_core_utils.internal_call_metadata import forwarded_internal_call_metadata
from litellm.llms.base_llm.base_utils import type_to_response_format_param
from litellm.types.utils import (
@@ -655,6 +656,7 @@ class ClassificationOutcome(NamedTuple):
"heuristic_scorer",
"reasoning_override",
"llm_classifier",
+ "classifier_plugin",
"classifier_fallback",
"default_model_fallback",
]
@@ -1119,15 +1121,18 @@ class ComplexityRouter(CustomLogger):
system_prompt: str | None = None,
request_kwargs: dict[str, Any] | None = None,
messages: Sequence[Mapping[str, object]] | None = None,
+ raw_messages: list[dict[str, Any]] | None = None, # mutable-ok: same shape _run_routing_plugins receives
) -> ClassificationOutcome:
"""
Classify a prompt by complexity, using the LLM classifier when configured.
Falls back to the local heuristic scorer if classifier_type is "heuristic". If the LLM call
- fails, times out, or returns an unparseable response, the configured fallback_tier wins on a
- custom tier set, and classifier_fallback otherwise decides between the heuristic scorer and
- default_model. The outcome's `cause` reports which path actually ran.
+ or the classifier plugin fails, times out, or produces no usable tier, the configured
+ fallback_tier wins on a custom tier set, and classifier_fallback otherwise decides between
+ the heuristic scorer and default_model. The outcome's `cause` reports which path actually ran.
"""
+ if self.config.classifier_type == "custom":
+ return await self._classify_with_plugin(prompt, system_prompt, request_kwargs, raw_messages)
if self.config.classifier_type != "llm" or self.config.classifier_llm_config is None:
tier, score, signals, cause = self._score_and_classify(prompt, system_prompt)
return ClassificationOutcome(tier=tier, score=score, signals=signals, cause=cause)
@@ -1142,26 +1147,86 @@ class ComplexityRouter(CustomLogger):
classifier_cost=classifier_cost,
)
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 configured fallback path
- fallback_tier: Final = self.config.fallback_tier
- if fallback_tier is not None:
- verbose_router_logger.warning(
- "ComplexityRouter: LLM classifier failed (%s), routing to fallback_tier %s", e, fallback_tier
- )
- return ClassificationOutcome(
- tier=fallback_tier,
- score=None,
- signals=(f"classifier-fallback:{fallback_tier}",),
- cause="classifier_fallback",
+ return self._classifier_failure_outcome(f"LLM classifier failed ({e})", prompt, system_prompt)
+
+ def _classifier_failure_outcome(self, reason: str, prompt: str, system_prompt: str | None) -> ClassificationOutcome:
+ """The outcome when the LLM classifier or classifier plugin produced no usable tier:
+ fallback_tier on a custom tier set, classifier_fallback otherwise."""
+ fallback_tier: Final = self.config.fallback_tier
+ if fallback_tier is not None:
+ verbose_router_logger.warning("ComplexityRouter: %s, routing to fallback_tier %s", reason, fallback_tier)
+ return ClassificationOutcome(
+ tier=fallback_tier,
+ score=None,
+ signals=(f"classifier-fallback:{fallback_tier}",),
+ cause="classifier_fallback",
+ )
+ verbose_router_logger.warning(
+ "ComplexityRouter: %s, falling back to %s", reason, self.config.classifier_fallback
+ )
+ if self.config.classifier_fallback == "default_model":
+ return self._default_model_fallback_outcome()
+ 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_plugin(
+ self,
+ prompt: str,
+ system_prompt: str | None,
+ request_kwargs: dict[str, Any] | None, # mutable-ok: handed to resolve_structured_messages as-is
+ raw_messages: list[dict[str, Any]] | None, # mutable-ok: same shape _run_routing_plugins receives
+ ) -> ClassificationOutcome:
+ from litellm.litellm_core_utils.prompt_templates.factory import resolve_structured_messages
+ from litellm.types.router import RoutingContext
+
+ plugin: Final = self.config.classifier_plugin
+ if plugin is None:
+ return self._classifier_failure_outcome("classifier_plugin is not set", prompt, system_prompt)
+ kwargs: Final = request_kwargs if request_kwargs is not None else EMPTY_MAPPING
+ pools: Final = self._tier_pools()
+ try:
+ context: Final = RoutingContext(
+ raw_messages=raw_messages or (),
+ structured_messages=resolve_structured_messages(
+ messages=raw_messages, request_kwargs=request_kwargs or EMPTY_MAPPING
)
- verbose_router_logger.warning(
- "ComplexityRouter: LLM classifier failed (%s), falling back to %s",
- e,
- self.config.classifier_fallback,
+ or (),
+ candidate_models=tuple(model for pool in pools.values() for model in pool),
+ metadata=kwargs.get(get_metadata_variable_name_from_kwargs(kwargs)) or EMPTY_MAPPING,
)
- if self.config.classifier_fallback == "default_model":
- return self._default_model_fallback_outcome()
- tier, score, signals, cause = self._score_and_classify(prompt, system_prompt)
- return ClassificationOutcome(tier=tier, score=score, signals=signals, cause=cause)
+ verdict: Final = await asyncio.wait_for(
+ plugin.classify(context), timeout=self.config.classifier_plugin_timeout_ms / 1000
+ )
+ except asyncio.TimeoutError:
+ return self._classifier_failure_outcome(
+ f"classifier plugin timed out after {self.config.classifier_plugin_timeout_ms}ms", prompt, system_prompt
+ )
+ except Exception as e: # noqa: BLE001 -- an operator hook can fail in arbitrary ways (network, bug); any failure must fall back rather than fail the request
+ return self._classifier_failure_outcome(f"classifier plugin failed ({e})", prompt, system_prompt)
+ if verdict is None:
+ return self._classifier_failure_outcome("classifier plugin declined to classify", prompt, system_prompt)
+ if not isinstance(verdict, str):
+ return self._classifier_failure_outcome(
+ f"classifier plugin returned a non-string verdict of type {type(verdict).__name__}",
+ prompt,
+ system_prompt,
+ )
+ tier: Final = self.config.resolve_classified_tier(verdict)
+ if tier is None:
+ return self._classifier_failure_outcome(
+ f"classifier plugin returned unknown tier {verdict!r}", prompt, system_prompt
+ )
+ tier_key: Final = _tier_name(tier)
+ if not pools.get(tier_key):
+ return self._classifier_failure_outcome(
+ f"classifier plugin returned tier {tier_key!r}, which has no models configured", prompt, system_prompt
+ )
+ return ClassificationOutcome(
+ tier=tier,
+ score=None,
+ signals=(f"classifier-plugin:{tier_key}",),
+ cause="classifier_plugin",
+ )
def _default_model_fallback_outcome(self) -> ClassificationOutcome:
"""The classifier-failed outcome for classifier_fallback='default_model'.
@@ -1402,7 +1467,7 @@ class ComplexityRouter(CustomLogger):
from litellm.types.router import RoutingContext
tier_key: Final = _tier_name(tier)
- metadata_key: Final = "litellm_metadata" if "litellm_metadata" in request_kwargs else "metadata"
+ metadata_key: Final = get_metadata_variable_name_from_kwargs(request_kwargs)
pool: Final = tuple(self._tier_pools().get(tier_key, ()))
if not pool:
# Nothing for the plugins to filter. Falling through would raise the
@@ -2218,7 +2283,9 @@ class ComplexityRouter(CustomLogger):
),
)
- outcome: Final = await self.aclassify(user_message, system_prompt, request_kwargs, resolved_messages)
+ outcome: Final = await self.aclassify(
+ user_message, system_prompt, request_kwargs, resolved_messages, raw_messages=messages
+ )
tier, score, signals = outcome.tier, outcome.score, outcome.signals
classified_tier: Final = tier
if escalation_keyword is not None:
diff --git a/litellm/router_strategy/complexity_router/config.py b/litellm/router_strategy/complexity_router/config.py
index 20329de34e2..6d43199c948 100644
--- a/litellm/router_strategy/complexity_router/config.py
+++ b/litellm/router_strategy/complexity_router/config.py
@@ -10,7 +10,7 @@ from typing import Final, Literal
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
-from litellm.types.router import AdaptiveRouterWeights, RoutingPlugin
+from litellm.types.router import AdaptiveRouterWeights, ClassifierPlugin, RoutingPlugin
class ComplexityTier(str, Enum):
@@ -434,7 +434,7 @@ class ComplexityRouterConfig(BaseModel):
"becomes that tier's rubric bullet; entries named after a built-in tier may omit the "
"description and inherit the built-in criteria. List order is ascending severity and "
"decides which tier wins when several keyword_tier_rules match. Requires classifier_type "
- "'llm', a fallback_tier, and `tiers` keys matching the defined names exactly. Escalation, "
+ "'llm' or 'custom', a fallback_tier, and `tiers` keys matching the defined names exactly. Escalation, "
"adaptive selection, session affinity, plugins, tier_labels, and the calibration-example "
"rubric presets are unavailable with a custom tier set: the first four are built on the "
"built-in tier ladder, and the last two rename or exemplify tiers the set replaces."
@@ -535,14 +535,31 @@ class ComplexityRouterConfig(BaseModel):
)
# Classifier strategy
- classifier_type: Literal["heuristic", "llm"] = Field(
+ classifier_type: Literal["heuristic", "llm", "custom"] = Field(
default="heuristic",
- description="Classification strategy: local regex/keyword scoring, or an LLM call",
+ description="Classification strategy: local regex/keyword scoring, an LLM call, or a custom classifier plugin",
)
classifier_llm_config: ClassifierLLMConfig | None = Field(
default=None,
description="Configuration for the LLM classifier; required when classifier_type is 'llm'",
)
+ classifier_plugin: ClassifierPlugin | None = Field(
+ default=None,
+ description=(
+ "Custom classifier deciding the tier; required when classifier_type is 'custom'. In the proxy "
+ "config, a dotted path to a ClassifierPlugin instance (resolved at startup, like plugins). Its "
+ "classify(context) receives the request messages and metadata (caller identity included) and "
+ "returns the name of the tier to route to, or None to decline and let classifier_fallback decide."
+ ),
+ )
+ classifier_plugin_timeout_ms: int = Field(
+ default=3000,
+ gt=0,
+ description=(
+ "Timeout budget for the classifier plugin call, in milliseconds. On expiry the fallback "
+ "path decides the tier. Only applies when classifier_type is 'custom'."
+ ),
+ )
classifier_fallback: Literal["heuristic", "default_model"] = Field(
default="heuristic",
@@ -553,7 +570,7 @@ class ComplexityRouterConfig(BaseModel):
"which is what a classifier on some other taxonomy wants: a prompt that grades data "
"sensitivity has no use for a complexity score, and scoring one produces a tier unrelated to "
"what the operator configured. Requires default_model when set to 'default_model'. Only "
- "applies when classifier_type is 'llm'."
+ "applies when classifier_type is 'llm' or 'custom'."
),
)
@@ -795,9 +812,16 @@ class ComplexityRouterConfig(BaseModel):
return self
@model_validator(mode="after")
- def _validate_llm_classifier_config(self) -> "ComplexityRouterConfig":
+ def _validate_classifier_config(self) -> "ComplexityRouterConfig":
if self.classifier_type == "llm" and self.classifier_llm_config is None:
raise ValueError("classifier_llm_config is required when classifier_type is 'llm'")
+ if self.classifier_type == "custom" and self.classifier_plugin is None:
+ raise ValueError("classifier_plugin is required when classifier_type is 'custom'")
+ if self.classifier_plugin is not None and self.classifier_type != "custom":
+ raise ValueError(
+ f"classifier_plugin is set but classifier_type is {self.classifier_type!r}; "
+ "the plugin would never run. Set classifier_type 'custom' or remove classifier_plugin"
+ )
return self
@field_validator("fallback_tier", "classification_prompt")
@@ -916,9 +940,10 @@ class ComplexityRouterConfig(BaseModel):
)
if duplicated:
raise ValueError(f"tier_definitions names must be unique (case-insensitive): {', '.join(duplicated)}")
- if self.classifier_type != "llm":
+ if self.classifier_type == "heuristic":
raise ValueError(
- "tier_definitions requires classifier_type 'llm': the heuristic scorer only produces the built-in tiers"
+ "tier_definitions requires classifier_type 'llm' or 'custom': the heuristic scorer only "
+ "produces the built-in tiers"
)
conflicts: Final = self._tier_definition_conflicts()
if conflicts:
diff --git a/litellm/types/management_endpoints/auto_router_endpoints.py b/litellm/types/management_endpoints/auto_router_endpoints.py
index 61601dd31eb..9461297feca 100644
--- a/litellm/types/management_endpoints/auto_router_endpoints.py
+++ b/litellm/types/management_endpoints/auto_router_endpoints.py
@@ -22,6 +22,9 @@ class RequestComplexityRouterConfig(ComplexityRouterConfig):
"""
plugins: None = Field(default=None, description="Not settable over HTTP; routing plugins are runtime objects")
+ classifier_plugin: None = Field( # pyright: ignore[reportIncompatibleVariableOverride] # narrowing to None is the point: runtime objects are not settable over HTTP
+ default=None, description="Not settable over HTTP; the classifier plugin is a runtime object"
+ )
class AutoRouterRoutingTestRequest(BaseModel):
diff --git a/litellm/types/router.py b/litellm/types/router.py
index f3f9276e6ba..6df757ef98c 100644
--- a/litellm/types/router.py
+++ b/litellm/types/router.py
@@ -956,6 +956,21 @@ class RoutingPlugin(Protocol):
async def run(self, context: RoutingContext) -> RoutingContext: ...
+@runtime_checkable
+class ClassifierPlugin(Protocol):
+ """Interface a custom classifier must implement to run as the complexity router's classifier_type='custom'.
+
+ `classify` returns the name of the tier the request belongs to (a built-in tier value or label,
+ or a tier_definitions name), or None to decline and let classifier_fallback decide.
+
+ The context's `candidate_models` is an informational snapshot of every tier's models, unlike
+ the narrowing surface RoutingPlugin filters: the returned tier decides the pool, so mutating
+ the list is a no-op.
+ """
+
+ async def classify(self, context: RoutingContext) -> str | None: ...
+
+
class RequestType(str, enum.Enum):
"""Fixed v0 taxonomy. User-extensible types come in v1."""
diff --git a/litellm/types/utils.py b/litellm/types/utils.py
index efa87203fb6..1b6730a734f 100644
--- a/litellm/types/utils.py
+++ b/litellm/types/utils.py
@@ -2767,11 +2767,14 @@ RoutingDecisionCause = Literal[
# meant anything that filtered `signals` silently changed what the row claimed.
"reasoning_override",
"llm_classifier",
- # The LLM classifier failed on a router with an operator-defined tier set, so the
- # request routed to the configured fallback_tier without being classified.
+ # The operator's classifier plugin (classifier_type 'custom') decided the tier.
+ "classifier_plugin",
+ # The LLM classifier or classifier plugin failed on a router with an operator-defined
+ # tier set, so the request routed to the configured fallback_tier without being classified.
"classifier_fallback",
- # The LLM classifier failed and classifier_fallback is 'default_model', so the request
- # went to default_model without being classified. Distinct from "default_fallback",
+ # The LLM classifier or classifier plugin failed and classifier_fallback is
+ # 'default_model', so the request went to default_model without being classified.
+ # Distinct from "default_fallback",
# which is a tier having no model configured rather than classification not happening.
"default_model_fallback",
"literal_keyword_match",
diff --git a/tests/local_testing/test_router.py b/tests/local_testing/test_router.py
index 2ee1aee9710..af1a052e86d 100644
--- a/tests/local_testing/test_router.py
+++ b/tests/local_testing/test_router.py
@@ -1303,7 +1303,7 @@ def test_consistent_model_id():
"""
- For a given model group + litellm params, assert the model id is always the same
- Test on `_generate_model_id`
+ Test on `generate_model_id`
Test on `set_model_list`
@@ -1317,11 +1317,11 @@ def test_consistent_model_id():
"stream_timeout": 0.001,
}
- id1 = Router()._generate_model_id(
+ id1 = Router().generate_model_id(
model_group=model_group, litellm_params=litellm_params
)
- id2 = Router()._generate_model_id(
+ id2 = Router().generate_model_id(
model_group=model_group, litellm_params=litellm_params
)
diff --git a/tests/router_unit_tests/test_router_helper_utils.py b/tests/router_unit_tests/test_router_helper_utils.py
index c883890f5f6..c3db9e67f9c 100644
--- a/tests/router_unit_tests/test_router_helper_utils.py
+++ b/tests/router_unit_tests/test_router_helper_utils.py
@@ -1841,8 +1841,8 @@ def test_init_auto_router_deployment_duplicate_model_name(mock_auto_router, mode
router.init_auto_router_deployment(deployment)
-def test_generate_model_id_with_deployment_model_name(model_list):
- """Test that _generate_model_id works correctly with deployment model_name and handles None values properly"""
+def testgenerate_model_id_with_deployment_model_name(model_list):
+ """Test that generate_model_id works correctly with deployment model_name and handles None values properly"""
router = Router(model_list=model_list)
# Test case 1: Normal case with valid model_group and litellm_params
@@ -1854,7 +1854,7 @@ def test_generate_model_id_with_deployment_model_name(model_list):
}
try:
- result = router._generate_model_id(
+ result = router.generate_model_id(
model_group=model_group, litellm_params=litellm_params
)
assert isinstance(result, str)
@@ -1865,7 +1865,7 @@ def test_generate_model_id_with_deployment_model_name(model_list):
# Test case 2: Edge case with None model_group (this should fail as expected - our fix prevents this from happening)
try:
- result = router._generate_model_id(
+ result = router.generate_model_id(
model_group=None, litellm_params=litellm_params
)
pytest.fail(
@@ -1888,7 +1888,7 @@ def test_generate_model_id_with_deployment_model_name(model_list):
}
try:
- result = router._generate_model_id(
+ result = router.generate_model_id(
model_group=model_group, litellm_params=litellm_params_with_none_key
)
assert isinstance(result, str)
@@ -1899,7 +1899,7 @@ def test_generate_model_id_with_deployment_model_name(model_list):
# Test case 4: Edge case with empty litellm_params
try:
- result = router._generate_model_id(model_group=model_group, litellm_params={})
+ result = router.generate_model_id(model_group=model_group, litellm_params={})
assert isinstance(result, str)
assert len(result) > 0
print(f"✓ Success with empty litellm_params: {result}")
@@ -1907,15 +1907,15 @@ def test_generate_model_id_with_deployment_model_name(model_list):
pytest.fail(f"Failed with empty litellm_params: {e}")
# Test case 5: Verify that the same inputs produce the same result (deterministic)
- result1 = router._generate_model_id(
+ result1 = router.generate_model_id(
model_group=model_group, litellm_params=litellm_params
)
- result2 = router._generate_model_id(
+ result2 = router.generate_model_id(
model_group=model_group, litellm_params=litellm_params
)
assert result1 == result2, "Model ID generation should be deterministic"
- print("✓ All _generate_model_id tests passed!")
+ print("✓ All generate_model_id tests passed!")
def test_handle_clientside_credential_with_deployment_model_name(model_list):
@@ -1945,13 +1945,13 @@ def test_handle_clientside_credential_with_deployment_model_name(model_list):
# Test that the method doesn't fail when metadata is empty
try:
- # This would normally call _generate_model_id internally
+ # This would normally call generate_model_id internally
# We're testing that the fix prevents the TypeError
model_group = deployment["model_name"] # This is what our fix does
assert model_group == "gpt-4.1"
- # Verify that _generate_model_id works with this model_group
- result = router._generate_model_id(
+ # Verify that generate_model_id works with this model_group
+ result = router.generate_model_id(
model_group=model_group, litellm_params=dynamic_litellm_params
)
assert isinstance(result, str)
diff --git a/tests/test_litellm/proxy/management_endpoints/test_auto_router_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_auto_router_endpoints.py
index 049d6ddb183..77149457e82 100644
--- a/tests/test_litellm/proxy/management_endpoints/test_auto_router_endpoints.py
+++ b/tests/test_litellm/proxy/management_endpoints/test_auto_router_endpoints.py
@@ -286,6 +286,13 @@ def test_semantic_matching_without_an_embedding_model_is_rejected():
_request("what is 2+2", semantic_keyword_matching=True)
+def test_classifier_plugin_is_not_settable_over_http():
+ """classifier_plugin holds a live runtime object, closed off like `plugins`; a plugin-mode
+ config is therefore unrepresentable in a request body."""
+ with pytest.raises(ValidationError):
+ _request("what is 2+2", classifier_type="custom", classifier_plugin="my_module.instance")
+
+
class TestAutoRouterBenchmarks:
from litellm.proxy.management_endpoints.auto_router_endpoints import _SessionAggRow
diff --git a/tests/test_litellm/proxy/proxy_server/test_proxy_config.py b/tests/test_litellm/proxy/proxy_server/test_proxy_config.py
index 17dd486763d..f31f67c317a 100644
--- a/tests/test_litellm/proxy/proxy_server/test_proxy_config.py
+++ b/tests/test_litellm/proxy/proxy_server/test_proxy_config.py
@@ -188,6 +188,77 @@ def test_resolve_complexity_router_plugins_rejects_synchronous_run_method(tmp_pa
)
+def test_resolve_complexity_router_plugins_resolves_classifier_plugin_dotted_path(tmp_path):
+ plugin_file = tmp_path / "my_classifier.py"
+ plugin_file.write_text(
+ "class _Classifier:\n"
+ " async def classify(self, context):\n"
+ " return 'SIMPLE'\n"
+ "\n"
+ "my_classifier_instance = _Classifier()\n"
+ )
+ config: dict[str, Any] = {
+ "classifier_type": "custom",
+ "classifier_plugin": "my_classifier.my_classifier_instance",
+ }
+
+ resolve_complexity_router_plugins(
+ model_name="smart-router",
+ complexity_router_config=config,
+ config_file_path=str(tmp_path / "config.yaml"),
+ )
+
+ assert hasattr(config["classifier_plugin"], "classify")
+ assert type(config["classifier_plugin"]).__name__ == "_Classifier"
+
+
+def test_resolve_complexity_router_plugins_rejects_non_classifier_object(tmp_path):
+ plugin_file = tmp_path / "bad_classifier.py"
+ plugin_file.write_text("not_a_classifier = object()\n")
+ config: dict[str, Any] = {"classifier_plugin": "bad_classifier.not_a_classifier"}
+
+ with pytest.raises(ValueError, match="does not implement the ClassifierPlugin interface"):
+ resolve_complexity_router_plugins(
+ model_name="smart-router",
+ complexity_router_config=config,
+ config_file_path=str(tmp_path / "config.yaml"),
+ )
+
+
+def test_resolve_complexity_router_plugins_rejects_synchronous_classify_method(tmp_path):
+ """A synchronous `classify` passes the runtime_checkable isinstance and would only fail on
+ the first classified request, so reject it at config load like the sync-run case above."""
+ plugin_file = tmp_path / "sync_classifier.py"
+ plugin_file.write_text(
+ "class _SyncClassifier:\n"
+ " def classify(self, context):\n"
+ " return 'SIMPLE'\n"
+ "\n"
+ "sync_classifier_instance = _SyncClassifier()\n"
+ )
+ config: dict[str, Any] = {"classifier_plugin": "sync_classifier.sync_classifier_instance"}
+
+ with pytest.raises(ValueError, match="does not implement the ClassifierPlugin interface"):
+ resolve_complexity_router_plugins(
+ model_name="smart-router",
+ complexity_router_config=config,
+ config_file_path=str(tmp_path / "config.yaml"),
+ )
+
+
+def test_resolve_complexity_router_plugins_leaves_live_classifier_instance_alone():
+ class _Classifier:
+ async def classify(self, context):
+ return "SIMPLE"
+
+ instance = _Classifier()
+ config: dict[str, Any] = {"classifier_plugin": instance}
+ resolve_complexity_router_plugins(
+ model_name="smart-router", complexity_router_config=config, config_file_path=None
+ )
+ assert config["classifier_plugin"] is instance
+
+
# ---------------------------------------------------------------------------
# resolve_routing_plugins
# ---------------------------------------------------------------------------
diff --git a/tests/test_litellm/proxy/test_update_llm_router_resilience.py b/tests/test_litellm/proxy/test_update_llm_router_resilience.py
index a7dc9c1783e..d6ebfde1091 100644
--- a/tests/test_litellm/proxy/test_update_llm_router_resilience.py
+++ b/tests/test_litellm/proxy/test_update_llm_router_resilience.py
@@ -154,7 +154,7 @@ class TestDeleteDeploymentResilience:
# Router has a model ID that's not in DB or config -> should be deleted
mock_router.get_model_ids.return_value = ["db-id-1", "stale-id"]
mock_router.delete_deployment.return_value = True
- mock_router._generate_model_id = MagicMock(return_value="config-id-1")
+ mock_router.generate_model_id = MagicMock(return_value="config-id-1")
with (
patch.object(
@@ -182,3 +182,111 @@ class TestDeleteDeploymentResilience:
"the returned set must be what the db + config still want, so a caller can "
f"tell that eviction apart from a deployment that went missing; got {result}"
)
+
+
+class TestDeleteDeploymentKeepsPluginConfigModels:
+ """Regression: _delete_deployment re-reads the raw config and hashes litellm_params to
+ compute the ids the config wants served. The Router used to derive plugin-bearing
+ deployment ids from the RESOLVED params (dotted paths swapped for live instances), so
+ the reconcile computed different ids and evicted every plugin-bearing auto-router one
+ sync after startup. load_config now pins model_info.id from the raw params before
+ resolution, so both sides hash the same input and the reconcile needs no resolution."""
+
+ @staticmethod
+ def _write_plugin_module(tmp_path):
+ (tmp_path / "rig_classifier.py").write_text(
+ "class _Classifier:\n"
+ " async def classify(self, context):\n"
+ " return 'SIMPLE'\n"
+ "\n"
+ "class _Narrower:\n"
+ " async def run(self, context):\n"
+ " return context\n"
+ "\n"
+ "classifier_instance = _Classifier()\n"
+ "narrower_instance = _Narrower()\n"
+ )
+
+ @staticmethod
+ def _raw_model_entry():
+ return {
+ "model_name": "smart-router",
+ "litellm_params": {
+ "model": "auto_router/complexity_router",
+ "complexity_router_default_model": "gpt-4o-mini",
+ "complexity_router_config": {
+ "classifier_type": "custom",
+ "classifier_plugin": "rig_classifier.classifier_instance",
+ "plugins": ["rig_classifier.narrower_instance"],
+ "tiers": {"SIMPLE": "gpt-4o-mini"},
+ },
+ },
+ }
+
+ @pytest.mark.asyncio
+ async def test_plugin_bearing_config_model_survives_reconcile_and_stale_ids_still_evict(self, tmp_path):
+ import copy
+
+ from litellm import Router
+ from litellm.proxy.proxy_server import (
+ pin_complexity_router_model_id,
+ resolve_complexity_router_plugins,
+ )
+
+ self._write_plugin_module(tmp_path)
+ config_file_path = str(tmp_path / "config.yaml")
+
+ resolved_entry = copy.deepcopy(self._raw_model_entry())
+ pin_complexity_router_model_id(resolved_entry)
+ resolve_complexity_router_plugins(
+ model_name="smart-router",
+ complexity_router_config=resolved_entry["litellm_params"]["complexity_router_config"],
+ config_file_path=config_file_path,
+ )
+ router = Router(
+ model_list=[
+ {"model_name": "gpt-4o-mini", "litellm_params": {"model": "gpt-4o-mini"}},
+ resolved_entry,
+ {
+ "model_name": "stale-model",
+ "litellm_params": {"model": "gpt-4o"},
+ "model_info": {"id": "stale-id"},
+ },
+ ]
+ )
+ assert "smart-router" in router.model_names
+ assert "stale-model" in router.model_names
+
+ raw_config = {
+ "model_list": [
+ {"model_name": "gpt-4o-mini", "litellm_params": {"model": "gpt-4o-mini"}},
+ self._raw_model_entry(),
+ ]
+ }
+ proxy_config = ProxyConfig()
+ with (
+ patch.object(proxy_config, "get_config", new_callable=AsyncMock, return_value=raw_config),
+ patch("litellm.proxy.proxy_server.llm_router", router),
+ patch("litellm.proxy.proxy_server.user_config_file_path", config_file_path),
+ patch("litellm.proxy.proxy_server.premium_user", False),
+ ):
+ result = await proxy_config._delete_deployment(db_models=[])
+
+ assert result is not None
+ assert "smart-router" in router.model_names
+ assert "stale-model" not in router.model_names
+
+ def test_pin_respects_an_explicit_model_id(self):
+ from litellm.proxy.proxy_server import pin_complexity_router_model_id
+
+ entry = self._raw_model_entry()
+ entry["model_info"] = {"id": "operator-pinned"}
+ pin_complexity_router_model_id(entry)
+ assert entry["model_info"]["id"] == "operator-pinned"
+
+ def test_pin_is_a_noop_without_a_complexity_router_config(self):
+ from litellm.proxy.proxy_server import pin_complexity_router_model_id
+
+ entry = {"model_name": "gpt-4o-mini", "litellm_params": {"model": "gpt-4o-mini"}}
+ pin_complexity_router_model_id(entry)
+ assert "model_info" not in entry
diff --git a/tests/test_litellm/router_strategy/test_complexity_router.py b/tests/test_litellm/router_strategy/test_complexity_router.py
index 7034ebc9bd7..e1e8d9553b3 100644
--- a/tests/test_litellm/router_strategy/test_complexity_router.py
+++ b/tests/test_litellm/router_strategy/test_complexity_router.py
@@ -4127,6 +4127,315 @@ class TestRoutingPlugins:
assert spy.call_count == 2
+class _FixedTierClassifier:
+ """Classifier plugin double returning a fixed verdict; records the context it received."""
+
+ def __init__(self, verdict):
+ self.verdict = verdict
+ self.seen_context = None
+
+ async def classify(self, context):
+ self.seen_context = context
+ return self.verdict
+
+
+class _TeamTierClassifier:
+ async def classify(self, context):
+ team = context.metadata.get("user_api_key_team_id")
+ return "REASONING" if team == "team-premium" else "SIMPLE"
+
+
+class _RaisingClassifier:
+ async def classify(self, context):
+ raise RuntimeError("lookup service down")
+
+
+class _SlowClassifier:
+ async def classify(self, context):
+ await asyncio.sleep(5)
+ return "SIMPLE"
+
+
+def _plugin_router(mock_router_instance, plugin, **config_overrides):
+ config = {
+ "tiers": {
+ "SIMPLE": "gpt-4o-mini",
+ "MEDIUM": "gpt-4o",
+ "COMPLEX": "claude-sonnet-4-20250514",
+ "REASONING": "o1-preview",
+ },
+ "classifier_type": "custom",
+ "classifier_plugin": plugin,
+ **config_overrides,
+ }
+ return ComplexityRouter(
+ model_name="test-complexity-router",
+ litellm_router_instance=mock_router_instance,
+ complexity_router_config=config,
+ )
+
+
+class TestClassifierPluginConfig:
+ """Config validation for classifier_type='custom'."""
+
+ def test_plugin_classifier_type_requires_plugin(self):
+ with pytest.raises(ValidationError, match="classifier_plugin is required"):
+ ComplexityRouterConfig(classifier_type="custom")
+
+ def test_classifier_plugin_without_plugin_mode_raises(self):
+ """A wired hook that would silently never run is a config error, not a no-op."""
+ with pytest.raises(ValidationError, match="would never run"):
+ ComplexityRouterConfig(classifier_plugin=_FixedTierClassifier("SIMPLE"))
+
+ def test_plugin_mode_tolerates_stale_llm_config(self):
+ """Switching classifier_type llm -> plugin must not force deleting classifier_llm_config,
+ matching how classifier_type='heuristic' tolerates it."""
+ config = ComplexityRouterConfig(
+ classifier_type="custom",
+ classifier_plugin=_FixedTierClassifier("SIMPLE"),
+ classifier_llm_config={"model": "haiku-classifier"},
+ )
+ assert config.classifier_type == "custom"
+
+ def test_plugin_mode_composes_with_adaptive(self):
+ """adaptive replaces selection, not classification, so a classifier plugin is allowed
+ where narrowing `plugins` are rejected (their pools bypass the bandit)."""
+ config = ComplexityRouterConfig(
+ classifier_type="custom",
+ classifier_plugin=_FixedTierClassifier("SIMPLE"),
+ adaptive=True,
+ )
+ assert config.adaptive is True
+
+ def test_plugin_mode_composes_with_tier_definitions(self):
+ config = ComplexityRouterConfig(
+ classifier_type="custom",
+ classifier_plugin=_FixedTierClassifier("cheap"),
+ tiers={"cheap": "gpt-4o-mini", "premium": "o1-preview"},
+ tier_definitions=[
+ {"name": "cheap", "description": "routine asks"},
+ {"name": "premium", "description": "hard asks"},
+ ],
+ fallback_tier="cheap",
+ )
+ assert config.tier_names() == ("cheap", "premium")
+
+ def test_tier_definitions_still_reject_heuristic(self):
+ with pytest.raises(ValidationError, match="heuristic scorer only"):
+ ComplexityRouterConfig(
+ classifier_type="heuristic",
+ tiers={"cheap": "gpt-4o-mini", "premium": "o1-preview"},
+ tier_definitions=[
+ {"name": "cheap", "description": "routine asks"},
+ {"name": "premium", "description": "hard asks"},
+ ],
+ fallback_tier="cheap",
+ )
+
+
+class TestClassifierPlugin:
+ """classifier_type='custom': an operator hook decides the tier."""
+
+ @pytest.mark.asyncio
+ async def test_plugin_verdict_decides_tier_without_scorer_or_llm(self, mock_router_instance):
+ mock_router_instance.acompletion = AsyncMock()
+ router = _plugin_router(mock_router_instance, _FixedTierClassifier("COMPLEX"))
+ outcome = await router.aclassify("hello")
+ assert outcome.cause == "classifier_plugin"
+ assert outcome.tier == ComplexityTier.COMPLEX
+ assert outcome.score is None
+ assert outcome.signals == ("classifier-plugin:COMPLEX",)
+ mock_router_instance.acompletion.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_plugin_verdict_resolves_case_insensitively(self, mock_router_instance):
+ router = _plugin_router(mock_router_instance, _FixedTierClassifier("reasoning"))
+ outcome = await router.aclassify("hello")
+ assert outcome.tier == ComplexityTier.REASONING
+ assert outcome.cause == "classifier_plugin"
+
+ @pytest.mark.asyncio
+ async def test_plugin_reads_caller_identity_from_request_metadata(self, mock_router_instance):
+ router = _plugin_router(mock_router_instance, _TeamTierClassifier())
+ premium = await router.aclassify("hi", request_kwargs={"metadata": {"user_api_key_team_id": "team-premium"}})
+ basic = await router.aclassify(
+ "hi", request_kwargs={"litellm_metadata": {"user_api_key_team_id": "team-basic"}}
+ )
+ assert premium.tier == ComplexityTier.REASONING
+ assert basic.tier == ComplexityTier.SIMPLE
+
+ @pytest.mark.asyncio
+ async def test_plugin_context_carries_messages_and_all_tier_models(self, mock_router_instance):
+ plugin = _FixedTierClassifier("SIMPLE")
+ router = _plugin_router(mock_router_instance, plugin)
+ raw = [{"role": "user", "content": [{"type": "text", "text": "hi"}]}]
+ await router.aclassify("hi", messages=[{"role": "user", "content": "hi"}], raw_messages=raw)
+ assert plugin.seen_context.raw_messages == raw
+ assert plugin.seen_context.structured_messages == raw
+ assert plugin.seen_context.candidate_models == [
+ "gpt-4o-mini",
+ "gpt-4o",
+ "claude-sonnet-4-20250514",
+ "o1-preview",
+ ]
+
+ @pytest.mark.asyncio
+ async def test_plugin_runs_without_messages(self, mock_router_instance):
+ """A prompt-only call (no message list) still reaches the plugin with an empty context."""
+ plugin = _FixedTierClassifier("COMPLEX")
+ router = _plugin_router(mock_router_instance, plugin)
+ outcome = await router.aclassify("hello", raw_messages=None)
+ assert outcome.cause == "classifier_plugin"
+ assert plugin.seen_context.raw_messages == []
+ assert plugin.seen_context.structured_messages == []
+
+ @pytest.mark.asyncio
+ async def test_plugin_decline_falls_back_to_heuristic(self, mock_router_instance):
+ router = _plugin_router(mock_router_instance, _FixedTierClassifier(None))
+ outcome = await router.aclassify("what is 2+2?")
+ assert outcome.cause == "heuristic_scorer"
+
+ @pytest.mark.asyncio
+ async def test_plugin_error_falls_back_to_heuristic(self, mock_router_instance):
+ router = _plugin_router(mock_router_instance, _RaisingClassifier())
+ outcome = await router.aclassify("what is 2+2?")
+ assert outcome.cause == "heuristic_scorer"
+
+ @pytest.mark.asyncio
+ async def test_plugin_timeout_falls_back_to_heuristic(self, mock_router_instance):
+ router = _plugin_router(mock_router_instance, _SlowClassifier(), classifier_plugin_timeout_ms=20)
+ outcome = await router.aclassify("what is 2+2?")
+ assert outcome.cause == "heuristic_scorer"
+
+ @pytest.mark.asyncio
+ async def test_plugin_non_string_verdict_falls_back_to_heuristic(self, mock_router_instance):
+ """An operator hook returning a non-string must fall back, not raise into the request."""
+ router = _plugin_router(mock_router_instance, _FixedTierClassifier(42))
+ outcome = await router.aclassify("what is 2+2?")
+ assert outcome.cause == "heuristic_scorer"
+
+ @pytest.mark.asyncio
+ async def test_plugin_unknown_tier_falls_back_to_heuristic(self, mock_router_instance):
+ router = _plugin_router(mock_router_instance, _FixedTierClassifier("galactic"))
+ outcome = await router.aclassify("what is 2+2?")
+ assert outcome.cause == "heuristic_scorer"
+
+ @pytest.mark.asyncio
+ async def test_plugin_tier_without_pool_falls_back(self, mock_router_instance):
+ """A built-in tier the operator gave no models is a decline, not a later routing error."""
+ router = ComplexityRouter(
+ model_name="test-complexity-router",
+ litellm_router_instance=mock_router_instance,
+ complexity_router_config={
+ "tiers": {"SIMPLE": "gpt-4o-mini"},
+ "classifier_type": "custom",
+ "classifier_plugin": _FixedTierClassifier("COMPLEX"),
+ },
+ )
+ outcome = await router.aclassify("what is 2+2?")
+ assert outcome.cause == "heuristic_scorer"
+
+ @pytest.mark.asyncio
+ async def test_plugin_failure_with_default_model_fallback(self, mock_router_instance):
+ router = _plugin_router(
+ mock_router_instance,
+ _RaisingClassifier(),
+ classifier_fallback="default_model",
+ default_model="gpt-4o-mini",
+ )
+ outcome = await router.aclassify("hello")
+ assert outcome.cause == "default_model_fallback"
+
+ @pytest.mark.asyncio
+ async def test_plugin_with_custom_tiers_routes_defined_name(self, mock_router_instance):
+ router = _plugin_router(
+ mock_router_instance,
+ _FixedTierClassifier("premium"),
+ tiers={"cheap": "gpt-4o-mini", "premium": "o1-preview"},
+ tier_definitions=[
+ {"name": "cheap", "description": "routine asks"},
+ {"name": "premium", "description": "hard asks"},
+ ],
+ fallback_tier="cheap",
+ )
+ outcome = await router.aclassify("hello")
+ assert outcome.tier == "premium"
+ assert outcome.cause == "classifier_plugin"
+ assert outcome.signals == ("classifier-plugin:premium",)
+
+ @pytest.mark.asyncio
+ async def test_plugin_failure_with_custom_tiers_routes_fallback_tier(self, mock_router_instance):
+ router = _plugin_router(
+ mock_router_instance,
+ _RaisingClassifier(),
+ tiers={"cheap": "gpt-4o-mini", "premium": "o1-preview"},
+ tier_definitions=[
+ {"name": "cheap", "description": "routine asks"},
+ {"name": "premium", "description": "hard asks"},
+ ],
+ fallback_tier="cheap",
+ )
+ outcome = await router.aclassify("hello")
+ assert outcome.tier == "cheap"
+ assert outcome.cause == "classifier_fallback"
+ assert outcome.signals == ("classifier-fallback:cheap",)
+
+ @pytest.mark.asyncio
+ async def test_hook_records_plugin_cause_without_score(self, mock_router_instance):
+ router = _plugin_router(mock_router_instance, _TeamTierClassifier())
+ response = await router.async_pre_routing_hook(
+ model="test-complexity-router",
+ request_kwargs={"metadata": {"user_api_key_team_id": "team-premium"}},
+ messages=[{"role": "user", "content": "prove P != NP"}],
+ )
+ decision = response.routing_decision
+ assert decision["cause"] == "classifier_plugin"
+ assert decision["tier"] == "REASONING"
+ assert decision["routed_model"] == "o1-preview"
+ assert response.model == "o1-preview"
+ assert "score" not in decision
+ assert "tier_boundaries" not in decision
+
+ @pytest.mark.asyncio
+ async def test_plugin_composes_with_narrowing_plugins(self, mock_router_instance):
+ class _BlockO1:
+ async def run(self, context):
+ context.candidate_models = [m for m in context.candidate_models if m != "o1-preview"]
+ return context
+
+ router = _plugin_router(
+ mock_router_instance,
+ _FixedTierClassifier("REASONING"),
+ tiers={
+ "SIMPLE": "gpt-4o-mini",
+ "MEDIUM": "gpt-4o",
+ "COMPLEX": "claude-sonnet-4-20250514",
+ "REASONING": ["o1-preview", "claude-sonnet-4-20250514"],
+ },
+ plugins=[_BlockO1()],
+ )
+ response = await router.async_pre_routing_hook(
+ model="test-complexity-router",
+ request_kwargs={},
+ messages=[{"role": "user", "content": "prove P != NP"}],
+ )
+ assert response.model == "claude-sonnet-4-20250514"
+ assert response.routing_decision["cause"] == "classifier_plugin"
+
+ def test_classifier_plugin_alone_keeps_tier_pinning_enabled(self, mock_router_instance):
+ """Narrowing plugins suppress session pinning (a policy verdict can change between turns);
+ a classifier plugin picks among operator-approved tiers, so pinning must stay on."""
+ pinning = _plugin_router(mock_router_instance, _FixedTierClassifier("SIMPLE"), session_affinity=True)
+ suppressed = _plugin_router(
+ mock_router_instance,
+ _FixedTierClassifier("SIMPLE"),
+ session_affinity=True,
+ plugins=[_DummyPlugin()],
+ )
+ assert pinning._uses_tier_pin is True
+ assert suppressed._uses_tier_pin is False
+
+
class TestEscalationKeywords:
"""Test user-triggered escalation: a keyword in the prompt bumps the resolved tier
one step higher so a user can force a stronger model when unhappy with results."""
diff --git a/tests/test_litellm/router_strategy/test_router_routing_plugins.py b/tests/test_litellm/router_strategy/test_router_routing_plugins.py
index 78ed71f5ffd..293af36080a 100644
--- a/tests/test_litellm/router_strategy/test_router_routing_plugins.py
+++ b/tests/test_litellm/router_strategy/test_router_routing_plugins.py
@@ -221,7 +221,7 @@ def test_filter_by_routing_plugin_candidates_narrows_and_raises_when_empty():
def test_json_default_stable_id_is_stable_across_instances():
- """_generate_model_id's json.dumps `default=` fallback must not embed an object's
+ """generate_model_id's json.dumps `default=` fallback must not embed an object's
memory address (e.g. plain str() on an object with no custom __repr__ falls back
to object.__repr__'s `<module.Class object at 0x...>`) -- that would make the
deployment id churn on every process restart for any deployment whose
@@ -232,7 +232,7 @@ def test_json_default_stable_id_is_stable_across_instances():
assert router._json_default_stable_id(LanguageDetector()) != router._json_default_stable_id(TenantPolicy())
-def test_generate_model_id_is_stable_when_litellm_params_contain_a_plugin_instance():
+def testgenerate_model_id_is_stable_when_litellm_params_contain_a_plugin_instance():
"""End-to-end: a deployment id built from litellm_params containing a routing
plugin instance (e.g. complexity_router_config.plugins) must be identical across
separate calls, not just non-crashing."""
@@ -242,8 +242,8 @@ def test_generate_model_id_is_stable_when_litellm_params_contain_a_plugin_instan
"complexity_router_config": {"plugins": [LanguageDetector()]},
}
- id1 = router._generate_model_id("smart-router", litellm_params)
- id2 = router._generate_model_id(
+ id1 = router.generate_model_id("smart-router", litellm_params)
+ id2 = router.generate_model_id(
"smart-router",
{
"model": "auto_router/complexity_router",
diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.ts
index a3a461edca0..3a129890267 100644
--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts
+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts
@@ -32300,20 +32300,31 @@ export interface components {
classifier_context_window_size: number;
/**
* Classifier Fallback
- * @description What classifies the request when the LLM classifier errors, times out, or returns an unparseable response. 'heuristic' runs the local complexity scorer, which is right when the classifier grades complexity too. 'default_model' skips scoring and routes to default_model, which is what a classifier on some other taxonomy wants: a prompt that grades data sensitivity has no use for a complexity score, and scoring one produces a tier unrelated to what the operator configured. Requires default_model when set to 'default_model'. Only applies when classifier_type is 'llm'.
+ * @description What classifies the request when the LLM classifier errors, times out, or returns an unparseable response. 'heuristic' runs the local complexity scorer, which is right when the classifier grades complexity too. 'default_model' skips scoring and routes to default_model, which is what a classifier on some other taxonomy wants: a prompt that grades data sensitivity has no use for a complexity score, and scoring one produces a tier unrelated to what the operator configured. Requires default_model when set to 'default_model'. Only applies when classifier_type is 'llm' or 'custom'.
* @default heuristic
* @enum {string}
*/
classifier_fallback: "heuristic" | "default_model";
/** @description Configuration for the LLM classifier; required when classifier_type is 'llm' */
classifier_llm_config?: components["schemas"]["ClassifierLLMConfig"] | null;
+ /**
+ * Classifier Plugin
+ * @description Not settable over HTTP; the classifier plugin is a runtime object
+ */
+ classifier_plugin?: null;
+ /**
+ * Classifier Plugin Timeout Ms
+ * @description Timeout budget for the classifier plugin call, in milliseconds. On expiry the fallback path decides the tier. Only applies when classifier_type is 'custom'.
+ * @default 3000
+ */
+ classifier_plugin_timeout_ms: number;
/**
* Classifier Type
- * @description Classification strategy: local regex/keyword scoring, or an LLM call
+ * @description Classification strategy: local regex/keyword scoring, an LLM call, or a custom classifier plugin
* @default heuristic
* @enum {string}
*/
- classifier_type: "heuristic" | "llm";
+ classifier_type: "heuristic" | "llm" | "custom";
/**
* Code Keywords
* @description Keywords indicating code-related content
@@ -32436,7 +32447,7 @@ export interface components {
};
/**
* Tier Definitions
- * @description Operator-defined tier set replacing the built-in SIMPLE/MEDIUM/COMPLEX/REASONING. Each entry's name becomes a value the LLM classifier can return and its description becomes that tier's rubric bullet; entries named after a built-in tier may omit the description and inherit the built-in criteria. List order is ascending severity and decides which tier wins when several keyword_tier_rules match. Requires classifier_type 'llm', a fallback_tier, and `tiers` keys matching the defined names exactly. Escalation, adaptive selection, session affinity, plugins, tier_labels, and the calibration-example rubric presets are unavailable with a custom tier set: the first four are built on the built-in tier ladder, and the last two rename or exemplify tiers the set replaces.
+ * @description Operator-defined tier set replacing the built-in SIMPLE/MEDIUM/COMPLEX/REASONING. Each entry's name becomes a value the LLM classifier can return and its description becomes that tier's rubric bullet; entries named after a built-in tier may omit the description and inherit the built-in criteria. List order is ascending severity and decides which tier wins when several keyword_tier_rules match. Requires classifier_type 'llm' or 'custom', a fallback_tier, and `tiers` keys matching the defined names exactly. Escalation, adaptive selection, session affinity, plugins, tier_labels, and the calibration-example rubric presets are unavailable with a custom tier set: the first four are built on the built-in tier ladder, and the last two rename or exemplify tiers the set replaces.
*/
tier_definitions?: components["schemas"]["TierDefinition"][] | null;
/**
@@ -33362,7 +33373,7 @@ export interface components {
* Cause
* @enum {string}
*/
- cause?: "heuristic_scorer" | "reasoning_override" | "llm_classifier" | "classifier_fallback" | "default_model_fallback" | "literal_keyword_match" | "semantic_keyword_match" | "plan_mode" | "session_affinity_pin" | "session_affinity_escalation" | "default_fallback" | "keyword" | "quality_tier" | "bandit";
+ cause?: "heuristic_scorer" | "reasoning_override" | "llm_classifier" | "classifier_plugin" | "classifier_fallback" | "default_model_fallback" | "literal_keyword_match" | "semantic_keyword_match" | "plan_mode" | "session_affinity_pin" | "session_affinity_escalation" | "default_fallback" | "keyword" | "quality_tier" | "bandit";
/** Classifier Cost */
classifier_cost?: number;
/** Classifier Model */