Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions litellm/proxy/pass_through_endpoints/streaming_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@


class 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())

@staticmethod
async def chunk_processor(
response: httpx.Response,
Expand Down Expand Up @@ -58,6 +63,7 @@ async def chunk_processor(
# 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 chunk
else:
# ``cost_injection_active`` already requires ``model_name`` to
Expand All @@ -67,6 +73,7 @@ async def chunk_processor(
resolved_model_name: str = model_name
async 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:
Comment on lines 74 to 77

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 The identical two-line stamp block appears in both the hot path and the cost-injection branch. The guard could live once, right after raw_bytes.append(chunk), before the if endpoint_type branch — removing the duplication without changing behavior.

Suggested change
async for chunk in response.aiter_bytes():
raw_bytes.append(chunk)
if litellm_logging_obj.completion_start_time is None:
litellm_logging_obj._update_completion_start_time(completion_start_time=datetime.now())
if endpoint_type == EndpointType.VERTEX_AI:
async for chunk in response.aiter_bytes():
raw_bytes.append(chunk)
if litellm_logging_obj.completion_start_time is None:
litellm_logging_obj._update_completion_start_time(
completion_start_time=datetime.now()
)
if endpoint_type == EndpointType.VERTEX_AI:

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

if "streamRawPredict" in url_route or "rawPredict" in url_route:
modified_chunk = ProxyBaseLLMRequestProcessing._process_chunk_with_cost_injection(
Expand Down
3 changes: 3 additions & 0 deletions litellm/responses/streaming_iterator.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,9 @@ def _process_chunk(self, chunk) -> Optional[Any]:
self.finished = True
return 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 chunk
parsed_chunk = json.loads(chunk)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ async def mock_aiter_bytes():

mock_logging_obj = Mock(spec=LiteLLMLoggingObj)
mock_logging_obj.model_call_details = {"litellm_params": {}}
mock_logging_obj.completion_start_time = None
mock_config = Mock(spec=BaseResponsesAPIConfig)

mock_responses_api_response = Mock(spec=ResponsesAPIResponse)
Expand Down Expand Up @@ -107,6 +108,7 @@ def test_process_chunk_with_response_completed_event(self):
mock_response.headers = {}
mock_logging_obj = Mock(spec=LiteLLMLoggingObj)
mock_logging_obj.model_call_details = {"litellm_params": {}}
mock_logging_obj.completion_start_time = None
mock_config = Mock(spec=BaseResponsesAPIConfig)

# Create a mock ResponsesAPIResponse for the completed event
Expand Down Expand Up @@ -179,6 +181,7 @@ def test_process_chunk_with_delta_event_no_id_update(self):
mock_response.headers = {}
mock_logging_obj = Mock(spec=LiteLLMLoggingObj)
mock_logging_obj.model_call_details = {"litellm_params": {}}
mock_logging_obj.completion_start_time = None
mock_config = Mock(spec=BaseResponsesAPIConfig)

# Create a mock OutputTextDeltaEvent (not a completed event)
Expand Down Expand Up @@ -239,6 +242,7 @@ def test_process_chunk_handles_invalid_json(self):
mock_response.headers = {}
mock_logging_obj = Mock(spec=LiteLLMLoggingObj)
mock_logging_obj.model_call_details = {"litellm_params": {}}
mock_logging_obj.completion_start_time = None
mock_config = Mock(spec=BaseResponsesAPIConfig)

# Create the iterator instance
Expand All @@ -265,6 +269,7 @@ def test_process_chunk_handles_done_marker(self):
mock_response.headers = {}
mock_logging_obj = Mock(spec=LiteLLMLoggingObj)
mock_logging_obj.model_call_details = {"litellm_params": {}}
mock_logging_obj.completion_start_time = None
mock_config = Mock(spec=BaseResponsesAPIConfig)

# Create the iterator instance
Expand All @@ -291,6 +296,7 @@ def test_process_chunk_handles_empty_chunk(self):
mock_response.headers = {}
mock_logging_obj = Mock(spec=LiteLLMLoggingObj)
mock_logging_obj.model_call_details = {"litellm_params": {}}
mock_logging_obj.completion_start_time = None
mock_config = Mock(spec=BaseResponsesAPIConfig)

# Create the iterator instance
Expand Down Expand Up @@ -329,6 +335,7 @@ def test_handle_logging_completed_response_with_unpickleable_objects(self):
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 = None
mock_logging_obj.async_success_handler = Mock()
mock_logging_obj.success_handler = Mock()
mock_config = Mock(spec=BaseResponsesAPIConfig)
Expand Down Expand Up @@ -397,6 +404,7 @@ async def mock_aiter_bytes():

mock_logging_obj = Mock(spec=LiteLLMLoggingObj)
mock_logging_obj.model_call_details = {"litellm_params": {}}
mock_logging_obj.completion_start_time = None
mock_logging_obj.async_failure_handler = Mock()
mock_logging_obj.failure_handler = Mock()

Expand Down Expand Up @@ -457,6 +465,7 @@ def mock_iter_bytes():

mock_logging_obj = Mock(spec=LiteLLMLoggingObj)
mock_logging_obj.model_call_details = {"litellm_params": {}}
mock_logging_obj.completion_start_time = None
mock_logging_obj.async_failure_handler = Mock()
mock_logging_obj.failure_handler = Mock()

Expand Down Expand Up @@ -505,6 +514,7 @@ def test_process_chunk_response_failed_calls_failure_handler(self):
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 = None
mock_logging_obj.async_failure_handler = Mock()
mock_logging_obj.failure_handler = Mock()
mock_logging_obj.async_success_handler = Mock()
Expand Down Expand Up @@ -587,6 +597,7 @@ def test_process_chunk_response_incomplete_calls_success_handler(self):
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 = None
mock_logging_obj.async_failure_handler = Mock()
mock_logging_obj.failure_handler = Mock()
mock_logging_obj.async_success_handler = Mock()
Expand Down
5 changes: 5 additions & 0 deletions tests/llm_responses_api_testing/test_responses_hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ def __init__(self):
self.last_success_kwargs = None
self.last_async_success_kwargs = None
self.start_time = datetime.now()
self.completion_start_time = None
self.model_call_details = {"litellm_params": {}}

# Signature alignment with Logging handlers
Expand All @@ -51,6 +52,10 @@ def failure_handler(self, *args, **kwargs):
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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ async def mock_aiter_bytes():
# Setup logging object with model info
litellm_logging_obj = MagicMock(spec=LiteLLMLoggingObj)
litellm_logging_obj.model_call_details = {"model": "claude-sonnet-4@20250514"}
litellm_logging_obj.completion_start_time = None
litellm_logging_obj.async_success_handler = AsyncMock()

request_body = {"model": "claude-sonnet-4@20250514"}
Expand Down Expand Up @@ -135,6 +136,7 @@ async def mock_aiter_bytes():

litellm_logging_obj = MagicMock(spec=LiteLLMLoggingObj)
litellm_logging_obj.model_call_details = {"model": "claude-sonnet-4@20250514"}
litellm_logging_obj.completion_start_time = None
litellm_logging_obj.async_success_handler = AsyncMock()

request_body = {"model": "claude-sonnet-4@20250514"}
Expand Down Expand Up @@ -196,6 +198,7 @@ async def mock_aiter_bytes():

litellm_logging_obj = MagicMock(spec=LiteLLMLoggingObj)
litellm_logging_obj.model_call_details = {"model": "claude-sonnet-4@20250514"}
litellm_logging_obj.completion_start_time = None
litellm_logging_obj.async_success_handler = AsyncMock()

request_body = {"model": "claude-sonnet-4@20250514"}
Expand Down Expand Up @@ -250,6 +253,7 @@ async def mock_aiter_bytes():

litellm_logging_obj = MagicMock(spec=LiteLLMLoggingObj)
litellm_logging_obj.model_call_details = {}
litellm_logging_obj.completion_start_time = None
litellm_logging_obj.async_success_handler = AsyncMock()

# Test model extraction from request body
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,126 @@ def _capture(async_coroutine):
assert 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


@pytest.mark.asyncio
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)


@pytest.mark.asyncio
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


@pytest.mark.asyncio
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 decode
via errors="replace" so the usage events already received are logged, instead
Expand Down
Loading
Loading