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]

refactor(proxy): type the PATCH /team/{team_id} request body (#34195)

yuneng-jiange2e51f055d9a
diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.py
index 7df725bf965..20dc14aa5a3 100644
--- a/litellm/proxy/_types.py
+++ b/litellm/proxy/_types.py
@@ -1856,6 +1856,17 @@ class UpdateTeamRequest(LiteLLMPydanticObjectBase):
default_team_member_models: Optional[List[str]] = None # default allowed_models seeded onto new team members
+class PatchTeamRequest(UpdateTeamRequest):
+ """
+ Body of PATCH /team/{team_id}.
+
+ Identical to UpdateTeamRequest except team_id is optional, because PATCH takes it
+ from the path. A team_id in the body is still accepted when it matches the path.
+ """
+
+ team_id: str | None = None
+
+
class ResetTeamBudgetRequest(LiteLLMPydanticObjectBase):
"""
internal type used to reset the budget on a team
diff --git a/litellm/proxy/management_endpoints/team_endpoints.py b/litellm/proxy/management_endpoints/team_endpoints.py
index 3a7e89aa20d..59b0cbc4ae7 100644
--- a/litellm/proxy/management_endpoints/team_endpoints.py
+++ b/litellm/proxy/management_endpoints/team_endpoints.py
@@ -47,6 +47,7 @@ from litellm.proxy._types import (
Member,
NewTeamRequest,
OrgMember,
+ PatchTeamRequest,
ProxyErrorTypes,
ProxyException,
SpecialManagementEndpointEnums,
@@ -1956,6 +1957,7 @@ async def update_team(
)
async def patch_team(
team_id: str,
+ data: PatchTeamRequest,
http_request: Request,
user_api_key_dict: Annotated[UserAPIKeyAuth, Depends(user_api_key_auth)],
litellm_changed_by: Annotated[
@@ -1968,11 +1970,12 @@ async def patch_team(
"""
Partially update a team using RFC 7386 JSON Merge Patch semantics.
- `team_id` is taken from the path. `metadata` is merged with the team's stored
- metadata rather than replacing it: an omitted key is preserved, `key: null`
- deletes it, and any other value overwrites (recursing into nested objects).
- Every other field behaves exactly like `POST /team/update` (omitted preserves,
- a value overwrites). Returns the full updated team.
+ `team_id` is taken from the path; a `team_id` in the body is accepted only when it
+ matches. `metadata` is merged with the team's stored metadata rather than replacing
+ it: an omitted key is preserved, `key: null` deletes it, and any other value
+ overwrites (recursing into nested objects). Every other field behaves exactly like
+ `POST /team/update` (omitted preserves, a value overwrites). Returns the full
+ updated team.
```
curl --location --request PATCH 'http://0.0.0.0:4000/team/8d916b1c-510d-4894-a334-1c16a93344f5' \
@@ -1992,21 +1995,15 @@ async def patch_team(
detail={"error": CommonProxyErrors.db_not_connected_error.value},
)
- try:
- body = await http_request.json()
- except (json.JSONDecodeError, ValueError):
- raise HTTPException(status_code=400, detail={"error": "Request body must be a JSON object"})
- if not isinstance(body, dict):
- raise HTTPException(status_code=400, detail={"error": "Request body must be a JSON object"})
-
- body_team_id = body.pop("team_id", None)
- if body_team_id is not None and body_team_id != team_id:
+ if data.team_id is not None and data.team_id != team_id:
raise HTTPException(
status_code=400,
- detail={"error": f"team_id in body ({body_team_id}) does not match team_id in path ({team_id})"},
+ detail={"error": f"team_id in body ({data.team_id}) does not match team_id in path ({team_id})"},
)
- if "metadata" in body:
+ patch_fields = data.model_dump(exclude_unset=True, exclude={"team_id"})
+
+ if "metadata" in patch_fields:
existing_team_row = await TeamRepository(prisma_client).table.find_unique(where={"team_id": team_id})
if existing_team_row is None:
raise HTTPException(
@@ -2014,9 +2011,9 @@ async def patch_team(
detail={"error": f"Team not found, passed team_id={team_id}"},
)
existing_metadata = existing_team_row.metadata if isinstance(existing_team_row.metadata, dict) else {}
- body["metadata"] = apply_json_merge_patch(existing_metadata, body["metadata"])
+ patch_fields["metadata"] = apply_json_merge_patch(existing_metadata, patch_fields["metadata"])
- update_request = UpdateTeamRequest(team_id=team_id, **body)
+ update_request = UpdateTeamRequest(team_id=team_id, **patch_fields)
result = await update_team(
data=update_request,
diff --git a/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py
index d5d61341c93..5202c8cbfc0 100644
--- a/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py
+++ b/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py
@@ -9813,7 +9813,6 @@ async def _drive_team_write(
raw_body=None,
user=None,
find_returns_none=False,
- json_side_effect=None,
):
"""Drive POST ``update_team`` or PATCH ``patch_team`` against a mocked team.
@@ -9828,6 +9827,7 @@ async def _drive_team_write(
from litellm.proxy._types import (
LiteLLM_TeamTable,
LitellmUserRoles,
+ PatchTeamRequest,
UpdateTeamRequest,
UserAPIKeyAuth,
)
@@ -9873,14 +9873,10 @@ async def _drive_team_write(
litellm_changed_by=None,
)
else:
- if json_side_effect is not None:
- req.json = AsyncMock(side_effect=json_side_effect)
- else:
- req.json = AsyncMock(
- return_value=raw_body if raw_body is not None else dict(payload or {})
- )
+ body = raw_body if raw_body is not None else dict(payload or {})
result = await patch_team(
team_id=_PATCH_TEAM_ID,
+ data=PatchTeamRequest.model_validate(body),
http_request=req,
user_api_key_dict=auth,
litellm_changed_by=None,
@@ -10028,25 +10024,36 @@ async def test_patch_strips_system_managed_metadata_key_like_post():
assert patch_meta == {"cost_center": "9999"}
[email protected]("raw_body", [["not", "an", "object"], "a-string", 42, True])
-async def test_patch_rejects_non_object_body(raw_body):
- from litellm.proxy._types import ProxyException
+ "kwargs",
+ [
+ {"json": ["not", "an", "object"]},
+ {"json": "a-string"},
+ {"json": 42},
+ {"content": b"{not json"},
+ {"json": {"tpm_limit": "not-an-int"}},
+ ],
+ ids=["list", "string", "number", "malformed-json", "wrong-field-type"],
+)
+def test_patch_rejects_a_malformed_body_with_422(kwargs):
+ """The body is a declared parameter, so FastAPI rejects a malformed one before the
+ handler runs. This is the same 422 POST /team/update already returns; the route
+ previously answered 400 here and 500 for a wrongly typed field, reporting a caller
+ mistake as a server fault."""
+ from fastapi import FastAPI
+ from fastapi.testclient import TestClient
- with pytest.raises(ProxyException) as exc:
- await _drive_team_write("patch", existing_metadata={"a": 1}, raw_body=raw_body)
- assert exc.value.code == "400" or exc.value.code == 400
+ from litellm.proxy._types import PatchTeamRequest
+ app = FastAPI()
-async def test_patch_rejects_invalid_json_body():
- from litellm.proxy._types import ProxyException
+ @app.patch("/team/{team_id}")
+ async def _route(team_id: str, data: PatchTeamRequest): # pragma: no cover - schema only
+ return {}
- with pytest.raises(ProxyException) as exc:
- await _drive_team_write(
- "patch", existing_metadata={"a": 1}, json_side_effect=ValueError("no body")
- )
- assert exc.value.code == "400" or exc.value.code == 400
+ response = TestClient(app).patch("/team/abc", **kwargs)
+
+ assert response.status_code == 422
@pytest.mark.asyncio
@@ -10116,3 +10123,103 @@ async def test_patch_returns_full_team_object_not_wrapper():
)
assert isinstance(result, LiteLLM_TeamTable)
assert result.team_id == _PATCH_TEAM_ID
+
+
+# ---------------------------------------------------------------------------
+# PATCH body is validated through PatchTeamRequest before it is handed to
+# update_team. The write below must stay byte-identical to what the untyped
+# **body construction produced, or a partial update starts writing columns the
+# caller never mentioned.
+# ---------------------------------------------------------------------------
+
+
+async def test_patch_writes_only_the_keys_the_caller_sent():
+ """An omitted field must not reach the DB write at all. If validation ever
+ materialises defaults, every unmentioned column gets overwritten with null."""
+ _, update_mock = await _drive_team_write("patch", raw_body={"tpm_limit": 5})
+ written = update_mock.call_args.kwargs["data"]
+
+ assert written["tpm_limit"] == 5
+ for untouched in ("rpm_limit", "max_budget", "models", "blocked", "budget_duration"):
+ assert untouched not in written, f"{untouched} was written despite not being sent"
+
+
+async def test_patch_preserves_explicit_null_as_a_clear():
+ """null is a clear, not an omission: it has to survive validation and reach the write."""
+ _, update_mock = await _drive_team_write("patch", raw_body={"max_budget": None})
+ written = update_mock.call_args.kwargs["data"]
+
+ assert "max_budget" in written
+ assert written["max_budget"] is None
+
+
+def _patch_body_to_update_request(body: dict):
+ """The exact reshaping patch_team performs between the raw body and update_team."""
+ from litellm.proxy._types import PatchTeamRequest, UpdateTeamRequest
+
+ parsed = PatchTeamRequest.model_validate(body)
+ return UpdateTeamRequest(
+ team_id=_PATCH_TEAM_ID,
+ **parsed.model_dump(exclude_unset=True, exclude={"team_id"}),
+ )
+
+
+ "body",
+ [
+ {"tpm_limit": 5},
+ {"max_budget": None},
+ {"object_permission": {"vector_stores": []}},
+ {"metadata": {"a": 1, "b": None}},
+ {"models": ["gpt-4"], "blocked": False},
+ ],
+ ids=["scalar", "explicit-null", "partial-nested", "metadata-with-null", "list-and-false"],
+)
+def test_patch_body_reshaping_adds_no_keys_the_caller_did_not_send(body):
+ """Validating through PatchTeamRequest must be shape-preserving. If it ever
+ materialises defaults, a partial update silently overwrites untouched columns,
+ and for the merge-only object_permission it would wipe sibling sub-keys."""
+ reshaped = _patch_body_to_update_request(body)
+ dumped = reshaped.model_dump(exclude_unset=True, exclude={"team_id"})
+
+ assert dumped == body
+ assert reshaped.model_fields_set == set(body) | {"team_id"}
+
+
+async def test_patch_ignores_unknown_body_keys():
+ """Unknown keys were silently dropped by the previous construction; keep that."""
+ _, update_mock = await _drive_team_write(
+ "patch", raw_body={"tpm_limit": 5, "not_a_team_field": "x"}
+ )
+ written = update_mock.call_args.kwargs["data"]
+
+ assert written["tpm_limit"] == 5
+ assert "not_a_team_field" not in written
+
+
+def test_patch_team_request_makes_team_id_optional():
+ """PATCH takes team_id from the path, so the body model must not require it,
+ while still inheriting every UpdateTeamRequest field."""
+ from litellm.proxy._types import PatchTeamRequest, UpdateTeamRequest
+
+ parsed = PatchTeamRequest.model_validate({"tpm_limit": 5})
+
+ assert parsed.team_id is None
+ assert parsed.model_fields_set == {"tpm_limit"}
+ assert set(UpdateTeamRequest.model_fields).issubset(set(PatchTeamRequest.model_fields))
+
+
+def test_patch_team_route_publishes_its_request_body_schema():
+ """The dashboard's generated client types this call off the OpenAPI spec, which
+ FastAPI can only emit because the body is a declared parameter."""
+ from litellm.proxy.proxy_server import app
+
+ operation = app.openapi()["paths"]["/team/{team_id}"]["patch"]
+ schema = operation["requestBody"]["content"]["application/json"]["schema"]
+
+ assert schema == {"$ref": "#/components/schemas/PatchTeamRequest"}
+ properties = app.openapi()["components"]["schemas"]["PatchTeamRequest"]["properties"]
+ assert "tpm_limit" in properties and "metadata" in properties
diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.ts
index d109fc1783d..e612bddaca1 100644
--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts
+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts
@@ -13860,11 +13860,12 @@ export interface paths {
* Patch Team
* @description Partially update a team using RFC 7386 JSON Merge Patch semantics.
*
- * `team_id` is taken from the path. `metadata` is merged with the team's stored
- * metadata rather than replacing it: an omitted key is preserved, `key: null`
- * deletes it, and any other value overwrites (recursing into nested objects).
- * Every other field behaves exactly like `POST /team/update` (omitted preserves,
- * a value overwrites). Returns the full updated team.
+ * `team_id` is taken from the path; a `team_id` in the body is accepted only when it
+ * matches. `metadata` is merged with the team's stored metadata rather than replacing
+ * it: an omitted key is preserved, `key: null` deletes it, and any other value
+ * overwrites (recursing into nested objects). Every other field behaves exactly like
+ * `POST /team/update` (omitted preserves, a value overwrites). Returns the full
+ * updated team.
*
* ```
* curl --location --request PATCH 'http://0.0.0.0:4000/team/8d916b1c-510d-4894-a334-1c16a93344f5' --header 'Authorization: Bearer sk-1234' --header 'Content-Type: application/json' --data-raw '{
@@ -28807,6 +28808,102 @@ export interface components {
litellm_params?: components["schemas"]["PromptLiteLLMParams"] | null;
prompt_info?: components["schemas"]["PromptInfo"] | null;
};
+ /**
+ * PatchTeamRequest
+ * @description Body of PATCH /team/{team_id}.
+ *
+ * Identical to UpdateTeamRequest except team_id is optional, because PATCH takes it
+ * from the path. A team_id in the body is still accepted when it matches the path.
+ */
+ PatchTeamRequest: {
+ /** Access Group Ids */
+ access_group_ids?: string[] | null;
+ /** Allowed Passthrough Routes */
+ allowed_passthrough_routes?: unknown[] | null;
+ /** Allowed Vector Store Indexes */
+ allowed_vector_store_indexes?: components["schemas"]["AllowedVectorStoreIndexItem"][] | null;
+ /** Blocked */
+ blocked?: boolean | null;
+ /** Budget Duration */
+ budget_duration?: string | null;
+ /** Budget Limits */
+ budget_limits?: components["schemas"]["BudgetLimitEntry"][] | null;
+ /** Default Team Member Models */
+ default_team_member_models?: string[] | null;
+ /** Disable Global Guardrails */
+ disable_global_guardrails?: boolean | null;
+ /** Enforced Batch Output Expires After */
+ enforced_batch_output_expires_after?: {
+ [key: string]: unknown;
+ } | null;
+ /** Enforced File Expires After */
+ enforced_file_expires_after?: {
+ [key: string]: unknown;
+ } | null;
+ /** Guardrails */
+ guardrails?: string[] | null;
+ /** Max Budget */
+ max_budget?: number | null;
+ /** Mcp Rpm Limit */
+ mcp_rpm_limit?: {
+ [key: string]: number;
+ } | null;
+ /** Metadata */
+ metadata?: {
+ [key: string]: unknown;
+ } | null;
+ /** Model Aliases */
+ model_aliases?: {
+ [key: string]: unknown;
+ } | null;
+ /** Model Rpm Limit */
+ model_rpm_limit?: {
+ [key: string]: number;
+ } | null;
+ /** Model Tpm Limit */
+ model_tpm_limit?: {
+ [key: string]: number;
+ } | null;
+ /** Models */
+ models?: unknown[] | null;
+ object_permission?: components["schemas"]["LiteLLM_ObjectPermissionBase"] | null;
+ /** Organization Id */
+ organization_id?: string | null;
+ /** Policies */
+ policies?: string[] | null;
+ /** Prompts */
+ prompts?: string[] | null;
+ /** Router Settings */
+ router_settings?: {
+ [key: string]: unknown;
+ } | null;
+ /** Rpm Limit */
+ rpm_limit?: number | null;
+ /** Secret Manager Settings */
+ secret_manager_settings?: {
+ [key: string]: unknown;
+ } | null;
+ /** Soft Budget */
+ soft_budget?: number | null;
+ /** Tags */
+ tags?: unknown[] | null;
+ /** Team Alias */
+ team_alias?: string | null;
+ /** Team Id */
+ team_id?: string | null;
+ /** Team Member Budget */
+ team_member_budget?: number | null;
+ /** Team Member Budget Duration */
+ team_member_budget_duration?: string | null;
+ /** Team Member Key Duration */
+ team_member_key_duration?: string | null;
+ /** Team Member Rpm Limit */
+ team_member_rpm_limit?: number | null;
+ /** Team Member Tpm Limit */
+ team_member_tpm_limit?: number | null;
+ /** Tpm Limit */
+ tpm_limit?: number | null;
+ };
/**
* PerTestingCriteriaResult
* @description Results for a specific testing criteria
@@ -50613,7 +50710,11 @@ export interface operations {
};
cookie?: never;
};
- requestBody?: never;
+ requestBody: {
+ content: {
+ "application/json": components["schemas"]["PatchTeamRequest"];
+ };
+ };
responses: {
/** @description Successful Response */
200: {