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
Merge branch 'litellm_internal_staging' into litellm_fix_autorouter_alias_forwarding
mateob55e6cb2f754
diff --cc litellm/router.pyindex e5db6c1d392,1f114f99118..c8441a6c93b--- a/litellm/router.py+++ b/litellm/router.py@@@ -11349,8 -11359,8 +11362,10 @@@ class RouterResolve the pre-routing strategy for `model`, disambiguating deploymentsthat share a `model_name` by matching the request's tags against eachregistered strategy's tags before falling back to the first registered.- Returns the tagged wrapper so callers can locate the marker deployment- the strategy was registered from via its (model_name, tags) pair.+ Returns the tagged registry entry so the caller can tell whether the- request's tags were what selected it.++ request's tags were what selected it, and can locate the marker++ deployment the strategy was registered from via its (model_name, tags)++ pair."""candidates: Final[list[TaggedPreRoutingStrategy[PreRoutingStrategy]]] = [*self.auto_routers.get(model, []),@@@ -11421,44 -11434,58 +11439,80 @@@key=SESSION_DEPLOYMENT_AFFINITY_TTL_METADATA_KEY,value=(pre_routing_hook_response.session_affinity_ttl_seconds if pre_routing_hook_response else None),)+ self._stamp_or_clear_metadata_key(+ request_kwargs=request_kwargs,+ key=CONSUMED_REQUEST_TAGS_METADATA_KEY,+ value=self._consumed_request_tags_stamp(+ selected_strategy=selected_strategy,+ pre_routing_hook_response=pre_routing_hook_response,+ request_tags=_get_tags_from_request_kwargs(request_kwargs),+ ),+ )# `model` (the alias, e.g. "smart-router") is never the deployment actually- # called - apply the alias's own litellm_params (besides `model` itself,- # which is just the alias marker) to the request, since the tier/route- # deployment the hook selected won't have them. Router-only fields- # (tpm, rpm, weight, complexity_router_config, ...) are excluded from the- # actual outbound LLM call downstream by litellm.types.utils.all_litellm_params,+ # called - apply the router marker's own litellm_params to the request,+ # since the tier/route deployment the hook selected won't have them. The+ # marker entry is looked up by its `auto_router/` model prefix and the+ # selected strategy's tags, never by list position: plain deployments may+ # share the alias `model_name` and must not leak their params (`api_base`,+ # `api_key`, ...) onto the routed call. Router-only fields (tpm, rpm,+ # weight, complexity_router_config, ...) are excluded from the actual+ # outbound LLM call downstream by litellm.types.utils.all_litellm_params,- # not here.+ # not here. Custom pricing fields ARE call params, so they must be+ # excluded here: they price the alias, not the deployment the hook+ # selected, and forwarding them re-registers the routed deployment at+ # the alias's price (an explicit 0 makes every alias request bill $0).if pre_routing_hook_response is not None:- for key, value in self._forwardable_alias_marker_params(model=model, strategy_tags=tagged_strategy.tags):- alias_index: Final = self.model_name_to_deployment_indices.get(model, [])- if alias_index:- alias_litellm_params: Final = self.model_list[alias_index[0]].get("litellm_params", {})- for key, value in alias_litellm_params.items():- if key != "model" and key not in CustomPricingLiteLLMParams.model_fields and value is not None:- request_kwargs.setdefault(key, value)++ for key, value in self._forwardable_alias_marker_params(model=model, strategy_tags=selected_strategy.tags):+ request_kwargs.setdefault(key, value)return pre_routing_hook_response+ def _forwardable_alias_marker_params(+ self, model: str, strategy_tags: tuple[str, ...]+ ) -> tuple[tuple[str, object], ...]:+ marker_params: Final = tuple(+ litellm_params+ for idx in self.model_name_to_deployment_indices.get(model, ())+ if isinstance(litellm_params := self.model_list[idx].get("litellm_params", {}), dict)+ and str(litellm_params.get("model", "")).startswith(AUTO_ROUTER_MODEL_PREFIX)+ )+ tag_matched: Final = tuple(+ params for params in marker_params if tuple(params.get("tags") or ()) == strategy_tags+ )+ selected: Final = tag_matched[0] if tag_matched else (marker_params[0] if marker_params else None)+ if selected is None:+ return ()+ return tuple(+ (key, value)+ for key, value in selected.items()- if key not in _ALIAS_PARAMS_NEVER_FORWARDED and value is not None++ if key not in _ALIAS_PARAMS_NEVER_FORWARDED++ and key not in CustomPricingLiteLLMParams.model_fields++ and value is not None+ )++ def _consumed_request_tags_stamp(+ self,+ selected_strategy: "TaggedPreRoutingStrategy[PreRoutingStrategy]",+ pre_routing_hook_response: PreRoutingHookResponse | None,+ request_tags: Sequence[str],+ ) -> ConsumedRequestTagsStamp | None:+ """Record which tags picked the router and which model group it rewrote to, or None.++ A request whose tags matched the selected strategy's tags has already spent those+ tags on picking the router; re-applying them to the routed tier's model group would+ empty the pool unless every tier deployment repeats the marker's tag. Only the+ strategy's own tags are spent: the request's other tags keep constraining+ deployment selection inside the routed group, and key/team policy tags are+ untouched because tag filtering separately re-applies whatever+ `metadata.inherited_tags` carries for the stamped group.+ """+ if pre_routing_hook_response is None or not selected_strategy.tags or not request_tags:+ return None+ if not is_valid_deployment_tag(selected_strategy.tags, request_tags, self.tag_filtering_match_any):+ return None+ return ConsumedRequestTagsStamp(model_group=pre_routing_hook_response.model, tags=selected_strategy.tags)+@staticmethoddef _record_routing_decision(request_kwargs: dict,diff --cc tests/test_litellm/router_strategy/test_complexity_router.pyindex efc9ecc74a5,7fc78aee619..ef0e5ac2229--- a/tests/test_litellm/router_strategy/test_complexity_router.py+++ b/tests/test_litellm/router_strategy/test_complexity_router.py@@@ -2040,17 -2040,53 +2040,55 @@@ class TestRouterPreRoutingAliasOverrideassert request_kwargs["drop_params"] is Trueassert request_kwargs["cache_control_injection_points"] == [{"location": "message", "role": "system"}]+ @pytest.mark.asyncio+ async def test_alias_custom_pricing_is_not_applied_to_request_kwargs(self):+ """Custom pricing on the alias prices the alias, not the tier deployment+ the hook picked. Unlike the router-only fields, pricing fields are real+ call params, so forwarding them would re-register the routed deployment+ at the alias's price - an explicit 0 billing every request as free."""+ router = Router(+ model_list=[+ {+ "model_name": "smart-router",+ "litellm_params": {+ "model": "auto_router/complexity_router",+ "input_cost_per_token": 0.0,+ "output_cost_per_token": 0.0,+ "input_cost_per_second": 0.0,+ "drop_params": True,+ "complexity_router_config": {"tiers": {"SIMPLE": "gpt-4o-mini"}},+ "complexity_router_default_model": "gpt-4o",+ },+ },+ {"model_name": "gpt-4o-mini", "litellm_params": {"model": "openai/gpt-4o-mini"}},+ {"model_name": "gpt-4o", "litellm_params": {"model": "openai/gpt-4o"}},+ ]+ )+ request_kwargs: dict = {}++ result = await router.async_pre_routing_hook(+ model="smart-router",+ request_kwargs=request_kwargs,+ messages=[{"role": "user", "content": "hi"}],+ )++ assert result is not None+ # Non-pricing alias params still carry over.+ assert request_kwargs["drop_params"] is True+ for field in ("input_cost_per_token", "output_cost_per_token", "input_cost_per_second"):+ assert field not in request_kwargs+@pytest.mark.asyncio- async def test_alias_overrides_exclude_only_model(self):- """`model` (the alias marker, e.g. auto_router/complexity_router) is- excluded since it's never a real provider model. Router-only fields- like complexity_router_config DO flow through into request_kwargs at- this layer - they're filtered from the actual outbound LLM call- downstream by litellm.types.utils.all_litellm_params instead, not by- the router's pre-routing hook. See test_router_init_only_params_are_- never_sent_to_a_provider for the guard on that downstream filter."""+ async def test_alias_overrides_exclude_only_marker_and_connection_params(self):+ """`model` (the alias marker, e.g. auto_router/complexity_router) and+ provider-connection params (api_base/api_key/api_version) are excluded+ since they never describe the tier deployment actually called.+ Router-only fields like complexity_router_config DO flow through into+ request_kwargs at this layer - they're filtered from the actual+ outbound LLM call downstream by litellm.types.utils.all_litellm_params+ instead, not by the router's pre-routing hook. See+ test_router_init_only_params_are_never_sent_to_a_provider for the+ guard on that downstream filter."""router = self._make_router()request_kwargs: Dict = {}