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]

Litellm dev 06 25 2025 p2 (#12049)

Krish Dholakia1a7fd1d1c717
diff --git a/litellm/proxy/batches_endpoints/endpoints.py b/litellm/proxy/batches_endpoints/endpoints.py
index 8bf5427d6d5..56b0677590f 100644
--- a/litellm/proxy/batches_endpoints/endpoints.py
+++ b/litellm/proxy/batches_endpoints/endpoints.py
@@ -368,20 +368,37 @@ async def list_batches(
```
"""
- from litellm.proxy.proxy_server import proxy_logging_obj, version
+ from litellm.proxy.proxy_server import llm_router, proxy_logging_obj, version
verbose_proxy_logger.debug("GET /v1/batches after={} limit={}".format(after, limit))
try:
- custom_llm_provider = (
- provider
- or await get_custom_llm_provider_from_request_body(request=request)
- or "openai"
- )
- response = await litellm.alist_batches(
- custom_llm_provider=custom_llm_provider, # type: ignore
- after=after,
- limit=limit,
- )
+ if llm_router is None:
+ raise HTTPException(
+ status_code=500,
+ detail={"error": CommonProxyErrors.no_llm_router.value},
+ )
+
+ ## check for target model names
+ data = await _read_request_body(request=request)
+ target_model_names = data.get("target_model_names", None)
+ if target_model_names:
+ model = target_model_names.split(",")[0]
+ response = await llm_router.alist_batches(
+ model=model,
+ after=after,
+ limit=limit,
+ )
+ else:
+ custom_llm_provider = (
+ provider
+ or await get_custom_llm_provider_from_request_body(request=request)
+ or "openai"
+ )
+ response = await litellm.alist_batches(
+ custom_llm_provider=custom_llm_provider, # type: ignore
+ after=after,
+ limit=limit,
+ )
### RESPONSE HEADERS ###
hidden_params = getattr(response, "_hidden_params", {}) or {}
diff --git a/litellm/router.py b/litellm/router.py
index d301fe8d5ee..e3baa3b46b1 100644
--- a/litellm/router.py
+++ b/litellm/router.py
@@ -6215,6 +6215,8 @@ class Router:
*OR*
- Dict, if specific model chosen
"""
+ from litellm.router_utils.common_utils import filter_team_based_models
+
model, healthy_deployments = self._common_checks_available_deployment(
model=model,
messages=messages,
@@ -6222,6 +6224,13 @@ class Router:
specific_deployment=specific_deployment,
) # type: ignore
+ # IF TEAM ID SPECIFIED ON MODEL, AND REQUEST CONTAINS USER_API_KEY_TEAM_ID, FILTER OUT MODELS THAT ARE NOT IN THE TEAM
+ ## THIS PREVENTS WRITING FILES OF OTHER TEAMS TO MODELS THAT ARE TEAM-ONLY MODELS
+ healthy_deployments = filter_team_based_models(
+ healthy_deployments=healthy_deployments,
+ request_kwargs=request_kwargs,
+ )
+
if isinstance(healthy_deployments, dict):
return healthy_deployments
diff --git a/litellm/router_utils/common_utils.py b/litellm/router_utils/common_utils.py
index a7163545d3d..4f4cb8687ef 100644
--- a/litellm/router_utils/common_utils.py
+++ b/litellm/router_utils/common_utils.py
@@ -1,6 +1,10 @@
import hashlib
import json
+<<<<<<< litellm_dev_06_25_2025_p2
+from typing import TYPE_CHECKING, Dict, List, Optional, Union
+=======
from typing import TYPE_CHECKING, Dict, List, Union
+>>>>>>> main
if TYPE_CHECKING:
from litellm.types.llms.openai import OpenAIFileObject
@@ -38,3 +42,41 @@ def add_model_file_id_mappings(
for model_id, file_id in healthy_deployments.items():
model_file_id_mapping[model_id] = file_id
return model_file_id_mapping
+<<<<<<< litellm_dev_06_25_2025_p2
+
+
+def filter_team_based_models(
+ healthy_deployments: Union[List[Dict], Dict],
+ request_kwargs: Optional[Dict] = None,
+) -> Union[List[Dict], Dict]:
+ """
+ If a model has a team_id
+
+ Only use if request is from that team
+ """
+ if request_kwargs is None:
+ return healthy_deployments
+
+ metadata = request_kwargs.get("metadata") or {}
+ litellm_metadata = request_kwargs.get("litellm_metadata") or {}
+ request_team_id = metadata.get("user_api_key_team_id") or litellm_metadata.get(
+ "user_api_key_team_id"
+ )
+ ids_to_remove = []
+ if isinstance(healthy_deployments, dict):
+ return healthy_deployments
+ for deployment in healthy_deployments:
+ _model_info = deployment.get("model_info") or {}
+ model_team_id = _model_info.get("team_id")
+ if model_team_id is None:
+ continue
+ if model_team_id != request_team_id:
+ ids_to_remove.append(deployment.get("model_info", {}).get("id"))
+
+ return [
+ deployment
+ for deployment in healthy_deployments
+ if deployment.get("model_info", {}).get("id") not in ids_to_remove
+ ]
+=======
+>>>>>>> main
diff --git a/tests/test_litellm/router_utils/test_router_utils_common_utils.py b/tests/test_litellm/router_utils/test_router_utils_common_utils.py
new file mode 100644
index 00000000000..79b975a8786
--- /dev/null
+++ b/tests/test_litellm/router_utils/test_router_utils_common_utils.py
@@ -0,0 +1,189 @@
+from typing import Dict, List, Optional, Union
+from unittest.mock import Mock
+
+import pytest
+
+from litellm.router_utils.common_utils import filter_team_based_models
+
+
+class TestFilterTeamBasedModels:
+ """Test cases for filter_team_based_models function"""
+
+ @pytest.fixture
+ def sample_deployments_with_teams(self) -> List[Dict]:
+ """Sample deployments where some have team_id and some don't"""
+ return [
+ {"model_info": {"id": "deployment-1", "team_id": "team-a"}},
+ {"model_info": {"id": "deployment-2", "team_id": "team-b"}},
+ {
+ "model_info": {
+ "id": "deployment-3"
+ # No team_id - should always be included
+ }
+ },
+ {"model_info": {"id": "deployment-4", "team_id": "team-a"}},
+ ]
+
+ @pytest.fixture
+ def sample_deployments_no_teams(self) -> List[Dict]:
+ """Sample deployments with no team_id restrictions"""
+ return [
+ {"model_info": {"id": "deployment-1"}},
+ {"model_info": {"id": "deployment-2"}},
+ ]
+
+ def test_filter_team_based_models_none_request_kwargs(
+ self, sample_deployments_with_teams
+ ):
+ """Test that when request_kwargs is None, all deployments are returned unchanged"""
+ result = filter_team_based_models(sample_deployments_with_teams, None)
+ assert result == sample_deployments_with_teams
+
+ def test_filter_team_based_models_empty_request_kwargs(
+ self, sample_deployments_with_teams
+ ):
+ """Test with empty request_kwargs"""
+ result = filter_team_based_models(sample_deployments_with_teams, {})
+ # Should include all deployments since no team_id in request
+ assert len(result) == 1
+
+ def test_filter_team_based_models_no_metadata(self, sample_deployments_with_teams):
+ """Test with request_kwargs that has no metadata"""
+ request_kwargs = {"some_other_key": "value"}
+ result = filter_team_based_models(sample_deployments_with_teams, request_kwargs)
+ # Should include only non-team based deployments
+ assert len(result) == 1
+
+ def test_filter_team_based_models_team_match_metadata(
+ self, sample_deployments_with_teams
+ ):
+ """Test filtering when team_id is in metadata"""
+ request_kwargs = {"metadata": {"user_api_key_team_id": "team-a"}}
+ result = filter_team_based_models(sample_deployments_with_teams, request_kwargs)
+
+ # Should include:
+ # - deployment-1 (team-a matches)
+ # - deployment-3 (no team_id restriction)
+ # - deployment-4 (team-a matches)
+ # Should exclude:
+ # - deployment-2 (team-b doesn't match)
+ expected_ids = ["deployment-1", "deployment-3", "deployment-4"]
+ result_ids = [d.get("model_info", {}).get("id") for d in result]
+ assert sorted(result_ids) == sorted(expected_ids)
+
+ def test_filter_team_based_models_team_match_litellm_metadata(
+ self, sample_deployments_with_teams
+ ):
+ """Test filtering when team_id is in litellm_metadata"""
+ request_kwargs = {"litellm_metadata": {"user_api_key_team_id": "team-b"}}
+ result = filter_team_based_models(sample_deployments_with_teams, request_kwargs)
+
+ # Should include:
+ # - deployment-2 (team-b matches)
+ # - deployment-3 (no team_id restriction)
+ # Should exclude:
+ # - deployment-1 (team-a doesn't match)
+ # - deployment-4 (team-a doesn't match)
+ expected_ids = ["deployment-2", "deployment-3"]
+ result_ids = [d.get("model_info", {}).get("id") for d in result]
+ assert sorted(result_ids) == sorted(expected_ids)
+
+ def test_filter_team_based_models_priority_metadata_over_litellm(
+ self, sample_deployments_with_teams
+ ):
+ """Test that metadata.user_api_key_team_id takes priority over litellm_metadata.user_api_key_team_id"""
+ request_kwargs = {
+ "metadata": {
+ "user_api_key_team_id": "team-a", # This should take priority
+ "litellm_metadata": {"user_api_key_team_id": "team-b"},
+ }
+ }
+ result = filter_team_based_models(sample_deployments_with_teams, request_kwargs)
+
+ # Should filter based on team-a (from metadata, not litellm_metadata)
+ expected_ids = ["deployment-1", "deployment-3", "deployment-4"]
+ result_ids = [d.get("model_info", {}).get("id") for d in result]
+ assert sorted(result_ids) == sorted(expected_ids)
+
+ def test_filter_team_based_models_no_matching_team(
+ self, sample_deployments_with_teams
+ ):
+ """Test when request team doesn't match any deployment teams"""
+ request_kwargs = {"metadata": {"user_api_key_team_id": "team-nonexistent"}}
+ result = filter_team_based_models(sample_deployments_with_teams, request_kwargs)
+
+ # Should only include deployment-3 (no team_id restriction)
+ expected_ids = ["deployment-3"]
+ result_ids = [d.get("model_info", {}).get("id") for d in result]
+ assert result_ids == expected_ids
+
+ def test_filter_team_based_models_no_team_restrictions(
+ self, sample_deployments_no_teams
+ ):
+ """Test with deployments that have no team restrictions"""
+ request_kwargs = {"metadata": {"user_api_key_team_id": "any-team"}}
+ result = filter_team_based_models(sample_deployments_no_teams, request_kwargs)
+
+ # Should include all deployments since none have team_id restrictions
+ assert result == sample_deployments_no_teams
+
+ def test_filter_team_based_models_missing_model_info(self):
+ """Test with deployments missing model_info"""
+ deployments = [
+ {"model_info": {"id": "deployment-1", "team_id": "team-a"}},
+ {
+ # Missing model_info entirely
+ },
+ {
+ "model_info": {
+ # Missing id
+ "team_id": "team-b"
+ }
+ },
+ ]
+
+ request_kwargs = {"metadata": {"user_api_key_team_id": "team-a"}}
+ result = filter_team_based_models(deployments, request_kwargs)
+
+ # Should handle missing model_info gracefully
+ # deployment-1 should be included (team matches)
+ # others should be included since they don't have proper team_id setup
+ assert len(result) >= 1 # At least deployment-1 should be included
+
+ def test_filter_team_based_models_dict_input(self):
+ """Test with Dict input instead of List[Dict]"""
+ # Note: Based on the function signature, it accepts Union[List[Dict], Dict]
+ # But the implementation seems to expect List[Dict] for the filtering logic
+ # This test documents the current behavior
+ deployments_dict = {"key1": "value1", "key2": "value2"}
+
+ request_kwargs = {"metadata": {"user_api_key_team_id": "team-a"}}
+
+ # This should not crash, though the filtering logic won't apply to Dict input
+ result = filter_team_based_models(deployments_dict, request_kwargs)
+ # The function will likely return the dict unchanged or handle it differently
+ assert result is not None
+
+ def test_filter_team_based_models_empty_deployments(self):
+ """Test with empty deployments list"""
+ result = filter_team_based_models(
+ [], {"metadata": {"user_api_key_team_id": "team-a"}}
+ )
+ assert result == []
+
+ def test_filter_team_based_models_none_team_id_in_deployment(self):
+ """Test with explicit None team_id in deployment"""
+ deployments = [
+ {"model_info": {"id": "deployment-1", "team_id": None}},
+ {"model_info": {"id": "deployment-2", "team_id": "team-a"}},
+ ]
+
+ request_kwargs = {"metadata": {"user_api_key_team_id": "team-a"}}
+ result = filter_team_based_models(deployments, request_kwargs)
+
+ # Both should be included:
+ # - deployment-1 (None team_id is treated as no restriction)
+ # - deployment-2 (team matches)
+ expected_ids = ["deployment-1", "deployment-2"]
+ result_ids = [d.get("model_info", {}).get("id") for d in result]
+ assert sorted(result_ids) == sorted(expected_ids)
diff --git a/tests/test_litellm/test_router.py b/tests/test_litellm/test_router.py
index 921cb178081..5682a51144f 100644
--- a/tests/test_litellm/test_router.py
+++ b/tests/test_litellm/test_router.py
@@ -423,3 +423,62 @@ async def test_router_aretrieve_file_content():
print(mock_afile_content.call_args.kwargs)
assert mock_afile_content.call_args.kwargs["api_key"] == "my-custom-key"
assert mock_afile_content.call_args.kwargs["api_base"] == "my-custom-base"
+
+
+
+async def test_router_filter_team_based_models():
+ """
+ Test that router.filter_team_based_models filters out models that are not in the team
+ """
+ from litellm.types.router import Deployment
+
+ router = litellm.Router(
+ model_list=[
+ {
+ "model_name": "gpt-3.5-turbo",
+ "litellm_params": {"model": "gpt-3.5-turbo"},
+ "model_info": {
+ "team_id": "test-team",
+ },
+ },
+ ],
+ )
+
+ # WORKS
+ result = await router.acompletion(
+ model="gpt-3.5-turbo",
+ messages=[{"role": "user", "content": "Hello, world!"}],
+ metadata={"user_api_key_team_id": "test-team"},
+ mock_response="Hello, world!",
+ )
+
+ assert result is not None
+
+ # FAILS
+ with pytest.raises(Exception) as e:
+ result = await router.acompletion(
+ model="gpt-3.5-turbo",
+ messages=[{"role": "user", "content": "Hello, world!"}],
+ metadata={"user_api_key_team_id": "test-team-2"},
+ mock_response="Hello, world!",
+ )
+ assert "No deployments available" in str(e.value)
+
+ ## ADD A MODEL THAT IS NOT IN THE TEAM
+ router.add_deployment(
+ Deployment(
+ model_name="gpt-3.5-turbo",
+ litellm_params={"model": "gpt-3.5-turbo"},
+ model_info={"tpm": 1000, "rpm": 1000},
+ )
+ )
+
+ result = await router.acompletion(
+ model="gpt-3.5-turbo",
+ messages=[{"role": "user", "content": "Hello, world!"}],
+ metadata={"user_api_key_team_id": "test-team-2"},
+ mock_response="Hello, world!",
+ )
+
+ assert result is not None