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
chore: merge origin/litellm_internal_staging into litellm_decrease_anys_opus5_r4
mateo-berri9c068117e752
diff --cc basedpyright-code-budget.jsonindex eb7f484901f,669107bb5b1..2e5e7d14d14--- a/basedpyright-code-budget.json+++ b/basedpyright-code-budget.json@@@ -1,9 -1,9 +1,9 @@@{"reportAny": {- "limit": 14074+ "limit": 13431},"reportArgumentType": {- "limit": 2207- "limit": 2206++ "limit": 2198},"reportAssignmentType": {"limit": 319@@@ -24,7 -24,7 +24,7 @@@"limit": 19},"reportExplicitAny": {- "limit": 3371- "limit": 4124++ "limit": 3372},"reportFunctionMemberAccess": {"limit": 7@@@ -42,22 -42,22 +42,22 @@@"limit": 12},"reportIndexIssue": {- "limit": 25+ "limit": 24},"reportInvalidTypeForm": {- "limit": 34+ "limit": 30},"reportInvalidTypeVarUse": {- "limit": 2+ "limit": 1},"reportMatchNotExhaustive": {"limit": 0},"reportMissingParameterType": {- "limit": 5601+ "limit": 5570},"reportMissingTypeArgument": {- "limit": 15285- "limit": 15284++ "limit": 15281},"reportMissingTypeStubs": {"limit": 40@@@ -90,10 -90,10 +90,10 @@@"limit": 8},"reportReturnType": {- "limit": 181+ "limit": 180},"reportTypedDictNotRequiredAccess": {- "limit": 24+ "limit": 22},"reportUndefinedVariable": {"limit": 0@@@ -105,16 -105,16 +105,16 @@@"limit": 109},"reportUnknownMemberType": {- "limit": 38298- "limit": 38309++ "limit": 38283},"reportUnknownParameterType": {- "limit": 19589- "limit": 19621++ "limit": 19585},"reportUnknownVariableType": {- "limit": 29846- "limit": 29844++ "limit": 29829},"reportUnnecessaryCast": {- "limit": 111+ "limit": 110},"reportUnnecessaryComparison": {"limit": 687diff --cc litellm/_service_logger.pyindex 703aa197a63,fc27d3a118a..0ccac4b5291--- a/litellm/_service_logger.py+++ b/litellm/_service_logger.py@@@ -1,6 -1,7 +1,7 @@@import asyncio+ from collections.abc import Callable, Coroutinefrom datetime import datetime, timedelta-from typing import TYPE_CHECKING, Any, Final+from typing import TYPE_CHECKING, Any, Final, Protocolimport litellmfrom litellm._logging import verbose_logger@@@ -105,10 -80,51 +106,51 @@@ class ServiceLogging(CustomLogger)if callback == "otel":from litellm.proxy.proxy_server import open_telemetry_logger- if open_telemetry_logger is not None and _is_otel_logger(open_telemetry_logger):- return open_telemetry_logger+ if open_telemetry_logger is not None:+ return _as_otel_logger(open_telemetry_logger)return None+ @staticmethod+ def _sync_dispatch_loop() -> asyncio.AbstractEventLoop | None:+ """The event loop a blocking caller can dispatch on, or ``None`` if it has none."""+ try:+ loop: Final = asyncio.get_event_loop()+ except RuntimeError:+ return None+ return None if loop.is_closed() else loop++ @staticmethod+ async def _emit_guarded(hook: Callable[[], Coroutine[object, object, None]]) -> None:+ """Emit one service event, absorbing anything the callbacks raise.++ Monitoring must not break the call it monitors. Sync callers are the ones that+ swallow their own service failures (a Redis batch read returns an empty dict),+ so an exception from a misconfigured callback would replace a Redis outage with+ a callback error and skip the caller's fallback handling.+ """+ try:+ await hook()+ except Exception as e:+ verbose_logger.exception("Error emitting service event - %s", e)++ @staticmethod+ def _dispatch_from_sync(hook: Callable[[], Coroutine[object, object, None]]) -> None:+ """Run an async service hook from a blocking caller, whatever event loop it holds.++ Takes a factory rather than a coroutine so the hook is built on the path that+ runs it, and only ever once.+ """+ loop: Final = ServiceLogging._sync_dispatch_loop()+ try:+ if loop is None:+ asyncio.run(ServiceLogging._emit_guarded(hook))+ elif loop.is_running():+ loop.create_task(ServiceLogging._emit_guarded(hook))+ else:+ loop.run_until_complete(ServiceLogging._emit_guarded(hook))+ except Exception as e:+ verbose_logger.exception("Error dispatching service event - %s", e)+def service_success_hook(self,service: ServiceTypes,diff --cc litellm/llms/bedrock/base_aws_llm.pyindex ec98a7a2c8f,c3da992a904..a197702921f--- a/litellm/llms/bedrock/base_aws_llm.py+++ b/litellm/llms/bedrock/base_aws_llm.py@@@ -4,10 -4,10 +4,10 @@@ import jsoimport osimport reimport urllib.parse-from collections.abc import Callable+from collections.abc import Callable, Mappingfrom datetime import datetimefrom threading import Lock- from typing import TYPE_CHECKING, Any, ClassVar, Final, Literal, cast, get_args+ from typing import TYPE_CHECKING, Any, ClassVar, Final, Literal, cast, get_args, overloadimport httpxfrom pydantic import BaseModel, ValidationErrordiff --cc litellm/llms/custom_httpx/container_handler.pyindex d4f1f0a4f1b,de72735e4ec..01ad8755915--- a/litellm/llms/custom_httpx/container_handler.py+++ b/litellm/llms/custom_httpx/container_handler.py@@@ -139,9 -139,9 +139,9 @@@ def _build_query_paramsreturn {name: value if isinstance(value, str) else str(value) for name, value in supplied if value is not None}- def _error_message_from_response(response: httpx.Response) -> str:+ def error_message_from_response(response: httpx.Response) -> str:try:- body: Final = response.json()+ body: Final[object] = response.json()except ValueError:return response.textdiff --cc litellm/llms/openai/responses/guardrail_translation/handler.pyindex d851375ed0e,ecc89c5f135..2dec2b3f178--- a/litellm/llms/openai/responses/guardrail_translation/handler.py+++ b/litellm/llms/openai/responses/guardrail_translation/handler.py@@@ -115,7 -118,200 +118,200 @@@ class ResponsesStreamChunk(TypedDict, tcontent_index: ReadOnly[int]+ _PATCHABLE_ITEM_FIELDS: Final[Mapping[str, str]] = MappingProxyType(+ {"function_call_output": "output", "message": "content"}+ )++ _EMPTY_RESPONSES_REQUEST: Final[ResponsesAPIOptionalRequestParams] = {}+++ def _item_rewrite_field(item: Mapping[str, object]) -> str | None:+ item_type: Final = item.get("type")+ if item_type is None:+ return "content" if "content" in item else None+ if not isinstance(item_type, str):+ return None+ return _PATCHABLE_ITEM_FIELDS.get(item_type)+++ def _rewritten_input_item(item: Mapping[str, object], rewritten: object) -> Mapping[str, object] | None:+ field: Final = _item_rewrite_field(item)+ if field is None or not isinstance(rewritten, Mapping):+ return None+ rewritten_content: Final = rewritten.get("content")+ if isinstance(item.get(field), str) and isinstance(rewritten_content, str):+ return {**item, field: rewritten_content} # mutable-ok: request input items must stay JSON-plain dicts+ rewritten_row: Final = cast("AllMessageValues", rewritten) # cast-ok: guardrails hand back chat-shaped rows+ converted_items, _ = LiteLLMResponsesTransformationHandler().convert_chat_completion_messages_to_responses_api(+ [rewritten_row] # mutable-ok: converter signature takes a list+ )+ if len(converted_items) != 1 or not isinstance(converted_items[0], Mapping):+ return None+ first_converted: Final = cast("Mapping[str, object]", converted_items[0]) # cast-ok: isinstance-checked above+ converted_value: Final = first_converted.get(field)+ if converted_value is None:+ return None+ return {**item, field: converted_value} # mutable-ok: request input items must stay JSON-plain dicts+++ def _is_function_call_item(item: object) -> bool:+ return isinstance(item, Mapping) and item.get("type") in ("function_call", "custom_tool_call")+++ def _last_message_role(messages: Sequence[object]) -> str | None:+ if not messages:+ return None+ last: Final = messages[-1]+ role: Final = last.get("role") if isinstance(last, Mapping) else getattr(last, "role", None)+ return role if isinstance(role, str) else None+++ def _provenance_unit_bounds(+ raw_input: Sequence[object],+ solo_conversions: Sequence[Sequence[object]],+ ) -> tuple[tuple[int, int], ...]:+ trailing_roles: Final = tuple(+ accumulate(+ (_last_message_role(messages) for messages in solo_conversions),+ lambda previous, current: current if current is not None else previous,+ )+ )+ start_indexes: Final = tuple(+ index+ for index in range(len(raw_input))+ if index == 0 or not (_is_function_call_item(raw_input[index]) and trailing_roles[index - 1] == "assistant")+ )+ return tuple(zip(start_indexes, (*start_indexes[1:], len(raw_input))))+++ def _input_item_provenance(+ raw_input: Sequence[object],+ expected_messages: Sequence[object],+ ) -> tuple[Mapping[int, int], frozenset[int]] | None:+ if not all(isinstance(item, Mapping) for item in raw_input):+ return None+ solo_conversions: Final = tuple(+ LiteLLMCompletionResponsesConfig.transform_responses_api_input_to_messages(+ input=cast("ResponseInputParam", [item]), # cast-ok: items checked as Mappings above+ responses_api_request=_EMPTY_RESPONSES_REQUEST,+ )+ for item in raw_input+ )+ full_conversion: Final = tuple(+ LiteLLMCompletionResponsesConfig.transform_responses_api_input_to_messages(+ input=cast("ResponseInputParam", list(raw_input)), # cast-ok: items checked as Mappings above+ responses_api_request=_EMPTY_RESPONSES_REQUEST,+ )+ )+ if full_conversion != tuple(expected_messages):+ return None+ units: Final = _provenance_unit_bounds(raw_input, solo_conversions)+ unit_messages: Final = tuple(+ tuple(solo_conversions[start])+ if end - start == 1+ else tuple(+ LiteLLMCompletionResponsesConfig.transform_responses_api_input_to_messages(+ input=cast("ResponseInputParam", list(raw_input[start:end])), # cast-ok: checked as Mappings above+ responses_api_request=_EMPTY_RESPONSES_REQUEST,+ )+ )+ for start, end in units+ )+ if tuple(message for messages in unit_messages for message in messages) != full_conversion:+ return None+ boundaries: Final = tuple(accumulate((len(messages) for messages in unit_messages), initial=0))+ item_for_message: Final = MappingProxyType(+ {+ message_index: start+ for unit_index, (start, end) in enumerate(units)+ if end - start == 1+ for message_index in range(boundaries[unit_index], boundaries[unit_index + 1])+ }+ )+ tainted: Final = frozenset(+ message_index+ for unit_index, (start, end) in enumerate(units)+ if end - start > 1+ for message_index in range(boundaries[unit_index], boundaries[unit_index + 1])+ )+ return item_for_message, tainted+++ class _RequestFields(NamedTuple):+ input: tuple[object, ...]+ instructions: str | None+++ class _ExtractedInputs(NamedTuple):+ inputs: GenericGuardrailAPIInputs+ task_mappings: tuple[tuple[int, int | None], ...]+++ def _patched_request_fields(+ raw_input: object,+ instructions: object,+ original_messages: Sequence[object],+ structured_messages: Sequence[object],+ ) -> _RequestFields | None:+ if not isinstance(raw_input, list) or len(original_messages) != len(structured_messages):+ return None+ offset: Final = 1 if instructions else 0+ provenance: Final = _input_item_provenance(raw_input, tuple(original_messages)[offset:])+ if provenance is None:+ return None+ item_for_message, tainted = provenance+ changed: Final = tuple(+ (index, rewritten)+ for index, (original, rewritten) in enumerate(zip(original_messages, structured_messages))+ if original != rewritten+ )+ instruction_rewrites: Final = tuple(rewritten for index, rewritten in changed if index < offset)+ rewritten_instructions: Final = (+ instruction_rewrites[0].get("content")+ if instruction_rewrites and isinstance(instruction_rewrites[0], Mapping)+ else instructions+ )+ instructions_value: Final = rewritten_instructions if isinstance(rewritten_instructions, str) else None+ if rewritten_instructions is not None and instructions_value is None:+ return None+ body_changes: Final = tuple((index - offset, rewritten) for index, rewritten in changed if index >= offset)+ if any(message_index in tainted or message_index not in item_for_message for message_index, _ in body_changes):+ return None+ replacements: Final = MappingProxyType(+ {+ item_for_message[message_index]: _rewritten_input_item(+ cast("Mapping[str, object]", raw_input[item_for_message[message_index]]), # cast-ok: checked Mappings+ rewritten,+ )+ for message_index, rewritten in body_changes+ }+ )+ if len(replacements) != len(body_changes) or any(item is None for item in replacements.values()):+ return None+ return _RequestFields(+ input=tuple(replacements.get(index, item) for index, item in enumerate(raw_input)),+ instructions=instructions_value,+ )+++ def _patch_or_convert_request_fields(+ raw_input: object,+ instructions: object,+ original_messages: Sequence[object],+ structured_messages: Sequence[AllMessageValues],+ ) -> _RequestFields | None:+ if not isinstance(structured_messages, list):+ return None+ patched: Final = _patched_request_fields(raw_input, instructions, original_messages, structured_messages)+ if patched is not None:+ return patched+ input_items, converted_instructions = (+ LiteLLMResponsesTransformationHandler().convert_chat_completion_messages_to_responses_api(structured_messages)+ )+ return _RequestFields(input=tuple(input_items), instructions=converted_instructions)++-def _next_stream_sequence_number(responses_so_far: Sequence[Any] | None) -> int:+def _next_stream_sequence_number(responses_so_far: Sequence[object] | None) -> int:sequence_numbers: Final = (item.get("sequence_number") if isinstance(item, dict) else getattr(item, "sequence_number", None)for item in reversed(responses_so_far or ())diff --cc litellm/proxy/client/cli/commands/agents.pyindex 5cf0bd6f89f,ce416ef237b..9f79240fe55--- a/litellm/proxy/client/cli/commands/agents.py+++ b/litellm/proxy/client/cli/commands/agents.py@@@ -7,8 -9,9 +9,9 @@@ from typing import Finaimport clickimport requests+ from pydantic import BaseModel, TypeAdapter, ValidationError-from .auth import context_secret_vault, get_stored_api_key, login+from .auth import CliContextObj, context_secret_vault, get_stored_api_key, loginfrom .cmd_quoting import quote_for_cmdANTHROPIC_BASE_URL_ENV: Final = "ANTHROPIC_BASE_URL"diff --cc litellm/proxy/container_endpoints/handler_factory.pyindex 95642bc74bc,cc742f0520b..3989bdacef1--- a/litellm/proxy/container_endpoints/handler_factory.py+++ b/litellm/proxy/container_endpoints/handler_factory.py@@@ -6,8 -6,10 +6,10 @@@ FastAPI route handlers for ALL containe"""import json+ from collections.abc import Mapping, Sequencefrom pathlib import Path+ from types import MappingProxyType-from typing import Any, Final+from typing import Finalfrom fastapi import APIRouter, Depends, Request, Responsefrom fastapi.responses import ORJSONResponse@@@ -357,7 -367,8 +367,8 @@@ async def _process_requestuser_api_key_dict: UserAPIKeyAuth,route_type: str,path_params: dict[str, str],+ query_param_names: Sequence[str] = (),-):+) -> object:"""Common request processing logic."""from litellm.proxy.proxy_server import (general_settings,@@@ -374,8 -385,9 +385,9 @@@)query_params: Final = dict(request.query_params)- data: Final[dict[str, Any]] = {+ data: Final[dict[str, object]] = {"query_params": query_params,+ **_declared_query_params(query_params, query_param_names),**path_params,}diff --cc litellm/proxy/guardrails/usage_tracking.pyindex 4f1d2380520,cb6aec14f8c..a20ad3935e5--- a/litellm/proxy/guardrails/usage_tracking.py+++ b/litellm/proxy/guardrails/usage_tracking.py@@@ -210,8 -240,8 +240,8 @@@ def _parse_payload_start_time(payload:def _iter_usage_unit_increments(- logs_to_process: Sequence[Mapping[str, Any]],+ logs_to_process: Sequence[Mapping[str, object]],- ) -> Iterator[tuple[_UsageUnitKey, int]]:+ ) -> Iterator[tuple[_UsageUnitKey, _UsageUnitIncrement]]:for payload in logs_to_process:start_time = _parse_payload_start_time(payload)if not payload.get("request_id") or start_time is None:@@@ -224,15 -254,23 +254,23 @@@usage = entry.get("guardrail_usage")if not guardrail_id or not isinstance(usage, dict):continue+ cost_by_unit = billed_guardrail_cost_by_unit(entry)for unit_name, units in usage.items():if isinstance(units, int) and not isinstance(units, bool) and units > 0:- yield _UsageUnitKey(guardrail_id, date_key, team_id, api_key, str(unit_name)), units+ key = _UsageUnitKey(guardrail_id, date_key, team_id, api_key, str(unit_name))+ cost = cost_by_unit.get(str(unit_name)) if cost_by_unit is not None else None+ yield key, _usage_unit_increment(units=units, cost=cost)- def _sum_usage_unit_increments(logs_to_process: Sequence[Mapping[str, object]]) -> Mapping[_UsageUnitKey, int]:+ def _sum_usage_unit_increments(- logs_to_process: Sequence[Mapping[str, Any]],++ logs_to_process: Sequence[Mapping[str, object]],+ ) -> Mapping[_UsageUnitKey, _UsageUnitIncrement]:ordered: Final = sorted(_iter_usage_unit_increments(logs_to_process), key=itemgetter(0))return MappingProxyType(- {key: sum(units for _, units in group) for key, group in groupby(ordered, key=itemgetter(0))}+ {+ key: _summed_increments(increment for _, increment in group)+ for key, group in groupby(ordered, key=itemgetter(0))+ })diff --cc litellm/proxy/management_endpoints/usage_endpoints/ai_usage_chat.pyindex 4fcc798f93c,7ef496f94e3..da4ddbd0aac--- a/litellm/proxy/management_endpoints/usage_endpoints/ai_usage_chat.py+++ b/litellm/proxy/management_endpoints/usage_endpoints/ai_usage_chat.py@@@ -4,9 -4,9 +4,9 @@@ usage/spend data by querying the aggreg"""import json- from collections.abc import AsyncIterator, Awaitable, Callable, Mapping, Sequence+ from collections.abc import AsyncGenerator, AsyncIterator, Awaitable, Callable, Mapping, Sequencefrom datetime import date-from typing import Any, Final, Literal, Protocol, cast, overload+from typing import Any, Final, Literal, NamedTuple, Protocol, cast, overloadfrom typing_extensions import ReadOnly, TypedDictdiff --cc litellm/proxy/vector_store_endpoints/utils.pyindex f224e02db32,6e94a5a88ac..f2070e6604c--- a/litellm/proxy/vector_store_endpoints/utils.py+++ b/litellm/proxy/vector_store_endpoints/utils.py@@@ -1,7 -1,8 +1,8 @@@import jsonimport re- from collections.abc import Mapping-from collections.abc import Iterable++from collections.abc import Iterable, Mapping+ from types import MappingProxyType-from typing import Any, Final, Literal+from typing import Final, Literalfrom fastapi import HTTPException, Requestdiff --cc ruff-strict-budget.jsonindex f9360a2308e,70408ea022b..3710b55ca0f--- a/ruff-strict-budget.json+++ b/ruff-strict-budget.json@@@ -6,16 -6,16 +6,16 @@@"limit": 71},"ANN003": {- "limit": 809+ "limit": 806},"ANN201": {- "limit": 1981- "limit": 1998++ "limit": 1979},"ANN202": {- "limit": 835+ "limit": 831},"ANN204": {- "limit": 693+ "limit": 683},"ANN205": {"limit": 112diff --cc type-discipline-budget.jsonindex 071f3418101,3d01c08e8eb..8bbe28d0d09--- a/type-discipline-budget.json+++ b/type-discipline-budget.json@@@ -1,9 -1,9 +1,9 @@@{"LIT001": {- "limit": 22188- "limit": 22326++ "limit": 22184},"LIT002": {- "limit": 26762- "limit": 26748++ "limit": 26747},"LIT003": {"limit": 261@@@ -27,12 -27,12 +27,12 @@@"limit": 0},"LIT010": {- "limit": 16477+ "limit": 16468},"LIT011": {- "limit": 5517- "limit": 5512++ "limit": 5510},"LIT012": {- "limit": 4488- "limit": 4487++ "limit": 4486}}