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 remote-tracking branch 'origin/litellm_internal_staging' into litellm_decrease_anys_fable6

mateo-berri6ab6e4fa7a32
diff --cc basedpyright-code-budget.json
index c71ef7a0020,7e4cc2d6100..ed8fa7fc50e
--- a/basedpyright-code-budget.json
+++ b/basedpyright-code-budget.json
@@@ -1,9 -1,9 +1,9 @@@
{
"reportAny": {
- "limit": 21974
- "limit": 23914
++ "limit": 21004
},
"reportArgumentType": {
- "limit": 2575
- "limit": 2580
++ "limit": 2568
},
"reportAssignmentType": {
"limit": 323
@@@ -24,7 -24,7 +24,7 @@@
"limit": 19
},
"reportExplicitAny": {
- "limit": 7068
- "limit": 7573
++ "limit": 6805
},
"reportFunctionMemberAccess": {
"limit": 7
@@@ -54,10 -54,10 +54,10 @@@
"limit": 0
},
"reportMissingParameterType": {
- "limit": 5697
- "limit": 5719
++ "limit": 5686
},
"reportMissingTypeArgument": {
- "limit": 15627
- "limit": 15657
++ "limit": 15600
},
"reportMissingTypeStubs": {
"limit": 40
@@@ -93,25 -93,25 +93,25 @@@
"limit": 213
},
"reportTypedDictNotRequiredAccess": {
-- "limit": 26
++ "limit": 24
},
"reportUndefinedVariable": {
"limit": 0
},
"reportUnknownArgumentType": {
- "limit": 44549
- "limit": 44832
++ "limit": 44392
},
"reportUnknownLambdaType": {
- "limit": 112
- "limit": 113
++ "limit": 110
},
"reportUnknownMemberType": {
- "limit": 39156
- "limit": 39269
++ "limit": 39100
},
"reportUnknownParameterType": {
- "limit": 19951
- "limit": 19988
++ "limit": 19925
},
"reportUnknownVariableType": {
- "limit": 30798
- "limit": 30923
++ "limit": 30737
},
"reportUnnecessaryCast": {
"limit": 118
@@@ -123,7 -123,7 +123,7 @@@
"limit": 5
},
"reportUnnecessaryIsInstance": {
- "limit": 852
- "limit": 853
++ "limit": 850
},
"reportUntypedBaseClass": {
"limit": 0
diff --cc litellm/google_genai/adapters/transformation.py
index 4c8e77d9feb,4f127f476c3..b73a1443330
--- a/litellm/google_genai/adapters/transformation.py
+++ b/litellm/google_genai/adapters/transformation.py
@@@ -1,9 -1,6 +1,9 @@@
import json
-from collections.abc import AsyncIterator, Iterator
-from typing import Any, Final, cast
+from collections.abc import AsyncIterator, Callable, Iterator, Mapping, Sequence
+from types import MappingProxyType
+from typing import Any, Final, TypeAlias, cast
+
- from typing_extensions import TypedDict
++from typing_extensions import ReadOnly, TypedDict
from litellm import verbose_logger
from litellm.litellm_core_utils.json_validation_rule import normalize_tool_schema
@@@ -36,66 -27,6 +36,66 @@@ from litellm.types.utils import
StreamingChoices,
)
+_JsonDict: TypeAlias = dict[str, object]
+_JsonDictList: TypeAlias = list[_JsonDict]
+
+
+class _ToolCallAccumulator(TypedDict):
- name: str
- arguments: str
++ name: ReadOnly[str]
++ arguments: ReadOnly[str]
+
+
+class _GenAIFunctionCall(TypedDict):
- name: str
- args: Mapping[str, object]
++ name: ReadOnly[str]
++ args: ReadOnly[Mapping[str, object]]
+
+
+class _GenAIPart(TypedDict, total=False):
- text: str
- functionCall: _GenAIFunctionCall
++ text: ReadOnly[str]
++ functionCall: ReadOnly[_GenAIFunctionCall]
+
+
+class _GenAIFunctionResponse(TypedDict, total=False):
- name: str
- response: object
++ name: ReadOnly[str]
++ response: ReadOnly[object]
+
+
+class _GenAIRequestFunctionCall(TypedDict, total=False):
- name: str
- args: Mapping[str, object]
++ name: ReadOnly[str]
++ args: ReadOnly[Mapping[str, object]]
+
+
+class _GenAIContentPart(TypedDict, total=False):
- text: str
- inline_data: Mapping[str, str]
- functionResponse: _GenAIFunctionResponse
- functionCall: _GenAIRequestFunctionCall
++ text: ReadOnly[str]
++ inline_data: ReadOnly[Mapping[str, str]]
++ functionResponse: ReadOnly[_GenAIFunctionResponse]
++ functionCall: ReadOnly[_GenAIRequestFunctionCall]
+
+
+class _GenAIFunctionDeclaration(TypedDict, total=False):
- name: str
- description: str
- parametersJsonSchema: object
++ name: ReadOnly[str]
++ description: ReadOnly[str]
++ parametersJsonSchema: ReadOnly[object]
+
+
+class _GenAITool(TypedDict, total=False):
- functionDeclarations: Sequence[_GenAIFunctionDeclaration]
++ functionDeclarations: ReadOnly[Sequence[_GenAIFunctionDeclaration]]
+
+
+class _GenAIFunctionCallingConfig(TypedDict, total=False):
- mode: str
++ mode: ReadOnly[str]
+
+
+class _GenAIToolConfig(TypedDict, total=False):
- functionCallingConfig: _GenAIFunctionCallingConfig
++ functionCallingConfig: ReadOnly[_GenAIFunctionCallingConfig]
+
+
+class _GenAISystemInstruction(TypedDict, total=False):
- parts: Sequence[Mapping[str, str]]
++ parts: ReadOnly[Sequence[Mapping[str, str]]]
+
+
+_EMPTY_STR_MAPPING: Final[Mapping[str, str]] = MappingProxyType({})
+
class GoogleGenAIStreamWrapper(AdapterCompletionStreamWrapper):
"""
@@@ -748,11 -666,11 +748,11 @@@ class GoogleGenAIAdapter
verbose_logger.debug("Skipping empty tool call chunk for index: %s", tool_call_index)
continue
-- if function_name:
-- wrapper.accumulated_tool_calls[tool_call_index]["name"] = function_name
--
-- if args_chunk:
-- wrapper.accumulated_tool_calls[tool_call_index]["arguments"] += args_chunk
++ previous_data: _ToolCallAccumulator = wrapper.accumulated_tool_calls[tool_call_index]
++ wrapper.accumulated_tool_calls[tool_call_index] = _ToolCallAccumulator(
++ name=function_name or previous_data["name"],
++ arguments=previous_data["arguments"] + (args_chunk or ""),
++ )
# Attempt to parse and emit a complete tool call
accumulated_data = wrapper.accumulated_tool_calls[tool_call_index]
diff --cc litellm/integrations/rubrik.py
index c206849c86f,97e831f5822..c9e511905a6
--- a/litellm/integrations/rubrik.py
+++ b/litellm/integrations/rubrik.py
@@@ -6,14 -6,12 +6,14 @@@ import rando
import time
import uuid
from collections import Counter
-from collections.abc import Mapping, Sequence
+from collections.abc import Awaitable, Mapping, Sequence
from dataclasses import dataclass
+from datetime import datetime
from types import MappingProxyType
-from typing import TYPE_CHECKING, Any, Final, Literal, Optional
+from typing import TYPE_CHECKING, Final, Literal, Optional, Protocol, TypedDict, overload
import httpx
- from typing_extensions import Never, Required
++from typing_extensions import Never, ReadOnly, Required
from litellm._logging import verbose_logger
from litellm.integrations.custom_batch_logger import CustomBatchLogger
@@@ -51,105 -48,7 +51,105 @@@ _WEBHOOK_PATH_PROMPT_MODERATION: Final
_WEBHOOK_PATH_LOGGING_BATCH: Final = "/v1/litellm/batch"
_MAX_QUEUE_SIZE: Final = 10_000
_DROP_WARNING_INTERVAL_SECONDS: Final = 60.0
-_EMPTY_MAPPING: Final[Mapping[str, Any]] = MappingProxyType({})
+_EMPTY_MAPPING: Final[Mapping[str, Never]] = MappingProxyType({})
+
+
+class _ModerationToolCall(TypedDict, total=False):
- id: Required[str]
++ id: ReadOnly[Required[str]]
+
+
+class _ModerationMessage(TypedDict, total=False):
- content: str | None
- tool_calls: Sequence[_ModerationToolCall] | None
++ content: ReadOnly[str | None]
++ tool_calls: ReadOnly[Sequence[_ModerationToolCall] | None]
+
+
+class _ModerationChoice(TypedDict, total=False):
- message: _ModerationMessage | None
++ message: ReadOnly[_ModerationMessage | None]
+
+
+class _ModerationResponse(TypedDict, total=False):
- choices: Sequence[_ModerationChoice]
++ choices: ReadOnly[Sequence[_ModerationChoice]]
+
+
+class _LogEventKwargs(TypedDict, total=False):
- standard_logging_object: Required[StandardLoggingPayload]
- litellm_call_id: str
++ standard_logging_object: ReadOnly[Required[StandardLoggingPayload]]
++ litellm_call_id: ReadOnly[str]
+
+
+class _HasCallId(Protocol):
+ def get(self, key: Literal["litellm_call_id"], /) -> str | None: ...
+
+
+class _HasModelAttr(Protocol):
+ model: str | None
+
+
+class _ResponseSource(Protocol):
+ def get(self, key: Literal["response"], /) -> "_HasModelAttr | None": ...
+
+
+class _ModelSource(Protocol):
+ def get(self, key: Literal["model"], default: str, /) -> str: ...
+
+
+class _FallbackSource(Protocol):
+ @overload
+ def get(self, key: Literal["start_time"], /) -> datetime | None: ...
+ @overload
+ def get(self, key: str, /) -> object | None: ...
+
+
+class _RequestContextSource(Protocol):
+ @overload
+ def get(self, key: Literal["optional_params"], /) -> Mapping[str, object] | None: ...
+ @overload
+ def get(self, key: str, /) -> object | None: ...
+ def __contains__(self, key: object, /) -> bool: ...
+ def __getitem__(self, key: str, /) -> object: ...
+
+
+class _ToolCallLike(Protocol):
+ id: str | None
+ type: str | None
+ function: Function
+
+
+class _ModerationSourceToolCall(TypedDict, total=False):
- function: Mapping[str, object] | None
++ function: ReadOnly[Mapping[str, object] | None]
+
+
+class _ModerationSourceMessage(TypedDict, total=False):
- role: str
- function_call: Mapping[str, object] | None
- tool_calls: Sequence[_ModerationSourceToolCall | None] | None
++ role: ReadOnly[str]
++ function_call: ReadOnly[Mapping[str, object] | None]
++ tool_calls: ReadOnly[Sequence[_ModerationSourceToolCall | None] | None]
+
+
+class _FlattenedModerationMessage(TypedDict):
- role: str | None
- content: str
++ role: ReadOnly[str | None]
++ content: ReadOnly[str]
+
+
+class _CorrelatablePayload(TypedDict):
- id: str
++ id: str # writable-ok: _apply_correlation_id overwrites the provider id on a deep-copied payload
+
+
+class _SystemPromptCarrier(TypedDict, total=False):
- messages: object
++ messages: object # writable-ok: _prepend_system_prompt rebinds messages on the copied payload by design
+
+
+class _BlockFailurePayload(TypedDict, total=False):
- id: object
- model: object
- model_group: object
- model_id: str
- model_parameters: object
- startTime: float | None
- endTime: float | None
- completionStartTime: float | None
- messages: object
- metadata: StandardLoggingUserAPIKeyMetadata
- response: str
- status: str
++ id: object # writable-ok: correlation id is pinned after copying the base payload
++ model: ReadOnly[object]
++ model_group: ReadOnly[object]
++ model_id: ReadOnly[str]
++ model_parameters: ReadOnly[object]
++ startTime: ReadOnly[float | None]
++ endTime: ReadOnly[float | None]
++ completionStartTime: ReadOnly[float | None]
++ messages: object # writable-ok: passed to _prepend_system_prompt, which rebinds messages
++ metadata: ReadOnly[StandardLoggingUserAPIKeyMetadata]
++ response: str # writable-ok: block failure text replaces the copied response
++ status: ReadOnly[str]
class _MalformedToolBlockingResponseError(Exception):
diff --cc litellm/integrations/websearch_interception/handler.py
index edd3fdb8c61,972ae1d9856..182393dd343
--- a/litellm/integrations/websearch_interception/handler.py
+++ b/litellm/integrations/websearch_interception/handler.py
@@@ -10,8 -10,8 +10,10 @@@ import asynci
import math
import uuid
from collections.abc import AsyncIterator, Mapping, Sequence
-from typing import TYPE_CHECKING, Any, Final, TypedDict, cast
+from typing import TYPE_CHECKING, Any, Final, Literal, Never, TypedDict, TypeVar, cast
+
++from typing_extensions import ReadOnly
+
import litellm
from litellm._logging import verbose_logger
from litellm.anthropic_interface import messages as anthropic_messages
@@@ -95,96 -85,9 +97,96 @@@ class _WebSearchSettingsView(TypedDict)
websearch_interception_params: WebSearchInterceptionConfig
+class _SearchToolLitellmParams(TypedDict, total=False):
- search_provider: str | None
++ search_provider: ReadOnly[str | None]
+
+
class _SearchToolConfig(TypedDict, total=False):
search_tool_name: str
- litellm_params: _SearchToolLitellmParams | None
- litellm_params: Mapping[str, object] | None
++ litellm_params: ReadOnly[_SearchToolLitellmParams | None]
+
+
+class _LitellmParamsProviderView(TypedDict, total=False):
- custom_llm_provider: str
++ custom_llm_provider: ReadOnly[str]
+
+
+class _DeploymentCallKwargsView(TypedDict):
- custom_llm_provider: str
- litellm_params: _LitellmParamsProviderView
- model: str
++ custom_llm_provider: ReadOnly[str]
++ litellm_params: ReadOnly[_LitellmParamsProviderView]
++ model: ReadOnly[str]
+
+
+class _AcreateNamedParams(TypedDict, total=False):
- metadata: Never
- stop_sequences: Never
- stream: bool | None
- system: str | None
- temperature: float | None
- thinking: Never
- tool_choice: Never
- tools: Never
- top_k: int | None
- top_p: float | None
- container: Never
++ 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: int | None
- search_domain_filter: Never
- max_tokens_per_page: int | None
- country: str | None
- api_key: str | None
- api_base: str | None
- timeout: float | None
- extra_headers: Never
++ 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: Never
- function_call: str | None
- timeout: float | None
- temperature: float | None
- top_p: float | None
- n: int | None
- stream: bool | None
- stream_options: Never
- stop: Never
- max_tokens: int | None
- max_completion_tokens: int | None
- modalities: Never
- prediction: ChatCompletionPredictionContentParam | None
- audio: ChatCompletionAudioParam | None
- presence_penalty: float | None
- frequency_penalty: float | None
- logit_bias: Never
- user: str | None
- response_format: Never
- seed: int | None
- tools: Never
- tool_choice: Never
- parallel_tool_calls: bool | None
- logprobs: bool | None
- top_logprobs: int | None
- deployment_id: str | None
- reasoning_effort: Literal["none", "minimal", "low", "medium", "high", "xhigh", "default"] | None
- verbosity: Literal["low", "medium", "high"] | None
- safety_identifier: str | None
- service_tier: str | None
- base_url: str | None
- api_version: str | None
- api_key: str | None
- model_list: Never
- extra_headers: Never
- thinking: AnthropicThinkingParam | None
- web_search_options: OpenAIWebSearchOptions | None
- include_server_side_tool_invocations: bool | None
- shared_session: "ClientSession | None"
- enable_json_schema_validation: bool | None
++ 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]
++ 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/chat/guardrail_translation/handler.py
index 47dfe8de292,e4a4d23b438..78be9046642
--- a/litellm/llms/anthropic/chat/guardrail_translation/handler.py
+++ b/litellm/llms/anthropic/chat/guardrail_translation/handler.py
@@@ -13,12 -13,12 +13,12 @@@ Pattern Overview
"""
import json
-from collections.abc import Mapping
+from collections.abc import Mapping, Sequence
from copy import deepcopy
from dataclasses import dataclass
-from typing import TYPE_CHECKING, Any, Final, cast
+from typing import TYPE_CHECKING, Any, Final, Protocol, cast, overload, runtime_checkable
- from typing_extensions import TypedDict, assert_never
-from typing_extensions import assert_never
++from typing_extensions import ReadOnly, TypedDict, assert_never
from litellm._logging import verbose_proxy_logger
from litellm.llms.anthropic.chat.transformation import AnthropicConfig
@@@ -96,48 -95,6 +96,48 @@@ InputWriteBackTarget =
)
+class _SSEDelta(TypedDict, total=False):
- type: str
- text: str
- stop_reason: str | None
++ type: ReadOnly[str]
++ text: ReadOnly[str]
++ stop_reason: ReadOnly[str | None]
+
+
+class _SSEEventData(TypedDict, total=False):
- delta: _SSEDelta
++ 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
@@@ -241,7 -196,7 +241,7 @@@ class AnthropicMessagesHandler(BaseTran
def _sse(event_type: str, payload: dict) -> bytes:
return f"event: {event_type}\ndata: {json.dumps(payload)}\n\n".encode()
-- output_tokens: Final = blocked_response_usage(getattr(exc, "original_response", None))["output_tokens"]
++ output_tokens: Final = blocked_response_usage(getattr(exc, "original_response", None)).get("output_tokens", 0)
open_index, max_index = self._content_block_state(responses_so_far)
new_index: Final = (max_index + 1) if max_index is not None else 0
chunks: list[bytes] = []
diff --cc litellm/llms/anthropic/experimental_pass_through/context_management/editors/compact.py
index d230b438086,dbeac453791..e4bb56c1a53
--- 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,10 -13,8 +13,10 @@@ Mirrors Anthropic's native ``compact_20
"""
import re
-from collections.abc import Mapping
-from typing import TYPE_CHECKING, Any, Final, Literal, Optional, Union, cast
+from collections.abc import Awaitable, Mapping, Sequence
+from typing import TYPE_CHECKING, Any, Final, Literal, Optional, Protocol, TypeVar, Union, cast
+
- from typing_extensions import NotRequired, TypedDict, Unpack
++from typing_extensions import NotRequired, ReadOnly, TypedDict, Unpack
import litellm
from litellm._logging import verbose_logger
@@@ -84,69 -82,6 +84,74 @@@ _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: str
- max_tokens: int
- timeout: float
- litellm_metadata: Mapping[str, object]
- user: NotRequired[str]
- allowed_model_region: NotRequired[str]
++ 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]
+ ) -> "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."""
@@@ -950,34 -860,31 +955,42 @@@ async def _call_summary_model
# the parent ``/v1/messages`` request. On timeout the caller catches the
# exception and surfaces ``applied_edits[0].error = "summary_call_failed"``,
# forwarding the request without compaction rather than hanging.
- call_kwargs: Final[dict[str, Any]] = {
- "model": summary_model,
- "messages": summary_messages,
- "max_tokens": max_tokens,
- "timeout": COMPACT_SUMMARY_TIMEOUT_SECONDS,
- "litellm_metadata": metadata,
- }
+ # The end-user id must also travel as the top-level ``user`` kwarg: legacy
+ # limiter hooks and prometheus end-user tracking read it from there rather
+ # than from ``litellm_metadata``, so without it the summary tokens would not
+ # debit the caller's end-user counters.
+ end_user_id: Final = metadata.get("user_api_key_end_user_id")
- if end_user_id:
- call_kwargs["user"] = end_user_id
- if allowed_model_region is not None:
- call_kwargs["allowed_model_region"] = allowed_model_region
- if llm_router is not None and hasattr(llm_router, "acompletion"):
- return await llm_router.acompletion(**call_kwargs)
- return await litellm.acompletion(**call_kwargs)
++ user_kwargs: Final = (
++ _SummaryOptionalKwargs(user=end_user_id)
++ if isinstance(end_user_id, str) and end_user_id
++ else _SummaryOptionalKwargs()
++ )
++ region_kwargs: Final = (
++ _SummaryOptionalKwargs(allowed_model_region=allowed_model_region)
++ if allowed_model_region is not None
++ else _SummaryOptionalKwargs()
++ )
+ call_kwargs: Final[_SummaryCallKwargs] = {
+ "model": summary_model,
+ "max_tokens": max_tokens,
+ "timeout": COMPACT_SUMMARY_TIMEOUT_SECONDS,
+ "litellm_metadata": metadata,
++ **user_kwargs,
++ **region_kwargs,
+ }
- # The end-user id must also travel as the top-level ``user`` kwarg: legacy
- # limiter hooks and prometheus end-user tracking read it from there rather
- # than from ``litellm_metadata``, so without it the summary tokens would not
- # debit the caller's end-user counters.
- end_user_id: Final = metadata.get("user_api_key_end_user_id")
- if isinstance(end_user_id, str) and end_user_id:
- call_kwargs["user"] = end_user_id
- if allowed_model_region is not None:
- call_kwargs["allowed_model_region"] = allowed_model_region
+ router_acompletion: Final[_SummaryAcompletion | None] = getattr(llm_router, "acompletion", None)
+ if llm_router is not None and router_acompletion is not None:
+ return await router_acompletion(messages=summary_messages, **call_kwargs)
+ return await litellm.acompletion(messages=[*summary_messages], **call_kwargs)
-def _extract_response_text(response: Any) -> str | None:
+def _extract_response_text(response: object) -> str | None:
try:
- choice: Final = response.choices[0]
- message: Final = choice.message
+ choices: Final[Sequence[object] | None] = getattr(response, "choices", None)
+ if choices is None:
+ return None
+ choice: Final = choices[0]
+ message: Final = getattr(choice, "message", None)
content: Final = getattr(message, "content", None)
if isinstance(content, str):
return content
diff --cc litellm/llms/runwayml/videos/transformation.py
index 6e720c058fb,2e0ae30a192..940c8a8cf3d
--- a/litellm/llms/runwayml/videos/transformation.py
+++ b/litellm/llms/runwayml/videos/transformation.py
@@@ -1,10 -1,8 +1,10 @@@
+from collections.abc import Mapping, Sequence
from datetime import datetime
-from typing import TYPE_CHECKING, Any, Final
+from typing import TYPE_CHECKING, Any, Final, Literal, TypedDict
import httpx
-from httpx._types import RequestFiles
+from httpx._types import FileTypes, RequestFiles
- from typing_extensions import NotRequired
++from typing_extensions import NotRequired, ReadOnly
import litellm
from litellm.constants import RUNWAYML_DEFAULT_API_VERSION
@@@ -33,31 -31,6 +33,41 @@@ else
LiteLLMLoggingObj = Any
+class _RunwayTaskResponse(TypedDict, total=False):
- id: str
- status: str
- createdAt: str
- completedAt: str
- output: Sequence[str] | str
- progress: int
- failureCode: str
- failure: str
++ id: ReadOnly[str]
++ status: ReadOnly[str]
++ createdAt: ReadOnly[str]
++ completedAt: ReadOnly[str]
++ output: ReadOnly[Sequence[str] | str]
++ progress: ReadOnly[int]
++ failureCode: ReadOnly[str]
++ failure: ReadOnly[str]
+
+
+class _RunwayVideoData(TypedDict):
- id: str
- object: Literal["video"]
- status: str
- created_at: int
- output_url: NotRequired[str]
- completed_at: NotRequired[int]
- progress: NotRequired[int]
- error: NotRequired[Mapping[str, str]]
- model: NotRequired[str]
- size: NotRequired[str]
- seconds: NotRequired[str]
++ id: ReadOnly[str]
++ object: ReadOnly[Literal["video"]]
++ status: ReadOnly[str]
++ created_at: ReadOnly[int]
++ output_url: ReadOnly[NotRequired[str]]
++ completed_at: ReadOnly[NotRequired[int]]
++ progress: ReadOnly[NotRequired[int]]
++ error: ReadOnly[NotRequired[Mapping[str, str]]]
++ model: ReadOnly[NotRequired[str]]
++ size: ReadOnly[NotRequired[str]]
++ seconds: ReadOnly[NotRequired[str]]
++
++
++class _RunwayVideoOptionalData(TypedDict, total=False):
++ output_url: ReadOnly[str]
++ completed_at: ReadOnly[int]
++ progress: ReadOnly[int]
++ error: ReadOnly[Mapping[str, str]]
++ model: ReadOnly[str]
++ size: ReadOnly[str]
++ seconds: ReadOnly[str]
+
+
class RunwayMLVideoConfig(BaseVideoConfig):
"""
Configuration class for RunwayML video generation.
@@@ -252,44 -216,45 +262,65 @@@
We map this to OpenAI VideoObject format.
"""
- response_data: Final = raw_response.json()
+ response_data: Final[_RunwayTaskResponse] = self._parse_task_response(raw_response)
+
++ # RunwayML returns output as array of URLs when task succeeds
++ output: Final = response_data.get("output")
++ output_kwargs: Final = (
++ _RunwayVideoOptionalData(output_url=output if isinstance(output, str) else output[0])
++ if output
++ else _RunwayVideoOptionalData()
++ )
++ completed_at_kwargs: Final = (
++ _RunwayVideoOptionalData(completed_at=self._parse_runway_timestamp(response_data.get("completedAt")))
++ if "completedAt" in response_data
++ else _RunwayVideoOptionalData()
++ )
++ error_kwargs: Final = (
++ _RunwayVideoOptionalData(
++ error={
++ "code": response_data.get("failureCode", "unknown"),
++ "message": response_data.get("failure", "Video generation failed"),
++ }
++ )
++ if "failureCode" in response_data or "failure" in response_data
++ else _RunwayVideoOptionalData()
++ )
++
++ # Add model and size info if available from request
++ model_kwargs: Final = (
++ _RunwayVideoOptionalData(model=request_data["model"])
++ if request_data and "model" in request_data
++ else _RunwayVideoOptionalData()
++ )
++ # Convert ratio back to size format
++ ratio: Final = request_data.get("ratio") if request_data else None
++ size_kwargs: Final = (
++ _RunwayVideoOptionalData(size=ratio.replace(":", "x"))
++ if isinstance(ratio, str) and ":" in ratio
++ else _RunwayVideoOptionalData()
++ )
++ seconds_kwargs: Final = (
++ _RunwayVideoOptionalData(seconds=str(request_data["duration"]))
++ if request_data and "duration" in request_data
++ else _RunwayVideoOptionalData()
++ )
+
# Map RunwayML task response to VideoObject format
- video_data: Final[dict[str, Any]] = {
+ video_data: Final[_RunwayVideoData] = {
"id": response_data.get("id", ""),
"object": "video",
"status": self._map_runway_status(response_data.get("status", "pending")),
"created_at": self._parse_runway_timestamp(response_data.get("createdAt")),
++ **output_kwargs,
++ **completed_at_kwargs,
++ **error_kwargs,
++ **model_kwargs,
++ **size_kwargs,
++ **seconds_kwargs,
}
-- # Add optional fields if present
-- if "output" in response_data and response_data["output"]:
-- # RunwayML returns output as array of URLs when task succeeds
- output: Final = response_data["output"]
- video_data["output_url"] = output if isinstance(output, str) else output[0]
- video_data["output_url"] = (
- response_data["output"][0] if isinstance(response_data["output"], list) else response_data["output"]
- )
--
-- if "completedAt" in response_data:
-- video_data["completed_at"] = self._parse_runway_timestamp(response_data.get("completedAt"))
--
-- if "failureCode" in response_data or "failure" in response_data:
-- video_data["error"] = {
-- "code": response_data.get("failureCode", "unknown"),
-- "message": response_data.get("failure", "Video generation failed"),
-- }
--
-- # Add model and size info if available from request
-- if request_data:
-- if "model" in request_data:
-- video_data["model"] = request_data["model"]
-- if "ratio" in request_data:
-- # Convert ratio back to size format
-- ratio: Final = request_data["ratio"]
-- if isinstance(ratio, str) and ":" in ratio:
-- video_data["size"] = ratio.replace(":", "x")
-- if "duration" in request_data:
-- video_data["seconds"] = str(request_data["duration"])
--
- video_obj: Final = VideoObject(**video_data)
+ video_obj: Final = VideoObject.model_validate(video_data)
if custom_llm_provider and video_obj.id:
video_obj.id = encode_video_id_with_provider(video_obj.id, custom_llm_provider, model)
@@@ -566,34 -537,35 +597,48 @@@
"""
Transform the RunwayML video status retrieve response.
"""
- response_data: Final = raw_response.json()
+ response_data: Final[_RunwayTaskResponse] = self._parse_task_response(raw_response)
+
++ output: Final = response_data.get("output")
++ output_kwargs: Final = (
++ _RunwayVideoOptionalData(output_url=output if isinstance(output, str) else output[0])
++ if output
++ else _RunwayVideoOptionalData()
++ )
++ completed_at_kwargs: Final = (
++ _RunwayVideoOptionalData(completed_at=self._parse_runway_timestamp(response_data.get("completedAt")))
++ if "completedAt" in response_data
++ else _RunwayVideoOptionalData()
++ )
++ progress_kwargs: Final = (
++ _RunwayVideoOptionalData(progress=response_data["progress"])
++ if "progress" in response_data
++ else _RunwayVideoOptionalData()
++ )
++ error_kwargs: Final = (
++ _RunwayVideoOptionalData(
++ error={
++ "code": response_data.get("failureCode", "unknown"),
++ "message": response_data.get("failure", "Video generation failed"),
++ }
++ )
++ if "failureCode" in response_data or "failure" in response_data
++ else _RunwayVideoOptionalData()
++ )
+
# Map RunwayML task response to VideoObject format
- video_data: Final[dict[str, Any]] = {
+ video_data: Final[_RunwayVideoData] = {
"id": response_data.get("id", ""),
"object": "video",
"status": self._map_runway_status(response_data.get("status", "pending")),
"created_at": self._parse_runway_timestamp(response_data.get("createdAt")),
++ **output_kwargs,
++ **completed_at_kwargs,
++ **progress_kwargs,
++ **error_kwargs,
}
-- # Add optional fields if present
-- if "output" in response_data and response_data["output"]:
- output: Final = response_data["output"]
- video_data["output_url"] = output if isinstance(output, str) else output[0]
- video_data["output_url"] = (
- response_data["output"][0] if isinstance(response_data["output"], list) else response_data["output"]
- )
--
-- if "completedAt" in response_data:
-- video_data["completed_at"] = self._parse_runway_timestamp(response_data.get("completedAt"))
--
-- if "progress" in response_data:
-- video_data["progress"] = response_data["progress"]
--
-- if "failureCode" in response_data or "failure" in response_data:
-- video_data["error"] = {
-- "code": response_data.get("failureCode", "unknown"),
-- "message": response_data.get("failure", "Video generation failed"),
-- }
--
- video_obj: Final = VideoObject(**video_data)
+ video_obj: Final = VideoObject.model_validate(video_data)
if custom_llm_provider and video_obj.id:
video_obj.id = encode_video_id_with_provider(video_obj.id, custom_llm_provider, None)
diff --cc litellm/llms/vertex_ai/files/transformation.py
index 131ee41ea8b,3538fc5b1a7..d9ec3e753d2
--- a/litellm/llms/vertex_ai/files/transformation.py
+++ b/litellm/llms/vertex_ai/files/transformation.py
@@@ -11,7 -11,6 +11,7 @@@ from typing import Final, TypedDic
import httpx
from httpx import Headers, Response
from openai.types.file_deleted import FileDeleted
- from typing_extensions import Required
++from typing_extensions import ReadOnly, Required
import litellm
from litellm._uuid import uuid
@@@ -64,47 -62,6 +64,47 @@@ _GCP_LABEL_VALUE_MAX_LEN: Final = 6
_CUSTOM_ID_RAW_LABEL_PREFIX: Final = "b32_"
+class _OpenAIBatchRequestBody(TypedDict, total=False):
- model: str
- messages: Sequence[AllMessageValues]
++ model: ReadOnly[str]
++ messages: ReadOnly[Sequence[AllMessageValues]]
+
+
+class _OpenAIBatchJsonlEntry(TypedDict, total=False):
- custom_id: Required[object]
- body: _OpenAIBatchRequestBody
++ custom_id: ReadOnly[Required[object]]
++ body: ReadOnly[_OpenAIBatchRequestBody]
+
+
+class _VertexBatchOutputRequest(TypedDict, total=False):
- labels: Mapping[str, str]
++ labels: ReadOnly[Mapping[str, str]]
+
+
+class _VertexBatchResponse(GenerateContentResponseBody, total=False):
+ modelVersion: str
+
+
+class _VertexBatchOutputRow(TypedDict, total=False):
- request: _VertexBatchOutputRequest
- status: str
- processed_time: str
- response: _VertexBatchResponse
++ request: ReadOnly[_VertexBatchOutputRequest]
++ status: ReadOnly[str]
++ processed_time: ReadOnly[str]
++ response: ReadOnly[_VertexBatchResponse]
+
+
+class _GcsObjectMetadata(TypedDict, total=False):
- purpose: OpenAIFilesPurpose
++ purpose: ReadOnly[OpenAIFilesPurpose]
+
+
+class _GcsObjectResponse(GcsBucketResponse, total=False):
+ metadata: _GcsObjectMetadata
+
+
+def _parse_gcs_object_response(raw_response: Response) -> _GcsObjectResponse:
+ return raw_response.json()
+
+
+def _parse_vertex_batch_output_row(line: str) -> _VertexBatchOutputRow:
+ return json.loads(line)
+
+
def _sanitize_gcp_label_value(value: str) -> str:
"""
Sanitize a string to meet GCP label value constraints.
diff --cc litellm/proxy/response_polling/background_streaming.py
index a8ec8884d9b,383ada5a1bc..f755c6d478b
--- a/litellm/proxy/response_polling/background_streaming.py
+++ b/litellm/proxy/response_polling/background_streaming.py
@@@ -10,12 -10,9 +10,12 @@@ https://platform.openai.com/docs/api-re
import asyncio
import json
-from typing import Any, Final, cast
+from collections.abc import Callable, Mapping, Sequence
+from typing import TYPE_CHECKING, Final, TypeAlias
from fastapi import Request, Response
+from fastapi.responses import StreamingResponse
- from typing_extensions import TypedDict
++from typing_extensions import ReadOnly, TypedDict
from litellm._logging import verbose_proxy_logger
from litellm.proxy.auth.user_api_key_auth import UserAPIKeyAuth
@@@ -23,56 -20,6 +23,56 @@@ from litellm.proxy.common_request_proce
from litellm.proxy.response_polling.polling_handler import ResponsePollingHandler
from litellm.types.llms.openai import ResponsesAPIStatus
+if TYPE_CHECKING:
+ from litellm.proxy.proxy_server import ProxyConfig
+ from litellm.proxy.utils import ProxyLogging
+ from litellm.router import Router
+
+
+_JsonDict: TypeAlias = dict[str, object]
+_JsonList: TypeAlias = list[object]
+
+
+class _OutputItem(TypedDict, total=False):
- id: str
- content: Sequence[object]
++ id: ReadOnly[str]
++ content: ReadOnly[Sequence[object]]
+
+
+class _TerminalResponse(TypedDict, total=False):
- status: ResponsesAPIStatus
- error: _JsonDict
- usage: _JsonDict
- reasoning: _JsonDict
- tool_choice: object
- tools: _JsonList
- model: str
- instructions: str
- temperature: float
- top_p: float
- max_output_tokens: int
- previous_response_id: str
- text: _JsonDict
- truncation: str
- parallel_tool_calls: bool
- user: str
- store: bool
- incomplete_details: _JsonDict
- output: Sequence[_OutputItem]
++ status: ReadOnly[ResponsesAPIStatus]
++ error: ReadOnly[_JsonDict]
++ usage: ReadOnly[_JsonDict]
++ reasoning: ReadOnly[_JsonDict]
++ tool_choice: ReadOnly[object]
++ tools: ReadOnly[_JsonList]
++ model: ReadOnly[str]
++ instructions: ReadOnly[str]
++ temperature: ReadOnly[float]
++ top_p: ReadOnly[float]
++ max_output_tokens: ReadOnly[int]
++ previous_response_id: ReadOnly[str]
++ text: ReadOnly[_JsonDict]
++ truncation: ReadOnly[str]
++ parallel_tool_calls: ReadOnly[bool]
++ user: ReadOnly[str]
++ store: ReadOnly[bool]
++ incomplete_details: ReadOnly[_JsonDict]
++ output: ReadOnly[Sequence[_OutputItem]]
+
+
+class _StreamEvent(TypedDict, total=False):
- type: str
- item: _OutputItem
- item_id: str
- content_index: int
- delta: str
- part: object
- response: _TerminalResponse
++ type: ReadOnly[str]
++ item: ReadOnly[_OutputItem]
++ item_id: ReadOnly[str]
++ content_index: ReadOnly[int]
++ delta: ReadOnly[str]
++ part: ReadOnly[object]
++ response: ReadOnly[_TerminalResponse]
+
+
+class _StreamEventParser:
+ parse: Callable[[str], _StreamEvent] = staticmethod(json.loads)
+
async def background_streaming_task(
polling_id: str,
@@@ -236,8 -181,9 +236,11 @@@
if item_id and item_id in output_items:
# Update the output item with new content
- if "content" not in output_items[item_id]:
- output_items[item_id]["content"] = []
- output_items[item_id]["content"].append(content_part)
+ added_item = output_items[item_id]
- added_item["content"] = (*added_item.get("content", ()), content_part)
++ output_items[item_id] = {
++ **added_item,
++ "content": (*added_item.get("content", ()), content_part),
++ }
state_dirty = True
elif event_type == "response.output_text.delta":
@@@ -273,14 -217,10 +276,17 @@@
if item_id and item_id in output_items:
# Update with final content from event
- if "content" in output_items[item_id]:
- content_list = output_items[item_id]["content"]
+ done_item = output_items[item_id]
+ if "content" in done_item:
+ content_list = done_item["content"]
if content_index < len(content_list):
- done_item["content"] = tuple(
- content_part if part_index == content_index else existing_part
- for part_index, existing_part in enumerate(content_list)
- )
- content_list[content_index] = content_part
++ output_items[item_id] = {
++ **done_item,
++ "content": tuple(
++ content_part if part_index == content_index else existing_part
++ for part_index, existing_part in enumerate(content_list)
++ ),
++ }
state_dirty = True
elif event_type == "response.output_item.done":
diff --cc litellm/responses/file_search/emulated_handler.py
index 205189a6043,7854b17a06f..47646372935
--- a/litellm/responses/file_search/emulated_handler.py
+++ b/litellm/responses/file_search/emulated_handler.py
@@@ -14,19 -14,16 +14,21 @@@ Flow
import json
import time
import uuid
-from collections.abc import Iterable
-from typing import Any, Final, cast
+from collections.abc import Iterable, Mapping, Sequence
+from typing import TYPE_CHECKING, Any, Final, TypedDict, cast
+
++from typing_extensions import ReadOnly
+
from litellm._internal_context import is_internal_call
from litellm._logging import verbose_logger
-from litellm.types.llms.openai import ResponseOutputItem, ResponsesAPIResponse
+from litellm.types.llms.openai import ResponsesAPIResponse
from litellm.types.vector_stores import VectorStoreSearchResult
+if TYPE_CHECKING:
+ from litellm.llms.base_llm.responses.transformation import BaseResponsesAPIConfig
+
# Keep ToolParam broad so we stay compatible with both dict and Pydantic forms
-ToolParam = Any
+ToolParam = object
FILE_SEARCH_FUNCTION_NAME: Final = "litellm_file_search"
@@@ -408,13 -410,7 +410,13 @@@ def _extract_tool_call_fields(tool_call
return call_id, raw_args
-def _resolve_queries_from_args(args: dict[str, Any], input: Any) -> list[str]:
+class _FileSearchArguments(TypedDict, total=False):
- queries: Sequence[str]
- query: str
- vector_store_id: str
++ queries: ReadOnly[Sequence[str]]
++ query: ReadOnly[str]
++ vector_store_id: ReadOnly[str]
+
+
+def _resolve_queries_from_args(args: _FileSearchArguments, input: object) -> Sequence[str]:
"""Pull the queries list out of parsed tool-call arguments, with backward-compat fallbacks."""
queries_from_call: Final = args.get("queries")
if not queries_from_call:
diff --cc litellm/router_strategy/tag_based_routing.py
index 209dea87cc5,1120323b4f9..eabd9278cf6
--- a/litellm/router_strategy/tag_based_routing.py
+++ b/litellm/router_strategy/tag_based_routing.py
@@@ -10,10 -10,12 +10,12 @@@ Use this to route requests between Team
import re
from collections.abc import Mapping, Sequence
from types import MappingProxyType
-from typing import TYPE_CHECKING, Any, Final, Literal
+from typing import TYPE_CHECKING, Any, Final, Literal, Protocol, overload
from litellm._logging import verbose_logger
- from litellm.types.router import DeploymentTypedDict, RouterErrors
+ from litellm.constants import CONSUMED_REQUEST_TAGS_METADATA_KEY
+ from litellm.litellm_core_utils.core_helpers import get_metadata_variable_name_from_kwargs
-from litellm.types.router import ConsumedRequestTagsStamp, RouterErrors
++from litellm.types.router import ConsumedRequestTagsStamp, DeploymentTypedDict, RouterErrors
if TYPE_CHECKING:
from litellm.router import Router as _Router
@@@ -450,6 -393,25 +452,27 @@@ def _tag_known_to_group
)
-def _request_tags_after_router_consumption(metadata: Mapping[Any, Any], model: str) -> Sequence[str] | None:
++def _request_tags_after_router_consumption(metadata: object, model: str) -> Sequence[str] | None:
+ # The pre-routing hook stamps which tags selected the router it rewrote the request
+ # to: those tags already did their job and must not also constrain deployment choice
+ # inside the routed group. The request's other tags still apply there, on top of the
+ # inherited_tags snapshot that keeps key/team policy applying. Every other model
+ # group keeps the full list.
- stamp: Final = metadata.get(CONSUMED_REQUEST_TAGS_METADATA_KEY)
++ if not isinstance(metadata, Mapping):
++ return None
++ typed_metadata: Final[Mapping[str, object]] = metadata
++ request_tags: Final = _tags_in_metadata(typed_metadata)
++ stamp: Final = typed_metadata.get(CONSUMED_REQUEST_TAGS_METADATA_KEY)
+ if not isinstance(stamp, ConsumedRequestTagsStamp) or stamp.model_group != model:
- return metadata.get("tags")
- request_tags: Final = metadata.get("tags")
- leftover: Final = tuple(
- tag for tag in (request_tags if isinstance(request_tags, (list, tuple)) else ()) if tag not in stamp.tags
- )
- inherited_tags: Final = metadata.get("inherited_tags")
++ return request_tags
++ leftover: Final = tuple(tag for tag in request_tags if tag not in stamp.tags)
++ inherited_tags: Final = typed_metadata.get("inherited_tags")
+ if not isinstance(inherited_tags, (list, tuple)):
+ return leftover or None
- return tuple(dict.fromkeys((*leftover, *inherited_tags)))
++ typed_inherited_tags: Final[Sequence[object]] = inherited_tags
++ return tuple(dict.fromkeys((*leftover, *(tag for tag in typed_inherited_tags if isinstance(tag, str)))))
+
+
async def get_deployments_for_tag(
llm_router_instance: LitellmRouter,
model: str, # used to raise the correct error
@@@ -623,9 -584,27 +646,27 @@@
return healthy_deployments
+ def _tags_in_metadata(metadata: object) -> list[str]:
+ """
+ Tags out of a metadata bucket the caller controls the shape of.
+
+ A request can send its metadata (and its ``tags``) as anything the JSON body
+ allowed, an unparsed string or null included, so any shape that is not a list
+ of string tags carries no tags rather than raising.
+ """
+ if not isinstance(metadata, Mapping):
+ return []
+ typed_metadata: Final[Mapping[str, object]] = metadata
+ tags: Final = typed_metadata.get("tags")
+ if isinstance(tags, str) or not isinstance(tags, Sequence):
+ return []
+ typed_tags: Final[Sequence[object]] = tags
+ return [tag for tag in typed_tags if isinstance(tag, str)]
+
+
def _get_tags_from_request_kwargs(
- request_kwargs: _RequestKwargsLike | None = None,
- metadata_variable_name: Literal["metadata", "litellm_metadata"] = "metadata",
- request_kwargs: Mapping[Any, Any] | None = None,
++ request_kwargs: Mapping[str, object] | None = None,
+ metadata_variable_name: Literal["metadata", "litellm_metadata"] | None = None,
) -> list[str]:
"""
Helper to get tags from request kwargs
diff --cc ruff-strict-budget.json
index 90033af024b,dff010bfd30..3e4a1339208
--- a/ruff-strict-budget.json
+++ b/ruff-strict-budget.json
@@@ -1,6 -1,6 +1,6 @@@
{
"ANN001": {
- "limit": 3036
- "limit": 3058
++ "limit": 3003
},
"ANN002": {
"limit": 71
@@@ -9,7 -9,7 +9,7 @@@
"limit": 827
},
"ANN201": {
- "limit": 2020
- "limit": 2022
++ "limit": 2017
},
"ANN202": {
"limit": 855
@@@ -24,7 -24,7 +24,7 @@@
"limit": 133
},
"ANN401": {
- "limit": 1286
- "limit": 1384
++ "limit": 1139
},
"ASYNC230": {
"limit": 11
@@@ -39,7 -39,7 +39,7 @@@
"limit": 505
},
"B009": {
- "limit": 63
- "limit": 64
++ "limit": 60
},
"B010": {
"limit": 190
@@@ -123,7 -123,7 +123,7 @@@
"limit": 12
},
"PERF403": {
- "limit": 33
- "limit": 34
++ "limit": 30
},
"PIE804": {
"limit": 18
@@@ -180,7 -180,7 +180,7 @@@
"limit": 8
},
"RUF019": {
- "limit": 36
- "limit": 38
++ "limit": 29
},
"RUF046": {
"limit": 4
@@@ -201,7 -201,7 +201,7 @@@
"limit": 58
},
"SIM102": {
- "limit": 318
- "limit": 321
++ "limit": 312
},
"SIM103": {
"limit": 119
@@@ -234,7 -234,7 +234,7 @@@
"limit": 5
},
"TID251": {
- "limit": 1214
- "limit": 1224
++ "limit": 1193
},
"TRY002": {
"limit": 524
diff --cc type-discipline-budget.json
index 83def5fe2e3,a7286d9a89a..e24b793dd92
--- a/type-discipline-budget.json
+++ b/type-discipline-budget.json
@@@ -1,9 -1,9 +1,9 @@@
{
"LIT001": {
- "limit": 22780
- "limit": 23001
++ "limit": 22117
},
"LIT002": {
- "limit": 27144
- "limit": 27146
++ "limit": 27142
},
"LIT003": {
"limit": 269
@@@ -15,7 -15,7 +15,7 @@@
"limit": 0
},
"LIT006": {
- "limit": 1069
- "limit": 1077
++ "limit": 1061
},
"LIT007": {
"limit": 0
@@@ -27,9 -27,12 +27,12 @@@
"limit": 0
},
"LIT010": {
- "limit": 16725
- "limit": 16731
++ "limit": 16703
},
"LIT011": {
- "limit": 5590
- "limit": 5596
++ "limit": 5573
+ },
+ "LIT012": {
- "limit": 4519
++ "limit": 4516
}
}