Skip to content
Merged
Show file tree
Hide file tree
Changes from 20 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
f626587
feat(teams): resolve access group models/MCPs/agents in team endpoints
ryan-crabbe-berri Apr 2, 2026
bbe708b
perf(teams): single-pass access group resolution + asyncio.gather in …
ryan-crabbe-berri Apr 2, 2026
59b0910
docs: add default_team_params to config reference and update examples
ryan-crabbe-berri Apr 2, 2026
c19a63e
docs: clarify that models sub-field only applies to SSO auto-created …
ryan-crabbe-berri Apr 2, 2026
f0bd334
fix: lazy import get_access_object to break cyclic import + short-cir…
ryan-crabbe-berri Apr 2, 2026
5a8f910
add: making organizations a select instead of read only badges
ryan-crabbe-berri Apr 3, 2026
1bb726a
fix(ui): only send organization_id when changed and use raw initial v…
ryan-crabbe-berri Apr 3, 2026
cd7b262
fix(ui): add paginated team search to usage page filter
ryan-crabbe-berri Apr 3, 2026
1533f68
fix(ui): fix imports and update placeholder for team multi select
ryan-crabbe-berri Apr 3, 2026
96b660b
fix(ui): wire team_id filter to key alias dropdown on Virtual Keys tab
ryan-crabbe-berri Apr 3, 2026
1521004
Merge pull request #25114 from BerriAI/litellm_fix-virtual-keys-team-…
ryan-crabbe-berri Apr 3, 2026
0575c3f
Merge pull request #25107 from BerriAI/litellm_fix-team-id-search-filter
ryan-crabbe-berri Apr 3, 2026
20077fe
Merge pull request #25095 from BerriAI/litellm_fix-ui-update-org-teams
ryan-crabbe-berri Apr 3, 2026
eb780a8
Merge pull request #25032 from BerriAI/litellm_docs-default-team-params
ryan-crabbe-berri Apr 3, 2026
38f6c94
fix(tests): correct mock targets in TestResolveAccessGroupResources
ryan-crabbe-berri Apr 3, 2026
ea32cb5
fix: use direct attribute access with or [] fallback in _resolve_acce…
ryan-crabbe-berri Apr 3, 2026
3bdd042
fix(ui): remove model source legend from team detail view
ryan-crabbe-berri Apr 3, 2026
bb03a11
fix(ui): add missing access_group fields to TeamData.team_info type
ryan-crabbe-berri Apr 3, 2026
93369bf
perf(teams): batch-fetch access groups in single DB query
ryan-crabbe-berri Apr 4, 2026
0331fb5
Merge pull request #25027 from BerriAI/litellm_add-access-group-to-model
ryan-crabbe-berri Apr 4, 2026
ce219fc
refactor(proxy): extract helpers to fix PLR0915 violations
ryan-crabbe-berri Apr 4, 2026
866c4a2
test(ui): update tests to match new team_id / access-group signatures
ryan-crabbe-berri Apr 4, 2026
c495acd
fix(ui): send null (not '') for cleared organization_id on team update
ryan-crabbe-berri Apr 4, 2026
ad203dc
poetry
ryan-crabbe-berri Apr 4, 2026
ad81892
Merge remote-tracking branch 'origin/main' into litellm_ryan-march-31
ryan-crabbe-berri Apr 4, 2026
76c0591
chore: regen poetry.lock for litellm-proxy-extras 0.4.64 bump
ryan-crabbe-berri Apr 4, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/my-website/docs/proxy/config_settings.md
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,7 @@ router_settings:
| enable_json_schema_validation | boolean | If true, enables json schema validation for all requests. |
| enable_key_alias_format_validation | boolean | If true, validates `key_alias` format on `/key/generate` and `/key/update`. Must be 2-255 chars, start/end with alphanumeric, only allow `a-zA-Z0-9_-/.@`. Default `false`. |
| disable_copilot_system_to_assistant | boolean | **DEPRECATED** - GitHub Copilot API supports system prompts. |
| default_team_params | object | Default parameters applied to every new team created via `/team/new` (including SSO auto-created teams). Only fills in fields not explicitly set in the request. Sub-fields: `max_budget` (float), `budget_duration` (string, e.g. `"30d"`), `tpm_limit` (integer), `rpm_limit` (integer), `team_member_permissions` (array of strings, e.g. `["/team/daily/activity", "/key/generate"]`), `models` (array of strings — only applied to SSO auto-created teams). |

