Skip to content

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]

fix(router): honor request-level tag filtering in pre-routing strategy selection

mateo-berri47f3cf804ed9
diff --git a/litellm/router.py b/litellm/router.py
index 8b9c4b0db1a..85eb2dac51e 100644
--- a/litellm/router.py
+++ b/litellm/router.py
@@ -11454,8 +11454,10 @@ class Router:
deployment the strategy was registered from via its (model_name, tags)
pair.
- With tag filtering enabled, strategies that all carry real tags matching
- none of the request's do not capture it when the name also has plain
+ With tag filtering enabled, router-wide or by the request's
+ enable_tag_filtering (which the proxy sets from key/team
+ router_settings), strategies that all carry real tags matching none of
+ the request's do not capture it when the name also has plain
deployments: returning None hands the request to ordinary tag-aware
deployment selection.
"""
@@ -11478,8 +11480,9 @@ class Router:
for tagged in candidates:
if "default" in tagged.tags:
return tagged
+ request_scoped_filtering: Final = request_kwargs.get("enable_tag_filtering") is True
if (
- self.enable_tag_filtering
+ (self.enable_tag_filtering or request_scoped_filtering)
and all(tagged.tags for tagged in candidates)
and self._model_name_has_plain_deployments(model)
):
diff --git a/tests/e2e/models.py b/tests/e2e/models.py
index 957da605546..df5cb841fad 100644
--- a/tests/e2e/models.py
+++ b/tests/e2e/models.py
@@ -73,6 +73,7 @@ class KeyGenerateBody(BaseModel):
allowed_passthrough_routes: list[str] | None = None
metadata: KeyMetadata | None = None
object_permission: ObjectPermission | None = None
+ router_settings: "RouterSettingsOverride | None" = None
class KeyGenerateResponse(BaseModel):
@@ -234,16 +235,18 @@ class ChatBody(BaseModel):
class RouterSettingsOverride(BaseModel):
- """Per-request `router_settings_override` in a /chat/completions body: the
- reliability knobs (fallbacks by trigger, retry count) the reliability suite
- drives per call instead of via static router config. Serialized exclude_none, so
- an override sets only the strategies a test exercises. Each fallbacks map is
- model_name -> the ordered fallback model_names to try."""
+ """Router settings a test scopes below the global config: sent per request as
+ `router_settings_override` in a /chat/completions body (the reliability suite's
+ fallback and retry knobs) or stored on a key as `router_settings` at
+ /key/generate (the auto-router suite's tag filtering switch). Serialized
+ exclude_none, so an override sets only the knobs a test exercises. Each
+ fallbacks map is model_name -> the ordered fallback model_names to try."""
fallbacks: list[dict[str, list[str]]] | None = None
context_window_fallbacks: list[dict[str, list[str]]] | None = None
content_policy_fallbacks: list[dict[str, list[str]]] | None = None
num_retries: int | None = None
+ enable_tag_filtering: bool | None = None
class ReliabilityChatBody(ChatBody):
diff --git a/tests/e2e/router/test_auto_router_regressions_e2e.py b/tests/e2e/router/test_auto_router_regressions_e2e.py
index a23b50f2a73..c6ef9cda05d 100644
--- a/tests/e2e/router/test_auto_router_regressions_e2e.py
+++ b/tests/e2e/router/test_auto_router_regressions_e2e.py
@@ -31,15 +31,15 @@ pins one fixed behavior:
its own credentials.
Every deployment is registered via /model/new (stage has no static config for
-these) and ``enable_tag_filtering`` is flipped through /config/update and
-restored on teardown, mirroring TestRouterSettings in the management suite.
+these) and ``enable_tag_filtering`` is enabled through key-level
+``router_settings`` on the keys the tag tests mint, so the switch rides only
+this module's own requests and the rest of the suite is never filtered.
The served deployment is always read back from the spend log's ``model``,
which stores either the registered alias or the provider-prefixed form.
"""
import json
import os
-import time
from collections.abc import Iterator
from dataclasses import dataclass
from typing import Final
@@ -48,7 +48,7 @@ import pytest
from pydantic import BaseModel, ConfigDict, Field
from e2e_config import unique_marker
-from e2e_http import AnthropicHeaders, AuthHeaders, NoBody, UnauthorizedError, unwrap
+from e2e_http import AnthropicHeaders, AuthHeaders, UnauthorizedError, unwrap
from lifecycle import ResourceManager
from models import (
AnthropicMessagesBody,
@@ -58,6 +58,7 @@ from models import (
ChatMetadata,
KeyGenerateBody,
LiteLLMParamsBody,
+ RouterSettingsOverride,
SpendLogRow,
)
from proxy_client import ProxyClient
@@ -117,26 +118,6 @@ class ResponsesApiResponse(BaseModel):
model: str | None = None
-class RouterSettingsPatch(BaseModel):
- enable_tag_filtering: bool
-
-
-class ConfigUpdateBody(BaseModel):
- router_settings: RouterSettingsPatch
-
-
-class ConfigUpdateResponse(BaseModel):
- message: str
-
-
-class RouterCurrentValues(BaseModel):
- enable_tag_filtering: bool | None = None
-
-
-class RouterSettingsResponse(BaseModel):
- current_values: RouterCurrentValues
-
-
@dataclass(frozen=True, slots=True)
class TagSplitDeployments:
"""Scenario A mirrors the customer-shaped config from GitHub issue #36619:
@@ -191,44 +172,16 @@ def _uniform_tier_config(tier_model: str) -> dict[str, object]:
}
-def _read_tag_filtering(proxy: ProxyClient) -> bool | None:
- return unwrap(
- proxy.transport.get(
- "/router/settings",
- headers=proxy.transport.master,
- params=NoBody(),
- response_type=RouterSettingsResponse,
- )
- ).current_values.enable_tag_filtering
-
-
-def _write_tag_filtering(proxy: ProxyClient, enabled: bool) -> None:
- response: Final = unwrap(
- proxy.transport.post(
- "/config/update",
- headers=proxy.transport.master,
- json=ConfigUpdateBody(router_settings=RouterSettingsPatch(enable_tag_filtering=enabled)),
- response_type=ConfigUpdateResponse,
+def _key_for(
+ proxy: ProxyClient, resources: ResourceManager, models: list[str], tag_filtering: bool = False
+) -> str:
+ key: Final = proxy.generate_key(
+ KeyGenerateBody(
+ models=models,
+ user_id="e2e-auto-router-regressions",
+ router_settings=RouterSettingsOverride(enable_tag_filtering=True) if tag_filtering else None,
)
)
- assert "success" in response.message.lower(), (
- f"/config/update reported {response.message!r}, expected a success message"
- )
-
-
-def _await_tag_filtering(proxy: ProxyClient, expected: bool) -> None:
- deadline: Final = time.monotonic() + proxy.poll_timeout
- while time.monotonic() < deadline:
- if _read_tag_filtering(proxy) is expected:
- return
- time.sleep(proxy.poll_interval)
- raise AssertionError(
- f"GET /router/settings never reported enable_tag_filtering={expected} after /config/update"
- )
-
-
-def _key_for(proxy: ProxyClient, resources: ResourceManager, models: list[str]) -> str:
- key: Final = proxy.generate_key(KeyGenerateBody(models=models, user_id="e2e-auto-router-regressions"))
resources.defer(lambda: proxy.delete_key(key))
return key
@@ -258,23 +211,7 @@ def _assert_served_only_by(rows: list[SpendLogRow], allowed: frozenset[str], con
@pytest.fixture(scope="module")
-def tag_filtering(proxy: ProxyClient) -> Iterator[None]:
- """enable_tag_filtering is what splits tagged from untagged traffic in every
- scenario here. /config/update is the only write path for router_settings;
- the original value is restored on teardown so the shared proxy keeps its
- configuration for the rest of the run."""
- original: Final = bool(_read_tag_filtering(proxy))
- _write_tag_filtering(proxy, True)
- _await_tag_filtering(proxy, True)
- try:
- yield
- finally:
- _write_tag_filtering(proxy, original)
- _await_tag_filtering(proxy, original)
-
-
[email protected](scope="module")
-def split(proxy: ProxyClient, tag_filtering: None) -> Iterator[TagSplitDeployments]:
+def split(proxy: ProxyClient) -> Iterator[TagSplitDeployments]:
marker: Final = unique_marker()
deployments: Final = TagSplitDeployments(
tag_a=f"e2e-split-a-{marker}",
@@ -421,7 +358,7 @@ class TestTagSplitRouting:
body metadata tags match the tagged marker under a shared model name is
answered by the marker's tier deployment, not by the plain deployment
that was registered under the name first."""
- key: Final = _key_for(proxy, resources, [split.shared_a, split.tier_a])
+ key: Final = _key_for(proxy, resources, [split.shared_a, split.tier_a], tag_filtering=True)
chat: Final = unwrap(proxy.chat(key, _hello_chat_body(split.shared_a, tags=[split.tag_a])))
assert chat.choices, "tagged chat through the shared name returned no choices"
rows: Final = proxy.poll_logs_for_key(key, min_rows=1)
@@ -435,7 +372,7 @@ class TestTagSplitRouting:
succeed on every call and are all served by the plain deployment; the
tagged marker never captures them, so no intermittent auto-router
errors and no tier hijacking."""
- key: Final = _key_for(proxy, resources, [split.shared_a, split.tier_a])
+ key: Final = _key_for(proxy, resources, [split.shared_a, split.tier_a], tag_filtering=True)
for _ in range(5):
chat = unwrap(proxy.chat(key, _hello_chat_body(split.shared_a)))
assert chat.choices, "untagged chat through the shared name returned no choices"
@@ -449,7 +386,7 @@ class TestTagSplitRouting:
"""Pins GitHub issue #36620 on the /v1/messages surface: an untagged
Anthropic-native request to the shared name is served by the plain
deployment, not captured by the tagged marker."""
- key: Final = _key_for(proxy, resources, [split.shared_a, split.tier_a])
+ key: Final = _key_for(proxy, resources, [split.shared_a, split.tier_a], tag_filtering=True)
answer: Final = unwrap(proxy.messages(key, _hello_messages_body(split.shared_a)))
assert answer.content or answer.choices, "untagged /v1/messages returned neither content nor choices"
rows: Final = proxy.poll_logs_for_key(key, min_rows=1)
@@ -465,7 +402,7 @@ class TestUntaggedTierDeployments:
x-litellm-tags header selects the tagged marker, and the rewrite still
lands on the tier deployment even though that deployment carries no
tags, because the marker consumed the routing tags."""
- key: Final = _key_for(proxy, resources, [split.shared_b, split.tier_b])
+ key: Final = _key_for(proxy, resources, [split.shared_b, split.tier_b], tag_filtering=True)
headers: Final = TaggedAnthropicHeaders(authorization=f"Bearer {key}", x_litellm_tags=split.tag_b)
answer: Final = unwrap(
proxy.transport.post(
@@ -487,7 +424,7 @@ class TestUntaggedTierDeployments:
tagged marker rewrites the request to its tier model, the consumed
routing tags no longer constrain deployment selection, so the untagged
tier deployment serves the request instead of a strict-tag denial."""
- key: Final = _key_for(proxy, resources, [split.shared_b, split.tier_b])
+ key: Final = _key_for(proxy, resources, [split.shared_b, split.tier_b], tag_filtering=True)
chat: Final = unwrap(proxy.chat(key, _hello_chat_body(split.shared_b, tags=[split.tag_b])))
assert chat.choices, "body-tagged chat through the marker-first shared name returned no choices"
rows: Final = proxy.poll_logs_for_key(key, min_rows=1)
@@ -500,7 +437,7 @@ class TestUntaggedTierDeployments:
"""The tag-consumption fix must not loosen strict tag semantics: a
tagged request aimed directly at an untagged deployment (no marker
involved) is still rejected with the 401 tags-configuration error."""
- key: Final = _key_for(proxy, resources, [split.tier_b])
+ key: Final = _key_for(proxy, resources, [split.tier_b], tag_filtering=True)
result: Final = proxy.chat(key, _hello_chat_body(split.tier_b, tags=[split.tag_b]))
assert isinstance(result, UnauthorizedError), (
f"expected the tagged direct call to an untagged deployment to be denied with 401, got {result}"
@@ -516,7 +453,7 @@ class TestResponsesApiTagRouting:
#36620/#36621): a /v1/responses request with string input, tagged via
the x-litellm-tags header, succeeds and routes through the tagged
marker to its tier."""
- key: Final = _key_for(proxy, resources, [split.shared_a, split.tier_a])
+ key: Final = _key_for(proxy, resources, [split.shared_a, split.tier_a], tag_filtering=True)
headers: Final = TaggedAuthHeaders(authorization=f"Bearer {key}", x_litellm_tags=split.tag_a)
body: Final = ResponsesBody(
model=split.shared_a, input=f"say hello {unique_marker()}", max_output_tokens=64
@@ -535,7 +472,7 @@ class TestResponsesApiTagRouting:
"""Pins the body-tag and list-input combination of the same split:
/v1/responses with litellm_metadata.tags and structured input items
routes through the tagged marker to its tier."""
- key: Final = _key_for(proxy, resources, [split.shared_a, split.tier_a])
+ key: Final = _key_for(proxy, resources, [split.shared_a, split.tier_a], tag_filtering=True)
body: Final = ResponsesBody(
model=split.shared_a,
input=[ResponsesInputItem(role="user", content=f"say hello {unique_marker()}")],
@@ -561,7 +498,7 @@ class TestResponsesApiTagRouting:
"""Pins the untagged half of the /v1/responses tag split: an untagged
request to the shared name is served by the plain deployment, matching
the chat and messages surfaces."""
- key: Final = _key_for(proxy, resources, [split.shared_a, split.tier_a])
+ key: Final = _key_for(proxy, resources, [split.shared_a, split.tier_a], tag_filtering=True)
body: Final = ResponsesBody(
model=split.shared_a, input=f"say hello {unique_marker()}", max_output_tokens=64
)
diff --git a/tests/test_litellm/test_router.py b/tests/test_litellm/test_router.py
index b3c348a1221..16a309ebb4c 100644
--- a/tests/test_litellm/test_router.py
+++ b/tests/test_litellm/test_router.py
@@ -7674,6 +7674,21 @@ class TestTaggedAutoRouterOnSharedModelName:
assert response is not None
assert response.model == "gemini-flash"
+ @pytest.mark.asyncio
+ async def test_request_level_tag_filtering_from_key_settings_bypasses_the_marker(self):
+ router = self._router(marker_tags=["route"], include_plain_sibling=True, enable_tag_filtering=False)
+
+ assert await self._hook_response(router, {"enable_tag_filtering": True}) is None
+
+ @pytest.mark.asyncio
+ async def test_globally_disabled_filtering_still_lets_the_marker_capture_untagged_requests(self):
+ router = self._router(marker_tags=["route"], include_plain_sibling=True, enable_tag_filtering=False)
+
+ response = await self._hook_response(router, {})
+
+ assert response is not None
+ assert response.model == "gemini-flash"
+
@pytest.mark.asyncio
async def test_marker_only_alias_still_captures_untagged_requests(self):
router = self._router(marker_tags=["route"], include_plain_sibling=False, enable_tag_filtering=True)