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): random-pick multi-model complexity tiers (#32967)
Krrish Dholakiaf717e3b2f0d4
diff --git a/litellm/router_strategy/complexity_router/complexity_router.py b/litellm/router_strategy/complexity_router/complexity_router.pyindex 11719b8a18f..2138a0112a0 100644--- a/litellm/router_strategy/complexity_router/complexity_router.py+++ b/litellm/router_strategy/complexity_router/complexity_router.py@@ -14,6 +14,7 @@ Inspired by ClawRouter: https://github.com/BlockRunAI/ClawRouter"""import asyncio+import randomimport refrom typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Tuple, Union, cast@@ -437,22 +438,26 @@ class ComplexityRouter(CustomLogger):"""tier_key = tier.value if isinstance(tier, ComplexityTier) else tier- # Check config tiers mapping- model = self.config.tiers.get(tier_key)- if model:- return model+ if tier_key in self.config.tiers:+ return self._pick_from_tier_value(self.config.tiers[tier_key], tier_key)- # Fallback to default model if configuredif self.config.default_model:return self.config.default_model- # Last resort: return MEDIUM tier model or error- medium_model = self.config.tiers.get(ComplexityTier.MEDIUM.value)- if medium_model:- return medium_model+ medium_key = ComplexityTier.MEDIUM.value+ if medium_key in self.config.tiers:+ return self._pick_from_tier_value(self.config.tiers[medium_key], medium_key)raise ValueError(f"No model configured for tier {tier_key} and no default_model set")+ @staticmethod+ def _pick_from_tier_value(model: str | list[str], tier_key: str) -> str:+ if isinstance(model, str):+ return model+ if not model:+ raise ValueError(f"Empty model pool for tier {tier_key}")+ return random.choice(model)+def _lexical_tier_override(self, user_message: str) -> Optional[ComplexityTier]:"""When keyword_tier_rules match literally, the most-severe matched tier wins.diff --git a/litellm/router_strategy/complexity_router/config.py b/litellm/router_strategy/complexity_router/config.pyindex 125de6f7489..8c8e5acb51f 100644--- a/litellm/router_strategy/complexity_router/config.py+++ b/litellm/router_strategy/complexity_router/config.py@@ -8,7 +8,7 @@ All values are configurable via proxy config.yaml.from enum import Enumfrom typing import Dict, List, Literal, Optional-from pydantic import BaseModel, ConfigDict, Field, model_validator+from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validatorclass ComplexityTier(str, Enum):@@ -244,10 +244,12 @@ class ClassifierLLMConfig(BaseModel):class ComplexityRouterConfig(BaseModel):"""Configuration for the ComplexityRouter."""- # Tier to model mapping- tiers: Dict[str, str] = Field(+ # string = pin; list = random pick from the tier pool+ tiers: dict[str, str | list[str]] = Field(default_factory=lambda: DEFAULT_TIER_MODELS.copy(),- description="Mapping of complexity tiers to model names",+ description=(+ "Mapping of complexity tiers to a model or model pool. A list is randomly picked from for that tier"+ ),)# Tier boundaries (normalized scores)@@ -335,6 +337,21 @@ class ComplexityRouterConfig(BaseModel):model_config = ConfigDict(extra="allow") # Allow additional fields+ @field_validator("tiers", mode="before")+ @classmethod+ def _coerce_tier_values(cls, value: object) -> object:+ if not isinstance(value, dict):+ return value+ coerced: dict[str, object] = {}+ for key, item in value.items():+ if isinstance(item, str):+ coerced[key] = item+ elif isinstance(item, (list, tuple)):+ coerced[key] = list(item)+ else:+ coerced[key] = item+ return coerced+@model_validator(mode="after")def _validate_llm_classifier_config(self) -> "ComplexityRouterConfig":if self.classifier_type == "llm" and self.classifier_llm_config is None:diff --git a/tests/test_litellm/router_strategy/test_complexity_router.py b/tests/test_litellm/router_strategy/test_complexity_router.pyindex f47c19b2baa..e1133620a57 100644--- a/tests/test_litellm/router_strategy/test_complexity_router.py+++ b/tests/test_litellm/router_strategy/test_complexity_router.py@@ -315,6 +315,36 @@ class TestModelSelection:model = router.get_model_for_tier(ComplexityTier.SIMPLE)assert model == "fallback-model"+ def test_get_model_for_tier_list_random_choice(self, mock_router_instance):+ router = ComplexityRouter(+ model_name="test-router",+ litellm_router_instance=mock_router_instance,+ complexity_router_config={+ "tiers": {"SIMPLE": ["cheap", "premium"], "MEDIUM": "mid"},+ "default_model": "mid",+ },+ )+ pool = ["cheap", "premium"]+ with patch(+ "litellm.router_strategy.complexity_router.complexity_router.random.choice",+ return_value="premium",+ ) as choice:+ assert router.get_model_for_tier(ComplexityTier.SIMPLE) == "premium"+ choice.assert_called_once_with(pool)+ assert router.get_model_for_tier(ComplexityTier.MEDIUM) == "mid"++ def test_get_model_for_tier_empty_pool_raises(self, mock_router_instance):+ router = ComplexityRouter(+ model_name="test-router",+ litellm_router_instance=mock_router_instance,+ complexity_router_config={+ "tiers": {"SIMPLE": []},+ "default_model": "mid",+ },+ )+ with pytest.raises(ValueError, match="Empty model pool for tier SIMPLE"):+ router.get_model_for_tier(ComplexityTier.SIMPLE)+class TestPreRoutingHook:"""Test the async_pre_routing_hook method."""