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): opt-in session affinity for complexity router (#33126)
Krrish Dholakia397c84678b74
diff --git a/litellm/router_strategy/complexity_router/complexity_router.py b/litellm/router_strategy/complexity_router/complexity_router.pyindex bebdbba90ef..bd3b300b558 100644--- a/litellm/router_strategy/complexity_router/complexity_router.py+++ b/litellm/router_strategy/complexity_router/complexity_router.py@@ -18,7 +18,7 @@ from __future__ import annotationsimport asyncioimport randomimport re-from typing import TYPE_CHECKING, Any, Literal, Optional, Union, cast+from typing import TYPE_CHECKING, Any, Literal, Union, castfrom pydantic import BaseModel@@ -809,6 +809,44 @@ class ComplexityRouter(CustomLogger):return user_message, system_prompt+ @staticmethod+ def _iter_metadata_dicts(request_kwargs: dict) -> list[dict]:+ """Metadata may land on `metadata` or `litellm_metadata` depending on the+ endpoint, mirroring DeploymentAffinityCheck's precedence."""+ return [+ metadata+ for metadata_key in ("litellm_metadata", "metadata")+ if isinstance(metadata := request_kwargs.get(metadata_key), dict)+ ]++ @staticmethod+ def _get_session_id_from_request_kwargs(request_kwargs: dict) -> str | None:+ """Resolve a client-supplied session_id."""+ for metadata in ComplexityRouter._iter_metadata_dicts(request_kwargs):+ session_id = metadata.get("session_id")+ if session_id is not None:+ return str(session_id)+ return None++ @staticmethod+ def _get_user_api_key_hash_from_request_kwargs(request_kwargs: dict) -> str | None:+ """Resolve the proxy-derived API key hash, the same trust boundary+ DeploymentAffinityCheck uses for its own key-based affinity (not the+ client-supplied OpenAI `user` param, which isn't authenticated)."""+ for metadata in ComplexityRouter._iter_metadata_dicts(request_kwargs):+ user_key = metadata.get("user_api_key_hash")+ if user_key is not None:+ return str(user_key)+ return None++ def _get_session_affinity_cache_key(self, session_id: str, request_kwargs: dict) -> str:+ # Namespace by the caller's API key hash so two different callers reusing the+ # same client-supplied session_id can't poison each other's routing pin. Falls+ # back to "unscoped" only when there's no authenticated caller to scope by+ # (e.g. direct Router usage without the proxy layer).+ caller_scope = self._get_user_api_key_hash_from_request_kwargs(request_kwargs) or "unscoped"+ return f"complexity_router_session_affinity:v1:{self.model_name}:{caller_scope}:{session_id}"+async def async_pre_routing_hook(self,model: str,@@ -816,10 +854,70 @@ class ComplexityRouter(CustomLogger):messages: list[dict[str, Any]] | None = None,input: Union[str, list] | None = None,specific_deployment: bool | None = False,- ) -> Optional[PreRoutingHookResponse]:+ ) -> PreRoutingHookResponse | None:"""Pre-routing hook called before the routing decision.+ 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 later+ turn, skipping classification entirely. Otherwise delegates to `_classify_and_route`.+ """+ from litellm.types.router import PreRoutingHookResponse++ session_id = self._get_session_id_from_request_kwargs(request_kwargs) if self.config.session_affinity else None+ cache_key = self._get_session_affinity_cache_key(session_id, request_kwargs) if session_id is not None else None++ if cache_key is not None:+ pinned_model = await self.litellm_router_instance.cache.async_get_cache(key=cache_key)+ if isinstance(pinned_model, str):+ # Refresh the TTL on every hit so an active session doesn't lose its+ # pin mid-conversation just because it outlives the original write.+ await self.litellm_router_instance.cache.async_set_cache(+ key=cache_key,+ value=pinned_model,+ ttl=self.config.session_affinity_ttl_seconds,+ )+ if self.config.adaptive:+ from litellm.router_strategy.adaptive_router.config import (+ ADAPTIVE_ROUTER_CHOSEN_MODEL_KEY,+ )++ kwargs_metadata = request_kwargs.setdefault("metadata", {})+ if isinstance(kwargs_metadata, dict):+ kwargs_metadata[ADAPTIVE_ROUTER_CHOSEN_MODEL_KEY] = pinned_model+ verbose_router_logger.info(+ f"ComplexityRouter: routing decision cause=session_affinity_pin, routed_model={pinned_model}"+ )+ has_original_messages = messages is not None and len(messages) > 0+ return PreRoutingHookResponse(+ model=pinned_model,+ messages=messages if has_original_messages else None,+ )++ response = await self._classify_and_route(+ model=model,+ request_kwargs=request_kwargs,+ messages=messages,+ input=input,+ specific_deployment=specific_deployment,+ )+ if cache_key is not None and response is not None:+ await self.litellm_router_instance.cache.async_set_cache(+ key=cache_key,+ value=response.model,+ ttl=self.config.session_affinity_ttl_seconds,+ )+ return response++ async def _classify_and_route(+ self,+ model: str,+ request_kwargs: dict,+ messages: list[dict[str, Any]] | None = None,+ input: Union[str, list] | None = None,+ specific_deployment: bool | None = False,+ ) -> PreRoutingHookResponse | None:+ """Classifies the request by complexity and returns the appropriate model.Supports chat completions (messages), Responses API (input), and otherformats via the guardrail translation handler dispatch.diff --git a/litellm/router_strategy/complexity_router/config.py b/litellm/router_strategy/complexity_router/config.pyindex df699d1a059..e4bd36505e6 100644--- a/litellm/router_strategy/complexity_router/config.py+++ b/litellm/router_strategy/complexity_router/config.py@@ -361,6 +361,20 @@ class ComplexityRouterConfig(BaseModel):description="Minimum cosine similarity for a semantic keyword match",)+ # Session affinity: pin the first turn's routed model for the rest of the session+ session_affinity: bool = Field(+ default=False,+ description=(+ "When True and a session_id is resolvable on the request, pin the model chosen on the "+ "session's first turn and reuse it for every later turn, skipping re-classification."+ ),+ )+ session_affinity_ttl_seconds: int = Field(+ default=3600,+ gt=0,+ description="TTL for the session affinity pin; refreshed on every cache hit",+ )+model_config = ConfigDict(extra="allow") # Allow additional fields@field_validator("tiers", mode="before")diff --git a/tests/test_litellm/router_strategy/test_complexity_router.py b/tests/test_litellm/router_strategy/test_complexity_router.pyindex dc8b0a5cf26..f7c9f343f80 100644--- a/tests/test_litellm/router_strategy/test_complexity_router.py+++ b/tests/test_litellm/router_strategy/test_complexity_router.py@@ -19,6 +19,7 @@ sys.path.insert(0, os.path.abspath("../../..")) # Adds the parent directory toimport litellmfrom litellm import Routerfrom litellm._logging import verbose_router_logger+from litellm.caching.dual_cache import DualCachefrom litellm.router_strategy.complexity_router.complexity_router import (ComplexityRouter,DimensionScore,@@ -2485,3 +2486,217 @@ class TestRoutingDecisionCauseLogging:assert "score=" in router_log_capture.textassert "cause=literal_keyword_match" not in router_log_capture.textassert "cause=semantic_keyword_match" not in router_log_capture.text+++class TestSessionAffinity:+ """Test the opt-in session_affinity sticky-routing behavior."""++ REASONING_MESSAGE = [+ {+ "role": "user",+ "content": "Let's think step by step and reason through this problem carefully.",+ }+ ]+ SIMPLE_MESSAGE = [{"role": "user", "content": "Hello!"}]++ @pytest.fixture+ def session_affinity_config(self, basic_config) -> Dict:+ return {**basic_config, "session_affinity": True}++ @staticmethod+ def _request_kwargs(session_id: str) -> Dict:+ return {"metadata": {"session_id": session_id}}++ @pytest.mark.asyncio+ async def test_disabled_by_default_reclassifies_every_turn(self, mock_router_instance, basic_config):+ """Regression: session_affinity defaults to False, so a shared session_id must+ not pin the model -- each turn is still classified independently."""+ mock_router_instance.cache = DualCache()+ router = ComplexityRouter(+ model_name="test-router",+ litellm_router_instance=mock_router_instance,+ complexity_router_config=basic_config,+ )+ request_kwargs = self._request_kwargs("session-1")+ first = await router.async_pre_routing_hook(+ model="test-model", request_kwargs=request_kwargs, messages=self.REASONING_MESSAGE+ )+ second = await router.async_pre_routing_hook(+ model="test-model", request_kwargs=request_kwargs, messages=self.SIMPLE_MESSAGE+ )+ assert first.model == "o1-preview"+ assert second.model == "gpt-4o-mini"++ @pytest.mark.asyncio+ async def test_pins_model_after_first_turn(self, mock_router_instance, session_affinity_config):+ mock_router_instance.cache = DualCache()+ router = ComplexityRouter(+ model_name="test-router",+ litellm_router_instance=mock_router_instance,+ complexity_router_config=session_affinity_config,+ )+ request_kwargs = self._request_kwargs("session-1")+ first = await router.async_pre_routing_hook(+ model="test-model", request_kwargs=request_kwargs, messages=self.REASONING_MESSAGE+ )+ assert first.model == "o1-preview"++ with patch.object(router, "aclassify", wraps=router.aclassify) as spy_aclassify:+ second = await router.async_pre_routing_hook(+ model="test-model", request_kwargs=request_kwargs, messages=self.SIMPLE_MESSAGE+ )+ spy_aclassify.assert_not_called()+ # Pinned to the first turn's model, not re-classified down to SIMPLE.+ assert second.model == "o1-preview"++ @pytest.mark.asyncio+ async def test_different_sessions_classify_independently(self, mock_router_instance, session_affinity_config):+ mock_router_instance.cache = DualCache()+ router = ComplexityRouter(+ model_name="test-router",+ litellm_router_instance=mock_router_instance,+ complexity_router_config=session_affinity_config,+ )+ reasoning = await router.async_pre_routing_hook(+ model="test-model", request_kwargs=self._request_kwargs("session-a"), messages=self.REASONING_MESSAGE+ )+ simple = await router.async_pre_routing_hook(+ model="test-model", request_kwargs=self._request_kwargs("session-b"), messages=self.SIMPLE_MESSAGE+ )+ assert reasoning.model == "o1-preview"+ assert simple.model == "gpt-4o-mini"++ @pytest.mark.asyncio+ async def test_respects_ttl_seconds(self, mock_router_instance, basic_config):+ cache = AsyncMock()+ cache.async_get_cache = AsyncMock(return_value=None)+ mock_router_instance.cache = cache+ router = ComplexityRouter(+ model_name="test-router",+ litellm_router_instance=mock_router_instance,+ complexity_router_config={+ **basic_config,+ "session_affinity": True,+ "session_affinity_ttl_seconds": 120,+ },+ )+ await router.async_pre_routing_hook(+ model="test-model", request_kwargs=self._request_kwargs("session-1"), messages=self.SIMPLE_MESSAGE+ )+ cache.async_set_cache.assert_called_once()+ call_kwargs = cache.async_set_cache.call_args.kwargs+ assert call_kwargs["ttl"] == 120+ assert call_kwargs["value"] == "gpt-4o-mini"++ @pytest.mark.asyncio+ async def test_ttl_refreshed_on_cache_hit(self, mock_router_instance, basic_config):+ """Regression: a pinned turn must refresh the TTL, not just the first write --+ otherwise a session outliving session_affinity_ttl_seconds silently loses its pin."""+ cache = AsyncMock()+ cache.async_get_cache = AsyncMock(return_value="o1-preview")+ mock_router_instance.cache = cache+ router = ComplexityRouter(+ model_name="test-router",+ litellm_router_instance=mock_router_instance,+ complexity_router_config={+ **basic_config,+ "session_affinity": True,+ "session_affinity_ttl_seconds": 90,+ },+ )+ result = await router.async_pre_routing_hook(+ model="test-model", request_kwargs=self._request_kwargs("session-1"), messages=self.SIMPLE_MESSAGE+ )+ assert result.model == "o1-preview"+ cache.async_set_cache.assert_called_once()+ call_kwargs = cache.async_set_cache.call_args.kwargs+ assert call_kwargs["value"] == "o1-preview"+ assert call_kwargs["ttl"] == 90++ @pytest.mark.asyncio+ async def test_different_api_keys_do_not_share_pin(self, mock_router_instance, session_affinity_config):+ """A session_id is client-supplied and unauthenticated; two different callers+ (API keys) reusing the same session_id must not poison each other's pin."""+ mock_router_instance.cache = DualCache()+ router = ComplexityRouter(+ model_name="test-router",+ litellm_router_instance=mock_router_instance,+ complexity_router_config=session_affinity_config,+ )+ caller_a_kwargs = {"metadata": {"session_id": "shared-session", "user_api_key_hash": "key-a"}}+ caller_b_kwargs = {"metadata": {"session_id": "shared-session", "user_api_key_hash": "key-b"}}++ pinned_for_a = await router.async_pre_routing_hook(+ model="test-model", request_kwargs=caller_a_kwargs, messages=self.REASONING_MESSAGE+ )+ assert pinned_for_a.model == "o1-preview"++ # Caller B reuses the same session_id but has a different API key; its trivial+ # message must classify fresh, not inherit caller A's REASONING-tier pin.+ result_for_b = await router.async_pre_routing_hook(+ model="test-model", request_kwargs=caller_b_kwargs, messages=self.SIMPLE_MESSAGE+ )+ assert result_for_b.model == "gpt-4o-mini"++ @pytest.mark.asyncio+ async def test_no_session_id_falls_back_to_reclassify(self, mock_router_instance, session_affinity_config):+ cache = AsyncMock()+ mock_router_instance.cache = cache+ router = ComplexityRouter(+ model_name="test-router",+ litellm_router_instance=mock_router_instance,+ complexity_router_config=session_affinity_config,+ )+ result = await router.async_pre_routing_hook(+ model="test-model", request_kwargs={}, messages=self.SIMPLE_MESSAGE+ )+ assert result.model == "gpt-4o-mini"+ cache.async_get_cache.assert_not_called()+ cache.async_set_cache.assert_not_called()++ @pytest.mark.asyncio+ async def test_adaptive_pinned_turn_still_stamps_chosen_model_metadata(self, mock_router_instance):+ """Regression: skipping classification on a pinned turn must not break the+ adaptive bandit's reward-feedback loop, which only records a turn's outcome+ when ADAPTIVE_ROUTER_CHOSEN_MODEL_KEY is present in the request metadata."""+ mock_router_instance.cache = DualCache()+ mock_router_instance.model_list = [+ {+ "model_name": "cheap",+ "litellm_params": {"model": "openai/gpt-4o-mini", "input_cost_per_token": 0.0},+ "model_info": {},+ },+ ]+ mock_router_instance.model_name_to_deployment_indices = {"cheap": [0]}+ router = ComplexityRouter(+ model_name="hybrid",+ litellm_router_instance=mock_router_instance,+ complexity_router_config={+ "adaptive": True,+ "session_affinity": True,+ "tiers": {+ "SIMPLE": ["cheap"],+ "MEDIUM": ["cheap"],+ "COMPLEX": ["cheap"],+ "REASONING": ["cheap"],+ },+ "default_model": "cheap",+ },+ )+ first = await router.async_pre_routing_hook(+ model="hybrid",+ request_kwargs=self._request_kwargs("session-1"),+ messages=[{"role": "user", "content": "hi"}],+ )+ assert first.model == "cheap"++ request_kwargs_2 = self._request_kwargs("session-1")+ with patch.object(router, "aclassify", wraps=router.aclassify) as spy_aclassify:+ second = await router.async_pre_routing_hook(+ model="hybrid",+ request_kwargs=request_kwargs_2,+ messages=[{"role": "user", "content": "hi again"}],+ )+ spy_aclassify.assert_not_called()+ assert second.model == "cheap"+ assert request_kwargs_2["metadata"]["adaptive_router_chosen_model"] == "cheap"