The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
Merge remote-tracking branch 'origin/litellm_internal_staging' into litellm_daily_any_cleanup_08_04_2026
mateo-berrid259070fdfc0
diff --cc basedpyright-code-budget.jsonindex b030d7c1cde,d3259f88dce..2a00e4704f1--- a/basedpyright-code-budget.json+++ b/basedpyright-code-budget.json@@@ -1,9 -1,9 +1,9 @@@{"reportAny": {- "limit": 29082- "limit": 29809++ "limit": 29207},"reportArgumentType": {- "limit": 2645+ "limit": 2635},"reportAssignmentType": {"limit": 329@@@ -15,34 -15,34 +15,34 @@@"limit": 123},"reportConstantRedefinition": {- "limit": 59+ "limit": 40},"reportDeprecated": {- "limit": 325+ "limit": 215},"reportDuplicateImport": {- "limit": 42+ "limit": 24},"reportExplicitAny": {- "limit": 9198- "limit": 9473++ "limit": 9231},"reportFunctionMemberAccess": {- "limit": 11+ "limit": 7},"reportGeneralTypeIssues": {- "limit": 227+ "limit": 157},"reportIncompatibleMethodOverride": {- "limit": 77+ "limit": 56},"reportIncompatibleVariableOverride": {- "limit": 12+ "limit": 8},"reportInconsistentOverload": {- "limit": 18+ "limit": 12},"reportIndexIssue": {- "limit": 37+ "limit": 35},"reportInvalidTypeForm": {"limit": 35@@@ -54,13 -54,13 +54,13 @@@"limit": 0},"reportMissingParameterType": {- "limit": 5843- "limit": 5855++ "limit": 5850},"reportMissingTypeArgument": {- "limit": 15834- "limit": 15849++ "limit": 15833},"reportMissingTypeStubs": {- "limit": 41+ "limit": 40},"reportOperatorIssue": {"limit": 0@@@ -81,16 -81,16 +81,16 @@@"limit": 0},"reportPossiblyUnboundVariable": {- "limit": 77+ "limit": 56},"reportPrivateUsage": {- "limit": 2437+ "limit": 1825},"reportRedeclaration": {- "limit": 12+ "limit": 8},"reportReturnType": {- "limit": 219+ "limit": 218},"reportTypedDictNotRequiredAccess": {"limit": 27@@@ -99,31 -99,31 +99,31 @@@"limit": 0},"reportUnknownArgumentType": {- "limit": 45277- "limit": 45262++ "limit": 45242},"reportUnknownLambdaType": {"limit": 113},"reportUnknownMemberType": {- "limit": 40303- "limit": 40452++ "limit": 40345},"reportUnknownParameterType": {- "limit": 20285- "limit": 20309++ "limit": 20293},"reportUnknownVariableType": {- "limit": 31883- "limit": 31978++ "limit": 31895},"reportUnnecessaryCast": {- "limit": 175- "limit": 124++ "limit": 122},"reportUnnecessaryComparison": {- "limit": 1021+ "limit": 703},"reportUnnecessaryContains": {- "limit": 7+ "limit": 5},"reportUnnecessaryIsInstance": {- "limit": 1203- "limit": 866++ "limit": 865},"reportUntypedBaseClass": {"limit": 165@@@ -132,15 -132,15 +132,15 @@@"limit": 33},"reportUnusedClass": {- "limit": 33+ "limit": 23},"reportUnusedFunction": {- "limit": 204+ "limit": 139},"reportUnusedImport": {- "limit": 1002- "limit": 588++ "limit": 587},"reportUnusedVariable": {- "limit": 1297+ "limit": 147}}diff --cc litellm/_redis.pyindex e05e9d4eb20,b1c2b16d7f1..ed9f3580162--- a/litellm/_redis.py+++ b/litellm/_redis.py@@@ -394,9 -395,9 +395,7 @@@ def _get_redis_client_logic(**env_overrif _sentinel_password is not None:redis_kwargs["sentinel_password"] = _sentinel_password- _service_name: str | None = redis_kwargs.get("service_name", None) or get_secret( # type: ignore- _service_name: Final[str | None] = redis_kwargs.get("service_name", None) or get_secret(-- "REDIS_SERVICE_NAME"-- )++ _service_name: Final[str | None] = redis_kwargs.get("service_name", None) or get_secret("REDIS_SERVICE_NAME")if _service_name is not None:redis_kwargs["service_name"] = _service_namediff --cc litellm/a2a_protocol/litellm_completion_bridge/handler.pyindex 8d6c5a97f00,fd637a779cc..90a82e8fa28--- a/litellm/a2a_protocol/litellm_completion_bridge/handler.py+++ b/litellm/a2a_protocol/litellm_completion_bridge/handler.py@@@ -10,8 -10,8 +10,8 @@@ A2A Streaming Events (in order)4. Status update (kind: "status-update") - Final status "completed" with final=true"""-from collections.abc import AsyncIterator+from collections.abc import AsyncIterator, Mapping- from typing import Any+ from typing import Any, Finalimport litellmfrom litellm._logging import verbose_logger@@@ -47,23 -45,56 +47,23 @@@ class A2ACompletionBridgeHandler"""@staticmethod- async def handle_non_streaming(- request_id: str,+ def _build_completion_params(params: dict[str, Any],- litellm_params: dict[str, Any],- api_base: str | None = None,- agent_extra_headers: dict[str, str] | None = None,+ litellm_params: Mapping[str, Any],+ api_base: str | None,+ agent_extra_headers: Mapping[str, str] | None,*,- _skip_a2a_provider_routing: bool = False,- ) -> dict[str, Any]:- """- Handle non-streaming A2A request via litellm.acompletion.-- Args:- request_id: A2A JSON-RPC request ID- params: A2A MessageSendParams containing the message- litellm_params: Agent's litellm_params (custom_llm_provider, model, etc.)- api_base: API base URL from agent_card_params- agent_extra_headers: Per-request headers (from x-a2a-{agent}-* rewrite and- admin extra_headers) to forward on the upstream HTTP call.-- Returns:- A2A SendMessageResponse dict- """- custom_llm_provider = litellm_params.get("custom_llm_provider")- if not _skip_a2a_provider_routing:- a2a_provider_config: Final = A2AProviderConfigManager.get_provider_config(- custom_llm_provider=custom_llm_provider,- model=litellm_params.get("model"),- )-- if a2a_provider_config is not None:- verbose_logger.info("A2A: Using provider config for %s", custom_llm_provider)-- return await a2a_provider_config.handle_non_streaming(- request_id=request_id,- params=params,- api_base=api_base,- litellm_params=litellm_params,- agent_extra_headers=agent_extra_headers,- )-+ stream: bool,+ ) -> Mapping[str, Any]:# Extract message from params- message = params.get("message", {})+ message: Final = params.get("message", {})# Transform A2A message to OpenAI format- openai_messages = A2ACompletionBridgeTransformation.a2a_message_to_openai_messages(message)+ openai_messages: Final = A2ACompletionBridgeTransformation.a2a_message_to_openai_messages(message)# Get completion params-- custom_llm_provider = litellm_params.get("custom_llm_provider")- model = litellm_params.get("model", "agent")++ custom_llm_provider: Final = litellm_params.get("custom_llm_provider")+ model: Final = litellm_params.get("model", "agent")# Build full model string if provider specified# Skip prepending if model already starts with the provider prefix@@@ -72,20 -103,17 +72,20 @@@else:full_model = model- verbose_logger.info("A2A completion bridge: model=%s, api_base=%s", full_model, api_base)+ if stream:+ verbose_logger.info("A2A completion bridge streaming: model=%s, api_base=%s", full_model, api_base)+ else:+ verbose_logger.info("A2A completion bridge: model=%s, api_base=%s", full_model, api_base)# Build completion params dict- completion_params: dict[str, Any] = {+ completion_params: Final[dict[str, Any]] = {"model": full_model,"messages": openai_messages,"api_base": api_base,- "stream": False,+ "stream": stream,}# Add litellm_params (contains api_key, client_id, client_secret, tenant_id, etc.)- litellm_params_to_add = {+ litellm_params_to_add: Final = {k: vfor k, v in litellm_params.items()if k not in ("model", "custom_llm_provider") and k not in _AGENT_ONLY_PARAMS@@@ -106,67 -134,11 +106,67 @@@static_headers=completion_params.get("extra_headers"),)+ return completion_params++ @staticmethod+ async def _acompletion(completion_params: Mapping[str, Any]) -> ModelResponse | CustomStreamWrapper:+ return await litellm.acompletion(**completion_params)++ @staticmethod+ async def handle_non_streaming(+ request_id: str,+ params: dict[str, Any],+ litellm_params: dict[str, Any],+ api_base: str | None = None,+ agent_extra_headers: dict[str, str] | None = None,+ *,+ _skip_a2a_provider_routing: bool = False,+ ) -> dict[str, object]:+ """+ Handle non-streaming A2A request via litellm.acompletion.++ Args:+ request_id: A2A JSON-RPC request ID+ params: A2A MessageSendParams containing the message+ litellm_params: Agent's litellm_params (custom_llm_provider, model, etc.)+ api_base: API base URL from agent_card_params+ agent_extra_headers: Per-request headers (from x-a2a-{agent}-* rewrite and+ admin extra_headers) to forward on the upstream HTTP call.++ Returns:+ A2A SendMessageResponse dict+ """- custom_llm_provider = litellm_params.get("custom_llm_provider")++ custom_llm_provider: Final = litellm_params.get("custom_llm_provider")+ if not _skip_a2a_provider_routing:- a2a_provider_config = A2AProviderConfigManager.get_provider_config(++ a2a_provider_config: Final = A2AProviderConfigManager.get_provider_config(+ custom_llm_provider=custom_llm_provider,+ model=litellm_params.get("model"),+ )++ if a2a_provider_config is not None:+ verbose_logger.info("A2A: Using provider config for %s", custom_llm_provider)++ return await a2a_provider_config.handle_non_streaming(+ request_id=request_id,+ params=params,+ api_base=api_base,+ litellm_params=litellm_params,+ agent_extra_headers=agent_extra_headers,+ )+- completion_params = A2ACompletionBridgeHandler._build_completion_params(++ completion_params: Final = A2ACompletionBridgeHandler._build_completion_params(+ params=params,+ litellm_params=litellm_params,+ api_base=api_base,+ agent_extra_headers=agent_extra_headers,+ stream=False,+ )+# Call litellm.acompletion- response = await A2ACompletionBridgeHandler._acompletion(completion_params)- response: Final = await litellm.acompletion(**completion_params)++ response: Final = await A2ACompletionBridgeHandler._acompletion(completion_params)# Transform response to A2A format- a2a_response = A2ACompletionBridgeTransformation.openai_response_to_a2a_response(+ a2a_response: Final = A2ACompletionBridgeTransformation.openai_response_to_a2a_response(response=response,request_id=request_id,)@@@ -205,9 -177,9 +205,9 @@@Yields:A2A streaming response events"""-- custom_llm_provider = litellm_params.get("custom_llm_provider")++ custom_llm_provider: Final = litellm_params.get("custom_llm_provider")if not _skip_a2a_provider_routing:- a2a_provider_config = A2AProviderConfigManager.get_provider_config(+ a2a_provider_config: Final = A2AProviderConfigManager.get_provider_config(custom_llm_provider=custom_llm_provider,model=litellm_params.get("model"),)@@@ -226,22 -198,62 +226,22 @@@return- # Extract message from params- message: Final = params.get("message", {})-# Create streaming context- ctx = A2AStreamingContext(+ ctx: Final = A2AStreamingContext(request_id=request_id,- input_message=message,+ input_message=params.get("message", {}),)- completion_params = A2ACompletionBridgeHandler._build_completion_params(- # Transform A2A message to OpenAI format- openai_messages: Final = A2ACompletionBridgeTransformation.a2a_message_to_openai_messages(message)-- # Get completion params- custom_llm_provider = litellm_params.get("custom_llm_provider")- model: Final = litellm_params.get("model", "agent")-- # Build full model string if provider specified- # Skip prepending if model already starts with the provider prefix- if custom_llm_provider and not model.startswith(f"{custom_llm_provider}/"):- full_model = f"{custom_llm_provider}/{model}"- else:- full_model = model-- verbose_logger.info("A2A completion bridge streaming: model=%s, api_base=%s", full_model, api_base)-- # Build completion params dict- completion_params: Final[dict[str, Any]] = {- "model": full_model,- "messages": openai_messages,- "api_base": api_base,- "stream": True,- }- # Add litellm_params (contains api_key, client_id, client_secret, tenant_id, etc.)- litellm_params_to_add: Final = {- k: v- for k, v in litellm_params.items()- if k not in ("model", "custom_llm_provider") and k not in _AGENT_ONLY_PARAMS- }- completion_params.update(litellm_params_to_add)- # Apply forward metadata AFTER the litellm_params merge so the helper- # sees any agent-owner-configured ``extra_body.metadata`` and can keep- # those keys authoritative over the client-supplied A2A metadata.- A2ACompletionBridgeTransformation.apply_forward_metadata_to_completion_params(- completion_params=completion_params,- a2a_message=message,++ completion_params: Final = A2ACompletionBridgeHandler._build_completion_params(params=params,+ litellm_params=litellm_params,+ api_base=api_base,+ agent_extra_headers=agent_extra_headers,+ stream=True,)- if agent_extra_headers:- completion_params["extra_headers"] = merge_agent_headers(- dynamic_headers=agent_extra_headers,- static_headers=completion_params.get("extra_headers"),- )-# 1. Emit initial task event (kind: "task", status: "submitted")- task_event = A2ACompletionBridgeTransformation.create_task_event(ctx)+ task_event: Final = A2ACompletionBridgeTransformation.create_task_event(ctx)yield task_event# 2. Emit status update (kind: "status-update", status: "working")@@@ -254,7 -266,7 +254,7 @@@yield working_event# Call litellm.acompletion with streaming- response = await A2ACompletionBridgeHandler._acompletion(completion_params)- response: Final = await litellm.acompletion(**completion_params)++ response: Final = await A2ACompletionBridgeHandler._acompletion(completion_params)# 3. Accumulate content and emit artifact updateaccumulated_text = ""diff --cc litellm/google_genai/adapters/handler.pyindex f13a2a21cac,5dafe2befee..8df71504850--- a/litellm/google_genai/adapters/handler.py+++ b/litellm/google_genai/adapters/handler.py@@@ -1,8 -1,7 +1,8 @@@-from collections.abc import AsyncIterator, Coroutine-from typing import Any, Final, cast+from collections.abc import AsyncIterator, Coroutine, Mapping- from typing import cast++from typing import Final, castimport litellm+from litellm.types.google_genai.adapters import GenerateContentCompletionKwargsfrom litellm.types.router import GenericLiteLLMParamsfrom litellm.types.utils import ModelResponse@@@ -35,7 -34,7 +35,7 @@@ class GenerateContentToCompletionHandle**(extra_kwargs or {}),)- completion_kwargs = dict(completion_request)- completion_kwargs: Final[dict[str, Any]] = dict(completion_request)++ completion_kwargs: Final = dict(completion_request)# Forward extra_kwargs that should be passed to completion callif extra_kwargs is not None:@@@ -54,15 -53,15 +54,15 @@@@staticmethodasync def async_generate_content_handler(model: str,- contents: list[dict[str, Any]] | dict[str, Any],+ contents: list[dict[str, object]] | dict[str, object],litellm_params: GenericLiteLLMParams,- config: dict[str, Any] | None = None,+ config: dict[str, object] | None = None,stream: bool = False,- **kwargs,- ) -> dict[str, Any] | AsyncIterator[bytes]:+ **kwargs: object,+ ) -> dict[str, object] | AsyncIterator[bytes]:"""Handle generate_content call asynchronously using completion adapter"""- completion_kwargs = GenerateContentToCompletionHandler._prepare_completion_kwargs(+ completion_kwargs: Final = GenerateContentToCompletionHandler._prepare_completion_kwargs(model=model,contents=contents,config=config,diff --cc litellm/integrations/code_interpreter_interception/handler.pyindex 00ea510e00f,f142f1b88a7..764dd3ed3e0--- a/litellm/integrations/code_interpreter_interception/handler.py+++ b/litellm/integrations/code_interpreter_interception/handler.py@@@ -9,8 -9,7 +9,8 @@@ captured stdout back through the typedimport jsonimport timeimport uuid- from collections.abc import Sequence- from typing import TYPE_CHECKING, Any, Literal, Protocol, TypedDict, runtime_checkable-from typing import Any, Final, Literal, TypedDict, cast++from collections.abc import Mapping, Sequence++from typing import TYPE_CHECKING, Any, Final, Literal, Protocol, TypeAlias, TypedDict, runtime_checkablefrom pydantic import ValidationError@@@ -42,17 -37,14 +42,17 @@@ from litellm.types.utils importModelResponse,)+if TYPE_CHECKING:+ from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj+- LITELLM_CODE_EXECUTION_TOOL_NAME = "litellm_code_execution"- _INTERCEPTION_ACTIVE_KEY = "_code_interpreter_interception_active"- _SANDBOX_KEY = "_code_interpreter_interception_sandbox_key"- _SESSION_SCOPED_KEY = "_code_interpreter_interception_session_scoped"- _CONVERTED_STREAM_KEY = "_code_interpreter_interception_converted_stream"- _LITELLM_METADATA_KEY = "litellm_metadata"- _CACHE_TTL_SECONDS = 15 * 60- _SESSION_SCOPED_PER_IDENTITY_CAP = 10+ LITELLM_CODE_EXECUTION_TOOL_NAME: Final = "litellm_code_execution"+ _INTERCEPTION_ACTIVE_KEY: Final = "_code_interpreter_interception_active"+ _SANDBOX_KEY: Final = "_code_interpreter_interception_sandbox_key"+ _SESSION_SCOPED_KEY: Final = "_code_interpreter_interception_session_scoped"+ _CONVERTED_STREAM_KEY: Final = "_code_interpreter_interception_converted_stream"+ _LITELLM_METADATA_KEY: Final = "litellm_metadata"+ _CACHE_TTL_SECONDS: Final = 15 * 60+ _SESSION_SCOPED_PER_IDENTITY_CAP: Final = 10class CodeExecutionToolCall(TypedDict, total=False):@@@ -117,54 -109,7 +117,61 @@@ class ChatCompletionFunctionToolChoice(CodeExecutionFunctionToolChoice = ResponsesFunctionToolChoice | ChatCompletionFunctionToolChoice-def _extract_session_id(kwargs: dict[str, Any]) -> str | None:+class SandboxToolParams(TypedDict):+ sandbox_provider: str+ api_key: str | None+ api_base: str | None+++class SandboxConfigProtocol(Protocol):+ async def acreate_sandbox(self) -> ContainerHandle: ...++ async def arun_code(self, *, container: ContainerHandle, code: str) -> CodeExecutionResult: ...++ async def adelete_sandbox(self, *, container: ContainerHandle) -> object: ...+++@runtime_checkable+class _SupportsOutput(Protocol):+ output: object++- _CachedContainer = tuple[ContainerHandle, SandboxToolParams | None, float, str | None]++_CachedContainer: TypeAlias = tuple[ContainerHandle, SandboxToolParams | None, float, str | None]+++def _output_item_type(item: object) -> object:+ if isinstance(item, dict):- item_mapping: dict[str, object] = item++ item_mapping: Final[dict[str, object]] = item+ return item_mapping.get("type")+ return getattr(item, "type", None)++++def _response_output(response: object) -> object:++ if isinstance(response, dict):++ response_mapping: Final[Mapping[str, object]] = response++ return response_mapping.get("output", [])++ return getattr(response, "output", []) or []+++++def _tool_call_arguments(arguments: object) -> str:+ if isinstance(arguments, str):+ return arguments+ return "" if arguments is None else str(arguments)++- def _narrow_tool_call(tool_call: dict[str, object]) -> CodeExecutionToolCall:- tool_call_id = tool_call.get("id")- call_id = tool_call.get("call_id")++def _narrow_tool_call(tool_call: Mapping[str, object]) -> CodeExecutionToolCall:++ tool_call_id: Final = tool_call.get("id")++ call_id: Final = tool_call.get("call_id")+ return {+ "id": tool_call_id if isinstance(tool_call_id, str) else None,+ "call_id": call_id if isinstance(call_id, str) else None,+ "type": "function",+ "name": LITELLM_CODE_EXECUTION_TOOL_NAME,+ "arguments": _tool_call_arguments(tool_call.get("arguments")),+ }+++def _extract_session_id(kwargs: dict[str, object]) -> str | None:for meta_key in ("metadata", "litellm_metadata"):meta = kwargs.get(meta_key)if isinstance(meta, dict):@@@ -175,29 -119,16 +182,29 @@@return None- def _extract_identity(kwargs: dict[str, object]) -> str:- identity = kwargs.get("user_api_key_hash")-def _extract_identity(kwargs: dict[str, Any]) -> str:- return kwargs.get("user_api_key_hash") or ""++def _extract_identity(kwargs: Mapping[str, object]) -> str:++ identity: Final = kwargs.get("user_api_key_hash")+ return identity if isinstance(identity, str) else ""-def _resolve_sandbox_tool(sandbox_tool_name: str | None) -> dict[str, Any] | None:+def _resolve_sandbox_tool(sandbox_tool_name: str | None) -> SandboxToolParams | None:+ if sandbox_tool_name is None:+ return Nonetry:from litellm.sandbox.sandbox_tools import resolve_sandbox_toolexcept ImportError:return None- resolved: dict[str, object] | None = resolve_sandbox_tool(sandbox_tool_name)- return resolve_sandbox_tool(sandbox_tool_name)++ resolved: Final[dict[str, object] | None] = resolve_sandbox_tool(sandbox_tool_name)+ if resolved is None:+ return None- provider = resolved.get("sandbox_provider")- api_key = resolved.get("api_key")- api_base = resolved.get("api_base")++ provider: Final = resolved.get("sandbox_provider")++ api_key: Final = resolved.get("api_key")++ api_base: Final = resolved.get("api_base")+ return SandboxToolParams(+ sandbox_provider=provider if isinstance(provider, str) else "",+ api_key=api_key if isinstance(api_key, str) else None,+ api_base=api_base if isinstance(api_base, str) else None,+ )class CodeInterpreterInterceptionLogger(CustomLogger):@@@ -240,16 -171,19 +247,18 @@@litellm_settings: dict[str, Any],callback_specific_params: dict[str, Any],) -> "CodeInterpreterInterceptionLogger":-- params: CodeInterpreterInterceptionConfig = {}-- if "code_interpreter_interception_params" in litellm_settings:-- params = litellm_settings["code_interpreter_interception_params"]- elif isinstance(callback_specific_params.get("code_interpreter_interception"), dict):- params = callback_specific_params["code_interpreter_interception"]- elif "code_interpreter_interception" in callback_specific_params and isinstance(- callback_specific_params["code_interpreter_interception"], dict- ):- params = cast(- CodeInterpreterInterceptionConfig,- callback_specific_params["code_interpreter_interception"],- )++ params: Final[CodeInterpreterInterceptionConfig] = (++ litellm_settings["code_interpreter_interception_params"]++ if "code_interpreter_interception_params" in litellm_settings++ else callback_specific_params["code_interpreter_interception"]++ if isinstance(callback_specific_params.get("code_interpreter_interception"), dict)++ else {}++ )return CodeInterpreterInterceptionLogger.from_config_yaml(params)- async def async_pre_call_deployment_hook(self, kwargs: dict[str, Any], call_type: CallTypes | None) -> dict | None:+ async def async_pre_call_deployment_hook(+ self, kwargs: dict[str, object], call_type: CallTypes | None+ ) -> dict | None:if not kwargs.get("_agentic_loop_depth"):kwargs.pop(_INTERCEPTION_ACTIVE_KEY, None)kwargs.pop(_SANDBOX_KEY, None)@@@ -295,14 -229,13 +304,14 @@@return kwargs@staticmethod- def _strip_interception_metadata(kwargs: dict[str, Any]) -> None:+ def _strip_interception_metadata(kwargs: dict[str, object]) -> None:- metadata = kwargs.get(_LITELLM_METADATA_KEY)+ metadata: Final = kwargs.get(_LITELLM_METADATA_KEY)if not isinstance(metadata, dict):return- current_metadata: dict[str, object] = metadata- filtered_metadata = {++ current_metadata: Final[dict[str, object]] = metadata+ filtered_metadata: Final = {key: value- for key, value in metadata.items()+ for key, value in current_metadata.items()if not is_interception_internal_key(key)and not key.startswith("_agentic_loop")and key != "max_agentic_loops"@@@ -314,9 -247,9 +323,9 @@@kwargs.pop(_LITELLM_METADATA_KEY, None)@staticmethod- def _write_interception_metadata(kwargs: dict[str, Any]) -> None:- metadata = kwargs.get(_LITELLM_METADATA_KEY)- metadata = dict(metadata) if isinstance(metadata, dict) else {}+ def _write_interception_metadata(kwargs: dict[str, object]) -> None:- existing = kwargs.get(_LITELLM_METADATA_KEY)- metadata: dict[str, object] = dict(existing) if isinstance(existing, dict) else {}++ existing: Final = kwargs.get(_LITELLM_METADATA_KEY)++ metadata: Final[dict[str, object]] = dict(existing) if isinstance(existing, dict) else {}for key in (_INTERCEPTION_ACTIVE_KEY, _SANDBOX_KEY, _SESSION_SCOPED_KEY, _CONVERTED_STREAM_KEY):if key in kwargs:metadata[key] = kwargs[key]@@@ -363,23 -296,22 +372,23 @@@}@staticmethod- def _tool_choice_targets_code_interpreter(tool_choice: Any) -> bool:+ def _tool_choice_targets_code_interpreter(tool_choice: object) -> bool:if not isinstance(tool_choice, dict):return False- choice: dict[str, object] = tool_choice- function = choice.get("function")- function: Final = tool_choice.get("function")++ choice: Final[dict[str, object]] = tool_choice++ function: Final = choice.get("function")return (- tool_choice.get("type") == "code_interpreter"- or tool_choice.get("name") == "code_interpreter"- or tool_choice.get("name") == LITELLM_CODE_EXECUTION_TOOL_NAME+ choice.get("type") == "code_interpreter"+ or choice.get("name") == "code_interpreter"+ or choice.get("name") == LITELLM_CODE_EXECUTION_TOOL_NAMEor (isinstance(function, dict) and function.get("name") == LITELLM_CODE_EXECUTION_TOOL_NAME))- def _resolve_provider(self, kwargs: dict[str, Any]) -> str | None:+ def _resolve_provider(self, kwargs: dict[str, object]) -> str | None:- provider = kwargs.get("custom_llm_provider")+ provider: Final = kwargs.get("custom_llm_provider")- if provider:+ if isinstance(provider, str) and provider:return provider- model = kwargs.get("model")+ model: Final = kwargs.get("model")if not isinstance(model, str):return Nonetry:@@@ -436,16 -368,16 +445,16 @@@)await self._prune_expired_cache()- tool_calls = self._agentic_tool_calls(tools)- sandbox_key = self._extract_sandbox_key(kwargs)- is_session = bool(kwargs.get(_SESSION_SCOPED_KEY))- identity = _extract_identity(kwargs) if is_session else None- tool_calls: Final = cast(list[CodeExecutionToolCall], tools.get("tool_calls", []))- sandbox_key: Final = kwargs.get(_SANDBOX_KEY)++ tool_calls: Final = self._agentic_tool_calls(tools)++ sandbox_key: Final = self._extract_sandbox_key(kwargs)+ is_session: Final = bool(kwargs.get(_SESSION_SCOPED_KEY))+ identity: Final = _extract_identity(kwargs) if is_session else Nonecontainer, params = await self._get_or_create_container(cache_key=sandbox_key, identity=identity)try:- container_id = self._container_id(container)- input_list = self._normalize_messages(messages)- code_interpreter_calls: list[CodeInterpreterCall] = []- container_id: Final = cast(str | None, getattr(container, "id", None))++ container_id: Final = self._container_id(container)+ input_list: Final = self._normalize_messages(messages)+ code_interpreter_calls: Final[list[CodeInterpreterCall]] = []for tool_call in tool_calls:arguments = tool_call.get("arguments", "")code = self._parse_code(arguments)@@@ -511,15 -443,15 +520,15 @@@kwargs: dict[str, object],) -> AgenticLoopPlan:await self._prune_expired_cache()- tool_calls = self._agentic_tool_calls(tools)- sandbox_key = self._extract_sandbox_key(kwargs)- is_session = bool(kwargs.get(_SESSION_SCOPED_KEY))- identity = _extract_identity(kwargs) if is_session else None- tool_calls: Final = cast(list[CodeExecutionToolCall], tools.get("tool_calls", []))- sandbox_key: Final = cast(str | None, kwargs.get(_SANDBOX_KEY))++ tool_calls: Final = self._agentic_tool_calls(tools)++ sandbox_key: Final = self._extract_sandbox_key(kwargs)+ is_session: Final = bool(kwargs.get(_SESSION_SCOPED_KEY))- identity: Final = _extract_identity(cast(dict[str, Any], kwargs)) if is_session else None++ identity: Final = _extract_identity(kwargs) if is_session else Nonecontainer, params = await self._get_or_create_container(cache_key=sandbox_key, identity=identity)try:- container_id = self._container_id(container)- tool_results = [- container_id: Final = cast(str | None, getattr(container, "id", None))++ container_id: Final = self._container_id(container)+ tool_results: Final = [await self._build_chat_completion_tool_result(container=container,params=params,@@@ -557,28 -489,10 +566,28 @@@},)+ @staticmethod+ def _container_id(container: ContainerHandle) -> str | None:- container_id: object = getattr(container, "id", None)++ container_id: Final[object] = getattr(container, "id", None)+ return container_id if isinstance(container_id, str) else None++ @staticmethod+ def _agentic_tool_calls(tools: dict[str, object]) -> list[CodeExecutionToolCall]:- tool_calls = tools.get("tool_calls")++ tool_calls: Final = tools.get("tool_calls")+ if not isinstance(tool_calls, list):+ return []- items: list[object] = tool_calls++ items: Final[list[object]] = tool_calls+ return [_narrow_tool_call(item) for item in items if isinstance(item, dict)]++ @staticmethod+ def _extract_sandbox_key(kwargs: dict[str, object]) -> str | None:- sandbox_key = kwargs.get(_SANDBOX_KEY)++ sandbox_key: Final = kwargs.get(_SANDBOX_KEY)+ return sandbox_key if isinstance(sandbox_key, str) else None+async def _build_chat_completion_tool_result(self,- container: object,- params: dict[str, Any] | None,+ container: ContainerHandle,+ params: SandboxToolParams | None,tool_call: CodeExecutionToolCall,container_id: str | None,) -> tuple[ChatCompletionToolMessage, CodeInterpreterCall]:@@@ -603,15 -517,10 +612,15 @@@)async def async_agentic_loop_cleanup_hook(self, plan: AgenticLoopPlan, kwargs: dict) -> None:- metadata: dict[str, object] = plan.metadata or {} if plan else {}- metadata: Final = plan.metadata or {} if plan else {}++ metadata: Final[dict[str, object]] = plan.metadata or {} if plan else {}if metadata.get("is_session_scoped"):return- await self._delete_container_for_cache_key(metadata.get("sandbox_key"))+ await self._delete_container_for_cache_key(self._metadata_sandbox_key(metadata))++ @staticmethod- def _metadata_sandbox_key(metadata: dict[str, object]) -> str | None:- sandbox_key = metadata.get("sandbox_key")++ def _metadata_sandbox_key(metadata: Mapping[str, object]) -> str | None:++ sandbox_key: Final = metadata.get("sandbox_key")+ return sandbox_key if isinstance(sandbox_key, str) else None@staticmethoddef _filter_agentic_loop_kwargs(kwargs: dict[str, object]) -> dict[str, object]:@@@ -640,41 -549,33 +649,41 @@@k: v for k, v in optional_params.items() if k != "tools" and not (k == "tool_choice" and drop_tool_choice)}- async def async_post_agentic_loop_response_hook(self, response: Any, plan: AgenticLoopPlan, kwargs: dict) -> Any:- metadata: Final = plan.metadata or {} if plan else {}+ async def async_post_agentic_loop_response_hook(+ self, response: object, plan: AgenticLoopPlan, kwargs: dict+ ) -> object:- metadata: dict[str, object] = plan.metadata or {} if plan else {}++ metadata: Final[dict[str, object]] = plan.metadata or {} if plan else {}if not metadata.get("is_session_scoped"):- await self._delete_container_for_cache_key(metadata.get("sandbox_key"))+ await self._delete_container_for_cache_key(self._metadata_sandbox_key(metadata))- calls = metadata.get("code_interpreter_calls")+ calls: Final = metadata.get("code_interpreter_calls")- if not calls:+ if not calls or not isinstance(calls, list):return response- is_dict: Final = isinstance(response, dict)- output: Final = response.get("output") if is_dict else getattr(response, "output", None)- if not isinstance(output, list):+ if isinstance(response, dict):- response_mapping: dict[str, object] = response- merged = self._merge_code_interpreter_calls(response_mapping.get("output"), calls)- if merged is not None:- response_mapping["output"] = merged++ response_mapping: Final[dict[str, object]] = response++ merged_mapping_output: Final = self._merge_code_interpreter_calls(response_mapping.get("output"), calls)++ if merged_mapping_output is not None:++ response_mapping["output"] = merged_mapping_outputreturn response- def _item_type(item: Any) -> Any:- return item.get("type") if isinstance(item, dict) else getattr(item, "type", None)+ if not isinstance(response, _SupportsOutput):+ return response- merged = self._merge_code_interpreter_calls(response.output, calls)- if merged is not None:- response.output = merged++ merged_attr_output: Final = self._merge_code_interpreter_calls(response.output, calls)++ if merged_attr_output is not None:++ response.output = merged_attr_output+ return response+ @staticmethod+ def _merge_code_interpreter_calls(output: object, calls: Sequence[object]) -> list[object] | None:+ if not isinstance(output, list):+ return None- items: list[object] = output- insert_at = next(++ items: Final[list[object]] = output+ insert_at: Final = next(- (i for i, item in enumerate(output) if _item_type(item) == "message"),- len(output),+ (i for i, item in enumerate(items) if _output_item_type(item) == "message"),+ len(items),)- new_output: Final = output[:insert_at] + list(calls) + output[insert_at:]- if is_dict:- response["output"] = new_output- else:- response.output = new_output- return response+ return items[:insert_at] + list(calls) + items[insert_at:]@staticmethoddef _parse_code(arguments: str) -> str:@@@ -683,9 -584,9 +692,9 @@@except (json.JSONDecodeError, TypeError, AttributeError):return ""- async def _run_tool_call(self, container: Any, params: dict[str, Any] | None, arguments: str) -> str:+ async def _run_tool_call(self, container: ContainerHandle, params: SandboxToolParams | None, arguments: str) -> str:try:- code = json.loads(arguments).get("code", "") if arguments else ""+ code: Final = json.loads(arguments).get("code", "") if arguments else ""except (json.JSONDecodeError, TypeError):return "[invalid tool arguments: could not parse code]"@@@ -700,9 -601,9 +709,9 @@@self,cache_key: str | None,identity: str | None = None,- ) -> tuple[Any, dict[str, Any] | None]:+ ) -> tuple[ContainerHandle, SandboxToolParams | None]:if cache_key:- cached = self._container_cache.get(cache_key)+ cached: Final = self._container_cache.get(cache_key)if cached is not None:self._container_cache[cache_key] = (cached[0], cached[1], time.time(), cached[3])return cached[0], cached[1]@@@ -786,11 -685,10 +795,7 @@@return []def _extract_code_execution_tool_calls(self, response: object) -> list[CodeExecutionToolCall]:-- if isinstance(response, dict):- response_mapping: dict[str, object] = response- output: object = response_mapping.get("output", [])- output = response.get("output", [])-- else:-- output = getattr(response, "output", []) or []++ output: Final = _response_output(response)if not isinstance(output, list):return []@@@ -804,15 -702,17 +809,15 @@@if self._is_code_execution_call(item)]- def _extract_chat_completion_code_execution_tool_calls(- self, response: ModelResponse | dict[str, Any]- ) -> list[CodeExecutionToolCall]:+ def _extract_chat_completion_code_execution_tool_calls(self, response: object) -> list[CodeExecutionToolCall]:- model_response = self._to_model_response(response)+ model_response: Final = self._to_model_response(response)if model_response is None:return []- choices = model_response.choices or []+ choices: Final = model_response.choices or []if not choices:return []- message = choices[0].message- tool_calls = message.tool_calls or []+ message: Final = choices[0].message+ tool_calls: Final = message.tool_calls or []return [normalized@@@ -843,50 -743,48 +848,50 @@@@staticmethoddef _build_chat_completion_assistant_message(- tool_calls: list[CodeExecutionToolCall],+ tool_calls: Sequence[CodeExecutionToolCall],) -> ChatCompletionAssistantMessage:- assistant_tool_calls: list[ChatCompletionAssistantToolCall] = [++ assistant_tool_calls: Final[list[ChatCompletionAssistantToolCall]] = [+ {+ "id": tool_call.get("id"),+ "type": "function",+ "function": {+ "name": LITELLM_CODE_EXECUTION_TOOL_NAME,+ "arguments": tool_call.get("arguments", ""),+ },+ }+ for tool_call in tool_calls+ ]return {"role": "assistant",- "tool_calls": [- cast(- ChatCompletionAssistantToolCall,- {- "id": tool_call.get("id"),- "type": "function",- "function": {- "name": LITELLM_CODE_EXECUTION_TOOL_NAME,- "arguments": tool_call.get("arguments", ""),- },- },- )- for tool_call in tool_calls- ],+ "tool_calls": assistant_tool_calls,}@staticmethod- def _to_model_response(- response: ModelResponse | dict[str, Any],- ) -> ModelResponse | None:+ def _to_model_response(response: object) -> ModelResponse | None:if isinstance(response, ModelResponse):return response+ if not isinstance(response, dict):+ return None- response_fields: dict[str, object] = response++ response_fields: Final[dict[str, object]] = responsetry:- return ModelResponse(**response)+ return ModelResponse(**response_fields)except (TypeError, ValidationError):return None- def _is_code_execution_call(self, item: Any) -> bool:+ def _is_code_execution_call(self, item: object) -> bool:if isinstance(item, dict):- item_mapping: dict[str, object] = item- return item.get("type") == "function_call" and item.get("name") == LITELLM_CODE_EXECUTION_TOOL_NAME- return (- getattr(item, "type", None) == "function_call"- and getattr(item, "name", None) == LITELLM_CODE_EXECUTION_TOOL_NAME- )++ item_mapping: Final[dict[str, object]] = item+ return (+ item_mapping.get("type") == "function_call"+ and item_mapping.get("name") == LITELLM_CODE_EXECUTION_TOOL_NAME+ )- item_type: object = getattr(item, "type", None)- item_name: object = getattr(item, "name", None)++ item_type: Final[object] = getattr(item, "type", None)++ item_name: Final[object] = getattr(item, "name", None)+ return item_type == "function_call" and item_name == LITELLM_CODE_EXECUTION_TOOL_NAMEasync def _prune_expired_cache(self) -> None:- now = time.time()- expired = [+ now: Final = time.time()+ expired: Final = [(cache_key, container, params)for cache_key, (container, params, last_accessed, *_) in self._container_cache.items()if now - last_accessed > _CACHE_TTL_SECONDSdiff --cc litellm/llms/anthropic/experimental_pass_through/adapters/handler.pyindex c0c8726754e,27754012ea5..a9751489473--- a/litellm/llms/anthropic/experimental_pass_through/adapters/handler.py+++ b/litellm/llms/anthropic/experimental_pass_through/adapters/handler.py@@@ -1,9 -1,5 +1,10 @@@from collections.abc import AsyncIterator, Coroutine, Iterator-from typing import Any, Final, cast+from typing import (+ TYPE_CHECKING,+ Any,++ Final,+ cast,+)import litellmfrom litellm._logging import verbose_logger@@@ -25,12 -21,8 +26,12 @@@ from litellm.types.llms.anthropic_messafrom litellm.types.utils import ModelResponsefrom litellm.utils import get_model_info+if TYPE_CHECKING:+ from litellm.proxy._types import UserAPIKeyAuth+ from litellm.router import Router+# Anthropic-only keys already mapped by the translator; strip on extra_kwargs re-merge.- ANTHROPIC_ONLY_REQUEST_KEYS: frozenset[str] = frozenset({"output_config"})+ ANTHROPIC_ONLY_REQUEST_KEYS: Final[frozenset[str]] = frozenset({"output_config"})def _messages_have_compaction_block(messages: list[dict]) -> bool:@@@ -45,6 -37,6 +46,14 @@@return False++def _proxy_router_fallback() -> "Router | None":++ try:++ from litellm.proxy.proxy_server import llm_router as _proxy_router++ except Exception:++ return None++ return _proxy_router++++def _extract_proxy_litellm_metadata(kwargs: dict[str, Any]) -> dict[str, Any] | None:"""Return ``kwargs["litellm_metadata"]`` when it's a dict; ``None`` otherwise.@@@ -339,12 -334,12 +348,12 @@@ class LiteLLMMessagesToCompletionTransf# Prefix model with "responses/" to route to OpenAI Responses APIcompletion_kwargs["model"] = f"responses/{model}"- auto_summary = is_reasoning_auto_summary_enabled()+ auto_summary: Final = is_reasoning_auto_summary_enabled()- reasoning_effort = completion_kwargs.get("reasoning_effort")- summary = thinking.get("summary")+ reasoning_effort: Final = completion_kwargs.get("reasoning_effort")+ summary: Final = thinking.get("summary")if isinstance(reasoning_effort, str) and reasoning_effort:- reasoning_dict: dict[str, object] = {"effort": reasoning_effort}- reasoning_dict: Final[dict[str, Any]] = {"effort": reasoning_effort}++ reasoning_dict: Final[dict[str, object]] = {"effort": reasoning_effort}if summary:reasoning_dict["summary"] = summaryelif auto_summary:@@@ -533,21 -528,21 +542,17 @@@top_p: float | None = None,output_format: dict | None = None,**kwargs,- ) -> AnthropicMessagesResponse | AsyncIterator[Any] | Iterator[bytes]:+ ) -> AnthropicMessagesResponse | AsyncIterator[bytes] | Iterator[bytes]:"""Handle non-Anthropic models asynchronously using the adapter"""- context_management = kwargs.pop("context_management", None)- additional_drop_params: list[str] | None = kwargs.get("additional_drop_params", None)- litellm_router: Router | None = kwargs.pop("litellm_router", None)- if litellm_router is None:- try:- from litellm.proxy.proxy_server import llm_router as _proxy_router-- litellm_router = _proxy_router- except Exception:- pass+ context_management: Final = kwargs.pop("context_management", None)+ additional_drop_params: Final[list[str] | None] = kwargs.get("additional_drop_params", None)- litellm_router = kwargs.pop("litellm_router", None)- if litellm_router is None:- try:- from litellm.proxy.proxy_server import llm_router as _proxy_router-- litellm_router = _proxy_router- except Exception:- pass++ requested_router: Final[Router | None] = kwargs.pop("litellm_router", None)++ litellm_router: Final[Router | None] = (++ requested_router if requested_router is not None else _proxy_router_fallback()++ )- proxy_litellm_metadata = _extract_proxy_litellm_metadata(kwargs)- user_api_key_auth: UserAPIKeyAuth | None = (+ proxy_litellm_metadata: Final = _extract_proxy_litellm_metadata(kwargs)- user_api_key_auth: Final = (++ user_api_key_auth: Final[UserAPIKeyAuth | None] = (proxy_litellm_metadata.get("user_api_key_auth") if proxy_litellm_metadata is not None else None)@@@ -672,7 -667,7 +677,7 @@@# ``llm_router`` is ``None``, which is safe to call from the bridged# loop. The async ``async_anthropic_messages_handler`` path is# unaffected because it ``await``s within the original event loop.- litellm_router: Router | None = kwargs.pop("litellm_router", None)- litellm_router: Final = kwargs.pop("litellm_router", None)++ litellm_router: Final[Router | None] = kwargs.pop("litellm_router", None)# Skip the async bridge entirely when there is nothing for either the# polyfill or the client-history slice-only fallback to do. The vast@@@ -683,8 -678,8 +688,8 @@@if context_management is None and not _messages_have_compaction_block(messages):polyfill_result: PolyfillResult | None = Noneelse:- proxy_litellm_metadata = _extract_proxy_litellm_metadata(kwargs)- user_api_key_auth: UserAPIKeyAuth | None = (+ proxy_litellm_metadata: Final = _extract_proxy_litellm_metadata(kwargs)- user_api_key_auth: Final = (++ user_api_key_auth: Final[UserAPIKeyAuth | None] = (proxy_litellm_metadata.get("user_api_key_auth") if proxy_litellm_metadata is not None else None)polyfill_result = run_async_function(diff --cc litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.pyindex 9ae13901445,4e9cc508d3e..2d7589a8715--- a/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py+++ b/litellm/llms/anthropic/experimental_pass_through/adapters/streaming_iterator.py@@@ -4,14 -4,8 +4,15 @@@ import copimport jsonimport tracebackfrom collections import deque-from collections.abc import AsyncIterator, Iterator-from typing import TYPE_CHECKING, Any, Final, Literal, get_args+from collections.abc import AsyncIterator, Iterator, Sequence+from typing import (+ TYPE_CHECKING,+ Any,++ Final,+ Literal,+ Protocol,+ get_args,+)from typing_extensions import assert_never@@@ -33,28 -25,9 +34,28 @@@ if TYPE_CHECKINGfrom litellm.types.utils import ModelResponseStream- _STREAMING_DELTA_TYPES = frozenset(get_args(StreamingContentBlockDeltaType))+ _STREAMING_DELTA_TYPES: Final = frozenset(get_args(StreamingContentBlockDeltaType))+class _UsageDeltaWithIterations(UsageDelta, total=False):+ iterations: list[UsageIteration]+++class _ChunkStream(Protocol):+ def __iter__(self) -> "Iterator[ModelResponseStream]": ...++ def __aiter__(self) -> "AsyncIterator[ModelResponseStream]": ...+++def _optional_attr(obj: object, name: str) -> object:+ return getattr(obj, name, None)+++def _optional_attr_sequence(obj: object, name: str) -> Sequence[object]:- value = getattr(obj, name, None)++ value: Final = getattr(obj, name, None)+ return value if value else ()++def _delta_payload_field(delta_type: StreamingContentBlockDeltaType) -> str:match delta_type:case "text_delta":@@@ -89,22 -62,22 +90,22 @@@ class _CombinedChunkSplitterwould advance them out of sync."""- def __init__(self, completion_stream: Any):- self._stream = completion_stream- self._sync_iter: Iterator[Any] | None = None- self._async_iter: AsyncIterator[Any] | None = None- self._buffer: deque = deque()+ def __init__(self, completion_stream: _ChunkStream):+ self._stream: _ChunkStream = completion_stream+ self._sync_iter: Iterator[ModelResponseStream] | None = None+ self._async_iter: AsyncIterator[ModelResponseStream] | None = None+ self._buffer: deque[ModelResponseStream] = deque()@staticmethod- def _is_combined(chunk: Any) -> bool:+ def _is_combined(chunk: "ModelResponseStream") -> bool:"""True if ``chunk`` carries response content AND a finish_reason."""- choices = _optional_attr_sequence(chunk, "choices")- choices: Final = getattr(chunk, "choices", None)++ choices: Final = _optional_attr_sequence(chunk, "choices")if not choices:return False- choice = choices[0]+ choice: Final = choices[0]- if getattr(choice, "finish_reason", None) is None:+ if _optional_attr(choice, "finish_reason") is None:return False- delta = _optional_attr(choice, "delta")- delta: Final = getattr(choice, "delta", None)++ delta: Final = _optional_attr(choice, "delta")if delta is None:return Falsereturn bool(@@@ -146,21 -119,21 +147,21 @@@normalized to ``reasoning_content`` so the synthesized block startstays empty and the thinking text is emitted exactly once."""- choices = _optional_attr_sequence(chunk, "choices")- choices: Final = getattr(chunk, "choices", None)- if not choices or len(choices) != 1:++ choices: Final = _optional_attr_sequence(chunk, "choices")+ if len(choices) != 1:return (chunk,)- delta = _optional_attr(choices[0], "delta")- delta: Final = getattr(choices[0], "delta", None)++ delta: Final = _optional_attr(choices[0], "delta")if delta is None:return (chunk,)- tool_calls = _optional_attr_sequence(delta, "tool_calls")- tool_calls: Final = getattr(delta, "tool_calls", None)++ tool_calls: Final = _optional_attr_sequence(delta, "tool_calls")if tool_calls and not any(- getattr(getattr(tool_call, "function", None), "name", None) for tool_call in tool_calls+ _optional_attr(_optional_attr(tool_call, "function"), "name") for tool_call in tool_calls):return (chunk,)- present_groups = tuple(+ present_groups: Final = tuple(groupfor group in _CombinedChunkSplitter._PAYLOAD_FIELD_GROUPS- if any(getattr(delta, field, None) for field in group)+ if any(_optional_attr(delta, field) for field in group))if len(present_groups) <= 1:return (chunk,)@@@ -376,11 -349,11 +377,11 @@@ class AnthropicStreamWrapper(AdapterComif not isinstance(usage, dict) or "iterations" in usage:return message_delta_chunk- input_tokens = usage.get("input_tokens", 0) or 0- output_tokens = usage.get("output_tokens", 0) or 0- augmented = message_delta_chunk.copy()- augmented_usage: _UsageDeltaWithIterations = {**usage}- iterations: list[UsageIteration] = list(self.iterations_usage)+ input_tokens: Final = usage.get("input_tokens", 0) or 0+ output_tokens: Final = usage.get("output_tokens", 0) or 0+ augmented: Final = message_delta_chunk.copy()- augmented_usage: Final = dict(usage)++ augmented_usage: Final[_UsageDeltaWithIterations] = {**usage}+ iterations: Final[list[UsageIteration]] = list(self.iterations_usage)# Only emit a ``message`` iteration when we have real token data.# Without a separate usage chunk (e.g. provider sent finish_reason# alone), the held ``message_delta`` carries placeholder zeros fromdiff --cc litellm/proxy/_experimental/mcp_server/sampling_handler.pyindex e2cb38f11f8,0f5c02bd781..0896c344f05--- a/litellm/proxy/_experimental/mcp_server/sampling_handler.py+++ b/litellm/proxy/_experimental/mcp_server/sampling_handler.py@@@ -12,7 -12,7 +12,7 @@@ MCP Spec Referenceimport typingfrom collections.abc import Mapping, Sequence- from typing import Any, NamedTuple, Optional, Protocol, Union, runtime_checkable-from typing import Any, Final, NamedTuple, Optional, Protocol, Union++from typing import Any, Final, NamedTuple, Optional, Protocol, Union, runtime_checkableif typing.TYPE_CHECKING:from fastapi import Request@@@ -315,57 -316,52 +323,57 @@@ def _convert_single_content"""import json- content_type: str | None = getattr(content, "type", None)- content_type: Final = getattr(content, "type", None)++ content_type: Final[str | None] = getattr(content, "type", None)if content_type == "text":+ if not isinstance(content, _TextContentLike):+ raise AttributeError(f"{type(content).__name__!r} object has no attribute 'text'")return {"type": "text", "text": content.text}elif content_type == "image":- data: str = getattr(content, "data", "")- mime_type: str = getattr(content, "mimeType", "image/png")- data = getattr(content, "data", "")- mime_type = getattr(content, "mimeType", "image/png")++ image_data: Final[str] = getattr(content, "data", "")++ image_mime_type: Final[str] = getattr(content, "mimeType", "image/png")return {"type": "image_url",-- "image_url": {"url": f"data:{mime_type};base64,{data}"},++ "image_url": {"url": f"data:{image_mime_type};base64,{image_data}"},}elif content_type == "audio":-- data = getattr(content, "data", "")-- mime_type = getattr(content, "mimeType", "audio/wav")++ audio_data: Final[str] = getattr(content, "data", "")++ audio_mime_type: Final[str] = getattr(content, "mimeType", "audio/wav")# Map MIME type to OpenAI audio format- format_map = {+ format_map: Final = {"audio/wav": "wav","audio/mp3": "mp3","audio/mpeg": "mp3","audio/flac": "flac","audio/ogg": "ogg",}- audio_format = format_map.get(mime_type, "wav")- audio_format: Final = format_map.get(mime_type, "wav")++ audio_format: Final = format_map.get(audio_mime_type, "wav")return {"type": "input_audio",-- "input_audio": {"data": data, "format": audio_format},++ "input_audio": {"data": audio_data, "format": audio_format},}elif content_type == "tool_use":# ToolUseContent → proper OpenAI function-call representation.# The ``_marker_type`` key lets the message-level converter# hoist this into the ``tool_calls`` array on the assistant# message instead of embedding it inline as a content part.- tool_use_id: str = getattr(content, "id", f"call_{id(content)}")- tool_name: str = getattr(content, "name", "")- tool_input: dict[str, object] = getattr(content, "input", {})++ tool_use_id: Final[str] = getattr(content, "id", f"call_{id(content)}")++ tool_name: Final[str] = getattr(content, "name", "")++ tool_input: Final[dict[str, object]] = getattr(content, "input", {})return {"_marker_type": "tool_use",- "id": getattr(content, "id", f"call_{id(content)}"),+ "id": tool_use_id,"type": "function","function": {- "name": getattr(content, "name", ""),- "arguments": json.dumps(getattr(content, "input", {}), default=str),+ "name": tool_name,+ "arguments": json.dumps(tool_input, default=str),},}elif content_type == "tool_result":# ToolResultContent → proper OpenAI tool-role message.# Marked so the message-level converter can emit it as a# separate ``{"role": "tool", ...}`` message.- tool_use_id = getattr(content, "toolUseId", "")- nested_content: Sequence[ContentBlock] = getattr(content, "content", [])- tool_use_id: Final = getattr(content, "toolUseId", "")++ tool_result_use_id: Final = getattr(content, "toolUseId", "")+ nested_content: Final[Sequence[ContentBlock]] = getattr(content, "content", [])if isinstance(nested_content, list):text_parts = [getattr(c, "text", str(c)) for c in nested_content if getattr(c, "type", None) == "text"]result_text = "\n".join(text_parts) if text_parts else ""@@@ -374,7 -370,7 +382,7 @@@return {"_marker_type": "tool_result","role": "tool",-- "tool_call_id": tool_use_id,++ "tool_call_id": tool_result_use_id,"content": result_text,}# Fallback: treat as text@@@ -633,21 -613,6 +641,21 @@@ class _SamplingCompletionResponse(Protodef model(self) -> str | None: ...- _TOOL_ARGUMENTS_ADAPTER = TypeAdapter(dict[str, object])++_TOOL_ARGUMENTS_ADAPTER: Final = TypeAdapter(dict[str, object])+++def _parse_tool_arguments(arguments: object) -> "dict[str, object]":+ """Decode OpenAI tool-call arguments into the MCP ``input`` mapping."""+ import json++ if not isinstance(arguments, str):+ return _TOOL_ARGUMENTS_ADAPTER.validate_python(arguments)+ try:+ return _TOOL_ARGUMENTS_ADAPTER.validate_python(json.loads(arguments))+ except (json.JSONDecodeError, TypeError):+ return {"raw": arguments}++def _convert_openai_response_to_mcp_result(response: _SamplingCompletionResponse,model_name: str,@@@ -682,12 -647,12 +690,12 @@@stop_reason = "maxTokens"else:stop_reason = "endTurn"- actual_model: str = getattr(response, "model", model_name) or model_name+ actual_model: Final[str] = getattr(response, "model", model_name) or model_name# Check if response has tool calls- tool_calls = message.tool_calls if hasattr(message, "tool_calls") else None- tool_calls: Final = getattr(message, "tool_calls", None)++ tool_calls: Final = message.tool_calls if hasattr(message, "tool_calls") else Noneif tool_calls:# Build ToolUseContent items- content_parts: list[SamplingMessageContentBlock] = []+ content_parts: Final[list[SamplingMessageContentBlock]] = []# Include text content if presentif message.content:content_parts.append(TextContent(type="text", text=message.content))@@@ -1138,7 -1109,7 +1146,7 @@@ async def _build_completion_kwargsmessages=params.messages,system_prompt=params.systemPrompt,)- completion_kwargs: dict[str, object] = {- completion_kwargs: dict[str, Any] = {++ completion_kwargs: Final[dict[str, object]] = {"model": model,"messages": openai_messages,"max_tokens": params.maxTokens,@@@ -1147,26 -1118,28 +1155,25 @@@completion_kwargs["temperature"] = params.temperatureif params.stopSequences:completion_kwargs["stop"] = params.stopSequences- openai_tools = _convert_mcp_tools_to_openai(params.tools)+ openai_tools: Final = _convert_mcp_tools_to_openai(params.tools)if openai_tools:completion_kwargs["tools"] = openai_tools- openai_tool_choice = _convert_mcp_tool_choice_to_openai(params.toolChoice)+ openai_tool_choice: Final = _convert_mcp_tool_choice_to_openai(params.toolChoice)if openai_tool_choice is not None:completion_kwargs["tool_choice"] = openai_tool_choice- completion_kwargs["metadata"] = {}- if params.metadata:- completion_kwargs["metadata"]["mcp_metadata"] = params.metadata+ completion_kwargs["metadata"] = {"mcp_metadata": params.metadata} if params.metadata else {}from litellm.proxy.litellm_pre_call_utils import add_litellm_data_to_requestfrom litellm.proxy.proxy_server import proxy_configcompletion_kwargs["user"] = getattr(user_api_key_auth, "user_id", None)- _dummy_request = _build_sampling_request(raw_headers=raw_headers, client_ip=client_ip)- completion_kwargs = await add_litellm_data_to_request(+ _dummy_request: Final = _build_sampling_request(raw_headers=raw_headers, client_ip=client_ip)- completion_kwargs = await add_litellm_data_to_request(++ return await add_litellm_data_to_request(data=completion_kwargs,request=_dummy_request,user_api_key_dict=user_api_key_auth,proxy_config=proxy_config,)-- return completion_kwargsasync def _run_guardrails_and_call_llm(diff --cc litellm/proxy/hooks/parallel_request_limiter_v3.pyindex 09087a6b994,2725da1ee12..32d1fd5a4f7--- a/litellm/proxy/hooks/parallel_request_limiter_v3.py+++ b/litellm/proxy/hooks/parallel_request_limiter_v3.py@@@ -12,14 -12,7 +12,16 @@@ from collections.abc import Callable, Sfrom contextvars import ContextVarfrom dataclasses import dataclass, fieldfrom datetime import datetime-from typing import TYPE_CHECKING, Any, Final, Literal, TypedDict, Union, cast+from typing import (+ TYPE_CHECKING,+ Any,++ Final,+ Literal,+ Protocol,++ TypeAlias,+ TypedDict,+ Union,+)from litellm import DualCachefrom litellm._logging import verbose_proxy_logger@@@ -298,16 -290,9 +300,16 @@@ _TPM_FLOOR_FRACTION: Final =# considered leaked (worker crashed without any release callback firing) and# pruned. Also the longest request duration the gauge can track: a request# running longer than this stops occupying its slot.- PARALLEL_REQUEST_SLOT_TTL_SECONDS = 3600+ PARALLEL_REQUEST_SLOT_TTL_SECONDS: Final = 3600- CacheCounterValue = int | float | str | bytes++CacheCounterValue: TypeAlias = int | float | str | bytes+- CacheCounterValues = Sequence[CacheCounterValue | None]++CacheCounterValues: TypeAlias = Sequence[CacheCounterValue | None]+- ParallelGaugeCacheValue = dict[str, object] | int | float | str | bytes++ParallelGaugeCacheValue: TypeAlias = dict[str, object] | int | float | str | bytes++class RateLimitDescriptorRateLimitObject(TypedDict, total=False):requests_per_unit: int | Nonetokens_per_unit: int | None@@@ -350,42 -335,6 +352,42 @@@ class RateLimitResponseWithDescriptors(response: RateLimitResponse+class WindowKeyMetadata(TypedDict):+ requests_limit: int | None+ tokens_limit: int | None+ window_size: int+ descriptor_key: str+++class AtomicCounterMeta(TypedDict):+ descriptor_key: str+ current_limit: int+ rate_limit_type: Literal["requests", "tokens"]+ window_key: str+ counter_key: str+ increment: int+ ttl: int+ window_size: int+++class AtomicCounterState(TypedDict):+ window_expired: bool+ current: int++- DescriptorAtomicGroup = tuple[list[str], list[int], list[AtomicCounterMeta]]++DescriptorAtomicGroup: TypeAlias = tuple[list[str], list[int], list[AtomicCounterMeta]]+++class CallTypeRateLimiter(Protocol):+ async def async_pre_call_hook(+ self,+ user_api_key_dict: UserAPIKeyAuth,+ cache: DualCache,+ data: dict[str, object],+ call_type: str,+ ) -> Exception | str | dict[str, object] | None: ...++@dataclass(slots=True)class RequestRateLimiterStash:"""@@@ -655,7 -604,7 +657,7 @@@ class _PROXY_MaxParallelRequestsHandlerImplement sliding window rate limiting logic using in-memory cache operations.This follows the same logic as the Redis Lua script but uses async cache operations."""- results: list[CacheCounterValue | None] = []- results: Final[list[Any]] = []++ results: Final[list[CacheCounterValue | None]] = []# Process each window/counter pairfor i in range(0, len(keys), 2):@@@ -868,8 -792,8 +870,8 @@@if self.batch_rate_limiter_script is None:return []- key_groups = self._group_keys_by_hash_tag(keys_to_fetch)- all_cache_values: list[CacheCounterValue | None] = []+ key_groups: Final = self._group_keys_by_hash_tag(keys_to_fetch)- all_cache_values: Final = []++ all_cache_values: Final[list[CacheCounterValue | None]] = []for hash_tag, group_keys in key_groups.items():try:@@@ -937,7 -861,7 +939,7 @@@windowed_response = RateLimitResponse(overall_code="OK", statuses=[])if keys_to_fetch:## CHECK IN-MEMORY CACHE- cache_values = await self._batch_get_counter_values(- cache_values = await self.internal_usage_cache.async_batch_get_cache(++ cache_values = await self._batch_get_counter_values( # rebind-ok: refreshed by the Redis read below when the in-memory pass is under limitkeys=keys_to_fetch,parent_otel_span=parent_otel_span,local_only=True,@@@ -951,7 -875,7 +953,7 @@@## IF under limit in-memory, check Redisif read_only:# READ-ONLY MODE: Just read current values without incrementing- cache_values = await self._batch_get_counter_values(- cache_values = await self.internal_usage_cache.async_batch_get_cache(++ cache_values = await self._batch_get_counter_values( # rebind-ok: read-only mode replaces the in-memory snapshot with Redis valueskeys=keys_to_fetch,parent_otel_span=parent_otel_span,local_only=False, # Check Redis too@@@ -959,7 -883,9 +961,9 @@@# For keys that don't exist yet, set them to 0if cache_values is None:- cache_values = [str(now_int) if key.endswith(":window") else 0 for key in keys_to_fetch]- cache_values = []- for _ in keys_to_fetch:- cache_values.append(str(now_int) if _.endswith(":window") else 0)++ cache_values = [ # rebind-ok: missing keys default to a zeroed window snapshot++ str(now_int) if key.endswith(":window") else 0 for key in keys_to_fetch++ ]elif self.batch_rate_limiter_script is not None:# NORMAL MODE: Increment counters in Redis# Group keys by hash tag for Redis cluster compatibility@@@ -1024,9 -950,9 +1028,9 @@@list with its per-window metadata, and the concurrency gauges fordescriptors carrying a max_parallel_requests limit."""- keys_to_fetch: list[str] = []- key_metadata: dict[str, WindowKeyMetadata] = {}- gauges: list[ParallelRequestGauge] = []+ keys_to_fetch: Final[list[str]] = []- key_metadata: Final[dict[str, dict[str, Any]]] = {}++ key_metadata: Final[dict[str, WindowKeyMetadata]] = {}+ gauges: Final[list[ParallelRequestGauge]] = []for descriptor in descriptors:descriptor_key = descriptor["key"]descriptor_value = descriptor["value"]@@@ -1118,7 -1044,7 +1122,7 @@@if read_only:if self.parallel_count_script is not None:try:- raw_counts: list[CacheCounterValue] = await self.parallel_count_script(- raw_counts: Final = await self.parallel_count_script(++ raw_counts: Final[list[CacheCounterValue]] = await self.parallel_count_script(keys=gauge_keys,args=[PARALLEL_REQUEST_SLOT_TTL_SECONDS for _ in gauges],)@@@ -1147,7 -1073,7 +1151,7 @@@if self.parallel_acquire_script is not None:try:- raw: list[CacheCounterValue] = await self.parallel_acquire_script(- raw: Final = await self.parallel_acquire_script(++ raw: Final[list[CacheCounterValue]] = await self.parallel_acquire_script(keys=gauge_keys,args=[arg for gauge in gauges for arg in (gauge["limit"], PARALLEL_REQUEST_SLOT_TTL_SECONDS, slot_id)@@@ -1183,9 -1109,10 +1187,9 @@@gauge_keys: list[str],parent_otel_span: Span | None = None,) -> list[int]:- values = await self._batch_get_gauge_values(- values: Final = await self.internal_usage_cache.async_batch_get_cache(++ values: Final = await self._batch_get_gauge_values(keys=gauge_keys,parent_otel_span=parent_otel_span,- local_only=True,)if values is None:return [0 for _ in gauge_keys]@@@ -1207,11 -1134,11 +1211,11 @@@an integer counter (not discarded as an empty registry, which wouldbriefly double the admitted concurrency during a Redis outage)."""- now = self._get_current_time().timestamp()- cutoff = now - PARALLEL_REQUEST_SLOT_TTL_SECONDS- states: list[tuple[dict[str, float] | None, int]] = []+ now: Final = self._get_current_time().timestamp()+ cutoff: Final = now - PARALLEL_REQUEST_SLOT_TTL_SECONDS+ states: Final[list[tuple[dict[str, float] | None, int]]] = []for gauge in gauges:- raw_value = await self.internal_usage_cache.async_get_cache(+ raw_value: ParallelGaugeCacheValue | None = await self.internal_usage_cache.async_get_cache(key=gauge["counter_key"],litellm_parent_otel_span=parent_otel_span,local_only=True,@@@ -1266,7 -1193,7 +1270,7 @@@returnif self.parallel_release_script is not None:try:- raw: list[CacheCounterValue] = await self.parallel_release_script(- raw: Final = await self.parallel_release_script(++ raw: Final[list[CacheCounterValue]] = await self.parallel_release_script(keys=counter_keys,args=[slot_id for _ in counter_keys],)@@@ -1343,7 -1270,7 +1347,7 @@@# Build per-descriptor (keys, args, meta) groups. All keys within a# group share the descriptor's {key:value} hash tag, so a single Lua# call per group never triggers CROSSSLOT on Redis Cluster.- descriptor_groups: list[DescriptorAtomicGroup] = []- descriptor_groups: Final[list[tuple[list[str], list[Any], list[dict[str, Any]]]]] = []++ descriptor_groups: Final[list[DescriptorAtomicGroup]] = []for descriptor, increment_amounts in zip(descriptors, increments):keys, args, meta = self._build_descriptor_atomic_payload(descriptor=descriptor,@@@ -1366,7 -1293,7 +1370,9 @@@parent_otel_span=parent_otel_span,)- flat_meta: list[AtomicCounterMeta] = [m for _keys, _args, group_meta in descriptor_groups for m in group_meta]- flat_meta: list[dict[str, Any]] = [m for _keys, _args, group_meta in descriptor_groups for m in group_meta]++ flat_meta: Final[list[AtomicCounterMeta]] = [++ m for _keys, _args, group_meta in descriptor_groups for m in group_meta++ ]async with self._check_and_increment_lock:return await self._atomic_check_and_increment_in_memory(per_counter_meta=flat_meta,@@@ -1382,20 -1309,20 +1388,20 @@@Build (KEYS, ARGV, per-counter meta) for a single descriptor's Luacall. All keys returned share the descriptor's {key:value} hash tag."""- descriptor_key = descriptor["key"]- descriptor_value = descriptor["value"]- rate_limit: RateLimitDescriptorRateLimitObject = (+ descriptor_key: Final = descriptor["key"]+ descriptor_value: Final = descriptor["value"]+ rate_limit: Final[RateLimitDescriptorRateLimitObject] = (descriptor.get("rate_limit") or RateLimitDescriptorRateLimitObject())- window_size = rate_limit.get("window_size") or self.window_size- window_key = f"{{{descriptor_key}:{descriptor_value}}}:window"+ window_size: Final = rate_limit.get("window_size") or self.window_size+ window_key: Final = f"{{{descriptor_key}:{descriptor_value}}}:window"- keys: list[str] = []- args: list[int] = []- meta: list[AtomicCounterMeta] = []+ keys: Final[list[str]] = []- args: Final[list[Any]] = []- meta: Final[list[dict[str, Any]]] = []++ args: Final[list[int]] = []++ meta: Final[list[AtomicCounterMeta]] = []- rate_limit_types: tuple[Literal["requests", "tokens"], ...] = ("requests", "tokens")- for rate_limit_type in ("requests", "tokens"):- rlt: Literal["requests", "tokens"] = cast(Literal["requests", "tokens"], rate_limit_type)++ rate_limit_types: Final[tuple[Literal["requests", "tokens"], ...]] = ("requests", "tokens")+ for rlt in rate_limit_types:if rlt == "requests":limit_value = rate_limit.get("requests_per_unit")inc_amount = int(increment_amounts.get("requests", 0) or 0)@@@ -1440,9 -1367,8 +1446,9 @@@descriptor i, refund descriptors 0..i-1's increments. On Lua failuremid-loop, refund applied increments and fall back to in-memory."""- applied: list[list[AtomicCounterMeta]] = []- statuses: list[RateLimitStatus] = []- applied: Final[list[list[dict[str, Any]]]] = []++ applied: Final[list[list[AtomicCounterMeta]]] = []+ statuses: Final[list[RateLimitStatus]] = []+ raw: list[CacheCounterValue]for _idx, (keys, args, meta) in enumerate(descriptor_groups):try:@@@ -1571,13 -1497,13 +1577,13 @@@"""# Use a single 'now' for the duration of this critical section so all# descriptors evaluate window expiry consistently.- now_int = int(self._get_current_time().timestamp())+ now_int: Final = int(self._get_current_time().timestamp())# Pass 1: read state, validate.- descriptor_state: list[AtomicCounterState] = []- descriptor_state: Final[list[dict[str, Any]]] = []++ descriptor_state: Final[list[AtomicCounterState]] = []for meta in per_counter_meta:window_size = meta["window_size"]- window_start = await self.internal_usage_cache.async_get_cache(+ window_start: CacheCounterValue | None = await self.internal_usage_cache.async_get_cache(key=meta["window_key"],litellm_parent_otel_span=parent_otel_span,local_only=True,@@@ -2310,10 -2238,10 +2316,10 @@@# Fail safe: enforce limits if we can't checkreturn True- def get_rate_limiter_for_call_type(self, call_type: str) -> Any | None:+ def get_rate_limiter_for_call_type(self, call_type: str) -> CallTypeRateLimiter | None:"""Get the rate limiter for the call type."""if call_type == "acreate_batch":- batch_limiter = self._get_batch_rate_limiter()+ batch_limiter: Final = self._get_batch_rate_limiter()return batch_limiterreturn None@@@ -2845,7 -2773,7 +2851,7 @@@``x-ratelimit-{descriptor_key}-{remaining|limit}-{rate_limit_type}``entries. Non-mutating so callers pick their own target dict."""- merged: dict[str, object] = dict(additional_headers)- merged: Final[dict[str, Any]] = dict(additional_headers)++ merged: Final[dict[str, object]] = dict(additional_headers)for status in statuses:prefix = f"x-ratelimit-{status['descriptor_key']}"merged[f"{prefix}-remaining-{status['rate_limit_type']}"] = status["limit_remaining"]diff --cc litellm/proxy/pass_through_endpoints/managed_id_rewriter.pyindex 72ca942fe21,002ddd27e32..04f1390540e--- a/litellm/proxy/pass_through_endpoints/managed_id_rewriter.py+++ b/litellm/proxy/pass_through_endpoints/managed_id_rewriter.py@@@ -32,8 -32,7 +32,8 @@@ from __future__ import annotationimport jsonimport re-from typing import Any, Final+from collections.abc import Callable, Mapping, Sequence- from typing import TYPE_CHECKING, TypeVar, overload++from typing import TYPE_CHECKING, Final, TypeVar, overloadfrom urllib.parse import quote, unquotefrom fastapi import HTTPException@@@ -68,12 -51,6 +68,14 @@@ from litellm.types.passthrough_endpointfrom .managed_id_codec import ManagedIdPayload, decode, is_managed, new_managed_id+if TYPE_CHECKING:+ from litellm.integrations.custom_logger import CustomLogger+ from litellm.proxy.utils import PrismaClient+- _RowT = TypeVar("_RowT", bound=ManagedResourceRow)++_RowT = TypeVar(++ "_RowT", bound=ManagedResourceRow++) # rebind-ok: TypeVar declarations must stay bare assignments for pyright+# ---------------------------------------------------------------------------# Field map# ---------------------------------------------------------------------------@@@ -220,7 -197,7 +222,7 @@@ class _RawIdGuardBudget# ---------------------------------------------------------------------------# Maps (provider, canonical_path) -> "files" | "batches"- _LIST_ROUTE_TABLE: dict[tuple[str, str], ResourceKind] = {-_LIST_ROUTE_TABLE: Final[dict[tuple[str, str], str]] = {++_LIST_ROUTE_TABLE: Final[dict[tuple[str, str], ResourceKind]] = {("openai", "/v1/files"): "files",("openai", "/v1/batches"): "batches",("azure", "/v1/files"): "files",@@@ -336,9 -305,9 +338,9 @@@ async def _resolve_one# 2. DB lookup — pick table based on raw ID prefixif any(raw_id.startswith(p) for p in _FILE_PREFIXES):# File table — use hook's internal cache for speed when available- if managed_files_hook is not None:+ if isinstance(managed_files_hook, ManagedFileIdReader):try:- file_row = await managed_files_hook.get_unified_file_id(+ file_row: Final = await managed_files_hook.get_unified_file_id(managed_id,litellm_parent_otel_span=None,)@@@ -353,7 -322,9 +355,7 @@@)if not found and prisma_client is not None:try:- db_row = await _file_table(prisma_client).find_first(where={"unified_file_id": managed_id})- db_row: Final = await ManagedFileRepository(prisma_client).table.find_first(- where={"unified_file_id": managed_id}- )++ db_row: Final = await _file_table(prisma_client).find_first(where={"unified_file_id": managed_id})if db_row is not None:row_created_by = db_row.created_byrow_team_id = db_row.team_id@@@ -367,7 -338,9 +369,7 @@@# Object table (batches, responses)if prisma_client is not None:try:- obj_row = await _object_table(prisma_client).find_first(where={"unified_object_id": managed_id})- obj_row: Final = await ManagedObjectRepository(prisma_client).table.find_first(- where={"unified_object_id": managed_id}- )++ obj_row: Final = await _object_table(prisma_client).find_first(where={"unified_object_id": managed_id})if obj_row is not None:row_created_by = obj_row.created_byrow_team_id = obj_row.team_id@@@ -425,7 -398,7 +427,7 @@@ async def _guard_raw_provider_id# id and scope to the current provider in the application layer (same as# _mint_or_reuse_file's dedup).try:- candidates = await _file_table(prisma_client).find_many(- candidates: Final = await ManagedFileRepository(prisma_client).table.find_many(++ candidates: Final = await _file_table(prisma_client).find_many(where={"flat_model_file_ids": {"has": raw_id}},)except Exception:@@@ -446,7 -419,7 +448,7 @@@# Object rows store model_object_id as "passthrough:{provider}:{raw}", so# the lookup is exact and already provider-scoped.try:- existing = await _object_table(prisma_client).find_first(- existing: Final = await ManagedObjectRepository(prisma_client).table.find_first(++ existing: Final = await _object_table(prisma_client).find_first(where={"model_object_id": f"passthrough:{provider}:{raw_id}"})except Exception:@@@ -505,8 -478,8 +507,9 @@@ async def _mint_or_reuse_file# the oldest match deterministically so two providers issuing the same raw id# reuse a stable row instead of minting duplicate rows on every call.if prisma_client is not None:++ candidates: list[ManagedFileRow]try:- candidates: list[ManagedFileRow] = await _file_table(prisma_client).find_many(- candidates = await ManagedFileRepository(prisma_client).table.find_many(++ candidates = await _file_table(prisma_client).find_many(where={"flat_model_file_ids": {"has": raw_id}},order={"created_at": "asc"},)@@@ -596,9 -567,9 +599,9 @@@ async def _mint_or_reuse_object# and causing every subsequent _resolve_one for that ID to return 404.# This mirrors the pattern in container_endpoints/ownership.py which uses# f"{purpose}:{provider}:{raw_id}" for the same reason.- namespaced_model_object_id = f"passthrough:{provider}:{raw_id}"+ namespaced_model_object_id: Final = f"passthrough:{provider}:{raw_id}"- async def _reuse_existing(existing: Any, refresh_snapshot: bool) -> str:+ async def _reuse_existing(existing: ManagedObjectRow, refresh_snapshot: bool) -> str:"""Resolve an already-persisted namespaced row: enforce the accesscheck, optionally refresh the snapshot, and return its managed ID."""if not can_access_resource(user_api_key_dict, existing.created_by, existing.team_id):@@@ -646,8 -617,10 +649,9 @@@return existing.unified_object_id# Dedup: look up by the namespaced key — guaranteed unique per provider.++ existing: ManagedObjectRow | Nonetry:- existing = await ManagedObjectRepository(prisma_client).table.find_first(- where={"model_object_id": namespaced_model_object_id}- )+ existing = await _object_table(prisma_client).find_first(where={"model_object_id": namespaced_model_object_id})except Exception:verbose_proxy_logger.debug("managed_id_rewriter: object dedup lookup failed", exc_info=True)existing = None@@@ -685,8 -658,10 +689,9 @@@# loser's create hits a UniqueConstraintViolation). Re-read it and reuse# the winner's managed ID so both callers converge on one ID instead of# the loser silently keeping the raw id.++ raced: ManagedObjectRow | Nonetry:- raced = await ManagedObjectRepository(prisma_client).table.find_first(- where={"model_object_id": namespaced_model_object_id}- )+ raced = await _object_table(prisma_client).find_first(where={"model_object_id": namespaced_model_object_id})except Exception:raced = Noneif raced is not None:@@@ -844,8 -819,8 +849,8 @@@ def _empty_list_response() -> ManagedLi}-def _parse_list_limit(query_params: dict[str, Any] | None) -> tuple[int, int]:+def _parse_list_limit(query_params: Mapping[str, str] | None) -> tuple[int, int]:- params = query_params or {}+ params: Final = query_params or {}try:raw_limit = int(params.get("limit", 20))except (TypeError, ValueError):@@@ -855,32 -830,34 +860,34 @@@async def _build_list_where_with_cursor(- prisma_client: Any,- resource_kind: str,+ prisma_client: PrismaClient,+ resource_kind: ResourceKind,provider: str,- owner_filter: dict[str, Any],- query_params: dict[str, Any] | None,-) -> tuple[dict[str, Any], str]:+ owner_filter: Mapping[str, PrismaWhereValue],+ query_params: Mapping[str, str] | None,+) -> tuple[PrismaWhere, SortOrder]:"""Return a Prisma ``where`` clause and fetch order for a list query."""- params = query_params or {}- after_id: str | None = params.get("after")- before_id: str | None = params.get("before")- where: PrismaWhere = dict(owner_filter)- fetch_order: SortOrder = "desc"-- cursor_id = after_id or before_id+ params: Final = query_params or {}+ after_id: Final[str | None] = params.get("after")+ before_id: Final[str | None] = params.get("before")- where: dict[str, Any] = dict(owner_filter)- fetch_order = "desc"++ where: PrismaWhere = dict(++ owner_filter++ ) # rebind-ok: narrowed with the cursor boundary when a valid cursor row exists++ fetch_order: SortOrder = "desc" # rebind-ok: flipped to asc when paging backwards from a before cursor++ cursor_id: Final = after_id or before_id# A cursor minted for a different provider would resolve to that provider's# created_at boundary and silently skip/repeat this provider's rows, so# ignore it and serve the unscoped first page instead.if not cursor_id or not _managed_id_matches_provider(cursor_id, provider):return where, fetch_order- cursor_table: ManagedFileTable | ManagedObjectTable = (- cursor_table: Final = (- ManagedFileRepository(prisma_client).table- if resource_kind == "files"- else ManagedObjectRepository(prisma_client).table++ cursor_table: Final[ManagedFileTable | ManagedObjectTable] = (+ _file_table(prisma_client) if resource_kind == "files" else _object_table(prisma_client))- cursor_field = "unified_file_id" if resource_kind == "files" else "unified_object_id"+ cursor_field: Final = "unified_file_id" if resource_kind == "files" else "unified_object_id"try:- cursor_row = await cursor_table.find_first(where={**owner_filter, cursor_field: cursor_id})+ cursor_row: Final = await cursor_table.find_first(where={**owner_filter, cursor_field: cursor_id})if cursor_row is not None:if after_id:op = "lt"@@@ -890,7 -867,7 +897,7 @@@# created_at is not unique, so the boundary must also compare the# unique id (the secondary sort key) to avoid skipping or repeating# rows that share the cursor row's timestamp across a page boundary.- boundary: PrismaWhere = {- boundary: Final = {++ boundary: Final[PrismaWhere] = {"OR": [{"created_at": {op: cursor_row.created_at}},{@@@ -948,10 -931,15 +955,10 @@@ async def _fetch_provider_scoped_list_rpage, with no application-layer scanning that could truncate large pools.A DB failure returns an empty page (fail closed) so the caller never falls- through to the upstream provider.+ through to the upstream provider. ``open_table`` is opened inside that+ guarded region so a client missing the managed tables fails closed too."""- rows = await _fetch_list_rows(open_table, {**where, **provider_scope}, id_field, fetch_order, fetch_limit)- scoped_where: Final = dict(where)- if resource_kind == "files":- scoped_where["flat_model_file_ids"] = {"has": _passthrough_provider_marker(provider)}- else:- scoped_where["model_object_id"] = {"startswith": f"passthrough:{provider}:"}-- rows: Final = await _fetch_list_rows(prisma_client, resource_kind, scoped_where, fetch_order, fetch_limit)++ rows: Final = await _fetch_list_rows(open_table, {**where, **provider_scope}, id_field, fetch_order, fetch_limit)if rows is None:return [], False@@@ -963,8 -951,8 +970,8 @@@return page, has_more-def _serialize_file_list_item(row: Any) -> dict[str, Any]:- item: Final[dict[str, Any]] = {+def _serialize_file_list_item(row: ManagedFileRow) -> dict[str, JsonValue]:- item: dict[str, JsonValue] = {++ item: Final[dict[str, JsonValue]] = {"id": row.unified_file_id,"object": "file","created_at": int(row.created_at.timestamp()) if row.created_at else None,@@@ -976,9 -964,9 +983,9 @@@return item-def _serialize_batch_list_item(row: Any) -> dict[str, Any]:- item: Final[dict[str, Any]] = {}+def _serialize_batch_list_item(row: ManagedObjectRow) -> dict[str, JsonValue]:- item: dict[str, JsonValue] = {}- file_object = _parse_file_object(row.file_object)++ item: Final[dict[str, JsonValue]] = {}+ file_object: Final = _parse_file_object(row.file_object)if isinstance(file_object, dict):item.update(file_object)item["id"] = row.unified_object_id # managed ID always wins@@@ -1031,31 -1020,21 +1038,34 @@@ async def list_passthrough_ids_from_dbwhere, fetch_order = await _build_list_where_with_cursor(prisma_client, resource_kind, provider, owner_filter, query_params)- page, has_more = await _fetch_provider_scoped_list_rows(- prisma_client,- resource_kind,- provider,- where,- fetch_order,- raw_limit,- fetch_limit,- )++ data: list[dict[str, JsonValue]]++ first_id: str | None++ last_id: str | Noneif resource_kind == "files":- data = [_serialize_file_list_item(row) for row in page]+ file_page, has_more = await _fetch_provider_scoped_list_rows(+ lambda: _file_table(prisma_client),+ where,+ {"flat_model_file_ids": {"has": _passthrough_provider_marker(provider)}},+ "unified_file_id",+ fetch_order,+ raw_limit,+ fetch_limit,+ )+ data = [_serialize_file_list_item(row) for row in file_page]+ first_id, last_id = _list_boundary_ids(file_page, lambda row: row.unified_file_id)else:- data = [_serialize_batch_list_item(row) for row in page]+ object_page, has_more = await _fetch_provider_scoped_list_rows(+ lambda: _object_table(prisma_client),+ where,+ {"model_object_id": {"startswith": f"passthrough:{provider}:"}, "file_purpose": "batch"},+ "unified_object_id",+ fetch_order,+ raw_limit,+ fetch_limit,+ )+ data = [_serialize_batch_list_item(row) for row in object_page]+ first_id, last_id = _list_boundary_ids(object_page, lambda row: row.unified_object_id)- first_id, last_id = _list_boundary_ids(page, resource_kind)verbose_proxy_logger.debug("managed_id_rewriter: list served from DB provider=%s kind=%s count=%d admin=%s",provider,@@@ -1193,29 -1138,9 +1203,29 @@@ async def rewrite_body_idsif not body:return body- budget = _RawIdGuardBudget()+ budget: Final = _RawIdGuardBudget()- async def _walk(node: Any, depth: int) -> Any:+ async def _walk_mapping(node: dict[str, object], depth: int) -> dict[str, object]:- result: dict[str, object] = {}- changed_inner = False++ result: Final[dict[str, object]] = {}++ changed_inner = False # rebind-ok: flips when any child rewrite returns a new object+ for k, v in node.items():+ # Skip litellm internal injection keys (e.g. litellm_logging_obj)+ if _is_litellm_internal_key(k):+ result[k] = v+ continue+ new_v = await _walk(v, depth + 1)+ result[k] = new_v+ if new_v is not v:+ changed_inner = True+ return result if changed_inner else node++ async def _walk_sequence(node: list[object], depth: int) -> list[object]:- new_list = [await _walk(item, depth + 1) for item in node]++ new_list: Final = [await _walk(item, depth + 1) for item in node]+ if any(n is not o for n, o in zip(new_list, node)):+ return new_list+ return node++ async def _walk(node: object, depth: int) -> object:if depth >= _MAX_BODY_REWRITE_DEPTH:return nodeif isinstance(node, dict):diff --cc litellm/responses/mcp/mcp_streaming_iterator.pyindex 383760a02f8,12c32d491ea..e4cc36de06c--- a/litellm/responses/mcp/mcp_streaming_iterator.py+++ b/litellm/responses/mcp/mcp_streaming_iterator.py@@@ -1,5 -1,4 +1,5 @@@+from collections.abc import Mapping, Sequence- from typing import TYPE_CHECKING, Any, cast+ from typing import TYPE_CHECKING, Any, Final, castfrom litellm._logging import verbose_loggerfrom litellm._uuid import uuiddiff --cc litellm/responses/streaming_iterator.pyindex 7cb161ea98d,94cfe0fcb1f..820839fc6bf--- a/litellm/responses/streaming_iterator.py+++ b/litellm/responses/streaming_iterator.py@@@ -9,7 -9,7 +9,7 @@@ from collections.abc import Mappinfrom datetime import datetimefrom functools import lru_cachefrom types import MappingProxyType- from typing import TYPE_CHECKING, Any, Literal-from typing import Any, Final, Literal++from typing import TYPE_CHECKING, Any, Final, Literalimport httpxfrom openai._streaming import SSEDecoder@@@ -56,28 -42,10 +56,28 @@@ def _get_openai_response_types()return openai_types-def _log_background_task_failure(task: asyncio.Task[Any], *, task_name: str) -> None:+def _is_json_object(value: object) -> TypeIs[dict[str, object]]: # guard-ok: trivial isinstance; JSON keys are str+ return isinstance(value, dict)+++def _is_json_array(value: object) -> TypeIs[list[object]]: # guard-ok: trivial isinstance narrowing+ return isinstance(value, list)+++def _is_str_mapping(value: object) -> TypeIs[dict[str, str]]: # guard-ok: verifies every value is str+ return _is_json_object(value) and all(isinstance(item, str) for item in value.values())+++def _model_id_from_metadata(litellm_metadata: dict[str, object] | None) -> str | None:- model_info = litellm_metadata.get("model_info") if litellm_metadata else None- model_id = model_info.get("id") if _is_json_object(model_info) else 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+ return model_id if isinstance(model_id, str) else None+++def _log_background_task_failure(task: asyncio.Task[object], *, task_name: str) -> None:if task.cancelled():return- exception = task.exception()+ exception: Final = task.exception()if exception is not None:verbose_logger.error("%s failed: %s", task_name, exception)@@@ -253,12 -222,14 +253,12 @@@ class BaseResponsesAPIStreamingIteratorsetattr(openai_responses_api_chunk, "response", response)# Encode container_id on streaming events so proxy/UI follow-ups route correctly- _event_type = getattr(openai_responses_api_chunk, "type", None)+ _event_type: Final = getattr(openai_responses_api_chunk, "type", None)if _event_type == ResponsesAPIStreamEvents.OUTPUT_TEXT_DELTA:- _delta = getattr(openai_responses_api_chunk, "delta", None)+ _delta: Final = getattr(openai_responses_api_chunk, "delta", None)if isinstance(_delta, str):self._generated_content += _delta- _stream_model_id = _model_id_from_metadata(self.litellm_metadata)- _stream_model_id: Final = (- self.litellm_metadata.get("model_info", {}).get("id") if self.litellm_metadata else None- )++ _stream_model_id: Final = _model_id_from_metadata(self.litellm_metadata)if _event_type in (ResponsesAPIStreamEvents.OUTPUT_ITEM_ADDED,ResponsesAPIStreamEvents.OUTPUT_ITEM_DONE,@@@ -302,11 -273,15 +302,11 @@@openai_types.ResponsesAPIStreamEvents.OUTPUT_ITEM_ADDED,openai_types.ResponsesAPIStreamEvents.OUTPUT_ITEM_DONE,):- item = getattr(openai_responses_api_chunk, "item", None)+ item: Final = getattr(openai_responses_api_chunk, "item", None)if item:- encrypted_content = getattr(item, "encrypted_content", None)+ encrypted_content: Final = getattr(item, "encrypted_content", None)if encrypted_content and isinstance(encrypted_content, str):- model_id = _model_id_from_metadata(self.litellm_metadata)- model_id: Final = (- self.litellm_metadata.get("model_info", {}).get("id")- if self.litellm_metadata- else None- )++ model_id: Final = _model_id_from_metadata(self.litellm_metadata)if model_id:wrapped_content = ResponsesAPIRequestUtils._wrap_encrypted_content_with_model_id(encrypted_content, model_id@@@ -426,10 -401,10 +426,10 @@@)self._handle_failure(exception)- def _record_failed_response_usage(self, response_obj: Any | None) -> None:+ def _record_failed_response_usage(self, response_obj: ResponsesAPIResponse | None) -> None:if response_obj is None or self.logging_obj is None:return- usage_obj = getattr(response_obj, "usage", None)+ usage_obj: Final = getattr(response_obj, "usage", None)if usage_obj is None:returntry:@@@ -476,9 -451,9 +476,9 @@@is_pre_first_chunk=not self._yielded_first_chunk,)- def _get_completed_response_object(self) -> Any | None:+ def _get_completed_response_object(self) -> ResponsesAPIResponse | None:- openai_types = _get_openai_response_types()- completed_response = self.completed_response+ openai_types: Final = _get_openai_response_types()+ completed_response: Final = self.completed_responseif isinstance(completed_response, openai_types.ResponsesAPIResponse):return completed_response@@@ -885,12 -856,12 +885,12 @@@ class MockResponsesAPIStreamingIteratormodel: str,responses_api_provider_config: BaseResponsesAPIConfig,logging_obj: LiteLLMLoggingObj,- litellm_metadata: dict[str, Any] | None = None,+ litellm_metadata: dict[str, object] | None = None,custom_llm_provider: str | None = None,- request_data: dict[str, Any] | None = None,+ request_data: dict[str, object] | None = None,call_type: str | None = None,):- transformed = responses_api_provider_config.transform_response_api_response(+ transformed: Final = responses_api_provider_config.transform_response_api_response(model=model,raw_response=response,logging_obj=logging_obj,@@@ -923,12 -894,12 +923,12 @@@def __aiter__(self):return self- async def __anext__(self) -> Any:+ async def __anext__(self) -> ResponsesAPIStreamingResponse:if self._idx >= len(self._events):raise StopAsyncIteration- evt = self._events[self._idx]+ evt: Final = self._events[self._idx]self._idx += 1- openai_types = _get_openai_response_types()+ openai_types: Final = _get_openai_response_types()if getattr(evt, "type", None) == openai_types.ResponsesAPIStreamEvents.RESPONSE_COMPLETED:self.completed_response = evtself._log_completed_response(is_async=True)@@@ -937,12 -908,12 +937,12 @@@def __iter__(self):return self- def __next__(self) -> Any:+ def __next__(self) -> ResponsesAPIStreamingResponse:if self._idx >= len(self._events):raise StopIteration- evt = self._events[self._idx]+ evt: Final = self._events[self._idx]self._idx += 1- openai_types = _get_openai_response_types()+ openai_types: Final = _get_openai_response_types()if getattr(evt, "type", None) == openai_types.ResponsesAPIStreamEvents.RESPONSE_COMPLETED:self.completed_response = evtself._log_completed_response(is_async=False)@@@ -990,12 -961,12 +990,12 @@@ class CachedResponsesAPIStreamingIteratdef __aiter__(self):return self- async def __anext__(self) -> Any:+ async def __anext__(self) -> ResponsesAPIStreamingResponse:if self._idx >= len(self._events):raise StopAsyncIteration- evt = self._events[self._idx]+ evt: Final = self._events[self._idx]self._idx += 1- openai_types = _get_openai_response_types()+ openai_types: Final = _get_openai_response_types()if getattr(evt, "type", None) == openai_types.ResponsesAPIStreamEvents.RESPONSE_COMPLETED:self.completed_response = evtself._log_completed_response(is_async=True)@@@ -1004,12 -975,12 +1004,12 @@@def __iter__(self):return self- def __next__(self) -> Any:+ def __next__(self) -> ResponsesAPIStreamingResponse:if self._idx >= len(self._events):raise StopIteration- evt = self._events[self._idx]+ evt: Final = self._events[self._idx]self._idx += 1- openai_types = _get_openai_response_types()+ openai_types: Final = _get_openai_response_types()if getattr(evt, "type", None) == openai_types.ResponsesAPIStreamEvents.RESPONSE_COMPLETED:self.completed_response = evtself._log_completed_response(is_async=False)@@@ -1029,10 -1000,10 +1029,10 @@@ def _build_response_status_event"response.created","response.in_progress",],- transformed: Any,-) -> Any:+ transformed: ResponsesAPIResponse,+) -> ResponsesAPIStreamingResponse:- openai_types = _get_openai_response_types()- in_progress_response = transformed.model_copy(+ openai_types: Final = _get_openai_response_types()+ in_progress_response: Final = transformed.model_copy(deep=True,update={"status": "in_progress", "output": []},)@@@ -1047,12 -1018,12 +1047,12 @@@ def _build_content_part_done_eventoutput_index: int,content_index: int,part_payload: dict[str, Any],-) -> Any | None:+) -> ResponsesAPIStreamingResponse | None:- openai_types = _get_openai_response_types()- part_type = part_payload.get("type")+ openai_types: Final = _get_openai_response_types()+ part_type: Final = part_payload.get("type")- part: Any+ part: PART_UNION_TYPESif part_type == "output_text":- annotations = [+ annotations: Final = [openai_types.BaseLiteLLMOpenAIResponseObject(**annotation)for annotation in part_payload.get("annotations", []) or []]@@@ -1152,22 -1123,22 +1152,22 @@@ def _add_text_like_part_eventsdef _build_synthetic_response_events(*,- transformed: Any,+ transformed: ResponsesAPIResponse,logging_obj: LiteLLMLoggingObj,chunk_size: int,-) -> list[Any]:+) -> list[ResponsesAPIStreamingResponse]:- openai_types = _get_openai_response_types()+ openai_types: Final = _get_openai_response_types()if litellm.include_cost_in_streaming_usage and logging_obj is not None:- usage_obj = transformed.usage if hasattr(transformed, "usage") else None- usage_obj: Final[Any | None] = getattr(transformed, "usage", None)++ usage_obj: Final = transformed.usage if hasattr(transformed, "usage") else Noneif usage_obj is not None:try:- cost: float | None = logging_obj._response_cost_calculator(result=transformed)+ cost: Final[float | None] = logging_obj._response_cost_calculator(result=transformed)if cost is not None:setattr(usage_obj, "cost", cost)except Exception:pass- events: list[ResponsesAPIStreamingResponse] = [- events: Final[list[Any]] = [++ events: Final[list[ResponsesAPIStreamingResponse]] = [_build_response_status_event(openai_types.ResponsesAPIStreamEvents.RESPONSE_CREATED, transformed),_build_response_status_event(openai_types.ResponsesAPIStreamEvents.RESPONSE_IN_PROGRESS, transformed),]@@@ -1472,8 -1443,8 +1472,8 @@@ class ResponsesWebSocketStreamingif not self.authorized_model:return Falsemodified = False- nested = msg_obj.get("response")+ nested: Final = msg_obj.get("response")- if isinstance(nested, dict):+ if _is_json_object(nested):if nested.get("model") != self.authorized_model:nested["model"] = self.authorized_modelmodified = True@@@ -1621,9 -1590,7 +1621,9 @@@if not self.guardrail_callbacks:return response_str- metadata = self.request_data.get("metadata")- raw_pii_tokens = metadata.get("pii_tokens") if _is_json_object(metadata) else None- pii_tokens: dict[str, str] = raw_pii_tokens if _is_str_mapping(raw_pii_tokens) else {}- pii_tokens: Final[dict[str, str]] = (self.request_data.get("metadata") or {}).get("pii_tokens", {})++ metadata: Final = self.request_data.get("metadata")++ raw_pii_tokens: Final = metadata.get("pii_tokens") if _is_json_object(metadata) else None++ pii_tokens: Final[dict[str, str]] = raw_pii_tokens if _is_str_mapping(raw_pii_tokens) else {}if not pii_tokens:return response_str@@@ -1637,18 -1604,17 +1637,18 @@@if event_type == "response.completed":modified = False- response_obj = evt_obj.get("response")- response_obj: Final = evt_obj.get("response") or {}- if not isinstance(response_obj, dict):++ response_obj: Final = evt_obj.get("response")+ if not _is_json_object(response_obj):return response_str- output_items = response_obj.get("output")- for output_item in response_obj.get("output") or []:- if not isinstance(output_item, dict):++ output_items: Final = response_obj.get("output")+ for output_item in output_items if _is_json_array(output_items) else []:+ if not _is_json_object(output_item):continue- content = output_item.get("content") or []- if not isinstance(content, list):+ content = output_item.get("content")+ if not _is_json_array(content):continuefor content_block in content:- if not isinstance(content_block, dict):+ if not _is_json_object(content_block):continuetext = content_block.get("text")if isinstance(text, str):@@@ -1791,12 -1756,12 +1791,12 @@@# Managed WebSocket mode (HTTP-backed, provider-agnostic)# ---------------------------------------------------------------------------- _RESPONSE_CREATE_PARAMS: frozenset[str] = (-_RESPONSE_CREATE_PARAMS: Final[frozenset] = (++_RESPONSE_CREATE_PARAMS: Final[frozenset[str]] = (_get_openai_response_types().ResponsesAPIRequestParams.__required_keys__| _get_openai_response_types().ResponsesAPIRequestParams.__optional_keys__)- _MANAGED_WS_SKIP_KWARGS: frozenset[str] = frozenset(-_MANAGED_WS_SKIP_KWARGS: Final[frozenset] = frozenset(++_MANAGED_WS_SKIP_KWARGS: Final[frozenset[str]] = frozenset({"litellm_logging_obj","litellm_call_id",@@@ -1896,11 -1861,11 +1896,11 @@@ class ManagedResponsesWebSocketHandlerThe key is the *decoded* response ID (the raw provider response ID beforeLiteLLM base64-encodes it into the ``resp_...`` format)."""- decoded = ResponsesAPIRequestUtils._decode_responses_api_response_id(previous_response_id)- raw_id = decoded.get("response_id", previous_response_id)+ decoded: Final = ResponsesAPIRequestUtils._decode_responses_api_response_id(previous_response_id)+ raw_id: Final = decoded.get("response_id", previous_response_id)return list(self._session_history.get(raw_id, []))- def _store_history(self, response_id: str, messages: list[dict[str, Any]]) -> None:+ def _store_history(self, response_id: str, messages: list[dict[str, object]]) -> None:"""Store the complete accumulated message history for *response_id*.@@@ -1915,12 -1880,11 +1915,12 @@@Pull the raw (decoded) response ID out of a ``response.completed`` event.Returns *None* if the event doesn't contain a usable ID."""- resp_obj = completed_event.get("response", {})- raw_id = resp_obj.get("id") if _is_json_object(resp_obj) else None- encoded_id: str | None = raw_id if isinstance(raw_id, str) else None+ resp_obj: Final = completed_event.get("response", {})- encoded_id: Final[str | None] = resp_obj.get("id") if isinstance(resp_obj, dict) else None++ raw_id: Final = resp_obj.get("id") if _is_json_object(resp_obj) else None++ encoded_id: Final[str | None] = raw_id if isinstance(raw_id, str) else Noneif not encoded_id:return None- decoded = ResponsesAPIRequestUtils._decode_responses_api_response_id(encoded_id)+ decoded: Final = ResponsesAPIRequestUtils._decode_responses_api_response_id(encoded_id)return decoded.get("response_id", encoded_id)@staticmethod@@@ -1931,10 -1895,10 +1931,10 @@@Convert the output items in a ``response.completed`` event intoResponses API message dicts suitable for the next turn's ``input``."""- resp_obj = completed_event.get("response", {})+ resp_obj: Final = completed_event.get("response", {})if not isinstance(resp_obj, dict):return []- messages: list[dict[str, object]] = []- messages: Final[list[dict[str, Any]]] = []++ messages: Final[list[dict[str, object]]] = []for item in resp_obj.get("output", []) or []:if not isinstance(item, dict):continue@@@ -1982,10 -1946,10 +1982,10 @@@# _process_response_create sub-methods# ------------------------------------------------------------------- async def _parse_message(self, raw_message: str) -> dict[str, Any] | None:+ async def _parse_message(self, raw_message: str) -> dict[str, object] | None:"""Parse raw WS text; return the message dict or None (JSON error / ignored type)."""try:- msg_obj = json.loads(raw_message)+ msg_obj: Final = json.loads(raw_message)except json.JSONDecodeError:await self._send_error("Invalid JSON in response.create event", "invalid_request_error")return None@@@ -1995,10 -1959,10 +1995,10 @@@return msg_obj@staticmethod- def _is_warmup_frame(msg_obj: dict[str, Any]) -> bool:+ def _is_warmup_frame(msg_obj: dict[str, object]) -> bool:"""Return True for a response.create whose generate flag is false."""- nested = msg_obj.get("response")- source = nested if _is_json_object(nested) and nested else msg_obj+ nested: Final = msg_obj.get("response")- source: Final = nested if isinstance(nested, dict) and nested else msg_obj++ source: Final = nested if _is_json_object(nested) and nested else msg_objreturn source.get("generate") is False@staticmethod@@@ -2011,16 -1975,16 +2011,16 @@@return str(raw_id).startswith(_WARMUP_RESPONSE_ID_PREFIX)@staticmethod- def _warmup_source_params(msg_obj: dict[str, Any]) -> dict[str, Any]:+ def _warmup_source_params(msg_obj: dict[str, object]) -> dict[str, object]:- nested = msg_obj.get("response")+ nested: Final = msg_obj.get("response")- if isinstance(nested, dict) and nested:+ if _is_json_object(nested) and nested:return nestedreturn {k: v for k, v in msg_obj.items() if k != "type"}- def _build_warmup_response(self, msg_obj: dict[str, Any]) -> dict[str, Any]:+ def _build_warmup_response(self, msg_obj: dict[str, object]) -> dict[str, object]:"""Build a minimal completed Responses API object for a warmup ack."""- source = self._warmup_source_params(msg_obj)- wire_model = source.get("model") or self.model_group or self.model+ source: Final = self._warmup_source_params(msg_obj)+ wire_model: Final = source.get("model") or self.model_group or self.modelreturn {"id": f"{_WARMUP_RESPONSE_ID_PREFIX}{uuid.uuid4().hex}","object": "response",@@@ -2064,9 -2028,9 +2064,9 @@@Nested: {"type": "response.create", "response": {"input": [...], ...}}Flat: {"type": "response.create", "input": [...], "model": "...", ...}"""- nested = msg_obj.get("response")- response_params: dict[str, Any] = (+ nested: Final = msg_obj.get("response")+ response_params: Final[dict[str, Any]] = (- nested if isinstance(nested, dict) and nested else {k: v for k, v in msg_obj.items() if k != "type"}+ nested if _is_json_object(nested) and nested else {k: v for k, v in msg_obj.items() if k != "type"})return {param: response_params[param]@@@ -2175,9 -2139,9 +2175,11 @@@directly (before serialization) to avoid a redundant JSON round-trip onevery chunk. Returns the completed event dict, or ``None``."""- completed_event: dict[str, object] | None = None- stream_response = await litellm.aresponses(model=model, **call_kwargs)- async for chunk in stream_response: # type: ignore[union-attr]- completed_event: dict[str, Any] | None = None++ completed_event: dict[str, object] | None = (++ None # rebind-ok: captures the completed event once the stream yields it++ )+ stream_response: Final = await litellm.aresponses(model=model, **call_kwargs)+ async for chunk in stream_response:if chunk is None:continue# Read type from the object before serializing to avoid double JSON parsediff --cc litellm/router.pyindex 7d6499cf7d2,39d5080a33d..cdff78e4987--- a/litellm/router.py+++ b/litellm/router.py@@@ -3400,9 -3410,9 +3410,7 @@@ class Router# Await the first task to complete successfullywhile pending_tasks:- done, pending_tasks = await asyncio.wait( # type: ignore- done, pending_tasks = await asyncio.wait(-- pending_tasks, return_when=asyncio.FIRST_COMPLETED-- )++ done, pending_tasks = await asyncio.wait(pending_tasks, return_when=asyncio.FIRST_COMPLETED)for completed_task in done:result = await check_response(completed_task)@@@ -5230,10 -5240,10 +5238,8 @@@# Update kwargs with the current model name or any other model-specific adjustments## SET CUSTOM PROVIDER TO SELECTED DEPLOYMENT ##if not custom_llm_provider:- _, custom_llm_provider, _, _ = get_llm_provider( # type: ignore- _, custom_llm_provider, _, _ = get_llm_provider(-- model=model-- )- new_kwargs = safe_deep_copy(kwargs)++ _, custom_llm_provider, _, _ = get_llm_provider(model=model)+ new_kwargs: Final = safe_deep_copy(kwargs)self._update_kwargs_with_deployment(deployment=cast(dict, model_name),kwargs=new_kwargs,@@@ -6019,9 -6029,9 +6025,7 @@@raise Exception("'custom_llm_provider' must be set. Either via:\n `Router(assistants_config={'custom_llm_provider': ..})` \nor\n `router.arun_thread(custom_llm_provider=..)`")- return await original_function( # type: ignore- return await original_function(-- custom_llm_provider=custom_llm_provider, client=client, **kwargs-- )++ return await original_function(custom_llm_provider=custom_llm_provider, client=client, **kwargs)#### [END] ASSISTANTS API ####@@@ -6351,9 -6364,9 +6358,7 @@@mask_sensitive_structure(fallback_model_group),)if len(fallback_failure_exception_str) > 0:- original_exception.message += ( # type: ignore- original_exception.message += (-- f"\nError doing the fallback: {fallback_failure_exception_str}"-- )++ original_exception.message += f"\nError doing the fallback: {fallback_failure_exception_str}"raise original_exception@@@ -9108,12 -9121,12 +9113,10 @@@model_group_info.output_cost_per_token = _output_cost_per_tokenif (model_info.get("supports_parallel_function_calling", None) is not None- and model_info["supports_parallel_function_calling"] is True # type: ignore+ and model_info["supports_parallel_function_calling"] is True):model_group_info.supports_parallel_function_calling = True-- if (- model_info.get("supports_vision", None) is not None and model_info["supports_vision"] is True # type: ignore- model_info.get("supports_vision", None) is not None and model_info["supports_vision"] is True-- ):++ if model_info.get("supports_vision", None) is not None and model_info["supports_vision"] is True:model_group_info.supports_vision = Trueif (model_info.get("supports_function_calling", None) is not None@@@ -9131,9 -9144,9 +9134,7 @@@):model_group_info.supports_url_context = True-- if (- model_info.get("supports_reasoning", None) is not None and model_info["supports_reasoning"] is True # type: ignore- model_info.get("supports_reasoning", None) is not None and model_info["supports_reasoning"] is True-- ):++ if model_info.get("supports_reasoning", None) is not None and model_info["supports_reasoning"] is True:model_group_info.supports_reasoning = Trueif (model_info.get("supported_openai_params", None) is not None@@@ -10863,9 -10876,9 +10864,7 @@@args=(e, traceback_exception),).start() # log response# Handle any exceptions that might occur during streaming-- asyncio.create_task(- logging_obj.async_failure_handler(e, traceback_exception) # type: ignore- logging_obj.async_failure_handler(e, traceback_exception)-- )++ asyncio.create_task(logging_obj.async_failure_handler(e, traceback_exception))raise easync def async_get_available_deployment_for_pass_through(@@@ -10990,9 -11003,9 +10989,7 @@@target=logging_obj.failure_handler,args=(e, traceback_exception),).start()-- asyncio.create_task(- logging_obj.async_failure_handler(e, traceback_exception) # type: ignore- logging_obj.async_failure_handler(e, traceback_exception)-- )++ asyncio.create_task(logging_obj.async_failure_handler(e, traceback_exception))raise easync def _run_routing_plugins(diff --cc litellm/types/passthrough_endpoints/managed_id_rewriter.pyindex 33749cc2ab8,00000000000..675aae96a5bmode 100644,000000..100644--- a/litellm/types/passthrough_endpoints/managed_id_rewriter.py+++ b/litellm/types/passthrough_endpoints/managed_id_rewriter.py@@@ -1,123 -1,0 +1,125 @@@+"""+Typed surfaces for the passthrough managed-ID rewriter.++Prisma's generated client is untyped at the ``litellm`` boundary, so the row+shapes, table actions, and query fragments the rewriter touches are declared+here as protocols instead of leaking ``Any`` through every call site.+"""++from __future__ import annotations++from collections.abc import Mapping, Sequence+from datetime import datetime+from typing import (+ TYPE_CHECKING,+ Literal,+ Protocol,+ TypeAlias,+ TypedDict,+ TypeVar,+ runtime_checkable,+)++from pydantic import JsonValue++if TYPE_CHECKING:+ from litellm.models.managed_files import LiteLLM_ManagedFileTable+ from litellm.proxy._types import UserAPIKeyAuth+ from litellm.types.llms.openai import OpenAIFileObject++SortOrder: TypeAlias = Literal["asc", "desc"]+ResourceKind: TypeAlias = Literal["files", "batches"]++PrismaWhereValue: TypeAlias = (+ "str | int | bool | datetime | None | Mapping[str, PrismaWhereValue] | Sequence[PrismaWhereValue]"+)+PrismaWhere: TypeAlias = "Mapping[str, PrismaWhereValue]"+PrismaOrder: TypeAlias = "Mapping[str, SortOrder]"+ManagedRowData: TypeAlias = "Mapping[str, str | None]"+++class ManagedResourceRow(Protocol):+ """Columns shared by ``LiteLLM_ManagedFileTable`` and ``LiteLLM_ManagedObjectTable`` rows."""++ created_by: str | None+ team_id: str | None+ created_at: datetime | None+ file_object: JsonValue+++class ManagedFileRow(ManagedResourceRow, Protocol):+ unified_file_id: str+++class ManagedObjectRow(ManagedResourceRow, Protocol):+ unified_object_id: str++- RowT = TypeVar("RowT", bound=ManagedResourceRow)++RowT = TypeVar(++ "RowT", bound=ManagedResourceRow++) # rebind-ok: TypeVar declarations must stay bare assignments for pyright+++class ManagedTable(Protocol[RowT]):+ """The Prisma table actions the rewriter reads rows through."""++ async def find_first(self, *, where: PrismaWhere) -> RowT | None: ...++ async def find_many(+ self,+ *,+ where: PrismaWhere,+ order: PrismaOrder | Sequence[PrismaOrder] | None = None,+ take: int | None = None,+ ) -> list[RowT]: ...+++class ManagedFileTable(ManagedTable[ManagedFileRow], Protocol): ...+++class ManagedObjectTable(ManagedTable[ManagedObjectRow], Protocol):+ async def update(self, *, where: PrismaWhere, data: ManagedRowData) -> ManagedObjectRow | None: ...++ async def upsert(self, *, where: PrismaWhere, data: Mapping[str, ManagedRowData]) -> ManagedObjectRow: ...+++@runtime_checkable+class ManagedFileIdReader(Protocol):+ """Row lookup on the enterprise managed-files hook.++ The proxy hook registry is untyped and hands back a bare ``CustomLogger``,+ so this protocol is an ``isinstance`` target: the rewriter checks the method+ is really there before calling it. It is kept separate from+ ``ManagedFileIdWriter`` so a hook implementing only one of the two is+ narrowed on exactly the capability about to be used.+ """++ async def get_unified_file_id(+ self,+ file_id: str,+ litellm_parent_otel_span: object = None,+ ) -> LiteLLM_ManagedFileTable | None: ...+++@runtime_checkable+class ManagedFileIdWriter(Protocol):+ """Row persistence on the enterprise managed-files hook."""++ async def store_unified_file_id(+ self,+ file_id: str,+ file_object: OpenAIFileObject | None,+ litellm_parent_otel_span: object,+ model_mappings: dict[str, str],+ user_api_key_dict: UserAPIKeyAuth,+ ) -> None: ...+++class ManagedListResponse(TypedDict):+ """OpenAI-style paginated list body served from the managed-resource tables."""++ object: Literal["list"]+ data: list[dict[str, JsonValue]]+ first_id: str | None+ last_id: str | None+ has_more: booldiff --cc litellm/utils.pyindex 5dbff5070aa,19c3d10695a..de96489a816--- a/litellm/utils.py+++ b/litellm/utils.py@@@ -774,17 -766,17 +766,9 @@@ def function_setupif (len(litellm.input_callback) > 0 or len(litellm.success_callback) > 0 or len(litellm.failure_callback) > 0-- ) and len(- callback_list # type: ignore- ) == 0: # type: ignore- callback_list- ) == 0:-- callback_list = list(-- set(- litellm.input_callback # type: ignore- litellm.input_callback-- + litellm.success_callback-- + litellm.failure_callback-- )-- )- get_set_callbacks = getattr(sys.modules[__name__], "get_set_callbacks")++ ) and len(callback_list) == 0:++ callback_list = list(set(litellm.input_callback + litellm.success_callback + litellm.failure_callback))+ get_set_callbacks: Final = getattr(sys.modules[__name__], "get_set_callbacks")get_set_callbacks()(callback_list=callback_list, function_id=function_id)## ASYNC CALLBACKS - safety net for callbacks added via direct appendif len(litellm.input_callback) > 0:diff --cc ruff-strict-budget.jsonindex 13ee3cd66c8,d03881416f0..e17b57a557b--- a/ruff-strict-budget.json+++ b/ruff-strict-budget.json@@@ -1,39 -1,39 +1,39 @@@{"ANN001": {- "limit": 3094- "limit": 2849++ "limit": 2846},"ANN002": {- "limit": 69+ "limit": 65},"ANN003": {- "limit": 829- "limit": 776++ "limit": 774},"ANN201": {- "limit": 2136- "limit": 1961++ "limit": 1960},"ANN202": {- "limit": 940- "limit": 868++ "limit": 867},"ANN204": {- "limit": 724+ "limit": 669},"ANN205": {- "limit": 127+ "limit": 115},"ANN206": {- "limit": 130+ "limit": 121},"ANN401": {- "limit": 1848+ "limit": 1762},"ASYNC230": {- "limit": 14+ "limit": 11},"B004": {- "limit": 4+ "limit": 2},"B006": {- "limit": 188+ "limit": 178},"B008": {"limit": 505@@@ -222,7 -222,7 +222,7 @@@"limit": 0},"RET504": {- "limit": 702- "limit": 180++ "limit": 179},"RUF010": {"limit": 0@@@ -249,28 -249,28 +249,28 @@@"limit": 0},"RUF059": {- "limit": 73+ "limit": 67},"RUF100": {- "limit": 480+ "limit": 100},"S110": {- "limit": 236- "limit": 220++ "limit": 219},"S112": {- "limit": 24+ "limit": 22},"SIM101": {- "limit": 61+ "limit": 58},"SIM102": {- "limit": 324+ "limit": 314},"SIM103": {- "limit": 129+ "limit": 119},"SIM113": {- "limit": 6+ "limit": 3},"SIM114": {"limit": 0diff --cc type-discipline-budget.jsonindex 35d89580a72,c3c5a5fb24a..c418bccc1e2--- a/type-discipline-budget.json+++ b/type-discipline-budget.json@@@ -1,29 -1,35 +1,35 @@@{"LIT001": {- "limit": 23349- "limit": 23346++ "limit": 23343},"LIT002": {- "limit": 27242- "limit": 27227++ "limit": 27217},"LIT003": {- "limit": 292+ "limit": 286},"LIT004": {- "limit": 44+ "limit": 43},"LIT005": {"limit": 0},"LIT006": {- "limit": 1096- "limit": 1103++ "limit": 1094},"LIT007": {"limit": 0},"LIT008": {- "limit": 1004+ "limit": 951},"LIT009": {- "limit": 2465+ "limit": 0+ },+ "LIT010": {- "limit": 16828++ "limit": 16802+ },+ "LIT011": {- "limit": 5603++ "limit": 5602}}