### general_settings - Reference

Expand Down
25 changes: 17 additions & 8 deletions docs/my-website/docs/proxy/self_serve.md
Original file line number Diff line number Diff line change
Expand Up @@ -358,10 +358,15 @@ When you connect litellm to your SSO provider, litellm can auto-create teams. Us

```yaml showLineNumbers title="Default Params for new teams"
litellm_settings:
default_team_params: # Default Params to apply when litellm auto creates a team from SSO IDP provider
max_budget: 100 # Optional[float], optional): $100 budget for the team
budget_duration: 30d # Optional[str], optional): 30 days budget_duration for the team
models: ["gpt-3.5-turbo"] # Optional[List[str]], optional): models to be used by the team
default_team_params: # Applied to all /team/new calls (including SSO auto-created teams) when the field is not explicitly set
max_budget: 100 # Optional[float]: $100 budget for the team
budget_duration: 30d # Optional[str]: 30 days budget_duration for the team
models: ["gpt-3.5-turbo"] # Optional[List[str]]: models for the team (only applied to SSO auto-created teams)
tpm_limit: 100000 # Optional[int]: tokens per minute limit
rpm_limit: 1000 # Optional[int]: requests per minute limit
team_member_permissions: # Optional[List[str]]: permissions granted to non-admin team members
- "/team/daily/activity" # Allow members to view team usage
- "/key/generate" # Allow members to generate API keys
```


Expand Down Expand Up @@ -390,10 +395,14 @@ litellm_settings:
max_budget_in_team: 100 # Optional[float], optional): $100 budget for the team. Defaults to None.
user_role: "user" # Optional[str], optional): "user" or "admin". Defaults to "user"

default_team_params: # Default Params to apply when litellm auto creates a team from SSO IDP provider
max_budget: 100 # Optional[float], optional): $100 budget for the team
budget_duration: 30d # Optional[str], optional): 30 days budget_duration for the team
models: ["gpt-3.5-turbo"] # Optional[List[str]], optional): models to be used by the team
default_team_params: # Applied to all /team/new calls (including SSO auto-created teams) when the field is not explicitly set
max_budget: 100 # Optional[float]: $100 budget for the team
budget_duration: 30d # Optional[str]: 30 days budget_duration for the team
models: ["gpt-3.5-turbo"] # Optional[List[str]]: models for the team (only applied to SSO auto-created teams)
tpm_limit: 100000 # Optional[int]: tokens per minute limit
rpm_limit: 1000 # Optional[int]: requests per minute limit
team_member_permissions: # Optional[List[str]]: permissions granted to non-admin team members
- "/team/daily/activity"


upperbound_key_generate_params: # Upperbound for /key/generate requests when self-serve flow is on
Expand Down
10 changes: 6 additions & 4 deletions docs/my-website/docs/tutorials/msft_sso.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,10 +123,12 @@ Navigate to your litellm config file and set the following params

```yaml showLineNumbers title="litellm config with default_team_params"
litellm_settings:
default_team_params: # Default Params to apply when litellm auto creates a team from SSO IDP provider
max_budget: 100 # Optional[float], optional): $100 budget for the team
budget_duration: 30d # Optional[str], optional): 30 days budget_duration for the team
models: ["gpt-3.5-turbo"] # Optional[List[str]], optional): models to be used by the team
default_team_params: # Applied to all /team/new calls (including SSO auto-created teams) when the field is not explicitly set
max_budget: 100 # Optional[float]: $100 budget for the team
budget_duration: 30d # Optional[str]: 30 days budget_duration for the team
models: ["gpt-3.5-turbo"] # Optional[List[str]]: models for the team (only applied to SSO auto-created teams)
team_member_permissions: # Optional[List[str]]: permissions granted to non-admin team members
- "/team/daily/activity" # Allow members to view team usage
```

