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): resolve the global SSE keepalive interval through the per-deployment engine
mateo-berrie53f044d2089
diff --git a/litellm/proxy/common_request_processing.py b/litellm/proxy/common_request_processing.pyindex 308d0340e22..a9773c22d96 100644--- a/litellm/proxy/common_request_processing.py+++ b/litellm/proxy/common_request_processing.py@@ -47,11 +47,7 @@ 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 (- ANTHROPIC_PING_SSE_CHUNK,- SSE_COMMENT_PING_CHUNK,- wrap_sse_stream_with_keepalive_pings,-)+from litellm.proxy.common_utils.sse_keepalive import wrap_sse_stream_with_keepalive_pingsfrom 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@@ -2030,7 +2026,6 @@ class ProxyBaseLLMRequestProcessing:generator=wrap_sse_stream_with_keepalive_pings(stream=selected_data_generator,ping_interval_seconds=litellm.anthropic_sse_ping_interval_seconds,- ping_chunk=ANTHROPIC_PING_SSE_CHUNK,),media_type="text/event-stream",headers=custom_headers,@@ -2062,11 +2057,7 @@ class ProxyBaseLLMRequestProcessing:))return await create_response(- generator=wrap_sse_stream_with_keepalive_pings(- stream=selected_data_generator,- ping_interval_seconds=litellm.sse_keepalive_ping_interval_seconds,- ping_chunk=SSE_COMMENT_PING_CHUNK,- ),+ generator=selected_data_generator,media_type="text/event-stream",headers=custom_headers,request=request,diff --git a/litellm/proxy/common_utils/sse_keepalive.py b/litellm/proxy/common_utils/sse_keepalive.pyindex d3ff4b0ca30..6700700ff7c 100644--- a/litellm/proxy/common_utils/sse_keepalive.py+++ b/litellm/proxy/common_utils/sse_keepalive.py@@ -7,7 +7,6 @@ from typing import Finalimport anyioANTHROPIC_PING_SSE_CHUNK: Final = 'event: ping\ndata: {"type": "ping"}\n\n'-SSE_COMMENT_PING_CHUNK: Final = ": ping\n\n"def _coerce_interval(ping_interval_seconds: float | str | None) -> float | None:@@ -25,18 +24,16 @@ def _coerce_interval(ping_interval_seconds: float | str | None) -> float | None:def wrap_sse_stream_with_keepalive_pings(stream: AsyncGenerator[str, None],ping_interval_seconds: float | str | None,- ping_chunk: str,) -> AsyncGenerator[str, None]:interval: Final = _coerce_interval(ping_interval_seconds)if interval is None:return stream- return _keepalive_ping_stream(stream=stream, ping_interval_seconds=interval, ping_chunk=ping_chunk)+ return _keepalive_ping_stream(stream=stream, ping_interval_seconds=interval)async def _keepalive_ping_stream(stream: AsyncGenerator[str, None],ping_interval_seconds: float,- ping_chunk: str,) -> AsyncGenerator[str, None]:pending = asyncio.ensure_future(stream.__anext__()@@ -45,7 +42,7 @@ async def _keepalive_ping_stream(while True:await asyncio.wait({pending}, timeout=ping_interval_seconds)if not pending.done():- yield ping_chunk+ yield ANTHROPIC_PING_SSE_CHUNKcontinuetry:yield pending.result()diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex 0f0079c542f..2fc69ef5f6e 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -7865,8 +7865,17 @@ def _resolve_keepalive_seconds(request_data: Mapping[str, Any], response: object# keepalive_seconds is operator-only unless the deployment explicitly opts in:# a client can't unilaterally enable heartbeats (and the LB-idle-timeout# evasion that comes with them) for a deployment that never configured this.+ # When neither the request nor the deployment sets a value, the operator's+ # global `litellm_settings.sse_keepalive_ping_interval_seconds` applies; a+ # deployment's explicit `keepalive_seconds: 0` above still hard-disables it.client_supplied: Final = request_data.get("keepalive_seconds") if allow_client_override else None- raw: Final = client_supplied if client_supplied is not None else deployment_raw+ raw: Final = (+ client_supplied+ if client_supplied is not None+ else deployment_raw+ if deployment_raw is not None+ else litellm.sse_keepalive_ping_interval_seconds+ )try:value: Final = float(raw) if isinstance(raw, (int, float, str)) else 0.0except ValueError:@@ -7977,18 +7986,19 @@ async def async_data_generator(# A stream can start on a deployment with keepalive off and fall back# mid-stream to one that enables it: only skip wrapping altogether when- # there's no router to ever fall back through in the first place (in- # which case _resolve_keepalive_seconds can never return non-zero for- # any chunk of this stream), not merely because the first chunk's- # deployment happens to start with it off.+ # there's no router to ever fall back through AND the resolved interval+ # (including the global sse_keepalive_ping_interval_seconds fallback)+ # starts disabled, not merely because the first chunk's deployment+ # happens to start with it off.resolve_keepalive_seconds: Final = _make_keepalive_resolver(request_data)+ initial_keepalive_seconds: Final = resolve_keepalive_seconds(response)stream_source: Final = (_iter_with_keepalive(stream_iterator.__aiter__(),resolve_keepalive_seconds,- resolve_keepalive_seconds(response),+ initial_keepalive_seconds,)- if llm_router is not None+ if llm_router is not None or initial_keepalive_seconds > 0else stream_iterator)diff --git a/tests/test_litellm/proxy/common_utils/test_sse_keepalive.py b/tests/test_litellm/proxy/common_utils/test_sse_keepalive.pyindex e343e46e187..9cca9bbfe12 100644--- a/tests/test_litellm/proxy/common_utils/test_sse_keepalive.py+++ b/tests/test_litellm/proxy/common_utils/test_sse_keepalive.py@@ -22,11 +22,7 @@ async def test_pings_fill_mid_stream_silence_and_preserve_chunk_order():await asyncio.sleep(0.3)yield TEXT_DELTA_CHUNK- wrapped: Final = wrap_sse_stream_with_keepalive_pings(- stream=gappy_stream(),- ping_interval_seconds=0.05,- ping_chunk=ANTHROPIC_PING_SSE_CHUNK,- )+ wrapped: Final = wrap_sse_stream_with_keepalive_pings(stream=gappy_stream(), ping_interval_seconds=0.05)collected: Final = [chunk async for chunk in wrapped]assert collected[0] == MESSAGE_START_CHUNK@@ -44,11 +40,7 @@ async def test_ping_emitted_while_waiting_for_first_chunk():await asyncio.sleep(0.2)yield MESSAGE_START_CHUNK- wrapped: Final = wrap_sse_stream_with_keepalive_pings(- stream=slow_start_stream(),- ping_interval_seconds=0.05,- ping_chunk=ANTHROPIC_PING_SSE_CHUNK,- )+ wrapped: Final = wrap_sse_stream_with_keepalive_pings(stream=slow_start_stream(), ping_interval_seconds=0.05)collected: Final = [chunk async for chunk in wrapped]assert collected[0] == ANTHROPIC_PING_SSE_CHUNK@@ -62,11 +54,7 @@ async def test_no_pings_when_chunks_arrive_faster_than_interval():yield TEXT_DELTA_CHUNKyield TEXT_DELTA_CHUNK- wrapped: Final = wrap_sse_stream_with_keepalive_pings(- stream=fast_stream(),- ping_interval_seconds=1.0,- ping_chunk=ANTHROPIC_PING_SSE_CHUNK,- )+ wrapped: Final = wrap_sse_stream_with_keepalive_pings(stream=fast_stream(), ping_interval_seconds=1.0)collected: Final = [chunk async for chunk in wrapped]assert collected == [MESSAGE_START_CHUNK, TEXT_DELTA_CHUNK, TEXT_DELTA_CHUNK]@@ -78,11 +66,7 @@ async def test_upstream_exception_propagates():yield MESSAGE_START_CHUNKraise ValueError("upstream broke")- wrapped: Final = wrap_sse_stream_with_keepalive_pings(- stream=failing_stream(),- ping_interval_seconds=5.0,- ping_chunk=ANTHROPIC_PING_SSE_CHUNK,- )+ wrapped: Final = wrap_sse_stream_with_keepalive_pings(stream=failing_stream(), ping_interval_seconds=5.0)assert await wrapped.__anext__() == MESSAGE_START_CHUNKwith pytest.raises(ValueError, match="upstream broke"):@@ -101,11 +85,7 @@ async def test_aclose_mid_silence_cancels_upstream_and_runs_its_cleanup():finally:upstream_cleaned_up.set()- wrapped: Final = wrap_sse_stream_with_keepalive_pings(- stream=hung_stream(),- ping_interval_seconds=0.05,- ping_chunk=ANTHROPIC_PING_SSE_CHUNK,- )+ wrapped: Final = wrap_sse_stream_with_keepalive_pings(stream=hung_stream(), ping_interval_seconds=0.05)assert await wrapped.__anext__() == MESSAGE_START_CHUNKassert await wrapped.__anext__() == ANTHROPIC_PING_SSE_CHUNK@@ -120,11 +100,7 @@ async def test_non_positive_interval_returns_stream_unwrapped():yield MESSAGE_START_CHUNKstream: Final = any_stream()- assert wrap_sse_stream_with_keepalive_pings(- stream=stream,- ping_interval_seconds=0,- ping_chunk=ANTHROPIC_PING_SSE_CHUNK,- ) is stream+ assert wrap_sse_stream_with_keepalive_pings(stream=stream, ping_interval_seconds=0) is streamawait stream.aclose()@@ -147,11 +123,7 @@ async def test_invalid_config_interval_returns_stream_unwrapped(bad_interval: flyield MESSAGE_START_CHUNKstream: Final = any_stream()- assert wrap_sse_stream_with_keepalive_pings(- stream=stream,- ping_interval_seconds=bad_interval,- ping_chunk=ANTHROPIC_PING_SSE_CHUNK,- ) is stream+ assert wrap_sse_stream_with_keepalive_pings(stream=stream, ping_interval_seconds=bad_interval) is streamawait stream.aclose()@@ -161,11 +133,7 @@ async def test_numeric_string_interval_from_yaml_config_enables_pings():await asyncio.sleep(0.2)yield MESSAGE_START_CHUNK- wrapped: Final = wrap_sse_stream_with_keepalive_pings(- stream=slow_start_stream(),- ping_interval_seconds="0.05",- ping_chunk=ANTHROPIC_PING_SSE_CHUNK,- )+ wrapped: Final = wrap_sse_stream_with_keepalive_pings(stream=slow_start_stream(), ping_interval_seconds="0.05")collected: Final = [chunk async for chunk in wrapped]assert collected[0] == ANTHROPIC_PING_SSE_CHUNK@@ -179,11 +147,7 @@ async def test_create_response_streams_ping_first_for_slow_upstream():yield MESSAGE_START_CHUNKresponse: Final = await create_response(- generator=wrap_sse_stream_with_keepalive_pings(- stream=slow_start_stream(),- ping_interval_seconds=0.05,- ping_chunk=ANTHROPIC_PING_SSE_CHUNK,- ),+ generator=wrap_sse_stream_with_keepalive_pings(stream=slow_start_stream(), ping_interval_seconds=0.05),media_type="text/event-stream",headers={},)diff --git a/tests/test_litellm/proxy/proxy_server/test_streaming_helpers.py b/tests/test_litellm/proxy/proxy_server/test_streaming_helpers.pyindex 15758c595c0..585e4d05124 100644--- a/tests/test_litellm/proxy/proxy_server/test_streaming_helpers.py+++ b/tests/test_litellm/proxy/proxy_server/test_streaming_helpers.py@@ -1229,6 +1229,78 @@ def test_resolve_keepalive_seconds_deployment_disable_cannot_be_overridden_by_reassert result == 0.0+def test_resolve_keepalive_seconds_global_default_applies_when_unconfigured(monkeypatch):+ """litellm_settings.sse_keepalive_ping_interval_seconds is the operator's+ global default: it applies when neither the serving deployment nor the+ request supplies keepalive_seconds, including proxies with no router at+ all."""+ import litellm++ monkeypatch.setattr(ps, "llm_router", None)+ monkeypatch.setattr(litellm, "sse_keepalive_ping_interval_seconds", 15.0)++ result = _resolve_keepalive_seconds({}, response=None)+ assert result == 15.0+++def test_resolve_keepalive_seconds_global_default_is_clamped(monkeypatch):+ import litellm++ monkeypatch.setattr(ps, "llm_router", None)+ monkeypatch.setattr(litellm, "sse_keepalive_ping_interval_seconds", 900.0)++ result = _resolve_keepalive_seconds({}, response=None)+ assert result == _KEEPALIVE_MAX_SECONDS+++def test_resolve_keepalive_seconds_deployment_zero_beats_global_default(monkeypatch):+ """A deployment's explicit keepalive_seconds: 0 is a hard operator disable+ that must also win over the global default interval, or the global setting+ would silently re-enable heartbeats (and the LB-idle-timeout evasion that+ comes with them) for a deployment the operator opted out of."""+ from unittest.mock import MagicMock++ import litellm++ deployment = MagicMock()+ deployment.litellm_params.keepalive_seconds = 0+ deployment.litellm_params.allow_client_keepalive_override = False++ router = MagicMock()+ router.get_deployment.return_value = deployment++ monkeypatch.setattr(ps, "llm_router", router)+ monkeypatch.setattr(litellm, "sse_keepalive_ping_interval_seconds", 15.0)++ response = MagicMock()+ response._hidden_params = {"model_id": "deploy-disabled"}++ result = _resolve_keepalive_seconds({"model": "my-model"}, response=response)+ assert result == 0.0+++def test_resolve_keepalive_seconds_deployment_value_beats_global_default(monkeypatch):+ from unittest.mock import MagicMock++ import litellm++ deployment = MagicMock()+ deployment.litellm_params.keepalive_seconds = 30.0+ deployment.litellm_params.allow_client_keepalive_override = False++ router = MagicMock()+ router.get_deployment.return_value = deployment++ monkeypatch.setattr(ps, "llm_router", router)+ monkeypatch.setattr(litellm, "sse_keepalive_ping_interval_seconds", 15.0)++ response = MagicMock()+ response._hidden_params = {"model_id": "deploy-tuned"}++ result = _resolve_keepalive_seconds({"model": "my-model"}, response=response)+ assert result == 30.0++def test_keepalive_from_deployment_config_reads_by_model_id(monkeypatch):from unittest.mock import MagicMock@@ -1536,6 +1608,39 @@ async def test_async_data_generator_emits_ping_heartbeat(monkeypatch):assert out[-1] == "data: [DONE]\n\n"+async def test_async_data_generator_emits_ping_heartbeat_from_global_default_without_router(monkeypatch):+ """The global sse_keepalive_ping_interval_seconds must produce ': ping'+ frames even on a proxy with no router, where the wrap was previously+ skipped entirely because no deployment could ever resolve a non-zero+ interval."""+ import asyncio++ import litellm++ _patch_logging_flags(monkeypatch)+ monkeypatch.setattr(ps, "_KEEPALIVE_MIN_SECONDS", 0.05)+ monkeypatch.setattr(ps, "llm_router", None)+ monkeypatch.setattr(litellm, "sse_keepalive_ping_interval_seconds", 0.05)++ async def _slow_response():+ yield _simple_chunk(content="hello")+ await asyncio.sleep(0.4)+ yield _simple_chunk(content="world")++ out = []+ async for line in async_data_generator(+ response=_slow_response(),+ user_api_key_dict=_user_auth(),+ request_data={"model": "gpt-4"},+ ):+ out.append(line)++ pings = [item for item in out if item == ": ping\n\n"]+ assert len(pings) >= 2, f"expected >= 2 ping frames; got {len(pings)}"+ assert out[-1] == "data: [DONE]\n\n"++@pytest.mark.asyncioasync def test_async_data_generator_no_keepalive_no_pings(monkeypatch):"""Without keepalive_seconds, no ': ping' frames are emitted."""diff --git a/tests/test_litellm/proxy/test_common_request_processing.py b/tests/test_litellm/proxy/test_common_request_processing.pyindex ebdcab379a3..a3c0f0089fe 100644--- a/tests/test_litellm/proxy/test_common_request_processing.py+++ b/tests/test_litellm/proxy/test_common_request_processing.py@@ -35,12 +35,10 @@ from litellm.proxy.common_request_processing import (_UpstreamClosingStreamingResponse,create_response,)-from litellm.proxy.common_utils.sse_keepalive import SSE_COMMENT_PING_CHUNKfrom litellm.proxy.dd_span_tagger import DDSpanTaggerfrom litellm.proxy._types import ProxyExceptionfrom litellm.proxy._types import UserAPIKeyAuth as ProxyUserAPIKeyAuthfrom litellm.proxy.utils import ProxyLogging-from litellm.types.utils import ModelResponseStreamclass TestProxyBaseLLMRequestProcessing:@@ -5751,85 +5749,6 @@ class TestPerRequestModelGroupAlias:assert merged_for == ["group-b"]-class TestOpenAISseKeepalivePings:- """- Regression for a streaming request dying at an ingress idle read timeout- (e.g. nginx `proxy-read-timeout`) when time-to-first-token exceeds it: the- OpenAI-shaped SSE routes must emit a keepalive comment while the upstream is- silent, once `litellm.sse_keepalive_ping_interval_seconds` is configured.- """-- async def _run(self, monkeypatch, first_chunk_delay: float):- import litellm.proxy.common_request_processing as crp- from litellm.proxy._types import UserAPIKeyAuth as RealUserAPIKeyAuth-- logging_obj = MagicMock()- logging_obj.litellm_call_id = "call-keepalive"- logging_obj.cost_breakdown = None- processing_obj = ProxyBaseLLMRequestProcessing(- data={"model": "gpt-4o", "stream": True, "litellm_logging_obj": logging_obj}- )-- async def upstream():- await asyncio.sleep(first_chunk_delay)- yield ModelResponseStream()-- async def fake_route_request(**kwargs):- async def _llm_call():- return upstream()-- return _llm_call()-- monkeypatch.setattr(crp, "route_request", fake_route_request)-- def select_data_generator(response, user_api_key_dict, request_data, request):- async def _gen():- async for _ in response:- yield 'data: {"choices": []}\n\n'-- return _gen()-- proxy_logging_obj = MagicMock(spec=ProxyLogging)- proxy_logging_obj.during_call_hook = AsyncMock(return_value=None)- proxy_logging_obj.update_request_status = AsyncMock(return_value=None)- proxy_logging_obj.post_call_response_headers_hook = AsyncMock(return_value=None)- proxy_logging_obj.post_call_success_hook = AsyncMock()-- return await processing_obj.base_process_llm_request(- request=MagicMock(spec=Request, headers={}),- fastapi_response=Response(),- user_api_key_dict=RealUserAPIKeyAuth(api_key="sk-test"),- route_type="acompletion",- proxy_logging_obj=proxy_logging_obj,- general_settings={},- proxy_config=MagicMock(spec=ProxyConfig),- select_data_generator=select_data_generator,- llm_router=None,- skip_pre_call_logic=True,- )-- @pytest.mark.asyncio- async def test_ping_precedes_slow_first_chunk_on_chat_completions(self, monkeypatch):- monkeypatch.setattr(litellm, "sse_keepalive_ping_interval_seconds", 0.05)-- result = await self._run(monkeypatch, first_chunk_delay=0.3)-- assert isinstance(result, StreamingResponse)- streamed = [chunk async for chunk in result.body_iterator]- assert streamed[0] == SSE_COMMENT_PING_CHUNK- assert streamed[-1] == 'data: {"choices": []}\n\n'-- @pytest.mark.asyncio- async def test_no_pings_emitted_when_interval_unset(self, monkeypatch):- monkeypatch.setattr(litellm, "sse_keepalive_ping_interval_seconds", None)-- result = await self._run(monkeypatch, first_chunk_delay=0.3)-- assert isinstance(result, StreamingResponse)- streamed = [chunk async for chunk in result.body_iterator]- assert streamed == ['data: {"choices": []}\n\n']--class TestInjectCostIntoUsageDict:@staticmethoddef _expected_cost(model, prompt_tokens, completion_tokens):