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]

[Bug Fix] x-litellm-tags not routing with Responses API (#14289)

Ishaan Jaff982800069c91
diff --git a/docs/my-website/docs/proxy/load_balancing.md b/docs/my-website/docs/proxy/load_balancing.md
index 67f41d231db..2d8f73a13e4 100644
--- a/docs/my-website/docs/proxy/load_balancing.md
+++ b/docs/my-website/docs/proxy/load_balancing.md
@@ -124,6 +124,8 @@ curl --location 'http://0.0.0.0:4000/chat/completions' \
}'
```
+</TabItem>
+</Tabs>
### Test - Loadbalancing
diff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.json
index a7586124509..f3c4abf5f00 100644
--- a/litellm/model_prices_and_context_window_backup.json
+++ b/litellm/model_prices_and_context_window_backup.json
@@ -21033,5 +21033,65 @@
"metadata": {
"notes": "DALL-E 2 via AI/ML API - Reliable text-to-image generation"
}
+ },
+ "doubao-embedding-large": {
+ "max_tokens": 4096,
+ "max_input_tokens": 4096,
+ "output_vector_size": 2048,
+ "input_cost_per_token": 0.0,
+ "output_cost_per_token": 0.0,
+ "litellm_provider": "volcengine",
+ "mode": "embedding",
+ "metadata": {
+ "notes": "Volcengine Doubao embedding model - large version with 2048 dimensions"
+ }
+ },
+ "doubao-embedding-large-text-250515": {
+ "max_tokens": 4096,
+ "max_input_tokens": 4096,
+ "output_vector_size": 2048,
+ "input_cost_per_token": 0.0,
+ "output_cost_per_token": 0.0,
+ "litellm_provider": "volcengine",
+ "mode": "embedding",
+ "metadata": {
+ "notes": "Volcengine Doubao embedding model - text-250515 version with 2048 dimensions"
+ }
+ },
+ "doubao-embedding-large-text-240915": {
+ "max_tokens": 4096,
+ "max_input_tokens": 4096,
+ "output_vector_size": 4096,
+ "input_cost_per_token": 0.0,
+ "output_cost_per_token": 0.0,
+ "litellm_provider": "volcengine",
+ "mode": "embedding",
+ "metadata": {
+ "notes": "Volcengine Doubao embedding model - text-240915 version with 4096 dimensions"
+ }
+ },
+ "doubao-embedding": {
+ "max_tokens": 4096,
+ "max_input_tokens": 4096,
+ "output_vector_size": 2560,
+ "input_cost_per_token": 0.0,
+ "output_cost_per_token": 0.0,
+ "litellm_provider": "volcengine",
+ "mode": "embedding",
+ "metadata": {
+ "notes": "Volcengine Doubao embedding model - standard version with 2560 dimensions"
+ }
+ },
+ "doubao-embedding-text-240715": {
+ "max_tokens": 4096,
+ "max_input_tokens": 4096,
+ "output_vector_size": 2560,
+ "input_cost_per_token": 0.0,
+ "output_cost_per_token": 0.0,
+ "litellm_provider": "volcengine",
+ "mode": "embedding",
+ "metadata": {
+ "notes": "Volcengine Doubao embedding model - text-240715 version with 2560 dimensions"
+ }
}
}
\ No newline at end of file
diff --git a/litellm/router.py b/litellm/router.py
index 1ed95ee7b29..5eea60e4b3d 100644
--- a/litellm/router.py
+++ b/litellm/router.py
@@ -4562,6 +4562,20 @@ class Router:
parent_otel_span=parent_otel_span,
ttl=RoutingArgs.ttl.value,
)
+
+ def _get_metadata_variable_name_from_kwargs(self, kwargs: dict) -> Literal["metadata", "litellm_metadata"]:
+ """
+ Helper to return what the "metadata" field should be called in the request data
+
+ - New endpoints return `litellm_metadata`
+ - Old endpoints return `metadata`
+
+ Context:
+ - LiteLLM used `metadata` as an internal field for storing metadata
+ - OpenAI then started using this field for their metadata
+ - LiteLLM is now moving to using `litellm_metadata` for our metadata
+ """
+ return "litellm_metadata" if "litellm_metadata" in kwargs else "metadata"
def log_retry(self, kwargs: dict, e: Exception) -> dict:
"""
@@ -6788,6 +6802,7 @@ class Router:
model=model,
request_kwargs=request_kwargs,
healthy_deployments=healthy_deployments,
+ metadata_variable_name=self._get_metadata_variable_name_from_kwargs(request_kwargs),
)
if len(healthy_deployments) == 0:
diff --git a/litellm/router_strategy/tag_based_routing.py b/litellm/router_strategy/tag_based_routing.py
index 34261d83dcf..8094b5d86ac 100644
--- a/litellm/router_strategy/tag_based_routing.py
+++ b/litellm/router_strategy/tag_based_routing.py
@@ -6,7 +6,7 @@ Use this to route requests between Teams
- If no default_deployments are set, return all deployments
"""
-from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union
+from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Union
from litellm._logging import verbose_logger
from litellm.types.router import RouterErrors
@@ -41,6 +41,7 @@ async def get_deployments_for_tag(
model: str, # used to raise the correct error
healthy_deployments: Union[List[Any], Dict[Any, Any]],
request_kwargs: Optional[Dict[Any, Any]] = None,
+ metadata_variable_name: Literal["metadata", "litellm_metadata"] = "metadata",
):
"""
Returns a list of deployments that match the requested model and tags in the request.
@@ -63,9 +64,9 @@ async def get_deployments_for_tag(
)
return healthy_deployments
- verbose_logger.debug("request metadata: %s", request_kwargs.get("metadata"))
- if "metadata" in request_kwargs:
- metadata = request_kwargs["metadata"]
+ verbose_logger.debug("request metadata: %s", request_kwargs.get(metadata_variable_name))
+ if metadata_variable_name in request_kwargs:
+ metadata = request_kwargs[metadata_variable_name]
request_tags = metadata.get("tags")
new_healthy_deployments = []
@@ -120,7 +121,8 @@ async def get_deployments_for_tag(
def _get_tags_from_request_kwargs(
- request_kwargs: Optional[Dict[Any, Any]] = None
+ request_kwargs: Optional[Dict[Any, Any]] = None,
+ metadata_variable_name: Literal["metadata", "litellm_metadata"] = "metadata",
) -> List[str]:
"""
Helper to get tags from request kwargs
@@ -133,11 +135,11 @@ def _get_tags_from_request_kwargs(
"""
if request_kwargs is None:
return []
- if "metadata" in request_kwargs:
- metadata = request_kwargs["metadata"]
+ if metadata_variable_name in request_kwargs:
+ metadata = request_kwargs[metadata_variable_name]
return metadata.get("tags", [])
elif "litellm_params" in request_kwargs:
litellm_params = request_kwargs["litellm_params"]
- _metadata = litellm_params.get("metadata", {})
+ _metadata = litellm_params.get(metadata_variable_name, {})
return _metadata.get("tags", [])
return []
diff --git a/tests/router_unit_tests/test_router_helper_utils.py b/tests/router_unit_tests/test_router_helper_utils.py
index 48bb836dfd6..094df944bcc 100644
--- a/tests/router_unit_tests/test_router_helper_utils.py
+++ b/tests/router_unit_tests/test_router_helper_utils.py
@@ -1690,3 +1690,38 @@ def test_handle_clientside_credential_with_responses_function(model_list):
print(
"✓ Success with _ageneric_api_call_with_fallbacks function name and litellm_metadata"
)
+
+
+def test_get_metadata_variable_name_from_kwargs(model_list):
+ """
+ Test _get_metadata_variable_name_from_kwargs method returns correct metadata variable name based on kwargs content.
+ """
+ router = Router(model_list=model_list)
+
+ # Test case 1: kwargs contains litellm_metadata - should return "litellm_metadata"
+ kwargs_with_litellm_metadata = {
+ "litellm_metadata": {"user": "test"},
+ "metadata": {"other": "data"}
+ }
+ result = router._get_metadata_variable_name_from_kwargs(kwargs_with_litellm_metadata)
+ assert result == "litellm_metadata"
+
+ # Test case 2: kwargs only contains metadata - should return "metadata"
+ kwargs_with_metadata_only = {
+ "metadata": {"user": "test"}
+ }
+ result = router._get_metadata_variable_name_from_kwargs(kwargs_with_metadata_only)
+ assert result == "metadata"
+
+ # Test case 3: kwargs contains neither - should return "metadata" (default)
+ kwargs_empty = {}
+ result = router._get_metadata_variable_name_from_kwargs(kwargs_empty)
+ assert result == "metadata"
+
+ # Test case 4: kwargs contains other keys but no metadata keys - should return "metadata"
+ kwargs_other = {
+ "model": "gpt-4",
+ "messages": [{"role": "user", "content": "hello"}]
+ }
+ result = router._get_metadata_variable_name_from_kwargs(kwargs_other)
+ assert result == "metadata"
diff --git a/tests/test_litellm/llms/openai/responses/test_openai_responses_transformation.py b/tests/test_litellm/llms/openai/responses/test_openai_responses_transformation.py
index 21232161d0c..ddcf11495f2 100644
--- a/tests/test_litellm/llms/openai/responses/test_openai_responses_transformation.py
+++ b/tests/test_litellm/llms/openai/responses/test_openai_responses_transformation.py
@@ -669,247 +669,3 @@ def test_get_supported_openai_params():
assert "background" in params
assert "stream" in params
-
-class TestOpenAIFieldExclusionRegistry:
- """Test suite for the OpenAI Field Exclusion Registry system"""
-
- def setup_method(self):
- """Setup test fixtures"""
- from litellm.llms.openai.responses.transformation import (
- OpenAIFieldExclusionRegistry,
- OpenAIResponsesAPIConfig
- )
- self.registry = OpenAIFieldExclusionRegistry
- self.config = OpenAIResponsesAPIConfig()
-
- def test_registry_initialization(self):
- """Test that the registry is properly initialized with ResponseReasoningItem"""
- # Test that we can get excluded fields (should not be empty if ResponseReasoningItem is registered)
- all_excluded_fields = self.registry.get_all_excluded_fields()
-
- # The registry should have at least some fields if ResponseReasoningItem was successfully registered
- # If OpenAI SDK is not available, this might be empty, which is also valid
- assert isinstance(all_excluded_fields, set), "get_all_excluded_fields should return a set"
-
- # If we have the OpenAI SDK available, we should have the expected fields
- try:
- from openai.types.responses import ResponseReasoningItem
- reasoning_fields = self.registry.get_excluded_fields_for_model(ResponseReasoningItem)
- expected_fields = {'status', 'content', 'encrypted_content'}
- assert expected_fields.issubset(reasoning_fields), f"Expected fields {expected_fields} to be subset of {reasoning_fields}"
- except ImportError:
- # If OpenAI SDK is not available, that's fine - the registry should handle this gracefully
- pytest.skip("OpenAI SDK not available, skipping ResponseReasoningItem specific tests")
-
- def test_register_model_functionality(self):
- """Test that we can register new models to the registry"""
- from pydantic import BaseModel
- from typing import Optional
-
- # Create a test model with default None fields
- class TestResponseModel(BaseModel):
- id: str
- type: str = "test"
- status: Optional[str] = None
- content: Optional[str] = None
- required_field: str
-
- # Register the test model
- self.registry.register_model(TestResponseModel)
-
- # Verify it was registered and fields are detected
- excluded_fields = self.registry.get_excluded_fields_for_model(TestResponseModel)
- expected_excluded = {'status', 'content'} # Fields with default None
-
- assert expected_excluded.issubset(excluded_fields), f"Expected {expected_excluded} to be in {excluded_fields}"
- assert 'id' not in excluded_fields, "Required field 'id' should not be excluded"
- assert 'required_field' not in excluded_fields, "Required field 'required_field' should not be excluded"
-
- def test_get_all_excluded_fields(self):
- """Test that get_all_excluded_fields aggregates fields from all registered models"""
- all_fields_before = self.registry.get_all_excluded_fields()
-
- # Create and register a test model
- from pydantic import BaseModel
- from typing import Optional
-
- class AnotherTestModel(BaseModel):
- id: str
- unique_field: Optional[str] = None
-
- self.registry.register_model(AnotherTestModel)
-
- all_fields_after = self.registry.get_all_excluded_fields()
-
- # The new fields should be included
- assert 'unique_field' in all_fields_after, "New model's excluded field should be included"
- assert len(all_fields_after) >= len(all_fields_before), "Should have at least as many fields as before"
-
- def test_convenience_registration_method(self):
- """Test the convenience method for registering models"""
- from pydantic import BaseModel
- from typing import Optional
-
- class ConvenienceTestModel(BaseModel):
- id: str
- convenience_field: Optional[str] = None
-
- # Use the convenience method
- self.config.register_model_for_field_exclusion(ConvenienceTestModel)
-
- # Verify it was registered
- excluded_fields = self.registry.get_excluded_fields_for_model(ConvenienceTestModel)
- assert 'convenience_field' in excluded_fields, "Field should be excluded after registration"
-
- def test_field_filtering_with_registry(self):
- """Test that the field filtering works correctly with the registry"""
-
- # Test data that matches the structure of ResponseReasoningItem
- test_input = [
- {
- "role": "user",
- "content": "test message"
- },
- {
- "id": "reasoning-123",
- "type": "reasoning",
- "status": None, # Should be filtered out
- "content": None, # Should be filtered out
- "encrypted_content": None, # Should be filtered out
- "summary": [{"text": "This reasoning shows...", "type": "summary_text"}],
- "role": "assistant"
- },
- {
- "id": "message-456",
- "type": "message",
- "status": "completed", # Should be preserved (not None)
- "content": "Hello! How can I help?", # Should be preserved (not None)
- "role": "assistant"
- }
- ]
-
- # Process the input through the validation
- result = self.config._validate_input_param(test_input)
-
- # Verify the structure
- assert len(result) == 3, "Should have 3 items"
-
- # Check the reasoning item (index 1)
- reasoning_item = result[1]
- assert reasoning_item["type"] == "reasoning"
- assert reasoning_item["id"] == "reasoning-123"
- assert "summary" in reasoning_item, "summary field should be preserved"
- assert "role" in reasoning_item, "role field should be preserved"
-
- # These fields should be filtered out if they are in the registry
- all_excluded_fields = self.registry.get_all_excluded_fields()
- if 'status' in all_excluded_fields:
- assert "status" not in reasoning_item, "status field should be filtered out"
- if 'content' in all_excluded_fields:
- assert "content" not in reasoning_item, "content field should be filtered out"
- if 'encrypted_content' in all_excluded_fields:
- assert "encrypted_content" not in reasoning_item, "encrypted_content field should be filtered out"
-
- # Check the message item (index 2) - non-None values should be preserved
- message_item = result[2]
- assert message_item["type"] == "message"
- assert message_item["status"] == "completed", "Non-None status should be preserved"
- assert message_item["content"] == "Hello! How can I help?", "Non-None content should be preserved"
-
- def test_field_filtering_with_empty_registry(self):
- """Test that filtering works gracefully when no models are registered"""
- # Create a fresh registry for this test
- from litellm.llms.openai.responses.transformation import OpenAIFieldExclusionRegistry
-
- # Save the current state
- original_models = OpenAIFieldExclusionRegistry._MODELS_REQUIRING_EXCLUSION.copy()
-
- try:
- # Clear the registry
- OpenAIFieldExclusionRegistry._MODELS_REQUIRING_EXCLUSION.clear()
-
- # Test data
- test_input = [{
- "id": "test-123",
- "status": None,
- "content": None,
- "other_field": "should be preserved"
- }]
-
- # Process the input
- result = self.config._validate_input_param(test_input)
-
- # With empty registry, nothing should be filtered (all fields preserved)
- assert len(result) == 1
- item = result[0]
- assert "status" in item, "With empty registry, status should be preserved"
- assert "content" in item, "With empty registry, content should be preserved"
- assert item["other_field"] == "should be preserved"
-
- finally:
- # Restore the original state
- OpenAIFieldExclusionRegistry._MODELS_REQUIRING_EXCLUSION = original_models
-
- def test_pydantic_v1_v2_compatibility(self):
- """Test that the registry works with both Pydantic v1 and v2"""
- from pydantic import BaseModel
- from typing import Optional
-
- class CompatibilityTestModel(BaseModel):
- id: str
- optional_field: Optional[str] = None
- required_field: str = "default"
-
- # Register the model
- self.registry.register_model(CompatibilityTestModel)
-
- # Get excluded fields
- excluded_fields = self.registry.get_excluded_fields_for_model(CompatibilityTestModel)
-
- # Should work regardless of Pydantic version
- assert isinstance(excluded_fields, set), "Should return a set"
- assert 'optional_field' in excluded_fields, "Field with default None should be excluded"
-
- # Test that the model fields are accessible (works in both v1 and v2)
- model_fields = getattr(CompatibilityTestModel, "model_fields", None)
- if model_fields is None:
- model_fields = getattr(CompatibilityTestModel, "__fields__", {})
- assert len(model_fields) > 0, "Should be able to access model fields"
-
- def test_non_registered_model_returns_empty_set(self):
- """Test that non-registered models return empty excluded fields"""
- from pydantic import BaseModel
-
- class UnregisteredModel(BaseModel):
- id: str
- some_field: str = None
-
- # Don't register this model
- excluded_fields = self.registry.get_excluded_fields_for_model(UnregisteredModel)
-
- assert excluded_fields == set(), "Non-registered model should return empty set"
-
- @pytest.mark.parametrize("field_value", [None, "", 0, False, []])
- def test_only_none_values_are_filtered(self, field_value):
- """Test that only None values are filtered, not other falsy values"""
- test_input = [{
- "id": "test-123",
- "status": field_value,
- "content": "actual content",
- "other_field": "preserved"
- }]
-
- result = self.config._validate_input_param(test_input)
- item = result[0]
-
- if field_value is None:
- # Only None should be filtered (if status is in the registry)
- all_excluded_fields = self.registry.get_all_excluded_fields()
- if 'status' in all_excluded_fields:
- assert "status" not in item, f"None value should be filtered out"
- else:
- assert item["status"] is None, f"If not in registry, None should be preserved"
- else:
- # Other falsy values should be preserved
- assert "status" in item, f"Non-None value {field_value} should be preserved"
- assert item["status"] == field_value, f"Value should be exactly {field_value}"
diff --git a/tests/local_testing/test_router_tag_routing.py b/tests/test_litellm/router_strategy/test_router_tag_routing.py
similarity index 81%
rename from tests/local_testing/test_router_tag_routing.py
rename to tests/test_litellm/router_strategy/test_router_tag_routing.py
index 87cf2261a67..e78a16c6212 100644
--- a/tests/local_testing/test_router_tag_routing.py
+++ b/tests/test_litellm/router_strategy/test_router_tag_routing.py
@@ -63,6 +63,7 @@ async def test_router_free_paid_tier():
model="gpt-4",
messages=[{"role": "user", "content": "Tell me a joke."}],
metadata={"tags": ["free"]},
+ mock_response="Tell me a joke.",
)
print("Response: ", response)
@@ -78,6 +79,7 @@ async def test_router_free_paid_tier():
model="gpt-4",
messages=[{"role": "user", "content": "Tell me a joke."}],
metadata={"tags": ["paid"]},
+ mock_response="Tell me a joke.",
)
print("Response: ", response)
@@ -136,6 +138,7 @@ async def test_router_free_paid_tier_embeddings():
model="gpt-4",
input="Tell me a joke.",
metadata={"tags": ["free"]},
+ mock_response=[1, 2, 3],
)
print("Response: ", response)
@@ -151,6 +154,7 @@ async def test_router_free_paid_tier_embeddings():
model="gpt-4",
input="Tell me a joke.",
metadata={"tags": ["paid"]},
+ mock_response=[1, 2, 3],
)
print("Response: ", response)
@@ -205,6 +209,7 @@ async def test_default_tagged_deployments():
response = await router.acompletion(
model="gpt-4",
messages=[{"role": "user", "content": "Tell me a joke."}],
+ mock_response="Tell me a joke.",
)
print("Response: ", response)
@@ -220,6 +225,7 @@ async def test_default_tagged_deployments():
model="gpt-4",
messages=[{"role": "user", "content": "Tell me a joke."}],
metadata={"tags": ["default"]},
+ mock_response="Tell me a joke.",
)
print("Response: ", response)
@@ -235,6 +241,7 @@ async def test_default_tagged_deployments():
model="gpt-4",
messages=[{"role": "user", "content": "Tell me a joke."}],
metadata={"tags": ["invalid-tag"]},
+ mock_response="Tell me a joke.",
)
print("Response: ", response)
@@ -292,6 +299,7 @@ async def test_error_from_tag_routing():
model="gpt-4",
messages=[{"role": "user", "content": "Tell me a joke."}],
metadata={"tags": ["paid"]},
+ mock_response="Tell me a joke.",
)
pytest.fail("this should have failed - expected it to fail")
@@ -315,3 +323,66 @@ def test_tag_routing_with_list_of_tags():
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"])
+
+
+async def test_router_free_paid_tier_with_responses_api():
+ """
+ Pass list of orgs in 1 model definition,
+ expect a unique deployment for each to be created
+ """
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["free"],
+ },
+ "model_info": {"id": "very-cheap-model"},
+ },
+ {
+ "model_name": "gpt-4",
+ "litellm_params": {
+ "model": "gpt-4o-mini",
+ "api_base": "https://exampleopenaiendpoint-production.up.railway.app/",
+ "tags": ["paid"],
+ },
+ "model_info": {"id": "very-expensive-model"},
+ },
+ ],
+ enable_tag_filtering=True,
+ )
+
+ for _ in range(5):
+ # this should pick model with id == very-cheap-model
+ response = await router.aresponses(
+ model="gpt-4",
+ input="Tell me a joke.",
+ litellm_metadata={"tags": ["free"]},
+ mock_response="Tell me a joke.",
+ )
+
+ print("Response: ", response)
+
+ response_extra_info = response._hidden_params
+ print("response_extra_info: ", response_extra_info)
+
+ assert response_extra_info["model_id"] == "very-cheap-model"
+
+ for _ in range(5):
+ # this should pick model with id == very-cheap-model
+ response = await router.aresponses(
+ model="gpt-4",
+ input="Tell me a joke.",
+ litellm_metadata={"tags": ["paid"]},
+ mock_response="Tell me a joke.",
+ )
+
+ print("Response: ", response)
+
+ response_extra_info = response._hidden_params
+ print("response_extra_info: ", response_extra_info)
+
+ assert response_extra_info["model_id"] == "very-expensive-model"
\ No newline at end of file