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
Merge remote-tracking branch 'origin/litellm_internal_staging' into litellm_decrease_anys_opus5_round2
mateo-berri4582496c8a57
diff --cc basedpyright-code-budget.jsonindex 7e57539d1dd,19c28716025..e3bac754074--- a/basedpyright-code-budget.json+++ b/basedpyright-code-budget.json@@@ -1,9 -1,9 +1,9 @@@{"reportAny": {- "limit": 18501- "limit": 19949++ "limit": 18505},"reportArgumentType": {- "limit": 2566+ "limit": 2564},"reportAssignmentType": {"limit": 320@@@ -54,10 -54,10 +54,10 @@@"limit": 0},"reportMissingParameterType": {-- "limit": 5661++ "limit": 5659},"reportMissingTypeArgument": {- "limit": 15555+ "limit": 15504},"reportMissingTypeStubs": {"limit": 40@@@ -99,19 -99,19 +99,19 @@@"limit": 0},"reportUnknownArgumentType": {- "limit": 44527- "limit": 44655++ "limit": 44530},"reportUnknownLambdaType": {"limit": 109},"reportUnknownMemberType": {- "limit": 38827- "limit": 39009++ "limit": 38828},"reportUnknownParameterType": {- "limit": 19848- "limit": 19883++ "limit": 19847},"reportUnknownVariableType": {- "limit": 30384- "limit": 30569++ "limit": 30386},"reportUnnecessaryCast": {"limit": 117diff --cc litellm/proxy/auth/user_api_key_auth.pyindex 035265d55f4,28d76e6799c..d86132e51f0--- a/litellm/proxy/auth/user_api_key_auth.py+++ b/litellm/proxy/auth/user_api_key_auth.py@@@ -1988,25 -1984,21 +1993,21 @@@ async def _user_api_key_auth_builder)if team_member_info is None:# read from DB- _user_id: Final = valid_token.user_id- _team_id: Final = valid_token.team_id-- if _user_id is not None and _team_id is not None:- _db_member: Final = await TeamMembershipRepository(prisma_client).table.find_first(- where={- "user_id": _user_id,- "team_id": _team_id,- },- include={"litellm_budget_table": True},+ _db_member: Final = await TeamMembershipRepository(prisma_client).table.find_first(+ where={+ "user_id": _user_id,+ "team_id": _team_id,+ },+ include={"litellm_budget_table": True},+ )+ if _db_member is not None:- team_member_info = LiteLLM_TeamMembership(**_db_member.dict())++ team_member_info = LiteLLM_TeamMembership(**_db_member.model_dump())+ await user_api_key_cache.async_set_cache(+ key=_cache_key,+ value=team_member_info,+ model_type=LiteLLM_TeamMembership,+ ttl=5,)- if _db_member is not None:- team_member_info = LiteLLM_TeamMembership(**_db_member.model_dump())- await user_api_key_cache.async_set_cache(- key=_cache_key,- value=team_member_info,- model_type=LiteLLM_TeamMembership,- ttl=5,- )if team_member_info is not None and team_member_info.litellm_budget_table is not None:team_member_budget: Final = team_member_info.litellm_budget_table.max_budgetdiff --cc litellm/proxy/management_endpoints/team_endpoints.pyindex c8373fe6c30,ba4fb81323f..f2327b18914--- a/litellm/proxy/management_endpoints/team_endpoints.py+++ b/litellm/proxy/management_endpoints/team_endpoints.py@@@ -16,16 -16,7 +16,7 @@@ import tracebacfrom collections.abc import Mapping, Sequencefrom datetime import datetime, timezonefrom types import MappingProxyType- from typing import (- TYPE_CHECKING,- Annotated,- Final,- NamedTuple,- Protocol,- TypedDict,- TypeVar,- cast,- )-from typing import Annotated, Final, NamedTuple, NoReturn, Protocol, TypeVar, cast++from typing import TYPE_CHECKING, Annotated, Final, NamedTuple, NoReturn, Protocol, TypeVar, castimport fastapifrom fastapi import APIRouter, Depends, Header, HTTPException, Request, status@@@ -299,11 -333,44 +295,44 @@@ class _TeamIdInFilter(TypedDict, total=team_id: Mapping[str, Sequence[str]]+ class _DeletedTeamsResult(TypedDict):+ deleted_teams: ReadOnly[Sequence[str]]+++ class _ErrorDetail(TypedDict):+ error: ReadOnly[str]++class _TeamCreateTx(AccessGroupSyncTx, Protocol):@property- def litellm_teamtable(self) -> "_PrismaTableActions[LiteLLM_TeamTable]": ...+ def litellm_teamtable(self) -> "TableActions[prisma_models.LiteLLM_TeamTable]": ...+ class _MemberDeleteTx(Protocol):+ """The tables `/team/member_delete` reads while it holds the team's advisory lock.++ Reading them off the transaction keeps the whole endpoint on the one pooled connection+ it already checked out: a request that has the lock but still needs another connection+ can be starved by the lock waiters, which is a deadlock rather than a wait when enough+ of them hold the rest of the pool."""++ @property- def litellm_usertable(self) -> "_PrismaTableActions[LiteLLM_UserTable]": ...++ def litellm_usertable(self) -> "TableActions[prisma_models.LiteLLM_UserTable]": ...++ @property- def litellm_verificationtoken(self) -> "_PrismaTableActions[LiteLLM_VerificationToken]": ...++ def litellm_verificationtoken(self) -> "TableActions[prisma_models.LiteLLM_VerificationToken]": ...+++ class _TeamDeleteTx(AccessGroupSyncTx, Protocol):+ async def execute_raw(self, query: str, *args: object) -> int: ...++ @property- def litellm_teamtable(self) -> "_PrismaTableActions[LiteLLM_TeamTable]": ...++ def litellm_teamtable(self) -> "TableActions[prisma_models.LiteLLM_TeamTable]": ...++ @property- def litellm_teammembership(self) -> "_PrismaTableActions[LiteLLM_TeamMembership]": ...++ def litellm_teammembership(self) -> "TableActions[prisma_models.LiteLLM_TeamMembership]": ...++_STRIP_DELETED_TEAM_FROM_USERS_SQL: Final = """UPDATE "LiteLLM_UserTable" SET teams = array_remove(teams, $1) WHERE $1 = ANY(teams)"""@@@ -2682,66 -2750,41 +2718,39 @@@ async def _add_team_members_to_teamprisma_client: PrismaClient,user_api_key_dict: UserAPIKeyAuth,litellm_proxy_admin_name: str,-) -> tuple[LiteLLM_TeamTable, list[LiteLLM_UserTable], list[LiteLLM_TeamMembership]]:+) -> tuple["prisma_models.LiteLLM_TeamTable", list[LiteLLM_UserTable], list[LiteLLM_TeamMembership]]:- """Add team members to the team.-- The members_with_roles reconciliation runs inside a transaction that locks- the team row with ``SELECT ... FOR UPDATE`` before reading the current- membership. Concurrent /team/member_add calls for the same team therefore- serialize on the row lock and each appends onto the other's committed- result, instead of both rewriting the whole JSON array from a stale- snapshot (which silently drops one member on the losing write).-- The same lock serializes this against /team/delete: the delete cannot remove- the row while the reconcile holds it, and a reconcile that finds the row- already gone cleans up after itself rather than leaving the member pointing- at a deleted team id.- """- # Process and add new members- updated_users, updated_team_memberships = await _process_team_members(- data=data,- complete_team_data=complete_team_data,- prisma_client=prisma_client,- user_api_key_dict=user_api_key_dict,- litellm_proxy_admin_name=litellm_proxy_admin_name,- )-- updated_team: Final = await _write_members_with_roles_locked(- data=data,- complete_team_data=complete_team_data,- prisma_client=prisma_client,- updated_users=updated_users,- )- if updated_team is None:- await _sweep_deleted_team_references(team_ids=(data.team_id,), prisma_client=prisma_client)- raise HTTPException(- status_code=404,- detail={"error": f"Team={data.team_id} was deleted while this member add was running"},- )-- return updated_team, updated_users, updated_team_memberships--- async def _write_members_with_roles_locked(- data: TeamMemberAddRequest,- complete_team_data: LiteLLM_TeamTable,- prisma_client: PrismaClient,- updated_users: list[LiteLLM_UserTable],- ) -> "prisma_models.LiteLLM_TeamTable | None":- """Reconcile members_with_roles under the team row lock. None when the team row is gone.-- That read is at least as recent as the user and membership writes the caller- already made, so a missing row means /team/delete committed after them. Its- post-delete sweep can have run before those writes landed, which is why the- caller sweeps this team id again rather than only reporting the 404.+ """Add team members to the team, under the team's advisory lock.++ The lock (``TEAM_ADVISORY_LOCK_SQL``, keyed on the team id) is taken first, and the+ team is re-read under it before any write, so a delete that already committed is+ visible here before this call writes anything: the user and membership writes only+ happen once the re-read proves the team is still live. /team/delete takes the same+ lock around its own sweep-and-delete, so the two can never interleave; whichever+ acquires the lock first runs to completion before the other's re-read can proceed.++ The user and membership writes run on this transaction too, not on a second+ connection from the pool: a lock waiter that needs a connection it hasn't got yet is+ a waiter that can deadlock the pool, since enough concurrent adds for one team would+ hold every connection waiting on the lock while the holder waits for a free one."""++ gone_detail: Final[_ErrorDetail] = {"error": f"Team={data.team_id} was deleted while this member add was running"}async with prisma_client.tx() as tx:+ await tx.query_raw(TEAM_ADVISORY_LOCK_SQL, data.team_id)+locked_members: Final = await TeamRepository(prisma_client).get_members_with_roles_locked(tx, data.team_id)if locked_members is None:- return None-- gone_detail: Final[_ErrorDetail] = {- "error": f"Team={data.team_id} was deleted while this member add was running"- }+ raise HTTPException(status_code=404, detail=gone_detail)complete_team_data.members_with_roles = locked_members+ updated_users, updated_team_memberships = await _process_team_members(+ data=data,+ complete_team_data=complete_team_data,+ prisma_client=prisma_client,+ user_api_key_dict=user_api_key_dict,+ litellm_proxy_admin_name=litellm_proxy_admin_name,+ tx=tx,+ )+await _update_team_members_list(data=data,complete_team_data=complete_team_data,@@@ -2749,10 -2792,12 +2758,14 @@@)_db_team_members: Final = [m.model_dump() for m in complete_team_data.members_with_roles]- return await _team_tx_db(tx).update(- updated_team: Final = await tx.litellm_teamtable.update(++ updated_team: Final = await _team_tx_db(tx).update(where={"team_id": data.team_id},data={"members_with_roles": json.dumps(_db_team_members)},)++ if updated_team is None:++ raise HTTPException(status_code=404, detail=gone_detail)++ return updated_team, updated_users, updated_team_membershipsdef _emit_team_members_metric(team: LiteLLM_TeamTable) -> None:@@@ -3251,48 -3292,64 +3260,62 @@@ async def team_member_delete)## DELETE MEMBER FROM TEAM- removed_team_members, new_team_members = _cleanup_members_with_roles(- existing_team_row=existing_team_row,- data=data,- )+ # Everything from here on runs under the team's advisory lock, the same one+ # /team/member_add and /team/delete take: without it, this endpoint's own row-level+ # update lock used to be the only thing serializing it against a concurrent member_add,+ # and only by accident (their SELECT ... FOR UPDATE contended for the same row lock this+ # UPDATE takes). Now that member_add reads under the advisory lock instead, this has to+ # take it too, and re-read the roster under it rather than off the snapshot validated+ # above, or a member_add that commits in between can have its addition silently+ # overwritten by this delete computing from stale data.+ async with prisma_client.tx() as tx:+ await tx.query_raw(TEAM_ADVISORY_LOCK_SQL, data.team_id)- if not removed_team_members:- raise HTTPException(status_code=400, detail={"error": "User not found in team"})+ fresh_members: Final = await TeamRepository(prisma_client).get_members_with_roles_locked(tx, data.team_id)+ if fresh_members is None:+ raise HTTPException(+ status_code=400,+ detail={"error": f"Team id={data.team_id} does not exist in db"},+ )- existing_team_row.members_with_roles = new_team_members+ removed_team_members, new_team_members = _cleanup_members_with_roles(+ existing_team_row=LiteLLM_TeamTable(team_id=data.team_id, members_with_roles=fresh_members),+ data=data,+ )- _db_new_team_members: Final[list[dict]] = [m.model_dump() for m in new_team_members]+ if not removed_team_members:+ raise HTTPException(status_code=400, detail={"error": "User not found in team"})- ## DELETE TEAM ID from USER ROW, IF EXISTS ##- # get user row- removed_user_ids: Final = frozenset(m.user_id for m in removed_team_members if m.user_id is not None)- key_val: Final[Mapping[str, object]] = (- {"user_id": {"in": sorted(removed_user_ids)}} if removed_user_ids else {"user_email": data.user_email}- )- existing_user_rows: Final[Sequence[prisma_models.LiteLLM_UserTable]] = await _user_db(prisma_client).find_many(- where=key_val- )+ existing_team_row.members_with_roles = new_team_members- # Also clean up any existing team membership rows for this user and team- user_ids_to_delete: Final = removed_user_ids.union(- (data.user_id,) if data.user_id is not None else (),- (user.user_id for user in existing_user_rows if user.user_id),- )+ _db_new_team_members: Final[list[dict]] = [m.model_dump() for m in new_team_members]- ## DELETE KEYS CREATED BY USER FOR THIS TEAM- # Fetch keys before deletion so their audit records can be persisted alongside the delete.- # An empty user_ids_to_delete still resolves cleanly: prisma's "in": [] matches no rows.- keys_to_delete: Final = await _tokens_db(prisma_client).find_many(- where={- "user_id": {"in": sorted(user_ids_to_delete)},- "team_id": data.team_id,- }- )+ ## DELETE TEAM ID from USER ROW, IF EXISTS ##+ # get user row+ removed_user_ids: Final = frozenset(m.user_id for m in removed_team_members if m.user_id is not None)+ key_val: Final[Mapping[str, object]] = (+ {"user_id": {"in": sorted(removed_user_ids)}} if removed_user_ids else {"user_email": data.user_email}+ )+ member_tx: Final[_MemberDeleteTx] = tx- existing_user_rows: Final[Sequence[LiteLLM_UserTable]] = await member_tx.litellm_usertable.find_many(- where=key_val- )++ existing_user_rows: Final = await member_tx.litellm_usertable.find_many(where=key_val)++ # Also clean up any existing team membership rows for this user and team+ user_ids_to_delete: Final = removed_user_ids.union(+ (data.user_id,) if data.user_id is not None else (),+ (user.user_id for user in existing_user_rows if user.user_id),+ )++ ## DELETE KEYS CREATED BY USER FOR THIS TEAM+ # Fetch keys before deletion so their audit records can be persisted alongside the delete.+ # An empty user_ids_to_delete still resolves cleanly: prisma's "in": [] matches no rows.- keys_to_delete: Final[list[LiteLLM_VerificationToken]] = await member_tx.litellm_verificationtoken.find_many(++ keys_to_delete: Final = await member_tx.litellm_verificationtoken.find_many(+ where={+ "user_id": {"in": sorted(user_ids_to_delete)},+ "team_id": data.team_id,+ }+ )- # All four cleanups run on one connection so a failure between them leaves- # no partial removal: either every write below lands, or none of them do.- async with prisma_client.tx() as tx:- await tx.litellm_teamtable.update(+ await _team_tx_db(tx).update(where={"team_id": data.team_id},data={"members_with_roles": json.dumps(_db_new_team_members)},)@@@ -3906,8 -4098,18 +4062,18 @@@ async def _sweep_deleted_team_reference_ = await _team_membership_db(prisma_client).delete_many(where=_TeamIdInFilter(team_id={"in": tuple(team_ids)}))+ async def _sweep_deleted_team_references_tx(team_ids: Sequence[str], tx: _TeamDeleteTx) -> None:+ """Same sweep as `_sweep_deleted_team_references`, run on the transaction that holds+ every id's advisory lock and deletes the team rows, so it commits or rolls back with them."""+ for team_id in team_ids:+ _ = await tx.execute_raw(_STRIP_DELETED_TEAM_FROM_USERS_SQL, team_id)++ membership_filter: Final[_TeamIdInFilter] = {"team_id": {"in": tuple(team_ids)}}+ _ = await tx.litellm_teammembership.delete_many(where=membership_filter)++async def _invalidate_deleted_key_cache(- keys: Sequence[LiteLLM_VerificationToken],+ keys: "Sequence[prisma_models.LiteLLM_VerificationToken]",user_api_key_cache: UserApiKeyCache,proxy_logging_obj: ProxyLogging,) -> None:diff --cc ruff-strict-budget.jsonindex d5cddbb2a20,bbfbbbc1cfb..97484851715--- a/ruff-strict-budget.json+++ b/ruff-strict-budget.json@@@ -1,6 -1,6 +1,6 @@@{"ANN001": {-- "limit": 3016++ "limit": 3014},"ANN002": {"limit": 71@@@ -9,7 -9,7 +9,7 @@@"limit": 827},"ANN201": {- "limit": 2013- "limit": 2015++ "limit": 2012},"ANN202": {"limit": 852diff --cc tests/test_litellm/proxy/management_endpoints/test_team_endpoints.pyindex fbe856f4adf,f33854eeb81..6461245bb2c--- a/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py+++ b/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py@@@ -3,8 -3,8 +3,8 @@@ import jsofrom contextlib import asynccontextmanagerfrom datetime import datetime, timezonefrom types import SimpleNamespace-from typing import Optional, cast+from typing import Final, Optional, cast- from unittest.mock import AsyncMock, MagicMock, call, patch+ from unittest.mock import AsyncMock, MagicMock, PropertyMock, call, patchimport pytestfrom fastapi import HTTPExceptiondiff --cc tests/test_litellm/proxy/ui_crud_endpoints/test_proxy_setting_endpoints.pyindex b85c70cae12,b85c70cae12..dc256ccf718--- a/tests/test_litellm/proxy/ui_crud_endpoints/test_proxy_setting_endpoints.py+++ b/tests/test_litellm/proxy/ui_crud_endpoints/test_proxy_setting_endpoints.py@@@ -2770,7 -2770,7 +2770,7 @@@ def mock_team_lookup(monkeypatch)existing_team_ids: set = set()-- async def _find_many(where):++ async def _find_many(where, **_):requested = where["team_id"]["in"]return [{"team_id": team_id} for team_id in requested if team_id in existing_team_ids]diff --cc tests/test_litellm/proxy/utils/prisma_and_spend/test_prisma_client_get_data.pyindex ed1317e647d,ed1317e647d..ce6ecc2ea65--- a/tests/test_litellm/proxy/utils/prisma_and_spend/test_prisma_client_get_data.py+++ b/tests/test_litellm/proxy/utils/prisma_and_spend/test_prisma_client_get_data.py@@@ -84,7 -84,7 +84,7 @@@ def test_jsonify_object_fallback_for_undef test_jsonify_object_error_on_non_dict(prisma_client: PrismaClient) -> None:-- with pytest.raises(AttributeError):++ with pytest.raises(TypeError):prisma_client.jsonify_object(None) # type: ignore[arg-type]@@@ -134,7 -134,7 +134,7 @@@ def test_jsonify_team_object_converts_bdef test_jsonify_team_object_error_on_non_dict(prisma_client: PrismaClient) -> None:-- with pytest.raises(AttributeError):++ with pytest.raises(TypeError):prisma_client.jsonify_team_object(None) # type: ignore[arg-type]diff --cc type-discipline-budget.jsonindex 72fdfbef8c5,7165bb53812..31f3b29286a--- a/type-discipline-budget.json+++ b/type-discipline-budget.json@@@ -1,9 -1,9 +1,9 @@@{"LIT001": {- "limit": 22804+ "limit": 22749},"LIT002": {- "limit": 26867- "limit": 26872++ "limit": 26866},"LIT003": {"limit": 269@@@ -27,10 -27,10 +27,10 @@@"limit": 0},"LIT010": {- "limit": 16673+ "limit": 16655},"LIT011": {- "limit": 5586- "limit": 5587++ "limit": 5585},"LIT012": {"limit": 4510