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]

fix(router): rebuild the adaptive companion when an upserted complexity router participates in adaptive routing

Tin Chi Lo47a0c22f64a3
diff --git a/litellm/router.py b/litellm/router.py
index 4aa2731466e..29f548ca284 100644
--- a/litellm/router.py
+++ b/litellm/router.py
@@ -7702,6 +7702,21 @@ class Router:
"""True when this deployment opts in via the `auto_router/adaptive_router` model prefix."""
return litellm_params.model.startswith("auto_router/adaptive_router")
+ def _deployment_participates_in_adaptive_routing(self, litellm_params: LiteLLM_Params) -> bool:
+ """True when this deployment owns an `adaptive_routers` entry once finalized:
+ a dedicated adaptive router, or a complexity router whose config enables the
+ adaptive companion. Mirrors the two arms of
+ `_finalize_adaptive_router_if_configured`, which is the registry's only writer."""
+ if self._is_adaptive_router_deployment(litellm_params=litellm_params):
+ return True
+ if not self._is_complexity_router_deployment(litellm_params=litellm_params):
+ return False
+ config = litellm_params.complexity_router_config
+ if not config:
+ return False
+ adaptive_flag: object = config.get("adaptive")
+ return bool(adaptive_flag)
+
@staticmethod
def _has_registered_strategy(
registry: dict[str, list[TaggedPreRoutingStrategy[_PreRoutingStrategyT]]],
@@ -7784,15 +7799,6 @@ class Router:
build an AdaptiveRouter for each. Safe no-op when none are configured.
Idempotent: skips any deployment whose (model_name, tags) pair is already
initialized, so hot-reloads don't rebuild routers that would lose state."""
- # Drop any adaptive-router hooks left over from a previous Router
- # instance (e.g. after `/config/reload` replaced `llm_router`). Without
- # this, stale AdaptiveRouterPostCallHook callbacks from the old Router
- # remain wired up in `litellm.callbacks` and double-fire signal
- # recording for every request.
- from litellm.router_strategy.adaptive_router.hooks import (
- AdaptiveRouterPostCallHook,
- )
-
for entry in self.model_list or []:
lp = entry.get("litellm_params") if isinstance(entry, dict) else entry.litellm_params
lp_model = (lp.get("model") if isinstance(lp, dict) else lp.model) if lp else None
@@ -8466,9 +8472,11 @@ class Router:
# set_model_list() defers until the whole model_list is visible. Re-run that
# deferred pass so an adaptive router whose slot was just released above is
# rebuilt rather than left unregistered.
- if self._is_adaptive_router_deployment(litellm_params=deployment.litellm_params) or (
+ if self._deployment_participates_in_adaptive_routing(litellm_params=deployment.litellm_params) or (
_deployment_on_router is not None
- and self._is_adaptive_router_deployment(litellm_params=_deployment_on_router.litellm_params)
+ and self._deployment_participates_in_adaptive_routing(
+ litellm_params=_deployment_on_router.litellm_params
+ )
):
self._finalize_adaptive_router_if_configured()
return deployment
diff --git a/tests/test_litellm/test_router.py b/tests/test_litellm/test_router.py
index 3b7bcad78b0..f04e4a60283 100644
--- a/tests/test_litellm/test_router.py
+++ b/tests/test_litellm/test_router.py
@@ -6207,3 +6207,159 @@ class TestPreRoutingStrategyRegistryLifecycle:
registered = router.quality_routers["quality-router"]
assert len(registered) == 1
assert registered[0].strategy.config.default_model == "gpt-4o-mini"
+
+ @staticmethod
+ def _hybrid_router_params(tiers: dict) -> dict:
+ return {
+ "model": "auto_router/complexity_router",
+ "complexity_router_config": {"tiers": tiers, "adaptive": True},
+ "complexity_router_default_model": "gpt-4o",
+ }
+
+ @classmethod
+ def _router_with_hybrid_router(cls) -> "litellm.Router":
+ return litellm.Router(
+ model_list=[
+ {"model_name": "gpt-4o", "litellm_params": {"model": "openai/gpt-4o"}},
+ {"model_name": "gpt-4o-mini", "litellm_params": {"model": "openai/gpt-4o-mini"}},
+ {
+ "model_name": "hybrid-router",
+ "litellm_params": cls._hybrid_router_params({"SIMPLE": "gpt-4o-mini", "MEDIUM": "gpt-4o"}),
+ "model_info": {"id": "router-1", "db_model": True},
+ },
+ ],
+ ignore_invalid_deployments=True,
+ )
+
+ def test_upsert_of_edited_hybrid_complexity_router_relinks_adaptive(self):
+ """Editing an adaptive-enabled complexity router releases its adaptive companion
+ along with the complexity slot; the finalize re-run must fire for it (not just for
+ `auto_router/adaptive_router` deployments) or the rebuilt complexity router keeps
+ routing while bandit recording, DB persistence and /adaptive_router/state all
+ silently stop until the next full reload."""
+ import litellm as litellm_module
+ from litellm.router_strategy.adaptive_router.hooks import AdaptiveRouterPostCallHook
+ from litellm.types.router import Deployment, LiteLLM_Params, ModelInfo
+
+ router = self._router_with_hybrid_router()
+ assert "hybrid-router" in router.adaptive_routers
+
+ router.upsert_deployment(
+ deployment=Deployment(
+ model_name="hybrid-router",
+ litellm_params=LiteLLM_Params(
+ **self._hybrid_router_params(
+ {"SIMPLE": "gpt-4o-mini", "MEDIUM": "gpt-4o", "COMPLEX": "gpt-4o"}
+ )
+ ),
+ model_info=ModelInfo(id="router-1", db_model=True),
+ )
+ )
+
+ assert "hybrid-router" in self._model_names(router)
+ assert "hybrid-router" in router.complexity_routers
+ assert "hybrid-router" in router.adaptive_routers
+ rebuilt = router.complexity_routers["hybrid-router"][0].strategy
+ assert router.adaptive_routers["hybrid-router"][0].strategy is rebuilt.adaptive_router
+ hooks = litellm_module.logging_callback_manager.get_custom_loggers_for_type(AdaptiveRouterPostCallHook)
+ assert len(hooks) == 1
+
+ def test_upsert_turning_adaptive_on_builds_the_companion(self):
+ """An edit that flips `adaptive: true` on an existing complexity router must
+ register the companion immediately; neither side of the old prefix-only gate
+ matches a complexity deployment, so the flip was a silent no-op until restart."""
+ from litellm.types.router import Deployment, LiteLLM_Params, ModelInfo
+
+ router = self._router_with_complexity_router()
+ assert "smart-router" not in router.adaptive_routers
+
+ params = self._complexity_router_params("gpt-4o")
+ params["complexity_router_config"] = {**params["complexity_router_config"], "adaptive": True}
+ router.upsert_deployment(
+ deployment=Deployment(
+ model_name="smart-router",
+ litellm_params=LiteLLM_Params(**params),
+ model_info=ModelInfo(id="router-1", db_model=True),
+ )
+ )
+
+ assert "smart-router" in router.adaptive_routers
+
+ def test_unregister_pre_routing_strategy_scopes_the_drop_by_tags(self):
+ """The bool return drives the hook re-sync; a tag mismatch must report False and
+ leave the registry untouched, and dropping the last entry must free the key."""
+ from litellm.types.router import TaggedPreRoutingStrategy
+
+ registry = {
+ "m": [
+ TaggedPreRoutingStrategy(tags=("team-a",), strategy=object()),
+ TaggedPreRoutingStrategy(tags=(), strategy=object()),
+ ]
+ }
+
+ assert litellm.Router._unregister_pre_routing_strategy(registry, "m", ("team-b",)) is False
+ assert len(registry["m"]) == 2
+
+ assert litellm.Router._unregister_pre_routing_strategy(registry, "m", ("team-a",)) is True
+ assert [entry.tags for entry in registry["m"]] == [()]
+
+ assert litellm.Router._unregister_pre_routing_strategy(registry, "m", ()) is True
+ assert "m" not in registry
+
+ def test_unregister_for_deployment_ignores_non_router_deployments(self):
+ """Direct twin of the endpoint-level test: a regular deployment that shares a
+ router's model_name must not evict the router's registry slot."""
+ from litellm.types.router import Deployment, LiteLLM_Params, ModelInfo
+
+ router = self._router_with_complexity_router()
+
+ router._unregister_pre_routing_strategy_for_deployment(
+ deployment=Deployment(
+ model_name="smart-router",
+ litellm_params=LiteLLM_Params(model="openai/gpt-4o"),
+ model_info=ModelInfo(id="plain-1", db_model=True),
+ )
+ )
+
+ assert "smart-router" in router.complexity_routers
+
+ def test_sync_adaptive_router_hooks_keeps_one_hook_per_registered_router(self):
+ """Re-syncing must replace, not accumulate: a duplicated hook double-fires
+ bandit signal recording for every request."""
+ import litellm as litellm_module
+ from litellm.router_strategy.adaptive_router.hooks import AdaptiveRouterPostCallHook
+
+ router = self._router_with_hybrid_router()
+
+ router._sync_adaptive_router_hooks()
+ router._sync_adaptive_router_hooks()
+
+ hooks = litellm_module.logging_callback_manager.get_custom_loggers_for_type(AdaptiveRouterPostCallHook)
+ assert len(hooks) == 1
+
+ def test_deployment_participates_in_adaptive_routing_matrix(self):
+ """The upsert finalize re-run keys off this predicate for both the incoming and
+ outgoing deployment; a false negative silently strands the adaptive companion."""
+ from litellm.types.router import LiteLLM_Params
+
+ router = self._router_with_complexity_router()
+
+ cases = [
+ ({"model": "auto_router/adaptive_router", "adaptive_router_config": {}}, True),
+ (self._hybrid_router_params({"SIMPLE": "gpt-4o-mini"}), True),
+ (self._complexity_router_params("gpt-4o"), False),
+ (
+ {
+ "model": "auto_router/complexity_router",
+ "complexity_router_config": {"tiers": {"SIMPLE": "gpt-4o-mini"}, "adaptive": False},
+ "complexity_router_default_model": "gpt-4o",
+ },
+ False,
+ ),
+ ({"model": "openai/gpt-4o"}, False),
+ ]
+ for params, expected in cases:
+ actual = router._deployment_participates_in_adaptive_routing(
+ litellm_params=LiteLLM_Params(**params)
+ )
+ assert actual is expected, params["model"]