Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

Merge remote-tracking branch 'origin/litellm_internal_staging' into litellm_decrease_anys_opus5_r2

mateo-berrifb89695cee18
diff --cc litellm/litellm_core_utils/prompt_templates/common_utils.py
index fa1b57c894f,f0e5086b660..510592095df
--- a/litellm/litellm_core_utils/prompt_templates/common_utils.py
+++ b/litellm/litellm_core_utils/prompt_templates/common_utils.py
@@@ -1747,7 -1747,47 +1747,47 @@@ def hoist_images_from_tool_messages
]
+ def _is_tool_reference_part(part: object) -> bool:
+ return isinstance(part, dict) and part.get("type") == "tool_reference"
+
+
+ def _tool_message_carries_tool_reference(message: AllMessageValues) -> bool:
+ if message.get("role") != "tool":
+ return False
+ content = message.get("content")
+ return isinstance(content, list) and any(_is_tool_reference_part(part) for part in content)
+
+
+ def _drop_tool_reference_parts(message: AllMessageValues) -> AllMessageValues:
+ if not _tool_message_carries_tool_reference(message):
+ return message
+ content = cast(list, message.get("content")) # cast-ok: shape checked by _tool_message_carries_tool_reference
+ remaining_parts = [ # mutable-ok: tool message content must stay a json list
+ part for part in content if not _is_tool_reference_part(part)
+ ]
+ new_content = remaining_parts if remaining_parts else ""
+ rewritten = {**message, "content": new_content} # mutable-ok: chat messages are plain json dicts
+ return cast(AllMessageValues, rewritten) # cast-ok: dict spread keeps keys like cache_control
+
+
+ def drop_tool_reference_parts_from_tool_messages(
+ messages: list[AllMessageValues], # mutable-ok: message pipelines type messages as mutable lists
+ ) -> list[AllMessageValues]: # mutable-ok: message pipelines type messages as mutable lists
+ """
+ Remove tool_reference content parts from role:"tool" messages.
+
+ The OpenAI chat spec only accepts text in tool messages, so a tool_reference
+ part carried through the Anthropic adapter makes strict providers reject the
+ request. The reference names an already-declared tool rather than carrying
+ content, so it is dropped; a reference-only result keeps its tool message with
+ empty text so the preceding tool_call stays answered.
+ """
+ if not any(_tool_message_carries_tool_reference(message) for message in messages):
+ return messages
+ return [_drop_tool_reference_parts(message) for message in messages] # mutable-ok: pipelines mutate message lists
+
+
-def _attempt_json_repair(s: str) -> Any | None:
+def _attempt_json_repair(s: str) -> object | None:
"""
Attempt to repair truncated JSON produced by LLM tool calls.
diff --cc litellm/litellm_core_utils/token_counter.py
index f51e2122fca,256bee7b348..9e8976940e6
--- a/litellm/litellm_core_utils/token_counter.py
+++ b/litellm/litellm_core_utils/token_counter.py
@@@ -3,10 -3,9 +3,10 @@@
import base64
import io
import struct
- from collections.abc import Callable, Mapping
+ from collections.abc import Callable, Iterable, Mapping, Sequence
-from typing import Any, Final, Literal, cast
+from typing import Final, Literal, cast
+import httpx
import tiktoken
import litellm
@@@ -651,8 -653,48 +658,48 @@@ def _validate_anthropic_content(content
return expected_cls
+ def _anthropic_image_source_data(
+ source: AnthropicContentParamSource | AnthropicContentParamSourceUrl | AnthropicContentParamSourceFileId,
+ ) -> str:
+ if source["type"] == "base64":
+ data: Final = source.get("data")
+ if not data:
+ return ""
+ media_type: Final = source.get("media_type") or "image/png"
+ return f"data:{media_type};base64,{data}"
+ if source["type"] == "url":
+ return source.get("url") or ""
+ return ""
+
+
+ def _count_document_tokens(
+ document: ChatCompletionDocumentObject | AnthropicMessagesDocumentParam,
+ count_function: TokenCounterFunction,
+ use_default_image_token_count: bool,
+ default_token_count: int | None,
+ ) -> int:
+ source: Final = document["source"]
+ metadata_tokens: Final = sum(
+ count_function(text) for text in (document.get("title"), document.get("context")) if text
+ )
+ if source["type"] == "text":
+ return metadata_tokens + count_function(source["data"])
+ if source["type"] == "content":
+ content: Final = source["content"]
+ if isinstance(content, str):
+ return metadata_tokens + count_function(content)
+ return metadata_tokens + _count_content_list(
+ count_function, content, use_default_image_token_count, default_token_count
+ )
+ return metadata_tokens + calculate_img_tokens(
+ data=_anthropic_image_source_data(source),
+ mode="auto",
+ use_default_image_token_count=use_default_image_token_count,
+ )
+
+
def _count_anthropic_content(
- content: Mapping[str, Any],
+ content: Mapping[str, object],
count_function: TokenCounterFunction,
use_default_image_token_count: bool,
default_token_count: int | None,
diff --cc litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py
index 90f87e38842,a9fa00c827a..40c81eb715b
--- a/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py
+++ b/litellm/llms/anthropic/experimental_pass_through/adapters/transformation.py
@@@ -18,24 -18,22 +18,40 @@@ TOOL_NAME_PREFIX_LENGTH: Final = OPENAI
PROVIDERS_PROXYING_AN_UNKNOWN_BACKEND: Final = frozenset({"litellm_proxy"})
+def _optional_attr(source: object, name: str) -> object:
+ return getattr(source, name, None)
+
+
+def _as_string_mapping(value: object) -> Mapping[str, object] | None:
+ if isinstance(value, Mapping):
+ return value
+ return None
+
+
+def _thought_signature(provider_specific_fields: object) -> str | None:
+ fields: Final = _as_string_mapping(provider_specific_fields)
+ if fields is None:
+ return None
+ signature: Final = fields.get("thought_signature")
+ return signature if isinstance(signature, str) else None
+
+
+ _ANTHROPIC_TOOL_SCHEMA_KEYS: Final = frozenset(
+ {"name", "type", "input_schema", "description", "cache_control", "strict"}
+ )
+
+
+ def _is_openai_function_tool(tool: Mapping[str, object]) -> bool:
+ return tool.get("type") == "function" and "function" in tool
+
+
+ def is_provider_native_tool_dict(tool: Mapping[str, object]) -> bool:
+ if len(tool) != 1:
+ return False
+ key, value = next(iter(tool.items()))
+ return key not in _ANTHROPIC_TOOL_SCHEMA_KEYS and isinstance(value, dict)
+
+
def truncate_tool_name(name: str) -> str:
"""
Truncate tool names that exceed OpenAI's 64-character limit.
diff --cc litellm/llms/gemini/realtime/transformation.py
index 0b1dabbef33,367619db37d..c92af7de145
--- a/litellm/llms/gemini/realtime/transformation.py
+++ b/litellm/llms/gemini/realtime/transformation.py
@@@ -4,11 -4,9 +4,11 @@@ This file contains the transformation l
import json
from collections import OrderedDict
- from collections.abc import Mapping
+ from collections.abc import Mapping, Sequence
from typing import Any, Final, cast
+from typing_extensions import ReadOnly, Required, TypedDict
+
import litellm
from litellm import verbose_logger
from litellm._uuid import uuid
@@@ -97,23 -96,18 +98,35 @@@ def _gemini_live_speech_config(voice: o
return VertexGeminiConfig()._map_audio_params({"voice": voice})
+class _GeminiLiveSetupEnvelope(TypedDict, total=False):
+ setup: ReadOnly[BidiGenerateContentSetup]
+
+
+class _OpenAIRealtimeClientEvent(TypedDict, total=False):
+ type: ReadOnly[str]
+ audio: ReadOnly[Required[str]]
+ session: ReadOnly[dict[str, object]]
+ item: ReadOnly[dict[str, object]]
+
+
+def _parse_setup(session_configuration_request: str) -> BidiGenerateContentSetup:
+ envelope: Final[_GeminiLiveSetupEnvelope] = json.loads(session_configuration_request)
+ empty_setup: Final[BidiGenerateContentSetup] = {}
+ return envelope.get("setup", empty_setup)
+
+
+ # Google bills Live transcription at an estimated 25 audio tokens/sec of input and
+ # 175 text tokens/min of output (ai.google.dev/gemini-api/docs/pricing).
+ GEMINI_LIVE_TRANSCRIBE_AUDIO_TOKENS_PER_SECOND: Final = 25
+ GEMINI_LIVE_TRANSCRIBE_OUTPUT_TEXT_TOKENS_PER_MINUTE: Final = 175
+ PCM16_INPUT_AUDIO_BYTES_PER_SECOND: Final = 48000
+
+
+ def _base64_decoded_byte_count(data: str) -> int:
+ padding: Final = 2 if data.endswith("==") else 1 if data.endswith("=") else 0
+ return max(len(data) * 3 // 4 - padding, 0)
+
+
class GeminiRealtimeConfig(BaseRealtimeConfig):
_TOOL_CALL_ID_TO_NAME_MAX = 256 # LRU cap for call_id→name mapping
@@@ -405,17 -398,25 +419,25 @@@
return bool(entry.get("gemini_native_audio") or entry.get("gemini_audio_only_live"))
@staticmethod
- def _coerce_response_modalities(model: str, modalities: list[object]) -> list[str]:
- """Map unsupported TEXT responseModalities to AUDIO for audio-only Live models."""
- normalized: Final = [
+ def _is_text_only_live_model(model: str) -> bool:
+ return GeminiRealtimeConfig._model_cost_entry(model).get("mode") == "audio_transcription"
+
+ @staticmethod
+ def _default_response_modality(model: str) -> GeminiResponseModalities:
+ return "TEXT" if GeminiRealtimeConfig._is_text_only_live_model(model) else "AUDIO"
+
+ @staticmethod
- def _coerce_response_modalities(model: str, modalities: Sequence[Any]) -> tuple[str, ...]:
++ def _coerce_response_modalities(model: str, modalities: Sequence[object]) -> tuple[str, ...]:
+ """Swap responseModalities a Live model cannot produce: TEXT to AUDIO for
+ audio-only models, AUDIO to TEXT for text-only ones (e.g. transcribe-live)."""
+ normalized: Final = tuple(
modality.upper() if isinstance(modality, str) else str(modality).upper() for modality in modalities
- ]
- if not GeminiRealtimeConfig._is_audio_only_live_model(model):
- return normalized
- if "TEXT" not in normalized:
- return normalized
- without_text: Final = [modality for modality in normalized if modality != "TEXT"]
- return without_text if without_text else ["AUDIO"]
+ )
+ if GeminiRealtimeConfig._is_audio_only_live_model(model) and "TEXT" in normalized:
+ return tuple(modality for modality in normalized if modality != "TEXT") or ("AUDIO",)
+ if GeminiRealtimeConfig._is_text_only_live_model(model) and "AUDIO" in normalized:
+ return tuple(modality for modality in normalized if modality != "AUDIO") or ("TEXT",)
+ return normalized
@staticmethod
def _finalize_gemini_live_setup(model: str, setup: dict[str, Any]) -> dict[str, Any]:
diff --cc litellm/proxy/guardrails/guardrail_hooks/presidio.py
index a942dd70611,8d78393d687..da51a905ae3
--- a/litellm/proxy/guardrails/guardrail_hooks/presidio.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/presidio.py
@@@ -11,10 -11,10 +11,10 @@@
import asyncio
import json
import threading
- from collections.abc import AsyncGenerator, AsyncIterable, Awaitable
-from collections.abc import AsyncGenerator, Sequence
++from collections.abc import AsyncGenerator, AsyncIterable, Awaitable, Sequence
from contextlib import asynccontextmanager
from datetime import datetime
-from typing import TYPE_CHECKING, Any, Final, Literal, Optional, TypedDict, cast
+from typing import TYPE_CHECKING, Any, Final, Literal, Optional, Protocol, TypedDict, cast
import aiohttp
from typing_extensions import NotRequired, ReadOnly
@@@ -63,14 -68,18 +68,26 @@@ class _PresidioAnonymizeResponse(TypedD
items: ReadOnly[NotRequired[list[_PresidioAnonymizeItem]]]
+class _JsonResponse(Protocol):
+ def json(self) -> Awaitable[object]: ...
+
+
+async def _json_body(response: _JsonResponse) -> object:
+ return await response.json()
+
+
+ _LoopSemaphores = dict[asyncio.AbstractEventLoop, asyncio.Semaphore]
+
+
+ def _json_escaped_len(text: str) -> int:
+ """
+ Byte length of ``text`` as it appears serialized inside the JSON request
+ body sent to Presidio (``json.dumps`` escapes non-ASCII characters, so a
+ 3-byte UTF-8 character can occupy 6+ bytes on the wire).
+ """
+ return len(json.dumps(text).encode("utf-8")) - 2 # strip the surrounding quotes
+
+
class _OPTIONAL_PresidioPIIMasking(CustomGuardrail):
user_api_key_cache = None
ad_hoc_recognizers: list[str] | None = None
diff --cc litellm/proxy/litellm_pre_call_utils.py
index da54c8d6de5,b7688790e54..efa7cb04315
--- a/litellm/proxy/litellm_pre_call_utils.py
+++ b/litellm/proxy/litellm_pre_call_utils.py
@@@ -51,9 -51,10 +52,10 @@@ from litellm.proxy.common_utils.callbac
strip_callback_config,
)
from litellm.proxy.common_utils.http_parsing_utils import _safe_get_request_headers
+ from litellm.types.integrations.anthropic_cache_control_hook import GATEWAY_INJECTED_CACHE_METADATA_KEY
# Cache special headers as a frozenset for O(1) lookup performance
-_SPECIAL_HEADERS_CACHE: Final = frozenset(v.value.lower() for v in SpecialHeaders._member_map_.values())
+_SPECIAL_HEADERS_CACHE: Final = frozenset(str(v.value).lower() for v in SpecialHeaders)
_REDACTED_HEADER_VALUE: Final = "***REDACTED***"
_CREDENTIAL_HEADER_NAMES: Final = SpecialHeaders.litellm_credential_header_names() | frozenset(