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: litellm_internal_staging into litellm_fix_headroom_stream_leak

mateo-berri4ab654cbc5d5
diff --cc litellm/integrations/custom_logger.py
index 60af4063f84,195eb85c07d..0339be106ea
--- a/litellm/integrations/custom_logger.py
+++ b/litellm/integrations/custom_logger.py
@@@ -60,8 -60,25 +60,26 @@@ _BASE64_INLINE_PATTERN: Final = re.comp
class CustomLogger: # https://docs.litellm.ai/docs/observability/custom_callback#callback-class
# Class variables or attributes
+ server_fulfilled_tool_names: ClassVar[frozenset[str]] = frozenset()
+ enforces_request_content: bool = False
+ """
+ Whether this hook's ``async_pre_call_hook`` judges the request payload itself.
+
+ False for the accounting hooks, which count a request rather than read it: rate limits,
+ parallel slots, budgets, cache lookups. Those must run once per request and never once per
+ record of a batch upload, which would charge a caller once for every line of their file.
+
+ Set it to True on a hook that inspects or rejects content, so that scanning a payload which
+ is not itself a request, such as one record of a batch input file, still reaches it. A
+ ``CustomGuardrail`` does not need it; guardrails are dispatched by their own branch.
+
+ Judging content is necessary but not sufficient. A hook that also rewrites the payload for
+ routing, as the managed-files and managed-vector-store hooks do, stays False: a per-record
+ rewrite would read as a redaction and ship embedded in the record. Only the leaf class is
+ consulted, so a subclass that does not override ``async_pre_call_hook`` inherits nothing.
+ """
+
def __init__(
self,
turn_off_message_logging: bool = False,
diff --cc litellm/proxy/common_request_processing.py
index 3aeb7729c81,6fd743deb44..33d5ec31313
--- a/litellm/proxy/common_request_processing.py
+++ b/litellm/proxy/common_request_processing.py
@@@ -26,8 -28,8 +28,9 @@@ from litellm.constants import
LITELLM_HTTP_STATUS_CLIENT_DISCONNECTED,
MAX_PAYLOAD_SIZE_FOR_DEBUG_LOG,
RETURN_RAW_MODEL_NAME_METADATA_KEY,
+ ROUTER_MODEL_NAME_RESPONSE_FIELD,
STREAM_SSE_DATA_PREFIX,
+ STREAM_SSE_KEEPALIVE_PING_BYTES,
UNSAFE_PROXY_RESPONSE_HEADERS,
)
from litellm.integrations.custom_guardrail import CustomGuardrail
@@@ -40,9 -44,9 +45,12 @@@ from litellm.litellm_core_utils.llm_res
get_response_headers,
)
from litellm.litellm_core_utils.safe_json_dumps import safe_dumps
+ from litellm.litellm_core_utils.streaming_handler import (
+ backfill_missing_cache_usage_fields,
+ )
+from litellm.llms.anthropic.experimental_pass_through.messages.agentic_streaming_iterator import (
+ AgenticAnthropicStreamingIterator,
+)
from litellm.proxy._types import ProxyException, UserAPIKeyAuth
from litellm.proxy.auth.auth_checks import can_key_call_resolved_model
from litellm.proxy.auth.auth_utils import check_response_size_is_safe
diff --cc litellm/proxy/common_utils/sse_keepalive.py
index 6e0ea4db431,6fba9e96f6e..429fff99ae6
--- a/litellm/proxy/common_utils/sse_keepalive.py
+++ b/litellm/proxy/common_utils/sse_keepalive.py
@@@ -6,12 -6,18 +6,20 @@@ from typing import Fina
import anyio
-ANTHROPIC_PING_SSE_CHUNK: Final = 'event: ping\ndata: {"type": "ping"}\n\n'
+from litellm.constants import STREAM_SSE_KEEPALIVE_PING_CHUNK
+
+ANTHROPIC_PING_SSE_CHUNK: Final = STREAM_SSE_KEEPALIVE_PING_CHUNK
+ SSE_COMMENT_PING: Final = ": ping\n\n"
+ SSE_COMMENT_PING_BYTES: Final = SSE_COMMENT_PING.encode()
+ # The byte form of proxy_server._SSE_FRAME_DELIMITERS, CR-only included: SSE
+ # terminates a line with CRLF, LF or CR, so a blank line is any of these three.
+ _SSE_FRAME_DELIMITERS: Final = (b"\r\n\r\n", b"\n\n", b"\r\r")
+ _SSE_DELIMITER_LOOKBACK: Final = max(len(delimiter) for delimiter in _SSE_FRAME_DELIMITERS)
+ _STREAM_START_TAIL: Final = b"\n\n"
+ _SSE_MEDIA_TYPE: Final = "text/event-stream"
- def _coerce_interval(ping_interval_seconds: float | str | None) -> float | None:
+ def coerce_keepalive_interval(ping_interval_seconds: float | str | None) -> float | None:
if ping_interval_seconds is None:
return None
try:
diff --cc tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_agentic_streaming_iterator.py
index b0467430533,db8aae6702f..015b5754c6e
--- a/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_agentic_streaming_iterator.py
+++ b/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_agentic_streaming_iterator.py
@@@ -2,20 -2,14 +2,17 @@@
Tests for AgenticAnthropicStreamingIterator and SSE rebuild helpers.
"""
+import asyncio
import json
- import os
- import sys
from typing import Any, Dict, List, Optional, Tuple
from unittest.mock import AsyncMock, MagicMock
import pytest
- sys.path.insert(0, os.path.abspath("../../../../.."))
+from litellm.constants import STREAM_SSE_KEEPALIVE_PING_BYTES
from litellm.llms.anthropic.experimental_pass_through.messages.agentic_streaming_iterator import (
+ SERVER_FULFILLED_TOOL_LEAK_ERROR_SSE_BYTES,
AgenticAnthropicStreamingIterator,
_handle_content_block_delta,
_handle_content_block_start,
@@@ -840,265 -787,3 +837,269 @@@ class TestAgenticStreamingIteratorError
call_kwargs = mock_handler._call_agentic_completion_hooks.call_args
assert call_kwargs.kwargs["stream"] is True
+
+
+class TestAgenticStreamingIteratorHoldBack:
+ @pytest.mark.asyncio
+ async def test_should_not_leak_intercepted_message_when_follow_up_fires(self):
+ """The buffered tool_use message must be dropped: only pings and follow-up bytes reach the client."""
+ phase1_chunks = _build_tool_use_stream()
+ phase2_chunks = [b"follow-up-chunk-1", b"follow-up-chunk-2"]
+
+ mock_handler = MagicMock()
+ mock_handler._call_agentic_completion_hooks = AsyncMock(return_value=MockAsyncStream(phase2_chunks))
+
+ iterator = _build_hold_back_iterator(MockAsyncStream(phase1_chunks), mock_handler)
+
+ collected = []
+ async for chunk in iterator:
+ collected.append(chunk)
+
+ non_ping = [c for c in collected if c != STREAM_SSE_KEEPALIVE_PING_BYTES]
+ assert non_ping == phase2_chunks
+ assert b"litellm_content_retrieve" not in b"".join(collected)
+ assert collected[0] == STREAM_SSE_KEEPALIVE_PING_BYTES
+
+ @pytest.mark.asyncio
+ async def test_should_replay_buffer_verbatim_when_no_hook_fires(self):
+ """Without interception the buffered message is replayed byte-identical after the pings."""
+ chunks = _build_simple_text_stream()
+
+ mock_handler = MagicMock()
+ mock_handler._call_agentic_completion_hooks = AsyncMock(return_value=None)
+
+ iterator = _build_hold_back_iterator(MockAsyncStream(chunks), mock_handler)
+
+ collected = []
+ async for chunk in iterator:
+ collected.append(chunk)
+
+ assert [c for c in collected if c != STREAM_SSE_KEEPALIVE_PING_BYTES] == chunks
+ mock_handler._call_agentic_completion_hooks.assert_awaited_once()
+
+ @pytest.mark.asyncio
+ async def test_should_emit_pings_while_upstream_is_slow(self):
+ """Pings keep the client connection alive while the upstream message is buffered."""
+ chunks = _build_simple_text_stream()
+
+ mock_handler = MagicMock()
+ mock_handler._call_agentic_completion_hooks = AsyncMock(return_value=None)
+
+ iterator = _build_hold_back_iterator(
+ MockSlowAsyncStream(chunks, delay_seconds=0.05),
+ mock_handler,
+ ping_interval_seconds=0.02,
+ )
+
+ collected = []
+ async for chunk in iterator:
+ collected.append(chunk)
+
+ assert collected.count(STREAM_SSE_KEEPALIVE_PING_BYTES) >= 2
+ assert [c for c in collected if c != STREAM_SSE_KEEPALIVE_PING_BYTES] == chunks
+
+ @pytest.mark.asyncio
+ async def test_should_propagate_upstream_error_instead_of_partial_message(self):
+ """An upstream failure surfaces as an error; the client never receives a truncated message."""
+ chunks = _build_simple_text_stream()[:2]
+
+ mock_handler = MagicMock()
+ mock_handler._call_agentic_completion_hooks = AsyncMock(return_value=None)
+
+ iterator = _build_hold_back_iterator(
+ MockFailingAsyncStream(chunks, RuntimeError("upstream died")),
+ mock_handler,
+ )
+
+ collected = []
- with pytest.raises(RuntimeError, match="upstream died"):
++
++ async def _drain():
+ async for chunk in iterator:
+ collected.append(chunk)
+
++ with pytest.raises(RuntimeError, match="upstream died"):
++ await _drain()
++
+ assert all(c == STREAM_SSE_KEEPALIVE_PING_BYTES for c in collected)
+ mock_handler._call_agentic_completion_hooks.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_should_emit_pings_while_hooks_are_slow(self):
+ """Retrieval and follow-up generation can outlast a client's idle timeout, so hooks get keepalives too."""
+ chunks = _build_tool_use_stream()
+ phase2_chunks = [b"follow-up-chunk"]
+
+ async def slow_hooks(**_kwargs):
+ await asyncio.sleep(0.12)
+ return MockAsyncStream(phase2_chunks)
+
+ mock_handler = MagicMock()
+ mock_handler._call_agentic_completion_hooks = AsyncMock(side_effect=slow_hooks)
+
+ iterator = _build_hold_back_iterator(
+ MockAsyncStream(chunks),
+ mock_handler,
+ ping_interval_seconds=0.02,
+ )
+
+ collected = []
+ async for chunk in iterator:
+ collected.append(chunk)
+
+ assert collected.count(STREAM_SSE_KEEPALIVE_PING_BYTES) >= 4
+ assert [c for c in collected if c != STREAM_SSE_KEEPALIVE_PING_BYTES] == phase2_chunks
+
+ @pytest.mark.asyncio
+ async def test_should_error_instead_of_replaying_server_fulfilled_tool_use_when_hook_crashes(self):
+ """A hook crash must not replay the buffered retrieval tool_use: that is the unknown-tool bug."""
+ chunks = _build_tool_use_stream()
+
+ mock_handler = MagicMock()
+ mock_handler._call_agentic_completion_hooks = AsyncMock(side_effect=RuntimeError("hook exploded"))
+
+ iterator = _build_hold_back_iterator(MockAsyncStream(chunks), mock_handler)
+
+ collected = []
+ async for chunk in iterator:
+ collected.append(chunk)
+
+ assert [c for c in collected if c != STREAM_SSE_KEEPALIVE_PING_BYTES] == [SERVER_FULFILLED_TOOL_LEAK_ERROR_SSE_BYTES]
+ assert b"litellm_content_retrieve" not in b"".join(collected)
+
+ @pytest.mark.asyncio
+ async def test_should_error_instead_of_replaying_when_no_hook_fires_on_tool_use(self):
+ """Hooks returning None on a retrieval tool_use is still a leak, so the turn fails loudly."""
+ chunks = _build_tool_use_stream()
+
+ mock_handler = MagicMock()
+ mock_handler._call_agentic_completion_hooks = AsyncMock(return_value=None)
+
+ iterator = _build_hold_back_iterator(MockAsyncStream(chunks), mock_handler)
+
+ collected = []
+ async for chunk in iterator:
+ collected.append(chunk)
+
+ assert [c for c in collected if c != STREAM_SSE_KEEPALIVE_PING_BYTES] == [SERVER_FULFILLED_TOOL_LEAK_ERROR_SSE_BYTES]
+
+ @pytest.mark.asyncio
+ async def test_should_replay_client_owned_tool_use_verbatim(self):
+ """Only server-fulfilled tools are withheld: a client's own tool_use still reaches it byte-identical."""
+ chunks = _build_tool_use_stream()
+
+ mock_handler = MagicMock()
+ mock_handler._call_agentic_completion_hooks = AsyncMock(return_value=None)
+
+ iterator = _build_hold_back_iterator(
+ MockAsyncStream(chunks),
+ mock_handler,
+ server_fulfilled_tool_names=frozenset({"headroom_retrieve"}),
+ )
+
+ collected = []
+ async for chunk in iterator:
+ collected.append(chunk)
+
+ assert [c for c in collected if c != STREAM_SSE_KEEPALIVE_PING_BYTES] == chunks
+
+ @pytest.mark.asyncio
+ async def test_should_emit_pings_while_the_follow_up_stream_is_slow(self):
+ """The corrected answer can be slow to generate, so the follow-up stream gets keepalives too."""
+ chunks = _build_tool_use_stream()
+ phase2_chunks = [b"follow-up-chunk-1", b"follow-up-chunk-2"]
+
+ mock_handler = MagicMock()
+ mock_handler._call_agentic_completion_hooks = AsyncMock(
+ return_value=MockSlowAsyncStream(phase2_chunks, delay_seconds=0.06)
+ )
+
+ iterator = _build_hold_back_iterator(
+ MockAsyncStream(chunks),
+ mock_handler,
+ ping_interval_seconds=0.02,
+ )
+
+ collected = []
+ async for chunk in iterator:
+ collected.append(chunk)
+
+ first_follow_up_index = collected.index(phase2_chunks[0])
+ assert collected[first_follow_up_index + 1] == STREAM_SSE_KEEPALIVE_PING_BYTES
+ assert [c for c in collected if c != STREAM_SSE_KEEPALIVE_PING_BYTES] == phase2_chunks
+
+ @pytest.mark.asyncio
+ async def test_should_propagate_follow_up_stream_error(self):
+ """A failing follow-up stream surfaces its error instead of hanging on pings forever."""
+ chunks = _build_tool_use_stream()
+
+ mock_handler = MagicMock()
+ mock_handler._call_agentic_completion_hooks = AsyncMock(
+ return_value=MockFailingAsyncStream([b"follow-up-chunk"], RuntimeError("follow-up died"))
+ )
+
+ iterator = _build_hold_back_iterator(MockAsyncStream(chunks), mock_handler, ping_interval_seconds=0.02)
+
+ with pytest.raises(RuntimeError, match="follow-up died"):
+ async for _ in iterator:
+ pass
+
+ @pytest.mark.asyncio
+ async def test_aclose_cancels_in_flight_follow_up_chunk_task(self):
+ """Closing while a follow-up chunk is pending must not orphan that task."""
+ chunks = _build_tool_use_stream()
+
+ mock_handler = MagicMock()
+ mock_handler._call_agentic_completion_hooks = AsyncMock(
+ return_value=MockSlowAsyncStream([b"follow-up-chunk"], delay_seconds=5.0)
+ )
+
+ iterator = _build_hold_back_iterator(MockAsyncStream(chunks), mock_handler, ping_interval_seconds=0.02)
+
+ while iterator._follow_up_chunk_task is None:
+ await iterator.__anext__()
+
+ await iterator.aclose()
+ assert iterator._follow_up_chunk_task.cancelled()
+
+ @pytest.mark.asyncio
+ async def test_aclose_cancels_drain_task(self):
+ """Closing the iterator mid-buffer must cancel the background drain task."""
+ chunks = _build_simple_text_stream()
+
+ mock_handler = MagicMock()
+ mock_handler._call_agentic_completion_hooks = AsyncMock(return_value=None)
+
+ iterator = _build_hold_back_iterator(
+ MockSlowAsyncStream(chunks, delay_seconds=5.0),
+ mock_handler,
+ )
+
+ first = await iterator.__anext__()
+ assert first == STREAM_SSE_KEEPALIVE_PING_BYTES
+ assert iterator._drain_task is not None
+
+ await iterator.aclose()
+ assert iterator._drain_task.cancelled()
+
+ @pytest.mark.asyncio
+ async def test_aclose_cancels_in_flight_hook_task(self):
+ """Closing while hooks are running must not leave the retrieval follow-up task orphaned."""
+ chunks = _build_tool_use_stream()
+
+ async def never_finishing_hooks(**_kwargs):
+ await asyncio.sleep(5.0)
+
+ mock_handler = MagicMock()
+ mock_handler._call_agentic_completion_hooks = AsyncMock(side_effect=never_finishing_hooks)
+
+ iterator = _build_hold_back_iterator(
+ MockAsyncStream(chunks),
+ mock_handler,
+ ping_interval_seconds=0.02,
+ )
+
+ while iterator._hook_task is None:
+ await iterator.__anext__()
+
+ await iterator.aclose()
+ assert iterator._hook_task.cancelled()
diff --cc tests/test_litellm/llms/custom_httpx/test_llm_http_handler.py
index 798fb4c92e2,a93b14d45f3..387cd8760eb
--- a/tests/test_litellm/llms/custom_httpx/test_llm_http_handler.py
+++ b/tests/test_litellm/llms/custom_httpx/test_llm_http_handler.py
@@@ -2073,72 -2146,512 +2146,583 @@@ async def test_anthropic_invalid_thinki
assert retry_authorization != first_attempt_headers["Authorization"]
+class TestServerFulfilledToolsInRequest:
+ """_server_fulfilled_tools_in_request gates the buffered (non-leaking) streaming
+ mode for server-fulfilled tools like headroom_retrieve."""
+
+ @staticmethod
+ def _logging_obj_with(callbacks):
+ logging_obj = Mock()
+ logging_obj.dynamic_success_callbacks = callbacks
+ return logging_obj
+
+ def test_should_hold_back_when_callback_owns_tool_in_request(self):
+ from litellm.integrations.custom_logger import CustomLogger
+
+ class RetrievalCallback(CustomLogger):
+ server_fulfilled_tool_names = frozenset({"headroom_retrieve"})
+
+ tools = [
+ {"name": "Bash", "input_schema": {"type": "object"}},
+ {"name": "headroom_retrieve", "input_schema": {"type": "object"}},
+ ]
+ assert BaseLLMHTTPHandler._server_fulfilled_tools_in_request(
+ logging_obj=self._logging_obj_with([RetrievalCallback()]), tools=tools
+ ) == frozenset({"headroom_retrieve"})
+
+ def test_should_stream_live_when_tool_absent_from_request(self):
+ from litellm.integrations.custom_logger import CustomLogger
+
+ class RetrievalCallback(CustomLogger):
+ server_fulfilled_tool_names = frozenset({"headroom_retrieve"})
+
+ tools = [{"name": "Bash", "input_schema": {"type": "object"}}]
+ assert (
+ BaseLLMHTTPHandler._server_fulfilled_tools_in_request(
+ logging_obj=self._logging_obj_with([RetrievalCallback()]), tools=tools
+ )
+ == frozenset()
+ )
+
+ def test_should_stream_live_when_no_callback_declares_tool_names(self):
+ from litellm.integrations.custom_logger import CustomLogger
+
+ tools = [{"name": "headroom_retrieve", "input_schema": {"type": "object"}}]
+ assert (
+ BaseLLMHTTPHandler._server_fulfilled_tools_in_request(
+ logging_obj=self._logging_obj_with([CustomLogger()]), tools=tools
+ )
+ == frozenset()
+ )
+
+ def test_should_stream_live_without_tools(self):
+ assert (
+ BaseLLMHTTPHandler._server_fulfilled_tools_in_request(logging_obj=self._logging_obj_with([]), tools=None)
+ == frozenset()
+ )
+
+ def test_interception_callbacks_declare_their_retrieval_tools(self):
+ from litellm.integrations.compression_interception.handler import (
+ LITELLM_CONTENT_RETRIEVE_TOOL_NAME,
+ CompressionInterceptionLogger,
+ )
+ from litellm.proxy.guardrails.guardrail_hooks.headroom.headroom import (
+ HEADROOM_RETRIEVE_TOOL_NAME,
+ HeadroomGuardrail,
+ )
+
+ assert HeadroomGuardrail.server_fulfilled_tool_names == frozenset({HEADROOM_RETRIEVE_TOOL_NAME})
+ assert CompressionInterceptionLogger.server_fulfilled_tool_names == frozenset(
+ {LITELLM_CONTENT_RETRIEVE_TOOL_NAME}
+ )
++
++
+ def _make_stub_direct_vector_store_config(response):
+ from litellm.llms.base_llm.vector_store.transformation import (
+ BaseDirectVectorStoreConfig,
+ )
+
+ class StubDirectVectorStoreConfig(BaseDirectVectorStoreConfig):
+ def __init__(self):
+ super().__init__()
+ self.sync_calls = []
+ self.async_calls = []
+
+ def execute_search_vector_store_request(self, **kwargs):
+ self.sync_calls.append(kwargs)
+ return response
+
+ async def aexecute_search_vector_store_request(self, **kwargs):
+ self.async_calls.append(kwargs)
+ return response
+
+ return StubDirectVectorStoreConfig()
+
+
+ def test_vector_store_search_handler_direct_config_sync_skips_http():
+ handler = BaseLLMHTTPHandler()
+ stub_response = {"object": "vector_store.search_results.page", "search_query": "q", "data": []}
+ config = _make_stub_direct_vector_store_config(stub_response)
+ logging_obj = Mock()
+
+ with patch("litellm.llms.custom_httpx.llm_http_handler._get_httpx_client") as mock_get_client:
+ result = handler.vector_store_search_handler(
+ vector_store_id="vs_direct",
+ query="q",
+ vector_store_search_optional_params={"max_num_results": 4},
+ vector_store_provider_config=config,
+ custom_llm_provider="valkey",
+ litellm_params=GenericLiteLLMParams(valkey_host="localhost"),
+ logging_obj=logging_obj,
+ timeout=12.5,
+ _is_async=False,
+ )
+
+ assert result is stub_response
+ mock_get_client.assert_not_called()
+ assert len(config.sync_calls) == 1
+ call = config.sync_calls[0]
+ assert call["vector_store_id"] == "vs_direct"
+ assert call["query"] == "q"
+ assert call["timeout"] == 12.5
+ assert call["vector_store_search_optional_params"] == {"max_num_results": 4}
+ assert isinstance(call["litellm_params"], dict)
+ assert call["litellm_params"]["valkey_host"] == "localhost"
+ pre_call_args = logging_obj.pre_call.call_args.kwargs["additional_args"]
+ assert pre_call_args["query"] == "q"
+ assert pre_call_args["vector_store_id"] == "vs_direct"
+
+
+ @pytest.mark.asyncio
+ async def test_vector_store_search_handler_direct_config_async_skips_http():
+ handler = BaseLLMHTTPHandler()
+ stub_response = {"object": "vector_store.search_results.page", "search_query": "q", "data": []}
+ config = _make_stub_direct_vector_store_config(stub_response)
+ logging_obj = Mock()
+
+ with patch("litellm.llms.custom_httpx.llm_http_handler.get_async_httpx_client") as mock_get_client:
+ result = await handler.vector_store_search_handler(
+ vector_store_id="vs_direct",
+ query=["q1", "q2"],
+ vector_store_search_optional_params={},
+ vector_store_provider_config=config,
+ custom_llm_provider="valkey",
+ litellm_params=GenericLiteLLMParams(valkey_host="localhost"),
+ logging_obj=logging_obj,
+ timeout=7.0,
+ _is_async=True,
+ )
+
+ assert result is stub_response
+ mock_get_client.assert_not_called()
+ assert len(config.async_calls) == 1
+ assert config.async_calls[0]["query"] == ["q1", "q2"]
+ assert config.async_calls[0]["litellm_params"]["valkey_host"] == "localhost"
+ assert config.async_calls[0]["timeout"] == 7.0
+ pre_call_args = logging_obj.pre_call.call_args.kwargs["additional_args"]
+ assert pre_call_args["query"] == ["q1", "q2"]
+ assert pre_call_args["vector_store_id"] == "vs_direct"
+
+
+ def _direct_vector_store_debug_logging_obj():
+ from litellm.litellm_core_utils.litellm_logging import Logging as LitellmLogging
+
+ logging_obj = LitellmLogging(
+ model="valkey",
+ messages=[{"role": "user", "content": "q"}],
+ stream=False,
+ call_type="vector_store_search",
+ start_time=time.time(),
+ litellm_call_id="vs-debug-call-id",
+ function_id="vs-debug-function-id",
+ log_raw_request_response=True,
+ )
+ logging_obj.update_environment_variables(
+ model="valkey",
+ optional_params={"vector_store_id": "vs_direct", "query": "q"},
+ litellm_params={
+ "litellm_call_id": "vs-debug-call-id",
+ "vector_store_id": "vs_direct",
+ "litellm_request_debug": True,
+ "metadata": {"user_api_key_alias": "vs-test-key"},
+ "valkey_host": "valkey.internal",
+ "valkey_password": "sup3r-s3cret-valkey-pw",
+ "litellm_embedding_config": {"api_key": "sk-embedding-s3cret"},
+ },
+ )
+ return logging_obj
+
+
+ @pytest.mark.parametrize("is_async", [False, True])
+ def test_direct_vector_store_search_debug_log_omits_stored_credentials(caplog, is_async):
+ """Regression: an empty api_base made pre_call dump the whole model_call_details, so every
+ search shipped the stored valkey_password / embedding api_key into the raw_request metadata."""
+ handler = BaseLLMHTTPHandler()
+ stub_response = {"object": "vector_store.search_results.page", "search_query": "q", "data": []}
+ config = _make_stub_direct_vector_store_config(stub_response)
+ logging_obj = _direct_vector_store_debug_logging_obj()
+
+ with caplog.at_level(logging.DEBUG, logger=verbose_logger.name):
+ result = handler.vector_store_search_handler(
+ vector_store_id="vs_direct",
+ query="q",
+ vector_store_search_optional_params={"max_num_results": 4},
+ vector_store_provider_config=config,
+ custom_llm_provider="valkey",
+ litellm_params=GenericLiteLLMParams(
+ valkey_host="valkey.internal",
+ valkey_password="sup3r-s3cret-valkey-pw",
+ ),
+ logging_obj=logging_obj,
+ _is_async=is_async,
+ )
+ if is_async:
+ result = asyncio.run(result)
+
+ assert result is stub_response
+ raw_request = logging_obj.model_call_details["litellm_params"]["metadata"]["raw_request"]
+ assert "sup3r-s3cret-valkey-pw" not in raw_request
+ assert "sk-embedding-s3cret" not in raw_request
+ assert "valkey://vs_direct" in raw_request
+ logged = "\n".join(record.getMessage() for record in caplog.records)
+ assert "sup3r-s3cret-valkey-pw" not in logged
+ assert "sk-embedding-s3cret" not in logged
+
+
+ @pytest.mark.asyncio
+ async def test_async_anthropic_messages_handler_carries_deployment_vertex_location_for_pricing(monkeypatch):
+ """
+ The proxy pre-creates the logging object before the router picks a deployment, so the
+ native /v1/messages path must copy the deployment's vertex_location into the logging
+ params it updates; otherwise cost resolution falls back to the environment and every
+ call on this surface prices with the regional uplift (#34393).
+ """
+ import contextlib
+ from datetime import datetime
+
+ from litellm.litellm_core_utils.litellm_logging import (
+ Logging,
+ _resolve_vertex_location_for_cost,
+ )
+
+ monkeypatch.setenv("VERTEXAI_LOCATION", "us-east5")
+ monkeypatch.setattr(litellm, "vertex_location", None)
+
+ handler = BaseLLMHTTPHandler()
+
+ async def logging_obj_after_handler(generic_params):
+ logging_obj = Logging(
+ model="vertex_ai/claude-haiku-4-5@20251001",
+ messages=[{"role": "user", "content": "hi"}],
+ stream=False,
+ call_type="anthropic_messages",
+ start_time=datetime.now(),
+ litellm_call_id="vertex-messages-location",
+ function_id="f",
+ )
+ logging_obj.update_environment_variables(
+ model="vertex_ai/claude-haiku-4-5@20251001",
+ user="",
+ optional_params={},
+ litellm_params={"api_base": ""},
+ custom_llm_provider="vertex_ai",
+ )
+ mock_config = Mock()
+ mock_config.validate_anthropic_messages_environment = Mock(
+ return_value=({"authorization": "Bearer t"}, "https://us-east5-aiplatform.googleapis.com")
+ )
+ mock_config.transform_anthropic_messages_request = Mock(
+ return_value={"model": "claude-haiku-4-5@20251001", "messages": []}
+ )
+ with contextlib.suppress(Exception):
+ await handler.async_anthropic_messages_handler(
+ model="claude-haiku-4-5@20251001",
+ messages=[{"role": "user", "content": "hi"}],
+ anthropic_messages_provider_config=mock_config,
+ anthropic_messages_optional_request_params={"max_tokens": 10},
+ custom_llm_provider="vertex_ai",
+ litellm_params=generic_params,
+ logging_obj=logging_obj,
+ client=AsyncMock(),
+ kwargs={},
+ )
+ return logging_obj
+
+ global_deployment = await logging_obj_after_handler(GenericLiteLLMParams(vertex_location="global"))
+ assert global_deployment.litellm_params["vertex_location"] == "global"
+ assert (
+ _resolve_vertex_location_for_cost(
+ custom_llm_provider="vertex_ai",
+ litellm_params=global_deployment.litellm_params,
+ optional_params=global_deployment.optional_params,
+ model="claude-haiku-4-5@20251001",
+ )
+ == "global"
+ )
+
+ unconfigured_deployment = await logging_obj_after_handler(GenericLiteLLMParams())
+ assert "vertex_location" not in unconfigured_deployment.litellm_params
+
+
+ _GENERIC_STREAM_SSE = (
+ b'data: {"id":"chatcmpl-1","object":"chat.completion.chunk","created":1,'
+ b'"model":"test-model","choices":[{"index":0,"delta":{"content":"hi"},'
+ b'"finish_reason":null}]}\n\n'
+ b"data: [DONE]\n\n"
+ )
+
+
+ def _generic_stream_upstream_response() -> httpx.Response:
+ return httpx.Response(
+ 200,
+ headers={
+ "x-request-id": "generic-req-123",
+ "x-ratelimit-remaining-requests": "42",
+ },
+ content=_GENERIC_STREAM_SSE,
+ request=httpx.Request("POST", "https://fake-vllm.test/v1/chat/completions"),
+ )
+
+
+ def test_generic_http_handler_sync_streaming_forwards_provider_response_headers():
+ """
+ Regression test for the generic BaseLLMHTTPHandler streaming path used by
+ ~30 providers (deepseek, groq, hosted_vllm, databricks, openrouter, ...).
+
+ The sync `completion()` streaming branch builds the CustomStreamWrapper from
+ `make_sync_call`, which returns the upstream response headers alongside the
+ stream. Those headers must reach the caller as `llm_provider-*` entries in
+ `_hidden_params["additional_headers"]`, which is what the proxy merges into
+ the client-facing response headers.
+ """
+ mock_client = Mock(spec=HTTPHandler)
+ mock_client.post = Mock(return_value=_generic_stream_upstream_response())
+
+ response = litellm.completion(
+ model="hosted_vllm/test-model",
+ messages=[{"role": "user", "content": "Hello"}],
+ api_base="https://fake-vllm.test/v1",
+ api_key="sk-test",
+ stream=True,
+ client=mock_client,
+ )
+
+ additional_headers = response._hidden_params["additional_headers"]
+ assert additional_headers["llm_provider-x-request-id"] == "generic-req-123"
+ assert additional_headers["llm_provider-x-ratelimit-remaining-requests"] == "42"
+
+ assert "".join([chunk.choices[0].delta.content or "" for chunk in response]) == "hi"
+
+
+ @pytest.mark.asyncio
+ async def test_generic_http_handler_async_streaming_forwards_provider_response_headers():
+ """
+ Companion to the sync test above for `acompletion_stream_function`, which
+ builds its CustomStreamWrapper from `make_async_call_stream_helper`.
+ """
+ mock_client = AsyncMock(spec=AsyncHTTPHandler)
+ mock_client.post = AsyncMock(return_value=_generic_stream_upstream_response())
+
+ response = await litellm.acompletion(
+ model="hosted_vllm/test-model",
+ messages=[{"role": "user", "content": "Hello"}],
+ api_base="https://fake-vllm.test/v1",
+ api_key="sk-test",
+ stream=True,
+ client=mock_client,
+ )
+
+ additional_headers = response._hidden_params["additional_headers"]
+ assert additional_headers["llm_provider-x-request-id"] == "generic-req-123"
+ assert additional_headers["llm_provider-x-ratelimit-remaining-requests"] == "42"
+
+ collected = [chunk async for chunk in response]
+ assert "".join([chunk.choices[0].delta.content or "" for chunk in collected]) == "hi"
+
+
+ @pytest.mark.parametrize(
+ "custom_llm_provider, litellm_params, expected",
+ [
+ ("openai", GenericLiteLLMParams(rust=True), True),
+ ("openai", GenericLiteLLMParams(), False),
+ ("openai", GenericLiteLLMParams(rust=False), False),
+ ("azure", GenericLiteLLMParams(rust=True), False),
+ ("hosted_vllm", GenericLiteLLMParams(rust=True), False),
+ (None, GenericLiteLLMParams(rust=True), False),
+ ],
+ )
+ def test_the_rust_responses_websocket_needs_both_openai_and_the_rust_flag(
+ custom_llm_provider, litellm_params, expected
+ ):
+ assert _rust_responses_websocket_enabled(custom_llm_provider, litellm_params) is expected
+
+
+ def test_a_plain_callback_does_not_advertise_a_pre_call_deployment_hook(monkeypatch):
+ from litellm.integrations.custom_logger import CustomLogger
+
+ class _PlainLogger(CustomLogger):
+ pass
+
+ logging_obj = Mock()
+ logging_obj.dynamic_success_callbacks = []
+
+ monkeypatch.setattr(litellm, "callbacks", [])
+ assert _has_pre_call_deployment_hook(logging_obj) is False
+
+ monkeypatch.setattr(litellm, "callbacks", [_PlainLogger()])
+ assert _has_pre_call_deployment_hook(logging_obj) is False
+
+
+ def test_a_callback_that_overrides_the_deployment_hook_is_detected(monkeypatch):
+ from litellm.integrations.custom_logger import CustomLogger
+
+ class _DeploymentHookLogger(CustomLogger):
+ async def async_pre_call_deployment_hook(self, kwargs, call_type):
+ return None
+
+ class _InheritsTheHook(_DeploymentHookLogger):
+ pass
+
+ logging_obj = Mock()
+ logging_obj.dynamic_success_callbacks = []
+
+ monkeypatch.setattr(litellm, "callbacks", [_DeploymentHookLogger()])
+ assert _has_pre_call_deployment_hook(logging_obj) is True
+
+ monkeypatch.setattr(litellm, "callbacks", [_InheritsTheHook()])
+ assert _has_pre_call_deployment_hook(logging_obj) is True
+
+ monkeypatch.setattr(litellm, "callbacks", [])
+ logging_obj.dynamic_success_callbacks = [_DeploymentHookLogger()]
+ assert _has_pre_call_deployment_hook(logging_obj) is True
+
+
+ def test_only_callbacks_that_can_charge_a_frame_are_collected_for_ws_quota(monkeypatch):
+ from litellm.integrations.custom_logger import CustomLogger
+
+ class _PlainLogger(CustomLogger):
+ pass
+
+ class _QuotaLogger(CustomLogger):
+ async def enforce_project_io_token_quota_for_frame(self, *args, **kwargs):
+ return None
+
+ class _NotCallableAttribute:
+ enforce_project_io_token_quota_for_frame = "not a method"
+
+ plain, quota, decoy = _PlainLogger(), _QuotaLogger(), _NotCallableAttribute()
+
+ monkeypatch.setattr(litellm, "callbacks", [plain, decoy])
+ assert _collect_ws_project_quota_callbacks() == ()
+
+ monkeypatch.setattr(litellm, "callbacks", [plain, quota, decoy])
+ assert _collect_ws_project_quota_callbacks() == (quota,)
+
+
+ class _JSONBodyVideoConfig(OpenAIVideoConfig):
+ def use_multipart_form_data(self) -> bool:
+ return False
+
+
+ def _video_create_call_kwargs(config, **optional_params):
+ return {
+ "model": "sora-2",
+ "prompt": "a cat surfing",
+ "video_generation_provider_config": config,
+ "video_generation_optional_request_params": {"seconds": "4", **optional_params},
+ "custom_llm_provider": "openai",
+ "litellm_params": GenericLiteLLMParams(api_key="sk-test", api_base="https://video.example/v1"),
+ "logging_obj": Mock(),
+ "timeout": 10.0,
+ }
+
+
+ def _capture_video_create_request(captured):
+ def respond(request):
+ captured["content_type"] = request.headers.get("content-type")
+ captured["body"] = request.content
+ return httpx.Response(
+ 200,
+ json={"id": "video_123", "object": "video", "status": "queued", "created_at": 1712697600, "model": "sora-2"},
+ )
+
+ return respond
+
+
+ def _multipart_text_fields(content_type: str, body: bytes) -> dict:
+ boundary = content_type.split("boundary=")[1].encode()
+ return {
+ part.split(b'name="')[1].split(b'"')[0].decode(): part.partition(b"\r\n\r\n")[2].rstrip(b"\r\n-").decode()
+ for part in body.split(b"--" + boundary)
+ if b'name="' in part and b"filename=" not in part
+ }
+
+
+ def test_video_generation_without_file_sends_multipart_form_data():
+ """Regression for #36493: the OpenAI SDK always sends /videos requests as
+ multipart/form-data, so OpenAI-compatible backends (SGLang Diffusion,
+ vLLM-Omni) reject the JSON body LiteLLM used to send when no
+ input_reference file was attached."""
+ captured = {}
+ client = HTTPHandler(client=httpx.Client(transport=httpx.MockTransport(_capture_video_create_request(captured))))
+
+ result = BaseLLMHTTPHandler().video_generation_handler(client=client, **_video_create_call_kwargs(OpenAIVideoConfig()))
+
+ assert captured["content_type"].startswith("multipart/form-data")
+ assert _multipart_text_fields(captured["content_type"], captured["body"]) == {
+ "model": "sora-2",
+ "prompt": "a cat surfing",
+ "seconds": "4",
+ }
+ assert result.status == "queued"
+
+
+ @pytest.mark.asyncio
+ async def test_async_video_generation_without_file_sends_multipart_form_data():
+ captured = {}
+ client = AsyncHTTPHandler()
+ client.client = httpx.AsyncClient(transport=httpx.MockTransport(_capture_video_create_request(captured)))
+
+ result = await BaseLLMHTTPHandler().async_video_generation_handler(
+ client=client, **_video_create_call_kwargs(OpenAIVideoConfig())
+ )
+
+ assert captured["content_type"].startswith("multipart/form-data")
+ assert _multipart_text_fields(captured["content_type"], captured["body"]) == {
+ "model": "sora-2",
+ "prompt": "a cat surfing",
+ "seconds": "4",
+ }
+ assert result.status == "queued"
+
+
+ def test_azure_video_generation_without_file_sends_multipart_form_data():
+ """AzureVideoConfig subclasses OpenAIVideoConfig, so it inherits the
+ file-less multipart behavior. Azure's /openai/v1/videos surface is
+ OpenAI-SDK-compatible (the SDK sends multipart there too), so this is
+ intentional; lock it so the inherited flip can't silently regress to JSON."""
+ assert AzureVideoConfig().use_multipart_form_data() is True
+
+ captured = {}
+ client = HTTPHandler(client=httpx.Client(transport=httpx.MockTransport(_capture_video_create_request(captured))))
+
+ result = BaseLLMHTTPHandler().video_generation_handler(client=client, **_video_create_call_kwargs(AzureVideoConfig()))
+
+ assert captured["content_type"].startswith("multipart/form-data")
+ assert _multipart_text_fields(captured["content_type"], captured["body"]) == {
+ "model": "sora-2",
+ "prompt": "a cat surfing",
+ "seconds": "4",
+ }
+ assert result.status == "queued"
+
+
+ def test_video_generation_json_provider_keeps_json_body():
+ captured = {}
+ client = HTTPHandler(client=httpx.Client(transport=httpx.MockTransport(_capture_video_create_request(captured))))
+
+ result = BaseLLMHTTPHandler().video_generation_handler(client=client, **_video_create_call_kwargs(_JSONBodyVideoConfig()))
+
+ assert captured["content_type"] == "application/json"
+ assert json.loads(captured["body"]) == {"model": "sora-2", "prompt": "a cat surfing", "seconds": "4"}
+ assert result.status == "queued"
+
+
+ def test_video_generation_with_input_reference_keeps_file_multipart():
+ captured = {}
+ client = HTTPHandler(client=httpx.Client(transport=httpx.MockTransport(_capture_video_create_request(captured))))
+
+ result = BaseLLMHTTPHandler().video_generation_handler(
+ client=client,
+ **_video_create_call_kwargs(OpenAIVideoConfig(), input_reference=b"\x89PNG\r\n\x1a\nfakepng"),
+ )
+
+ assert captured["content_type"].startswith("multipart/form-data")
+ assert b'name="input_reference"' in captured["body"]
+ assert b'filename="input_reference.png"' in captured["body"]
+ assert _multipart_text_fields(captured["content_type"], captured["body"]) == {
+ "model": "sora-2",
+ "prompt": "a cat surfing",
+ "seconds": "4",
+ }
+ assert result.status == "queued"
diff --cc tests/test_litellm/proxy/test_budget_reservation.py
index c3210dd7f4d,2388654bf4b..0444629ba34
--- a/tests/test_litellm/proxy/test_budget_reservation.py
+++ b/tests/test_litellm/proxy/test_budget_reservation.py
@@@ -2462,88 -2463,6 +2472,96 @@@ async def test_streaming_cancel_after_c
streaming_logging_obj._arelease_max_parallel_requests_on_disconnect.assert_awaited_once()
+async def test_streaming_cancel_after_only_keepalive_pings_reconciles_to_input_cost(
+ spend_counter_state,
+):
+ counter_cache, key_cache = spend_counter_state
+ proxy_logging_obj = ProxyLogging(user_api_key_cache=key_cache)
+ valid_token, reservation = await _reserve_for_stream(
+ counter_cache, key_cache, proxy_logging_obj, "key-cancel-after-ping"
+ )
+
+ async def cancel_after_ping(user_api_key_dict, response, request_data):
+ yield STREAM_SSE_KEEPALIVE_PING_BYTES
+ raise asyncio.CancelledError()
+
+ generator, streaming_logging_obj = _drive_streaming_cancel(valid_token, cancel_after_ping)
+ received = []
- with pytest.raises(asyncio.CancelledError):
++
++ async def _drain():
+ async for chunk in generator:
+ received.append(chunk)
+
++ with pytest.raises(asyncio.CancelledError):
++ await _drain()
++
+ assert received == [STREAM_SSE_KEEPALIVE_PING_BYTES]
+ assert counter_cache.in_memory_cache.get_cache(
+ key="spend:key:key-cancel-after-ping"
+ ) == pytest.approx(0.5)
+ assert reservation["finalized"] is True
+
+
+async def test_streaming_cancel_while_holding_back_provider_output_keeps_reservation(
+ spend_counter_state,
+):
+ counter_cache, key_cache = spend_counter_state
+ proxy_logging_obj = ProxyLogging(user_api_key_cache=key_cache)
+ valid_token, reservation = await _reserve_for_stream(
+ counter_cache, key_cache, proxy_logging_obj, "key-cancel-held-back"
+ )
+
+ held_back = AgenticAnthropicStreamingIterator(
+ completion_stream=_never_ending_stream(),
+ http_handler=MagicMock(),
+ model="claude-haiku-4-5",
+ messages=[],
+ anthropic_messages_provider_config=MagicMock(),
+ anthropic_messages_optional_request_params={},
+ logging_obj=MagicMock(),
+ custom_llm_provider="anthropic",
+ kwargs={},
+ hold_back=True,
+ server_fulfilled_tool_names=frozenset({"headroom_retrieve"}),
+ ping_interval_seconds=0.01,
+ )
+
+ async def ping_then_cancel(user_api_key_dict, response, request_data):
+ yield await response.__anext__()
+ while not response.has_buffered_provider_output:
+ yield await response.__anext__()
+ raise asyncio.CancelledError()
+
+ streaming_logging_obj = MagicMock()
+ streaming_logging_obj.async_post_call_streaming_iterator_hook = ping_then_cancel
+ streaming_logging_obj._arelease_max_parallel_requests_on_disconnect = AsyncMock()
+ generator = ProxyBaseLLMRequestProcessing.async_streaming_data_generator(
+ response=held_back,
+ user_api_key_dict=valid_token,
+ request_data=_request_body(),
+ proxy_logging_obj=streaming_logging_obj,
+ serialize_chunk=lambda chunk: chunk,
+ serialize_error=lambda exc: str(exc),
+ )
+
+ received = []
- with pytest.raises(asyncio.CancelledError):
++
++ async def _drain():
+ async for chunk in generator:
+ received.append(chunk)
+
++ with pytest.raises(asyncio.CancelledError):
++ await _drain()
++
+ assert received and received == [STREAM_SSE_KEEPALIVE_PING_BYTES] * len(received)
+ assert counter_cache.in_memory_cache.get_cache(
+ key="spend:key:key-cancel-held-back"
+ ) == pytest.approx(2.0)
+ assert reservation.get("finalized") is not True
+
+
@pytest.mark.asyncio
async def test_release_budget_reservation_on_cancel_swallows_release_errors():
# If the release itself fails (e.g. Redis unavailable) it must not escape