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]

feat(router): add required-AND (&) tag prefix and allow_fail_open flag (#36193)

Deepanshu Lulla84d6666a594e
diff --git a/litellm/proxy/litellm_pre_call_utils.py b/litellm/proxy/litellm_pre_call_utils.py
index 10142a894a1..0924b6aebea 100644
--- a/litellm/proxy/litellm_pre_call_utils.py
+++ b/litellm/proxy/litellm_pre_call_utils.py
@@ -1862,6 +1862,24 @@ async def add_litellm_data_to_request(
tags_to_add=project_metadata["tags"],
)
+ # inherited_tags: every tag key/team/project policy contributed, read
+ # directly from those three sources rather than snapshotted off the shared
+ # "tags" list. A pre-auth pass (apply_client_tag_policy_pre_auth, run from
+ # user_api_key_auth for _tag_max_budget_check) may already have merged the
+ # caller's own header tags into that same list before this function ever
+ # runs, so a snapshot taken here -- at any point in this function -- would
+ # misattribute caller-supplied tags as policy-backed. tag_based_routing.py's
+ # allow_fail_open reads this (rather than subtracting caller_tags from the
+ # final merged set) so a caller can't strip an inherited "!"/"&"
+ # constraint's protection just by resubmitting its exact value alongside a
+ # conflicting one.
+ _key_tags: Final = (key_metadata or MappingProxyType({})).get("tags") or ()
+ _team_tags: Final = team_metadata.get("tags") or ()
+ _project_tags: Final = project_metadata.get("tags") or ()
+ data[_metadata_variable_name]["inherited_tags"] = tuple( # rebind-ok: matches this file's data[...] mutation idiom
+ dict.fromkeys((*_key_tags, *_team_tags, *_project_tags))
+ )
+
## TEAM-LEVEL METADATA
data = LiteLLMProxyRequestSetup.add_management_endpoint_metadata_to_request_metadata(
data=data,
@@ -1958,15 +1976,28 @@ async def add_litellm_data_to_request(
tags_to_add=tags,
)
- if _metadata_variable_name != "metadata":
- _user_metadata = data.get("metadata")
- if isinstance(_user_metadata, dict):
- _user_tags: Final = _user_metadata.get("tags")
- if isinstance(_user_tags, list) and _user_tags:
- data[_metadata_variable_name]["tags"] = LiteLLMProxyRequestSetup._merge_tags(
- request_tags=data[_metadata_variable_name].get("tags"),
- tags_to_add=_user_tags,
- )
+ _caller_body_metadata: Final = data.get("metadata") if _metadata_variable_name != "metadata" else None
+ _caller_body_tags: Final = (
+ _caller_body_metadata.get("tags")
+ if isinstance(_caller_body_metadata, dict) and isinstance(_caller_body_metadata.get("tags"), list)
+ else None
+ )
+ if _caller_body_tags:
+ data[_metadata_variable_name]["tags"] = LiteLLMProxyRequestSetup._merge_tags( # rebind-ok: matches file idiom
+ request_tags=data[_metadata_variable_name].get("tags"),
+ tags_to_add=_caller_body_tags,
+ )
+
+ # caller_tags: exactly what this request itself supplied (x-litellm-tags header,
+ # body "tags", or body "metadata.tags" on litellm_metadata routes), never
+ # anything from key/team/project metadata. Read directly from the header and
+ # body values here, the same way inherited_tags above is read directly from
+ # key/team/project metadata -- neither is derived by inspecting the shared
+ # "tags" list, which a pre-auth pass (apply_client_tag_policy_pre_auth) may
+ # have already merged caller header tags into before this function runs.
+ data[_metadata_variable_name]["caller_tags"] = tuple( # rebind-ok: matches file idiom
+ dict.fromkeys((*(tags or ()), *(_caller_body_tags or ())))
+ )
# Team Callbacks controls
callback_settings_obj: Final = _get_dynamic_logging_metadata(
diff --git a/litellm/router.py b/litellm/router.py
index 9cece2014af..6af1c1a78e7 100644
--- a/litellm/router.py
+++ b/litellm/router.py
@@ -402,6 +402,7 @@ class Router:
enable_pre_call_checks: bool = False,
enable_tag_filtering: bool = False,
tag_filtering_match_any: bool = True,
+ tag_routing_prefix: str = "",
plugins: list[RoutingPlugin] | None = None,
retry_after: int = 0, # min time to wait before retrying a failed request
retry_policy: RetryPolicy | dict | None = None, # set custom retries for different exceptions
@@ -511,6 +512,7 @@ class Router:
self.enable_pre_call_checks = enable_pre_call_checks
self.enable_tag_filtering = enable_tag_filtering
self.tag_filtering_match_any = tag_filtering_match_any
+ self.tag_routing_prefix = tag_routing_prefix
from litellm._service_logger import ServiceLogging
self.service_logger_obj: ServiceLogging = ServiceLogging()
@@ -10109,6 +10111,7 @@ class Router:
"model_group_alias",
"enable_weighted_failover",
"enable_tag_filtering",
+ "tag_routing_prefix",
]
for var in vars_to_include:
@@ -10146,6 +10149,7 @@ class Router:
"model_group_alias",
"enable_weighted_failover",
"enable_tag_filtering",
+ "tag_routing_prefix",
]
_int_settings: Final = [
diff --git a/litellm/router_strategy/tag_based_routing.py b/litellm/router_strategy/tag_based_routing.py
index c952b54e672..bbe97613c57 100644
--- a/litellm/router_strategy/tag_based_routing.py
+++ b/litellm/router_strategy/tag_based_routing.py
@@ -4,9 +4,12 @@ Use this to route requests between Teams
- If tags in request is a subset of tags in deployment, return deployment
- if deployments are set with default tags, return all default deployment
- If no default_deployments are set, return all deployments
+- A "!tag" excludes deployments carrying that tag; a "&tag" requires it
"""
import re
+from collections.abc import Mapping, Sequence
+from types import MappingProxyType
from typing import TYPE_CHECKING, Any, Final, Literal
from litellm._logging import verbose_logger
@@ -114,14 +117,52 @@ def _match_deployment(
return None
-def _split_tags(tags: list[str]) -> tuple[list[str], list[str]]:
- positive: Final = [t for t in tags if not t.startswith("!")]
- excluded: Final = [tag[1:] for tag in tags if tag.startswith("!") and len(tag) > 1]
- return positive, excluded
+def _bare_tag_value(tag: str) -> str | None:
+ # Mirrors _split_tags' own stripping rule exactly, so a confirmed value
+ # compares equal to whatever required_set/excluded_set/positive_tags end up
+ # holding for the same tag: a "&"/"!" marker is stripped only when something
+ # follows it; a lone marker with nothing after it parses to nothing in any
+ # of the three sets, so it must not become a confirmed value either.
+ if tag.startswith(("&", "!")):
+ return tag[1:] if len(tag) > 1 else None
+ return tag
+
+
+def _strip_routing_prefix(tags: Sequence[str], prefix: str) -> tuple[tuple[str, ...], frozenset[str]]:
+ # Strips the configured routing-prefix marker from any tag carrying it, used
+ # exactly as configured with no delimiter auto-appended, and separately
+ # tracks the post-strip, post-marker-strip values that arrived prefixed: tags
+ # whose routing intent the caller declared explicitly, exempt from the "maybe
+ # foreign to this group" heuristics in _unknown_required_tag_hides_an_answer
+ # and _tag_known_to_group below. Confirmed values are compared against
+ # required_set/excluded_set downstream, which are themselves already stripped
+ # of their "&"/"!" marker by _split_tags -- confirmed must match that same
+ # bare form, not the raw post-prefix-strip value that still carries the
+ # marker character. An empty prefix must return every tag unconfirmed, not
+ # run every tag through str.startswith(""), which is trivially True for
+ # every string and would mark everything confirmed.
+ if not prefix:
+ return tuple(tags), frozenset()
+ rewritten: Final = tuple(t.removeprefix(prefix) for t in tags)
+ confirmed: Final = frozenset(
+ bare
+ for bare in (_bare_tag_value(t.removeprefix(prefix)) for t in tags if t.startswith(prefix))
+ if bare is not None
+ )
+ return rewritten, confirmed
+
+
+def _split_tags(tags: Sequence[str]) -> tuple[tuple[str, ...], list[str], tuple[str, ...]]:
+ required: Final = tuple(tag[1:] for tag in tags if tag.startswith("&") and len(tag) > 1)
+ positive: Final = [
+ t for t in tags if not t.startswith("!") and not t.startswith("&")
+ ] # mutable-ok: feeds _match_deployment's existing list[str]-typed request_tags param
+ excluded: Final = tuple(tag[1:] for tag in tags if tag.startswith("!") and len(tag) > 1)
+ return required, positive, excluded
def _exclude_deployments(
- deployments: list[Any] | dict[Any, Any],
+ deployments: Sequence[Any] | Mapping[Any, Any],
excluded_set: frozenset[str],
) -> list[Any]:
if not excluded_set:
@@ -129,24 +170,223 @@ def _exclude_deployments(
return [d for d in deployments if not excluded_set.intersection(d.get("litellm_params", {}).get("tags") or [])]
-def _require_candidates(
- candidates: list[Any],
+def _require_all_tags(
+ deployments: Sequence[Any] | Mapping[Any, Any],
+ required_set: frozenset[str],
+) -> tuple[Any, ...]:
+ if not required_set:
+ return tuple(deployments)
+ return tuple(d for d in deployments if required_set.issubset(d.get("litellm_params", {}).get("tags") or []))
+
+
+def _default_tagged_pool(
+ deployments: Sequence[Any] | Mapping[Any, Any],
+) -> tuple[Any, ...]:
+ defaults: Final = tuple(d for d in deployments if "default" in (d.get("litellm_params", {}).get("tags") or []))
+ return defaults if defaults else tuple(deployments)
+
+
+def _known_tag_values(deployments: Sequence[Any] | Mapping[Any, Any]) -> frozenset[str]:
+ return frozenset(
+ tag for d in deployments for tag in (d.get("litellm_params", MappingProxyType({})).get("tags") or ())
+ )
+
+
+def _unknown_required_tag_hides_an_answer(
+ healthy_deployments: Sequence[Any] | Mapping[Any, Any],
+ excluded_set: frozenset[str],
+ required_set: frozenset[str],
+ routing_confirmed: frozenset[str],
+) -> bool:
+ # A caller-invented "&" tag (one no deployment in this group has ever carried)
+ # guarantees an empty required-AND result on its own, regardless of whether the
+ # rest of the request's required tags were satisfiable. Dropping the unknown
+ # tags and recomputing: if that reveals a specific, non-empty answer, the invented
+ # tag was the actual cause of the exhaustion, and fail-open must not paper over
+ # it. If every required tag is known, or none are, there's nothing hidden to
+ # protect: either the caller made a real, honestly-unsatisfiable ask (fail-open
+ # proceeds normally), or the whole required set is unrecognized noise with no
+ # narrower answer to hide behind it. routing_confirmed (tag_routing_prefix)
+ # counts as known too: the caller explicitly declared it a routing directive,
+ # so it is never treated as invented noise regardless of deployment vocabulary.
+ known_required: Final = required_set & (_known_tag_values(healthy_deployments) | routing_confirmed)
+ if not known_required or known_required == required_set:
+ return False
+ allowed: Final = _exclude_deployments(healthy_deployments, excluded_set)
+ return bool(_require_all_tags(allowed, known_required))
+
+
+def _chain_allows_fail_open(
+ healthy_deployments: Sequence[Any] | Mapping[Any, Any],
+ excluded_set: frozenset[str],
+ required_set: frozenset[str],
+ routing_confirmed: frozenset[str],
+) -> bool:
+ if _unknown_required_tag_hides_an_answer(healthy_deployments, excluded_set, required_set, routing_confirmed):
+ return False
+ return any((d.get("model_info") or {}).get("allow_fail_open") is True for d in healthy_deployments)
+
+
+def _trusted_only_pool(
+ healthy_deployments: Sequence[Any] | Mapping[Any, Any],
+ excluded_set: frozenset[str],
+ required_set: frozenset[str],
+ inherited_excluded_set: frozenset[str] | None,
+ inherited_required_set: frozenset[str] | None,
+) -> tuple[Any, ...]:
+ # inherited_*_set is None only when this request carries no origin information
+ # at all (e.g. direct SDK Router usage, bypassing the proxy layer that
+ # populates metadata.inherited_tags) -- treat every constraint as
+ # caller-controlled in that case (protected == empty), reproducing this
+ # function's pre-provenance behavior exactly: an unconditional fall-open to the
+ # full default-tagged pool, constraints discarded entirely. Otherwise, a tag
+ # value is protected the moment it has ANY inherited backing, even when the
+ # caller also happens to submit the identical value themselves -- set
+ # membership can't distinguish "this value came from policy" from "this value
+ # coincidentally matches policy," so presence in the inherited set (not
+ # absence from a caller-supplied set) is what must gate discardability. This
+ # is deliberately intersection with inherited_*_set, not subtraction of a
+ # caller-supplied set: subtraction would let a caller strip an inherited
+ # requirement's protection just by resubmitting its exact value alongside a
+ # conflicting one (e.g. inherited "&region:eu" plus caller "&region:eu"
+ # and "!region:eu" would otherwise cancel the inherited requirement out).
+ trusted_excluded: Final = (
+ frozenset[str]() if inherited_excluded_set is None else inherited_excluded_set & excluded_set
+ )
+ trusted_required: Final = (
+ frozenset[str]() if inherited_required_set is None else inherited_required_set & required_set
+ )
+ return _require_all_tags(_exclude_deployments(healthy_deployments, trusted_excluded), trusted_required)
+
+
+def _resolve_or_fail_open(
+ pool: Sequence[Any],
+ healthy_deployments: Sequence[Any] | Mapping[Any, Any],
+ excluded_set: frozenset[str],
+ required_set: frozenset[str],
+ inherited_excluded_set: frozenset[str] | None,
+ inherited_required_set: frozenset[str] | None,
+ routing_confirmed: frozenset[str],
model: str,
- request_tags: Any,
-) -> list[Any]:
- if not candidates:
- raise ValueError(
- f"{RouterErrors.no_deployments_with_tag_routing.value}. Passed model={model} and tags={request_tags}"
+ request_tags: object,
+) -> tuple[Any, ...]:
+ if pool:
+ return tuple(pool)
+ if _chain_allows_fail_open(healthy_deployments, excluded_set, required_set, routing_confirmed):
+ # Fall open only within whatever still satisfies whichever constraints
+ # trace back to key/team policy. A constraint with no inherited backing at
+ # all (or, when inherited_tags is unavailable, any constraint at all) can
+ # be discarded; one inherited from key/team policy cannot -- if that alone
+ # is unsatisfiable, raise instead of silently routing around it.
+ trusted_pool: Final = _trusted_only_pool(
+ healthy_deployments, excluded_set, required_set, inherited_excluded_set, inherited_required_set
)
- return candidates
+ if trusted_pool:
+ return _default_tagged_pool(trusted_pool)
+ raise ValueError(
+ f"{RouterErrors.no_deployments_with_tag_routing.value}. Passed model={model} and tags={request_tags}"
+ )
-def _ban_only_base_pool(
- deployments: list[Any] | dict[Any, Any],
-) -> list[Any]:
- # Mirrors untagged-request semantics so callers can't use !tags to escape the default pool.
- defaults: Final = [d for d in deployments if "default" in (d.get("litellm_params", {}).get("tags") or [])]
- return defaults if defaults else list(deployments)
+def _resolve_constraint_only_pool(
+ healthy_deployments: Sequence[Any] | Mapping[Any, Any],
+ excluded_set: frozenset[str],
+ required_set: frozenset[str],
+ inherited_excluded_set: frozenset[str] | None,
+ inherited_required_set: frozenset[str] | None,
+ routing_confirmed: frozenset[str],
+ model: str,
+ request_tags: object,
+) -> tuple[Any, ...]:
+ pool: Final = (
+ _require_all_tags(_exclude_deployments(healthy_deployments, excluded_set), required_set)
+ if required_set
+ else _exclude_deployments(_default_tagged_pool(healthy_deployments), excluded_set)
+ )
+ return _resolve_or_fail_open(
+ pool,
+ healthy_deployments,
+ excluded_set,
+ required_set,
+ inherited_excluded_set,
+ inherited_required_set,
+ routing_confirmed,
+ model,
+ request_tags,
+ )
+
+
+def _all_deployments_or_fallback(
+ llm_router_instance: LitellmRouter,
+ model: str,
+ fallback: Sequence[Any] | Mapping[Any, Any],
+) -> Sequence[Any] | Mapping[Any, Any]:
+ try:
+ return llm_router_instance._get_all_deployments(model_name=model)
+ except Exception: # noqa: BLE001 # fail safe toward today's healthy-only behavior on lookup errors
+ return fallback
+
+
+def _chain_tag_filtering_override(
+ llm_router_instance: LitellmRouter,
+ model: str,
+ healthy_deployments: Sequence[Any] | Mapping[Any, Any],
+) -> bool | None:
+ # Resolved from every deployment configured for this model group, not just the
+ # ones that survived cooldown/health filtering (async_get_healthy_deployments
+ # filters cooldowns before calling get_deployments_for_tag) -- otherwise the
+ # sole deployment carrying this group's only explicit override loses its effect
+ # the moment it's transiently unhealthy, silently falling back to the
+ # router-wide default and letting an attacker disable a chain's tag policy by
+ # repeatedly failing that one deployment into cooldown. Falls back to
+ # healthy_deployments on a lookup error, preserving today's behavior rather
+ # than crashing the request.
+ all_deployments: Final = _all_deployments_or_fallback(llm_router_instance, model, healthy_deployments)
+ for d in all_deployments:
+ value = (d.get("model_info") or MappingProxyType({})).get("enable_tag_filtering")
+ if value is not None:
+ return value
+ return None
+
+
+def _inherited_constraint_sets(
+ inherited_tags: object, routing_prefix: str
+) -> tuple[frozenset[str] | None, frozenset[str] | None]:
+ # None means no origin information is available at all (e.g. this request
+ # bypassed the proxy layer that populates metadata.inherited_tags, as direct
+ # SDK Router usage does) -- callers of this must treat that as "nothing is
+ # protected," not "nothing is inherited," see _trusted_only_pool.
+ # metadata.inherited_tags is a snapshot of whatever key/team/project policy
+ # merged into "tags" *before* this request's own caller-supplied tags were
+ # merged in on top (see litellm_pre_call_utils.py), so a value present here is
+ # policy-backed regardless of whether the caller also happens to submit the
+ # identical value. inherited_tags is stripped through the same routing_prefix
+ # as the main request tags so a policy-inherited prefixed tag still matches
+ # correctly against the (already-stripped) required_set/excluded_set computed
+ # from request_tags.
+ if not isinstance(inherited_tags, (list, tuple)):
+ return None, None
+ rewritten_inherited_tags: Final = _strip_routing_prefix(inherited_tags, routing_prefix)[0]
+ inherited_required, _inherited_positive, inherited_excluded = _split_tags(rewritten_inherited_tags)
+ return frozenset(inherited_required), frozenset(inherited_excluded)
+
+
+def _tag_known_to_group(
+ llm_router_instance: LitellmRouter,
+ model: str,
+ positive_tags: Sequence[str],
+ routing_confirmed: frozenset[str],
+) -> bool:
+ tag_set: Final = frozenset(positive_tags)
+ if tag_set & routing_confirmed:
+ return True
+ try:
+ all_deployments: Final = llm_router_instance._get_all_deployments(model_name=model)
+ except Exception: # noqa: BLE001 # fail safe toward "unrecognized" so lookup errors preserve the existing silent-fallback behavior
+ return False
+ return any(
+ tag_set.intersection(d.get("litellm_params", MappingProxyType({})).get("tags") or ()) for d in all_deployments
+ )
async def get_deployments_for_tag(
@@ -161,24 +401,29 @@ async def get_deployments_for_tag(
Executes tag based filtering based on the tags in request metadata and the tags on the deployments
- Runs when the router-level `enable_tag_filtering` is True or the request carries
- `enable_tag_filtering=True` (set from key/team router_settings by the proxy).
- A request-level False never disables a router-level True, so per-request settings
- cannot escape an operator's global tag-routing policy.
+ Runs when the effective enable_tag_filtering is True. Effective value: a
+ request-level enable_tag_filtering=True (set from key/team router_settings by
+ the proxy) always wins; otherwise model_info.enable_tag_filtering on this model
+ group, if set on any of its deployments, overrides the router-wide default.
+ A request-level False never disables either of those, so per-request settings
+ cannot escape an operator's or a chain owner's tag-routing policy.
"""
- request_enable_tag_filtering: Final = request_kwargs.get("enable_tag_filtering") if request_kwargs else None
- if request_enable_tag_filtering is not True and llm_router_instance.enable_tag_filtering is not True:
- return healthy_deployments
-
- if request_kwargs is None:
+ if request_kwargs is None or not healthy_deployments:
verbose_logger.debug(
- "get_deployments_for_tag: request_kwargs is None returning healthy_deployments: %s",
+ "get_deployments_for_tag: skipping tag filter (request_kwargs=%s, healthy_deployments=%s)",
+ request_kwargs,
healthy_deployments,
)
return healthy_deployments
- if not healthy_deployments:
- verbose_logger.debug("get_deployments_for_tag: empty or None healthy_deployments; skipping tag filter")
+ request_enable_tag_filtering: Final = request_kwargs.get("enable_tag_filtering")
+ chain_enable_tag_filtering: Final = _chain_tag_filtering_override(llm_router_instance, model, healthy_deployments)
+ chain_default: Final = (
+ chain_enable_tag_filtering
+ if chain_enable_tag_filtering is not None
+ else llm_router_instance.enable_tag_filtering
+ )
+ if request_enable_tag_filtering is not True and chain_default is not True:
return healthy_deployments
verbose_logger.debug("request metadata: %s", request_kwargs.get(metadata_variable_name))
@@ -186,29 +431,52 @@ async def get_deployments_for_tag(
metadata: Final = request_kwargs[metadata_variable_name]
request_tags: Final = metadata.get("tags")
match_any: Final = llm_router_instance.tag_filtering_match_any
+ routing_prefix: Final = llm_router_instance.tag_routing_prefix or ""
# Build header strings for regex matching from what the proxy already stores.
# Currently we match against User-Agent; format matches "^User-Agent: claude-code/..."
user_agent: Final = metadata.get("user_agent", "")
header_strings: Final[list[str]] = [f"User-Agent: {user_agent}"] if user_agent else []
- positive_tags, excluded_patterns = _split_tags(request_tags or [])
+ # A tag_routing_prefix-marked tag is stripped before matching -- everything
+ # downstream (_split_tags, deployment matching) works off the unprefixed
+ # value, exactly as if the caller had sent it unprefixed -- and its
+ # post-strip value is remembered in routing_confirmed as an explicit,
+ # caller-declared routing directive, exempt from the "maybe foreign to this
+ # group" heuristics that unprefixed tags still go through unchanged below.
+ rewritten_tags, routing_confirmed = _strip_routing_prefix(request_tags or [], routing_prefix)
+ required_tags, positive_tags, excluded_patterns = _split_tags(rewritten_tags)
+ inherited_required_set, inherited_excluded_set = _inherited_constraint_sets(
+ metadata.get("inherited_tags"), routing_prefix
+ )
excluded_set: Final = frozenset(excluded_patterns)
- candidates: Final = _exclude_deployments(healthy_deployments, excluded_set)
+ required_set: Final = frozenset(required_tags)
+ allowed_deployments: Final = _exclude_deployments(healthy_deployments, excluded_set)
+ candidates: Final = _require_all_tags(allowed_deployments, required_set)
has_regex_deployments: Final = any(d.get("litellm_params", {}).get("tag_regex") for d in candidates)
- has_tag_filter: Final = bool(positive_tags) or (bool(header_strings) and has_regex_deployments)
- ban_only: Final = bool(excluded_set) and not has_tag_filter
-
- if ban_only:
- pool: Final = _exclude_deployments(_ban_only_base_pool(healthy_deployments), excluded_set)
- return _require_candidates(pool, model, request_tags)
+ has_positive_filter: Final = bool(positive_tags) or (
+ bool(header_strings) and has_regex_deployments and not required_set
+ )
+ constraint_only: Final = (bool(excluded_set) or bool(required_set)) and not has_positive_filter
+
+ if constraint_only:
+ return _resolve_constraint_only_pool(
+ healthy_deployments,
+ excluded_set,
+ required_set,
+ inherited_excluded_set,
+ inherited_required_set,
+ routing_confirmed,
+ model,
+ request_tags,
+ )
new_healthy_deployments: Final[list[Any]] = []
default_deployments: Final[list[Any]] = []
- if has_tag_filter:
+ if has_positive_filter:
verbose_logger.debug(
"get_deployments_for_tag routing: request_tags=%s user_agent=%s",
request_tags,
@@ -245,9 +513,33 @@ async def get_deployments_for_tag(
default_deployments.append(deployment)
if len(new_healthy_deployments) == 0 and len(default_deployments) == 0:
- raise ValueError(
- f"{RouterErrors.no_deployments_with_tag_routing.value}."
- f" Passed model={model} and tags={request_tags}"
+ return _resolve_or_fail_open(
+ (),
+ healthy_deployments,
+ excluded_set,
+ required_set,
+ inherited_excluded_set,
+ inherited_required_set,
+ routing_confirmed,
+ model,
+ request_tags,
+ )
+
+ if (
+ len(new_healthy_deployments) == 0
+ and positive_tags
+ and _tag_known_to_group(llm_router_instance, model, positive_tags, routing_confirmed)
+ ):
+ return _resolve_or_fail_open(
+ (),
+ healthy_deployments,
+ excluded_set,
+ required_set,
+ inherited_excluded_set,
+ inherited_required_set,
+ routing_confirmed,
+ model,
+ request_tags,
)
return new_healthy_deployments if len(new_healthy_deployments) > 0 else default_deployments
diff --git a/litellm/types/router.py b/litellm/types/router.py
index 3ac59c0f581..d7ff8d12aa6 100644
--- a/litellm/types/router.py
+++ b/litellm/types/router.py
@@ -123,6 +123,7 @@ class UpdateRouterConfig(BaseModel):
context_window_fallbacks: list[dict] | None = None
model_group_alias: dict[str, str | dict] | None = {}
enable_tag_filtering: bool | None = None
+ tag_routing_prefix: str | None = None
model_config = ConfigDict(protected_namespaces=())
@@ -170,6 +171,20 @@ class ModelInfo(MirroredPricingParams):
ptu_effective_from: datetime.datetime | None = None
ptu_effective_to: datetime.datetime | None = None
+ # when tag-based routing's "!" or "&" constraints eliminate every deployment
+ # in this model group, fall back to the default-tagged pool instead of
+ # raising no_deployments_with_tag_routing. Defaults to False (raise), so
+ # existing "!" negation behavior is unchanged unless explicitly opted in.
+ allow_fail_open: bool | None = None
+
+ # per-model-group override for router_settings.enable_tag_filtering; unset
+ # defers to the router-wide default. Checked against any deployment in the
+ # group, so set it consistently across every deployment sharing this
+ # model_name. A request-level enable_tag_filtering=True (from key/team
+ # settings) still wins over this, exactly as it already does over the
+ # router-wide default.
+ enable_tag_filtering: bool | None = None
+
def __init__(self, id: str | int | None = None, **params) -> None:
if id is None:
id = str(uuid.uuid4()) # Generate a UUID if id is None or not provided
diff --git a/ruff-strict-budget.json b/ruff-strict-budget.json
index da0f608fdb5..12a98dee7ed 100644
--- a/ruff-strict-budget.json
+++ b/ruff-strict-budget.json
@@ -24,7 +24,7 @@
"limit": 133
},
"ANN401": {
- "limit": 1495
+ "limit": 1491
},
"ASYNC230": {
"limit": 11
diff --git a/tests/test_litellm/proxy/test_litellm_pre_call_utils.py b/tests/test_litellm/proxy/test_litellm_pre_call_utils.py
index f48e1dba601..293cce5fa5d 100644
--- a/tests/test_litellm/proxy/test_litellm_pre_call_utils.py
+++ b/tests/test_litellm/proxy/test_litellm_pre_call_utils.py
@@ -6309,3 +6309,239 @@ class TestPromotedTraceControlFields:
assert "litellm_metadata" not in updated
assert updated["metadata"]["trace_id"] == "trace-1"
assert updated["metadata"]["session_id"] == "session-1"
+
+
+async def test_add_litellm_data_to_request_inherited_tags_excludes_caller_tags():
+ """inherited_tags must carry only what key/team/project policy contributed,
+ never anything the caller's own request (header/body) supplied, even when the
+ caller resubmits the identical value -- it's a snapshot taken before the
+ caller's own tags are merged in, not a set difference against caller_tags.
+ tag_based_routing.py's allow_fail_open relies on this so a caller can't strip
+ an inherited constraint's protection by resubmitting its exact value."""
+ request_mock = MagicMock(spec=Request)
+ request_mock.url.path = "/v1/chat/completions"
+ request_mock.url = MagicMock()
+ request_mock.url.__str__.return_value = "http://localhost/v1/chat/completions"
+ request_mock.method = "POST"
+ request_mock.query_params = {}
+ request_mock.headers = {"Content-Type": "application/json"}
+ request_mock.client = MagicMock()
+ request_mock.client.host = "127.0.0.1"
+
+ data = {
+ "model": "gpt-3.5-turbo",
+ # Caller resubmits the exact value the key policy also contributes.
+ "tags": ["key-supplied"],
+ }
+
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key="hashed-key",
+ user_id="real-user",
+ metadata={"tags": ["key-supplied"]},
+ team_metadata={"tags": ["team-supplied"]},
+ spend=0.0,
+ max_budget=100.0,
+ model_max_budget={},
+ team_spend=0.0,
+ team_max_budget=200.0,
+ )
+
+ updated = await add_litellm_data_to_request(
+ data=data,
+ request=request_mock,
+ user_api_key_dict=user_api_key_dict,
+ proxy_config=MagicMock(),
+ general_settings={},
+ version="test-version",
+ )
+
+ assert set(updated["metadata"]["tags"]) == {"key-supplied", "team-supplied"}
+ assert set(updated["metadata"]["inherited_tags"]) == {"key-supplied", "team-supplied"}
+ assert tuple(updated["metadata"]["caller_tags"]) == ("key-supplied",)
+
+
+async def test_add_litellm_data_to_request_inherited_tags_survives_pre_auth_header_merge():
+ """Regression: apply_client_tag_policy_pre_auth (run from user_api_key_auth,
+ for _tag_max_budget_check) merges the caller's x-litellm-tags header into the
+ same metadata.tags list this function later reads from -- before this
+ function ever runs. A snapshot-based inherited_tags would misattribute that
+ caller-controlled value as policy-backed; inherited_tags must instead be read
+ directly from key/team/project metadata, immune to whatever the pre-auth pass
+ already merged into "tags"."""
+ request_mock = MagicMock(spec=Request)
+ request_mock.url.path = "/v1/chat/completions"
+ request_mock.url = MagicMock()
+ request_mock.url.__str__.return_value = "http://localhost/v1/chat/completions"
+ request_mock.method = "POST"
+ request_mock.query_params = {}
+ request_mock.headers = {"Content-Type": "application/json", "x-litellm-tags": "caller-invented-tag"}
+ request_mock.client = MagicMock()
+ request_mock.client.host = "127.0.0.1"
+
+ data: dict = {"model": "gpt-3.5-turbo"}
+
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key="hashed-key",
+ user_id="real-user",
+ metadata={"tags": ["key-supplied"]},
+ team_metadata={},
+ spend=0.0,
+ max_budget=100.0,
+ model_max_budget={},
+ team_spend=0.0,
+ team_max_budget=200.0,
+ )
+
+ # Simulate the real request pipeline: the pre-auth merge runs first, on the
+ # same data dict, before add_litellm_data_to_request is ever called.
+ LiteLLMProxyRequestSetup.apply_client_tag_policy_pre_auth(
+ request=request_mock,
+ request_data=data,
+ user_api_key_dict=user_api_key_dict,
+ )
+ assert data["metadata"]["tags"] == ["caller-invented-tag"]
+
+ updated = await add_litellm_data_to_request(
+ data=data,
+ request=request_mock,
+ user_api_key_dict=user_api_key_dict,
+ proxy_config=MagicMock(),
+ general_settings={},
+ version="test-version",
+ )
+
+ assert set(updated["metadata"]["tags"]) == {"caller-invented-tag", "key-supplied"}
+ assert updated["metadata"]["inherited_tags"] == ("key-supplied",)
+ assert updated["metadata"]["caller_tags"] == ("caller-invented-tag",)
+
+
+async def test_add_litellm_data_to_request_caller_tags_excludes_key_and_team_tags():
+ """caller_tags must carry only what the caller itself sent (header + body
+ tags), never anything merged in from key/team metadata, even though the
+ merged "tags" field (used for matching) legitimately contains all three."""
+ request_mock = MagicMock(spec=Request)
+ request_mock.url.path = "/v1/chat/completions"
+ request_mock.url = MagicMock()
+ request_mock.url.__str__.return_value = "http://localhost/v1/chat/completions"
+ request_mock.method = "POST"
+ request_mock.query_params = {}
+ request_mock.headers = {"Content-Type": "application/json"}
+ request_mock.client = MagicMock()
+ request_mock.client.host = "127.0.0.1"
+
+ data = {
+ "model": "gpt-3.5-turbo",
+ "tags": ["caller-supplied"],
+ }
+
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key="hashed-key",
+ user_id="real-user",
+ metadata={"tags": ["key-supplied"]},
+ team_metadata={"tags": ["team-supplied"]},
+ spend=0.0,
+ max_budget=100.0,
+ model_max_budget={},
+ team_spend=0.0,
+ team_max_budget=200.0,
+ )
+
+ updated = await add_litellm_data_to_request(
+ data=data,
+ request=request_mock,
+ user_api_key_dict=user_api_key_dict,
+ proxy_config=MagicMock(),
+ general_settings={},
+ version="test-version",
+ )
+
+ assert set(updated["metadata"]["tags"]) == {"caller-supplied", "key-supplied", "team-supplied"}
+ assert tuple(updated["metadata"]["caller_tags"]) == ("caller-supplied",)
+
+
+async def test_add_litellm_data_to_request_caller_tags_includes_header_tags():
+ """The x-litellm-tags header is as much a caller-controlled input as the
+ body's "tags" field; both must land in caller_tags."""
+ request_mock = MagicMock(spec=Request)
+ request_mock.url.path = "/v1/chat/completions"
+ request_mock.url = MagicMock()
+ request_mock.url.__str__.return_value = "http://localhost/v1/chat/completions"
+ request_mock.method = "POST"
+ request_mock.query_params = {}
+ request_mock.headers = {"Content-Type": "application/json", "x-litellm-tags": "header-tag"}
+ request_mock.client = MagicMock()
+ request_mock.client.host = "127.0.0.1"
+
+ data = {"model": "gpt-3.5-turbo"}
+
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key="hashed-key",
+ user_id="real-user",
+ metadata={"tags": ["key-supplied"]},
+ team_metadata={},
+ spend=0.0,
+ max_budget=100.0,
+ model_max_budget={},
+ team_spend=0.0,
+ team_max_budget=200.0,
+ )
+
+ updated = await add_litellm_data_to_request(
+ data=data,
+ request=request_mock,
+ user_api_key_dict=user_api_key_dict,
+ proxy_config=MagicMock(),
+ general_settings={},
+ version="test-version",
+ )
+
+ assert set(updated["metadata"]["tags"]) == {"header-tag", "key-supplied"}
+ assert tuple(updated["metadata"]["caller_tags"]) == ("header-tag",)
+
+
+async def test_add_litellm_data_to_request_caller_tags_empty_when_caller_sends_nothing():
+ """caller_tags must be present (an empty tuple), not absent, when the caller
+ supplied no tags of their own -- an empty-but-present value tells
+ tag_based_routing.py's allow_fail_open that any required/excluded tag on the
+ request is entirely inherited, not that no origin information is available.
+ """
+ request_mock = MagicMock(spec=Request)
+ request_mock.url.path = "/v1/chat/completions"
+ request_mock.url = MagicMock()
+ request_mock.url.__str__.return_value = "http://localhost/v1/chat/completions"
+ request_mock.method = "POST"
+ request_mock.query_params = {}
+ request_mock.headers = {"Content-Type": "application/json"}
+ request_mock.client = MagicMock()
+ request_mock.client.host = "127.0.0.1"
+
+ data = {"model": "gpt-3.5-turbo"}
+
+ user_api_key_dict = UserAPIKeyAuth(
+ api_key="hashed-key",
+ user_id="real-user",
+ metadata={"tags": ["key-supplied"]},
+ team_metadata={},
+ spend=0.0,
+ max_budget=100.0,
+ model_max_budget={},
+ team_spend=0.0,
+ team_max_budget=200.0,
+ )
+
+ updated = await add_litellm_data_to_request(
+ data=data,
+ request=request_mock,
+ user_api_key_dict=user_api_key_dict,
+ proxy_config=MagicMock(),
+ general_settings={},
+ version="test-version",
+ )
+
+ assert updated["metadata"]["tags"] == ["key-supplied"]
+ assert updated["metadata"]["caller_tags"] == ()
diff --git a/tests/test_litellm/router_strategy/test_router_tag_regex_routing.py b/tests/test_litellm/router_strategy/test_router_tag_regex_routing.py
index dca2bd84f92..6591478a4e7 100644
--- a/tests/test_litellm/router_strategy/test_router_tag_regex_routing.py
+++ b/tests/test_litellm/router_strategy/test_router_tag_regex_routing.py
@@ -112,6 +112,7 @@ def _make_router_mock(enable_tag_filtering=True, match_any=True):
mock = MagicMock()
mock.enable_tag_filtering = enable_tag_filtering
mock.tag_filtering_match_any = match_any
+ mock.tag_routing_prefix = ""
return mock
diff --git a/tests/test_litellm/router_strategy/test_router_tag_routing.py b/tests/test_litellm/router_strategy/test_router_tag_routing.py
index 98506aad594..9e19e981f80 100644
--- a/tests/test_litellm/router_strategy/test_router_tag_routing.py
+++ b/tests/test_litellm/router_strategy/test_router_tag_routing.py
@@ -429,42 +429,58 @@ def test_get_tags_from_request_kwargs_various_inputs():
def test_split_tags_positive_only():
from litellm.router_strategy.tag_based_routing import _split_tags
- positive, excluded = _split_tags(["paid", "teamA"])
+ required, positive, excluded = _split_tags(["paid", "teamA"])
+ assert required == ()
assert positive == ["paid", "teamA"]
- assert excluded == []
+ assert excluded == ()
def test_split_tags_negation_only():
from litellm.router_strategy.tag_based_routing import _split_tags
- positive, excluded = _split_tags(["!provider:anthropic"])
+ required, positive, excluded = _split_tags(["!provider:anthropic"])
+ assert required == ()
assert positive == []
- assert excluded == ["provider:anthropic"]
+ assert excluded == ("provider:anthropic",)
+
+
+def test_split_tags_required_only():
+ from litellm.router_strategy.tag_based_routing import _split_tags
+
+ required, positive, excluded = _split_tags(["&reasoning_type:high", "&provider:anthropic"])
+ assert required == ("reasoning_type:high", "provider:anthropic")
+ assert positive == []
+ assert excluded == ()
def test_split_tags_mixed():
from litellm.router_strategy.tag_based_routing import _split_tags
- positive, excluded = _split_tags(["paid", "!provider:anthropic", "!inference:cerebras"])
+ required, positive, excluded = _split_tags(
+ ["paid", "!provider:anthropic", "!inference:cerebras", "&reasoning_type:high"]
+ )
+ assert required == ("reasoning_type:high",)
assert positive == ["paid"]
assert len(excluded) == 2
-def test_split_tags_bare_bang_skipped():
+def test_split_tags_bare_bang_and_amp_skipped():
from litellm.router_strategy.tag_based_routing import _split_tags
- # A bare "!" with nothing after it is not a valid negation tag; skip it
- positive, excluded = _split_tags(["paid", "!"])
+ # A bare "!" or "&" with nothing after it is not a valid tag; skip it
+ required, positive, excluded = _split_tags(["paid", "!", "&"])
+ assert required == ()
assert positive == ["paid"]
- assert excluded == []
+ assert excluded == ()
def test_split_tags_empty():
from litellm.router_strategy.tag_based_routing import _split_tags
- positive, excluded = _split_tags([])
+ required, positive, excluded = _split_tags([])
+ assert required == ()
assert positive == []
- assert excluded == []
+ assert excluded == ()
# --- get_deployments_for_tag negation integration tests ---
@@ -1115,3 +1131,1682 @@ async def test_request_level_enable_tag_filtering_false_cannot_disable_global():
mock_response="hi",
)
assert response._hidden_params["model_id"] == "team-a-deployment"
+
+
+# --- model_info.enable_tag_filtering per-chain override ---
+
+
+class _FakeRouterForChainOverride:
+ def __init__(self, all_deployments):
+ self._all_deployments = all_deployments
+
+ def _get_all_deployments(self, model_name):
+ return self._all_deployments
+
+
+def test_chain_tag_filtering_override_reads_any_member():
+ from litellm.router_strategy.tag_based_routing import _chain_tag_filtering_override
+
+ deployments = [
+ {"model_info": {}},
+ {"model_info": {"enable_tag_filtering": False}},
+ ]
+ router = _FakeRouterForChainOverride(deployments)
+ assert _chain_tag_filtering_override(router, "gpt-4", deployments) is False
+
+
+def test_chain_tag_filtering_override_none_when_unset_anywhere():
+ from litellm.router_strategy.tag_based_routing import _chain_tag_filtering_override
+
+ deployments = [{"model_info": {}}, {}]
+ router = _FakeRouterForChainOverride(deployments)
+ assert _chain_tag_filtering_override(router, "gpt-4", deployments) is None
+
+
+def test_chain_tag_filtering_override_survives_the_overriding_member_going_unhealthy():
+ # Regression: the per-group override must be resolved from every deployment
+ # configured for the model, not just the ones that survived cooldown/health
+ # filtering. async_get_healthy_deployments filters cooldowns before calling
+ # into get_deployments_for_tag, so healthy_deployments alone can be missing
+ # the one deployment that carries the group's only explicit override.
+ from litellm.router_strategy.tag_based_routing import _chain_tag_filtering_override
+
+ all_deployments = [
+ {"model_info": {"enable_tag_filtering": True}},
+ {"model_info": {}},
+ ]
+ router = _FakeRouterForChainOverride(all_deployments)
+ # The overriding deployment (index 0) is cooled down and absent from
+ # healthy_deployments -- the override must still be found via the full-group
+ # lookup, not silently lost.
+ healthy_deployments = [all_deployments[1]]
+ assert _chain_tag_filtering_override(router, "gpt-4", healthy_deployments) is True
+
+
+def test_chain_tag_filtering_override_falls_back_to_healthy_deployments_on_lookup_error():
+ from litellm.router_strategy.tag_based_routing import _chain_tag_filtering_override
+
+ class _BrokenRouter:
+ def _get_all_deployments(self, model_name):
+ raise RuntimeError("model group not found")
+
+ healthy_deployments = [{"model_info": {"enable_tag_filtering": False}}]
+ assert _chain_tag_filtering_override(_BrokenRouter(), "gpt-4", healthy_deployments) is False
+
+
+async def test_chain_enable_tag_filtering_true_overrides_router_level_false():
+ # Router-wide tag filtering is off; this model group opts in on its own via
+ # model_info.enable_tag_filtering, so tags still apply to requests for it.
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["teamA"],
+ },
+ "model_info": {"id": "team-a-deployment", "enable_tag_filtering": True},
+ },
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o-mini",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["teamB"],
+ },
+ "model_info": {"id": "team-b-deployment", "enable_tag_filtering": True},
+ },
+ ],
+ enable_tag_filtering=False,
+ )
+
+ for _ in range(5):
+ response = await router.acompletion(
+ model="gpt-4",
+ messages=[{"role": "user", "content": "hi"}],
+ metadata={"tags": ["teamA"]},
+ mock_response="hi",
+ )
+ assert response._hidden_params["model_id"] == "team-a-deployment"
+
+
+async def test_chain_enable_tag_filtering_false_overrides_router_level_true():
+ # Router-wide tag filtering is on, but this model group opts itself out via
+ # model_info.enable_tag_filtering: tags are ignored for requests to this group,
+ # so an untagged-style request just gets ordinary load-balanced routing.
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["teamA"],
+ },
+ "model_info": {"id": "team-a-deployment", "enable_tag_filtering": False},
+ },
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o-mini",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["teamB"],
+ },
+ "model_info": {"id": "team-b-deployment", "enable_tag_filtering": False},
+ },
+ ],
+ enable_tag_filtering=True,
+ )
+
+ seen_ids = set()
+ for _ in range(10):
+ response = await router.acompletion(
+ model="gpt-4",
+ messages=[{"role": "user", "content": "hi"}],
+ metadata={"tags": ["teamA"]},
+ mock_response="hi",
+ )
+ seen_ids.add(response._hidden_params["model_id"])
+
+ assert seen_ids == {"team-a-deployment", "team-b-deployment"}
+
+
+async def test_request_level_enable_tag_filtering_still_wins_over_chain_level_false():
+ # A key/team's own request-level enable_tag_filtering=True must still win over
+ # a chain that opted itself out, exactly as it already wins over the router
+ # default: request-level escalation is the highest-precedence layer.
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["teamA"],
+ },
+ "model_info": {"id": "team-a-deployment", "enable_tag_filtering": False},
+ },
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o-mini",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["teamB"],
+ },
+ "model_info": {"id": "team-b-deployment", "enable_tag_filtering": False},
+ },
+ ],
+ enable_tag_filtering=False,
+ )
+
+ for _ in range(5):
+ response = await router.acompletion(
+ model="gpt-4",
+ messages=[{"role": "user", "content": "hi"}],
+ metadata={"tags": ["teamA"]},
+ enable_tag_filtering=True,
+ mock_response="hi",
+ )
+ assert response._hidden_params["model_id"] == "team-a-deployment"
+
+
+# --- _require_all_tags / _chain_allows_fail_open unit tests ---
+
+
+def test_require_all_tags_empty_required_set_is_noop():
+ from litellm.router_strategy.tag_based_routing import _require_all_tags
+
+ deployments = [{"litellm_params": {"tags": ["a"]}}, {"litellm_params": {"tags": []}}]
+ assert _require_all_tags(deployments, frozenset()) == tuple(deployments)
+
+
+def test_require_all_tags_keeps_only_deployments_with_every_required_tag():
+ from litellm.router_strategy.tag_based_routing import _require_all_tags
+
+ has_both = {"litellm_params": {"tags": ["reasoning_type:high", "provider:anthropic"]}}
+ has_one = {"litellm_params": {"tags": ["reasoning_type:high"]}}
+ has_neither = {"litellm_params": {"tags": ["provider:openai"]}}
+
+ result = _require_all_tags(
+ [has_both, has_one, has_neither], frozenset({"reasoning_type:high", "provider:anthropic"})
+ )
+ assert result == (has_both,)
+
+
+def test_chain_allows_fail_open_true_when_any_member_sets_flag():
+ from litellm.router_strategy.tag_based_routing import _chain_allows_fail_open
+
+ deployments = [
+ {"model_info": {}, "litellm_params": {"tags": ["provider:anthropic"]}},
+ {"model_info": {"allow_fail_open": True}, "litellm_params": {"tags": ["provider:openai"]}},
+ ]
+ assert _chain_allows_fail_open(deployments, frozenset(), frozenset({"provider:anthropic"}), frozenset()) is True
+
+
+def test_chain_allows_fail_open_false_by_default():
+ from litellm.router_strategy.tag_based_routing import _chain_allows_fail_open
+
+ deployments = [{"model_info": {}}, {}]
+ assert _chain_allows_fail_open(deployments, frozenset(), frozenset(), frozenset()) is False
+
+
+def test_chain_allows_fail_open_true_when_no_required_tag_is_known_at_all():
+ # An entirely-invented required tag with nothing else known to compare against
+ # has no narrower answer to hide; a single-deployment catch-all fallback is a
+ # legitimate use of allow_fail_open, not something to deny.
+ from litellm.router_strategy.tag_based_routing import _chain_allows_fail_open
+
+ deployments = [
+ {"model_info": {"allow_fail_open": True}, "litellm_params": {"tags": ["default", "reasoning_type:low"]}},
+ ]
+ assert _chain_allows_fail_open(deployments, frozenset(), frozenset({"reasoning_type:high"}), frozenset()) is True
+
+
+def test_unknown_required_tag_hides_an_answer_denies_fail_open():
+ from litellm.router_strategy.tag_based_routing import _chain_allows_fail_open
+
+ deployments = [
+ {
+ "model_info": {},
+ "litellm_params": {"tags": ["provider:anthropic", "region:us-east"]},
+ },
+ {
+ "model_info": {"allow_fail_open": True},
+ "litellm_params": {"tags": ["default", "provider:openai"]},
+ },
+ ]
+ # region:us-east is real and satisfiable on the first deployment; the invented tag
+ # alone forces emptiness. Dropping it reveals a specific, non-default answer, so
+ # fail-open must be denied even though the flag is set on the group.
+ assert (
+ _chain_allows_fail_open(
+ deployments, frozenset(), frozenset({"region:us-east", "totally-invented-tag-nobody-has"}), frozenset()
+ )
+ is False
+ )
+
+
+def test_unknown_required_tag_allows_fail_open_when_no_answer_is_hidden():
+ from litellm.router_strategy.tag_based_routing import _chain_allows_fail_open
+
+ deployments = [
+ {
+ "model_info": {"allow_fail_open": True},
+ "litellm_params": {"tags": ["provider:anthropic", "region:us-east"]},
+ },
+ {
+ "model_info": {"allow_fail_open": True},
+ "litellm_params": {"tags": ["provider:eu", "region:eu"]},
+ },
+ {
+ "model_info": {"allow_fail_open": True},
+ "litellm_params": {"tags": ["default", "provider:openai"]},
+ },
+ ]
+ # region:us-east and region:eu are both real, known tags; no single deployment
+ # carries both, so this is a genuinely unsatisfiable combination, not an invented
+ # tag masking a narrower answer. Fail-open must proceed normally.
+ assert (
+ _chain_allows_fail_open(deployments, frozenset(), frozenset({"region:us-east", "region:eu"}), frozenset())
+ is True
+ )
+
+
+# --- _strip_routing_prefix / _bare_tag_value unit tests ---
+
+
+def test_strip_routing_prefix_empty_prefix_is_noop():
+ from litellm.router_strategy.tag_based_routing import _strip_routing_prefix
+
+ tags = ["provider:anthropic", "&region:eu", "!region:us"]
+ rewritten, confirmed = _strip_routing_prefix(tags, "")
+ assert rewritten == tuple(tags)
+ assert confirmed == frozenset()
+
+
+def test_strip_routing_prefix_splits_routed_from_other():
+ from litellm.router_strategy.tag_based_routing import _strip_routing_prefix
+
+ rewritten, confirmed = _strip_routing_prefix(["feature:demo", "route:!provider:openai"], "route:")
+ assert rewritten == ("feature:demo", "!provider:openai")
+ assert confirmed == frozenset({"provider:openai"})
+
+
+def test_strip_routing_prefix_confirmed_matches_bare_required_and_excluded_values():
+ # Regression: confirmed must carry the same bare (marker-stripped) form that
+ # _split_tags produces for required_set/excluded_set downstream. A prior bug
+ # left the "&"/"!" marker in `confirmed`, so `required_set & routing_confirmed`
+ # never intersected for any prefixed "&"/"!" tag -- the entire "trusted,
+ # caller-declared required/excluded tag" mechanism silently no-opped.
+ from litellm.router_strategy.tag_based_routing import _strip_routing_prefix
+
+ _, confirmed = _strip_routing_prefix(["route:&provider:anthropic", "route:!region:eu"], "route:")
+ assert confirmed == frozenset({"provider:anthropic", "region:eu"})
+
+
+def test_strip_routing_prefix_lone_marker_confirms_nothing():
+ from litellm.router_strategy.tag_based_routing import _strip_routing_prefix
+
+ # A lone "&"/"!" with nothing after it parses to nothing in required_set,
+ # excluded_set, or positive_tags (see test_split_tags_bare_bang_and_amp_skipped);
+ # confirmed must not invent a value for it either.
+ _, confirmed = _strip_routing_prefix(["route:&", "route:!"], "route:")
+ assert confirmed == frozenset()
+
+
+def test_chain_allows_fail_open_true_when_prefixed_unknown_required_tag_is_confirmed():
+ # Regression for the same bug: a required tag no deployment carries is normally
+ # treated as invented noise that can hide a narrower answer (see
+ # test_unknown_required_tag_hides_an_answer_denies_fail_open) -- but once the
+ # caller has explicitly marked it via the routing prefix, it counts as a known,
+ # honest ask, and fail-open must proceed rather than get denied.
+ from litellm.router_strategy.tag_based_routing import _chain_allows_fail_open
+
+ deployments = [
+ {
+ "model_info": {"allow_fail_open": True},
+ "litellm_params": {"tags": ["default", "provider:anthropic"]},
+ },
+ ]
+ required_set = frozenset({"provider:anthropic", "typo-tag"})
+ assert _chain_allows_fail_open(deployments, frozenset(), required_set, frozenset()) is False
+ assert _chain_allows_fail_open(deployments, frozenset(), required_set, required_set) is True
+
+
+# --- get_deployments_for_tag required-AND ("&") integration tests ---
+
+
+async def test_required_and_matches_deployment_with_all_tags():
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["reasoning_type:high", "provider:anthropic"],
+ },
+ "model_info": {"id": "high-reasoning-anthropic"},
+ },
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o-mini",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["reasoning_type:high", "provider:openai"],
+ },
+ "model_info": {"id": "high-reasoning-openai"},
+ },
+ ],
+ enable_tag_filtering=True,
+ )
+
+ for _ in range(5):
+ response = await router.acompletion(
+ model="gpt-4",
+ messages=[{"role": "user", "content": "hi"}],
+ metadata={"tags": ["&reasoning_type:high", "&provider:anthropic"]},
+ mock_response="hi",
+ )
+ assert response._hidden_params["model_id"] == "high-reasoning-anthropic"
+
+
+async def test_required_and_excludes_deployment_missing_one_tag():
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["reasoning_type:high", "provider:anthropic"],
+ },
+ "model_info": {"id": "high-reasoning-anthropic"},
+ },
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o-mini",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["reasoning_type:low", "provider:anthropic"],
+ },
+ "model_info": {"id": "low-reasoning-anthropic"},
+ },
+ ],
+ enable_tag_filtering=True,
+ )
+
+ for _ in range(5):
+ response = await router.acompletion(
+ model="gpt-4",
+ messages=[{"role": "user", "content": "hi"}],
+ metadata={"tags": ["&reasoning_type:high", "&provider:anthropic"]},
+ mock_response="hi",
+ )
+ assert response._hidden_params["model_id"] == "high-reasoning-anthropic"
+
+
+async def test_required_and_composes_with_negation():
+ # &reasoning_type:high requires the tag; !provider:anthropic bans that provider.
+ # Negation applies first, so the anthropic deployment is excluded even though
+ # it satisfies the required tag.
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["reasoning_type:high", "provider:anthropic"],
+ },
+ "model_info": {"id": "high-reasoning-anthropic"},
+ },
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o-mini",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["reasoning_type:high", "provider:openai"],
+ },
+ "model_info": {"id": "high-reasoning-openai"},
+ },
+ ],
+ enable_tag_filtering=True,
+ )
+
+ for _ in range(5):
+ response = await router.acompletion(
+ model="gpt-4",
+ messages=[{"role": "user", "content": "hi"}],
+ metadata={"tags": ["&reasoning_type:high", "!provider:anthropic"]},
+ mock_response="hi",
+ )
+ assert response._hidden_params["model_id"] == "high-reasoning-openai"
+
+
+async def test_required_and_combines_with_positive_or_preference():
+ # &reasoning_type:high is a hard requirement; provider:anthropic/provider:openai
+ # is a preference (OR) applied on top of the survivors.
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["reasoning_type:high", "provider:anthropic"],
+ },
+ "model_info": {"id": "high-reasoning-anthropic"},
+ },
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o-mini",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["reasoning_type:high", "provider:vertex"],
+ },
+ "model_info": {"id": "high-reasoning-vertex"},
+ },
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["reasoning_type:low", "provider:anthropic"],
+ },
+ "model_info": {"id": "low-reasoning-anthropic"},
+ },
+ ],
+ enable_tag_filtering=True,
+ )
+
+ for _ in range(5):
+ response = await router.acompletion(
+ model="gpt-4",
+ messages=[{"role": "user", "content": "hi"}],
+ metadata={"tags": ["&reasoning_type:high", "provider:anthropic", "provider:openai"]},
+ mock_response="hi",
+ )
+ assert response._hidden_params["model_id"] == "high-reasoning-anthropic"
+
+
+async def test_required_and_single_tag_matches_trivially():
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["reasoning_type:high"],
+ },
+ "model_info": {"id": "high-reasoning"},
+ },
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o-mini",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["reasoning_type:low"],
+ },
+ "model_info": {"id": "low-reasoning"},
+ },
+ ],
+ enable_tag_filtering=True,
+ )
+
+ for _ in range(5):
+ response = await router.acompletion(
+ model="gpt-4",
+ messages=[{"role": "user", "content": "hi"}],
+ metadata={"tags": ["&reasoning_type:high"]},
+ mock_response="hi",
+ )
+ assert response._hidden_params["model_id"] == "high-reasoning"
+
+
+async def test_required_and_unmatched_raises_by_default():
+ # allow_fail_open unset -> unmatched required-AND raises, same as today's "!" behavior.
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["reasoning_type:low"],
+ },
+ "model_info": {"id": "low-reasoning"},
+ },
+ ],
+ enable_tag_filtering=True,
+ )
+
+ with pytest.raises(Exception) as exc_info:
+ await router.acompletion(
+ model="gpt-4",
+ messages=[{"role": "user", "content": "hi"}],
+ metadata={"tags": ["&reasoning_type:high"]},
+ mock_response="hi",
+ )
+
+ from litellm.types.router import RouterErrors
+
+ assert RouterErrors.no_deployments_with_tag_routing.value in str(exc_info.value)
+
+
+async def test_required_and_combined_with_positive_unmatched_raises_by_default():
+ # &A eliminates every candidate before the positive-tag preference even runs;
+ # this must be gated by allow_fail_open too, not just the required-AND-only path.
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["reasoning_type:low", "provider:anthropic"],
+ },
+ "model_info": {"id": "low-reasoning-anthropic"},
+ },
+ ],
+ enable_tag_filtering=True,
+ )
+
+ with pytest.raises(Exception) as exc_info:
+ await router.acompletion(
+ model="gpt-4",
+ messages=[{"role": "user", "content": "hi"}],
+ metadata={"tags": ["&reasoning_type:high", "provider:anthropic"]},
+ mock_response="hi",
+ )
+
+ from litellm.types.router import RouterErrors
+
+ assert RouterErrors.no_deployments_with_tag_routing.value in str(exc_info.value)
+
+
+# --- get_deployments_for_tag allow_fail_open integration tests ---
+
+
+async def test_allow_fail_open_required_and_unmatched_falls_back_to_default_pool():
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["default", "reasoning_type:low"],
+ },
+ "model_info": {"id": "default-model", "allow_fail_open": True},
+ },
+ ],
+ enable_tag_filtering=True,
+ )
+
+ for _ in range(5):
+ response = await router.acompletion(
+ model="gpt-4",
+ messages=[{"role": "user", "content": "hi"}],
+ metadata={"tags": ["&reasoning_type:high"]},
+ mock_response="hi",
+ )
+ assert response._hidden_params["model_id"] == "default-model"
+
+
+async def test_allow_fail_open_negation_eliminates_everything_includes_banned_deployment():
+ # The core backwards-compatibility risk: once allow_fail_open opts a chain in,
+ # a "!" ban that eliminates every deployment falls back to the full default
+ # pool, INCLUDING the deployment the request tried to ban. This must never
+ # silently disappear (still raise) nor silently reappear on chains without
+ # the flag set (see test_negation_all_excluded_raises).
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["provider:anthropic"],
+ },
+ "model_info": {"id": "anthropic-model", "allow_fail_open": True},
+ },
+ ],
+ enable_tag_filtering=True,
+ )
+
+ for _ in range(5):
+ response = await router.acompletion(
+ model="gpt-4",
+ messages=[{"role": "user", "content": "hi"}],
+ metadata={"tags": ["!provider:anthropic"]},
+ mock_response="hi",
+ )
+ assert response._hidden_params["model_id"] == "anthropic-model"
+
+
+async def test_allow_fail_open_prefers_default_tagged_deployment_on_fallback():
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["provider:anthropic"],
+ },
+ "model_info": {"id": "anthropic-model", "allow_fail_open": True},
+ },
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o-mini",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["provider:anthropic", "default"],
+ },
+ "model_info": {"id": "anthropic-default-model", "allow_fail_open": True},
+ },
+ ],
+ enable_tag_filtering=True,
+ )
+
+ for _ in range(5):
+ response = await router.acompletion(
+ model="gpt-4",
+ messages=[{"role": "user", "content": "hi"}],
+ metadata={"tags": ["!provider:anthropic"]},
+ mock_response="hi",
+ )
+ assert response._hidden_params["model_id"] == "anthropic-default-model"
+
+
+async def test_allow_fail_open_per_hop_across_fallback_chain():
+ # required-AND fail-open must be re-evaluated fresh on every hop, the same
+ # per-hop guarantee the negation feature already established.
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "primary",
+ "litellm_params": {
+ "model": "gpt-4o",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["reasoning_type:low"],
+ },
+ "model_info": {"id": "primary-low-reasoning"},
+ },
+ {
+ "model_name": "fallback",
+ "litellm_params": {
+ "model": "gpt-4o-mini",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["default", "reasoning_type:low"],
+ },
+ "model_info": {"id": "fallback-model", "allow_fail_open": True},
+ },
+ ],
+ fallbacks=[{"primary": ["fallback"]}],
+ enable_tag_filtering=True,
+ )
+
+ response = await router.acompletion(
+ model="primary",
+ messages=[{"role": "user", "content": "hi"}],
+ metadata={"tags": ["&reasoning_type:high"]},
+ mock_response="hi",
+ )
+ assert response._hidden_params["model_id"] == "fallback-model"
+
+
+async def test_allow_fail_open_resolves_locally_without_triggering_external_fallback():
+ # allow_fail_open on the primary group's own default deployment absorbs the
+ # exhaustion internally (_resolve_or_fail_open returns a non-empty pool, so
+ # get_deployments_for_tag never raises); router.async_function_with_fallbacks
+ # only invokes the configured "fallbacks" chain on an exception, so a
+ # separate, unrelated fallback group must never be touched even though one is
+ # configured. A fallback deployment that would trivially satisfy the request
+ # tag if it were ever consulted makes this a meaningful negative assertion,
+ # not a vacuous one.
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "primary",
+ "litellm_params": {
+ "model": "gpt-4o",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["reasoning_type:high"],
+ },
+ "model_info": {"id": "primary-high-reasoning"},
+ },
+ {
+ "model_name": "primary",
+ "litellm_params": {
+ "model": "gpt-4o-mini",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["default", "reasoning_type:low"],
+ },
+ "model_info": {"id": "primary-default", "allow_fail_open": True},
+ },
+ {
+ "model_name": "fallback",
+ "litellm_params": {
+ "model": "gpt-4o-mini",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["region:eu"],
+ },
+ "model_info": {"id": "fallback-should-never-be-used"},
+ },
+ ],
+ fallbacks=[{"primary": ["fallback"]}],
+ enable_tag_filtering=True,
+ )
+
+ response = await router.acompletion(
+ model="primary",
+ messages=[{"role": "user", "content": "hi"}],
+ metadata={"tags": ["&region:eu"]},
+ mock_response="hi",
+ )
+ assert response._hidden_params["model_id"] == "primary-default"
+
+
+# --- allow_fail_open must also gate "!" exhaustion combined with a plain positive tag ---
+
+
+async def test_negation_combined_with_positive_unmatched_raises_by_default():
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["provider:anthropic", "paid"],
+ },
+ "model_info": {"id": "anthropic-paid"},
+ },
+ ],
+ enable_tag_filtering=True,
+ )
+
+ with pytest.raises(Exception) as exc_info:
+ await router.acompletion(
+ model="gpt-4",
+ messages=[{"role": "user", "content": "hi"}],
+ metadata={"tags": ["!provider:anthropic", "paid"]},
+ mock_response="hi",
+ )
+
+ from litellm.types.router import RouterErrors
+
+ assert RouterErrors.no_deployments_with_tag_routing.value in str(exc_info.value)
+
+
+async def test_negation_combined_with_positive_unmatched_falls_open_when_allowed():
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["provider:anthropic", "paid", "default"],
+ },
+ "model_info": {"id": "anthropic-paid", "allow_fail_open": True},
+ },
+ ],
+ enable_tag_filtering=True,
+ )
+
+ for _ in range(5):
+ response = await router.acompletion(
+ model="gpt-4",
+ messages=[{"role": "user", "content": "hi"}],
+ metadata={"tags": ["!provider:anthropic", "paid"]},
+ mock_response="hi",
+ )
+ assert response._hidden_params["model_id"] == "anthropic-paid"
+
+
+# --- a required-AND-only request must not be diluted by incidental regex/header preference ---
+
+
+async def test_required_and_only_returns_every_matching_deployment_despite_regex_header():
+ # Deployment A satisfies &reasoning_type:high and also happens to carry a tag_regex
+ # that matches the caller's User-Agent. Deployment B also satisfies the required tag
+ # but has no tag_regex at all. A required-AND-only request (no plain positive tags)
+ # must be free to route to either survivor, not be narrowed down to only the one
+ # that happens to match the incidental regex/header preference.
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["reasoning_type:high"],
+ "tag_regex": ["^User-Agent: claude-code\\/"],
+ },
+ "model_info": {"id": "high-reasoning-with-regex"},
+ },
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o-mini",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["reasoning_type:high"],
+ },
+ "model_info": {"id": "high-reasoning-no-regex"},
+ },
+ ],
+ enable_tag_filtering=True,
+ )
+
+ seen_ids = set()
+ for _ in range(30):
+ response = await router.acompletion(
+ model="gpt-4",
+ messages=[{"role": "user", "content": "hi"}],
+ metadata={"tags": ["&reasoning_type:high"], "user_agent": "claude-code/1.2.3"},
+ mock_response="hi",
+ )
+ seen_ids.add(response._hidden_params["model_id"])
+
+ assert seen_ids == {"high-reasoning-with-regex", "high-reasoning-no-regex"}
+
+
+async def test_required_and_only_excludes_regex_deployment_missing_the_required_tag():
+ # The tag_regex deployment matches the caller's User-Agent but does NOT carry the
+ # required tag; a required-AND-only request must not let it through on the strength
+ # of the regex/header match alone.
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["reasoning_type:low"],
+ "tag_regex": ["^User-Agent: claude-code\\/"],
+ },
+ "model_info": {"id": "low-reasoning-with-regex"},
+ },
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o-mini",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["reasoning_type:high"],
+ },
+ "model_info": {"id": "high-reasoning-no-regex"},
+ },
+ ],
+ enable_tag_filtering=True,
+ )
+
+ for _ in range(5):
+ response = await router.acompletion(
+ model="gpt-4",
+ messages=[{"role": "user", "content": "hi"}],
+ metadata={"tags": ["&reasoning_type:high"], "user_agent": "claude-code/1.2.3"},
+ mock_response="hi",
+ )
+ assert response._hidden_params["model_id"] == "high-reasoning-no-regex"
+
+
+# --- allow_fail_open must also gate exhaustion after a non-empty required-AND survivor
+# set fails to match a plain preference tag, not just full !/& exhaustion ---
+
+
+async def test_mixed_constraint_survivor_unmatched_by_positive_tag_raises_by_default():
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["reasoning_type:high", "provider:anthropic"],
+ },
+ "model_info": {"id": "high-reasoning-anthropic"},
+ },
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o-mini",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["default", "reasoning_type:low"],
+ },
+ "model_info": {"id": "default-fallback"},
+ },
+ ],
+ enable_tag_filtering=True,
+ )
+
+ with pytest.raises(Exception) as exc_info:
+ await router.acompletion(
+ model="gpt-4",
+ messages=[{"role": "user", "content": "hi"}],
+ metadata={"tags": ["&reasoning_type:high", "provider:openai"]},
+ mock_response="hi",
+ )
+
+ from litellm.types.router import RouterErrors
+
+ assert RouterErrors.no_deployments_with_tag_routing.value in str(exc_info.value)
+
+
+async def test_mixed_constraint_survivor_unmatched_by_positive_tag_falls_open_when_allowed():
+ # &reasoning_type:high survives to a non-empty candidate set (the anthropic
+ # deployment), but the plain preference tag provider:openai matches none of the
+ # survivors, and the surviving deployment itself is not "default"-tagged (so the
+ # pre-existing in-loop default-collection escape hatch can't mask the fix). Greptile
+ # flagged this exact path as bypassing allow_fail_open by raising unconditionally;
+ # it must instead fall back to the group's actual default-tagged deployment, which
+ # is a different deployment than the one &reasoning_type:high matched.
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["reasoning_type:high", "provider:anthropic"],
+ },
+ "model_info": {"id": "high-reasoning-anthropic", "allow_fail_open": True},
+ },
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o-mini",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["default", "reasoning_type:low"],
+ },
+ "model_info": {"id": "default-fallback", "allow_fail_open": True},
+ },
+ ],
+ enable_tag_filtering=True,
+ )
+
+ for _ in range(5):
+ response = await router.acompletion(
+ model="gpt-4",
+ messages=[{"role": "user", "content": "hi"}],
+ metadata={"tags": ["&reasoning_type:high", "provider:openai"]},
+ mock_response="hi",
+ )
+ assert response._hidden_params["model_id"] == "default-fallback"
+
+
+# --- allow_fail_open must not be triggerable by an invented tag the chain has never
+# carried; a caller-supplied garbage tag must not be able to force an otherwise-
+# satisfiable constraint (e.g. one inherited from the key/team) to be discarded ---
+
+
+async def test_allow_fail_open_denied_when_request_includes_unknown_tag():
+ # region:us-east is a real, satisfiable constraint on anthropic-deployment. Adding
+ # a single invented tag no deployment in this group has ever carried empties the
+ # required-AND set regardless of region:us-east's own satisfiability. allow_fail_open
+ # is set on the default deployment, but must not fire here: none of the *other*
+ # deployments carry the invented tag either, so it is unknown to the chain, and
+ # falling back would silently discard the still-satisfiable region:us-east ask.
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["provider:anthropic", "region:us-east"],
+ },
+ "model_info": {"id": "anthropic-deployment"},
+ },
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o-mini",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["default", "provider:openai"],
+ },
+ "model_info": {"id": "openai-default", "allow_fail_open": True},
+ },
+ ],
+ enable_tag_filtering=True,
+ )
+
+ with pytest.raises(Exception) as exc_info:
+ await router.acompletion(
+ model="gpt-4",
+ messages=[{"role": "user", "content": "hi"}],
+ metadata={"tags": ["&region:us-east", "&totally-invented-tag-nobody-has"]},
+ mock_response="hi",
+ )
+
+ from litellm.types.router import RouterErrors
+
+ assert RouterErrors.no_deployments_with_tag_routing.value in str(exc_info.value)
+
+
+async def test_allow_fail_open_still_fires_when_every_requested_tag_is_known():
+ # region:us-east and region:eu are both real tags this chain uses; no single
+ # deployment carries both, so the combination is genuinely unsatisfiable, not
+ # invented. allow_fail_open must still fall back normally in this case.
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["provider:anthropic", "region:us-east"],
+ },
+ "model_info": {"id": "anthropic-deployment", "allow_fail_open": True},
+ },
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o-mini",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["provider:eu", "region:eu"],
+ },
+ "model_info": {"id": "eu-deployment", "allow_fail_open": True},
+ },
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "openai/gpt-4o-mini",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["default", "provider:openai"],
+ },
+ "model_info": {"id": "openai-default", "allow_fail_open": True},
+ },
+ ],
+ enable_tag_filtering=True,
+ )
+
+ for _ in range(5):
+ response = await router.acompletion(
+ model="gpt-4",
+ messages=[{"role": "user", "content": "hi"}],
+ metadata={"tags": ["&region:us-east", "&region:eu"]},
+ mock_response="hi",
+ )
+ assert response._hidden_params["model_id"] == "openai-default"
+
+
+# --- required-AND, allow_fail_open, and the unknown-tag denial across fallback
+# chains spanning multiple model groups ---
+
+
+async def test_required_and_exhausts_primary_group_falls_through_to_fallback_group():
+ # &reasoning_type:high matches nothing on "primary" (raises internally, same as
+ # negation's own fallback-chain behavior), so the router advances to "fallback"
+ # where the tag is satisfiable. No allow_fail_open involved; this is the plain
+ # fallback-chain mechanics already established for "!" extended to "&".
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "primary",
+ "litellm_params": {
+ "model": "gpt-4o",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["reasoning_type:low"],
+ },
+ "model_info": {"id": "primary-low-reasoning"},
+ },
+ {
+ "model_name": "fallback",
+ "litellm_params": {
+ "model": "gpt-4o-mini",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["reasoning_type:high"],
+ },
+ "model_info": {"id": "fallback-high-reasoning"},
+ },
+ ],
+ fallbacks=[{"primary": ["fallback"]}],
+ enable_tag_filtering=True,
+ )
+
+ response = await router.acompletion(
+ model="primary",
+ messages=[{"role": "user", "content": "hi"}],
+ metadata={"tags": ["&reasoning_type:high"]},
+ mock_response="hi",
+ )
+ assert response._hidden_params["model_id"] == "fallback-high-reasoning"
+
+
+async def test_required_and_negation_and_allow_fail_open_combine_across_three_model_groups():
+ # A single request routes through three independent model groups via two
+ # fallback hops, exercising "!", "&", and allow_fail_open together at each hop:
+ # - "primary" is banned outright by "!provider:anthropic" -> raises, advances.
+ # - "secondary" satisfies the negation but not &reasoning_type:high, and has no
+ # allow_fail_open -> raises exactly as today, advances.
+ # - "tertiary" has reasoning_type:high, but only on the deployment the same
+ # "!provider:anthropic" also bans; the tag is known to the chain but its only
+ # carrier is legitimately excluded, not hidden behind an invented tag, so the
+ # opted-in allow_fail_open falls back to the group's own default deployment.
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "primary",
+ "litellm_params": {
+ "model": "gpt-4o",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["provider:anthropic", "reasoning_type:high"],
+ },
+ "model_info": {"id": "primary-anthropic"},
+ },
+ {
+ "model_name": "secondary",
+ "litellm_params": {
+ "model": "gpt-4o-mini",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["provider:openai", "reasoning_type:low"],
+ },
+ "model_info": {"id": "secondary-openai"},
+ },
+ {
+ "model_name": "tertiary",
+ "litellm_params": {
+ "model": "gpt-4o",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["provider:anthropic", "reasoning_type:high", "region:eu"],
+ },
+ "model_info": {"id": "tertiary-anthropic-high-reasoning"},
+ },
+ {
+ "model_name": "tertiary",
+ "litellm_params": {
+ "model": "gpt-4o-mini",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["default", "provider:openai", "reasoning_type:low"],
+ },
+ "model_info": {"id": "tertiary-default", "allow_fail_open": True},
+ },
+ ],
+ fallbacks=[{"primary": ["secondary"]}, {"secondary": ["tertiary"]}],
+ enable_tag_filtering=True,
+ )
+
+ response = await router.acompletion(
+ model="primary",
+ messages=[{"role": "user", "content": "hi"}],
+ metadata={"tags": ["!provider:anthropic", "&reasoning_type:high"]},
+ mock_response="hi",
+ )
+ assert response._hidden_params["model_id"] == "tertiary-default"
+
+
+async def test_unknown_tag_denial_is_scoped_per_hop_not_leaked_across_fallback_groups():
+ # On "primary": region:us-east is real and satisfiable there, but the invented
+ # tag masks it -> denies fail-open -> raises -> advances to "fallback".
+ # On "fallback": neither region:us-east nor the invented tag is known to this
+ # entirely different, unrelated group at all, so there's no answer for the
+ # invented tag to hide -> falls open normally. Each hop must independently
+ # discover what its own group knows; a deny decision from a prior hop's group
+ # must not leak forward and block a later hop that has no relevant knowledge.
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "primary",
+ "litellm_params": {
+ "model": "gpt-4o",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["region:us-east"],
+ },
+ "model_info": {"id": "primary-us-east", "allow_fail_open": True},
+ },
+ {
+ "model_name": "fallback",
+ "litellm_params": {
+ "model": "gpt-4o-mini",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["default", "provider:openai"],
+ },
+ "model_info": {"id": "fallback-default", "allow_fail_open": True},
+ },
+ ],
+ fallbacks=[{"primary": ["fallback"]}],
+ enable_tag_filtering=True,
+ )
+
+ response = await router.acompletion(
+ model="primary",
+ messages=[{"role": "user", "content": "hi"}],
+ metadata={"tags": ["&region:us-east", "&totally-invented-tag-nobody-has"]},
+ mock_response="hi",
+ )
+ assert response._hidden_params["model_id"] == "fallback-default"
+
+
+async def test_required_and_only_finds_compliant_non_default_deployment_over_noncompliant_default():
+ # A required-AND-only request must be checked against every deployment in the
+ # group, not just the one tagged "default". A compliant, healthy deployment that
+ # simply isn't the operator's default must win over routing to a noncompliant
+ # default just because allow_fail_open happened to be set.
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["provider:anthropic", "region:us-east"],
+ },
+ "model_info": {"id": "anthropic-us-east"},
+ },
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o-mini",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["default", "provider:openai"],
+ },
+ "model_info": {"id": "openai-default", "allow_fail_open": True},
+ },
+ ],
+ enable_tag_filtering=True,
+ )
+
+ for _ in range(5):
+ response = await router.acompletion(
+ model="gpt-4",
+ messages=[{"role": "user", "content": "hi"}],
+ metadata={"tags": ["&region:us-east"]},
+ mock_response="hi",
+ )
+ assert response._hidden_params["model_id"] == "anthropic-us-east"
+
+
+# --- plain positive-tag exhaustion must not be masked by a universally-applied
+# "default" tag; allow_fail_open must still be consulted (or hard-fail without it) ---
+
+
+def _quality_high_cost_low_router():
+ return litellm.Router(
+ model_list=[
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["default", "quality:high"],
+ },
+ "model_info": {"id": "quality-high-1"},
+ },
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["default", "quality:high"],
+ },
+ "model_info": {"id": "quality-high-2"},
+ },
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o-mini",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["default", "cost:low"],
+ },
+ "model_info": {"id": "cost-low-1"},
+ },
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o-mini",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["default", "cost:low"],
+ },
+ "model_info": {"id": "cost-low-2"},
+ },
+ ],
+ enable_tag_filtering=True,
+ )
+
+
+async def test_plain_tag_exhaustion_with_universal_default_tag_raises_by_default():
+ # Every deployment in the group is tagged "default" (a legitimate cross-cutting
+ # safety-net pattern), so default_deployments is never empty on its own. With
+ # the quality:high deployments unhealthy, a request asking for quality:high
+ # must still hard-fail, not silently get served by a cost:low deployment just
+ # because it happens to also carry "default".
+ from unittest.mock import AsyncMock, patch
+
+ router = _quality_high_cost_low_router()
+
+ with patch(
+ "litellm.router._async_get_cooldown_deployments",
+ new=AsyncMock(return_value=["quality-high-1", "quality-high-2"]),
+ ):
+ with pytest.raises(Exception) as exc_info:
+ await router.acompletion(
+ model="gpt-4",
+ messages=[{"role": "user", "content": "hi"}],
+ metadata={"tags": ["quality:high"]},
+ mock_response="hi",
+ )
+
+ from litellm.types.router import RouterErrors
+
+ assert RouterErrors.no_deployments_with_tag_routing.value in str(exc_info.value)
+
+
+async def test_plain_tag_exhaustion_with_universal_default_tag_falls_open_when_allowed():
+ router = _quality_high_cost_low_router()
+ for deployment in router.model_list:
+ deployment["model_info"]["allow_fail_open"] = True
+
+ from unittest.mock import AsyncMock, patch
+
+ with patch(
+ "litellm.router._async_get_cooldown_deployments",
+ new=AsyncMock(return_value=["quality-high-1", "quality-high-2"]),
+ ):
+ response = await router.acompletion(
+ model="gpt-4",
+ messages=[{"role": "user", "content": "hi"}],
+ metadata={"tags": ["quality:high"]},
+ mock_response="hi",
+ )
+
+ assert response._hidden_params["model_id"] in ("cost-low-1", "cost-low-2")
+
+
+async def test_plain_tag_unknown_to_group_still_falls_back_silently_unconditionally():
+ # A tag that no deployment in this group has ever carried (foreign to this
+ # group entirely, e.g. an attribution tag meant for an unrelated mechanism
+ # sharing the same request-tags list) must keep falling back to the
+ # "default"-tagged pool unconditionally, exactly like today, regardless of
+ # allow_fail_open. Only a tag that IS part of this group's real vocabulary
+ # triggers the new hard-fail/fail-open gate.
+ router = _quality_high_cost_low_router()
+
+ for _ in range(5):
+ response = await router.acompletion(
+ model="gpt-4",
+ messages=[{"role": "user", "content": "hi"}],
+ metadata={"tags": ["llm-preference-include:some-unrelated-mechanism"]},
+ mock_response="hi",
+ )
+ assert response._hidden_params["model_id"] in (
+ "quality-high-1",
+ "quality-high-2",
+ "cost-low-1",
+ "cost-low-2",
+ )
+
+
+def test_tag_known_to_group_true_for_real_tag():
+ from litellm.router_strategy.tag_based_routing import _tag_known_to_group
+
+ router = _quality_high_cost_low_router()
+ assert _tag_known_to_group(router, "gpt-4", ["quality:high"], frozenset()) is True
+
+
+def test_tag_known_to_group_false_for_foreign_tag():
+ from litellm.router_strategy.tag_based_routing import _tag_known_to_group
+
+ router = _quality_high_cost_low_router()
+ assert _tag_known_to_group(router, "gpt-4", ["llm-preference-include:unrelated"], frozenset()) is False
+
+
+def test_inherited_constraint_sets_none_when_inherited_tags_absent():
+ from litellm.router_strategy.tag_based_routing import _inherited_constraint_sets
+
+ assert _inherited_constraint_sets(None, "") == (None, None)
+
+
+def test_inherited_constraint_sets_splits_required_and_excluded():
+ from litellm.router_strategy.tag_based_routing import _inherited_constraint_sets
+
+ inherited_required_set, inherited_excluded_set = _inherited_constraint_sets(
+ ["&region:eu", "!region:us", "plain"], ""
+ )
+ assert inherited_required_set == frozenset({"region:eu"})
+ assert inherited_excluded_set == frozenset({"region:us"})
+
+
+def test_inherited_constraint_sets_none_for_non_sequence_value():
+ from litellm.router_strategy.tag_based_routing import _inherited_constraint_sets
+
+ # A malformed/unexpected inherited_tags value (anything but a list/tuple) must
+ # be treated the same as "no origin information", never as "nothing is
+ # inherited" -- the two are not interchangeable, see _trusted_only_pool.
+ assert _inherited_constraint_sets("not-a-sequence", "") == (None, None)
+
+
+def test_trusted_only_pool_discards_everything_when_inherited_sets_are_none():
+ from litellm.router_strategy.tag_based_routing import _trusted_only_pool
+
+ deployments = ({"litellm_params": {"tags": ["region:us"]}},)
+ # No origin info at all -> reproduce the pre-provenance unconditional
+ # fall-open: the trusted-only pool ignores excluded_set/required_set entirely.
+ assert _trusted_only_pool(deployments, frozenset({"region:eu"}), frozenset({"region:apac"}), None, None) == deployments
+
+
+def test_trusted_only_pool_keeps_constraint_backed_by_inherited_tags():
+ from litellm.router_strategy.tag_based_routing import _trusted_only_pool
+
+ eu = {"litellm_params": {"tags": ["region:eu"]}}
+ us = {"litellm_params": {"tags": ["region:us"]}}
+ # required_set={"region:eu"} IS in inherited_required_set -> protected, kept.
+ result = _trusted_only_pool(
+ (eu, us), frozenset(), frozenset({"region:eu"}), frozenset(), frozenset({"region:eu"})
+ )
+ assert result == (eu,)
+
+
+def test_trusted_only_pool_discards_a_value_with_no_inherited_backing_even_if_the_caller_also_sent_it():
+ # Regression for the value-collision bypass Greptile and veria-ai both
+ # flagged: a value with zero inherited backing is discardable even when it
+ # happens to be the exact value the caller submitted -- there is nothing here
+ # to distinguish "caller-only" from "caller happened to guess a real policy
+ # value" at this function's level, which is exactly why protection must be
+ # keyed off presence in inherited_required_set, never absence from a
+ # caller-supplied set (see the router-level regression below for the full
+ # bypass this replaces).
+ from litellm.router_strategy.tag_based_routing import _trusted_only_pool
+
+ eu = {"litellm_params": {"tags": ["region:eu"]}}
+ us = {"litellm_params": {"tags": ["region:us"]}}
+ result = _trusted_only_pool((eu, us), frozenset(), frozenset({"region:eu"}), frozenset(), frozenset())
+ assert result == (eu, us)
+
+
+def _eu_region_router():
+ # eu-1 deliberately carries no "default" tag, and us-default is the only
+ # "default"-tagged deployment -- this keeps _default_tagged_pool's outcome a
+ # single, deterministic deployment id in every scenario below, regardless of
+ # which of the two candidate pools (trusted-only vs fully-unconstrained) a
+ # given code path resolves to.
+ return litellm.Router(
+ model_list=[
+ {
+ "model_name": "chat",
+ "litellm_params": {
+ "model": "gpt-4o",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["region:eu"],
+ },
+ "model_info": {"id": "eu-1", "allow_fail_open": True},
+ },
+ {
+ "model_name": "chat",
+ "litellm_params": {
+ "model": "gpt-4o-mini",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["region:us", "default"],
+ },
+ "model_info": {"id": "us-default", "allow_fail_open": True},
+ },
+ ],
+ enable_tag_filtering=True,
+ )
+
+
+async def test_allow_fail_open_preserves_inherited_constraint_when_caller_tag_causes_exhaustion():
+ # &region:eu simulates a key/team-inherited hard requirement, captured in
+ # inherited_tags (a snapshot taken before the caller's own tags are merged
+ # in); !region:eu simulates the caller's own tag. Combined they exhaust the
+ # pool (nothing can both carry and not carry region:eu), but allow_fail_open
+ # must fall back to what still satisfies the inherited requirement, not the
+ # fully-unconstrained default pool (us-default), and not raise either.
+ router = _eu_region_router()
+
+ response = await router.acompletion(
+ model="chat",
+ messages=[{"role": "user", "content": "hi"}],
+ metadata={
+ "tags": ["&region:eu", "!region:eu"],
+ "inherited_tags": ["&region:eu"],
+ "caller_tags": ["!region:eu"],
+ },
+ mock_response="hi",
+ )
+
+ assert response._hidden_params["model_id"] == "eu-1"
+
+
+async def test_allow_fail_open_stays_protected_when_caller_duplicates_the_inherited_tag():
+ # Regression for the value-collision bypass Greptile and veria-ai both
+ # flagged: a caller who resubmits the exact value of an inherited "&" tag
+ # (here alongside a conflicting "!" for the same value) must not be able to
+ # strip that value's protection just because it now also appears in
+ # caller_tags. Protection is keyed off presence in inherited_tags, not
+ # absence from caller_tags -- if it were the latter, subtracting
+ # caller_required_set={"region:eu"} from required_set would zero out the
+ # inherited requirement entirely and this would incorrectly resolve to
+ # us-default instead of eu-1.
+ router = _eu_region_router()
+
+ response = await router.acompletion(
+ model="chat",
+ messages=[{"role": "user", "content": "hi"}],
+ metadata={
+ "tags": ["&region:eu", "!region:eu"],
+ "inherited_tags": ["&region:eu"],
+ "caller_tags": ["&region:eu", "!region:eu"],
+ },
+ mock_response="hi",
+ )
+
+ assert response._hidden_params["model_id"] == "eu-1"
+
+
+async def test_allow_fail_open_raises_when_inherited_constraint_alone_is_unsatisfiable():
+ # Both region:eu and region:us are known to the group (so the unknown-tag
+ # masking guard does not apply), but no single deployment carries both, and
+ # inherited_tags confirms the entire required-AND set traces back to policy.
+ # allow_fail_open must not paper over an inherited requirement that is
+ # unsatisfiable on its own; it should raise exactly as it would with
+ # allow_fail_open unset.
+ router = _eu_region_router()
+
+ with pytest.raises(Exception) as exc_info:
+ await router.acompletion(
+ model="chat",
+ messages=[{"role": "user", "content": "hi"}],
+ metadata={
+ "tags": ["&region:eu", "&region:us"],
+ "inherited_tags": ["&region:eu", "&region:us"],
+ "caller_tags": [],
+ },
+ mock_response="hi",
+ )
+
+ from litellm.types.router import RouterErrors
+
+ assert RouterErrors.no_deployments_with_tag_routing.value in str(exc_info.value)
+
+
+async def test_allow_fail_open_unconditional_discard_when_inherited_tags_key_absent():
+ # No "inherited_tags" key at all (e.g. a direct SDK Router call that never
+ # went through the proxy's litellm_pre_call_utils.py) must reproduce the exact
+ # pre-provenance behavior: unconditional fall-open to the default pool, even
+ # though region:eu here would otherwise look like an inherited requirement.
+ router = _eu_region_router()
+
+ response = await router.acompletion(
+ model="chat",
+ messages=[{"role": "user", "content": "hi"}],
+ metadata={"tags": ["&region:eu", "!region:eu"]},
+ mock_response="hi",
+ )
+
+ assert response._hidden_params["model_id"] == "us-default"
+
+
+# --- tag_routing_prefix must be configurable through every settings-update
+# path the router already supports for its sibling enable_tag_filtering, not
+# just the config.yaml constructor argument ---
+
+
+def test_router_update_settings_applies_tag_routing_prefix():
+ # Regression: tag_routing_prefix was missing from Router.update_settings's
+ # _allowed_settings, so an operator configuring it via the DB-backed
+ # router_settings path (proxy_server.py's _add_router_settings_from_db_config,
+ # which calls update_settings directly) had the value silently ignored.
+ router = litellm.Router(model_list=[{"model_name": "x", "litellm_params": {"model": "openai/gpt-4o-mini"}}])
+ assert router.tag_routing_prefix == ""
+
+ router.update_settings(tag_routing_prefix="route:")
+
+ assert router.tag_routing_prefix == "route:"
+
+
+def test_router_get_settings_includes_tag_routing_prefix():
+ router = litellm.Router(model_list=[{"model_name": "x", "litellm_params": {"model": "openai/gpt-4o-mini"}}])
+ router.update_settings(tag_routing_prefix="route:")
+
+ assert router.get_settings()["tag_routing_prefix"] == "route:"
+
+
+def test_update_router_config_schema_includes_tag_routing_prefix():
+ # The Admin UI's POST /config/update path validates through
+ # UpdateRouterConfig before calling update_settings; a field missing here
+ # causes model_dump(exclude_none=True) to silently drop it before
+ # update_settings is ever called -- the same bug shape LIT-3152 fixed for
+ # retry_policy (see tests/test_litellm/test_router_retry_policy_update.py).
+ from litellm.types.router import UpdateRouterConfig
+
+ config = UpdateRouterConfig(tag_routing_prefix="route:")
+ assert config.model_dump(exclude_none=True)["tag_routing_prefix"] == "route:"
diff --git a/type-discipline-budget.json b/type-discipline-budget.json
index c990ae52ff2..eee067815d2 100644
--- a/type-discipline-budget.json
+++ b/type-discipline-budget.json
@@ -1,9 +1,9 @@
{
"LIT001": {
- "limit": 23057
+ "limit": 23039
},
"LIT002": {
- "limit": 27156
+ "limit": 27154
},
"LIT003": {
"limit": 269
@@ -27,7 +27,7 @@
"limit": 0
},
"LIT010": {
- "limit": 16744
+ "limit": 16742
},
"LIT011": {
"limit": 5596
diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.ts
index 35adc9e92cf..05cba547f23 100644
--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts
+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts
@@ -34222,6 +34222,8 @@ export interface components {
routing_strategy_args?: {
[key: string]: unknown;
} | null;
+ /** Tag Routing Prefix */
+ tag_routing_prefix?: string | null;
/** Timeout */
timeout?: number | null;
};
@@ -35391,6 +35393,8 @@ export interface components {
};
/** ModelInfo */
litellm__types__router__ModelInfo: {
+ /** Allow Fail Open */
+ allow_fail_open?: boolean | null;
/** Base Model */
base_model?: string | null;
/** Blocked */
@@ -35410,6 +35414,8 @@ export interface components {
* @default false
*/
db_model: boolean;
+ /** Enable Tag Filtering */
+ enable_tag_filtering?: boolean | null;
/** Id */
id: string | null;
/** Input Cost Per Character */