Skip to content

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

feat(proxy): add per-deployment keepalive_seconds SSE heartbeat to prevent load-balancer timeout on long streams (#34423)

Deepanshu Lulla363d56f91788
diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.py
index c8ca9dcf57e..dc4f17c7b31 100644
--- a/litellm/proxy/_types.py
+++ b/litellm/proxy/_types.py
@@ -4031,6 +4031,7 @@ class LitellmDataForBackendLLMCall(TypedDict, total=False):
# deliberately tiny value isn't treated as a deployment health signal (see
# cooldown_handlers._trigger_cooldown_for_failed_deployment).
client_side_timeout: bool
+ keepalive_seconds: float | None
class LitellmMetadataFromRequestHeaders(TypedDict, total=False):
diff --git a/litellm/proxy/litellm_pre_call_utils.py b/litellm/proxy/litellm_pre_call_utils.py
index 66bfc8b81d8..10142a894a1 100644
--- a/litellm/proxy/litellm_pre_call_utils.py
+++ b/litellm/proxy/litellm_pre_call_utils.py
@@ -882,6 +882,19 @@ class LiteLLMProxyRequestSetup:
return float(stream_timeout_header)
return None
+ @staticmethod
+ def _get_keepalive_seconds_from_request(headers: Mapping[str, str]) -> float | None:
+ """
+ Get `keepalive_seconds` from the request headers, for clients (e.g. the
+ Vercel AI SDK) that can set custom headers more easily than extra body
+ fields. Subject to the same deployment-level allow_client_keepalive_override
+ gate as the request body field: see _resolve_keepalive_seconds.
+ """
+ keepalive_seconds_header: Final = headers.get("x-litellm-keepalive-seconds", None)
+ if keepalive_seconds_header is not None:
+ return float(keepalive_seconds_header)
+ return None
+
@staticmethod
def _get_num_retries_from_request(headers: dict) -> int | None:
"""
@@ -1114,6 +1127,10 @@ class LiteLLMProxyRequestSetup:
if num_retries is not None:
data["num_retries"] = num_retries
+ keepalive_seconds: Final = LiteLLMProxyRequestSetup._get_keepalive_seconds_from_request(headers)
+ if keepalive_seconds is not None:
+ data["keepalive_seconds"] = keepalive_seconds
+
return data
@staticmethod
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py
index bc980934f9f..baa1579d2c0 100644
--- a/litellm/proxy/proxy_server.py
+++ b/litellm/proxy/proxy_server.py
@@ -15,7 +15,7 @@ import threading
import time
import traceback
import warnings
-from collections.abc import AsyncGenerator, Callable, Mapping
+from collections.abc import AsyncGenerator, AsyncIterator, Callable, Mapping
from datetime import datetime, timedelta, timezone
from types import MappingProxyType, UnionType
from typing import (
@@ -23,6 +23,7 @@ from typing import (
Any,
Final,
Literal,
+ NamedTuple,
Optional,
TypedDict,
Union,
@@ -7643,6 +7644,200 @@ def _pop_complete_sse_frame(buffer: str) -> tuple[str | None, str]:
return buffer[:frame_end], buffer[frame_end:]
+_STREAM_KEEPALIVE: Final = object()
+
+_KEEPALIVE_MIN_SECONDS: Final = 1.0
+_KEEPALIVE_MAX_SECONDS: Final = 300.0
+_EMPTY_MAPPING: Final[Mapping[str, Any]] = MappingProxyType({})
+
+
+async def _iter_with_keepalive(
+ aiter: AsyncIterator[Any],
+ resolve_keepalive_seconds: Callable[[object], float],
+ keepalive_seconds: float,
+) -> AsyncGenerator[Any, None]:
+ """Wrap `aiter` with idle-gap heartbeats, re-resolving the interval after each
+ real chunk via `resolve_keepalive_seconds`. A mid-stream router fallback can
+ swap in a deployment with a different keepalive policy, including one that
+ newly enables or newly disables heartbeats, partway through the same stream;
+ re-resolving against each chunk's own identity (rather than trusting the
+ interval picked before iteration started, or picked the last time it went
+ inactive) keeps the heartbeat behavior in sync with whichever deployment
+ actually produced it, in both directions. While the interval is <= 0, no
+ task is created and no timeout is awaited: a chunk is forwarded the moment
+ it arrives, at the same cost as a bare `async for`."""
+ pending: asyncio.Task[Any] | None = None # rebind-ok: rebound each loop iteration
+ current_keepalive_seconds = keepalive_seconds # rebind-ok: re-resolved after each chunk
+ try:
+ while True:
+ if current_keepalive_seconds <= 0:
+ try:
+ item = await aiter.__anext__()
+ except StopAsyncIteration:
+ break
+ yield item
+ current_keepalive_seconds = resolve_keepalive_seconds(item)
+ continue
+
+ if pending is None:
+ pending = asyncio.create_task(aiter.__anext__())
+ done, _ = await asyncio.wait((pending,), timeout=current_keepalive_seconds)
+ if not done:
+ yield _STREAM_KEEPALIVE
+ continue
+ try:
+ item = pending.result()
+ except StopAsyncIteration:
+ break
+ finally:
+ pending = None
+ yield item
+ current_keepalive_seconds = resolve_keepalive_seconds(item)
+ finally:
+ if pending is not None and not pending.done():
+ pending.cancel()
+ try:
+ await pending
+ except asyncio.CancelledError:
+ pass
+
+
+class _DeploymentKeepaliveConfig(NamedTuple):
+ keepalive_seconds: Any
+ allow_client_override: bool
+
+
+def _keepalive_from_deployment_config(
+ request_data: Mapping[str, Any], response: object
+) -> _DeploymentKeepaliveConfig | None:
+ if llm_router is None:
+ return None
+
+ hidden: Final = get_hidden_params_dict(response)
+ model_id: Final = hidden.get("model_id")
+ if isinstance(model_id, str) and model_id:
+ deployment: Final = llm_router.get_deployment(model_id=model_id)
+ # A populated model_id names the specific deployment that served this
+ # stream. If it no longer resolves (e.g. removed by a config reload
+ # mid-stream), that's a stale identity, not an absent one: don't fall
+ # through to guessing via model_name below, since a currently-live
+ # sibling deployment's config was never what actually served this
+ # stream.
+ if deployment is None:
+ return None
+ return _DeploymentKeepaliveConfig(
+ keepalive_seconds=getattr(deployment.litellm_params, "keepalive_seconds", None),
+ allow_client_override=bool(getattr(deployment.litellm_params, "allow_client_keepalive_override", False)),
+ )
+
+ # No model_id at all to pin down which deployment actually served this
+ # stream: only trust the fallback when every deployment under this
+ # model_name agrees on both keepalive_seconds and
+ # allow_client_keepalive_override (including deployments that leave either
+ # field unset), so a stream never inherits a sibling deployment's policy.
+ configs: Final = frozenset(
+ (
+ (deployment_dict.get("litellm_params") or _EMPTY_MAPPING).get("keepalive_seconds"),
+ bool(
+ (deployment_dict.get("litellm_params") or _EMPTY_MAPPING).get("allow_client_keepalive_override", False)
+ ),
+ )
+ for deployment_dict in llm_router.get_model_list(model_name=request_data.get("model")) or ()
+ )
+ if len(configs) == 1:
+ keepalive_seconds, allow_client_override = next(iter(configs))
+ return _DeploymentKeepaliveConfig(
+ keepalive_seconds=keepalive_seconds, allow_client_override=allow_client_override
+ )
+ return None
+
+
+def _is_explicit_keepalive_disable(raw: object) -> bool:
+ if not isinstance(raw, (int, float, str)):
+ return False
+ try:
+ return float(raw) <= 0
+ except ValueError:
+ return False
+
+
+def _resolve_keepalive_seconds(request_data: Mapping[str, Any], response: object = None) -> float:
+ deployment_config: Final = _keepalive_from_deployment_config(request_data, response)
+ deployment_raw: Final = deployment_config.keepalive_seconds if deployment_config is not None else None
+ allow_client_override: Final = deployment_config.allow_client_override if deployment_config is not None else False
+
+ # An operator setting keepalive_seconds: 0 on a deployment is an explicit hard
+ # disable: an authenticated client must not be able to re-enable heartbeats
+ # (and the idle-timeout evasion that comes with them) for a deployment the
+ # operator opted out of, regardless of what the request body asks for.
+ if _is_explicit_keepalive_disable(deployment_raw):
+ return 0.0
+
+ # 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.
+ 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
+ try:
+ value: Final = float(raw) if isinstance(raw, (int, float, str)) else 0.0
+ except ValueError:
+ return 0.0
+ if value <= 0:
+ return 0.0
+ clamped: Final = max(_KEEPALIVE_MIN_SECONDS, min(value, _KEEPALIVE_MAX_SECONDS))
+ if clamped != value:
+ verbose_proxy_logger.info(
+ "keepalive_seconds=%s clamped to %s [min=%s, max=%s]",
+ value,
+ clamped,
+ _KEEPALIVE_MIN_SECONDS,
+ _KEEPALIVE_MAX_SECONDS,
+ )
+ return clamped
+
+
+_KEEPALIVE_CACHE_TTL_SECONDS: Final = 5.0
+
+
+def _make_keepalive_resolver(request_data: Mapping[str, Any]) -> Callable[[object], float]:
+ """Wrap `_resolve_keepalive_seconds` with a memo keyed on the serving
+ deployment's model_id. The steady-state case (no mid-stream fallback, the
+ overwhelming majority of streams) sees the same model_id on every chunk, so
+ this turns the per-chunk cost from a full `llm_router.get_deployment()`
+ Pydantic rebuild into a cheap hidden-params read once per
+ `_KEEPALIVE_CACHE_TTL_SECONDS` for that model_id. The cache expires on its
+ own rather than living for the life of the stream, so an operator's live
+ config change (disabling keepalive, revoking client override, or removing
+ the deployment) is observed within a bounded window instead of being able
+ to be evaded by an already-in-flight stream indefinitely. A missing/empty
+ model_id can't be trusted as a cache key (see
+ `_keepalive_from_deployment_config`'s model_name fallback, which reflects
+ current router state rather than one deployment's fixed identity), so
+ those chunks always resolve fresh, matching prior behavior exactly.
+ """
+ last_model_id: str | None = None # rebind-ok: memoized identity of the last-resolved chunk
+ last_value: float = 0.0 # rebind-ok: cached resolution for last_model_id
+ last_resolved_at: float = float("-inf") # rebind-ok: monotonic timestamp of the last real resolution
+
+ def _resolve(item: object) -> float:
+ nonlocal last_model_id, last_value, last_resolved_at
+ model_id = get_hidden_params_dict(item).get("model_id")
+ now: Final = time.monotonic()
+ if (
+ isinstance(model_id, str)
+ and model_id
+ and model_id == last_model_id
+ and now - last_resolved_at < _KEEPALIVE_CACHE_TTL_SECONDS
+ ):
+ return last_value
+ value: Final = _resolve_keepalive_seconds(request_data, item)
+ if isinstance(model_id, str) and model_id:
+ last_model_id, last_value, last_resolved_at = model_id, value, now
+ return value
+
+ return _resolve
+
+
async def async_data_generator(
response,
user_api_key_dict: UserAPIKeyAuth,
@@ -7691,7 +7886,28 @@ async def async_data_generator(
else:
stream_iterator = response
- async for chunk in stream_iterator:
+ # 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.
+ resolve_keepalive_seconds: Final = _make_keepalive_resolver(request_data)
+ stream_source: Final = (
+ _iter_with_keepalive(
+ stream_iterator.__aiter__(),
+ resolve_keepalive_seconds,
+ resolve_keepalive_seconds(response),
+ )
+ if llm_router is not None
+ else stream_iterator
+ )
+
+ async for item in stream_source:
+ if item is _STREAM_KEEPALIVE:
+ yield ": ping\n\n"
+ continue
+ chunk = cast(Any, item) # cast-ok: sentinel already handled above, item is a real chunk here
if needs_per_chunk_hook:
### CALL HOOKS ### - modify outgoing data
chunk, _str_so_far = await _apply_streaming_chunk_hooks(
diff --git a/litellm/types/router.py b/litellm/types/router.py
index b03796fb14f..4f8c133c20b 100644
--- a/litellm/types/router.py
+++ b/litellm/types/router.py
@@ -281,6 +281,12 @@ class GenericLiteLLMParams(CredentialLiteLLMParams, CustomPricingLiteLLMParams):
# Deployment budgets
max_budget: float | None = None
budget_duration: str | None = None
+ keepalive_seconds: float | None = None
+ # keepalive_seconds is operator-only by default: a client's request-level
+ # value is ignored unless the deployment opts in here. Prevents a client
+ # from unilaterally enabling heartbeats (and the LB-idle-timeout evasion
+ # that comes with them) for a deployment that never configured them.
+ allow_client_keepalive_override: bool | None = False
use_in_pass_through: bool | None = False
use_litellm_proxy: bool | None = False
use_chat_completions_api: bool | None = None
@@ -457,6 +463,8 @@ class LiteLLMParamsTypedDict(TypedDict, total=False):
# deployment budgets
max_budget: float | None
budget_duration: str | None
+ keepalive_seconds: float | None
+ allow_client_keepalive_override: bool | None
# per-deployment cooldown override
cooldown_time: float | None
diff --git a/litellm/types/utils.py b/litellm/types/utils.py
index abf9382845b..8c7664257df 100644
--- a/litellm/types/utils.py
+++ b/litellm/types/utils.py
@@ -3399,6 +3399,8 @@ all_litellm_params = (
+ [
"metadata",
"litellm_metadata",
+ "keepalive_seconds",
+ "allow_client_keepalive_override",
"litellm_trace_id",
"litellm_request_debug",
"guardrails",
diff --git a/tests/test_litellm/proxy/proxy_server/test_streaming_helpers.py b/tests/test_litellm/proxy/proxy_server/test_streaming_helpers.py
index f7e2d276a2e..15758c595c0 100644
--- a/tests/test_litellm/proxy/proxy_server/test_streaming_helpers.py
+++ b/tests/test_litellm/proxy/proxy_server/test_streaming_helpers.py
@@ -196,9 +196,7 @@ async def test_async_assistants_data_generator_hook_failure_yields_error_chunk(
async def _noop_failure(*args, **kwargs):
return None
- monkeypatch.setattr(
- ps.proxy_logging_obj, "async_post_call_streaming_hook", _boom_hook
- )
+ monkeypatch.setattr(ps.proxy_logging_obj, "async_post_call_streaming_hook", _boom_hook)
monkeypatch.setattr(ps.proxy_logging_obj, "post_call_failure_hook", _noop_failure)
stream = _FakeAssistantsStream([_simple_chunk()])
@@ -385,9 +383,7 @@ def test_get_streaming_fallback_metadata_no_additional_headers():
def test_get_streaming_fallback_metadata_zero_fallback_count():
stream = _FakeStream(
[],
- hidden_params={
- "additional_headers": {"x-litellm-attempted-fallbacks": 0}
- },
+ hidden_params={"additional_headers": {"x-litellm-attempted-fallbacks": 0}},
)
assert _get_streaming_fallback_metadata(stream) == (False, None, [])
@@ -558,9 +554,7 @@ async def test_apply_streaming_chunk_hooks_appends_to_str_so_far(monkeypatch):
async def _passthrough(*, user_api_key_dict, response, data, str_so_far=None):
return response
- monkeypatch.setattr(
- ps.proxy_logging_obj, "async_post_call_streaming_hook", _passthrough
- )
+ monkeypatch.setattr(ps.proxy_logging_obj, "async_post_call_streaming_hook", _passthrough)
new_chunk, new_str = await _apply_streaming_chunk_hooks(
chunk=chunk,
@@ -870,9 +864,7 @@ async def test_async_data_generator_mid_stream_exception_yields_error_payload(
out.append(line)
# First entry is the successful "partial" chunk (bytes), last is the error.
- assert any(
- isinstance(item, str) and item.startswith('data: {"error":') for item in out
- )
+ assert any(isinstance(item, str) and item.startswith('data: {"error":') for item in out)
# ---------------------------------------------------------------------------
@@ -914,3 +906,694 @@ def test_select_data_generator_missing_required_kwarg_raises_type_error():
streaming starts."""
with pytest.raises(TypeError):
select_data_generator(response=_async_iter([]), user_api_key_dict=_user_auth()) # type: ignore[call-arg]
+
+
+# ---------------------------------------------------------------------------
+# SSE keepalive helpers
+# ---------------------------------------------------------------------------
+
+
+from litellm.proxy.proxy_server import ( # noqa: E402
+ _iter_with_keepalive,
+ _keepalive_from_deployment_config,
+ _make_keepalive_resolver,
+ _resolve_keepalive_seconds,
+)
+from litellm.proxy.proxy_server import _KEEPALIVE_MAX_SECONDS, _KEEPALIVE_MIN_SECONDS # noqa: E402
+
+
+async def test_iter_with_keepalive_hot_path_no_task_wrapping():
+ """When keepalive_seconds <= 0, the generator is a transparent pass-through."""
+ chunks = [_simple_chunk(content="a"), _simple_chunk(content="b")]
+ out = []
+ async for item in _iter_with_keepalive(_async_iter(chunks), lambda _: 0, keepalive_seconds=0):
+ out.append(item)
+
+ assert out == chunks
+ assert ps._STREAM_KEEPALIVE not in out
+
+
+async def test_iter_with_keepalive_emits_sentinel_when_stream_stalls():
+ """With a short keepalive interval and a stalled upstream, _STREAM_KEEPALIVE
+ sentinels appear before the delayed chunk arrives. The resolver returns a
+ constant interval, since this test pins the timing mechanics, not
+ re-resolution."""
+ import asyncio
+
+ async def _slow_stream():
+ yield _simple_chunk(content="first")
+ await asyncio.sleep(0.3)
+ yield _simple_chunk(content="second")
+
+ items = []
+ async for item in _iter_with_keepalive(_slow_stream(), lambda _: 0.05, keepalive_seconds=0.05):
+ items.append(item)
+
+ sentinels = [i for i in items if i is ps._STREAM_KEEPALIVE]
+ real_chunks = [i for i in items if i is not ps._STREAM_KEEPALIVE]
+
+ assert len(sentinels) >= 2, f"expected >= 2 sentinels during 0.3s stall; got {len(sentinels)}"
+ assert len(real_chunks) == 2
+ assert real_chunks[0].choices[0].delta.content == "first"
+ assert real_chunks[1].choices[0].delta.content == "second"
+
+
+async def test_iter_with_keepalive_cancel_on_early_close():
+ """Closing the generator early cancels the in-flight task without raising."""
+ import asyncio
+
+ async def _infinite_stream():
+ while True:
+ await asyncio.sleep(10)
+ yield _simple_chunk()
+
+ gen = _iter_with_keepalive(_infinite_stream(), lambda _: 0.05, keepalive_seconds=0.05)
+ # Advance once to get the sentinel; then close before the real chunk.
+ first = await gen.__anext__()
+ assert first is ps._STREAM_KEEPALIVE
+ # aclose must not raise, and must drain the cancelled task cleanly.
+ await gen.aclose()
+
+
+async def test_iter_with_keepalive_disables_after_fallback_lowers_interval():
+ """Greptile P1: a mid-stream router fallback can hand off to a deployment
+ with a different (or disabled) keepalive policy partway through the same
+ stream. The interval must be re-resolved against each chunk's own identity,
+ not the one picked before iteration started, or heartbeats keep using the
+ pre-fallback deployment's policy for the rest of the stream."""
+ import asyncio
+
+ async def _slow_stream():
+ yield _simple_chunk(content="first")
+ await asyncio.sleep(0.3)
+ yield _simple_chunk(content="second")
+
+ def _resolver(item):
+ # First chunk resolves under the enabled interval used to start the
+ # wrapper; every chunk after that resolves as if a fallback disabled it.
+ return 0.0 if item.choices[0].delta.content == "first" else 999.0
+
+ items = []
+ async for item in _iter_with_keepalive(_slow_stream(), _resolver, keepalive_seconds=0.05):
+ items.append(item)
+
+ sentinels = [i for i in items if i is ps._STREAM_KEEPALIVE]
+ real_chunks = [i for i in items if i is not ps._STREAM_KEEPALIVE]
+
+ assert sentinels == [], f"expected no sentinels once the resolver disables keepalive; got {len(sentinels)}"
+ assert len(real_chunks) == 2
+ assert real_chunks[0].choices[0].delta.content == "first"
+ assert real_chunks[1].choices[0].delta.content == "second"
+
+
+async def test_iter_with_keepalive_enables_after_fallback_raises_interval():
+ """Symmetric case: a mid-stream fallback to a deployment with a *shorter*
+ keepalive interval must take effect immediately, not stay pinned to the
+ longer interval the stream started with. The interval used to wait for a
+ chunk is resolved from the *previous* chunk (the only one seen so far when
+ that wait begins), so the stall has to follow the fallback chunk rather
+ than precede it: waiting for "third" is where the shorter interval bites."""
+ import asyncio
+
+ async def _slow_stream():
+ yield _simple_chunk(content="first")
+ yield _simple_chunk(content="second")
+ await asyncio.sleep(0.3)
+ yield _simple_chunk(content="third")
+
+ def _resolver(item):
+ # "first" resolves under an interval too long to fire before "second"
+ # arrives; "second" (the fallback chunk) resolves as if the fallback
+ # deployment enabled a much shorter interval for everything after it.
+ return 999.0 if item.choices[0].delta.content == "first" else 0.05
+
+ items = []
+ async for item in _iter_with_keepalive(_slow_stream(), _resolver, keepalive_seconds=999.0):
+ items.append(item)
+
+ sentinels = [i for i in items if i is ps._STREAM_KEEPALIVE]
+ real_chunks = [i for i in items if i is not ps._STREAM_KEEPALIVE]
+
+ assert len(sentinels) >= 2, (
+ f"expected >= 2 sentinels once the resolver enables a short interval; got {len(sentinels)}"
+ )
+ assert len(real_chunks) == 3
+
+
+async def test_iter_with_keepalive_activates_from_a_fully_disabled_start():
+ """Greptile P1: a stream can start on a deployment with keepalive off
+ (keepalive_seconds passed in as 0, not merely a long interval) and fall back
+ mid-stream to one that enables it. The 0-second start must not be treated as
+ a one-time decision to skip heartbeats for the rest of the stream: no task
+ is created while inactive, but every chunk still re-resolves so the fallback
+ chunk can switch the stream into task-wrapped mode."""
+ import asyncio
+
+ async def _slow_stream():
+ yield _simple_chunk(content="first")
+ yield _simple_chunk(content="second")
+ await asyncio.sleep(0.3)
+ yield _simple_chunk(content="third")
+
+ def _resolver(item):
+ # "first" resolves to stay off; "second" (the fallback chunk) resolves
+ # as if the fallback deployment newly enabled a short interval.
+ return 0.0 if item.choices[0].delta.content == "first" else 0.05
+
+ items = []
+ async for item in _iter_with_keepalive(_slow_stream(), _resolver, keepalive_seconds=0):
+ items.append(item)
+
+ sentinels = [i for i in items if i is ps._STREAM_KEEPALIVE]
+ real_chunks = [i for i in items if i is not ps._STREAM_KEEPALIVE]
+
+ assert len(sentinels) >= 2, (
+ f"expected >= 2 sentinels once the resolver activates from a disabled start; got {len(sentinels)}"
+ )
+ assert len(real_chunks) == 3
+
+
+def test_resolve_keepalive_seconds_client_value_ignored_without_override_permission(monkeypatch):
+ """keepalive_seconds is operator-only by default: a deployment that hasn't set
+ allow_client_keepalive_override must not let a client's request-level value
+ change its behavior at all, since that would let any authenticated client
+ unilaterally enable heartbeats (and the LB-idle-timeout evasion that comes
+ with them) for a deployment that never opted in."""
+ from unittest.mock import MagicMock
+
+ deployment = MagicMock()
+ deployment.litellm_params.keepalive_seconds = 15.0
+ deployment.litellm_params.allow_client_keepalive_override = False
+
+ router = MagicMock()
+ router.get_deployment.return_value = deployment
+
+ monkeypatch.setattr(ps, "llm_router", router)
+
+ response = MagicMock()
+ response._hidden_params = {"model_id": "deploy-locked"}
+
+ result = _resolve_keepalive_seconds({"model": "my-model", "keepalive_seconds": 1}, response=response)
+ assert result == 15.0
+
+
+def test_resolve_keepalive_seconds_request_value_wins_when_override_allowed(monkeypatch):
+ from unittest.mock import MagicMock
+
+ deployment = MagicMock()
+ deployment.litellm_params.keepalive_seconds = None
+ deployment.litellm_params.allow_client_keepalive_override = True
+
+ router = MagicMock()
+ router.get_deployment.return_value = deployment
+
+ monkeypatch.setattr(ps, "llm_router", router)
+
+ response = MagicMock()
+ response._hidden_params = {"model_id": "deploy-opt-in"}
+
+ result = _resolve_keepalive_seconds({"model": "my-model", "keepalive_seconds": 30}, response=response)
+ assert result == 30.0
+
+
+def test_resolve_keepalive_seconds_explicit_zero_disables_when_override_allowed(monkeypatch):
+ from unittest.mock import MagicMock
+
+ deployment = MagicMock()
+ deployment.litellm_params.keepalive_seconds = 20.0
+ deployment.litellm_params.allow_client_keepalive_override = True
+
+ router = MagicMock()
+ router.get_deployment.return_value = deployment
+
+ monkeypatch.setattr(ps, "llm_router", router)
+
+ response = MagicMock()
+ response._hidden_params = {"model_id": "deploy-opt-in"}
+
+ result = _resolve_keepalive_seconds({"model": "my-model", "keepalive_seconds": 0}, response=response)
+ assert result == 0.0
+
+
+def test_resolve_keepalive_seconds_clamps_below_minimum(monkeypatch):
+ from unittest.mock import MagicMock
+
+ deployment = MagicMock()
+ deployment.litellm_params.keepalive_seconds = None
+ deployment.litellm_params.allow_client_keepalive_override = True
+
+ router = MagicMock()
+ router.get_deployment.return_value = deployment
+
+ monkeypatch.setattr(ps, "llm_router", router)
+
+ response = MagicMock()
+ response._hidden_params = {"model_id": "deploy-opt-in"}
+
+ result = _resolve_keepalive_seconds({"model": "my-model", "keepalive_seconds": 0.001}, response=response)
+ assert result == _KEEPALIVE_MIN_SECONDS
+
+
+def test_resolve_keepalive_seconds_clamps_above_maximum(monkeypatch):
+ from unittest.mock import MagicMock
+
+ deployment = MagicMock()
+ deployment.litellm_params.keepalive_seconds = None
+ deployment.litellm_params.allow_client_keepalive_override = True
+
+ router = MagicMock()
+ router.get_deployment.return_value = deployment
+
+ monkeypatch.setattr(ps, "llm_router", router)
+
+ response = MagicMock()
+ response._hidden_params = {"model_id": "deploy-opt-in"}
+
+ result = _resolve_keepalive_seconds({"model": "my-model", "keepalive_seconds": 9999}, response=response)
+ assert result == _KEEPALIVE_MAX_SECONDS
+
+
+def test_resolve_keepalive_seconds_non_numeric_returns_zero(monkeypatch):
+ from unittest.mock import MagicMock
+
+ deployment = MagicMock()
+ deployment.litellm_params.keepalive_seconds = None
+ deployment.litellm_params.allow_client_keepalive_override = True
+
+ router = MagicMock()
+ router.get_deployment.return_value = deployment
+
+ monkeypatch.setattr(ps, "llm_router", router)
+
+ response = MagicMock()
+ response._hidden_params = {"model_id": "deploy-opt-in"}
+
+ result = _resolve_keepalive_seconds({"model": "my-model", "keepalive_seconds": "not-a-number"}, response=response)
+ assert result == 0.0
+
+
+def test_resolve_keepalive_seconds_absent_returns_zero(monkeypatch):
+ monkeypatch.setattr(ps, "llm_router", None)
+ result = _resolve_keepalive_seconds({}, response=None)
+ assert result == 0.0
+
+
+def test_resolve_keepalive_seconds_deployment_disable_cannot_be_overridden_by_request(monkeypatch):
+ """A deployment that explicitly sets keepalive_seconds: 0 is a hard operator
+ disable: an authenticated client must not be able to re-enable heartbeats for
+ that deployment by passing a positive value in the request body, since that
+ would let a client evade the deployment's idle-timeout behavior at will. This
+ holds even if the deployment also grants override permission, since an
+ explicit disable is a stronger, unconditional signal than an override grant."""
+ from unittest.mock import MagicMock
+
+ deployment = MagicMock()
+ deployment.litellm_params.keepalive_seconds = 0
+ deployment.litellm_params.allow_client_keepalive_override = True
+
+ router = MagicMock()
+ router.get_deployment.return_value = deployment
+
+ monkeypatch.setattr(ps, "llm_router", router)
+
+ response = MagicMock()
+ response._hidden_params = {"model_id": "deploy-disabled"}
+
+ result = _resolve_keepalive_seconds({"model": "my-model", "keepalive_seconds": 250}, response=response)
+ assert result == 0.0
+
+
+def test_keepalive_from_deployment_config_reads_by_model_id(monkeypatch):
+ from unittest.mock import MagicMock
+
+ deployment = MagicMock()
+ deployment.litellm_params.keepalive_seconds = 45.0
+ deployment.litellm_params.allow_client_keepalive_override = True
+
+ router = MagicMock()
+ router.get_deployment.return_value = deployment
+
+ monkeypatch.setattr(ps, "llm_router", router)
+
+ response = MagicMock()
+ response._hidden_params = {"model_id": "deploy-abc"}
+
+ result = _keepalive_from_deployment_config({"model": "my-model"}, response)
+ assert result == ps._DeploymentKeepaliveConfig(keepalive_seconds=45.0, allow_client_override=True)
+ router.get_deployment.assert_called_once_with(model_id="deploy-abc")
+
+
+def test_keepalive_from_deployment_config_stale_model_id_does_not_fall_through(monkeypatch):
+ """A populated model_id names the specific deployment that served the stream.
+ If that ID no longer resolves (e.g. removed by a config reload mid-stream),
+ that's a stale identity, not an absent one: it must not fall through to the
+ model_name fallback, since a currently-live sibling deployment's config was
+ never what actually served this stream, even if that sibling's config is
+ unambiguous on its own."""
+ from unittest.mock import MagicMock
+
+ router = MagicMock()
+ router.get_deployment.return_value = None
+ router.get_model_list.return_value = [
+ {"litellm_params": {"keepalive_seconds": 20.0}},
+ ]
+
+ monkeypatch.setattr(ps, "llm_router", router)
+
+ response = MagicMock()
+ response._hidden_params = {"model_id": "stale-deploy-id"}
+
+ result = _keepalive_from_deployment_config({"model": "slow-model"}, response)
+ assert result is None
+ router.get_model_list.assert_not_called()
+
+
+def test_keepalive_from_deployment_config_fallback_by_name(monkeypatch):
+ from unittest.mock import MagicMock
+
+ router = MagicMock()
+ router.get_deployment.return_value = None
+ router.get_model_list.return_value = [
+ {"litellm_params": {"keepalive_seconds": 20.0}},
+ ]
+
+ monkeypatch.setattr(ps, "llm_router", router)
+
+ response = MagicMock()
+ response._hidden_params = {}
+
+ result = _keepalive_from_deployment_config({"model": "slow-model"}, response)
+ assert result == ps._DeploymentKeepaliveConfig(keepalive_seconds=20.0, allow_client_override=False)
+ router.get_model_list.assert_called_once_with(model_name="slow-model")
+
+
+def test_keepalive_from_deployment_config_fallback_by_name_agreeing_deployments(monkeypatch):
+ """Multiple deployments under the same model_name with the same keepalive_seconds
+ is unambiguous, so the shared value is used even without a model_id."""
+ from unittest.mock import MagicMock
+
+ router = MagicMock()
+ router.get_deployment.return_value = None
+ router.get_model_list.return_value = [
+ {"litellm_params": {"keepalive_seconds": 20.0, "allow_client_keepalive_override": True}},
+ {"litellm_params": {"keepalive_seconds": 20.0, "allow_client_keepalive_override": True}},
+ ]
+
+ monkeypatch.setattr(ps, "llm_router", router)
+
+ response = MagicMock()
+ response._hidden_params = {}
+
+ result = _keepalive_from_deployment_config({"model": "slow-model"}, response)
+ assert result == ps._DeploymentKeepaliveConfig(keepalive_seconds=20.0, allow_client_override=True)
+
+
+def test_keepalive_from_deployment_config_fallback_by_name_conflicting_deployments(monkeypatch):
+ """Without a model_id, if deployments under the same model_name disagree on
+ keepalive_seconds, we can't tell which one served the stream: don't guess and
+ apply the wrong deployment's interval (or override an explicit disable)."""
+ from unittest.mock import MagicMock
+
+ router = MagicMock()
+ router.get_deployment.return_value = None
+ router.get_model_list.return_value = [
+ {"litellm_params": {"keepalive_seconds": 20.0}},
+ {"litellm_params": {"keepalive_seconds": 0}},
+ ]
+
+ monkeypatch.setattr(ps, "llm_router", router)
+
+ response = MagicMock()
+ response._hidden_params = {}
+
+ result = _keepalive_from_deployment_config({"model": "slow-model"}, response)
+ assert result is None
+
+
+def test_keepalive_from_deployment_config_fallback_by_name_configured_plus_unset(monkeypatch):
+ """A deployment that leaves keepalive_seconds unset entirely (not explicitly 0)
+ must not inherit a sibling deployment's configured interval: without a model_id
+ we can't tell which deployment served the stream, so mixing a configured
+ deployment with an unconfigured one is just as ambiguous as two conflicting
+ configured values."""
+ from unittest.mock import MagicMock
+
+ router = MagicMock()
+ router.get_deployment.return_value = None
+ router.get_model_list.return_value = [
+ {"litellm_params": {"keepalive_seconds": 20.0}},
+ {"litellm_params": {}},
+ ]
+
+ monkeypatch.setattr(ps, "llm_router", router)
+
+ response = MagicMock()
+ response._hidden_params = {}
+
+ result = _keepalive_from_deployment_config({"model": "slow-model"}, response)
+ assert result is None
+
+
+def test_keepalive_from_deployment_config_no_router_returns_none(monkeypatch):
+ monkeypatch.setattr(ps, "llm_router", None)
+ result = _keepalive_from_deployment_config({"model": "gpt-4"}, None)
+ assert result is None
+
+
+def test_make_keepalive_resolver_caches_by_model_id(monkeypatch):
+ """The steady-state case (no fallback): every chunk shares the same
+ model_id, so the deployment lookup must happen once, not once per chunk."""
+ from unittest.mock import MagicMock
+
+ deployment = MagicMock()
+ deployment.litellm_params.keepalive_seconds = 5.0
+ deployment.litellm_params.allow_client_keepalive_override = False
+
+ router = MagicMock()
+ router.get_deployment.return_value = deployment
+ monkeypatch.setattr(ps, "llm_router", router)
+
+ resolve = _make_keepalive_resolver({"model": "my-model"})
+
+ first = _simple_chunk(content="a")
+ first._hidden_params = {"model_id": "deploy-steady"}
+ second = _simple_chunk(content="b")
+ second._hidden_params = {"model_id": "deploy-steady"}
+
+ assert resolve(first) == 5.0
+ assert resolve(second) == 5.0
+ router.get_deployment.assert_called_once_with(model_id="deploy-steady")
+
+
+def test_make_keepalive_resolver_reresolves_on_model_id_change(monkeypatch):
+ """A mid-stream fallback changes model_id: the cache must miss and
+ re-resolve against the new deployment, not keep serving the stale value."""
+ from unittest.mock import MagicMock
+
+ before = MagicMock()
+ before.litellm_params.keepalive_seconds = 5.0
+ before.litellm_params.allow_client_keepalive_override = False
+
+ after = MagicMock()
+ after.litellm_params.keepalive_seconds = 30.0
+ after.litellm_params.allow_client_keepalive_override = False
+
+ router = MagicMock()
+ router.get_deployment.side_effect = lambda model_id: {"deploy-a": before, "deploy-b": after}[model_id]
+ monkeypatch.setattr(ps, "llm_router", router)
+
+ resolve = _make_keepalive_resolver({"model": "my-model"})
+
+ chunk_a = _simple_chunk(content="a")
+ chunk_a._hidden_params = {"model_id": "deploy-a"}
+ chunk_b = _simple_chunk(content="b")
+ chunk_b._hidden_params = {"model_id": "deploy-b"}
+
+ assert resolve(chunk_a) == 5.0
+ assert resolve(chunk_b) == 30.0
+ assert router.get_deployment.call_count == 2
+
+
+def test_make_keepalive_resolver_missing_model_id_never_cached(monkeypatch):
+ """Without a model_id there's no reliable cache key (see the model_name
+ fallback in _keepalive_from_deployment_config), so every chunk must
+ re-resolve fresh rather than reuse a stale guess."""
+ from unittest.mock import MagicMock
+
+ router = MagicMock()
+ router.get_deployment.return_value = None
+ router.get_model_list.return_value = [{"litellm_params": {"keepalive_seconds": 12.0}}]
+ monkeypatch.setattr(ps, "llm_router", router)
+
+ resolve = _make_keepalive_resolver({"model": "slow-model"})
+
+ chunk_a = _simple_chunk(content="a")
+ chunk_a._hidden_params = {}
+ chunk_b = _simple_chunk(content="b")
+ chunk_b._hidden_params = {}
+
+ assert resolve(chunk_a) == 12.0
+ assert resolve(chunk_b) == 12.0
+ assert router.get_model_list.call_count == 2
+
+
+def test_make_keepalive_resolver_expires_cache_after_ttl(monkeypatch):
+ """An operator's live config change (revoking override, disabling
+ keepalive, removing the deployment) must be observed within
+ _KEEPALIVE_CACHE_TTL_SECONDS, not frozen for the rest of an
+ already-in-flight stream just because the model_id hasn't changed."""
+ from unittest.mock import MagicMock
+
+ before = MagicMock()
+ before.litellm_params.keepalive_seconds = 20.0
+ before.litellm_params.allow_client_keepalive_override = False
+
+ after = MagicMock()
+ after.litellm_params.keepalive_seconds = 0
+ after.litellm_params.allow_client_keepalive_override = False
+
+ router = MagicMock()
+ router.get_deployment.return_value = before
+ monkeypatch.setattr(ps, "llm_router", router)
+
+ clock = {"t": 0.0}
+ monkeypatch.setattr(ps.time, "monotonic", lambda: clock["t"])
+
+ resolve = _make_keepalive_resolver({"model": "my-model"})
+
+ chunk = _simple_chunk(content="a")
+ chunk._hidden_params = {"model_id": "deploy-live"}
+
+ assert resolve(chunk) == 20.0
+ assert router.get_deployment.call_count == 1
+
+ # Still within the TTL: same model_id, cached value reused even though
+ # the router's live config has since changed underneath it.
+ router.get_deployment.return_value = after
+ clock["t"] = ps._KEEPALIVE_CACHE_TTL_SECONDS - 0.01
+ assert resolve(chunk) == 20.0
+ assert router.get_deployment.call_count == 1
+
+ # Past the TTL: the config-reload disable is now observed.
+ clock["t"] = ps._KEEPALIVE_CACHE_TTL_SECONDS + 0.01
+ assert resolve(chunk) == 0.0
+ assert router.get_deployment.call_count == 2
+
+
+def test_keepalive_seconds_in_all_litellm_params():
+ from litellm.types.utils import all_litellm_params
+
+ assert "keepalive_seconds" in all_litellm_params
+
+
+def test_allow_client_keepalive_override_in_all_litellm_params():
+ """allow_client_keepalive_override is a deployment-only control flag: if it's
+ missing from all_litellm_params, it leaks straight through into the actual
+ provider API call as an unrecognized field and gets rejected (confirmed live
+ against the real Anthropic API, which returns 'Extra inputs are not
+ permitted')."""
+ from litellm.types.utils import all_litellm_params
+
+ assert "allow_client_keepalive_override" in all_litellm_params
+
+
+async def test_async_data_generator_emits_ping_heartbeat(monkeypatch):
+ """When keepalive_seconds is set on a deployment that allows client override,
+ ': ping' frames appear during upstream stalls."""
+ import asyncio
+ from unittest.mock import MagicMock
+
+ _patch_logging_flags(monkeypatch)
+ monkeypatch.setattr(ps, "_KEEPALIVE_MIN_SECONDS", 0.05)
+
+ router = MagicMock()
+ router.get_deployment.return_value = None
+ router.get_model_list.return_value = [{"litellm_params": {"allow_client_keepalive_override": True}}]
+ monkeypatch.setattr(ps, "llm_router", router)
+
+ 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", "keepalive_seconds": 0.05},
+ ):
+ 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"
+
+
+async def test_async_data_generator_no_keepalive_no_pings(monkeypatch):
+ """Without keepalive_seconds, no ': ping' frames are emitted."""
+ _patch_logging_flags(monkeypatch)
+
+ out = []
+ async for line in async_data_generator(
+ response=_async_iter([_simple_chunk(content="hello")]),
+ user_api_key_dict=_user_auth(),
+ request_data={"model": "gpt-4"},
+ ):
+ out.append(line)
+
+ assert ": ping\n\n" not in out
+ assert out[-1] == "data: [DONE]\n\n"
+
+
+async def test_async_data_generator_resolves_deployment_once_per_steady_stream(monkeypatch):
+ """Regression test for the per-chunk resolver cost: a stream where every
+ real chunk comes from the same deployment (the common, no-fallback case)
+ must only pay for one `llm_router.get_deployment()` call, not one per
+ chunk. Before caching, this asserted 1 but got len(chunks) since the
+ resolver re-ran the full deployment lookup after every single chunk.
+
+ The very first resolve happens on the raw `response` object before any
+ chunk is yielded; a bare async generator (unlike the real
+ CustomStreamWrapper this stands in for) can't carry `_hidden_params`, so
+ that one call goes through the model_name fallback instead of
+ `get_deployment` — hence it's asserted separately.
+ """
+ from unittest.mock import MagicMock
+
+ _patch_logging_flags(monkeypatch)
+
+ deployment = MagicMock()
+ deployment.litellm_params.keepalive_seconds = None
+ deployment.litellm_params.allow_client_keepalive_override = False
+
+ router = MagicMock()
+ router.get_deployment.return_value = deployment
+ router.get_model_list.return_value = [{"litellm_params": {}}]
+ monkeypatch.setattr(ps, "llm_router", router)
+
+ async def _steady_response():
+ for content in ("a", "b", "c", "d", "e"):
+ chunk = _simple_chunk(content=content)
+ chunk._hidden_params = {"model_id": "deploy-steady"}
+ yield chunk
+
+ out = []
+ async for line in async_data_generator(
+ response=_steady_response(),
+ user_api_key_dict=_user_auth(),
+ request_data={"model": "gpt-4"},
+ ):
+ out.append(line)
+
+ assert router.get_deployment.call_count == 1
+ assert router.get_model_list.call_count == 1
+ assert out[-1] == "data: [DONE]\n\n"
diff --git a/tests/test_litellm/proxy/test_litellm_pre_call_utils.py b/tests/test_litellm/proxy/test_litellm_pre_call_utils.py
index 803094e8d54..f48e1dba601 100644
--- a/tests/test_litellm/proxy/test_litellm_pre_call_utils.py
+++ b/tests/test_litellm/proxy/test_litellm_pre_call_utils.py
@@ -2076,6 +2076,55 @@ def test_get_num_retries_from_request():
assert result == -1
+def test_get_keepalive_seconds_from_request():
+ """
+ Test LiteLLMProxyRequestSetup._get_keepalive_seconds_from_request method
+ """
+ # Header present with valid float string
+ headers_with_keepalive = {"x-litellm-keepalive-seconds": "15"}
+ result = LiteLLMProxyRequestSetup._get_keepalive_seconds_from_request(
+ headers_with_keepalive
+ )
+ assert result == 15.0
+
+ # Header not present
+ result = LiteLLMProxyRequestSetup._get_keepalive_seconds_from_request(
+ {"Content-Type": "application/json"}
+ )
+ assert result is None
+
+ # Empty headers dictionary
+ result = LiteLLMProxyRequestSetup._get_keepalive_seconds_from_request({})
+ assert result is None
+
+ # Header present with a fractional value
+ result = LiteLLMProxyRequestSetup._get_keepalive_seconds_from_request(
+ {"x-litellm-keepalive-seconds": "1.5"}
+ )
+ assert result == 1.5
+
+ # Header present with invalid value raises ValueError, matching the other
+ # x-litellm-* numeric header helpers (_get_timeout_from_request, etc.)
+ with pytest.raises(ValueError):
+ LiteLLMProxyRequestSetup._get_keepalive_seconds_from_request(
+ {"x-litellm-keepalive-seconds": "not-a-number"}
+ )
+
+
+def test_add_litellm_data_for_backend_llm_call_merges_keepalive_seconds_header():
+ """
+ The x-litellm-keepalive-seconds header must be merged into the data dict
+ that add_litellm_data_to_request later data.update()s onto the request body,
+ the same way x-litellm-timeout/x-litellm-num-retries already are.
+ """
+ result = LiteLLMProxyRequestSetup.add_litellm_data_for_backend_llm_call(
+ headers={"x-litellm-keepalive-seconds": "20"},
+ request_data={},
+ user_api_key_dict=UserAPIKeyAuth(api_key="sk-test"),
+ )
+ assert result.get("keepalive_seconds") == 20.0
+
+
def test_add_user_api_key_auth_to_request_metadata():
"""
Test that add_user_api_key_auth_to_request_metadata properly adds user API key authentication data to request metadata
diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.ts
index fa8731d7a16..6323516b126 100644
--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts
+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts
@@ -26758,6 +26758,11 @@ export interface components {
} | null;
/** Adaptive Router Default Model */
adaptive_router_default_model?: string | null;
+ /**
+ * Allow Client Keepalive Override
+ * @default false
+ */
+ allow_client_keepalive_override: boolean | null;
/** Annotation Cost Per Page */
annotation_cost_per_page?: number | null;
/** Api Base */
@@ -26906,6 +26911,8 @@ export interface components {
input_cost_per_video_token?: number | null;
/** Itpm */
itpm?: number | null;
+ /** Keepalive Seconds */
+ keepalive_seconds?: number | null;
/** Litellm Credential Name */
litellm_credential_name?: string | null;
/** Litellm Trace Id */
@@ -35429,6 +35436,11 @@ export interface components {
} | null;
/** Adaptive Router Default Model */
adaptive_router_default_model?: string | null;
+ /**
+ * Allow Client Keepalive Override
+ * @default false
+ */
+ allow_client_keepalive_override: boolean | null;
/** Annotation Cost Per Page */
annotation_cost_per_page?: number | null;
/** Api Base */
@@ -35577,6 +35589,8 @@ export interface components {
input_cost_per_video_token?: number | null;
/** Itpm */
itpm?: number | null;
+ /** Keepalive Seconds */
+ keepalive_seconds?: number | null;
/** Litellm Credential Name */
litellm_credential_name?: string | null;
/** Litellm Trace Id */