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]

refactor: extract admin metadata helper, hoist loop-invariant tag resolution

user3cd5796fc794
diff --git a/litellm/integrations/custom_guardrail.py b/litellm/integrations/custom_guardrail.py
index 1e6a46044e0..4c294f6272e 100644
--- a/litellm/integrations/custom_guardrail.py
+++ b/litellm/integrations/custom_guardrail.py
@@ -255,6 +255,12 @@ class CustomGuardrail(CustomLogger):
f"Event hook {event_hook} is not in the supported event hooks {supported_event_hooks}"
)
+ @staticmethod
+ def _get_admin_metadata(data: dict) -> dict:
+ """Return the admin-configured key/team metadata from the request data."""
+ metadata = data.get("litellm_metadata") or data.get("metadata", {})
+ return metadata.get("user_api_key_metadata") or {}
+
def get_disable_global_guardrail(self, data: dict) -> Optional[bool]:
"""
Returns True if the global guardrail should be disabled.
@@ -262,9 +268,7 @@ class CustomGuardrail(CustomLogger):
Reads from admin-configured key/team metadata only, not from
the request body, to prevent callers from disabling guardrails.
"""
- metadata = data.get("litellm_metadata") or data.get("metadata", {})
- admin_metadata = metadata.get("user_api_key_metadata") or {}
- return admin_metadata.get("disable_global_guardrails", False)
+ return self._get_admin_metadata(data).get("disable_global_guardrails", False)
def get_opted_out_global_guardrails_from_metadata(self, data: dict) -> List[str]:
"""
@@ -272,9 +276,7 @@ class CustomGuardrail(CustomLogger):
Reads from admin-configured key/team metadata only.
"""
- metadata = data.get("litellm_metadata") or data.get("metadata", {})
- admin_metadata = metadata.get("user_api_key_metadata") or {}
- value = admin_metadata.get("opted_out_global_guardrails")
+ value = self._get_admin_metadata(data).get("opted_out_global_guardrails")
return value if isinstance(value, list) else []
def _is_valid_response_type(self, result: Any) -> bool:
diff --git a/litellm/router_strategy/budget_limiter.py b/litellm/router_strategy/budget_limiter.py
index 261e659644a..be27b852478 100644
--- a/litellm/router_strategy/budget_limiter.py
+++ b/litellm/router_strategy/budget_limiter.py
@@ -310,6 +310,16 @@ class RouterBudgetLimiting(CustomLogger):
deployment_configs: Dict[str, GenericBudgetInfo] = {}
deployment_providers: List[Optional[str]] = []
+ # Resolve tags once before the loop (loop-invariant)
+ _request_tags: List[str] = []
+ if self.tag_budget_config:
+ _request_tags = _get_tags_from_request_kwargs(
+ request_kwargs=request_kwargs,
+ metadata_variable_name=get_metadata_variable_name_from_kwargs(
+ request_kwargs or {}
+ ),
+ )
+
for deployment in healthy_deployments:
# Check provider budgets
if self.provider_budget_config:
@@ -336,20 +346,14 @@ class RouterBudgetLimiting(CustomLogger):
cache_keys.append(
f"deployment_spend:{model_id}:{budget_config.budget_duration}"
)
- # Check tag budgets
- if self.tag_budget_config:
- request_tags = _get_tags_from_request_kwargs(
- request_kwargs=request_kwargs,
- metadata_variable_name=get_metadata_variable_name_from_kwargs(
- request_kwargs or {}
- ),
+
+ # Check tag budgets (outside loop — tags are per-request, not per-deployment)
+ for _tag in _request_tags:
+ _tag_budget_config = self._get_budget_config_for_tag(_tag)
+ if _tag_budget_config:
+ cache_keys.append(
+ f"tag_spend:{_tag}:{_tag_budget_config.budget_duration}"
)
- for _tag in request_tags:
- _tag_budget_config = self._get_budget_config_for_tag(_tag)
- if _tag_budget_config:
- cache_keys.append(
- f"tag_spend:{_tag}:{_tag_budget_config.budget_duration}"
- )
return (
cache_keys,
provider_configs,
diff --git a/litellm/router_strategy/tag_based_routing.py b/litellm/router_strategy/tag_based_routing.py
index b0b154fc778..0163f3bbd4f 100644
--- a/litellm/router_strategy/tag_based_routing.py
+++ b/litellm/router_strategy/tag_based_routing.py
@@ -102,10 +102,10 @@ def _match_deployment(
return {"matched_via": "tags", "matched_value": matched_value}
# 2. Regex match against request headers.
- # When match_any=False and the deployment has both plain tags and tag_regex,
- # the strict tag check has already failed (step 1 returned None). Allow
- # the regex to fire only when the deployment has NO plain tags, so we never
- # use regex as a backdoor around the operator's strict-tag policy.
+ # When match_any=False and the deployment has plain tags, the strict tag
+ # check either didn't run (no request tags) or failed (step 1 returned
+ # None). Block the regex path so it cannot circumvent the operator's
+ # strict-tag policy.
strict_tag_check_failed = not match_any and bool(deployment_tags)
if deployment_tag_regex and header_strings and not strict_tag_check_failed:
regex_match = _is_valid_deployment_tag_regex(