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
fix(router): spend only the router-selecting tags, keep the caller's other tags constraining the routed tier
mateo-berri6dea3a57152a
diff --git a/litellm/constants.py b/litellm/constants.pyindex 5166fcadd74..ab027adbf57 100644--- a/litellm/constants.py+++ b/litellm/constants.py@@ -1323,7 +1323,7 @@ LITELLM_METADATA_FIELD: Final = "litellm_metadata"OLD_LITELLM_METADATA_FIELD: Final = "metadata"RETURN_RAW_MODEL_NAME_METADATA_KEY: Final = "_complexity_router_return_raw_model_name"SESSION_DEPLOYMENT_AFFINITY_TTL_METADATA_KEY: Final = "_session_deployment_affinity_ttl"-CONSUMED_REQUEST_TAGS_MODEL_GROUP_METADATA_KEY: Final = "_consumed_request_tags_model_group"+CONSUMED_REQUEST_TAGS_METADATA_KEY: Final = "_consumed_request_tags"INTERNAL_CALL_ORIGIN_METADATA_KEY: Final = "internal_call_origin"LITELLM_TRUNCATED_PAYLOAD_FIELD: Final = "litellm_truncated"LITELLM_TRUNCATION_DB_SAFEGUARD_NOTE: Final = (diff --git a/litellm/proxy/common_utils/callback_utils.py b/litellm/proxy/common_utils/callback_utils.pyindex e818147a9f0..1869328c039 100644--- a/litellm/proxy/common_utils/callback_utils.py+++ b/litellm/proxy/common_utils/callback_utils.py@@ -7,7 +7,7 @@ import litellmfrom litellm import get_secretfrom litellm._logging import verbose_proxy_loggerfrom litellm.constants import (- CONSUMED_REQUEST_TAGS_MODEL_GROUP_METADATA_KEY,+ CONSUMED_REQUEST_TAGS_METADATA_KEY,PRE_CALL_EXECUTED_GUARDRAILS_KEY,SESSION_DEPLOYMENT_AFFINITY_TTL_METADATA_KEY,)@@ -430,7 +430,7 @@ LITELLM_PROXY_INTERNAL_METADATA_KEYS: Final = frozenset("_pipeline_managed_guardrails",PRE_CALL_EXECUTED_GUARDRAILS_KEY,SESSION_DEPLOYMENT_AFFINITY_TTL_METADATA_KEY,- CONSUMED_REQUEST_TAGS_MODEL_GROUP_METADATA_KEY,+ CONSUMED_REQUEST_TAGS_METADATA_KEY,"disable_global_guardrails","disable_global_guardrail","opted_out_global_guardrails",diff --git a/litellm/proxy/litellm_pre_call_utils.py b/litellm/proxy/litellm_pre_call_utils.pyindex 3855fbf15e9..251ed1feb10 100644--- a/litellm/proxy/litellm_pre_call_utils.py+++ b/litellm/proxy/litellm_pre_call_utils.py@@ -16,7 +16,7 @@ import litellmfrom litellm._logging import verbose_logger, verbose_proxy_loggerfrom litellm._service_logger import ServiceLoggingfrom litellm.constants import (- CONSUMED_REQUEST_TAGS_MODEL_GROUP_METADATA_KEY,+ CONSUMED_REQUEST_TAGS_METADATA_KEY,INTERNAL_CALL_ORIGIN_METADATA_KEY,LITELLM_PROXY_MASTER_KEY_ALIAS,PRE_CALL_EXECUTED_GUARDRAILS_KEY,@@ -262,7 +262,7 @@ _UNTRUSTED_METADATA_CONTROL_FIELDS: Final = ("policy_sources","routing_decision",SESSION_DEPLOYMENT_AFFINITY_TTL_METADATA_KEY,- CONSUMED_REQUEST_TAGS_MODEL_GROUP_METADATA_KEY,+ CONSUMED_REQUEST_TAGS_METADATA_KEY,INTERNAL_CALL_ORIGIN_METADATA_KEY,"standard_logging_object","proxy_server_request",diff --git a/litellm/router.py b/litellm/router.pyindex f3015b71fd8..ed3c1ae676e 100644--- a/litellm/router.py+++ b/litellm/router.py@@ -43,7 +43,7 @@ from litellm.caching.caching import (RedisClusterCache,)from litellm.constants import (- CONSUMED_REQUEST_TAGS_MODEL_GROUP_METADATA_KEY,+ CONSUMED_REQUEST_TAGS_METADATA_KEY,DEFAULT_AUTO_ROUTER_MAX_INPUT_CHARS,DEFAULT_HEALTH_CHECK_INTERVAL,DEFAULT_HEALTH_CHECK_STALENESS_MULTIPLIER,@@ -172,6 +172,7 @@ from litellm.types.router import (AlertingConfig,AllowedFailsPolicy,AssistantsTypedDict,+ ConsumedRequestTagsStamp,CredentialLiteLLMParams,CustomRoutingStrategyBase,Deployment,@@ -11402,7 +11403,7 @@ class Router:request_kwargs=request_kwargs, key=SESSION_DEPLOYMENT_AFFINITY_TTL_METADATA_KEY, value=None)self._stamp_or_clear_metadata_key(- request_kwargs=request_kwargs, key=CONSUMED_REQUEST_TAGS_MODEL_GROUP_METADATA_KEY, value=None+ request_kwargs=request_kwargs, key=CONSUMED_REQUEST_TAGS_METADATA_KEY, value=None)return None@@ -11424,8 +11425,8 @@ class Router:)self._stamp_or_clear_metadata_key(request_kwargs=request_kwargs,- key=CONSUMED_REQUEST_TAGS_MODEL_GROUP_METADATA_KEY,- value=self._model_group_with_consumed_request_tags(+ 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),@@ -11449,25 +11450,27 @@ class Router:return pre_routing_hook_response- def _model_group_with_consumed_request_tags(+ def _consumed_request_tags_stamp(self,selected_strategy: "TaggedPreRoutingStrategy[PreRoutingStrategy]",pre_routing_hook_response: PreRoutingHookResponse | None,request_tags: Sequence[str],- ) -> str | None:- """Name the model group whose deployment selection must skip request-body tags, or None.+ ) -> 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 thosetags 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. Key/team- policy tags are untouched: tag filtering separately re-applies whatever+ 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 Noneif not is_valid_deployment_tag(selected_strategy.tags, request_tags, self.tag_filtering_match_any):return None- return pre_routing_hook_response.model+ return ConsumedRequestTagsStamp(model_group=pre_routing_hook_response.model, tags=selected_strategy.tags)@staticmethoddef _record_routing_decision(diff --git a/litellm/router_strategy/tag_based_routing.py b/litellm/router_strategy/tag_based_routing.pyindex 323aac23aca..40ed89ebfd8 100644--- a/litellm/router_strategy/tag_based_routing.py+++ b/litellm/router_strategy/tag_based_routing.py@@ -13,9 +13,9 @@ from types import MappingProxyTypefrom typing import TYPE_CHECKING, Any, Final, Literalfrom litellm._logging import verbose_logger-from litellm.constants import CONSUMED_REQUEST_TAGS_MODEL_GROUP_METADATA_KEY+from litellm.constants import CONSUMED_REQUEST_TAGS_METADATA_KEYfrom litellm.litellm_core_utils.core_helpers import get_metadata_variable_name_from_kwargs-from litellm.types.router import RouterErrors+from litellm.types.router import ConsumedRequestTagsStamp, RouterErrorsif TYPE_CHECKING:from litellm.router import Router as _Router@@ -394,15 +394,22 @@ def _tag_known_to_group(def _request_tags_after_router_consumption(metadata: Mapping[Any, Any], model: str) -> Sequence[str] | None:- # The pre-routing hook stamps the model group it rewrote the request to when the- # request's tags were what selected that router: those tags already did their job- # and must not also constrain deployment choice inside the routed group. Key/team- # policy keeps applying there, so the inherited_tags snapshot replaces the merged- # tag list rather than clearing it. Every other model group keeps the full list.- if metadata.get(CONSUMED_REQUEST_TAGS_MODEL_GROUP_METADATA_KEY) != model:+ # The pre-routing hook stamps which tags selected the router it rewrote the request+ # to: those tags already did their job and must not also constrain deployment choice+ # inside the routed group. The request's other tags still apply there, on top of the+ # inherited_tags snapshot that keeps key/team policy applying. Every other model+ # group keeps the full list.+ stamp: Final = metadata.get(CONSUMED_REQUEST_TAGS_METADATA_KEY)+ if not isinstance(stamp, ConsumedRequestTagsStamp) or stamp.model_group != model:return metadata.get("tags")+ request_tags: Final = metadata.get("tags")+ leftover: Final = tuple(+ tag for tag in (request_tags if isinstance(request_tags, (list, tuple)) else ()) if tag not in stamp.tags+ )inherited_tags: Final = metadata.get("inherited_tags")- return inherited_tags if isinstance(inherited_tags, (list, tuple)) else None+ if not isinstance(inherited_tags, (list, tuple)):+ return leftover or None+ return tuple(dict.fromkeys((*leftover, *inherited_tags)))async def get_deployments_for_tag(diff --git a/litellm/types/router.py b/litellm/types/router.pyindex d7ff8d12aa6..217364c48b7 100644--- a/litellm/types/router.py+++ b/litellm/types/router.py@@ -902,6 +902,14 @@ class TaggedPreRoutingStrategy(Generic[_PreRoutingStrategyT_co]):strategy: _PreRoutingStrategyT_co+@dataclass(frozen=True, slots=True)+class ConsumedRequestTagsStamp:+ """The model group a tagged router rewrote to, plus the request tags spent selecting it."""++ model_group: str+ tags: tuple[str, ...]++@runtime_checkableclass PreRoutingStrategy(Protocol):"""Structural interface shared by the auto / complexity / adaptive / quality routers."""diff --git a/tests/test_litellm/router_strategy/test_router_tag_routing.py b/tests/test_litellm/router_strategy/test_router_tag_routing.pyindex 0e870283015..93011bb29cc 100644--- a/tests/test_litellm/router_strategy/test_router_tag_routing.py+++ b/tests/test_litellm/router_strategy/test_router_tag_routing.py@@ -2890,21 +2890,21 @@ async def test_router_selecting_tag_is_consumed_on_litellm_metadata_shaped_requeassert deployment["model_info"]["id"] == "tier-gemini-flash"-def test_model_group_with_consumed_request_tags_names_the_routed_group_only_on_a_tag_match():- from litellm.types.router import PreRoutingHookResponse+def test_consumed_request_tags_stamp_names_the_routed_group_and_spent_tags_only_on_a_tag_match():+ from litellm.types.router import ConsumedRequestTagsStamp, PreRoutingHookResponserouter = _tagged_marker_router()strategy = router.auto_routers["gpt4o"][0]rewrite = PreRoutingHookResponse(model="gemini-flash", messages=None)- consumed = router._model_group_with_consumed_request_tags(+ consumed = router._consumed_request_tags_stamp(selected_strategy=strategy, pre_routing_hook_response=rewrite, request_tags=["route"])- unmatched = router._model_group_with_consumed_request_tags(+ unmatched = router._consumed_request_tags_stamp(selected_strategy=strategy, pre_routing_hook_response=rewrite, request_tags=["other"])- assert consumed == "gemini-flash"+ assert consumed == ConsumedRequestTagsStamp(model_group="gemini-flash", tags=("route",))assert unmatched is None@@ -2942,7 +2942,7 @@ async def test_caller_forged_consumption_stamp_is_neutralized_by_the_hook():metadata={"tags": ["route"],"inherited_tags": [],- "_consumed_request_tags_model_group": "gemini-flash",+ "_consumed_request_tags": {"model_group": "gemini-flash", "tags": ["route"]},},mock_response="hi",)@@ -2981,21 +2981,74 @@ async def test_inherited_constraint_still_applies_to_the_routed_tier():def test_request_tags_after_router_consumption_scopes_to_the_stamped_group():- from litellm.constants import CONSUMED_REQUEST_TAGS_MODEL_GROUP_METADATA_KEY+ from litellm.constants import CONSUMED_REQUEST_TAGS_METADATA_KEYfrom litellm.router_strategy.tag_based_routing import _request_tags_after_router_consumption+ from litellm.types.router import ConsumedRequestTagsStampmetadata = {"tags": ["route", "®ion:eu"],"inherited_tags": ["®ion:eu"],- CONSUMED_REQUEST_TAGS_MODEL_GROUP_METADATA_KEY: "gemini-flash",+ CONSUMED_REQUEST_TAGS_METADATA_KEY: ConsumedRequestTagsStamp(model_group="gemini-flash", tags=("route",)),}- assert _request_tags_after_router_consumption(metadata, "gemini-flash") == ["®ion:eu"]+ assert _request_tags_after_router_consumption(metadata, "gemini-flash") == ("®ion:eu",)assert _request_tags_after_router_consumption(metadata, "other-group") == ["route", "®ion:eu"]-def test_request_tags_after_router_consumption_without_inherited_info_drops_every_tag():- from litellm.constants import CONSUMED_REQUEST_TAGS_MODEL_GROUP_METADATA_KEY+def test_request_tags_after_router_consumption_drops_only_the_consumed_tags():+ from litellm.constants import CONSUMED_REQUEST_TAGS_METADATA_KEYfrom litellm.router_strategy.tag_based_routing import _request_tags_after_router_consumption+ from litellm.types.router import ConsumedRequestTagsStamp- metadata = {"tags": ["route"], CONSUMED_REQUEST_TAGS_MODEL_GROUP_METADATA_KEY: "gemini-flash"}- assert _request_tags_after_router_consumption(metadata, "gemini-flash") is None+ fully_consumed = {+ "tags": ["route"],+ CONSUMED_REQUEST_TAGS_METADATA_KEY: ConsumedRequestTagsStamp(model_group="gemini-flash", tags=("route",)),+ }+ assert _request_tags_after_router_consumption(fully_consumed, "gemini-flash") is None++ partially_consumed = {+ "tags": ["route", "deploy:us"],+ "inherited_tags": [],+ CONSUMED_REQUEST_TAGS_METADATA_KEY: ConsumedRequestTagsStamp(model_group="gemini-flash", tags=("route",)),+ }+ assert _request_tags_after_router_consumption(partially_consumed, "gemini-flash") == ("deploy:us",)+++async def test_non_router_tags_still_pick_the_matching_tier_deployment():+ # tags=["route", "deploy:us"]: "route" picks the router and is spent there,+ # but "deploy:us" must keep constraining deployment choice inside the routed+ # group instead of being dropped with it.+ from litellm.types.router import TaggedPreRoutingStrategy++ router = litellm.Router(+ model_list=[+ {+ "model_name": "gpt4o",+ "litellm_params": {"model": "openai/gpt-4o"},+ "model_info": {"id": "plain-gpt4o"},+ },+ {+ "model_name": "gemini-flash",+ "litellm_params": {"model": "gemini/gemini-3.6-flash", "tags": ["deploy:us"]},+ "model_info": {"id": "tier-gemini-flash-us"},+ },+ {+ "model_name": "gemini-flash",+ "litellm_params": {"model": "gemini/gemini-3.6-flash", "tags": ["deploy:eu"]},+ "model_info": {"id": "tier-gemini-flash-eu"},+ },+ ],+ enable_tag_filtering=True,+ )+ router.auto_routers = {+ "gpt4o": [TaggedPreRoutingStrategy(tags=("route",), strategy=_RewriteToTierStrategy("gemini-flash"))]+ }++ response = await router.acompletion(+ model="gpt4o",+ messages=[{"role": "user", "content": "hi"}],+ metadata={"tags": ["route", "deploy:us"], "inherited_tags": []},+ mock_response="hi",+ )++ assert response._hidden_params["model_id"] == "tier-gemini-flash-us"diff --git a/tests/test_litellm/test_router.py b/tests/test_litellm/test_router.pyindex fdccc46e5cb..0b47409eae1 100644--- a/tests/test_litellm/test_router.py+++ b/tests/test_litellm/test_router.py@@ -7510,29 +7510,35 @@ class TestConsumedRequestTagsStamp:@pytest.mark.asyncioasync def test_stamps_the_rewritten_group_when_request_tags_selected_the_router(self):- from litellm.constants import CONSUMED_REQUEST_TAGS_MODEL_GROUP_METADATA_KEY+ from litellm.constants import CONSUMED_REQUEST_TAGS_METADATA_KEY+ from litellm.types.router import ConsumedRequestTagsStamprouter = self._router()request_kwargs = {"metadata": {"tags": ["route"]}}await router.async_pre_routing_hook(model="gpt4o", request_kwargs=request_kwargs)- assert request_kwargs["metadata"][CONSUMED_REQUEST_TAGS_MODEL_GROUP_METADATA_KEY] == "gemini-flash"+ assert request_kwargs["metadata"][CONSUMED_REQUEST_TAGS_METADATA_KEY] == ConsumedRequestTagsStamp(+ model_group="gemini-flash", tags=("route",)+ )@pytest.mark.asyncioasync def test_stamps_into_litellm_metadata_when_the_request_uses_that_bucket(self):- from litellm.constants import CONSUMED_REQUEST_TAGS_MODEL_GROUP_METADATA_KEY+ from litellm.constants import CONSUMED_REQUEST_TAGS_METADATA_KEY+ from litellm.types.router import ConsumedRequestTagsStamprouter = self._router()request_kwargs = {"litellm_metadata": {"tags": ["route"]}}await router.async_pre_routing_hook(model="gpt4o", request_kwargs=request_kwargs)- assert request_kwargs["litellm_metadata"][CONSUMED_REQUEST_TAGS_MODEL_GROUP_METADATA_KEY] == "gemini-flash"+ assert request_kwargs["litellm_metadata"][CONSUMED_REQUEST_TAGS_METADATA_KEY] == ConsumedRequestTagsStamp(+ model_group="gemini-flash", tags=("route",)+ )@pytest.mark.asyncioasync def test_fallback_reentry_with_a_plain_group_clears_the_stale_stamp(self):- from litellm.constants import CONSUMED_REQUEST_TAGS_MODEL_GROUP_METADATA_KEY+ from litellm.constants import CONSUMED_REQUEST_TAGS_METADATA_KEYrouter = self._router()request_kwargs = {"metadata": {"tags": ["route"]}}@@ -7540,29 +7546,29 @@ class TestConsumedRequestTagsStamp:await router.async_pre_routing_hook(model="gpt4o", request_kwargs=request_kwargs)await router.async_pre_routing_hook(model="gemini-flash", request_kwargs=request_kwargs)- assert CONSUMED_REQUEST_TAGS_MODEL_GROUP_METADATA_KEY not in request_kwargs["metadata"]+ assert CONSUMED_REQUEST_TAGS_METADATA_KEY not in request_kwargs["metadata"]@pytest.mark.asyncioasync def test_no_stamp_when_the_request_is_untagged(self):- from litellm.constants import CONSUMED_REQUEST_TAGS_MODEL_GROUP_METADATA_KEY+ from litellm.constants import CONSUMED_REQUEST_TAGS_METADATA_KEYrouter = self._router()request_kwargs = {"metadata": {}}await router.async_pre_routing_hook(model="gpt4o", request_kwargs=request_kwargs)- assert CONSUMED_REQUEST_TAGS_MODEL_GROUP_METADATA_KEY not in request_kwargs["metadata"]+ assert CONSUMED_REQUEST_TAGS_METADATA_KEY not in request_kwargs["metadata"]@pytest.mark.asyncioasync def test_no_stamp_when_the_selected_strategy_carries_no_tags(self):- from litellm.constants import CONSUMED_REQUEST_TAGS_MODEL_GROUP_METADATA_KEY+ from litellm.constants import CONSUMED_REQUEST_TAGS_METADATA_KEYrouter = self._router(marker_tags=())request_kwargs = {"metadata": {"tags": ["route"]}}await router.async_pre_routing_hook(model="gpt4o", request_kwargs=request_kwargs)- assert CONSUMED_REQUEST_TAGS_MODEL_GROUP_METADATA_KEY not in request_kwargs["metadata"]+ assert CONSUMED_REQUEST_TAGS_METADATA_KEY not in request_kwargs["metadata"]class TestAutoRouterMaxInputCharsWiring: