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(proxy): send SSE keepalives while a slow upstream is still silent (#37322)
Yassin Kortam1857f5d04bb8
diff --git a/litellm/proxy/common_request_processing.py b/litellm/proxy/common_request_processing.pyindex 376d7785e5a..7c93155964d 100644--- a/litellm/proxy/common_request_processing.py+++ b/litellm/proxy/common_request_processing.py@@ -1,14 +1,15 @@import asyncio+import contextlibimport jsonimport loggingimport mathimport timeimport traceback-from collections.abc import AsyncGenerator, Callable, Mapping+from collections.abc import AsyncGenerator, Awaitable, Callable, Mappingfrom datetime import datetimefrom functools import lru_cachefrom types import MappingProxyType-from typing import TYPE_CHECKING, Any, Final, Literal, NamedTuple, Protocol, overload+from typing import TYPE_CHECKING, Any, Final, Literal, NamedTuple, Protocol, TypeAlias, TypeVar, overloadimport anyioimport httpx@@ -47,7 +48,12 @@ from litellm.proxy.common_utils.callback_utils import (get_logging_caching_headers,get_remaining_tokens_and_requests_from_request_data,)-from litellm.proxy.common_utils.sse_keepalive import wrap_sse_stream_with_keepalive_pings+from litellm.proxy.common_utils.sse_keepalive import (+ SSE_COMMENT_PING_BYTES,+ coerce_keepalive_interval,+ resolve_ttft_keepalive_interval,+ wrap_sse_stream_with_keepalive_pings,+)from litellm.proxy.dd_span_tagger import DDSpanTaggerfrom litellm.proxy.route_llm_request import route_requestfrom litellm.proxy.utils import ProxyLogging, _check_and_merge_model_level_guardrails@@ -56,6 +62,100 @@ from litellm.router_utils.add_retry_fallback_headers import get_hidden_params_difrom litellm.router_utils.common_utils import resolve_model_group_aliasfrom litellm.types.guardrails import GuardrailEventHooksfrom litellm.types.router import RouterRateLimitError++_LateResponseT = TypeVar("_LateResponseT", bound=Response)+_LlmCallT = TypeVar("_LlmCallT")++ProxyRouteType: TypeAlias = Literal[+ "acompletion",+ "aembedding",+ "aresponses",+ "_arealtime",+ "_aresponses_websocket",+ "acreate_realtime_client_secret",+ "arealtime_calls",+ "aget_responses",+ "adelete_responses",+ "acancel_responses",+ "acompact_responses",+ "acreate_batch",+ "aretrieve_batch",+ "alist_batches",+ "acancel_batch",+ "afile_content",+ "afile_retrieve",+ "afile_delete",+ "atext_completion",+ "acreate_fine_tuning_job",+ "acancel_fine_tuning_job",+ "alist_fine_tuning_jobs",+ "aretrieve_fine_tuning_job",+ "alist_input_items",+ "aimage_edit",+ "agenerate_content",+ "agenerate_content_stream",+ "allm_passthrough_route",+ "avector_store_search",+ "avector_store_create",+ "avector_store_retrieve",+ "avector_store_list",+ "avector_store_update",+ "avector_store_delete",+ "avector_store_file_create",+ "avector_store_file_list",+ "avector_store_file_retrieve",+ "avector_store_file_content",+ "avector_store_file_update",+ "avector_store_file_delete",+ "aocr",+ "asearch",+ "avideo_generation",+ "avideo_list",+ "avideo_status",+ "avideo_content",+ "avideo_remix",+ "avideo_create_character",+ "avideo_get_character",+ "avideo_edit",+ "avideo_extension",+ "acreate_container",+ "alist_containers",+ "aingest",+ "aretrieve_container",+ "adelete_container",+ "aupload_container_file",+ "alist_container_files",+ "aretrieve_container_file",+ "adelete_container_file",+ "aretrieve_container_file_content",+ "acreate_skill",+ "alist_skills",+ "aget_skill",+ "adelete_skill",+ "anthropic_messages",+ "acreate_interaction",+ "aget_interaction",+ "adelete_interaction",+ "acancel_interaction",+ "acreate_agent",+ "alist_agents",+ "aget_agent",+ "adelete_agent",+ "alist_agent_versions",+ "asend_message",+ "call_mcp_tool",+ "acreate_eval",+ "alist_evals",+ "aget_eval",+ "aupdate_eval",+ "adelete_eval",+ "acancel_eval",+ "acreate_run",+ "alist_runs",+ "aget_run",+ "acancel_run",+ "adelete_run",+]from litellm.types.utils import ServerToolUse# Type alias for streaming chunk serializer (chunk after hooks + cost injection -> wire format)@@ -559,6 +659,11 @@ class _UpstreamClosingStreamingResponse(StreamingResponse):super().__init__(content, status_code=status_code, headers=headers, media_type=media_type)self._upstream_generator = upstream_generator+ @property+ def upstream_generator(self) -> AsyncGenerator[str, None] | None:+ """The upstream LLM stream, for a caller that has to run this response's cleanup itself."""+ return self._upstream_generator+async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:try:await super().__call__(scope, receive, send)@@ -649,6 +754,39 @@ async def _buffer_first_chunk_honoring_disconnect(raise _ClientDisconnectedBeforeFirstChunk()+def _sse_error_payload(exc: BaseException) -> tuple[int, Mapping[str, object]]:+ """Build the ProxyException-shaped ``{"error": ...}`` body used in SSE error frames.++ Matches ``ProxyException.to_dict()`` so streaming and non-streaming error frames+ are byte-identical.+ """+ # Preserve status code from HTTPException (e.g. guardrail blocks)+ error_status: Final = getattr(exc, "status_code", status.HTTP_500_INTERNAL_SERVER_ERROR)+ raw_detail: Final = _getattr_object(exc, "detail", "Error processing stream start")+ message, structured_fields = _serialize_http_exception_detail(raw_detail)++ existing_fields: Final = getattr(exc, "provider_specific_fields", None) or {}+ merged_fields: Final = {**existing_fields, **structured_fields} if structured_fields else (existing_fields or None)++ # Built in one statement then given its one optional key, rather than spread+ # conditionally: the spread form costs two extra dict constructions, which+ # type-discipline-budget.json's LIT002 ceiling has no room for.+ error_obj: Final = {+ "message": message,+ "type": getattr(exc, "type", "None"),+ "param": getattr(exc, "param", "None"),+ "code": str(error_status),+ }+ if merged_fields:+ error_obj["provider_specific_fields"] = merged_fields+ return error_status, error_obj+++def _sse_error_frames(error_obj: Mapping[str, object]) -> tuple[str, str]:+ """The two frames an SSE stream ends with once it can no longer raise."""+ return f"data: {json.dumps({'error': error_obj})}\n\n", "data: [DONE]\n\n"++async def create_response(generator: AsyncGenerator[str, None],media_type: str,@@ -740,31 +878,11 @@ async def create_response(# Unexpected error consuming first chunk.verbose_proxy_logger.exception("Error consuming first chunk from generator: %s", e)- # Preserve status code from HTTPException (e.g., guardrail blocks)- error_status: Final = getattr(e, "status_code", status.HTTP_500_INTERNAL_SERVER_ERROR)- raw_detail: Final = _getattr_object(e, "detail", "Error processing stream start")- message, structured_fields = _serialize_http_exception_detail(raw_detail)-- existing_fields: Final = getattr(e, "provider_specific_fields", None) or {}- if structured_fields:- merged_fields: dict | None = {**existing_fields, **structured_fields}- else:- merged_fields = existing_fields or None-- # Match ProxyException.to_dict() shape so streaming and non-streaming- # error frames are byte-identical.- error_obj: Final[dict[str, object]] = {- "message": message,- "type": getattr(e, "type", "None"),- "param": getattr(e, "param", "None"),- "code": str(error_status),- }- if merged_fields:- error_obj["provider_specific_fields"] = merged_fields+ error_status, error_obj = _sse_error_payload(e)async def error_gen_message() -> AsyncGenerator[str, None]:- yield f"data: {json.dumps({'error': error_obj})}\n\n"- yield "data: [DONE]\n\n"+ for frame in _sse_error_frames(error_obj):+ yield framereturn StreamingResponse(error_gen_message(),@@ -797,6 +915,176 @@ async def create_response()+_TTFT_KEEPALIVE_HEADERS: Final[Mapping[str, str]] = MappingProxyType(+ {+ "Cache-Control": "no-cache",+ "X-Accel-Buffering": "no",+ }+)+++def ttft_keepalive_interval(request_data: Mapping[str, object], llm_router: Router | None = None) -> float | None:+ """The operator's keepalive interval, but only for a request that asked to stream.++ Resolved through the deployments the request could land on, so a deployment's+ `keepalive_seconds: 0` stays the hard disable it is documented to be rather+ than being switched back on by the global default.+ """+ if request_data.get("stream") is not True:+ return None+ requested_model: Final = request_data.get("model")+ deployments: Final = (+ llm_router.get_model_list(model_name=requested_model) or ()+ if llm_router is not None and isinstance(requested_model, str)+ else ()+ )+ return resolve_ttft_keepalive_interval(deployments, litellm.sse_keepalive_ping_interval_seconds)+++async def _aclose_late_response(produced: Response) -> None:+ """Run the cleanup Starlette would have run, for a response it never called.++ Closing an already-closed async generator is a no-op, so this is safe to call+ from both the relay's own teardown and the outer one.+ """+ if not isinstance(produced, StreamingResponse):+ return+ targets: Final = (+ (produced.body_iterator, produced.upstream_generator)+ if isinstance(produced, _UpstreamClosingStreamingResponse)+ else (produced.body_iterator,)+ )+ for target in targets:+ aclose = getattr(target, "aclose", None)+ if aclose is None:+ continue+ try:+ await aclose()+ except BaseException as exc: # noqa: BLE001 # teardown must not mask why the stream ended+ verbose_proxy_logger.debug("error closing relayed streaming generator: %s", exc)+++async def _relay_late_response(produced: Response) -> AsyncGenerator[bytes, None]:+ """Replay a Response that was built after a keepalive had already opened the wire."""+ if not isinstance(produced, StreamingResponse):+ # The status line is already on the wire, so a non-streaming body, an error+ # body included, can only reach the client as an SSE frame.+ yield b"data: " + (bytes(produced.body) or b"{}") + b"\n\n"+ yield b"data: [DONE]\n\n"+ return++ try:+ async for chunk in produced.body_iterator:+ yield chunk.encode("utf-8") if isinstance(chunk, str) else bytes(chunk)+ finally:+ # Starlette never called this response, so the cleanup its __call__ would+ # have run has to happen here or the upstream LLM connection leaks.+ with anyio.CancelScope(shield=True):+ await _aclose_late_response(produced)+++async def _sanitized_late_failure(+ exc: Exception,+ on_late_failure: "Callable[[Exception], Awaitable[HTTPException | None]] | None",+) -> Exception:+ """Report a late failure and return whatever should reach the client.++ ``post_call_failure_hook`` lets a callback replace the client-facing error, by+ returning a replacement or by raising one, and both are used elsewhere in this+ module. Serializing the original would leak provider detail a deployment had+ configured away, so the hook's answer wins. A callback that fails some other+ way is a bug in the callback, not a reason to lose the real error.+ """+ if on_late_failure is None:+ return exc+ try:+ replacement: Final = await on_late_failure(exc)+ except HTTPException as raised_replacement:+ return raised_replacement+ except Exception as hook_failure: # noqa: BLE001 # a broken callback must not replace the real error+ verbose_proxy_logger.exception("post_call_failure_hook raised while reporting a late failure: %s", hook_failure)+ return exc+ return replacement if replacement is not None else exc+++async def open_sse_before_first_byte(+ produce_response: Awaitable[_LateResponseT],+ ping_interval_seconds: float | str | None,+ media_type: str = "text/event-stream",+ on_late_failure: Callable[[Exception], Awaitable[HTTPException | None]] | None = None,+) -> _LateResponseT | StreamingResponse:+ """Write SSE keepalive comments while the upstream LLM call is still in flight.++ The whole time-to-first-token is spent inside `produce_response`: the upstream+ withholds its response headers until it emits its first token, so nothing has+ entered the ASGI response phase yet and the proxy writes zero bytes. An+ intermediary with an idle read timeout (AWS ALB and nginx both default to 60s)+ then drops a connection that is perfectly healthy.++ When `produce_response` does not finish within one interval, the response is+ opened immediately and `: ping` comments, which every conformant SSE client+ ignores, fill the wire until the real response is ready to be replayed onto it.+ Committing the status line that early is the cost: a failure discovered after+ the first ping reaches the client as an SSE error frame under a 200 rather than+ as an HTTP error status, and LiteLLM's own `x-litellm-*` response headers are+ not yet known. Both are why this stays off until an operator sets an interval.+ """+ interval: Final = coerce_keepalive_interval(ping_interval_seconds)+ if interval is None:+ return await produce_response++ produce_task: Final = asyncio.ensure_future(produce_response)+ await asyncio.wait((produce_task,), timeout=interval)+ if produce_task.done():+ # Fast path: the upstream answered inside one interval, so nothing was+ # written early and this is byte-identical to not being wrapped at all.+ return produce_task.result()++ async def keepalive_then_relay() -> AsyncGenerator[bytes, None]:+ try:+ while not produce_task.done():+ yield SSE_COMMENT_PING_BYTES+ await asyncio.wait((produce_task,), timeout=interval)+ try:+ produced: Final = produce_task.result()+ except Exception as exc: # noqa: BLE001 # the status line is already sent; surface it as a frame+ verbose_proxy_logger.exception(+ "request failed after its SSE keepalive had opened the response: %s", exc+ )+ # The caller's own `except` never sees this, so its failure hook+ # would never fire and the failure would go unaudited. The hook+ # also gets to sanitize what reaches the client, by returning or+ # raising a replacement, so its answer decides the frame.+ _, error_obj = _sse_error_payload(await _sanitized_late_failure(exc, on_late_failure))+ for frame in _sse_error_frames(error_obj):+ yield frame.encode()+ return+ async for chunk in _relay_late_response(produced):+ yield chunk+ finally:+ if not produce_task.done():+ produce_task.cancel()+ with anyio.CancelScope(shield=True):+ with contextlib.suppress(BaseException):+ await produce_task+ elif not produce_task.cancelled():+ # The upstream may have answered while nobody was draining this+ # relay, e.g. the client vanished first. Nothing else holds that+ # response, so its stream only gets closed here.+ with anyio.CancelScope(shield=True):+ with contextlib.suppress(BaseException):+ await _aclose_late_response(produce_task.result())++ verbose_proxy_logger.info(+ "no upstream response after %ss, opening the SSE response early and sending keepalives", interval+ )+ return StreamingResponse(+ keepalive_then_relay(),+ media_type=media_type,+ headers=_TTFT_KEEPALIVE_HEADERS,+ )++def _is_azure_model_router_request(model: str) -> bool:"""Check if the requested model is an Azure Model Router.@@ -1043,7 +1331,7 @@ def _log_llm_api_exception(e: Exception) -> None:async def _cancel_llm_call_on_client_disconnect(request: Request,- llm_api_call: "asyncio.Future[object]",+ llm_api_call: "asyncio.Future[_LlmCallT]",disconnect_event: asyncio.Event,) -> None:try:@@ -1062,8 +1350,8 @@ async def _cancel_llm_call_on_client_disconnect(async def _await_llm_call_cancelling_on_disconnect(request: Request,- llm_api_call: "asyncio.Future[Any]",-) -> Any:+ llm_api_call: "asyncio.Future[_LlmCallT]",+) -> _LlmCallT:disconnect_event: Final = asyncio.Event()monitor: Final = asyncio.create_task(_cancel_llm_call_on_client_disconnect(request, llm_api_call, disconnect_event))try:@@ -1714,100 +2002,76 @@ class ProxyBaseLLMRequestProcessing:request: Request,fastapi_response: Response,user_api_key_dict: UserAPIKeyAuth,- route_type: Literal[- "acompletion",- "aembedding",- "aresponses",- "_arealtime",- "_aresponses_websocket",- "acreate_realtime_client_secret",- "arealtime_calls",- "aget_responses",- "adelete_responses",- "acancel_responses",- "acompact_responses",- "acreate_batch",- "aretrieve_batch",- "alist_batches",- "acancel_batch",- "afile_content",- "afile_retrieve",- "afile_delete",- "atext_completion",- "acreate_fine_tuning_job",- "acancel_fine_tuning_job",- "alist_fine_tuning_jobs",- "aretrieve_fine_tuning_job",- "alist_input_items",- "aimage_edit",- "agenerate_content",- "agenerate_content_stream",- "allm_passthrough_route",- "avector_store_search",- "avector_store_create",- "avector_store_retrieve",- "avector_store_list",- "avector_store_update",- "avector_store_delete",- "avector_store_file_create",- "avector_store_file_list",- "avector_store_file_retrieve",- "avector_store_file_content",- "avector_store_file_update",- "avector_store_file_delete",- "aocr",- "asearch",- "avideo_generation",- "avideo_list",- "avideo_status",- "avideo_content",- "avideo_remix",- "avideo_create_character",- "avideo_get_character",- "avideo_edit",- "avideo_extension",- "acreate_container",- "alist_containers",- "aingest",- "aretrieve_container",- "adelete_container",- "aupload_container_file",- "alist_container_files",- "aretrieve_container_file",- "adelete_container_file",- "aretrieve_container_file_content",- "acreate_skill",- "alist_skills",- "aget_skill",- "adelete_skill",- "anthropic_messages",- "acreate_interaction",- "aget_interaction",- "adelete_interaction",- "acancel_interaction",- "acreate_agent",- "alist_agents",- "aget_agent",- "adelete_agent",- "alist_agent_versions",- "asend_message",- "call_mcp_tool",- "acreate_eval",- "alist_evals",- "aget_eval",- "aupdate_eval",- "adelete_eval",- "acancel_eval",- "acreate_run",- "alist_runs",- "aget_run",- "acancel_run",- "adelete_run",- ],+ route_type: ProxyRouteType,proxy_logging_obj: ProxyLogging,- general_settings: dict,+ general_settings: dict[str, object],+ proxy_config: ProxyConfig,+ select_data_generator: Callable[..., object] | None = None,+ llm_router: Router | None = None,+ model: str | None = None,+ user_model: str | None = None,+ user_temperature: float | None = None,+ user_request_timeout: float | None = None,+ user_max_tokens: int | None = None,+ user_api_base: str | None = None,+ version: str | None = None,+ is_streaming_request: bool | None = False,+ contents: list[object] | None = None,+ skip_pre_call_logic: bool = False,+ ) -> Any:+ """Run the request, sending SSE keepalives while the upstream is still silent.++ Everything below this point, the upstream call included, happens before the+ proxy can write a byte, so a slow time-to-first-token leaves the response+ idle. See ``open_sse_before_first_byte``; unwrapped unless an operator sets+ ``litellm_settings.sse_keepalive_ping_interval_seconds``.+ """++ async def _audit_late_failure(exc: Exception) -> HTTPException | None:+ # Once a keepalive is on the wire this can no longer raise, so the+ # caller's `except` never runs its own post_call_failure_hook.+ return await proxy_logging_obj.post_call_failure_hook(+ user_api_key_dict=user_api_key_dict,+ original_exception=exc,+ request_data=self.data,+ )++ return await open_sse_before_first_byte(+ self._process_llm_request(+ request=request,+ fastapi_response=fastapi_response,+ user_api_key_dict=user_api_key_dict,+ route_type=route_type,+ proxy_logging_obj=proxy_logging_obj,+ general_settings=general_settings,+ proxy_config=proxy_config,+ select_data_generator=select_data_generator,+ llm_router=llm_router,+ model=model,+ user_model=user_model,+ user_temperature=user_temperature,+ user_request_timeout=user_request_timeout,+ user_max_tokens=user_max_tokens,+ user_api_base=user_api_base,+ version=version,+ is_streaming_request=is_streaming_request,+ contents=contents,+ skip_pre_call_logic=skip_pre_call_logic,+ ),+ ping_interval_seconds=ttft_keepalive_interval(self.data, llm_router),+ on_late_failure=_audit_late_failure,+ )++ async def _process_llm_request(+ self,+ request: Request,+ fastapi_response: Response,+ user_api_key_dict: UserAPIKeyAuth,+ route_type: ProxyRouteType,+ proxy_logging_obj: ProxyLogging,+ general_settings: dict[str, object],proxy_config: ProxyConfig,- select_data_generator: Callable | None = None,+ select_data_generator: Callable[..., object] | None = None,llm_router: Router | None = None,model: str | None = None,user_model: str | None = None,@@ -1817,7 +2081,7 @@ class ProxyBaseLLMRequestProcessing:user_api_base: str | None = None,version: str | None = None,is_streaming_request: bool | None = False,- contents: list | None = None, # Add contents parameter+ contents: list[object] | None = None, # Add contents parameterskip_pre_call_logic: bool = False,) -> Any:"""diff --git a/litellm/proxy/common_utils/sse_keepalive.py b/litellm/proxy/common_utils/sse_keepalive.pyindex e5183ac29d4..51ace009f54 100644--- a/litellm/proxy/common_utils/sse_keepalive.py+++ b/litellm/proxy/common_utils/sse_keepalive.py@@ -1,15 +1,22 @@import asyncioimport contextlibimport math-from collections.abc import AsyncGenerator+from collections.abc import AsyncGenerator, Iterable, Mappingfrom typing import Finalimport anyioANTHROPIC_PING_SSE_CHUNK: Final = 'event: ping\ndata: {"type": "ping"}\n\n'+SSE_COMMENT_PING_BYTES: Final = b": ping\n\n"+# 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 Nonetry:@@ -28,7 +35,7 @@ def keepalive_ping_has_fired(elapsed_seconds: float, ping_interval_seconds: floathe status line is already on the wire. With pings disabled nothing flushes early, so a raisestill carries its real status."""- interval: Final = _coerce_interval(ping_interval_seconds)+ interval: Final = coerce_keepalive_interval(ping_interval_seconds)return interval is not None and elapsed_seconds >= interval@@ -36,7 +43,7 @@ def wrap_sse_stream_with_keepalive_pings(stream: AsyncGenerator[str, None],ping_interval_seconds: float | str | None,) -> AsyncGenerator[str, None]:- interval: Final = _coerce_interval(ping_interval_seconds)+ interval: Final = coerce_keepalive_interval(ping_interval_seconds)if interval is None:return streamreturn _keepalive_ping_stream(stream=stream, ping_interval_seconds=interval)@@ -66,3 +73,96 @@ async def _keepalive_ping_stream(with contextlib.suppress(BaseException):await pendingawait stream.aclose()+++def is_sse_content_type(content_type: str | None) -> bool:+ return content_type is not None and content_type.split(";", 1)[0].strip().lower() == _SSE_MEDIA_TYPE+++def wrap_passthrough_sse_bytes_with_keepalive_pings(+ stream: AsyncGenerator[bytes, None],+ ping_interval_seconds: float | str | None,+ upstream_headers: Mapping[str, str],+) -> AsyncGenerator[bytes, None]:+ """Fill upstream silence on a byte-relaying passthrough stream with SSE comments.++ Passthrough routes relay upstream bytes verbatim, so a model that thinks for+ longer than an intermediary's idle read timeout has its connection dropped+ before the first token. Only streams the upstream itself declares as+ ``text/event-stream`` are wrapped: a comment spliced into a binary transport+ (AWS event streams on ``/bedrock``, protobuf, NDJSON) would corrupt it.+ """+ interval: Final = coerce_keepalive_interval(ping_interval_seconds)+ if interval is None or not is_sse_content_type(upstream_headers.get("content-type")):+ return stream+ return _keepalive_ping_byte_stream(stream=stream, ping_interval_seconds=interval)+++async def _keepalive_ping_byte_stream(+ stream: AsyncGenerator[bytes, None],+ ping_interval_seconds: float,+) -> AsyncGenerator[bytes, None]:+ pending = asyncio.ensure_future(+ stream.__anext__()+ ) # rebind-ok: re-armed with the next __anext__ after each delivered chunk+ # The tail of the bytes relayed so far, long enough to hold any delimiter.+ # Seeded as a delimiter because a stream starts at a frame boundary, and kept+ # across chunks because a delimiter can be split between two transport reads,+ # which testing only the latest chunk would miss for the rest of the stream.+ recent_tail = _STREAM_START_TAIL # rebind-ok: rolling window over the relayed bytes+ try:+ while True:+ await asyncio.wait((pending,), timeout=ping_interval_seconds)+ if not pending.done():+ # The relayed chunks are raw transport reads, not whole SSE+ # frames, so an upstream that stalls halfway through a frame+ # must not have a comment spliced into it.+ if recent_tail.endswith(_SSE_FRAME_DELIMITERS):+ yield SSE_COMMENT_PING_BYTES+ continue+ try:+ chunk: bytes = pending.result()+ except StopAsyncIteration:+ return+ if chunk:+ recent_tail = (recent_tail + chunk)[-_SSE_DELIMITER_LOOKBACK:]+ yield chunk+ pending = asyncio.ensure_future(stream.__anext__())+ finally:+ pending.cancel()+ with anyio.CancelScope(shield=True):+ with contextlib.suppress(BaseException):+ await pending+ await stream.aclose()+++def resolve_ttft_keepalive_interval(+ deployments: Iterable[Mapping[str, object]],+ global_interval: float | str | None,+) -> float | None:+ """The keepalive interval to use before the upstream has answered at all.++ No deployment has served the request yet, so a per-deployment+ ``keepalive_seconds`` is only trusted when every candidate under the requested+ model carries the same one, which is how the mid-stream engine treats its own+ model_name fallback. Otherwise the operator's global default applies.++ An explicit ``0`` survives as a disable, since coercion rejects it: that keeps+ an operator's documented hard disable working on this path too, rather than+ letting the global switch a deployment back on behind their back.++ A client-supplied value is deliberately not consulted. Opening the response+ early is an operator decision, and a request must not be able to enable it for+ a deployment that never did.+ """+ configured: Final = frozenset(_keepalive_param(deployment) for deployment in deployments)+ agreed: Final = next(iter(configured)) if len(configured) == 1 else None+ return coerce_keepalive_interval(global_interval if agreed is None else agreed)+++def _keepalive_param(deployment: Mapping[str, object]) -> float | str | None:+ params: Final = deployment.get("litellm_params")+ if not isinstance(params, Mapping):+ return None+ value: Final = params.get("keepalive_seconds")+ return value if isinstance(value, (int, float, str)) else Nonediff --git a/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py b/litellm/proxy/pass_through_endpoints/pass_through_endpoints.pyindex 211c3742343..0df0aaa1bcd 100644--- a/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py+++ b/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py@@ -61,11 +61,17 @@ from litellm.proxy._types import (UserAPIKeyAuth,)from litellm.proxy.auth.user_api_key_auth import user_api_key_auth-from litellm.proxy.common_request_processing import ProxyBaseLLMRequestProcessing+from litellm.proxy.common_request_processing import (+ ProxyBaseLLMRequestProcessing,+ open_sse_before_first_byte,+)from litellm.proxy.common_utils.http_parsing_utils import (_read_request_body,_safe_get_request_headers,)+from litellm.proxy.common_utils.sse_keepalive import (+ wrap_passthrough_sse_bytes_with_keepalive_pings,+)from litellm.proxy.litellm_pre_call_utils import LiteLLMProxyRequestSetupfrom litellm.proxy.utils import normalize_route_for_root_pathfrom litellm.repositories.team_repository import TeamRepository@@ -1173,14 +1179,18 @@ async def pass_through_request(_response_headers.update(callback_headers)return StreamingResponse(- PassThroughStreamingHandler.chunk_processor(- response=response,- request_body=_parsed_body,- litellm_logging_obj=logging_obj,- endpoint_type=endpoint_type,- start_time=start_time,- passthrough_success_handler_obj=pass_through_endpoint_logging,- url_route=str(url),+ wrap_passthrough_sse_bytes_with_keepalive_pings(+ stream=PassThroughStreamingHandler.chunk_processor(+ response=response,+ request_body=_parsed_body,+ litellm_logging_obj=logging_obj,+ endpoint_type=endpoint_type,+ start_time=start_time,+ passthrough_success_handler_obj=pass_through_endpoint_logging,+ url_route=str(url),+ ),+ ping_interval_seconds=litellm.sse_keepalive_ping_interval_seconds,+ upstream_headers=response.headers,),headers=_response_headers,status_code=response.status_code,@@ -1245,14 +1255,18 @@ async def pass_through_request(_response_headers.update(callback_headers)return StreamingResponse(- PassThroughStreamingHandler.chunk_processor(- response=response,- request_body=_parsed_body,- litellm_logging_obj=logging_obj,- endpoint_type=endpoint_type,- start_time=start_time,- passthrough_success_handler_obj=pass_through_endpoint_logging,- url_route=str(url),+ wrap_passthrough_sse_bytes_with_keepalive_pings(+ stream=PassThroughStreamingHandler.chunk_processor(+ response=response,+ request_body=_parsed_body,+ litellm_logging_obj=logging_obj,+ endpoint_type=endpoint_type,+ start_time=start_time,+ passthrough_success_handler_obj=pass_through_endpoint_logging,+ url_route=str(url),+ ),+ ping_interval_seconds=litellm.sse_keepalive_ping_interval_seconds,+ upstream_headers=response.headers,),headers=_response_headers,status_code=response.status_code,@@ -1787,28 +1801,39 @@ def create_pass_through_route(elif isinstance(custom_body_data, dict):final_custom_body = custom_body_data- try:- return await pass_through_request(- request=request,- target=full_target,- custom_headers=headers_dict,- user_api_key_dict=user_api_key_dict,- forward_headers=cast(bool | None, param_forward_headers),- merge_query_params=cast(bool | None, param_merge_query_params),- query_params=final_query_params,- default_query_params=cast(dict | None, param_default_query_params),- stream=is_streaming_request or stream,- custom_body=final_custom_body,- cost_per_request=cast(float | None, param_cost_per_request),- custom_llm_provider=custom_llm_provider,- guardrails_config=cast(dict | None, param_guardrails),- timeout=cast(float | None, param_timeout),- )- finally:- if hasattr(request.state, LITELLM_PASS_THROUGH_CUSTOM_BODY_STATE_KEY):- delattr(request.state, LITELLM_PASS_THROUGH_CUSTOM_BODY_STATE_KEY)- if hasattr(request.state, LITELLM_PASS_THROUGH_RAW_BODY_STATE_KEY):- delattr(request.state, LITELLM_PASS_THROUGH_RAW_BODY_STATE_KEY)+ is_stream: Final = bool(is_streaming_request or stream)++ async def _relay() -> Response:+ try:+ return await pass_through_request(+ request=request,+ target=full_target,+ custom_headers=headers_dict,+ user_api_key_dict=user_api_key_dict,+ forward_headers=cast(bool | None, param_forward_headers),+ merge_query_params=cast(bool | None, param_merge_query_params),+ query_params=final_query_params,+ default_query_params=cast(dict | None, param_default_query_params),+ stream=is_stream,+ custom_body=final_custom_body,+ cost_per_request=cast(float | None, param_cost_per_request),+ custom_llm_provider=custom_llm_provider,+ guardrails_config=cast(dict | None, param_guardrails),+ timeout=cast(float | None, param_timeout),+ )+ finally:+ if hasattr(request.state, LITELLM_PASS_THROUGH_CUSTOM_BODY_STATE_KEY):+ delattr(request.state, LITELLM_PASS_THROUGH_CUSTOM_BODY_STATE_KEY)+ if hasattr(request.state, LITELLM_PASS_THROUGH_RAW_BODY_STATE_KEY):+ delattr(request.state, LITELLM_PASS_THROUGH_RAW_BODY_STATE_KEY)++ # The upstream withholds its response headers until its first token, so+ # the whole time-to-first-token is spent inside _relay with nothing on+ # the wire. Off unless an operator sets an interval.+ return await open_sse_before_first_byte(+ _relay(),+ ping_interval_seconds=(litellm.sse_keepalive_ping_interval_seconds if is_stream else None),+ )setattr(endpoint_func, LITELLM_PASS_THROUGH_ENDPOINT_MARKER, True)return endpoint_funcdiff --git a/tests/test_litellm/proxy/common_utils/test_sse_keepalive.py b/tests/test_litellm/proxy/common_utils/test_sse_keepalive.pyindex 9cca9bbfe12..89ae74920fe 100644--- a/tests/test_litellm/proxy/common_utils/test_sse_keepalive.py+++ b/tests/test_litellm/proxy/common_utils/test_sse_keepalive.py@@ -8,6 +8,9 @@ from fastapi.responses import StreamingResponsefrom litellm.proxy.common_request_processing import create_responsefrom litellm.proxy.common_utils.sse_keepalive import (ANTHROPIC_PING_SSE_CHUNK,+ SSE_COMMENT_PING_BYTES,+ resolve_ttft_keepalive_interval,+ wrap_passthrough_sse_bytes_with_keepalive_pings,wrap_sse_stream_with_keepalive_pings,)@@ -156,3 +159,229 @@ async def test_create_response_streams_ping_first_for_slow_upstream():collected: Final = [chunk async for chunk in response.body_iterator]assert collected[0] == ANTHROPIC_PING_SSE_CHUNKassert collected[-1] == MESSAGE_START_CHUNK+++SSE_FRAME_BYTES: Final = b'event: content_block_delta\ndata: {"type": "content_block_delta"}\n\n'+BEDROCK_EVENT_STREAM_CONTENT_TYPE: Final = "application/vnd.amazon.eventstream"+++async def test_passthrough_ping_emitted_while_waiting_for_the_first_upstream_byte():+ async def slow_start_stream() -> AsyncGenerator[bytes, None]:+ await asyncio.sleep(0.2)+ yield SSE_FRAME_BYTES++ wrapped: Final = wrap_passthrough_sse_bytes_with_keepalive_pings(+ stream=slow_start_stream(),+ ping_interval_seconds=0.05,+ upstream_headers={"content-type": "text/event-stream"},+ )+ collected: Final = [chunk async for chunk in wrapped]++ assert collected[0] == SSE_COMMENT_PING_BYTES+ assert collected[-1] == SSE_FRAME_BYTES+ assert b"".join(c for c in collected if c != SSE_COMMENT_PING_BYTES) == SSE_FRAME_BYTES++[email protected]("content_type", ["text/event-stream", "text/event-stream; charset=utf-8", "TEXT/Event-Stream"])+async def test_passthrough_wraps_every_spelling_of_the_sse_content_type(content_type: str):+ async def slow_start_stream() -> AsyncGenerator[bytes, None]:+ await asyncio.sleep(0.2)+ yield SSE_FRAME_BYTES++ wrapped: Final = wrap_passthrough_sse_bytes_with_keepalive_pings(+ stream=slow_start_stream(),+ ping_interval_seconds=0.05,+ upstream_headers={"content-type": content_type},+ )+ collected: Final = [chunk async for chunk in wrapped]++ assert SSE_COMMENT_PING_BYTES in collected+++ "content_type",+ [BEDROCK_EVENT_STREAM_CONTENT_TYPE, "application/json", "application/x-ndjson", None, "text/event-streamish"],+)+async def test_passthrough_leaves_a_non_sse_transport_untouched(content_type: str | None):+ """A comment spliced into a binary transport (e.g. an AWS event stream) corrupts it."""++ async def any_stream() -> AsyncGenerator[bytes, None]:+ yield SSE_FRAME_BYTES++ stream: Final = any_stream()+ assert (+ wrap_passthrough_sse_bytes_with_keepalive_pings(+ stream=stream,+ ping_interval_seconds=0.05,+ upstream_headers={} if content_type is None else {"content-type": content_type},+ )+ is stream+ )+ await stream.aclose()+++async def test_passthrough_ping_is_never_spliced_into_a_half_delivered_frame():+ """Relayed chunks are raw transport reads, so an upstream can stall mid-frame."""++ async def stalls_mid_frame() -> AsyncGenerator[bytes, None]:+ yield b'event: content_block_delta\ndata: {"partial":'+ await asyncio.sleep(0.3)+ yield b"1}\n\n"++ wrapped: Final = wrap_passthrough_sse_bytes_with_keepalive_pings(+ stream=stalls_mid_frame(),+ ping_interval_seconds=0.05,+ upstream_headers={"content-type": "text/event-stream"},+ )+ collected: Final = [chunk async for chunk in wrapped]++ assert SSE_COMMENT_PING_BYTES not in collected+ assert b"".join(collected) == b'event: content_block_delta\ndata: {"partial":1}\n\n'+++async def test_passthrough_ping_resumes_once_the_stalled_frame_completes():+ async def stalls_mid_frame_then_at_boundary() -> AsyncGenerator[bytes, None]:+ yield b'event: content_block_delta\ndata: {"partial":'+ await asyncio.sleep(0.2)+ yield b"1}\n\n"+ await asyncio.sleep(0.2)+ yield SSE_FRAME_BYTES++ wrapped: Final = wrap_passthrough_sse_bytes_with_keepalive_pings(+ stream=stalls_mid_frame_then_at_boundary(),+ ping_interval_seconds=0.05,+ upstream_headers={"content-type": "text/event-stream"},+ )+ collected: Final = [chunk async for chunk in wrapped]++ ping_index: Final = collected.index(SSE_COMMENT_PING_BYTES)+ assert collected[:ping_index] == [b'event: content_block_delta\ndata: {"partial":', b"1}\n\n"]+ assert collected[-1] == SSE_FRAME_BYTES++[email protected]("bad_interval", [None, 0, "abc", float("inf"), float("nan"), "-3"])+async def test_passthrough_invalid_or_disabled_interval_returns_stream_unwrapped(bad_interval: float | str | None):+ async def any_stream() -> AsyncGenerator[bytes, None]:+ yield SSE_FRAME_BYTES++ stream: Final = any_stream()+ assert (+ wrap_passthrough_sse_bytes_with_keepalive_pings(+ stream=stream,+ ping_interval_seconds=bad_interval,+ upstream_headers={"content-type": "text/event-stream"},+ )+ is stream+ )+ await stream.aclose()+++async def test_passthrough_aclose_mid_silence_cancels_upstream_and_runs_its_cleanup():+ upstream_cleaned_up: Final = asyncio.Event()++ async def hung_stream() -> AsyncGenerator[bytes, None]:+ try:+ yield SSE_FRAME_BYTES+ await asyncio.Event().wait()+ finally:+ upstream_cleaned_up.set()++ wrapped: Final = wrap_passthrough_sse_bytes_with_keepalive_pings(+ stream=hung_stream(),+ ping_interval_seconds=0.05,+ upstream_headers={"content-type": "text/event-stream"},+ )++ assert await wrapped.__anext__() == SSE_FRAME_BYTES+ assert await wrapped.__anext__() == SSE_COMMENT_PING_BYTES+ await wrapped.aclose()++ assert upstream_cleaned_up.is_set()+++async def test_passthrough_upstream_exception_propagates():+ async def failing_stream() -> AsyncGenerator[bytes, None]:+ yield SSE_FRAME_BYTES+ raise ValueError("upstream broke")++ wrapped: Final = wrap_passthrough_sse_bytes_with_keepalive_pings(+ stream=failing_stream(),+ ping_interval_seconds=5.0,+ upstream_headers={"content-type": "text/event-stream"},+ )++ assert await wrapped.__anext__() == SSE_FRAME_BYTES+ with pytest.raises(ValueError, match="upstream broke"):+ await wrapped.__anext__()+++ "split_frame",+ [+ (b'data: {"a": 1}\n', b"\n"),+ (b'data: {"a": 1}\r\n', b"\r\n"),+ (b'data: {"a": 1}\r', b"\n\r\n"),+ (b'data: {"a": 1}\r', b"\r"),+ (b'data: {"a": 1}\r\r', b""),+ (b'data: {"a": 1}\n\n', b""),+ ],+ ids=["lf-split", "crlf-split", "crlf-mixed-split", "cr-only-split", "cr-only-whole", "not-split"],+)+async def test_passthrough_sees_a_frame_delimiter_split_across_transport_chunks(split_frame):+ """A raw transport read can end mid-delimiter. Testing only the latest chunk+ would leave the stream looking permanently mid-frame, silently disabling the+ keepalive the operator configured."""++ async def split_delimiter_stream() -> AsyncGenerator[bytes, None]:+ for part in split_frame:+ if part:+ yield part+ await asyncio.sleep(0.3)+ yield SSE_FRAME_BYTES++ wrapped: Final = wrap_passthrough_sse_bytes_with_keepalive_pings(+ stream=split_delimiter_stream(),+ ping_interval_seconds=0.05,+ upstream_headers={"content-type": "text/event-stream"},+ )+ collected: Final = [chunk async for chunk in wrapped]++ assert SSE_COMMENT_PING_BYTES in collected+ assert b"".join(c for c in collected if c != SSE_COMMENT_PING_BYTES) == b"".join(split_frame) + SSE_FRAME_BYTES+++def _deployment(keepalive_seconds=..., model="openai/gpt-4o"):+ params = {"model": model}+ if keepalive_seconds is not ...:+ params["keepalive_seconds"] = keepalive_seconds+ return {"model_name": "m", "litellm_params": params}+++ "deployments, global_interval, expected, why",+ [+ ([], 30.0, 30.0, "no deployments known, the global applies"),+ ([_deployment()], 30.0, 30.0, "nothing configured, the global applies"),+ ([_deployment(0)], 30.0, None, "an operator's explicit 0 is a hard disable the global cannot lift"),+ ([_deployment("0")], 30.0, None, "the same, written as a yaml string"),+ ([_deployment(15)], 30.0, 15.0, "a deployment value wins over the global"),+ ([_deployment(15), _deployment(15)], 30.0, 15.0, "agreeing deployments are trusted"),+ ([_deployment(15), _deployment(60)], 30.0, 30.0, "disagreeing deployments fall back to the global"),+ ([_deployment(0), _deployment(30)], 30.0, 30.0, "a partial disable is not trusted before one is chosen"),+ ([_deployment(15)], None, 15.0, "a deployment value applies with no global set"),+ ([_deployment()], None, None, "nothing anywhere leaves it off"),+ ],+)+def test_ttft_interval_resolves_through_the_deployments_it_could_land_on(+ deployments, global_interval, expected, why+):+ assert resolve_ttft_keepalive_interval(deployments, global_interval) == expected, whydiff --git a/tests/test_litellm/proxy/guardrails/test_deferred_guardrail_logging.py b/tests/test_litellm/proxy/guardrails/test_deferred_guardrail_logging.pyindex be92b6fc6c4..c4a0a62ef97 100644--- a/tests/test_litellm/proxy/guardrails/test_deferred_guardrail_logging.py+++ b/tests/test_litellm/proxy/guardrails/test_deferred_guardrail_logging.py@@ -386,25 +386,30 @@ def test_flush_deferred_async_logging_noop_when_no_closure_stored():def test_proxy_finally_block_routes_through_flush_helper():"""- Source-level contract: the proxy's `base_process_llm_request` finally- block must delegate to `_flush_deferred_async_logging` rather than- inlining the gating logic. Inlining is what allowed the duplicate- Success+Failure spend log to slip in originally — this guards the- refactor.+ Source-level contract: the proxy's request-processing finally block must+ delegate to `_flush_deferred_async_logging` rather than inlining the gating+ logic. Inlining is what allowed the duplicate Success+Failure spend log to+ slip in originally — this guards the refactor.++ Both halves of the request path are inspected: `base_process_llm_request` is+ the public entry point and `_process_llm_request` holds the body, so neither+ may inline the reset regardless of which one carries the finally block."""import inspect- src = inspect.getsource(ProxyBaseLLMRequestProcessing.base_process_llm_request)+ src = inspect.getsource(ProxyBaseLLMRequestProcessing._process_llm_request) + inspect.getsource(+ ProxyBaseLLMRequestProcessing.base_process_llm_request+ )assert "_flush_deferred_async_logging" in src, (- "base_process_llm_request must call _flush_deferred_async_logging "- "from its finally block — do not inline the gating logic."+ "the request path must call _flush_deferred_async_logging from its "+ "finally block — do not inline the gating logic.")# Belt-and-braces: the inlined `_enqueue_deferred_logging = None` reset# was the symptom of the duplicate-log bug; assert it stays inside the# helper, not in the request-processing function.assert "_enqueue_deferred_logging = None" not in src, ("Reset of _enqueue_deferred_logging must live inside "- "_flush_deferred_async_logging, not in base_process_llm_request."+ "_flush_deferred_async_logging, not in the request path.")diff --git a/tests/test_litellm/proxy/pass_through_endpoints/test_pass_through_endpoints.py b/tests/test_litellm/proxy/pass_through_endpoints/test_pass_through_endpoints.pyindex eefdefcee80..b1b934b0949 100644--- a/tests/test_litellm/proxy/pass_through_endpoints/test_pass_through_endpoints.py+++ b/tests/test_litellm/proxy/pass_through_endpoints/test_pass_through_endpoints.py@@ -41,6 +41,10 @@ from litellm.proxy.pass_through_endpoints.success_handler import (PassThroughEndpointLogging,)+import litellm++MESSAGE_START_SSE_FRAME = b'event: message_start\ndata: {"type": "message_start"}\n\n'+# Test is_multipartdef test_is_multipart():@@ -5104,3 +5108,185 @@ async def test_passthrough_body_cannot_forge_budget_reservation():increment_spend_counters.assert_awaited_once()assert increment_spend_counters.await_args.kwargs["budget_reservation"] is None+++async def _drive_streaming_pass_through(+ upstream_content_type, chunk_delay_seconds, client_asked_for_stream=True+):+ """Drive pass_through_request against an upstream that stalls before its first byte.++ ``client_asked_for_stream`` picks which of pass_through_request's two streaming+ dispatch branches runs: the up-front one, and the one that only discovers the+ response is a stream from its content-type.+ """+ from litellm.proxy.pass_through_endpoints.pass_through_endpoints import (+ PassThroughStreamingHandler,+ )++ with ExitStack() as stack:+ mock_proxy_logging = stack.enter_context(+ patch("litellm.proxy.proxy_server.proxy_logging_obj")+ )+ mock_get_client = stack.enter_context(+ patch(+ "litellm.proxy.pass_through_endpoints.pass_through_endpoints.get_async_httpx_client"+ )+ )+ mock_chunk_processor = stack.enter_context(+ patch.object(PassThroughStreamingHandler, "chunk_processor")+ )++ mock_proxy_logging.pre_call_hook = AsyncMock(+ return_value={"model": "claude-3", "stream": True}+ if client_asked_for_stream+ else {"model": "claude-3"}+ )+ mock_proxy_logging.post_call_failure_hook = AsyncMock()+ mock_proxy_logging.post_call_response_headers_hook = AsyncMock(return_value={})++ upstream_response = MagicMock()+ upstream_response.status_code = 200+ upstream_response.headers = {"content-type": upstream_content_type}+ upstream_response.raise_for_status = MagicMock()++ async_client = MagicMock()+ async_client.build_request = MagicMock(return_value=MagicMock())+ async_client.send = AsyncMock(return_value=upstream_response)+ mock_get_client.return_value = MagicMock(client=async_client)++ async def _slow_first_chunk(*args, **kwargs):+ await asyncio.sleep(chunk_delay_seconds)+ yield MESSAGE_START_SSE_FRAME++ mock_chunk_processor.return_value = _slow_first_chunk()++ mock_request = MagicMock(spec=Request)+ mock_request.method = "POST"+ mock_request.url = "http://test-proxy.com/v1/messages"+ mock_request.body = AsyncMock(+ return_value=b'{"model": "claude-3", "stream": true}'+ if client_asked_for_stream+ else b'{"model": "claude-3"}'+ )+ mock_request.headers = Headers({})+ mock_request.query_params = QueryParams({})++ response = await pass_through_request(+ request=mock_request,+ target="http://target-api.com/v1/messages",+ custom_headers={},+ user_api_key_dict=MagicMock(),+ stream=client_asked_for_stream,+ )+ return [chunk async for chunk in response.body_iterator]++[email protected]("client_asked_for_stream", [True, False])+async def test_pass_through_sse_stream_emits_keepalive_before_the_first_upstream_byte(+ client_asked_for_stream,+):+ """+ Regression for #34819: a passthrough SSE stream wrote zero bytes during the+ model's time-to-first-token, so an intermediary with an idle read timeout+ (ALB, nginx) dropped a healthy connection before any token arrived.++ Both dispatch branches are covered: a request that declared stream=true, and+ one whose response is only recognised as a stream from its content-type.+ """+ with patch.object(litellm, "sse_keepalive_ping_interval_seconds", 0.05):+ collected = await _drive_streaming_pass_through(+ upstream_content_type="text/event-stream",+ chunk_delay_seconds=0.2,+ client_asked_for_stream=client_asked_for_stream,+ )++ assert collected[0] == b": ping\n\n"+ assert collected[-1] == MESSAGE_START_SSE_FRAME+++async def test_pass_through_sse_stream_stays_silent_when_keepalive_is_unconfigured():+ with patch.object(litellm, "sse_keepalive_ping_interval_seconds", None):+ collected = await _drive_streaming_pass_through(+ upstream_content_type="text/event-stream", chunk_delay_seconds=0.2+ )++ assert collected == [MESSAGE_START_SSE_FRAME]+++async def test_pass_through_binary_event_stream_is_never_given_an_sse_comment():+ """An AWS event stream is a binary transport: a ": ping" frame would corrupt it."""+ with patch.object(litellm, "sse_keepalive_ping_interval_seconds", 0.05):+ collected = await _drive_streaming_pass_through(+ upstream_content_type="application/vnd.amazon.eventstream",+ chunk_delay_seconds=0.2,+ )++ assert collected == [MESSAGE_START_SSE_FRAME]++[email protected]("configured_interval, expect_ping", [(0.05, True), (None, False)])+async def test_pass_through_route_pings_while_the_upstream_call_is_still_running(+ configured_interval, expect_ping+):+ """The upstream withholds its response headers until its first token, so the+ whole time-to-first-token is spent inside pass_through_request with nothing on+ the wire (issue #34819)."""+ from fastapi import Response+ from fastapi.responses import StreamingResponse++ module = "litellm.proxy.pass_through_endpoints.pass_through_endpoints"++ async def _relayed():+ yield MESSAGE_START_SSE_FRAME++ async def slow_pass_through(**kwargs):+ await asyncio.sleep(0.25)+ return StreamingResponse(_relayed(), media_type="text/event-stream")++ with ExitStack() as stack:+ stack.enter_context(+ patch(+ f"{module}.InitPassThroughEndpointHelpers.is_registered_pass_through_route",+ return_value=True,+ )+ )+ stack.enter_context(+ patch(+ f"{module}.InitPassThroughEndpointHelpers.get_registered_pass_through_route",+ return_value=None,+ )+ )+ stack.enter_context(patch(f"{module}.pass_through_request", slow_pass_through))+ stack.enter_context(+ patch.object(litellm, "sse_keepalive_ping_interval_seconds", configured_interval)+ )++ endpoint_func = create_pass_through_route(+ endpoint="/v1/messages",+ target="https://api.anthropic.com/v1/messages",+ custom_headers={},+ is_streaming_request=True,+ )++ mock_request = MagicMock(spec=Request)+ mock_request.method = "POST"+ mock_request.url = httpx.URL("http://test-proxy.com/v1/messages")+ mock_request.scope = {}+ mock_request.body = AsyncMock(return_value=b'{"model": "claude-3"}')+ mock_request.headers = Headers({"content-type": "application/json"})+ mock_request.query_params = QueryParams({})+ mock_request.state = SimpleNamespace()++ response = await endpoint_func(+ request=mock_request,+ fastapi_response=Response(),+ user_api_key_dict=MagicMock(),+ )+ collected = [chunk async for chunk in response.body_iterator]++ assert (collected[0] == b": ping\n\n") is expect_ping+ assert collected[-1] in (MESSAGE_START_SSE_FRAME, MESSAGE_START_SSE_FRAME.decode())diff --git a/tests/test_litellm/proxy/test_common_request_processing.py b/tests/test_litellm/proxy/test_common_request_processing.pyindex ddb7b0d510f..355c6d27eb2 100644--- a/tests/test_litellm/proxy/test_common_request_processing.py+++ b/tests/test_litellm/proxy/test_common_request_processing.py@@ -28,6 +28,9 @@ from litellm.proxy.common_request_processing import (_get_cost_breakdown_from_logging_obj,_has_attribute_error_in_chain,_is_azure_model_router_request,+ _UpstreamClosingStreamingResponse,+ open_sse_before_first_byte,+ ttft_keepalive_interval,_override_openai_response_model,_parse_event_data_for_error,_resolve_per_request_model_group_alias,@@ -6112,3 +6115,525 @@ class TestProcessChunkWithCostInjection:)assert ProxyBaseLLMRequestProcessing._process_chunk_with_cost_injection(chunk, "gpt-4o-mini") == chunk+++# ---------------------------------------------------------------------------+# SSE keepalive during the time-to-first-token (issue #34819)+# ---------------------------------------------------------------------------++TTFT_PING = b": ping\n\n"+++async def _drain(response):+ return [chunk async for chunk in response.body_iterator]+++def _sse_response(chunks, upstream_generator=None):+ async def gen():+ for chunk in chunks:+ yield chunk++ if upstream_generator is None:+ return StreamingResponse(gen(), media_type="text/event-stream")+ return _UpstreamClosingStreamingResponse(+ gen(),+ media_type="text/event-stream",+ upstream_generator=upstream_generator,+ )+++async def test_ttft_keepalive_fills_the_wire_while_the_upstream_is_still_silent():+ """Regression for #34819. The upstream withholds its headers until the first+ token, so the whole wait happens before a byte can be written and an+ idle-timeout hop drops a healthy connection."""++ async def slow_upstream():+ await asyncio.sleep(0.35)+ return _sse_response(['data: {"first": true}\n\n'])++ response = await open_sse_before_first_byte(slow_upstream(), ping_interval_seconds=0.05)++ assert isinstance(response, StreamingResponse)+ assert response.headers["x-accel-buffering"] == "no"+ collected = await _drain(response)+ assert collected[0] == TTFT_PING+ assert collected.count(TTFT_PING) >= 3+ assert collected[-1] == b'data: {"first": true}\n\n'+++async def test_ttft_keepalive_is_a_no_op_when_the_upstream_answers_in_time():+ produced = _sse_response(['data: {"fast": true}\n\n'])++ async def fast_upstream():+ return produced++ response = await open_sse_before_first_byte(fast_upstream(), ping_interval_seconds=5.0)++ assert response is produced+ assert await _drain(response) == ['data: {"fast": true}\n\n']++[email protected]("interval", [None, 0, "", "abc", float("inf"), float("nan"), -1])+async def test_ttft_keepalive_unconfigured_leaves_the_call_completely_untouched(interval):+ produced = _sse_response(['data: {"x": 1}\n\n'])+ started_at = asyncio.get_running_loop().time()++ async def slow_upstream():+ await asyncio.sleep(0.15)+ return produced++ response = await open_sse_before_first_byte(slow_upstream(), ping_interval_seconds=interval)++ assert response is produced+ assert asyncio.get_running_loop().time() - started_at >= 0.15+++async def test_ttft_keepalive_reraises_a_fast_failure_so_it_keeps_its_http_status():+ async def fast_failure():+ raise HTTPException(status_code=429, detail="rate limited")++ with pytest.raises(HTTPException) as excinfo:+ await open_sse_before_first_byte(fast_failure(), ping_interval_seconds=5.0)++ assert excinfo.value.status_code == 429+++async def test_ttft_keepalive_delivers_a_late_failure_as_an_sse_frame():+ """Once a ping is on the wire the status line is committed, so a failure+ discovered afterwards can only reach the client as a frame."""++ async def slow_failure():+ await asyncio.sleep(0.2)+ raise HTTPException(status_code=429, detail="rate limited")++ response = await open_sse_before_first_byte(slow_failure(), ping_interval_seconds=0.05)+ collected = await _drain(response)++ assert collected[0] == TTFT_PING+ assert collected[-1] == b"data: [DONE]\n\n"+ error_frame = json.loads(collected[-2].decode().removeprefix("data: ").strip())+ assert error_frame["error"]["code"] == "429"+ assert error_frame["error"]["message"] == "rate limited"+++async def test_ttft_keepalive_relays_a_late_non_streaming_body_as_an_sse_frame():+ async def slow_json():+ await asyncio.sleep(0.2)+ return JSONResponse(status_code=400, content={"error": {"message": "bad request"}})++ response = await open_sse_before_first_byte(slow_json(), ping_interval_seconds=0.05)+ collected = await _drain(response)++ assert collected[0] == TTFT_PING+ assert json.loads(collected[-2].decode().removeprefix("data: ").strip()) == {"error": {"message": "bad request"}}+ assert collected[-1] == b"data: [DONE]\n\n"+++async def test_ttft_keepalive_closes_the_upstream_stream_it_relayed():+ """Starlette never calls the produced response, so its own cleanup never runs+ and the upstream LLM connection would leak."""+ upstream_closed = asyncio.Event()++ async def upstream():+ try:+ yield 'data: {"a": 1}\n\n'+ finally:+ upstream_closed.set()++ upstream_gen = upstream()+ # Started, as create_response leaves it: aclose() on a never-started generator+ # skips its body, so an unstarted fixture cannot tell cleanup from no cleanup.+ await upstream_gen.__anext__()++ async def slow_upstream():+ await asyncio.sleep(0.2)+ return _sse_response(['data: {"a": 1}\n\n'], upstream_generator=upstream_gen)++ response = await open_sse_before_first_byte(slow_upstream(), ping_interval_seconds=0.05)+ await _drain(response)++ assert upstream_closed.is_set()+++async def test_ttft_keepalive_cancels_the_in_flight_call_when_the_client_gives_up():+ upstream_cancelled = asyncio.Event()++ async def never_answers():+ try:+ await asyncio.Event().wait()+ except asyncio.CancelledError:+ upstream_cancelled.set()+ raise++ response = await open_sse_before_first_byte(never_answers(), ping_interval_seconds=0.05)+ assert await response.body_iterator.__anext__() == TTFT_PING+ await response.body_iterator.aclose()+ await asyncio.sleep(0)++ assert upstream_cancelled.is_set()+++ "request_data, global_interval, expected",+ [+ ({"stream": True}, 30.0, 30.0),+ ({"stream": True}, None, None),+ ({"stream": False}, 30.0, None),+ ({}, 30.0, None),+ ({"stream": "true"}, 30.0, None),+ ],+)+def test_ttft_keepalive_interval_only_arms_for_a_streaming_request(request_data, global_interval, expected):+ with patch.object(litellm, "sse_keepalive_ping_interval_seconds", global_interval):+ assert ttft_keepalive_interval(request_data) == expected++[email protected]("stream_requested, expect_ping", [(True, True), (False, False)])+async def test_base_process_llm_request_pings_while_the_upstream_call_is_still_running(+ stream_requested, expect_ping+):+ """The wiring, not the helper: every route funnels through this method, and the+ whole time-to-first-token is spent inside the call it wraps."""++ async def slow_inner(self, **kwargs):+ await asyncio.sleep(0.25)+ return _sse_response(['data: {"late": true}\n\n'])++ processor = ProxyBaseLLMRequestProcessing(data={"model": "gpt-4o", "stream": stream_requested})++ with patch.object(litellm, "sse_keepalive_ping_interval_seconds", 0.05):+ with patch.object(ProxyBaseLLMRequestProcessing, "_process_llm_request", slow_inner):+ response = await processor.base_process_llm_request(+ request=MagicMock(spec=Request),+ fastapi_response=Response(),+ user_api_key_dict=MagicMock(spec=UserAPIKeyAuth),+ route_type="acompletion",+ proxy_logging_obj=MagicMock(spec=ProxyLogging),+ general_settings={},+ proxy_config=MagicMock(spec=ProxyConfig),+ )++ collected = await _drain(response)+ assert (collected[0] == TTFT_PING) is expect_ping+ assert collected[-1] == (b'data: {"late": true}\n\n' if expect_ping else 'data: {"late": true}\n\n')+++def _request_disconnecting_after(delay_seconds):+ """A Request whose ASGI channel delivers one http.disconnect, then goes quiet."""+ request = MagicMock(spec=Request)+ delivered = {"done": False}++ async def receive():+ if delivered["done"]:+ await asyncio.Event().wait()+ await asyncio.sleep(delay_seconds)+ delivered["done"] = True+ return {"type": "http.disconnect"}++ request.receive = receive+ return request+++ "disconnect_after, expect_full_delivery",+ [(0.25, False), (999.0, True)],+)+async def test_opening_the_response_early_still_closes_the_upstream_on_disconnect(+ disconnect_after, expect_full_delivery+):+ """Once the response is opened early, create_response's own disconnect+ monitoring runs while Starlette is already serving, so both read the same ASGI+ channel. Whichever observes the disconnect, the upstream LLM stream must close.+ """+ upstream_closed = asyncio.Event()+ delivered = []++ async def upstream():+ try:+ await asyncio.sleep(0.4)+ for chunk in ('data: {"a": 1}\n\n', "data: [DONE]\n\n"):+ delivered.append(chunk)+ yield chunk+ finally:+ upstream_closed.set()++ request = _request_disconnecting_after(disconnect_after)++ async def produce():+ await asyncio.sleep(0.15)+ return await create_response(+ generator=upstream(),+ media_type="text/event-stream",+ headers={},+ request=request,+ )++ response = await open_sse_before_first_byte(produce(), ping_interval_seconds=0.05)+ collected = await _drain(response)+ await asyncio.sleep(0.05)++ assert collected[0] == TTFT_PING+ assert upstream_closed.is_set()+ # The control has to actually deliver, or "the upstream closed" proves nothing.+ assert (delivered == ['data: {"a": 1}\n\n', "data: [DONE]\n\n"]) is expect_full_delivery+++async def test_a_disconnect_after_the_upstream_answered_still_closes_the_response():+ """The upstream can answer while nobody is draining the relay, e.g. the client+ vanished first. Nothing else holds that response, so only this teardown closes+ it; cancelling the produce task is not enough because it already finished."""+ upstream_closed = asyncio.Event()+ body_closed = asyncio.Event()++ async def upstream():+ try:+ yield 'data: {"a": 1}\n\n'+ await asyncio.Event().wait()+ finally:+ upstream_closed.set()++ async def body():+ try:+ yield 'data: {"a": 1}\n\n'+ await asyncio.Event().wait()+ finally:+ body_closed.set()++ # Both started, as create_response leaves them: aclose() on a never-started+ # generator skips its body, so an unstarted fixture cannot tell cleanup apart+ # from no cleanup at all.+ upstream_gen, body_gen = upstream(), body()+ await upstream_gen.__anext__()+ await body_gen.__anext__()++ async def produce():+ await asyncio.sleep(0.15)+ return _UpstreamClosingStreamingResponse(+ body_gen, media_type="text/event-stream", upstream_generator=upstream_gen+ )++ response = await open_sse_before_first_byte(produce(), ping_interval_seconds=0.05)+ assert await response.body_iterator.__anext__() == TTFT_PING+ await asyncio.sleep(0.25) # the produce task finishes while nothing is pulling+ await response.body_iterator.aclose()+ await asyncio.sleep(0.05)++ assert body_closed.is_set()+ assert upstream_closed.is_set()+++async def test_a_late_failure_is_reported_to_the_failure_hook():+ """Once a keepalive is on the wire this can no longer raise, so the caller's+ own `except` never runs and the failure would otherwise go unaudited."""+ audited = []++ async def slow_failure():+ await asyncio.sleep(0.2)+ raise HTTPException(status_code=500, detail="upstream exploded")++ async def record(exc):+ audited.append(exc)++ response = await open_sse_before_first_byte(+ slow_failure(), ping_interval_seconds=0.05, on_late_failure=record+ )+ collected = await _drain(response)++ assert [type(exc).__name__ for exc in audited] == ["HTTPException"]+ assert getattr(audited[0], "detail", None) == "upstream exploded"+ assert collected[-1] == b"data: [DONE]\n\n"+++async def test_a_failing_audit_hook_never_costs_the_client_its_error_frame():+ async def slow_failure():+ await asyncio.sleep(0.2)+ raise HTTPException(status_code=500, detail="upstream exploded")++ async def broken_hook(exc):+ raise RuntimeError("the audit backend is down")++ response = await open_sse_before_first_byte(+ slow_failure(), ping_interval_seconds=0.05, on_late_failure=broken_hook+ )+ collected = await _drain(response)++ error_frame = json.loads(collected[-2].decode().removeprefix("data: ").strip())+ assert error_frame["error"]["message"] == "upstream exploded"+ assert collected[-1] == b"data: [DONE]\n\n"+++async def test_base_process_llm_request_audits_a_failure_that_lands_after_its_keepalive():+ """The helper honouring on_late_failure is not enough: this pins that the shared+ funnel actually passes one, which is where the route's own except would have+ fired before the response was opened early."""++ async def slow_failure(self, **kwargs):+ await asyncio.sleep(0.25)+ raise HTTPException(status_code=503, detail="upstream exploded")++ proxy_logging_obj = MagicMock(spec=ProxyLogging)+ # None is what a hook that only audits returns; a bare AsyncMock would hand+ # back a MagicMock, which the code correctly reads as a sanitized replacement.+ proxy_logging_obj.post_call_failure_hook = AsyncMock(return_value=None)+ user_api_key_dict = MagicMock(spec=UserAPIKeyAuth)+ processor = ProxyBaseLLMRequestProcessing(data={"model": "gpt-4o", "stream": True})++ with patch.object(litellm, "sse_keepalive_ping_interval_seconds", 0.05):+ with patch.object(ProxyBaseLLMRequestProcessing, "_process_llm_request", slow_failure):+ response = await processor.base_process_llm_request(+ request=MagicMock(spec=Request),+ fastapi_response=Response(),+ user_api_key_dict=user_api_key_dict,+ route_type="acompletion",+ proxy_logging_obj=proxy_logging_obj,+ general_settings={},+ proxy_config=MagicMock(spec=ProxyConfig),+ )+ collected = await _drain(response)++ proxy_logging_obj.post_call_failure_hook.assert_awaited_once()+ call = proxy_logging_obj.post_call_failure_hook.await_args.kwargs+ assert call["user_api_key_dict"] is user_api_key_dict+ assert call["request_data"] is processor.data+ assert getattr(call["original_exception"], "detail", None) == "upstream exploded"++ assert collected[0] == TTFT_PING+ assert collected[-1] == b"data: [DONE]\n\n"+++ "deployment_keepalive, expect_ping",+ [(0, False), (None, True)],+ ids=["operator-hard-disabled-this-deployment", "deployment-says-nothing"],+)+async def test_base_process_llm_request_honours_a_deployment_hard_disable(+ deployment_keepalive, expect_ping+):+ """`keepalive_seconds: 0` is documented as a disable a request cannot lift. The+ funnel has to hand its router to the gate for that to hold before the upstream+ has answered, since no deployment has served the request yet."""+ params = {"model": "openai/gpt-4o"}+ if deployment_keepalive is not None:+ params["keepalive_seconds"] = deployment_keepalive++ llm_router = MagicMock()+ llm_router.get_model_list = MagicMock(return_value=[{"model_name": "m", "litellm_params": params}])++ async def slow_inner(self, **kwargs):+ await asyncio.sleep(0.25)+ return _sse_response(['data: {"late": true}\n\n'])++ processor = ProxyBaseLLMRequestProcessing(data={"model": "m", "stream": True})++ with patch.object(litellm, "sse_keepalive_ping_interval_seconds", 0.05):+ with patch.object(ProxyBaseLLMRequestProcessing, "_process_llm_request", slow_inner):+ response = await processor.base_process_llm_request(+ request=MagicMock(spec=Request),+ fastapi_response=Response(),+ user_api_key_dict=MagicMock(spec=UserAPIKeyAuth),+ route_type="acompletion",+ proxy_logging_obj=MagicMock(spec=ProxyLogging),+ general_settings={},+ proxy_config=MagicMock(spec=ProxyConfig),+ llm_router=llm_router,+ )++ collected = await _drain(response)+ assert (collected[0] == TTFT_PING) is expect_ping+++async def test_a_hook_returning_a_replacement_decides_what_the_client_sees():+ """post_call_failure_hook exists partly to sanitize client-facing errors.+ Serializing the original would leak provider detail a deployment configured away."""++ async def slow_failure():+ await asyncio.sleep(0.2)+ raise HTTPException(status_code=500, detail="upstream said host=10.0.0.7 key=sk-internal")++ async def sanitize(exc):+ return HTTPException(status_code=502, detail="upstream unavailable")++ response = await open_sse_before_first_byte(+ slow_failure(), ping_interval_seconds=0.05, on_late_failure=sanitize+ )+ collected = await _drain(response)++ error_frame = json.loads(collected[-2].decode().removeprefix("data: ").strip())+ assert error_frame["error"]["message"] == "upstream unavailable"+ assert "sk-internal" not in collected[-2].decode()+++async def test_a_hook_raising_a_replacement_also_decides_what_the_client_sees():+ """The hook's contract is return *or* raise, and raising is the path a+ suppress(Exception) around the call would silently discard."""++ async def slow_failure():+ await asyncio.sleep(0.2)+ raise HTTPException(status_code=500, detail="upstream said host=10.0.0.7 key=sk-internal")++ async def sanitize_by_raising(exc):+ raise HTTPException(status_code=403, detail="blocked by policy")++ response = await open_sse_before_first_byte(+ slow_failure(), ping_interval_seconds=0.05, on_late_failure=sanitize_by_raising+ )+ collected = await _drain(response)++ error_frame = json.loads(collected[-2].decode().removeprefix("data: ").strip())+ assert error_frame["error"]["message"] == "blocked by policy"+ assert "sk-internal" not in collected[-2].decode()+++async def test_a_hook_that_returns_nothing_leaves_the_real_error_intact():+ async def slow_failure():+ await asyncio.sleep(0.2)+ raise HTTPException(status_code=429, detail="rate limited")++ async def audit_only(exc):+ return None++ response = await open_sse_before_first_byte(+ slow_failure(), ping_interval_seconds=0.05, on_late_failure=audit_only+ )+ collected = await _drain(response)++ error_frame = json.loads(collected[-2].decode().removeprefix("data: ").strip())+ assert error_frame["error"]["message"] == "rate limited"+ assert error_frame["error"]["code"] == "429"+++async def test_a_broken_hook_does_not_replace_the_real_error_with_its_own_bug():+ async def slow_failure():+ await asyncio.sleep(0.2)+ raise HTTPException(status_code=429, detail="rate limited")++ async def broken_hook(exc):+ raise RuntimeError("the audit backend is down")++ response = await open_sse_before_first_byte(+ slow_failure(), ping_interval_seconds=0.05, on_late_failure=broken_hook+ )+ collected = await _drain(response)++ error_frame = json.loads(collected[-2].decode().removeprefix("data: ").strip())+ assert error_frame["error"]["message"] == "rate limited"+ assert "audit backend" not in collected[-2].decode()