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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
feat(router): resolve auto-router routing plugins from proxy YAML config (#33251)
Krrish Dholakiab96460608d6f
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex a0b07ece4dd..b04f12a0e90 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -556,6 +556,7 @@ from litellm.types.router import (from litellm.types.router import ModelInfo as RouterModelInfofrom litellm.types.router import (RouterGeneralSettings,+ RoutingPlugin,SearchToolTypedDict,updateDeployment,)@@ -3660,6 +3661,45 @@ def _attach_redis_usage_cache(redis_cache: RedisCache, enable_redis_auth_cache:litellm_config_cache.redis_cache = redis_cache+def resolve_complexity_router_plugins(+ model_name: str,+ complexity_router_config: dict,+ config_file_path: str | None,+) -> None:+ """+ Resolves `complexity_router_config["plugins"]` dotted-path strings to live+ instances via `get_instance_fn` (the same convention `litellm_settings.callbacks`+ uses), in place. Raises at config-load time if a path resolves to something that+ doesn't implement `RoutingPlugin`, rather than deferring to a confusing+ `AttributeError` on the first request that reaches the plugin pipeline.+ """+ plugin_paths = complexity_router_config.get("plugins")+ if not isinstance(plugin_paths, list):+ return++ resolved_plugins = [+ get_instance_fn(value=plugin_path, config_file_path=config_file_path)+ if isinstance(plugin_path, str)+ else plugin_path+ for plugin_path in plugin_paths+ ]+ for plugin_path, resolved_plugin in zip(plugin_paths, resolved_plugins):+ # `@runtime_checkable` only checks that `run` exists as an attribute, not that+ # it's a coroutine function -- a synchronous `def run(self, context)` would pass+ # isinstance() here and only fail at request time with a confusing `TypeError:+ # object RoutingContext can't be used in 'await' expression`.+ if not isinstance(resolved_plugin, RoutingPlugin) or not inspect.iscoroutinefunction(+ getattr(resolved_plugin, "run", None)+ ):+ raise ValueError(+ f"complexity_router_config.plugins entry {plugin_path!r} on model {model_name!r} "+ f"resolved to {resolved_plugin!r}, which does not implement the RoutingPlugin "+ "interface (an async `run(context)` method). Fix the referenced module before "+ "starting the proxy."+ )+ complexity_router_config["plugins"] = resolved_plugins++class ProxyConfig:"""Abstraction class on top of config loading/updating logic. Gives us one place to control all config updating logic.@@ -4720,6 +4760,13 @@ 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)+ complexity_router_config = model["litellm_params"].get("complexity_router_config")+ if isinstance(complexity_router_config, dict):+ resolve_complexity_router_plugins(+ model_name=model.get("model_name", ""),+ complexity_router_config=complexity_router_config,+ config_file_path=config_file_path,+ )print(f"\033[32m {model.get('model_name', '')}\033[0m") # noqa: T201litellm_model_name = model["litellm_params"]["model"]litellm_model_api_base = model["litellm_params"].get("api_base", None)diff --git a/litellm/router.py b/litellm/router.pyindex 6e8127110cc..3d49d7048e4 100644--- a/litellm/router.py+++ b/litellm/router.py@@ -7284,6 +7284,14 @@ class Router:raise ereturn returned_healthy_deployments+ @staticmethod+ def _json_default_stable_id(value: object) -> str:+ """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):"""Helper function to consistently generate the same id for a deployment@@ -7299,14 +7307,14 @@ class Router:if isinstance(k, str):parts.append(k)elif isinstance(k, dict):- parts.append(json.dumps(k))+ parts.append(json.dumps(k, default=self._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))+ parts.append(json.dumps(v, default=self._json_default_stable_id))else:parts.append(str(v))diff --git a/litellm/router_strategy/complexity_router/complexity_router.py b/litellm/router_strategy/complexity_router/complexity_router.pyindex bd3b300b558..eb0f74a58e7 100644--- a/litellm/router_strategy/complexity_router/complexity_router.py+++ b/litellm/router_strategy/complexity_router/complexity_router.py@@ -468,6 +468,38 @@ class ComplexityRouter(CustomLogger):def _tier_pools(self) -> dict[str, list[str]]:return {tier: (models if isinstance(models, list) else [models]) for tier, models in self.config.tiers.items()}+ async def _pick_model_for_tier(+ self,+ tier: ComplexityTier,+ raw_messages: list[dict[str, Any]] | None,+ resolved_messages: list[dict[str, Any]] | None,+ request_kwargs: dict,+ ) -> str:+ if not self.config.plugins:+ return self.get_model_for_tier(tier)++ from litellm.types.router import RoutingContext++ tier_key = tier.value+ metadata_key = "litellm_metadata" if "litellm_metadata" in request_kwargs else "metadata"+ context = RoutingContext(+ raw_messages=raw_messages or [],+ structured_messages=resolved_messages or [],+ candidate_models=list(self._tier_pools().get(tier_key, [])),+ metadata=request_kwargs.get(metadata_key) or {},+ )+ for plugin in self.config.plugins:+ context = await plugin.run(context)++ if not context.candidate_models:+ # A plugin narrowing a tier to zero candidates is a policy decision (e.g. no+ # model this tenant's budget allows) -- falling back to default_model here+ # (which was never checked against the plugins) would let that policy be+ # silently bypassed. Raise instead, matching the Router-level plugin+ # pipeline's own fail-closed behavior for the same situation.+ raise ValueError(f"No candidate models left for tier {tier_key} after routing-plugin filtering")+ return self._pick_from_tier_value(context.candidate_models, tier_key)+def _ensure_adaptive_router(self) -> Any | None:if not self.config.adaptive:return None@@ -861,10 +893,16 @@ class ComplexityRouter(CustomLogger):When `session_affinity` is enabled and a session_id is resolvable on the request,pins the model chosen on the session's first turn and reuses it for every laterturn, skipping classification entirely. Otherwise delegates to `_classify_and_route`.++ Skipped entirely when `plugins` are configured: reusing a stale pin would bypass+ the plugin pipeline on every turn after the first, since a pinned model was never+ re-checked against a policy plugin whose decision can change between turns (e.g. a+ budget plugin, once the session's spend crosses its cap)."""from litellm.types.router import PreRoutingHookResponse- session_id = self._get_session_id_from_request_kwargs(request_kwargs) if self.config.session_affinity else None+ use_session_affinity = self.config.session_affinity and not self.config.plugins+ session_id = self._get_session_id_from_request_kwargs(request_kwargs) if use_session_affinity else Nonecache_key = self._get_session_affinity_cache_key(session_id, request_kwargs) if session_id is not None else Noneif cache_key is not None:@@ -947,14 +985,26 @@ class ComplexityRouter(CustomLogger):if user_message is None:verbose_router_logger.debug("ComplexityRouter: No user message found, routing to default model")+ if not self.config.plugins and self.config.default_model:+ # No plugins configured: preserve the pre-existing default_model-first+ # priority exactly (changing it would be a silent behavior change for+ # every non-plugin user, not just a security fix).+ routed_model = self.config.default_model+ else:+ # Plugins configured: default_model must never bypass them, so it's not+ # checked here at all -- _pick_model_for_tier -> get_model_for_tier still+ # falls back to it (after the MEDIUM tier) once the plugin pipeline runs.+ routed_model = await self._pick_model_for_tier(+ ComplexityTier.MEDIUM, messages, resolved_messages, request_kwargs+ )return PreRoutingHookResponse(- model=self.config.default_model or self.get_model_for_tier(ComplexityTier.MEDIUM),+ model=routed_model,messages=messages if has_original_messages else None,)override_tier = await self._resolve_keyword_tier_override(user_message, request_kwargs)if override_tier is not None:- routed_model = self.get_model_for_tier(override_tier)+ routed_model = await self._pick_model_for_tier(override_tier, messages, resolved_messages, request_kwargs)cause = "semantic_keyword_match" if self.config.semantic_keyword_matching else "literal_keyword_match"verbose_router_logger.info(f"ComplexityRouter: routing decision cause={cause}, "@@ -980,7 +1030,7 @@ class ComplexityRouter(CustomLogger):f"signals={signals}, routed_model={routed_model}")else:- routed_model = self.get_model_for_tier(tier)+ 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}"diff --git a/litellm/router_strategy/complexity_router/config.py b/litellm/router_strategy/complexity_router/config.pyindex e4bd36505e6..b7ffa2866f2 100644--- a/litellm/router_strategy/complexity_router/config.py+++ b/litellm/router_strategy/complexity_router/config.py@@ -10,7 +10,7 @@ from typing import Literalfrom pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator-from litellm.types.router import AdaptiveRouterWeights+from litellm.types.router import AdaptiveRouterWeights, RoutingPluginclass ComplexityTier(str, Enum):@@ -375,7 +375,12 @@ class ComplexityRouterConfig(BaseModel):description="TTL for the session affinity pin; refreshed on every cache hit",)- model_config = ConfigDict(extra="allow") # Allow additional fields+ plugins: list[RoutingPlugin] | None = Field(+ default=None,+ description="RoutingPlugin instances that narrow the classified tier's candidate models before selection",+ )++ model_config = ConfigDict(extra="allow", arbitrary_types_allowed=True) # Allow additional fields@field_validator("tiers", mode="before")@classmethod@@ -421,6 +426,15 @@ class ComplexityRouterConfig(BaseModel):raise ValueError("keyword_tier_rules must be non-empty when semantic_keyword_matching is enabled")return self+ @model_validator(mode="after")+ def _validate_plugins_adaptive_combo(self) -> "ComplexityRouterConfig":+ if self.plugins and self.adaptive:+ raise ValueError(+ "plugins and adaptive=True cannot both be set: adaptive's bandit selection doesn't yet "+ "consume plugin-narrowed candidate pools. Disable adaptive or remove plugins."+ )+ return self+# Combined default configDEFAULT_COMPLEXITY_CONFIG = ComplexityRouterConfig()diff --git a/litellm/types/router.py b/litellm/types/router.pyindex 3bedd97c20c..d62c613bf57 100644--- a/litellm/types/router.py+++ b/litellm/types/router.py@@ -9,7 +9,7 @@ from typing import Any, Dict, List, Literal, Optional, Tuple, Union, get_type_hiimport httpxfrom pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator-from typing_extensions import Protocol, Required, TypedDict+from typing_extensions import Protocol, Required, TypedDict, runtime_checkablefrom litellm._uuid import uuid@@ -852,6 +852,7 @@ class RoutingContext(BaseModel):signals: dict[str, Any] = Field(default_factory=dict)+@runtime_checkableclass RoutingPlugin(Protocol):"""Interface a custom routing plugin must implement to run in `Router(plugins=[...])`."""diff --git a/tests/test_litellm/proxy/proxy_server/test_proxy_config.py b/tests/test_litellm/proxy/proxy_server/test_proxy_config.pyindex 98b270788dc..45d35419680 100644--- a/tests/test_litellm/proxy/proxy_server/test_proxy_config.py+++ b/tests/test_litellm/proxy/proxy_server/test_proxy_config.py@@ -21,6 +21,7 @@ from litellm.proxy.proxy_server import (_is_remote_module_url,_scrub_db_overlay_remote_module_loads,_scrub_guardrail_inner,+ resolve_complexity_router_plugins,)from .conftest import normalize@@ -112,6 +113,78 @@ def test__scrub_db_overlay_remote_module_loads_invalid_non_dict_returns_input():assert _scrub_db_overlay_remote_module_loads("litellm_settings", "raw") == "raw"+# ---------------------------------------------------------------------------+# resolve_complexity_router_plugins+# ---------------------------------------------------------------------------+++def test_resolve_complexity_router_plugins_no_plugins_key_is_a_noop():+ config: Dict[str, Any] = {"tiers": {"SIMPLE": "gpt-4o-mini"}}+ resolve_complexity_router_plugins(+ model_name="smart-router", complexity_router_config=config, config_file_path=None+ )+ assert config == {"tiers": {"SIMPLE": "gpt-4o-mini"}}+++def test_resolve_complexity_router_plugins_resolves_dotted_path_to_live_instance(tmp_path):+ plugin_file = tmp_path / "my_plugin.py"+ plugin_file.write_text(+ "class _Plugin:\n"+ " async def run(self, context):\n"+ " return context\n"+ "\n"+ "my_plugin_instance = _Plugin()\n"+ )+ config: Dict[str, Any] = {"plugins": ["my_plugin.my_plugin_instance"]}++ resolve_complexity_router_plugins(+ model_name="smart-router",+ complexity_router_config=config,+ config_file_path=str(tmp_path / "config.yaml"),+ )++ assert len(config["plugins"]) == 1+ assert hasattr(config["plugins"][0], "run")+ assert type(config["plugins"][0]).__name__ == "_Plugin"+++def test_resolve_complexity_router_plugins_rejects_non_routing_plugin_object(tmp_path):+ plugin_file = tmp_path / "bad_plugin.py"+ plugin_file.write_text("not_a_plugin = object()\n")+ config: Dict[str, Any] = {"plugins": ["bad_plugin.not_a_plugin"]}++ with pytest.raises(ValueError, match="does not implement the RoutingPlugin 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_run_method(tmp_path):+ """Regression: @runtime_checkable only checks that `run` exists as an attribute,+ not that it's a coroutine function. A plugin with a synchronous `run` passes a bare+ isinstance() check and would only fail at request time with a confusing+ `TypeError: object RoutingContext can't be used in 'await' expression`. Reported+ by Greptile on PR #33251."""+ plugin_file = tmp_path / "sync_plugin.py"+ plugin_file.write_text(+ "class _SyncPlugin:\n"+ " def run(self, context):\n"+ " return context\n"+ "\n"+ "sync_plugin_instance = _SyncPlugin()\n"+ )+ config: Dict[str, Any] = {"plugins": ["sync_plugin.sync_plugin_instance"]}++ with pytest.raises(ValueError, match="does not implement the RoutingPlugin interface"):+ resolve_complexity_router_plugins(+ model_name="smart-router",+ complexity_router_config=config,+ config_file_path=str(tmp_path / "config.yaml"),+ )++# ---------------------------------------------------------------------------# ProxyConfig.__init__# ---------------------------------------------------------------------------diff --git a/tests/test_litellm/router_strategy/test_complexity_router.py b/tests/test_litellm/router_strategy/test_complexity_router.pyindex f7c9f343f80..41dc7269372 100644--- a/tests/test_litellm/router_strategy/test_complexity_router.py+++ b/tests/test_litellm/router_strategy/test_complexity_router.py@@ -2700,3 +2700,250 @@ class TestSessionAffinity:spy_aclassify.assert_not_called()assert second.model == "cheap"assert request_kwargs_2["metadata"]["adaptive_router_chosen_model"] == "cheap"+++class _DummyPlugin:+ async def run(self, context):+ return context+++class TestRoutingPlugins:+ """Test the `complexity_router_config.plugins` field: narrows the classified+ tier's candidate pool before a model is picked. Discussion:+ https://github.com/BerriAI/litellm/discussions/32168"""++ @pytest.mark.asyncio+ async def test_plugin_narrows_tier_candidates(self, mock_router_instance):+ class ExcludeGpt4oMini:+ async def run(self, context):+ context.candidate_models = [m for m in context.candidate_models if m != "gpt-4o-mini"]+ return context++ router = ComplexityRouter(+ model_name="test-complexity-router",+ litellm_router_instance=mock_router_instance,+ complexity_router_config={+ "tiers": {"SIMPLE": ["gpt-4o-mini", "gpt-4o-nano"]},+ "plugins": [ExcludeGpt4oMini()],+ },+ )+ result = await router.async_pre_routing_hook(+ model="test-model",+ request_kwargs={},+ messages=[{"role": "user", "content": "hi"}],+ )+ assert result is not None+ assert result.model == "gpt-4o-nano"++ @pytest.mark.asyncio+ async def test_plugin_narrowing_to_zero_raises_even_with_default_model_configured(self, mock_router_instance):+ """Regression: default_model must never be used as an escape hatch around a+ plugin's narrowing decision -- it was never checked against the plugins, so+ falling back to it would let a tenant/budget policy be silently bypassed.+ Reported by Veria AI on PR #33251."""++ class BlockEverything:+ async def run(self, context):+ context.candidate_models = []+ return context++ router = ComplexityRouter(+ model_name="test-complexity-router",+ litellm_router_instance=mock_router_instance,+ complexity_router_config={+ "tiers": {"SIMPLE": "gpt-4o-mini"},+ "default_model": "gpt-4o-fallback",+ "plugins": [BlockEverything()],+ },+ )+ with pytest.raises(ValueError, match="No candidate models left for tier"):+ await router.async_pre_routing_hook(+ model="test-model",+ request_kwargs={},+ messages=[{"role": "user", "content": "hi"}],+ )++ @pytest.mark.asyncio+ async def test_plugin_narrowing_to_zero_without_default_model_raises(self, mock_router_instance):+ class BlockEverything:+ async def run(self, context):+ context.candidate_models = []+ return context++ router = ComplexityRouter(+ model_name="test-complexity-router",+ litellm_router_instance=mock_router_instance,+ complexity_router_config={+ "tiers": {"SIMPLE": "gpt-4o-mini"},+ "plugins": [BlockEverything()],+ },+ )+ with pytest.raises(ValueError, match="No candidate models left for tier"):+ await router.async_pre_routing_hook(+ model="test-model",+ request_kwargs={},+ messages=[{"role": "user", "content": "hi"}],+ )++ @pytest.mark.asyncio+ async def test_plugin_receives_metadata_from_request_kwargs(self, mock_router_instance):+ captured = {}++ class CaptureMetadata:+ async def run(self, context):+ captured.update(context.metadata)+ return context++ router = ComplexityRouter(+ model_name="test-complexity-router",+ litellm_router_instance=mock_router_instance,+ complexity_router_config={+ "tiers": {"SIMPLE": "gpt-4o-mini"},+ "plugins": [CaptureMetadata()],+ },+ )+ await router.async_pre_routing_hook(+ model="test-model",+ request_kwargs={"metadata": {"tenant": "acme-corp"}},+ messages=[{"role": "user", "content": "hi"}],+ )+ assert captured.get("tenant") == "acme-corp"++ @pytest.mark.asyncio+ async def test_plugin_applies_to_keyword_tier_override(self, mock_router_instance):+ """A policy plugin must not be bypassable via the keyword_tier_rules override path."""++ class ExcludeGpt4oMini:+ async def run(self, context):+ context.candidate_models = [m for m in context.candidate_models if m != "gpt-4o-mini"]+ return context++ router = ComplexityRouter(+ model_name="test-complexity-router",+ litellm_router_instance=mock_router_instance,+ complexity_router_config={+ "tiers": {"SIMPLE": ["gpt-4o-mini", "gpt-4o-nano"]},+ "keyword_tier_rules": [{"keywords": ["hello"], "tier": "SIMPLE"}],+ "plugins": [ExcludeGpt4oMini()],+ },+ )+ result = await router.async_pre_routing_hook(+ model="test-model",+ request_kwargs={},+ messages=[{"role": "user", "content": "hello there"}],+ )+ assert result is not None+ assert result.model == "gpt-4o-nano"++ @pytest.mark.asyncio+ async def test_plugin_applies_to_no_user_message_default_tier_path(self, mock_router_instance):+ """Regression: `self.config.default_model or await self._pick_model_for_tier(...)`+ short-circuited on a truthy default_model, so the no-user-message path never ran+ the plugin pipeline at all when default_model was configured. A policy plugin+ must not be bypassable via this path either. Reported by Veria AI on PR #33251."""++ class ExcludeDefaultModel:+ async def run(self, context):+ context.candidate_models = [m for m in context.candidate_models if m != "gpt-4o-default"]+ return context++ router = ComplexityRouter(+ model_name="test-complexity-router",+ litellm_router_instance=mock_router_instance,+ complexity_router_config={+ "tiers": {"MEDIUM": ["gpt-4o-default", "gpt-4o-nano"]},+ "default_model": "gpt-4o-default",+ "plugins": [ExcludeDefaultModel()],+ },+ )+ result = await router.async_pre_routing_hook(+ model="test-model",+ request_kwargs={},+ messages=[+ {"role": "system", "content": "You are helpful."},+ {"role": "assistant", "content": "Hello!"},+ ],+ )+ assert result is not None+ assert result.model == "gpt-4o-nano"++ @pytest.mark.asyncio+ async def test_no_user_message_prefers_default_model_over_medium_tier_without_plugins(+ self, mock_router_instance+ ):+ """Regression: without plugins configured, the no-user-message path must keep its+ pre-existing default_model-first priority over the MEDIUM tier exactly as before --+ closing the plugin-bypass gap must not silently flip model selection for the (much+ larger) population of users who don't use plugins at all. Flagged by Greptile on+ PR #33251 after the plugin-bypass fix changed this priority unconditionally."""+ router = ComplexityRouter(+ model_name="test-complexity-router",+ litellm_router_instance=mock_router_instance,+ complexity_router_config={+ "tiers": {"MEDIUM": ["gpt-4o-medium-tier"]},+ "default_model": "gpt-4o-configured-default",+ },+ )+ result = await router.async_pre_routing_hook(+ model="test-model",+ request_kwargs={},+ messages=[+ {"role": "system", "content": "You are helpful."},+ {"role": "assistant", "content": "Hello!"},+ ],+ )+ assert result is not None+ assert result.model == "gpt-4o-configured-default"++ def test_plugins_and_adaptive_together_raises(self):+ with pytest.raises(ValidationError, match="plugins and adaptive=True cannot both be set"):+ ComplexityRouterConfig(+ tiers={"SIMPLE": ["gpt-4o-mini"]},+ adaptive=True,+ plugins=[_DummyPlugin()],+ )++ @pytest.mark.asyncio+ async def test_no_plugins_configured_is_unaffected(self, complexity_router):+ """Regression guard: a ComplexityRouter with no `plugins` configured behaves exactly as before."""+ result = await complexity_router.async_pre_routing_hook(+ model="test-model",+ request_kwargs={},+ messages=[{"role": "user", "content": "Hello!"}],+ )+ assert result is not None++ @pytest.mark.asyncio+ async def test_session_affinity_pin_shortcut_disabled_when_plugins_configured(self, mock_router_instance):+ """Regression: the session_affinity cache-pin shortcut returned a stale pinned+ model without ever re-running it through plugins, so a policy plugin's decision+ (e.g. a budget cap crossed mid-session) was only ever enforced on a session's+ first turn. With plugins configured, every turn must go through+ _classify_and_route (and therefore the plugin pipeline) again."""+ mock_router_instance.cache = DualCache()++ class AllowAll:+ async def run(self, context):+ return context++ router = ComplexityRouter(+ model_name="test-router",+ litellm_router_instance=mock_router_instance,+ complexity_router_config={+ "tiers": {"SIMPLE": ["gpt-4o-mini"]},+ "session_affinity": True,+ "plugins": [AllowAll()],+ },+ )+ request_kwargs = {"metadata": {"session_id": "session-1"}}++ with patch.object(router, "_classify_and_route", wraps=router._classify_and_route) as spy:+ first = await router.async_pre_routing_hook(+ model="test-model", request_kwargs=request_kwargs, messages=[{"role": "user", "content": "hi"}]+ )+ second = await router.async_pre_routing_hook(+ model="test-model", request_kwargs=request_kwargs, messages=[{"role": "user", "content": "hi again"}]+ )+ assert first.model == "gpt-4o-mini"+ assert second.model == "gpt-4o-mini"+ assert spy.call_count == 2diff --git a/tests/test_litellm/router_strategy/test_router_routing_plugins.py b/tests/test_litellm/router_strategy/test_router_routing_plugins.pyindex e9c12d009e2..78ed71f5ffd 100644--- a/tests/test_litellm/router_strategy/test_router_routing_plugins.py+++ b/tests/test_litellm/router_strategy/test_router_routing_plugins.py@@ -218,3 +218,36 @@ def test_filter_by_routing_plugin_candidates_narrows_and_raises_when_empty():healthy_deployments=healthy_deployments,request_kwargs={"metadata": {"_routing_plugin_candidate_models": ["nonexistent/model"]}},)+++def test_json_default_stable_id_is_stable_across_instances():+ """_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+ litellm_params contain a live plugin instance."""+ router = Router(model_list=_smart_router_model_list())++ assert router._json_default_stable_id(LanguageDetector()) == router._json_default_stable_id(LanguageDetector())+ 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():+ """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."""+ router = Router(model_list=_smart_router_model_list())+ litellm_params = {+ "model": "auto_router/complexity_router",+ "complexity_router_config": {"plugins": [LanguageDetector()]},+ }++ id1 = router._generate_model_id("smart-router", litellm_params)+ id2 = router._generate_model_id(+ "smart-router",+ {+ "model": "auto_router/complexity_router",+ "complexity_router_config": {"plugins": [LanguageDetector()]},+ },+ )+ assert id1 == id2