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 branch 'litellm_internal_staging' into litellm_decrease_anys_opus5_r2

mateo-berrifb9ec79d7c98
diff --cc basedpyright-code-budget.json
index d693c251df8,d60c3e9c0af..45af8e1d7c9
--- a/basedpyright-code-budget.json
+++ b/basedpyright-code-budget.json
@@@ -1,9 -1,9 +1,9 @@@
{
"reportAny": {
- "limit": 15626
- "limit": 16171
++ "limit": 15468
},
"reportArgumentType": {
- "limit": 2220
- "limit": 2226
++ "limit": 2218
},
"reportAssignmentType": {
"limit": 319
@@@ -24,7 -24,7 +24,7 @@@
"limit": 19
},
"reportExplicitAny": {
- "limit": 4879
- "limit": 5199
++ "limit": 4846
},
"reportFunctionMemberAccess": {
"limit": 7
@@@ -54,10 -54,10 +54,10 @@@
"limit": 0
},
"reportMissingParameterType": {
- "limit": 5610
- "limit": 5611
++ "limit": 5609
},
"reportMissingTypeArgument": {
- "limit": 15338
- "limit": 15350
++ "limit": 15330
},
"reportMissingTypeStubs": {
"limit": 40
@@@ -105,13 -105,13 +105,13 @@@
"limit": 109
},
"reportUnknownMemberType": {
- "limit": 38449
- "limit": 38468
++ "limit": 38418
},
"reportUnknownParameterType": {
- "limit": 19657
- "limit": 19665
++ "limit": 19649
},
"reportUnknownVariableType": {
- "limit": 30012
- "limit": 30066
++ "limit": 29987
},
"reportUnnecessaryCast": {
"limit": 111
diff --cc litellm/google_genai/adapters/transformation.py
index 2864663df93,b73a1443330..c45c6bd98c0
--- a/litellm/google_genai/adapters/transformation.py
+++ b/litellm/google_genai/adapters/transformation.py
@@@ -690,10 -718,12 +718,12 @@@ class GoogleGenAIAdapter
parts.append({"text": delta.content})
# 2. Ensure tool_calls is iterable
- tool_calls: Final = delta.tool_calls or []
+ tool_calls: Final[Sequence[ChatCompletionDeltaToolCall | ChatCompletionDeltaCustomToolCall]] = (
+ delta.tool_calls or []
+ )
for tool_call in tool_calls:
- if not hasattr(tool_call, "function"):
+ if not hasattr(tool_call, "function") or isinstance(tool_call, ChatCompletionDeltaCustomToolCall):
continue
# 3. Use `index` as the primary key for accumulation
diff --cc litellm/llms/anthropic/chat/guardrail_translation/handler.py
index 4f739dc4c8d,eb6dbd3e5b3..6f6b82400f9
--- a/litellm/llms/anthropic/chat/guardrail_translation/handler.py
+++ b/litellm/llms/anthropic/chat/guardrail_translation/handler.py
@@@ -98,6 -100,48 +100,38 @@@ InputWriteBackTarget =
)
-class _SSEDelta(TypedDict, total=False):
- type: ReadOnly[str]
- text: ReadOnly[str]
- stop_reason: ReadOnly[str | None]
-
-
-class _SSEEventData(TypedDict, total=False):
- delta: ReadOnly[_SSEDelta]
-
-
+ def _as_str_mapping(value: Mapping[str, object]) -> Mapping[str, object]:
+ return value
+
+
+ def _content_block_at(blocks: Sequence[object], index: int) -> object:
+ return blocks[index]
+
+
+ @runtime_checkable
+ class _ModelDumpBlock(Protocol):
+ def model_dump(self) -> Mapping[str, object]: ...
+
+
+ @runtime_checkable
+ class _TextAttrBlock(Protocol):
+ text: str
+
+
+ class _WritableMessage(Protocol):
+ @overload
+ def get(self, key: str, /) -> object | None: ...
+
+ @overload
+ def get(self, key: str, default: object, /) -> object: ...
+
+ def __setitem__(self, key: str, value: object, /) -> None: ...
+
+
+ def _as_writable(value: _WritableMessage) -> _WritableMessage:
+ return value
+
+
@dataclass(frozen=True, slots=True)
class ScannedText:
text: str
diff --cc litellm/llms/anthropic/experimental_pass_through/context_management/editors/compact.py
index a45bfb93640,1cf52045a48..050ab67c86c
--- a/litellm/llms/anthropic/experimental_pass_through/context_management/editors/compact.py
+++ b/litellm/llms/anthropic/experimental_pass_through/context_management/editors/compact.py
@@@ -13,21 -13,10 +13,10 @@@ Mirrors Anthropic's native ``compact_20
"""
import re
- from collections.abc import Mapping, Sequence
- from typing import (
- TYPE_CHECKING,
- Final,
- Literal,
- NotRequired,
- Optional,
- Protocol,
- TypedDict,
- Union,
- cast,
- runtime_checkable,
- )
+ from collections.abc import Awaitable, Mapping, Sequence
-from typing import TYPE_CHECKING, Any, Final, Literal, Optional, Protocol, TypeVar, Union, cast
++from typing import TYPE_CHECKING, Final, Literal, Optional, Protocol, TypeVar, Union, cast
- from typing_extensions import ReadOnly
+ from typing_extensions import NotRequired, ReadOnly, TypedDict, Unpack
import litellm
from litellm._logging import verbose_logger
@@@ -870,27 -949,9 +951,9 @@@ def _append_text_to_content(content: ob
async def _call_summary_model(
*,
summary_model: str,
- summary_messages: list[dict[str, object]],
+ summary_messages: Sequence[Mapping[str, object]],
metadata: Mapping[str, object],
- llm_router: object,
+ llm_router: Optional["Router"],
allowed_model_region: str | None = None,
max_tokens: int = COMPACT_SUMMARY_MAX_TOKENS,
) -> Union["ModelResponse", "CustomStreamWrapper"]:
diff --cc litellm/proxy/management_endpoints/key_management_endpoints.py
index f0f684b0fa1,52a192f8537..6c3f2d082ec
--- a/litellm/proxy/management_endpoints/key_management_endpoints.py
+++ b/litellm/proxy/management_endpoints/key_management_endpoints.py
@@@ -2466,6 -2517,6 +2517,12 @@@ async def _validate_mcp_servers_for_key
return normalized_object_permission
++def _require_prisma_client(prisma_client: PrismaClient | None) -> PrismaClient:
++ if prisma_client is None:
++ raise HTTPException(status_code=500, detail={"error": "Database not connected"})
++ return prisma_client
++
++
async def _validate_update_key_data(
data: UpdateKeyRequest,
existing_key_row: LiteLLM_VerificationToken,
@@@ -2476,9 -2527,6 +2533,8 @@@
user_api_key_cache: UserApiKeyCache,
) -> None:
"""Validate permissions and constraints for key update."""
- if prisma_client is None:
- raise HTTPException(status_code=500, detail={"error": "Database not connected"})
++ checked_prisma_client: Final = _require_prisma_client(prisma_client)
+
# Reject NaN/±inf spend before it can reach the DB / spend counter.
validate_finite_spend(data.spend)
validate_budget_duration(data.budget_duration)
@@@ -2516,7 -2564,7 +2572,7 @@@
await TeamMemberPermissionChecks.can_team_member_execute_key_management_endpoint(
user_api_key_dict=user_api_key_dict,
route=KeyManagementRoutes.KEY_UPDATE,
-- prisma_client=prisma_client,
++ prisma_client=checked_prisma_client,
existing_key_row=existing_key_row,
user_api_key_cache=user_api_key_cache,
)
@@@ -2602,7 -2650,7 +2658,7 @@@
await _check_key_admin_access(
user_api_key_dict=user_api_key_dict,
hashed_token=hashed_key,
-- prisma_client=prisma_client,
++ prisma_client=checked_prisma_client,
user_api_key_cache=user_api_key_cache,
route=("/key/update (max_budget/spend)" if _is_budget_change else "/key/update"),
)
@@@ -2613,7 -2661,7 +2669,7 @@@
if _team_id_to_check is not None:
team_obj = await get_team_object(
team_id=_team_id_to_check,
-- prisma_client=prisma_client,
++ prisma_client=checked_prisma_client,
user_api_key_cache=user_api_key_cache,
check_db_only=True,
)
@@@ -2629,7 -2677,7 +2685,7 @@@
await _check_team_key_limits(
team_table=team_obj,
data=data,
-- prisma_client=prisma_client,
++ prisma_client=checked_prisma_client,
)
TeamMemberPermissionChecks.enforce_member_can_assign_access_groups(
@@@ -2644,7 -2692,7 +2700,7 @@@
await _check_project_key_limits(
project_id=_project_id_to_check,
data=data,
-- prisma_client=prisma_client,
++ prisma_client=checked_prisma_client,
user_api_key_cache=user_api_key_cache,
)
@@@ -2659,7 -2707,7 +2715,7 @@@
await _validate_caller_can_assign_key_org(
user_api_key_dict=user_api_key_dict,
organization_id=data.organization_id,
-- prisma_client=prisma_client,
++ prisma_client=checked_prisma_client,
)
# Check org key limits only when throughput-related fields or organization_id change
@@@ -2675,7 -2723,7 +2731,7 @@@
org_table: Final = await get_org_object(
org_id=_org_id_to_check,
user_api_key_cache=user_api_key_cache,
-- prisma_client=prisma_client,
++ prisma_client=checked_prisma_client,
)
if org_table is None:
raise HTTPException(
@@@ -2685,7 -2733,7 +2741,7 @@@
await _check_org_key_limits(
org_table=org_table,
data=data,
-- prisma_client=prisma_client,
++ prisma_client=checked_prisma_client,
)
# if team change - check if this is possible
@@@ -2715,7 -2763,7 +2771,7 @@@
data=data,
team_obj=team_obj,
existing_key_row=existing_key_row,
-- prisma_client=prisma_client,
++ prisma_client=checked_prisma_client,
user_api_key_cache=user_api_key_cache,
is_proxy_admin=_is_proxy_admin,
)
diff --cc litellm/responses/streaming_iterator.py
index 278b2bd6ec6,d070f7758fd..de802b95086
--- a/litellm/responses/streaming_iterator.py
+++ b/litellm/responses/streaming_iterator.py
@@@ -104,6 -81,60 +91,52 @@@ 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 _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_gets_litellm_params(fn: _GetsLitellmParams) -> _GetsLitellmParams:
+ return fn
+
+
-def _typed_pops_optional_str(fn: _PopsOptionalStr) -> _PopsOptionalStr:
- return fn
-
-
+ _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)
diff --cc ruff-strict-budget.json
index be3f13ea7ef,1e855ea1b71..caa8eef252a
--- a/ruff-strict-budget.json
+++ b/ruff-strict-budget.json
@@@ -1,6 -1,6 +1,6 @@@
{
"ANN001": {
- "limit": 2994
- "limit": 2995
++ "limit": 2993
},
"ANN002": {
"limit": 71
@@@ -9,13 -9,13 +9,13 @@@
"limit": 809
},
"ANN201": {
- "limit": 2003
+ "limit": 2002
},
"ANN202": {
- "limit": 845
+ "limit": 843
},
"ANN204": {
- "limit": 698
+ "limit": 696
},
"ANN205": {
"limit": 112
@@@ -24,7 -24,7 +24,7 @@@
"limit": 133
},
"ANN401": {
- "limit": 492
- "limit": 587
++ "limit": 487
},
"ASYNC230": {
"limit": 11
@@@ -198,7 -198,7 +198,7 @@@
"limit": 56
},
"SIM102": {
- "limit": 313
- "limit": 314
++ "limit": 312
},
"SIM103": {
"limit": 119
@@@ -231,7 -231,7 +231,7 @@@
"limit": 5
},
"TID251": {
- "limit": 1099
- "limit": 1108
++ "limit": 1096
},
"TRY002": {
"limit": 524
diff --cc type-discipline-budget.json
index 399d0f6abad,ab34775c460..57ee0606dca
--- a/type-discipline-budget.json
+++ b/type-discipline-budget.json
@@@ -1,9 -1,9 +1,9 @@@
{
"LIT001": {
- "limit": 22590
- "limit": 22521
++ "limit": 22462
},
"LIT002": {
- "limit": 26812
- "limit": 26820
++ "limit": 26800
},
"LIT003": {
"limit": 269
@@@ -27,12 -27,12 +27,12 @@@
"limit": 0
},
"LIT010": {
- "limit": 16532
- "limit": 16546
++ "limit": 16529
},
"LIT011": {
- "limit": 5557
- "limit": 5575
++ "limit": 5556
},
"LIT012": {
- "limit": 4496
+ "limit": 4495
}
}