### 3.2 Auto-create a new team on LiteLLM
Expand Down
4 changes: 4 additions & 0 deletions litellm/proxy/_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -3805,6 +3805,10 @@ class OrganizationMemberUpdateResponse(MemberUpdateResponse):

class TeamInfoResponseObjectTeamTable(LiteLLM_TeamTable):
team_member_budget_table: Optional[LiteLLM_BudgetTable] = None
# Resources inherited from access groups (separate from direct assignments)
access_group_models: Optional[List[str]] = None
access_group_mcp_server_ids: Optional[List[str]] = None
access_group_agent_ids: Optional[List[str]] = None


class TeamInfoResponseObject(TypedDict):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4395,6 +4395,9 @@ async def key_aliases(
search: Optional[str] = Query(
None, description="Search key aliases (case-insensitive partial match)"
),
team_id: Optional[str] = Query(
None, description="Filter aliases to keys belonging to this team"
),
) -> Dict[str, Any]:
"""
Lists key aliases with pagination and optional search.
Expand Down Expand Up @@ -4470,6 +4473,10 @@ async def key_aliases(
query_params.append(f"%{search}%")
where_parts.append(f"key_alias ILIKE ${len(query_params)}")

if team_id:
query_params.append(team_id)
where_parts.append(f"team_id = ${len(query_params)}")
Comment on lines +4489 to +4491

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Raw SQL for new team_id filter

The team_id filter is added using the existing raw-SQL pattern in this function. The comment at the top of the function explains why raw SQL is used here (Prisma doesn't support column-level SELECT projection on find_many), and the value is correctly parameterized, so there is no injection risk. However, CLAUDE.md explicitly states: "Do not write raw SQL for proxy DB operations. Use Prisma model methods instead of execute_raw/query_raw." The existing code already violates this rule, but extending it amplifies the concern. If a Prisma-level approach is ever adopted (e.g. returning only the key_alias column), the team_id filter should migrate with it.


where_sql = " AND ".join(where_parts)

count_sql = f'SELECT COUNT(*) AS count FROM "LiteLLM_VerificationToken" WHERE {where_sql}'
Expand Down
67 changes: 67 additions & 0 deletions litellm/proxy/management_endpoints/team_endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -3042,6 +3042,19 @@ async def team_info(
team_info_response_object=_team_info,
)

# Resolve resources inherited from access groups
if _team_info.access_group_ids:
ag_lookup = await _batch_resolve_access_group_resources(_team_info.access_group_ids)
models, mcp_ids, agent_ids = set(), set(), set()
for ag_id in _team_info.access_group_ids:
if ag_id in ag_lookup:
models.update(ag_lookup[ag_id]["models"])
mcp_ids.update(ag_lookup[ag_id]["mcp_server_ids"])
agent_ids.update(ag_lookup[ag_id]["agent_ids"])
_team_info.access_group_models = list(models)
_team_info.access_group_mcp_server_ids = list(mcp_ids)
_team_info.access_group_agent_ids = list(agent_ids)

response_object = TeamInfoResponseObject(
team_id=team_id,
team_info=_team_info,
Expand Down Expand Up @@ -3332,6 +3345,36 @@ async def _build_team_list_where_conditions(
return where_conditions


async def _batch_resolve_access_group_resources(
all_access_group_ids: List[str],
) -> Dict[str, Dict[str, List[str]]]:
"""
Batch-fetch access groups in a single DB query and return a per-group
resource map.

