The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
feat(tag-routing): support toggling tag matching between ANY and ALL (#18776)
Chongshun60edf13a218b
diff --git a/docs/my-website/docs/proxy/config_settings.md b/docs/my-website/docs/proxy/config_settings.mdindex dfc0efd37ad..68e1f629e8b 100644--- a/docs/my-website/docs/proxy/config_settings.md+++ b/docs/my-website/docs/proxy/config_settings.md@@ -146,6 +146,7 @@ router_settings:cooldown_time: 30 # (in seconds) how long to cooldown model if fails/min > allowed_failsdisable_cooldowns: True # bool - Disable cooldowns for all modelsenable_tag_filtering: True # bool - Use tag based routing for requests+ tag_filtering_match_any: True # bool - Tag matching behavior (only when enable_tag_filtering=true). `true`: match if deployment has ANY requested tag; `false`: match only if deployment has ALL requested tagsretry_policy: { # Dict[str, int]: retry policy for different types of exceptions"AuthenticationErrorRetries": 3,"TimeoutErrorRetries": 3,@@ -293,6 +294,7 @@ router_settings:cooldown_time: 30 # (in seconds) how long to cooldown model if fails/min > allowed_failsdisable_cooldowns: True # bool - Disable cooldowns for all modelsenable_tag_filtering: True # bool - Use tag based routing for requests+ tag_filtering_match_any: True # bool - Tag matching behavior (only when enable_tag_filtering=true). `true`: match if deployment has ANY requested tag; `false`: match only if deployment has ALL requested tagsretry_policy: { # Dict[str, int]: retry policy for different types of exceptions"AuthenticationErrorRetries": 3,"TimeoutErrorRetries": 3,@@ -322,6 +324,7 @@ router_settings:| content_policy_fallbacks | array of objects | Specifies fallback models for content policy violations. [More information here](reliability) || fallbacks | array of objects | Specifies fallback models for all types of errors. [More information here](reliability) || enable_tag_filtering | boolean | If true, uses tag based routing for requests [Tag Based Routing](tag_routing) |+| tag_filtering_match_any | boolean | Tag matching behavior (only when enable_tag_filtering=true). `true`: match if deployment has ANY requested tag; `false`: match only if deployment has ALL requested tags || cooldown_time | integer | The duration (in seconds) to cooldown a model if it exceeds the allowed failures. || disable_cooldowns | boolean | If true, disables cooldowns for all models. [More information here](reliability) || retry_policy | object | Specifies the number of retries for different types of exceptions. [More information here](reliability) |diff --git a/litellm/router.py b/litellm/router.pyindex 98ccf41c96d..84b38b3985b 100644--- a/litellm/router.py+++ b/litellm/router.py@@ -255,6 +255,7 @@ class Router:] = {},enable_pre_call_checks: bool = False,enable_tag_filtering: bool = False,+ tag_filtering_match_any: bool = True,retry_after: int = 0, # min time to wait before retrying a failed requestretry_policy: Optional[Union[RetryPolicy, dict]@@ -363,6 +364,7 @@ class Router:self.debug_level = debug_levelself.enable_pre_call_checks = enable_pre_call_checksself.enable_tag_filtering = enable_tag_filtering+ self.tag_filtering_match_any = tag_filtering_match_anyfrom litellm._service_logger import ServiceLoggingself.service_logger_obj: ServiceLogging = ServiceLogging()diff --git a/litellm/router_strategy/tag_based_routing.py b/litellm/router_strategy/tag_based_routing.pyindex b25c20eb281..e960e00a68f 100644--- a/litellm/router_strategy/tag_based_routing.py+++ b/litellm/router_strategy/tag_based_routing.py@@ -20,17 +20,28 @@ else:def is_valid_deployment_tag(- deployment_tags: List[str], request_tags: List[str]+ deployment_tags: List[str], request_tags: List[str], match_any: bool = True) -> bool:"""- Check if a tag is valid+ Check if a tag is valid, the matching can be either any or all based on `match_any` flag"""+ if not request_tags:+ return False- if any(tag in deployment_tags for tag in request_tags):+ dep_set = set(deployment_tags)+ req_set = set(request_tags)++ if match_any:+ is_valid_deployment = bool(dep_set & req_set)+ else:+ is_valid_deployment = req_set.issubset(dep_set)++ if is_valid_deployment:verbose_logger.debug(- "adding deployment with tags: %s, request tags: %s",+ "adding deployment with tags: %s, request tags: %s for match_any=%s",deployment_tags,request_tags,+ match_any,)return Truereturn False@@ -68,6 +79,7 @@ async def get_deployments_for_tag(if metadata_variable_name in request_kwargs:metadata = request_kwargs[metadata_variable_name]request_tags = metadata.get("tags")+ match_any = llm_router_instance.tag_filtering_match_anynew_healthy_deployments = []default_deployments = []@@ -76,7 +88,6 @@ async def get_deployments_for_tag("get_deployments_for_tag routing: router_keys: %s", request_tags)# example this can be router_keys=["free", "custom"]- # get all deployments that have a superset of these router keysfor deployment in healthy_deployments:deployment_litellm_params = deployment.get("litellm_params")deployment_tags = deployment_litellm_params.get("tags")@@ -90,7 +101,7 @@ async def get_deployments_for_tag(if deployment_tags is None:continue- if is_valid_deployment_tag(deployment_tags, request_tags):+ if is_valid_deployment_tag(deployment_tags, request_tags, match_any):new_healthy_deployments.append(deployment)if "default" in deployment_tags:diff --git a/litellm/types/management_endpoints/router_settings_endpoints.py b/litellm/types/management_endpoints/router_settings_endpoints.pyindex 9e3002ecf45..8b05c1483e8 100644--- a/litellm/types/management_endpoints/router_settings_endpoints.py+++ b/litellm/types/management_endpoints/router_settings_endpoints.py@@ -184,6 +184,14 @@ ROUTER_SETTINGS_FIELDS: List[RouterSettingsField] = [field_default=False,ui_field_name="Enable Tag Filtering",link="https://docs.litellm.ai/docs/proxy/tag_routing",+ ),+ RouterSettingsField(+ field_name="tag_filtering_match_any",+ field_type="Boolean",+ field_value=None,+ field_description="Match any tag instead of all tags for tag-based routing",+ field_default=True,+ ui_field_name="Tag Filtering Match Any",),RouterSettingsField(field_name="disable_cooldowns",diff --git a/tests/test_litellm/router_strategy/test_router_tag_routing.py b/tests/test_litellm/router_strategy/test_router_tag_routing.pyindex a3e722eeb85..1fdd3dad4da 100644--- a/tests/test_litellm/router_strategy/test_router_tag_routing.py+++ b/tests/test_litellm/router_strategy/test_router_tag_routing.py@@ -313,17 +313,31 @@ async def test_error_from_tag_routing():def test_tag_routing_with_list_of_tags():"""- Test that the router can handle a list of tags+ Test that the router can handle a list of tags with match_any behavior"""from litellm.router_strategy.tag_based_routing import is_valid_deployment_tagassert is_valid_deployment_tag(["teamA", "teamB"], ["teamA"])assert is_valid_deployment_tag(["teamA", "teamB"], ["teamA", "teamB"])assert is_valid_deployment_tag(["teamA", "teamB"], ["teamA", "teamC"])+ assert is_valid_deployment_tag(["teamA"], ["teamA", "teamB"])assert not is_valid_deployment_tag(["teamA", "teamB"], ["teamC"])assert not is_valid_deployment_tag(["teamA", "teamB"], [])assert not is_valid_deployment_tag(["default"], ["teamA"])+def test_tag_routing_with_list_of_tags_match_all():+ """+ Test that the router can handle a list of tags with match_all behavior+ """+ from litellm.router_strategy.tag_based_routing import is_valid_deployment_tag++ assert is_valid_deployment_tag(["teamA", "teamB"], ["teamA"], match_any=False)+ assert is_valid_deployment_tag(["teamA", "teamB"], ["teamA", "teamB"], match_any=False)+ assert not is_valid_deployment_tag(["teamA", "teamB", "teamC"], ["teamA", "teamD"], match_any=False)+ assert not is_valid_deployment_tag(["teamA"], ["teamA", "teamB"], match_any=False)+ assert not is_valid_deployment_tag(["teamA", "teamB"], ["teamA", "teamC"], match_any=False)+ assert not is_valid_deployment_tag(["teamA", "teamB"], [], match_any=False)+ assert not is_valid_deployment_tag(["default"], ["teamA"], match_any=False)@pytest.mark.asyncio()async def test_router_free_paid_tier_with_responses_api():