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
Management Fixes - don't apply default internal user settings to admins + preserve all model access for teams with empty model list, when team model added + /v2/model/info fixes (#11957)
Krish Dholakia7f3d8bb9c5e1
diff --git a/litellm/proxy/management_endpoints/internal_user_endpoints.py b/litellm/proxy/management_endpoints/internal_user_endpoints.pyindex 53a648ffdad..15cb3d2ad19 100644--- a/litellm/proxy/management_endpoints/internal_user_endpoints.py+++ b/litellm/proxy/management_endpoints/internal_user_endpoints.py@@ -63,7 +63,10 @@ def _update_internal_new_user_params(data_json: dict, data: NewUserRequest) -> d"user" # only create a user, don't create key if 'auto_create_key' set to False)- if litellm.default_internal_user_params:+ if litellm.default_internal_user_params and (+ data.user_role != LitellmUserRoles.PROXY_ADMIN.value+ and data.user_role != LitellmUserRoles.PROXY_ADMIN+ ):for key, value in litellm.default_internal_user_params.items():if key == "available_teams":continuediff --git a/litellm/proxy/management_endpoints/team_endpoints.py b/litellm/proxy/management_endpoints/team_endpoints.pyindex bdc61e812dc..31d2877ea69 100644--- a/litellm/proxy/management_endpoints/team_endpoints.py+++ b/litellm/proxy/management_endpoints/team_endpoints.py@@ -304,11 +304,12 @@ async def new_team( # noqa: PLR0915if prisma_client is None:raise HTTPException(status_code=500, detail={"error": "No db connected"})-# Check if license is over limittotal_teams = await prisma_client.db.litellm_teamtable.count()- if total_teams and _license_check.is_team_count_over_limit(team_count=total_teams):+ if total_teams and _license_check.is_team_count_over_limit(+ team_count=total_teams+ ):raise HTTPException(status_code=403,detail="License is over limit. Please contact [email protected] to upgrade your license.",@@ -2297,6 +2298,23 @@ async def ui_view_teams(raise HTTPException(status_code=500, detail=f"Error searching teams: {str(e)}")+def add_new_models_to_team(+ team_obj: LiteLLM_TeamTable, new_models: List[str]+) -> List[str]:+ """+ Add new models to a team's allowed model list.+ """+ current_models = team_obj.models+ if (+ current_models is not None and len(current_models) == 0+ ): # implies all model access+ current_models = [SpecialModelNames.all_proxy_models.value]+ else:+ current_models = []+ updated_models = list(set(current_models + new_models))+ return updated_models++@router.post("/team/model/add",tags=["team management"],@@ -2356,12 +2374,7 @@ async def team_model_add(detail={"error": "Only proxy admin or team admin can modify team models"},)- # Get current models list- current_models = team_obj.models or []-- # Add new models (avoid duplicates)- updated_models = list(set(current_models + data.models))-+ updated_models = add_new_models_to_team(team_obj=team_obj, new_models=data.models)# Update teamupdated_team = await prisma_client.db.litellm_teamtable.update(where={"team_id": data.team_id}, data={"models": updated_models}diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex 963858b220c..375833b7de5 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -5533,6 +5533,51 @@ async def non_admin_all_models(return unique_models+def _add_team_models_to_all_models(+ team_db_objects_typed: List[LiteLLM_TeamTable],+ llm_router: Router,+) -> Dict[str, Set[str]]:+ """+ Add team models to all models+ """+ team_models: Dict[str, Set[str]] = {}++ for team_object in team_db_objects_typed:++ if (+ len(team_object.models) == 0 # empty list = all model access+ or SpecialModelNames.all_proxy_models.value in team_object.models+ ):++ model_list = llm_router.get_model_list()+ if model_list is not None:+ for model in model_list:+ model_id = model.get("model_info", {}).get("id", None)+ if model_id is None:+ continue+ # if team model id set, check if team id in user_teams+ team_model_id = model.get("model_info", {}).get("team_id", None)+ can_add_model = False+ if team_model_id is None:+ can_add_model = True+ elif team_model_id in team_object.team_id:+ can_add_model = True++ if can_add_model:+ team_models.setdefault(model_id, set()).add(team_object.team_id)+ else:+ for model_name in team_object.models:+ _models = llm_router.get_model_list(model_name=model_name)+ if _models is not None:+ for model in _models:+ model_id = model.get("model_info", {}).get("id", None)+ if model_id is not None:+ team_models.setdefault(model_id, set()).add(+ team_object.team_id+ )+ return team_models++async def get_all_team_models(user_teams: Union[List[str], Literal["*"]],prisma_client: PrismaClient,@@ -5545,7 +5590,7 @@ async def get_all_team_models(2. Get all models across all teams3. Return {"model_id": ["team_id1", "team_id2"]}"""- team_models: Dict[str, Set[str]] = {}+team_db_objects_typed: List[LiteLLM_TeamTable] = []if user_teams == "*":@@ -5563,25 +5608,10 @@ async def get_all_team_models(for team_db_object in team_db_objects]- for team_object in team_db_objects_typed:- if (- len(team_object.models) == 0 # empty list = all model access- or SpecialModelNames.all_proxy_models.value in team_object.models- ):- _model_ids = llm_router.get_model_ids()- if _model_ids is not None:- for model_id in _model_ids:- team_models.setdefault(model_id, set()).add(team_object.team_id)- else:- for model_name in team_object.models:- _models = llm_router.get_model_list(model_name=model_name)- if _models is not None:- for model in _models:- model_id = model.get("model_info", {}).get("id", None)- if model_id is not None:- team_models.setdefault(model_id, set()).add(- team_object.team_id- )+ team_models = _add_team_models_to_all_models(+ team_db_objects_typed=team_db_objects_typed,+ llm_router=llm_router,+ )# convert set to listreturned_team_models: Dict[str, List[str]] = {}@@ -5625,7 +5655,7 @@ async def get_all_team_and_direct_access_models(if user_api_key_dict.user_role == LitellmUserRoles.PROXY_ADMIN:user_teams = "*"direct_access_models = llm_router.get_model_ids() # has access to all models- else:+ elif user_api_key_dict.user_id is not None:user_db_object = await prisma_client.db.litellm_usertable.find_unique(where={"user_id": user_api_key_dict.user_id})@@ -5645,10 +5675,17 @@ async def get_all_team_and_direct_access_models()for _model in all_models:model_id = _model.get("model_info", {}).get("id", None)+ team_only_model_id = _model.get("model_info", {}).get("team_id", None)if model_id is not None:- _model["model_info"]["access_via_team_ids"] = team_models.get(- model_id, []- )+ can_use_model = False+ if team_only_model_id is not None:+ pass+ else:+ can_use_model = True+ if can_use_model:+ _model["model_info"]["access_via_team_ids"] = team_models.get(+ model_id, []+ )## ADD DIRECT_ACCESS TO RELEVANT MODELSfor _model in all_models:diff --git a/tests/test_litellm/proxy/management_endpoints/test_internal_user_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_internal_user_endpoints.pyindex 2a0e4cc88d8..d87225e4d8d 100644--- a/tests/test_litellm/proxy/management_endpoints/test_internal_user_endpoints.py+++ b/tests/test_litellm/proxy/management_endpoints/test_internal_user_endpoints.py@@ -474,3 +474,141 @@ async def test_new_user_default_teams_flow(mocker):else:if hasattr(litellm, "default_internal_user_params"):delattr(litellm, "default_internal_user_params")+++def test_update_internal_new_user_params_proxy_admin_role():+ """+ Test that default_internal_user_params are NOT applied when user_role is PROXY_ADMIN+ """+ import litellm+ from litellm.proxy._types import LitellmUserRoles, NewUserRequest+ from litellm.proxy.management_endpoints.internal_user_endpoints import (+ _update_internal_new_user_params,+ )++ # Set up default_internal_user_params+ original_default_params = getattr(litellm, "default_internal_user_params", None)+ litellm.default_internal_user_params = {+ "max_budget": 1000,+ "models": ["gpt-3.5-turbo", "gpt-4"],+ "tpm_limit": 5000,+ }++ try:+ # Create test data with PROXY_ADMIN role+ data = NewUserRequest(+ user_email="[email protected]", user_role=LitellmUserRoles.PROXY_ADMIN.value+ )+ data_json = data.model_dump(exclude_unset=True)++ # Call the function+ result = _update_internal_new_user_params(data_json=data_json, data=data)++ # Assertions - default params should NOT be applied for PROXY_ADMIN+ assert (+ "max_budget" not in result+ ), "Default max_budget should NOT be applied to PROXY_ADMIN"+ assert (+ "models" not in result+ ), "Default models should NOT be applied to PROXY_ADMIN"+ assert (+ "tpm_limit" not in result+ ), "Default tpm_limit should NOT be applied to PROXY_ADMIN"++ # These should still work+ assert result["user_email"] == "[email protected]"+ assert result["user_role"] == LitellmUserRoles.PROXY_ADMIN.value++ finally:+ # Restore original default params+ if original_default_params is not None:+ litellm.default_internal_user_params = original_default_params+ else:+ if hasattr(litellm, "default_internal_user_params"):+ delattr(litellm, "default_internal_user_params")+++def test_update_internal_new_user_params_no_role_specified():+ """+ Test that default_internal_user_params ARE applied when user_role is not set+ """+ import litellm+ from litellm.proxy._types import NewUserRequest+ from litellm.proxy.management_endpoints.internal_user_endpoints import (+ _update_internal_new_user_params,+ )++ # Set up default_internal_user_params+ original_default_params = getattr(litellm, "default_internal_user_params", None)+ litellm.default_internal_user_params = {+ "max_budget": 1000,+ "models": ["gpt-3.5-turbo", "gpt-4"],+ "tpm_limit": 5000,+ }++ try:+ # Create test data without specifying user_role+ data = NewUserRequest(user_email="[email protected]") # No user_role specified+ data_json = data.model_dump(exclude_unset=True)++ # Call the function+ result = _update_internal_new_user_params(data_json=data_json, data=data)++ # Assertions - default params should be applied when no role is specified+ assert result.get("max_budget") == 1000+ assert result.get("models") == ["gpt-3.5-turbo", "gpt-4"]+ assert result.get("tpm_limit") == 5000+ assert result["user_email"] == "[email protected]"++ finally:+ # Restore original default params+ if original_default_params is not None:+ litellm.default_internal_user_params = original_default_params+ else:+ if hasattr(litellm, "default_internal_user_params"):+ delattr(litellm, "default_internal_user_params")+++def test_update_internal_new_user_params_internal_user_role():+ """+ Test that default_internal_user_params ARE applied when user_role is INTERNAL_USER+ """+ import litellm+ from litellm.proxy._types import LitellmUserRoles, NewUserRequest+ from litellm.proxy.management_endpoints.internal_user_endpoints import (+ _update_internal_new_user_params,+ )++ # Set up default_internal_user_params+ original_default_params = getattr(litellm, "default_internal_user_params", None)+ litellm.default_internal_user_params = {+ "max_budget": 1000,+ "models": ["gpt-3.5-turbo", "gpt-4"],+ "tpm_limit": 5000,+ }++ try:+ # Create test data with INTERNAL_USER role+ data = NewUserRequest(+ user_email="[email protected]",+ user_role=LitellmUserRoles.INTERNAL_USER.value,+ )+ data_json = data.model_dump(exclude_unset=True)++ # Call the function+ result = _update_internal_new_user_params(data_json=data_json, data=data)++ # Assertions - default params should be applied for INTERNAL_USER+ assert result.get("max_budget") == 1000+ assert result.get("models") == ["gpt-3.5-turbo", "gpt-4"]+ assert result.get("tpm_limit") == 5000+ assert result["user_email"] == "[email protected]"+ assert result["user_role"] == LitellmUserRoles.INTERNAL_USER.value++ finally:+ # Restore original default params+ if original_default_params is not None:+ litellm.default_internal_user_params = original_default_params+ else:+ if hasattr(litellm, "default_internal_user_params"):+ delattr(litellm, "default_internal_user_params")diff --git a/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.pyindex e42c01fdaba..9aee01ed07d 100644--- a/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py+++ b/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py@@ -281,7 +281,9 @@ async def test_new_team_with_object_permission(mock_db_client, mock_admin_auth):"object_permission_id": "objperm123",}mock_team_create = AsyncMock(return_value=team_create_result)- mock_team_count = AsyncMock(return_value=0) # Mock count to return 0 (no existing teams)+ mock_team_count = AsyncMock(+ return_value=0+ ) # Mock count to return 0 (no existing teams)mock_db_client.db.litellm_teamtable = MagicMock()mock_db_client.db.litellm_teamtable.create = mock_team_createmock_db_client.db.litellm_teamtable.count = mock_team_count@@ -715,3 +717,24 @@ async def test_add_team_member_budget_table_budget_not_found():mock_prisma_client.db.litellm_budgettable.find_unique.assert_called_once_with(where={"budget_id": "nonexistent-budget-789"})+++def test_add_new_models_to_team():+ """+ Test add_new_models_to_team function+ """+ from litellm.proxy._types import SpecialModelNames+ from litellm.proxy.management_endpoints.team_endpoints import add_new_models_to_team++ team_obj = MagicMock(spec=LiteLLM_TeamTable)+ team_obj.models = []+ new_models = ["model4", "model5"]+ updated_models = add_new_models_to_team(team_obj=team_obj, new_models=new_models)+ assert (+ updated_models.sort()+ == [+ SpecialModelNames.all_proxy_models.value,+ "model4",+ "model5",+ ].sort()+ )diff --git a/tests/test_litellm/proxy/test_proxy_server.py b/tests/test_litellm/proxy/test_proxy_server.pyindex 199f459c719..deaf69afe67 100644--- a/tests/test_litellm/proxy/test_proxy_server.py+++ b/tests/test_litellm/proxy/test_proxy_server.py@@ -434,3 +434,27 @@ async def test_get_all_team_models():assert isinstance(result, dict)print("result: ", result)assert result == {"gpt-4-model-1": ["team1"], "gpt-4-model-2": ["team1"]}+++def test_add_team_models_to_all_models():+ """+ Test add_team_models_to_all_models function+ """+ from litellm.proxy._types import LiteLLM_TeamTable+ from litellm.proxy.proxy_server import _add_team_models_to_all_models++ team_db_objects_typed = MagicMock(spec=LiteLLM_TeamTable)+ team_db_objects_typed.team_id = "team1"+ team_db_objects_typed.models = ["all-proxy-models"]++ llm_router = MagicMock()+ llm_router.get_model_list.return_value = [+ {"model_info": {"id": "gpt-4-model-1", "team_id": "team2"}},+ {"model_info": {"id": "gpt-4-model-2"}},+ ]++ result = _add_team_models_to_all_models(+ team_db_objects_typed=[team_db_objects_typed],+ llm_router=llm_router,+ )+ assert result == {"gpt-4-model-2": {"team1"}}