Returns {ag_id: {"models": [...], "mcp_server_ids": [...], "agent_ids": [...]}}.
Missing/invalid groups are silently omitted.
"""
from litellm.proxy.proxy_server import prisma_client as _prisma_client

if not all_access_group_ids or _prisma_client is None:
return {}

unique_ids = list(set(all_access_group_ids))
rows = await _prisma_client.db.litellm_accessgrouptable.find_many(
where={"access_group_id": {"in": unique_ids}},
)

result: Dict[str, Dict[str, List[str]]] = {}
for row in rows:
result[row.access_group_id] = {
"models": list(row.access_model_names or []),
"mcp_server_ids": list(row.access_mcp_server_ids or []),
"agent_ids": list(row.access_agent_ids or []),
}
return result


def _convert_teams_to_response_models(
teams: list,
use_deleted_table: bool,
Expand Down Expand Up @@ -3558,6 +3601,30 @@ async def list_team_v2(
# Convert Prisma models to response models with members_count
team_list = _convert_teams_to_response_models(teams, use_deleted_table)

# Resolve resources inherited from access groups (single batch query)
if not use_deleted_table:
team_items_with_ag = [
t for t in team_list
if isinstance(t, TeamListItem) and t.access_group_ids
]
if team_items_with_ag:
all_ag_ids = [
ag_id
for t in team_items_with_ag
for ag_id in (t.access_group_ids or [])
]
ag_lookup = await _batch_resolve_access_group_resources(all_ag_ids)
for team_item in team_items_with_ag:
models, mcp_ids, agent_ids = set(), set(), set()
for ag_id in (team_item.access_group_ids or []):
if ag_id in ag_lookup:
models.update(ag_lookup[ag_id]["models"])
mcp_ids.update(ag_lookup[ag_id]["mcp_server_ids"])
agent_ids.update(ag_lookup[ag_id]["agent_ids"])
team_item.access_group_models = list(models)
team_item.access_group_mcp_server_ids = list(mcp_ids)
team_item.access_group_agent_ids = list(agent_ids)

return {
"teams": team_list,
"total": total_count,
Expand Down
4 changes: 4 additions & 0 deletions litellm/types/proxy/management_endpoints/team_endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@ class TeamListItem(LiteLLM_TeamTable):
"""A team item in the paginated list response, enriched with computed fields."""

members_count: int = 0
# Resources inherited from access groups (separate from direct assignments)
access_group_models: Optional[List[str]] = None
access_group_mcp_server_ids: Optional[List[str]] = None
access_group_agent_ids: Optional[List[str]] = None


class TeamListResponse(BaseModel):
Expand Down
128 changes: 128 additions & 0 deletions tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -6497,3 +6497,131 @@ async def test_create_team_member_budget_table_with_duration():
assert budget_request.budget_duration == "30d"
assert budget_request.max_budget == 20.0
assert result["metadata"]["team_member_budget_id"] == "budget-abc"


# ---------------------------------------------------------------------------
# Tests for _batch_resolve_access_group_resources
# ---------------------------------------------------------------------------


class TestBatchResolveAccessGroupResources:
"""Tests for the batch access group resource resolution helper."""

@pytest.mark.asyncio
async def test_returns_empty_when_no_ids(self):
"""Empty list should return empty dict."""
from litellm.proxy.management_endpoints.team_endpoints import (
_batch_resolve_access_group_resources,
)

assert await _batch_resolve_access_group_resources([]) == {}

@pytest.mark.asyncio
async def test_single_access_group(self):
"""Single access group should return its resources."""
from litellm.proxy.management_endpoints.team_endpoints import (
_batch_resolve_access_group_resources,
)

fake_row = MagicMock()
fake_row.access_group_id = "ag-1"
fake_row.access_model_names = ["gpt-4", "claude-3"]
fake_row.access_mcp_server_ids = ["mcp-1"]
fake_row.access_agent_ids = ["agent-1", "agent-2"]

fake_prisma = MagicMock()
fake_prisma.db.litellm_accessgrouptable.find_many = AsyncMock(return_value=[fake_row])

with patch("litellm.proxy.proxy_server.prisma_client", fake_prisma):
result = await _batch_resolve_access_group_resources(["ag-1"])

assert sorted(result["ag-1"]["models"]) == ["claude-3", "gpt-4"]
assert result["ag-1"]["mcp_server_ids"] == ["mcp-1"]
assert sorted(result["ag-1"]["agent_ids"]) == ["agent-1", "agent-2"]

@pytest.mark.asyncio
async def test_multiple_access_groups(self):
"""Multiple access groups returned in a single query."""
from litellm.proxy.management_endpoints.team_endpoints import (
_batch_resolve_access_group_resources,
)

row1 = MagicMock()
row1.access_group_id = "ag-1"
row1.access_model_names = ["gpt-4"]
row1.access_mcp_server_ids = ["mcp-1"]
row1.access_agent_ids = ["agent-1"]

row2 = MagicMock()
row2.access_group_id = "ag-2"
row2.access_model_names = ["gemini"]
row2.access_mcp_server_ids = ["mcp-2"]
row2.access_agent_ids = ["agent-2"]

fake_prisma = MagicMock()
fake_prisma.db.litellm_accessgrouptable.find_many = AsyncMock(return_value=[row1, row2])

with patch("litellm.proxy.proxy_server.prisma_client", fake_prisma):
result = await _batch_resolve_access_group_resources(["ag-1", "ag-2"])

assert result["ag-1"]["models"] == ["gpt-4"]
assert result["ag-2"]["models"] == ["gemini"]

@pytest.mark.asyncio
async def test_missing_access_group_omitted(self):
"""If an access group doesn't exist in DB, it's simply not in the result."""
from litellm.proxy.management_endpoints.team_endpoints import (
_batch_resolve_access_group_resources,
)

row1 = MagicMock()
row1.access_group_id = "ag-1"
row1.access_model_names = ["gpt-4"]
row1.access_mcp_server_ids = []
row1.access_agent_ids = []

fake_prisma = MagicMock()
fake_prisma.db.litellm_accessgrouptable.find_many = AsyncMock(return_value=[row1])

with patch("litellm.proxy.proxy_server.prisma_client", fake_prisma):
result = await _batch_resolve_access_group_resources(["ag-1", "ag-missing"])

assert "ag-1" in result
assert "ag-missing" not in result

@pytest.mark.asyncio
async def test_returns_empty_when_prisma_unavailable(self):
"""If prisma_client is None, should return empty dict."""
from litellm.proxy.management_endpoints.team_endpoints import (
_batch_resolve_access_group_resources,
)

with patch("litellm.proxy.proxy_server.prisma_client", None):
result = await _batch_resolve_access_group_resources(["ag-1"])

assert result == {}

@pytest.mark.asyncio
async def test_deduplicates_input_ids(self):
"""Duplicate IDs in input should result in a single DB lookup."""
from litellm.proxy.management_endpoints.team_endpoints import (
_batch_resolve_access_group_resources,
)

row1 = MagicMock()
row1.access_group_id = "ag-1"
row1.access_model_names = ["gpt-4"]
row1.access_mcp_server_ids = []
row1.access_agent_ids = []

fake_find_many = AsyncMock(return_value=[row1])
fake_prisma = MagicMock()
fake_prisma.db.litellm_accessgrouptable.find_many = fake_find_many

with patch("litellm.proxy.proxy_server.prisma_client", fake_prisma):
result = await _batch_resolve_access_group_resources(["ag-1", "ag-1", "ag-1"])

# Should have been called with deduplicated list
call_args = fake_find_many.call_args
assert len(call_args.kwargs["where"]["access_group_id"]["in"]) == 1
assert "ag-1" in result
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@ const infiniteKeyAliasKeys = createQueryKeys("infiniteKeyAliases");
export const useInfiniteKeyAliases = (
size: number = 50,
search?: string,
team_id?: string,
) => {
const { accessToken } = useAuthorized();
return useInfiniteQuery<PaginatedKeyAliasResponse>({
queryKey: infiniteKeyAliasKeys.list({
filters: {
size,
...(search && { search }),
...(team_id && { team_id }),
},
}),
queryFn: async ({ pageParam }) => {
Expand All @@ -23,6 +25,7 @@ export const useInfiniteKeyAliases = (
pageParam as number,
size,
search,
team_id,
);
},
initialPageParam: 1,
Expand Down
Loading
Loading