Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 70 additions & 2 deletions litellm/router_strategy/complexity_router/complexity_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
import asyncio
import random
import re
from typing import TYPE_CHECKING, Any, Literal, Optional, Union, cast
from typing import TYPE_CHECKING, Any, Literal, Union, cast

from pydantic import BaseModel

Expand Down Expand Up @@ -809,17 +809,85 @@ def _extract_user_message_and_system_prompt(

return user_message, system_prompt

@staticmethod
def _get_session_id_from_request_kwargs(request_kwargs: dict) -> str | None:
"""Resolve a client-supplied session_id, mirroring DeploymentAffinityCheck's
metadata/litellm_metadata precedence (the proxy may populate either or both)."""
for metadata_key in ("litellm_metadata", "metadata"):
metadata = request_kwargs.get(metadata_key)
if isinstance(metadata, dict):
session_id = metadata.get("session_id")
if session_id is not None:
return str(session_id)
return None

def _get_session_affinity_cache_key(self, session_id: str) -> str:
return f"complexity_router_session_affinity:v1:{self.model_name}:{session_id}"
Comment thread
veria-ai[bot] marked this conversation as resolved.
Resolved

async def async_pre_routing_hook(
self,
model: str,
request_kwargs: dict,
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) 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):
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 other
formats via the guardrail translation handler dispatch.
Expand Down
14 changes: 14 additions & 0 deletions litellm/router_strategy/complexity_router/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
)
Comment on lines +372 to +376

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 TTL description claims refresh-on-hit, but code never refreshes

The description says "refreshed on every cache hit", but async_pre_routing_hook only calls async_set_cache after a cache miss (the first classification). On every subsequent pinned-turn cache hit, the code returns early without touching the cache, so the TTL counts down from the original write and a session active longer than session_affinity_ttl_seconds will silently lose its pin mid-conversation. Either the description should be corrected to say the TTL is fixed from first classification, or an async_set_cache call (with the same TTL) should be added in the cache-hit branch of async_pre_routing_hook.


model_config = ConfigDict(extra="allow") # Allow additional fields

@field_validator("tiers", mode="before")
Expand Down
165 changes: 165 additions & 0 deletions tests/test_litellm/router_strategy/test_complexity_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import litellm
from litellm import Router
from litellm._logging import verbose_router_logger
from litellm.caching.dual_cache import DualCache
from litellm.router_strategy.complexity_router.complexity_router import (
ComplexityRouter,
DimensionScore,
Expand Down Expand Up @@ -2424,3 +2425,167 @@ async def test_complexity_scorer_logs_its_cause(
assert "score=" in router_log_capture.text
assert "cause=literal_keyword_match" not in router_log_capture.text
assert "cause=semantic_keyword_match" not in router_log_capture.text


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_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"
Loading