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]

(Feat) allow setting guardrails on a team on the API (#7959)

Ishaan Jaff085920aa1ce4
diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.py
index c5fe5518786..6df8fc2ddb2 100644
--- a/litellm/proxy/_types.py
+++ b/litellm/proxy/_types.py
@@ -955,6 +955,7 @@ class TeamBase(LiteLLMPydanticObjectBase):
class NewTeamRequest(TeamBase):
model_aliases: Optional[dict] = None
tags: Optional[list] = None
+ guardrails: Optional[List[str]] = None
model_config = ConfigDict(protected_namespaces=())
@@ -979,6 +980,7 @@ class UpdateTeamRequest(LiteLLMPydanticObjectBase):
models: Optional[list] = None
blocked: Optional[bool] = None
budget_duration: Optional[str] = None
+ guardrails: Optional[List[str]] = None
"""
team_id: str # required
@@ -993,6 +995,7 @@ class UpdateTeamRequest(LiteLLMPydanticObjectBase):
budget_duration: Optional[str] = None
tags: Optional[list] = None
model_aliases: Optional[dict] = None
+ guardrails: Optional[List[str]] = None
class ResetTeamBudgetRequest(LiteLLMPydanticObjectBase):
@@ -2254,6 +2257,11 @@ LiteLLM_ManagementEndpoint_MetadataFields = [
"temp_budget_expiry",
]
+LiteLLM_ManagementEndpoint_MetadataFields_Premium = [
+ "guardrails",
+ "tags",
+]
+
class ProviderBudgetResponseObject(LiteLLMPydanticObjectBase):
"""
diff --git a/litellm/proxy/management_endpoints/team_endpoints.py b/litellm/proxy/management_endpoints/team_endpoints.py
index 6ebfed0eef1..6d59122566a 100644
--- a/litellm/proxy/management_endpoints/team_endpoints.py
+++ b/litellm/proxy/management_endpoints/team_endpoints.py
@@ -14,7 +14,7 @@ import json
import traceback
import uuid
from datetime import datetime, timedelta, timezone
-from typing import List, Optional, Tuple, Union, cast
+from typing import Any, List, Optional, Tuple, Union, cast
import fastapi
from fastapi import APIRouter, Depends, Header, HTTPException, Request, status
@@ -27,6 +27,8 @@ from litellm.proxy._types import (
CommonProxyErrors,
DeleteTeamRequest,
LiteLLM_AuditLogs,
+ LiteLLM_ManagementEndpoint_MetadataFields,
+ LiteLLM_ManagementEndpoint_MetadataFields_Premium,
LiteLLM_ModelTable,
LiteLLM_TeamMembership,
LiteLLM_TeamTable,
@@ -134,7 +136,7 @@ async def new_team( # noqa: PLR0915
- tags: Optional[List[str]] - Tags for [tracking spend](https://litellm.vercel.app/docs/proxy/enterprise#tracking-spend-for-custom-tags) and/or doing [tag-based routing](https://litellm.vercel.app/docs/proxy/tag_routing).
- organization_id: Optional[str] - The organization id of the team. Default is None. Create via `/organization/new`.
- model_aliases: Optional[dict] - Model aliases for the team. [Docs](https://docs.litellm.ai/docs/proxy/team_based_routing#create-team-with-model-alias)
-
+ - guardrails: Optional[List[str]] - Guardrails for the team. [Docs](https://docs.litellm.ai/docs/proxy/guardrails)
Returns:
- team_id: (str) Unique team id - used for tracking spend across multiple keys for same team id.
@@ -272,18 +274,14 @@ async def new_team( # noqa: PLR0915
model_id=_model_id,
)
- # Set tags on the new team
- if data.tags is not None:
- from litellm.proxy.proxy_server import premium_user
-
- if premium_user is not True:
- raise ValueError(
- f"Only premium users can add tags to teams. {CommonProxyErrors.not_premium_user.value}"
+ # Set Management Endpoint Metadata Fields
+ for field in LiteLLM_ManagementEndpoint_MetadataFields_Premium:
+ if getattr(data, field) is not None:
+ _set_team_metadata_field(
+ team_data=complete_team_data,
+ field_name=field,
+ value=getattr(data, field),
)
- if complete_team_data.metadata is None:
- complete_team_data.metadata = {"tags": data.tags}
- else:
- complete_team_data.metadata["tags"] = data.tags
# If budget_duration is set, set `budget_reset_at`
if complete_team_data.budget_duration is not None:
@@ -410,7 +408,7 @@ async def update_team(
- tags: Optional[List[str]] - Tags for [tracking spend](https://litellm.vercel.app/docs/proxy/enterprise#tracking-spend-for-custom-tags) and/or doing [tag-based routing](https://litellm.vercel.app/docs/proxy/tag_routing).
- organization_id: Optional[str] - The organization id of the team. Default is None. Create via `/organization/new`.
- model_aliases: Optional[dict] - Model aliases for the team. [Docs](https://docs.litellm.ai/docs/proxy/team_based_routing#create-team-with-model-alias)
-
+ - guardrails: Optional[List[str]] - Guardrails for the team. [Docs](https://docs.litellm.ai/docs/proxy/guardrails)
Example - update team TPM Limit
```
@@ -471,20 +469,14 @@ async def update_team(
# set the budget_reset_at in DB
updated_kv["budget_reset_at"] = reset_at
- # check if user is trying to update tags for team
- if "tags" in updated_kv and updated_kv["tags"] is not None:
- from litellm.proxy.proxy_server import premium_user
-
- if premium_user is not True:
- raise ValueError(
- f"Only premium users can add tags to teams. {CommonProxyErrors.not_premium_user.value}"
+ # update team metadata fields
+ _team_metadata_fields = LiteLLM_ManagementEndpoint_MetadataFields_Premium
+ for field in _team_metadata_fields:
+ if field in updated_kv and updated_kv[field] is not None:
+ _update_team_metadata_field(
+ updated_kv=updated_kv,
+ field_name=field,
)
- # remove tags from updated_kv
- _tags = updated_kv.pop("tags")
- if "metadata" in updated_kv and updated_kv["metadata"] is not None:
- updated_kv["metadata"]["tags"] = _tags
- else:
- updated_kv["metadata"] = {"tags": _tags}
if "model_aliases" in updated_kv:
updated_kv.pop("model_aliases")
@@ -1499,3 +1491,52 @@ async def get_paginated_teams(
f"[Non-Blocking] Error getting paginated teams: {e}"
)
return [], 0
+
+
+def _update_team_metadata_field(updated_kv: dict, field_name: str) -> None:
+ """
+ Helper function to update metadata fields that require premium user checks in the update endpoint
+
+ Args:
+ updated_kv: The key-value dict being used for the update
+ field_name: Name of the metadata field being updated
+ """
+ if field_name in LiteLLM_ManagementEndpoint_MetadataFields_Premium:
+ _premium_user_check()
+
+ if field_name in updated_kv and updated_kv[field_name] is not None:
+ # remove field from updated_kv
+ _value = updated_kv.pop(field_name)
+ if "metadata" in updated_kv and updated_kv["metadata"] is not None:
+ updated_kv["metadata"][field_name] = _value
+ else:
+ updated_kv["metadata"] = {field_name: _value}
+
+
+def _set_team_metadata_field(
+ team_data: LiteLLM_TeamTable, field_name: str, value: Any
+) -> None:
+ """
+ Helper function to set metadata fields that require premium user checks
+
+ Args:
+ team_data: The team data object to modify
+ field_name: Name of the metadata field to set
+ value: Value to set for the field
+ """
+ if field_name in LiteLLM_ManagementEndpoint_MetadataFields_Premium:
+ _premium_user_check()
+ team_data.metadata = team_data.metadata or {}
+ team_data.metadata[field_name] = value
+
+
+def _premium_user_check():
+ from litellm.proxy.proxy_server import premium_user
+
+ if not premium_user:
+ raise HTTPException(
+ status_code=403,
+ detail={
+ "error": f"This feature is only available for LiteLLM Enterprise users. {CommonProxyErrors.not_premium_user.value}"
+ },
+ )
diff --git a/tests/proxy_unit_tests/test_key_generate_prisma.py b/tests/proxy_unit_tests/test_key_generate_prisma.py
index e4382a4543c..7dbb9363d5a 100644
--- a/tests/proxy_unit_tests/test_key_generate_prisma.py
+++ b/tests/proxy_unit_tests/test_key_generate_prisma.py
@@ -3033,6 +3033,68 @@ async def test_generate_key_with_guardrails(prisma_client):
}
+async def test_team_guardrails(prisma_client):
+ """
+ - Test setting guardrails on a team
+ - Assert this is returned when calling /team/info
+ - Team/update with guardrails should update the guardrails
+ - Assert new guardrails are returned when calling /team/info
+ """
+ litellm.set_verbose = True
+ setattr(litellm.proxy.proxy_server, "prisma_client", prisma_client)
+ setattr(litellm.proxy.proxy_server, "master_key", "sk-1234")
+ await litellm.proxy.proxy_server.prisma_client.connect()
+
+ _new_team = NewTeamRequest(
+ team_alias="test-teamA",
+ guardrails=["aporia-pre-call"],
+ )
+
+ new_team_response = await new_team(
+ data=_new_team,
+ user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN),
+ http_request=Request(scope={"type": "http"}),
+ )
+
+ print("new_team_response", new_team_response)
+
+ # call /team/info
+ team_info_response = await team_info(
+ team_id=new_team_response["team_id"],
+ user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN),
+ http_request=Request(scope={"type": "http"}),
+ )
+ print("team_info_response", team_info_response)
+
+ assert team_info_response["team_info"].metadata["guardrails"] == ["aporia-pre-call"]
+
+ # team update with guardrails
+ team_update_response = await update_team(
+ data=UpdateTeamRequest(
+ team_id=new_team_response["team_id"],
+ guardrails=["aporia-pre-call", "aporia-post-call"],
+ ),
+ user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN),
+ http_request=Request(scope={"type": "http"}),
+ )
+
+ print("team_update_response", team_update_response)
+
+ # call /team/info again
+ team_info_response = await team_info(
+ team_id=new_team_response["team_id"],
+ user_api_key_dict=UserAPIKeyAuth(user_role=LitellmUserRoles.PROXY_ADMIN),
+ http_request=Request(scope={"type": "http"}),
+ )
+
+ print("team_info_response", team_info_response)
+ assert team_info_response["team_info"].metadata["guardrails"] == [
+ "aporia-pre-call",
+ "aporia-post-call",
+ ]
+
+
@pytest.mark.asyncio()
@pytest.mark.flaky(retries=6, delay=1)
async def test_team_access_groups(prisma_client):