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
fix(router): forward the hold-back keepalive ping live and carry the withheld-output flag through the stream wrappers
mateo-berri1b3739763354
diff --git a/litellm/llms/anthropic/experimental_pass_through/messages/streaming_iterator.py b/litellm/llms/anthropic/experimental_pass_through/messages/streaming_iterator.pyindex 0a12bc3135f..8387dd8310d 100644--- a/litellm/llms/anthropic/experimental_pass_through/messages/streaming_iterator.py+++ b/litellm/llms/anthropic/experimental_pass_through/messages/streaming_iterator.py@@ -312,6 +312,10 @@ class AnthropicMessagesStreamingResponse:self.completion_stream = completion_streamself._hidden_params = hidden_params+ @property+ def has_buffered_provider_output(self) -> bool:+ return getattr(self.completion_stream, "has_buffered_provider_output", False) is True+def __aiter__(self) -> "AnthropicMessagesStreamingResponse":return selfdiff --git a/litellm/proxy/common_request_processing.py b/litellm/proxy/common_request_processing.pyindex 33d5ec31313..4f56e4eb715 100644--- a/litellm/proxy/common_request_processing.py+++ b/litellm/proxy/common_request_processing.py@@ -48,9 +48,6 @@ from litellm.litellm_core_utils.safe_json_dumps import safe_dumpsfrom 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, UserAPIKeyAuthfrom litellm.proxy.auth.auth_checks import can_key_call_resolved_modelfrom litellm.proxy.auth.auth_utils import check_response_size_is_safe@@ -207,7 +204,7 @@ _CLIENT_DISCONNECTED_ERROR_INFORMATION: Final[StandardLoggingPayloadErrorInformadef _withheld_provider_output(response: object) -> bool:- return isinstance(response, AgenticAnthropicStreamingIterator) and response.has_buffered_provider_output+ return getattr(response, "has_buffered_provider_output", False) is Truedef _should_return_raw_model_name(request_data: dict[str, object]) -> bool:diff --git a/litellm/router.py b/litellm/router.pyindex d07effd0d90..4cceecf50d6 100644--- a/litellm/router.py+++ b/litellm/router.py@@ -383,6 +383,17 @@ def _anthropic_stream_should_drop_pre_content_ping(chunk: object, has_generated_return is_anthropic_ping_chunk(chunk)+def _anthropic_stream_forwards_ping_live(chunk: object, has_generated_content: bool, buffered_chunk_count: int) -> bool:+ """A `ping` that no lifecycle frame precedes reaches the client live: a fallback's own message_start can still+ follow it without overlapping lifecycles, and AgenticAnthropicStreamingIterator's hold-back keepalive is exactly+ such a ping."""+ from litellm.llms.anthropic.experimental_pass_through.messages.streaming_iterator import is_anthropic_ping_chunk++ if has_generated_content or buffered_chunk_count:+ return False+ return is_anthropic_ping_chunk(chunk)++def _is_retriable_anthropic_status(status_code: int) -> bool:return status_code == 429 or status_code >= 500@@ -426,10 +437,18 @@ class FallbackAwareAnthropicMessagesStream:def __init__(self, async_generator: AsyncGenerator[bytes, None], source_iterator: object) -> None:self._async_generator = async_generator+ self._source_iterator = source_iteratorself._hidden_params = dict( # mutable-ok: mutated in place by merge_fallback_hidden_paramsgetattr(source_iterator, "_hidden_params", None) or {})+ @property+ def has_buffered_provider_output(self) -> bool:+ return getattr(self._source_iterator, "has_buffered_provider_output", False) is True++ def adopt_fallback_source(self, fallback_response: object) -> None:+ self._source_iterator = fallback_response+def __aiter__(self) -> "FallbackAwareAnthropicMessagesStream":return self@@ -4973,7 +4992,9 @@ class Router:# arrives - at that point the primary attempt has committed and a# clean retry is no longer possible anyway - or once the primary# stream ends without ever producing content. A `ping` keepalive- # is dropped outright rather than buffered, since it can recur+ # that nothing precedes is forwarded live (it is how a hold-back+ # turn keeps its connection alive); one behind buffered frames is+ # dropped outright rather than buffered, since it can recur# indefinitely on a slow-starting connection and carries nothing# worth preserving; hitting MAX_BUFFERED_PRE_CONTENT_ANTHROPIC_CHUNKS# forces the same early commit as real content arriving, so a@@ -4983,6 +5004,11 @@ class Router:model: Final = cast(str, initial_kwargs.get("model")) # cast-ok: kwargs always carries the model grouptry:async for chunk in source_iterator:+ if _anthropic_stream_forwards_ping_live(+ chunk, has_generated_content, len(buffered_lifecycle_chunks)+ ):+ yield chunk+ continueif _anthropic_stream_should_drop_pre_content_ping(chunk, has_generated_content):continueif _anthropic_stream_commits_now(chunk, has_generated_content, len(buffered_lifecycle_chunks)):@@ -5086,6 +5112,7 @@ class Router:)fallback_hidden_params, fallback_headers = Router._prepare_fallback_hidden_params(fallback_response)wrapper.merge_fallback_hidden_params(fallback_hidden_params, fallback_headers)+ wrapper.adopt_fallback_source(fallback_response)if hasattr(fallback_response, "__aiter__"):async for fallback_item in fallback_response:yield fallback_itemdiff --git a/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_streaming_iterator.py b/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_streaming_iterator.pyindex 652c1f077a9..cb31280c2d5 100644--- a/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_streaming_iterator.py+++ b/tests/test_litellm/llms/anthropic/experimental_pass_through/messages/test_streaming_iterator.py@@ -8,6 +8,8 @@ import pytestfrom litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObjfrom litellm.llms.anthropic.experimental_pass_through.messages.streaming_iterator import (INCOMPLETE_STREAM_ERROR_MESSAGE,+ AnthropicMessagesStreamHiddenParams,+ AnthropicMessagesStreamingResponse,BaseAnthropicMessagesStreamingIterator,_incomplete_stream_error_sse_event,_is_message_stop_chunk,@@ -511,6 +513,32 @@ def test_anthropic_messages_response_as_sse_events_multiple_blocks_are_indexed()assert [d["delta"]["text"] for d in deltas] == ["a", "b"]+def test_anthropic_messages_streaming_response_reports_withheld_output_of_its_stream():+ class _HoldingBack:+ has_buffered_provider_output = True++ def __aiter__(self):+ return self++ async def __anext__(self) -> bytes:+ raise StopAsyncIteration++ async def _bare_stream():+ yield b""++ hidden_params: AnthropicMessagesStreamHiddenParams = {"additional_headers": {}}+ assert (+ AnthropicMessagesStreamingResponse(completion_stream=_HoldingBack(), hidden_params=hidden_params)+ .has_buffered_provider_output+ is True+ )+ assert (+ AnthropicMessagesStreamingResponse(completion_stream=_bare_stream(), hidden_params=hidden_params)+ .has_buffered_provider_output+ is False+ )++def test_anthropic_messages_response_as_sse_events_no_content_blocks():response = {"id": "msg_4", "content": [], "stop_reason": "end_turn"}decoded = _decode_sse_events(anthropic_messages_response_as_sse_events(response))diff --git a/tests/test_litellm/proxy/test_budget_reservation.py b/tests/test_litellm/proxy/test_budget_reservation.pyindex 0444629ba34..38a346e7fb7 100644--- a/tests/test_litellm/proxy/test_budget_reservation.py+++ b/tests/test_litellm/proxy/test_budget_reservation.py@@ -10,6 +10,9 @@ from fastapi import HTTPExceptionimport litellmfrom litellm.caching.dual_cache import DualCachefrom litellm.constants import STREAM_SSE_KEEPALIVE_PING_BYTES+from litellm.llms.anthropic.experimental_pass_through.messages.streaming_iterator import (+ AnthropicMessagesStreamingResponse,+)from litellm.llms.anthropic.experimental_pass_through.messages.agentic_streaming_iterator import (AgenticAnthropicStreamingIterator,)@@ -2527,6 +2530,18 @@ async def test_streaming_cancel_while_holding_back_provider_output_keeps_reservaserver_fulfilled_tool_names=frozenset({"headroom_retrieve"}),ping_interval_seconds=0.01,)+ router = Router(+ model_list=[+ {+ "model_name": "claude-haiku-4-5",+ "litellm_params": {"model": "anthropic/claude-haiku-4-5", "api_key": "sk-test"},+ }+ ]+ )+ response = await router._aanthropic_messages_streaming_iterator(+ response=AnthropicMessagesStreamingResponse(completion_stream=held_back, hidden_params={"additional_headers": {}}),+ initial_kwargs={"model": "claude-haiku-4-5"},+ )async def ping_then_cancel(user_api_key_dict, response, request_data):yield await response.__anext__()@@ -2538,7 +2553,7 @@ async def test_streaming_cancel_while_holding_back_provider_output_keeps_reservastreaming_logging_obj.async_post_call_streaming_iterator_hook = ping_then_cancelstreaming_logging_obj._arelease_max_parallel_requests_on_disconnect = AsyncMock()generator = ProxyBaseLLMRequestProcessing.async_streaming_data_generator(- response=held_back,+ response=response,user_api_key_dict=valid_token,request_data=_request_body(),proxy_logging_obj=streaming_logging_obj,@@ -2553,7 +2568,7 @@ async def test_streaming_cancel_while_holding_back_provider_output_keeps_reservareceived.append(chunk)with pytest.raises(asyncio.CancelledError):- await _drain()+ await asyncio.wait_for(_drain(), timeout=5)assert received and received == [STREAM_SSE_KEEPALIVE_PING_BYTES] * len(received)assert counter_cache.in_memory_cache.get_cache(diff --git a/tests/test_litellm/test_router.py b/tests/test_litellm/test_router.pyindex 56fd6df446f..4b9b91caf2c 100644--- a/tests/test_litellm/test_router.py+++ b/tests/test_litellm/test_router.py@@ -20,6 +20,7 @@ from litellm.router import (FallbackAwareAnthropicMessagesStream,_anthropic_stream_commits_now,_anthropic_stream_should_decline_fallback,+ _anthropic_stream_forwards_ping_live,_anthropic_stream_should_drop_pre_content_ping,_is_retriable_anthropic_status,)@@ -9469,21 +9470,79 @@ async def test_anthropic_messages_content_coalesced_with_error_in_one_physical_c@pytest.mark.asyncio-async def test_anthropic_messages_ping_keepalive_never_buffered_or_forwarded():- """Bugbot regression: a `ping` keepalive carries no content and must be- dropped outright before any real content arrives, rather than buffered -+async def test_anthropic_messages_ping_behind_buffered_lifecycle_frame_is_dropped():+ """Bugbot regression: a `ping` keepalive behind buffered lifecycle frames+ carries no content and is dropped outright rather than buffered -otherwise a slow-starting connection sending many pings could grow thepre-content buffer without bound."""router = _anthropic_messages_make_router()source = _AnthropicMessagesFakeByteStream(- [_anthropic_messages_ping_chunk(), _anthropic_messages_content_chunk("hi")]+ [+ _anthropic_messages_message_start_chunk(),+ _anthropic_messages_ping_chunk(),+ _anthropic_messages_content_chunk("hi"),+ ])wrapped = await router._aanthropic_messages_streaming_iterator(response=source, initial_kwargs={"model": "primary"})collected = [chunk async for chunk in wrapped]- assert _anthropic_messages_ping_chunk() not in collected- assert collected == [_anthropic_messages_content_chunk("hi")]+ assert collected == [_anthropic_messages_message_start_chunk(), _anthropic_messages_content_chunk("hi")]+++async def test_anthropic_messages_leading_ping_keepalive_is_forwarded_live():+ """A `ping` that no lifecycle frame precedes is how a hold-back turn keeps+ its connection alive (AgenticAnthropicStreamingIterator), so it must reach+ the client at once rather than wait behind the pre-content buffer."""+ router = _anthropic_messages_make_router()+ content_released = asyncio.Event()++ async def source():+ yield _anthropic_messages_ping_chunk()+ await content_released.wait()+ yield _anthropic_messages_message_start_chunk()+ yield _anthropic_messages_content_chunk("hi")++ wrapped = await router._aanthropic_messages_streaming_iterator(response=source(), initial_kwargs={"model": "primary"})++ assert await asyncio.wait_for(wrapped.__anext__(), timeout=1) == _anthropic_messages_ping_chunk()+ content_released.set()+ assert [chunk async for chunk in wrapped] == [+ _anthropic_messages_message_start_chunk(),+ _anthropic_messages_content_chunk("hi"),+ ]+++async def test_anthropic_messages_leading_ping_does_not_disqualify_fallback():+ """A live-forwarded leading `ping` commits nothing: a retriable error after+ it still falls back, and the fallback's own lifecycle follows the ping cleanly."""+ router = _anthropic_messages_make_router()+ source = _AnthropicMessagesFakeByteStream(+ [_anthropic_messages_ping_chunk(), _anthropic_messages_overloaded_error_chunk()]+ )+ fallback_message_start = b'event: message_start\ndata: {"type": "message_start", "message": {"id": "msg_2"}}\n\n'+ fallback_stream = _AnthropicMessagesFallbackByteStream(+ [fallback_message_start, _anthropic_messages_content_chunk("fallback answer")]+ )++ with patch.object(+ router,+ "async_function_with_fallbacks_common_utils",+ new=AsyncMock(return_value=fallback_stream),+ ):+ wrapped = await router._aanthropic_messages_streaming_iterator(+ response=source,+ initial_kwargs={"model": "primary"},+ )+ collected = [chunk async for chunk in wrapped]++ assert collected == [+ _anthropic_messages_ping_chunk(),+ fallback_message_start,+ _anthropic_messages_content_chunk("fallback answer"),+ ]@pytest.mark.asyncio@@ -9815,6 +9874,30 @@ def test_anthropic_stream_should_drop_pre_content_ping_direct_call():assert _anthropic_stream_should_drop_pre_content_ping(content, has_generated_content=False) is False+def test_anthropic_stream_forwards_ping_live_direct_call():+ ping = _anthropic_messages_ping_chunk()+ content = _anthropic_messages_content_chunk("hi")+ assert _anthropic_stream_forwards_ping_live(ping, has_generated_content=False, buffered_chunk_count=0) is True+ assert _anthropic_stream_forwards_ping_live(ping, has_generated_content=False, buffered_chunk_count=1) is False+ assert _anthropic_stream_forwards_ping_live(ping, has_generated_content=True, buffered_chunk_count=0) is False+ assert _anthropic_stream_forwards_ping_live(content, has_generated_content=False, buffered_chunk_count=0) is False+++def test_fallback_aware_stream_reports_withheld_output_of_its_current_source():+ """The proxy's cancel-refund guard reads this flag off the router wrapper, so it+ must reflect the stream actually being drained: the primary, then the fallback."""++ class _HoldingBack:+ _hidden_params = {"additional_headers": {}}+ has_buffered_provider_output = True++ wrapper = FallbackAwareAnthropicMessagesStream(_anthropic_messages_empty_generator(), _HoldingBack())+ assert wrapper.has_buffered_provider_output is True++ wrapper.adopt_fallback_source(_AnthropicMessagesFakeByteStream([]))+ assert wrapper.has_buffered_provider_output is False++def test_is_retriable_anthropic_status_direct_call():assert _is_retriable_anthropic_status(429) is Trueassert _is_retriable_anthropic_status(503) is True