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(streaming): stamp completion_start_time on first chunk for /v1/messages and /v1/responses (#32284)
yucheng-berri8449ecee6ad3
diff --git a/litellm/proxy/pass_through_endpoints/streaming_handler.py b/litellm/proxy/pass_through_endpoints/streaming_handler.pyindex af61281243d..4dc1e0e70dd 100644--- a/litellm/proxy/pass_through_endpoints/streaming_handler.py+++ b/litellm/proxy/pass_through_endpoints/streaming_handler.py@@ -25,6 +25,11 @@ from .success_handler import PassThroughEndpointLoggingclass PassThroughStreamingHandler:+ @staticmethod+ def _stamp_first_chunk_if_needed(litellm_logging_obj: LiteLLMLoggingObj) -> None:+ if litellm_logging_obj.completion_start_time is None:+ litellm_logging_obj._update_completion_start_time(completion_start_time=datetime.now())+@staticmethodasync def chunk_processor(response: httpx.Response,@@ -58,6 +63,7 @@ class PassThroughStreamingHandler:# Hot path: just buffer for end-of-stream logging and forward.async for chunk in response.aiter_bytes():raw_bytes.append(chunk)+ PassThroughStreamingHandler._stamp_first_chunk_if_needed(litellm_logging_obj)yield chunkelse:# ``cost_injection_active`` already requires ``model_name`` to@@ -67,6 +73,7 @@ class PassThroughStreamingHandler:resolved_model_name: str = model_nameasync for chunk in response.aiter_bytes():raw_bytes.append(chunk)+ PassThroughStreamingHandler._stamp_first_chunk_if_needed(litellm_logging_obj)if endpoint_type == EndpointType.VERTEX_AI:if "streamRawPredict" in url_route or "rawPredict" in url_route:modified_chunk = ProxyBaseLLMRequestProcessing._process_chunk_with_cost_injection(diff --git a/litellm/responses/streaming_iterator.py b/litellm/responses/streaming_iterator.pyindex 6df544dee3e..890b3b636ba 100644--- a/litellm/responses/streaming_iterator.py+++ b/litellm/responses/streaming_iterator.py@@ -128,6 +128,9 @@ class BaseResponsesAPIStreamingIterator:self.finished = Truereturn None+ if self.logging_obj.completion_start_time is None:+ self.logging_obj._update_completion_start_time(completion_start_time=datetime.now())+try:# Parse the JSON chunkparsed_chunk = json.loads(chunk)diff --git a/tests/llm_responses_api_testing/test_base_responses_api_streaming_iterator.py b/tests/llm_responses_api_testing/test_base_responses_api_streaming_iterator.pyindex 37fcc602d37..2acced4c679 100644--- a/tests/llm_responses_api_testing/test_base_responses_api_streaming_iterator.py+++ b/tests/llm_responses_api_testing/test_base_responses_api_streaming_iterator.py@@ -67,6 +67,7 @@ class TestBaseResponsesAPIStreamingIterator:mock_logging_obj = Mock(spec=LiteLLMLoggingObj)mock_logging_obj.model_call_details = {"litellm_params": {}}+ mock_logging_obj.completion_start_time = Nonemock_config = Mock(spec=BaseResponsesAPIConfig)mock_responses_api_response = Mock(spec=ResponsesAPIResponse)@@ -107,6 +108,7 @@ class TestBaseResponsesAPIStreamingIterator:mock_response.headers = {}mock_logging_obj = Mock(spec=LiteLLMLoggingObj)mock_logging_obj.model_call_details = {"litellm_params": {}}+ mock_logging_obj.completion_start_time = Nonemock_config = Mock(spec=BaseResponsesAPIConfig)# Create a mock ResponsesAPIResponse for the completed event@@ -179,6 +181,7 @@ class TestBaseResponsesAPIStreamingIterator:mock_response.headers = {}mock_logging_obj = Mock(spec=LiteLLMLoggingObj)mock_logging_obj.model_call_details = {"litellm_params": {}}+ mock_logging_obj.completion_start_time = Nonemock_config = Mock(spec=BaseResponsesAPIConfig)# Create a mock OutputTextDeltaEvent (not a completed event)@@ -239,6 +242,7 @@ class TestBaseResponsesAPIStreamingIterator:mock_response.headers = {}mock_logging_obj = Mock(spec=LiteLLMLoggingObj)mock_logging_obj.model_call_details = {"litellm_params": {}}+ mock_logging_obj.completion_start_time = Nonemock_config = Mock(spec=BaseResponsesAPIConfig)# Create the iterator instance@@ -265,6 +269,7 @@ class TestBaseResponsesAPIStreamingIterator:mock_response.headers = {}mock_logging_obj = Mock(spec=LiteLLMLoggingObj)mock_logging_obj.model_call_details = {"litellm_params": {}}+ mock_logging_obj.completion_start_time = Nonemock_config = Mock(spec=BaseResponsesAPIConfig)# Create the iterator instance@@ -291,6 +296,7 @@ class TestBaseResponsesAPIStreamingIterator:mock_response.headers = {}mock_logging_obj = Mock(spec=LiteLLMLoggingObj)mock_logging_obj.model_call_details = {"litellm_params": {}}+ mock_logging_obj.completion_start_time = Nonemock_config = Mock(spec=BaseResponsesAPIConfig)# Create the iterator instance@@ -329,6 +335,7 @@ class TestBaseResponsesAPIStreamingIterator:mock_response.aiter_bytes = Mock()mock_logging_obj = Mock(spec=LiteLLMLoggingObj)mock_logging_obj.model_call_details = {"litellm_params": {}}+ mock_logging_obj.completion_start_time = Nonemock_logging_obj.async_success_handler = Mock()mock_logging_obj.success_handler = Mock()mock_config = Mock(spec=BaseResponsesAPIConfig)@@ -397,6 +404,7 @@ class TestBaseResponsesAPIStreamingIterator:mock_logging_obj = Mock(spec=LiteLLMLoggingObj)mock_logging_obj.model_call_details = {"litellm_params": {}}+ mock_logging_obj.completion_start_time = Nonemock_logging_obj.async_failure_handler = Mock()mock_logging_obj.failure_handler = Mock()@@ -457,6 +465,7 @@ class TestBaseResponsesAPIStreamingIterator:mock_logging_obj = Mock(spec=LiteLLMLoggingObj)mock_logging_obj.model_call_details = {"litellm_params": {}}+ mock_logging_obj.completion_start_time = Nonemock_logging_obj.async_failure_handler = Mock()mock_logging_obj.failure_handler = Mock()@@ -505,6 +514,7 @@ class TestBaseResponsesAPIStreamingIterator:mock_response.aiter_bytes = Mock()mock_logging_obj = Mock(spec=LiteLLMLoggingObj)mock_logging_obj.model_call_details = {"litellm_params": {}}+ mock_logging_obj.completion_start_time = Nonemock_logging_obj.async_failure_handler = Mock()mock_logging_obj.failure_handler = Mock()mock_logging_obj.async_success_handler = Mock()@@ -587,6 +597,7 @@ class TestBaseResponsesAPIStreamingIterator:mock_response.aiter_bytes = Mock()mock_logging_obj = Mock(spec=LiteLLMLoggingObj)mock_logging_obj.model_call_details = {"litellm_params": {}}+ mock_logging_obj.completion_start_time = Nonemock_logging_obj.async_failure_handler = Mock()mock_logging_obj.failure_handler = Mock()mock_logging_obj.async_success_handler = Mock()diff --git a/tests/llm_responses_api_testing/test_responses_hooks.py b/tests/llm_responses_api_testing/test_responses_hooks.pyindex 3799a0b9121..3cc5e3984e2 100644--- a/tests/llm_responses_api_testing/test_responses_hooks.py+++ b/tests/llm_responses_api_testing/test_responses_hooks.py@@ -34,6 +34,7 @@ class _FakeLoggingObj:self.last_success_kwargs = Noneself.last_async_success_kwargs = Noneself.start_time = datetime.now()+ self.completion_start_time = Noneself.model_call_details = {"litellm_params": {}}# Signature alignment with Logging handlers@@ -51,6 +52,10 @@ class _FakeLoggingObj:async def async_failure_handler(self, *args, **kwargs):self.async_failure_calls += 1+ def _update_completion_start_time(self, completion_start_time):+ self.completion_start_time = completion_start_time+ self.model_call_details["completion_start_time"] = completion_start_time+def _make_completed_response(response_id: str = "resp_test") -> ResponseCompletedEvent:return ResponseCompletedEvent(diff --git a/tests/pass_through_unit_tests/test_vertex_ai_anthropic_streaming_cost_injection.py b/tests/pass_through_unit_tests/test_vertex_ai_anthropic_streaming_cost_injection.pyindex b42f1fe6f0a..ac754aefaea 100644--- a/tests/pass_through_unit_tests/test_vertex_ai_anthropic_streaming_cost_injection.py+++ b/tests/pass_through_unit_tests/test_vertex_ai_anthropic_streaming_cost_injection.py@@ -57,6 +57,7 @@ async def test_vertex_ai_anthropic_streaming_cost_injection_enabled():# Setup logging object with model infolitellm_logging_obj = MagicMock(spec=LiteLLMLoggingObj)litellm_logging_obj.model_call_details = {"model": "claude-sonnet-4@20250514"}+ litellm_logging_obj.completion_start_time = Nonelitellm_logging_obj.async_success_handler = AsyncMock()request_body = {"model": "claude-sonnet-4@20250514"}@@ -135,6 +136,7 @@ async def test_vertex_ai_anthropic_streaming_cost_injection_disabled():litellm_logging_obj = MagicMock(spec=LiteLLMLoggingObj)litellm_logging_obj.model_call_details = {"model": "claude-sonnet-4@20250514"}+ litellm_logging_obj.completion_start_time = Nonelitellm_logging_obj.async_success_handler = AsyncMock()request_body = {"model": "claude-sonnet-4@20250514"}@@ -196,6 +198,7 @@ async def test_vertex_ai_anthropic_streaming_cost_injection_no_usage_chunk():litellm_logging_obj = MagicMock(spec=LiteLLMLoggingObj)litellm_logging_obj.model_call_details = {"model": "claude-sonnet-4@20250514"}+ litellm_logging_obj.completion_start_time = Nonelitellm_logging_obj.async_success_handler = AsyncMock()request_body = {"model": "claude-sonnet-4@20250514"}@@ -250,6 +253,7 @@ async def test_vertex_ai_anthropic_streaming_model_extraction():litellm_logging_obj = MagicMock(spec=LiteLLMLoggingObj)litellm_logging_obj.model_call_details = {}+ litellm_logging_obj.completion_start_time = Nonelitellm_logging_obj.async_success_handler = AsyncMock()# Test model extraction from request bodydiff --git a/tests/test_litellm/proxy/pass_through_endpoints/test_streaming_handler_interrupt.py b/tests/test_litellm/proxy/pass_through_endpoints/test_streaming_handler_interrupt.pyindex 80702e605e7..163a0cbff3c 100644--- a/tests/test_litellm/proxy/pass_through_endpoints/test_streaming_handler_interrupt.py+++ b/tests/test_litellm/proxy/pass_through_endpoints/test_streaming_handler_interrupt.py@@ -241,6 +241,126 @@ async def test_chunk_processor_routes_logging_through_logging_worker_on_disconneassert asyncio.iscoroutine(enqueued[0])+def _logging_obj_with_write_once_cst():+ """Build a MagicMock that mirrors the real Logging behavior: _update_completion_start_time+ latches self.completion_start_time so the write-once guard actually latches."""+ obj = MagicMock()+ obj.completion_start_time = None++ def _update(*, completion_start_time):+ obj.completion_start_time = completion_start_time++ obj._update_completion_start_time.side_effect = _update+ return obj+++async def test_chunk_processor_stamps_completion_start_time_on_first_chunk():+ """Regression: LIT-4185 — streaming pass-through must stamp completion_start_time on+ the first upstream chunk. Otherwise _success_handler_helper_fn falls back to+ completion_start_time = end_time, and Prometheus/OTEL/SpendLogs TTFT reads as+ total request duration (0 speedup)."""+ chunks = [b"chunk-1", b"chunk-2", b"chunk-3"]+ response = _make_streaming_response(chunks)++ mock_logging_obj = _logging_obj_with_write_once_cst()+ mock_passthrough_handler = MagicMock()++ with patch.object(+ PassThroughStreamingHandler,+ "_route_streaming_logging_to_handler",+ new=AsyncMock(),+ ):+ received = []+ async for chunk in PassThroughStreamingHandler.chunk_processor(+ response=response,+ request_body={"model": "claude-haiku-4-5"},+ litellm_logging_obj=mock_logging_obj,+ endpoint_type=EndpointType.ANTHROPIC,+ start_time=datetime.now(),+ passthrough_success_handler_obj=mock_passthrough_handler,+ url_route="/v1/messages",+ ):+ received.append(chunk)++ await asyncio.sleep(0)++ assert received == chunks+ mock_logging_obj._update_completion_start_time.assert_called_once()+ stamped = mock_logging_obj._update_completion_start_time.call_args.kwargs["completion_start_time"]+ assert isinstance(stamped, datetime)+++async def test_chunk_processor_does_not_reset_completion_start_time_on_later_chunks():+ """The stamp must be write-once: reading it on chunk 2/3 must not overwrite a real TTFT+ from chunk 1 (which would collapse TTFT to time-to-last-chunk)."""+ chunks = [b"chunk-1", b"chunk-2", b"chunk-3"]+ response = _make_streaming_response(chunks)++ real_first = datetime(2020, 1, 1, 0, 0, 0)+ mock_logging_obj = MagicMock()+ # Simulate first-chunk stamp having already landed (e.g. under contention or a+ # prior wrapper that already set it): later chunks must be no-ops.+ mock_logging_obj.completion_start_time = real_first+ mock_passthrough_handler = MagicMock()++ with patch.object(+ PassThroughStreamingHandler,+ "_route_streaming_logging_to_handler",+ new=AsyncMock(),+ ):+ async for _ in PassThroughStreamingHandler.chunk_processor(+ response=response,+ request_body={"model": "claude-haiku-4-5"},+ litellm_logging_obj=mock_logging_obj,+ endpoint_type=EndpointType.ANTHROPIC,+ start_time=datetime.now(),+ passthrough_success_handler_obj=mock_passthrough_handler,+ url_route="/v1/messages",+ ):+ pass++ mock_logging_obj._update_completion_start_time.assert_not_called()+ assert mock_logging_obj.completion_start_time == real_first+++async def test_chunk_processor_stamps_completion_start_time_on_cost_injection_path():+ """The cost-injection branch runs alongside a hot path; both must stamp TTFT."""+ import litellm as litellm_mod++ chunks = [b"event: message_start\ndata: {}\n\n"]+ response = _make_streaming_response(chunks)++ mock_logging_obj = _logging_obj_with_write_once_cst()+ mock_logging_obj.model_call_details = {"model": "claude-haiku-4-5"}+ mock_passthrough_handler = MagicMock()++ original = getattr(litellm_mod, "include_cost_in_streaming_usage", False)+ litellm_mod.include_cost_in_streaming_usage = True+ try:+ with patch.object(+ PassThroughStreamingHandler,+ "_route_streaming_logging_to_handler",+ new=AsyncMock(),+ ):+ async for _ in PassThroughStreamingHandler.chunk_processor(+ response=response,+ request_body={"model": "claude-haiku-4-5"},+ litellm_logging_obj=mock_logging_obj,+ endpoint_type=EndpointType.ANTHROPIC,+ start_time=datetime.now(),+ passthrough_success_handler_obj=mock_passthrough_handler,+ url_route="/v1/messages",+ ):+ pass+ finally:+ litellm_mod.include_cost_in_streaming_usage = original++ mock_logging_obj._update_completion_start_time.assert_called_once()++def test_convert_raw_bytes_survives_truncated_multibyte_sequence():"""A stream cut mid-multibyte-sequence (client disconnect) must still decodevia errors="replace" so the usage events already received are logged, insteaddiff --git a/tests/test_litellm/responses/test_streaming_iterator.py b/tests/test_litellm/responses/test_streaming_iterator.pynew file mode 100644index 00000000000..3e4b07fce18--- /dev/null+++ b/tests/test_litellm/responses/test_streaming_iterator.py@@ -0,0 +1,124 @@+"""Regression tests for LIT-4185 — /v1/responses streaming must stamp+completion_start_time on the first chunk so downstream TTFT consumers+(Prometheus, OTEL, SpendLogs completionStartTime) do not fall back to+completion_start_time = end_time."""++import json+from datetime import datetime+from unittest.mock import Mock++import pytest++from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj+from litellm.llms.base_llm.responses.transformation import BaseResponsesAPIConfig+from litellm.responses.streaming_iterator import ResponsesAPIStreamingIterator+from litellm.types.llms.openai import (+ ResponseCompletedEvent,+ ResponsesAPIResponse,+ ResponsesAPIStreamEvents,+)+++def _sse_event(payload: dict) -> bytes:+ return f"data: {json.dumps(payload)}\n\n".encode("utf-8")+++def _make_iterator(+ *,+ sse_events: list[bytes],+ logging_obj: LiteLLMLoggingObj,+) -> ResponsesAPIStreamingIterator:+ async def aiter_bytes():+ for evt in sse_events:+ yield evt++ mock_response = Mock()+ mock_response.headers = {}+ mock_response.aiter_bytes = aiter_bytes++ mock_config = Mock(spec=BaseResponsesAPIConfig)+ mock_responses_api_response = Mock(spec=ResponsesAPIResponse)+ mock_responses_api_response.id = "resp_ttft"++ def _transform(model, parsed_chunk, logging_obj):+ evt_type = parsed_chunk.get("type")+ if evt_type == "response.completed":+ completed = Mock(spec=ResponseCompletedEvent)+ completed.type = ResponsesAPIStreamEvents.RESPONSE_COMPLETED+ completed.response = mock_responses_api_response+ return completed+ stub = Mock()+ stub.type = evt_type+ return stub++ mock_config.transform_streaming_response.side_effect = _transform++ return ResponsesAPIStreamingIterator(+ response=mock_response,+ model="gpt-4o-mini",+ responses_api_provider_config=mock_config,+ logging_obj=logging_obj,+ litellm_metadata={},+ custom_llm_provider="openai",+ )+++async def test_responses_streaming_stamps_completion_start_time_on_first_chunk():+ """Without the fix, `logging_obj.completion_start_time` stays None across the+ entire stream and _success_handler_helper_fn falls back to end_time — collapsing+ the reported TTFT to full generation time."""+ logging_obj = Mock(spec=LiteLLMLoggingObj)+ logging_obj.completion_start_time = None+ logging_obj.model_call_details = {"litellm_params": {}}+ stamped: list[datetime] = []++ def _update(*, completion_start_time):+ stamped.append(completion_start_time)+ logging_obj.completion_start_time = completion_start_time+ logging_obj.model_call_details["completion_start_time"] = completion_start_time++ logging_obj._update_completion_start_time.side_effect = _update++ iterator = _make_iterator(+ sse_events=[+ _sse_event({"type": "response.created"}),+ _sse_event({"type": "response.output_text.delta", "delta": "hi"}),+ _sse_event({"type": "response.completed"}),+ ],+ logging_obj=logging_obj,+ )++ async for _ in iterator:+ pass++ assert len(stamped) == 1, (+ f"Expected exactly one first-chunk stamp; got {len(stamped)}. "+ "Later chunks must not re-stamp completion_start_time."+ )+ assert isinstance(stamped[0], datetime)+++async def test_responses_streaming_does_not_reset_prior_completion_start_time():+ """If `completion_start_time` is already set (e.g. by an outer wrapper), the+ iterator must not overwrite it — otherwise TTFT would collapse to+ time-to-last-chunk under contention."""+ prior = datetime(2020, 1, 1, 0, 0, 0)+ logging_obj = Mock(spec=LiteLLMLoggingObj)+ logging_obj.completion_start_time = prior+ logging_obj.model_call_details = {"litellm_params": {}}++ iterator = _make_iterator(+ sse_events=[+ _sse_event({"type": "response.created"}),+ _sse_event({"type": "response.completed"}),+ ],+ logging_obj=logging_obj,+ )++ async for _ in iterator:+ pass++ logging_obj._update_completion_start_time.assert_not_called()+ assert logging_obj.completion_start_time == prior