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]

merge(litellm_internal_staging): resolve typing sweep overlap, keep best-of-both types

mateo-berri683330e4e81d
diff --cc basedpyright-code-budget.json
index ed8fa7fc50e,962d1266fd7..d08a85f6795
--- a/basedpyright-code-budget.json
+++ b/basedpyright-code-budget.json
@@@ -1,30 -1,30 +1,30 @@@
{
"reportAny": {
- "limit": 21004
- "limit": 17271
++ "limit": 16413
},
"reportArgumentType": {
- "limit": 2568
- "limit": 2539
++ "limit": 2530
},
"reportAssignmentType": {
- "limit": 323
+ "limit": 319
},
"reportAttributeAccessIssue": {
- "limit": 488
+ "limit": 480
},
"reportCallIssue": {
- "limit": 114
+ "limit": 112
},
"reportConstantRedefinition": {
"limit": 40
},
"reportDeprecated": {
- "limit": 213
- "limit": 212
++ "limit": 209
},
"reportDuplicateImport": {
"limit": 19
},
"reportExplicitAny": {
- "limit": 6805
- "limit": 5486
++ "limit": 5357
},
"reportFunctionMemberAccess": {
"limit": 7
@@@ -54,10 -54,10 +54,10 @@@
"limit": 0
},
"reportMissingParameterType": {
- "limit": 5686
- "limit": 5658
++ "limit": 5649
},
"reportMissingTypeArgument": {
- "limit": 15600
- "limit": 15425
++ "limit": 15407
},
"reportMissingTypeStubs": {
"limit": 40
@@@ -93,37 -93,37 +93,37 @@@
"limit": 213
},
"reportTypedDictNotRequiredAccess": {
- "limit": 24
- "limit": 25
++ "limit": 22
},
"reportUndefinedVariable": {
"limit": 0
},
"reportUnknownArgumentType": {
- "limit": 44392
- "limit": 44526
++ "limit": 44463
},
"reportUnknownLambdaType": {
- "limit": 110
+ "limit": 109
},
"reportUnknownMemberType": {
- "limit": 39100
- "limit": 38721
++ "limit": 38625
},
"reportUnknownParameterType": {
- "limit": 19925
- "limit": 19778
++ "limit": 19754
},
"reportUnknownVariableType": {
- "limit": 30737
- "limit": 30290
++ "limit": 30212
},
"reportUnnecessaryCast": {
- "limit": 118
+ "limit": 117
},
"reportUnnecessaryComparison": {
- "limit": 699
+ "limit": 697
},
"reportUnnecessaryContains": {
"limit": 5
},
"reportUnnecessaryIsInstance": {
- "limit": 850
- "limit": 829
++ "limit": 826
},
"reportUntypedBaseClass": {
"limit": 0
diff --cc litellm/integrations/websearch_interception/handler.py
index 182393dd343,13a16947fb4..cc2656219cc
--- a/litellm/integrations/websearch_interception/handler.py
+++ b/litellm/integrations/websearch_interception/handler.py
@@@ -10,7 -10,7 +10,7 @@@ import asynci
import math
import uuid
from collections.abc import AsyncIterator, Mapping, Sequence
- from typing import TYPE_CHECKING, Any, Final, Literal, Never, TypedDict, TypeVar, cast
-from typing import TYPE_CHECKING, Any, Final, TypedDict, cast
++from typing import TYPE_CHECKING, Any, Final, Literal, Never, TypedDict, cast
from typing_extensions import ReadOnly
@@@ -116,77 -103,10 +117,79 @@@ class _DeploymentCallKwargsView(TypedDi
model: ReadOnly[str]
-class _UserAuthView(TypedDict):
- """Typed read of the optional team attached to the caller's auth object."""
-
- team_id: ReadOnly[str | None]
+class _AcreateNamedParams(TypedDict, total=False):
+ metadata: ReadOnly[Never]
+ stop_sequences: ReadOnly[Never]
+ stream: ReadOnly[bool | None]
+ system: ReadOnly[str | None]
+ temperature: ReadOnly[float | None]
+ thinking: ReadOnly[Never]
+ tool_choice: ReadOnly[Never]
+ tools: ReadOnly[Never]
+ top_k: ReadOnly[int | None]
+ top_p: ReadOnly[float | None]
+ container: ReadOnly[Never]
+
+
+class _AsearchNamedParams(TypedDict, total=False):
+ max_results: ReadOnly[int | None]
+ search_domain_filter: ReadOnly[Never]
+ max_tokens_per_page: ReadOnly[int | None]
+ country: ReadOnly[str | None]
+ api_key: ReadOnly[str | None]
+ api_base: ReadOnly[str | None]
+ timeout: ReadOnly[float | None]
+ extra_headers: ReadOnly[Never]
+
+
+class _AcompletionNamedParams(TypedDict, total=False):
+ functions: ReadOnly[Never]
+ function_call: ReadOnly[str | None]
+ timeout: ReadOnly[float | None]
+ temperature: ReadOnly[float | None]
+ top_p: ReadOnly[float | None]
+ n: ReadOnly[int | None]
+ stream: ReadOnly[bool | None]
+ stream_options: ReadOnly[Never]
+ stop: ReadOnly[Never]
+ max_tokens: ReadOnly[int | None]
+ max_completion_tokens: ReadOnly[int | None]
+ modalities: ReadOnly[Never]
+ prediction: ReadOnly[ChatCompletionPredictionContentParam | None]
+ audio: ReadOnly[ChatCompletionAudioParam | None]
+ presence_penalty: ReadOnly[float | None]
+ frequency_penalty: ReadOnly[float | None]
+ logit_bias: ReadOnly[Never]
+ user: ReadOnly[str | None]
+ response_format: ReadOnly[Never]
+ seed: ReadOnly[int | None]
+ tools: ReadOnly[Never]
+ tool_choice: ReadOnly[Never]
+ parallel_tool_calls: ReadOnly[bool | None]
+ logprobs: ReadOnly[bool | None]
+ top_logprobs: ReadOnly[int | None]
+ deployment_id: ReadOnly[str | None]
+ reasoning_effort: ReadOnly[Literal["none", "minimal", "low", "medium", "high", "xhigh", "default"] | None]
+ verbosity: ReadOnly[Literal["low", "medium", "high"] | None]
+ safety_identifier: ReadOnly[str | None]
+ service_tier: ReadOnly[str | None]
++ store: ReadOnly[bool | None]
++ prompt_cache_key: ReadOnly[str | None]
+ base_url: ReadOnly[str | None]
+ api_version: ReadOnly[str | None]
+ api_key: ReadOnly[str | None]
+ model_list: ReadOnly[Never]
+ extra_headers: ReadOnly[Never]
+ thinking: ReadOnly[AnthropicThinkingParam | None]
+ web_search_options: ReadOnly[OpenAIWebSearchOptions | None]
+ include_server_side_tool_invocations: ReadOnly[bool | None]
+ shared_session: ReadOnly["ClientSession | None"]
+ enable_json_schema_validation: ReadOnly[bool | None]
+
+
+_NO_ACREATE_NAMED: Final[_AcreateNamedParams] = {}
+_NO_ASEARCH_NAMED: Final[_AsearchNamedParams] = {}
+_NO_ACOMPLETION_NAMED: Final[_AcompletionNamedParams] = {}
class WebSearchInterceptionLogger(CustomLogger):
diff --cc litellm/llms/anthropic/experimental_pass_through/context_management/editors/compact.py
index e4bb56c1a53,c8cbbba8784..1cf52045a48
--- a/litellm/llms/anthropic/experimental_pass_through/context_management/editors/compact.py
+++ b/litellm/llms/anthropic/experimental_pass_through/context_management/editors/compact.py
@@@ -84,74 -84,6 +85,77 @@@ _PROPAGATED_METADATA_KEYS: Final =
_SUMMARY_TAG_RE: Final = re.compile(r"<summary>(.*?)</summary>", re.IGNORECASE | re.DOTALL)
+_MsgT: Final = TypeVar("_MsgT", bound=Mapping[str, object])
+
+
+def _as_object(value: object) -> object:
+ return value
+
+
+def _is_tool_result_block(block: object) -> bool:
+ return isinstance(block, dict) and block.get("type") in ("tool_result",)
+
+
+class _SummaryCallKwargs(TypedDict):
+ model: ReadOnly[str]
+ max_tokens: ReadOnly[int]
+ timeout: ReadOnly[float]
+ litellm_metadata: ReadOnly[Mapping[str, object]]
+ user: ReadOnly[NotRequired[str]]
+ allowed_model_region: ReadOnly[NotRequired[str]]
+
+
+class _SummaryOptionalKwargs(TypedDict, total=False):
+ user: ReadOnly[str]
+ allowed_model_region: ReadOnly[str]
+
+
+class _SummaryAcompletion(Protocol):
+ def __call__(
- self, *, messages: Sequence[Mapping[str, object]], **kwargs: Unpack[_SummaryCallKwargs]
++ self,
++ *,
++ messages: Sequence[Mapping[str, object]],
++ **kwargs: Unpack[_SummaryCallKwargs], # kwargs-ok: forwarded verbatim to acompletion, which owns them
+ ) -> "Awaitable[ModelResponse | CustomStreamWrapper]": ...
+
+
+class _CreateRateLimitDescriptors(Protocol):
+ def __call__(
+ self,
+ *,
+ user_api_key_dict: "UserAPIKeyAuth",
+ data: Mapping[str, str],
+ rpm_limit_type: object,
+ tpm_limit_type: object,
+ model_has_failures: bool,
+ ) -> "Sequence[RateLimitDescriptor]": ...
+
+
+class _AddModelRateLimitDescriptor(Protocol):
+ def __call__(
+ self,
+ *,
+ user_api_key_dict: "UserAPIKeyAuth",
+ requested_model: str,
+ descriptors: "Sequence[RateLimitDescriptor]",
+ ) -> None: ...
+
+
+class _CreateOrgRateLimitDescriptors(Protocol):
+ def __call__(
+ self, user_api_key_dict: "UserAPIKeyAuth", requested_model: str | None = None
+ ) -> "Sequence[RateLimitDescriptor]": ...
+
+
+class _ShouldRateLimit(Protocol):
+ def __call__(
+ self,
+ *,
+ descriptors: "Sequence[RateLimitDescriptor]",
+ parent_otel_span: object,
+ read_only: bool,
+ ) -> "Awaitable[RateLimitResponse]": ...
+
def _read_summary_model_setting() -> str | None:
"""Look up the configured summarization model from proxy general_settings."""
@@@ -416,8 -352,27 +424,27 @@@ async def _check_summary_model_budget
)
return False
+ user_model_max_budget: Final = user_api_key_auth.user_model_max_budget
+ user_id: Final = user_api_key_auth.user_id
+ if isinstance(user_model_max_budget, dict) and user_model_max_budget and user_id is not None:
+ try:
+ await model_max_budget_limiter.is_user_within_model_budget(
+ user_id=user_id,
+ user_model_max_budget=user_model_max_budget,
+ model=summary_model,
+ )
+ except litellm.BudgetExceededError:
+ return False
+ except Exception as e: # noqa: BLE001 # a budget gate denies on any failure, as the key and end-user scopes do
+ verbose_logger.warning(
+ "compact_20260112: unexpected error during user model-budget check for summary_model=%s; denying: %s",
+ summary_model,
+ e,
+ )
+ return False
+
end_user_model_max_budget: Final = getattr(user_api_key_auth, "end_user_model_max_budget", None)
- end_user_id: Final = getattr(user_api_key_auth, "end_user_id", None)
+ end_user_id: Final[str | None] = getattr(user_api_key_auth, "end_user_id", None)
if isinstance(end_user_model_max_budget, dict) and end_user_model_max_budget and end_user_id is not None:
try:
await model_max_budget_limiter.is_end_user_within_model_budget(
diff --cc litellm/proxy/db/tool_registry_writer.py
index e6fcff548d6,367552e783e..cd0aa75b859
--- a/litellm/proxy/db/tool_registry_writer.py
+++ b/litellm/proxy/db/tool_registry_writer.py
@@@ -23,86 -22,28 +24,35 @@@ from litellm.types.tool_management impo
)
if TYPE_CHECKING:
- from litellm.proxy.utils import PrismaClient
-
-
- class _ToolTableRecord(Protocol):
- tool_name: str
- input_policy: str | None
- output_policy: str | None
-
-
- class _TokenRelationRecord(Protocol):
- token: str | None
- key_alias: str | None
-
-
- class _TeamRelationRecord(Protocol):
- team_id: str | None
- team_alias: str | None
-
-
- class _ObjectPermissionRecord(Protocol):
- object_permission_id: str
- blocked_tools: Sequence[str] | None
- verification_tokens: Sequence[_TokenRelationRecord] | None
- teams: Sequence[_TeamRelationRecord] | None
-
-
- class _ToolTable(Protocol):
- async def find_many(
- self,
- *,
- where: Mapping[str, object] | None = None,
- order: Mapping[str, str] | None = None,
- ) -> Sequence[_ToolTableRecord]: ...
+ from prisma import models as prisma_db_models
- async def find_unique(self, *, where: Mapping[str, object]) -> _ToolTableRecord | None: ...
-
- async def upsert(self, *, where: Mapping[str, object], data: Mapping[str, object]) -> object: ...
-
-
- class _ObjectPermissionTable(Protocol):
- async def find_many(
- self,
- *,
- where: Mapping[str, object] | None = None,
- include: Mapping[str, bool] | None = None,
- ) -> Sequence[_ObjectPermissionRecord]: ...
-
- async def find_unique(self, *, where: Mapping[str, object]) -> _ObjectPermissionRecord | None: ...
-
- async def update(self, *, where: Mapping[str, object], data: Mapping[str, object]) -> object: ...
+ from litellm.proxy.utils import PrismaClient
+class _ModelDumpMethod(Protocol):
+ def __call__(self) -> Mapping: ...
+
+
+_ROW_DICT: Final = TypeAdapter(dict)
+
+
- class _ToolTableHolder(Protocol):
- @property
- def table(self) -> _ToolTable: ...
-
-
- class _ObjectPermissionTableHolder(Protocol):
- @property
- def table(self) -> _ObjectPermissionTable: ...
+ def _tool_table_actions(prisma_client: "PrismaClient") -> "TableActions[prisma_db_models.LiteLLM_ToolTable]":
+ table: Final[TableActions[prisma_db_models.LiteLLM_ToolTable]] = ToolRepository(prisma_client).table
+ return table
- def _tool_table(repo: _ToolTableHolder) -> _ToolTable:
- return repo.table
-
-
- def _object_permission_table(repo: _ObjectPermissionTableHolder) -> _ObjectPermissionTable:
- return repo.table
+ def _object_permission_table_actions(
+ prisma_client: "PrismaClient",
+ ) -> "TableActions[prisma_db_models.LiteLLM_ObjectPermissionTable]":
+ table: Final[TableActions[prisma_db_models.LiteLLM_ObjectPermissionTable]] = ObjectPermissionRepository(
+ prisma_client
+ ).table
+ return table
-def _row_to_model(row: dict | Any) -> LiteLLM_ToolTableRow:
+def _row_to_model(row: object) -> LiteLLM_ToolTableRow:
"""Convert a Prisma model instance or dict to LiteLLM_ToolTableRow."""
- model_dump: Final = getattr(row, "model_dump", None)
+ model_dump: Final[_ModelDumpMethod | None] = getattr(row, "model_dump", None)
if callable(model_dump):
row = model_dump()
elif not isinstance(row, dict):
@@@ -261,18 -200,16 +211,18 @@@ async def update_tool_policy
"created_at": now,
"updated_at": now,
}
- update_data: Final[dict[str, object]] = {
- "updated_by": _updated_by,
- "updated_at": now,
+ update_data: Final[Mapping[str, str | datetime]] = {
+ key: value
+ for key, value in (
+ ("updated_by", _updated_by),
+ ("updated_at", now),
+ ("input_policy", input_policy),
+ ("output_policy", output_policy),
+ )
+ if value is not None
}
- if input_policy is not None:
- update_data["input_policy"] = input_policy
- if output_policy is not None:
- update_data["output_policy"] = output_policy
- await _tool_table(ToolRepository(prisma_client)).upsert(
+ await _tool_table_actions(prisma_client).upsert(
where={"tool_name": tool_name},
data={
"create": create_data,
@@@ -473,12 -408,13 +423,12 @@@ async def add_tool_to_object_permission
)
if row is None:
return False
- current: Final = list(getattr(row, "blocked_tools", []) or [])
+ current: Final[Sequence[str]] = getattr(row, "blocked_tools", []) or []
if tool_name in current:
return True
- await _object_permission_table(ObjectPermissionRepository(prisma_client)).update(
- current.append(tool_name)
+ await _object_permission_table_actions(prisma_client).update(
where={"object_permission_id": object_permission_id},
- data={"blocked_tools": current},
+ data={"blocked_tools": [*current, tool_name]},
)
return True
except Exception as e:
@@@ -500,12 -436,13 +450,12 @@@ async def remove_tool_from_object_permi
)
if row is None:
return False
- current = list(getattr(row, "blocked_tools", []) or [])
+ current: Final[Sequence[str]] = getattr(row, "blocked_tools", []) or []
if tool_name not in current:
return False
- await _object_permission_table(ObjectPermissionRepository(prisma_client)).update(
- current = [t for t in current if t != tool_name]
+ await _object_permission_table_actions(prisma_client).update(
where={"object_permission_id": object_permission_id},
- data={"blocked_tools": current},
+ data={"blocked_tools": [t for t in current if t != tool_name]},
)
return True
except Exception as e:
diff --cc litellm/proxy/management_endpoints/internal_user_endpoints.py
index 7dfc80d2b2a,9a98bdbb6b1..9c4c9948c10
--- a/litellm/proxy/management_endpoints/internal_user_endpoints.py
+++ b/litellm/proxy/management_endpoints/internal_user_endpoints.py
@@@ -15,9 -15,9 +15,9 @@@ These are members of a Team on LiteLL
import asyncio
import json
import traceback
- from collections.abc import Mapping, Sequence
+ from collections.abc import Awaitable, Mapping, Sequence
from datetime import datetime, timezone
- from typing import Any, Final, Literal, Protocol, TypeAlias, TypeVar, cast, overload
-from typing import Any, Final, Literal, cast
++from typing import Any, Final, Literal, Protocol, cast, overload
import fastapi
from fastapi import APIRouter, Depends, Header, HTTPException, Request, status
@@@ -820,56 -735,12 +735,46 @@@ def _enforce_user_info_access(user_id:
)
- _TeamIdList: TypeAlias = list[str]
-
-
+class _UserInfoDataClient(Protocol):
+ @overload
+ async def get_data(self, *, user_id: str) -> "prisma_models.LiteLLM_UserTable | None": ...
+
+ @overload
+ async def get_data(
+ self,
+ *,
+ user_id: str | None,
+ table_name: Literal["key"],
+ query_type: Literal["find_all"],
+ ) -> "Sequence[LiteLLM_VerificationToken] | None": ...
+
+ @overload
+ async def get_data(
+ self,
+ *,
- team_id_list: _TeamIdList,
++ team_id_list: list[str],
+ table_name: Literal["team"],
+ query_type: Literal["find_all"],
+ ) -> "Sequence[TeamListResponseObject] | None": ...
+
+
- async def _get_user_info_row(
- prisma_client: "_UserInfoDataClient",
- user_id: str,
- ) -> "prisma_models.LiteLLM_UserTable | None":
- return await prisma_client.get_data(user_id=user_id)
-
-
+async def _get_user_info_keys(
+ prisma_client: "_UserInfoDataClient",
+ user_id: str | None,
+) -> "Sequence[LiteLLM_VerificationToken] | None":
+ return await prisma_client.get_data(
+ user_id=user_id,
+ table_name="key",
+ query_type="find_all",
+ )
+
+
async def _get_user_info_teams(
- prisma_client: Any,
+ prisma_client: "_UserInfoDataClient",
user_id: str | None,
- user_info: Any | None,
+ user_info: "prisma_models.LiteLLM_UserTable",
user_api_key_dict: UserAPIKeyAuth,
- ) -> tuple[Sequence[TeamListResponseObject], Sequence[TeamListResponseObject] | None]:
+ ) -> tuple[list[TeamListResponseObject], list[TeamListResponseObject] | None]:
"""Fetch and merge teams from membership + user.teams field."""
from litellm.proxy.management_endpoints.team_endpoints import list_team
@@@ -881,10 -755,11 +789,11 @@@
user_api_key_dict=user_api_key_dict,
)
- team_list: Final = teams_1 if teams_1 is not None and isinstance(teams_1, list) else list[TeamListResponseObject]()
- team_id_list: Final = [team.team_id for team in team_list]
+ if teams_1 is not None and isinstance(teams_1, list):
+ team_list = teams_1
+ team_id_list = [team.team_id for team in teams_1]
- teams_2: list[TeamListResponseObject] | None = None
+ teams_2: Sequence[TeamListResponseObject] | None = None
target_team_ids: Final = getattr(user_info, "teams", None)
if target_team_ids and isinstance(target_team_ids, list):
@@@ -932,9 -807,10 +841,10 @@@ def _redact_scim_enterprise_metadata
def _build_user_info_response(
user_id: str | None,
user_info: Any | None,
- keys: list[LiteLLM_VerificationToken] | None,
+ keys: Sequence[LiteLLM_VerificationToken] | None,
- team_list: Sequence[TeamListResponseObject],
- teams_1: Sequence[TeamListResponseObject] | None,
+ team_list: list[TeamListResponseObject],
+ teams_1: list[TeamListResponseObject] | None,
+ model_max_budget_usage: dict[str, dict[str, object]] | None = None,
) -> UserInfoResponse:
"""Create UserInfoResponse while filtering sensitive fields."""
if user_info is None and keys is not None:
@@@ -1254,8 -1140,8 +1179,8 @@@ async def _get_user_info_for_proxy_admi
def _process_keys_for_user_info(
- keys: list[LiteLLM_VerificationToken] | None,
+ keys: Sequence[LiteLLM_VerificationToken] | None,
- all_teams: Sequence[LiteLLM_TeamTable] | Sequence[TeamListResponseObject] | None,
+ all_teams: list[LiteLLM_TeamTable] | list[TeamListResponseObject] | None,
):
from litellm.constants import UI_SESSION_TOKEN_TEAM_ID
from litellm.proxy.proxy_server import general_settings, litellm_master_key_hash
diff --cc litellm/proxy/management_endpoints/key_management_endpoints.py
index 8fe388d2fea,0d12b012c18..52a192f8537
--- a/litellm/proxy/management_endpoints/key_management_endpoints.py
+++ b/litellm/proxy/management_endpoints/key_management_endpoints.py
@@@ -18,10 -18,9 +18,10 @@@ import o
import re
import secrets
import traceback
-from collections.abc import Awaitable, Callable, Mapping, Sequence
+from collections.abc import Awaitable, Callable, Iterator, Mapping, Sequence
+from contextlib import AbstractAsyncContextManager
from datetime import datetime, timedelta, timezone
- from typing import Any, Final, Literal, Optional, Protocol, TypeAlias, TypeVar, cast
+ from typing import TYPE_CHECKING, Any, Final, Literal, Optional, Protocol, TypeVar, cast
import fastapi
import yaml
@@@ -190,160 -191,45 +192,93 @@@ class _ConfigTableActions(Protocol)
*,
where: Mapping[str, object],
data: Mapping[str, object],
- ) -> _PrismaRowT | None: ...
+ ) -> ConfigParam | None: ...
- async def upsert(
- self,
- *,
- where: Mapping[str, object],
- data: Mapping[str, object],
- ) -> _PrismaRowT: ...
+ def _prisma_table(
+ repository: BaseRepository[_RepositoryModelT],
+ ) -> TableActions[_RepositoryModelT]:
+ return cast( # cast-ok: callers read only the field names the prisma row and repository model share
+ "TableActions[_RepositoryModelT]", repository.table
+ )
+
+
+ def _deleted_verification_token_table(
+ prisma_client: PrismaClient,
+ ) -> "TableActions[prisma_models.LiteLLM_DeletedVerificationToken]":
+ return DeletedVerificationTokenRepository(prisma_client).table
+
+
+ def _deprecated_verification_token_table(
+ prisma_client: PrismaClient,
+ ) -> "TableActions[prisma_models.LiteLLM_DeprecatedVerificationToken]":
+ return DeprecatedVerificationTokenRepository(prisma_client).table
- class _PrismaTableHolder(Protocol[_PrismaRowT]):
- @property
- def table(self) -> _PrismaTableActions[_PrismaRowT]: ...
+ def _user_table(prisma_client: PrismaClient) -> TableActions[_UserRowLike]:
+ return UserRepository(prisma_client).table
- def _typed_table(holder: _PrismaTableHolder[_PrismaRowT]) -> _PrismaTableActions[_PrismaRowT]:
- return holder.table
+
+ def _credentials_table(prisma_client: PrismaClient) -> TableActions[CredentialItem]:
+ return cast( # cast-ok: the rotation loop reads and rewrites these rows through CredentialItem names only
+ "TableActions[CredentialItem]", CredentialsRepository(prisma_client).table
+ )
+
+
+ def _config_table(prisma_client: PrismaClient) -> _ConfigTableActions:
+ return cast( # cast-ok: ConfigRepository.table hides the write actions this module needs on that same object
+ "_ConfigTableActions", ConfigRepository(prisma_client).table
+ )
+class _CustomKeyHooksModule(Protocol):
+ user_custom_key_generate: Callable[..., Awaitable[Mapping[str, object]]] | None
+ user_custom_key_update: Callable[..., Awaitable[Mapping[str, object]]] | None
+
+
+def _custom_key_generate_hook(
+ hooks: _CustomKeyHooksModule,
+) -> Callable[..., Awaitable[Mapping[str, object]]] | None:
+ return hooks.user_custom_key_generate
+
+
+def _custom_key_update_hook(
+ hooks: _CustomKeyHooksModule,
+) -> Callable[..., Awaitable[Mapping[str, object]]] | None:
+ return hooks.user_custom_key_update
+
+
+class _LegacyDumpable(Protocol):
+ def dict(self) -> Mapping[str, object]: ...
+
+
+def _legacy_model_dict(row: _LegacyDumpable) -> Mapping[str, object]:
+ return row.dict()
+
+
- class _PrismaTableLenient(Protocol[_PrismaRowCoT]):
- async def find_unique(self, *, where: Mapping[str, object]) -> _PrismaRowCoT: ...
-
- async def find_many(self, *, where: Mapping[str, object] | None = None) -> Sequence[_PrismaRowCoT] | None: ...
-
-
- class _PrismaTableLenientHolder(Protocol[_PrismaRowCoT]):
- @property
- def table(self) -> _PrismaTableLenient[_PrismaRowCoT]: ...
-
-
- def _lenient_table(holder: _PrismaTableLenientHolder[_PrismaRowCoT]) -> _PrismaTableLenient[_PrismaRowCoT]:
- return holder.table
-
-
- def _prisma_table_lenient(
- repository: BaseRepository[_RepositoryModelT],
- ) -> _PrismaTableLenient[_RepositoryModelT]:
- return _lenient_table(repository)
-
-
- def _jsonify_for_db(client: PrismaClient, data: Mapping[str, object]) -> Mapping[str, object]:
- return client.jsonify_object(dict[str, object](data))
-
-
- class _TxTables(Protocol):
- litellm_proxymodeltable: _PrismaTableActions[object]
-
-
- def _prisma_table(
- repository: BaseRepository[_RepositoryModelT],
- ) -> _PrismaTableActions[_RepositoryModelT]:
- return _typed_table(repository)
-
-
- def _deleted_verification_token_table(
- prisma_client: PrismaClient,
- ) -> _PrismaTableActions[LiteLLM_DeletedVerificationToken]:
- return _typed_table(DeletedVerificationTokenRepository(prisma_client))
-
-
- def _credentials_table(prisma_client: PrismaClient) -> _PrismaTableActions[CredentialItem]:
- return _typed_table(CredentialsRepository(prisma_client))
-
-
- def _config_table(prisma_client: PrismaClient) -> _PrismaTableActions[ConfigParam]:
- return _typed_table(ConfigRepository(prisma_client))
-
-
- def _deprecated_verification_token_table(prisma_client: PrismaClient) -> _PrismaTableActions[object]:
- return _typed_table(DeprecatedVerificationTokenRepository(prisma_client))
-
-
- _StringList: TypeAlias = list[str]
-
-
- class _CreatedUserRow(Protocol):
- models: _StringList
-
-
- def _created_user_row(user_row: "_CreatedUserRow | None") -> "_CreatedUserRow | None":
- return user_row
-
-
- async def _query_raw_text_rows(prisma_client: PrismaClient, sql: str, *params: object) -> Sequence[Mapping[str, str]]:
- return await prisma_client.db.query_raw(sql, *params)
-
-
+def _as_object_dict(values: Mapping[str, object]) -> Mapping[str, object]:
+ return values
+
+
+def _model_items(model: BaseModel) -> Iterator[tuple[str, object]]:
+ return iter(model)
+
+
- class _SpendCache(Protocol):
- async def async_get_cache(self, key: str) -> float | None: ...
-
-
- def _spend_cache(cache: _SpendCache) -> _SpendCache:
- return cache
-
-
- class _ObjectPermissionUtils(Protocol):
- @property
- def attach_object_permission_to_dict(
- self,
- ) -> Callable[..., Awaitable[Mapping[str, object]]]: ...
-
-
- def _object_permission_utils(module: _ObjectPermissionUtils) -> _ObjectPermissionUtils:
- return module
-
-
+class _EnvVarsParam(Protocol):
+ @property
+ def param_value(self) -> Mapping[str, str] | None: ...
+
+
+def _env_vars_param_value(param: _EnvVarsParam) -> Mapping[str, str] | None:
+ return param.param_value
+
+
+def _tx_tables_context(
+ open_tx: Callable[[], AbstractAsyncContextManager[_TxTables]],
+) -> AbstractAsyncContextManager[_TxTables]:
+ return open_tx()
+
+
async def _check_custom_key_allowed(custom_key_value: str | None) -> None:
"""Raise 403 if custom API keys are disabled and a custom key was provided."""
if custom_key_value is None:
@@@ -1006,19 -910,26 +959,26 @@@ async def _common_key_generation_helper
# check if user set default key/generate params on config.yaml
if litellm.default_key_generate_params is not None:
- for elem in data:
+ for elem in _model_items(data):
key, value = elem
- if value is None and key in [
- "max_budget",
- "user_id",
- "team_id",
- "max_parallel_requests",
- "tpm_limit",
- "rpm_limit",
- "budget_duration",
- "duration",
- ]:
- setattr(data, key, litellm.default_key_generate_params.get(key, None))
+ if (
+ value is None
+ and (key != "budget_duration" or key not in data.model_fields_set)
+ and key
+ in [
+ "max_budget",
+ "user_id",
+ "team_id",
+ "max_parallel_requests",
+ "tpm_limit",
+ "rpm_limit",
+ "budget_duration",
+ "duration",
+ ]
+ ):
+ default_value = litellm.default_key_generate_params.get(key)
+ if default_value is not None:
+ setattr(data, key, default_value)
elif key == "models" and value == []:
setattr(data, key, litellm.default_key_generate_params.get(key, []))
elif key == "metadata" and value == {}:
diff --cc litellm/proxy/prompts/prompt_endpoints.py
index d1dc1482401,9cfd6959a66..b6cbd2d7889
--- a/litellm/proxy/prompts/prompt_endpoints.py
+++ b/litellm/proxy/prompts/prompt_endpoints.py
@@@ -3,9 -3,10 +3,10 @@@ CRUD ENDPOINTS FOR PROMPT
"""
import tempfile
- from collections.abc import Mapping, Sequence
+ from collections.abc import Awaitable, Mapping, Sequence
+ from datetime import datetime
from pathlib import Path
-from typing import TYPE_CHECKING, Any, Final, Protocol, cast
+from typing import TYPE_CHECKING, Final, Protocol, cast
from fastapi import (
APIRouter,
diff --cc litellm/responses/streaming_iterator.py
index 1385e329e93,368fd481e63..6a4fb199b9f
--- a/litellm/responses/streaming_iterator.py
+++ b/litellm/responses/streaming_iterator.py
@@@ -49,9 -48,33 +49,19 @@@ if TYPE_CHECKING
ResponsesBackendWebSocket,
ResponsesClientWebSocket,
)
-
- class _StreamCachingHandler(Protocol):
- """The ``_llm_caching_handler`` attached to a logging object, as this module uses it."""
-
- original_function: Callable[..., object]
-
- def _should_store_result_in_cache(
- self, original_function: Callable[..., object], kwargs: Mapping[str, object]
- ) -> bool: ...
-
- class PiiUnmaskingGuardrailCallback(PresidioGuardrailCallback, Protocol):
- """Guardrail callback that can also reverse its own masking, selected by
- ``llm_http_handler`` on exactly this attribute."""
-
- def _unmask_pii_text(self, text: str, pii_tokens: Mapping[str, str]) -> str: ...
+ from litellm.types.router import LiteLLM_Params
+ class ProjectQuotaCallback(Protocol):
+ async def enforce_project_io_token_quota_for_frame(
+ self,
+ user_api_key_dict: UserAPIKeyAuth | None,
+ requested_model: str | None,
+ estimated_input_tokens: int,
+ estimated_output_tokens: int,
+ ) -> None: ...
+
+
@lru_cache(maxsize=1)
def _get_openai_response_types():
from litellm.types.llms import openai as openai_types
@@@ -71,79 -94,16 +81,70 @@@ def _is_str_mapping(value: object) -> T
return _is_json_object(value) and all(isinstance(item, str) for item in value.values())
+class _MutableJsonObject(Protocol):
+ @overload
+ def get(self, key: str, /) -> object | None: ...
+ @overload
+ def get(self, key: str, default: object, /) -> object: ...
+ def __getitem__(self, key: str, /) -> object: ...
+ def __setitem__(self, key: str, value: object, /) -> None: ...
+ def __contains__(self, key: object, /) -> bool: ...
+ def items(self) -> Iterable[tuple[str, object]]: ...
+
+
- class _LoadsJsonValue(Protocol):
- def __call__(self, s: str | bytes, /) -> object: ...
-
-
- class _LoadsJsonDict(Protocol):
- def __call__(self, s: str | bytes, /) -> _MutableJsonObject: ...
-
-
+class _GetsLitellmParams(Protocol):
+ def __call__(self, key: str, default: Mapping[str, object], /) -> LiteLLM_Params: ...
+
+
+class _PopsOptionalStr(Protocol):
+ def __call__(self, key: str, default: None, /) -> str | None: ...
+
+
+class _UnmasksPiiText(Protocol):
+ def __call__(self, text: str, pii_tokens: Mapping[str, str]) -> str: ...
+
+
+class _ShouldStoreResultInCache(Protocol):
+ def __call__(self, *, original_function: Callable[..., object] | None, kwargs: Mapping[str, object]) -> bool: ...
+
+
+class _PostStreamingDeploymentHook(Protocol):
+ def __call__(
+ self,
+ *,
+ request_data: Mapping[str, object],
+ response_chunk: ResponsesAPIStreamingResponse,
+ call_type: CallTypes | None,
+ ) -> Awaitable[ResponsesAPIStreamingResponse | None]: ...
+
+
+@runtime_checkable
+class _HasPostStreamingDeploymentHook(Protocol):
+ async_post_call_streaming_deployment_hook: _PostStreamingDeploymentHook
+
+
- def _typed_loads_json_value(fn: _LoadsJsonValue) -> _LoadsJsonValue:
- return fn
-
-
- def _typed_loads_json_dict(fn: _LoadsJsonDict) -> _LoadsJsonDict:
- return fn
-
-
+def _typed_gets_litellm_params(fn: _GetsLitellmParams) -> _GetsLitellmParams:
+ return fn
+
+
+def _typed_pops_optional_str(fn: _PopsOptionalStr) -> _PopsOptionalStr:
+ return fn
+
+
- _LOADS_JSON_VALUE: Final = _typed_loads_json_value(json.loads)
- _LOADS_JSON_DICT: Final = _typed_loads_json_dict(json.loads)
-
+_SHOULD_STORE_RESULT_IN_CACHE_ATTR: Final = "_should_store_result_in_cache"
+_UNMASK_PII_TEXT_ATTR: Final = "_unmask_pii_text"
+
+
+ def _load_json_object(payload: str | bytes) -> dict[str, object]:
+ """Parse a JSON payload that the caller consumes as an object."""
+ return json.loads(payload)
+
+
+ def _load_json_value(payload: str | bytes) -> object:
+ """Parse a JSON payload whose top-level shape the caller narrows itself."""
+ return json.loads(payload)
+
+
def _model_id_from_metadata(litellm_metadata: dict[str, object] | None) -> str | None:
model_info: Final = litellm_metadata.get("model_info") if litellm_metadata else None
model_id: Final = model_info.get("id") if _is_json_object(model_info) else None
@@@ -1443,8 -1474,9 +1525,9 @@@ class ResponsesWebSocketStreaming
user_api_key_dict: UserAPIKeyAuth | None = None,
request_data: dict[str, object] | None = None,
first_message: str | None = None,
- guardrail_callbacks: list[PiiUnmaskingGuardrailCallback] | None = None,
+ guardrail_callbacks: Sequence[PresidioGuardrailCallback] | None = None,
output_guardrail_callbacks: list[PresidioGuardrailCallback] | None = None,
+ quota_callbacks: Sequence[ProjectQuotaCallback] | None = None,
authorized_model: str | None = None,
):
self.websocket = websocket
@@@ -1452,11 -1484,12 +1535,12 @@@
self.logging_obj = logging_obj
self.user_api_key_dict = user_api_key_dict
self.request_data: dict[str, object] = request_data or {}
- self.messages: list[dict[str, object]] = []
+ self.messages: list[_MutableJsonObject] = []
self.input_messages: list[dict[str, object]] = []
self.first_message = first_message
- self.guardrail_callbacks: list[PiiUnmaskingGuardrailCallback] = guardrail_callbacks or []
+ self.guardrail_callbacks: Sequence[PresidioGuardrailCallback] = guardrail_callbacks or []
self.output_guardrail_callbacks: list[PresidioGuardrailCallback] = output_guardrail_callbacks or []
+ self.quota_callbacks: tuple[ProjectQuotaCallback, ...] = tuple(quota_callbacks) if quota_callbacks else ()
# Model name authorized at connection time; enforced on every
# response.create frame to prevent deployment-substitution attacks.
self.authorized_model: str | None = authorized_model
@@@ -2100,10 -2170,10 +2219,10 @@@ class ManagedResponsesWebSocketHandler
# _process_response_create sub-methods
# ------------------------------------------------------------------
- async def _parse_message(self, raw_message: str) -> dict[str, object] | None:
+ async def _parse_message(self, raw_message: str) -> _MutableJsonObject | None:
"""Parse raw WS text; return the message dict or None (JSON error / ignored type)."""
try:
- msg_obj: Final = _LOADS_JSON_DICT(raw_message)
+ msg_obj: Final = _load_json_object(raw_message)
except json.JSONDecodeError:
await self._send_error("Invalid JSON in response.create event", "invalid_request_error")
return None
@@@ -2384,15 -2462,12 +2511,14 @@@
# reuse the router-resolved self.model; passing the alias raw to
# litellm.aresponses fails in get_llm_provider. A genuinely different
# provider-prefixed per-frame model is still honored.
- requested_model: Final = _typed_pops_optional_str(call_kwargs.pop)("model", None)
- if requested_model is None or requested_model == self.model_group:
- model = self.model
- else:
- model = requested_model
- requested_model: Final[str | None] = call_kwargs.pop("model", None)
++ requested_model: Final[str | None] = _typed_pops_optional_str(call_kwargs.pop)("model", None)
+ model: Final[str] = (
+ self.model if requested_model is None or requested_model == self.model_group else requested_model
+ )
- previous_response_id: Final[str | None] = call_kwargs.pop("previous_response_id", None)
+ previous_response_id: Final[str | None] = _typed_pops_optional_str(call_kwargs.pop)(
+ "previous_response_id", None
+ )
current_messages: Final = self._input_to_messages(call_kwargs.get("input"))
# Fetch history once; reused in both _apply_history and _save_turn_history
diff --cc ruff-strict-budget.json
index 3e4a1339208,c60988eccc0..6b0e44edbc7
--- a/ruff-strict-budget.json
+++ b/ruff-strict-budget.json
@@@ -9,22 -9,22 +9,22 @@@
"limit": 827
},
"ANN201": {
- "limit": 2017
- "limit": 2003
++ "limit": 2000
},
"ANN202": {
- "limit": 855
+ "limit": 845
},
"ANN204": {
- "limit": 712
+ "limit": 702
},
"ANN205": {
- "limit": 114
+ "limit": 112
},
"ANN206": {
"limit": 133
},
"ANN401": {
- "limit": 1139
- "limit": 655
++ "limit": 625
},
"ASYNC230": {
"limit": 11
@@@ -123,7 -123,7 +123,7 @@@
"limit": 12
},
"PERF403": {
- "limit": 30
- "limit": 34
++ "limit": 31
},
"PIE804": {
"limit": 18
@@@ -234,7 -231,7 +231,7 @@@
"limit": 5
},
"TID251": {
- "limit": 1193
- "limit": 1117
++ "limit": 1105
},
"TRY002": {
"limit": 524
diff --cc type-discipline-budget.json
index e24b793dd92,f3f1a7defe7..60a6167a675
--- a/type-discipline-budget.json
+++ b/type-discipline-budget.json
@@@ -1,9 -1,9 +1,9 @@@
{
"LIT001": {
- "limit": 22117
- "limit": 22705
++ "limit": 22342
},
"LIT002": {
- "limit": 27142
- "limit": 26854
++ "limit": 26812
},
"LIT003": {
"limit": 269
@@@ -15,7 -15,7 +15,7 @@@
"limit": 0
},
"LIT006": {
- "limit": 1061
- "limit": 1063
++ "limit": 1054
},
"LIT007": {
"limit": 0
@@@ -27,12 -27,12 +27,12 @@@
"limit": 0
},
"LIT010": {
- "limit": 16703
- "limit": 16564
++ "limit": 16552
},
"LIT011": {
- "limit": 5573
- "limit": 5577
++ "limit": 5574
},
"LIT012": {
- "limit": 4516
- "limit": 4508
++ "limit": 4505
}
}