Skip to content
Closed
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
28 changes: 19 additions & 9 deletions litellm/litellm_core_utils/streaming_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -1859,11 +1859,11 @@ def __next__(self) -> "ModelResponseStream":
continue
# add usage as hidden param
if self.sent_last_chunk is True and self.stream_options is None:
usage = calculate_total_usage(chunks=self.chunks)
response_hidden_params_for_final_chunk = cast( # cast-ok: preserve dynamic mapping behavior
dict[str, object], getattr(response, HIDDEN_PARAMS_ATTR)
)
response_hidden_params_for_final_chunk["usage"] = usage
if (reported_usage := _reported_total_usage(chunks=self.chunks)) is not None:
response_hidden_params_for_final_chunk["usage"] = reported_usage
self._last_returned_hidden_params = response_hidden_params_for_final_chunk
# Add MCP metadata to final chunk if present
response = self._add_mcp_metadata_to_final_chunk(response)
Expand Down Expand Up @@ -1960,8 +1960,10 @@ def __next__(self) -> "ModelResponseStream":
if self.received_finish_reason is not None or self.intermittent_finish_reason is not None:
self.chunks.append(processed_chunk)
if self.stream_options is None: # add usage as hidden param
usage = calculate_total_usage(chunks=self.chunks)
processed_chunk.hidden_params["usage"] = usage
self._last_returned_hidden_params = processed_chunk.hidden_params
synthetic_finish_usage: Final = _reported_total_usage(chunks=self.chunks)
if synthetic_finish_usage is not None:
self._last_returned_hidden_params["usage"] = synthetic_finish_usage
## LOGGING
executor.submit(
self.run_success_logging_and_cache_storage,
Expand Down Expand Up @@ -2075,11 +2077,11 @@ async def __anext__(self) -> "ModelResponseStream":

# add usage as hidden param
if self.sent_last_chunk is True and self.stream_options is None:
usage = calculate_total_usage(chunks=self.chunks)
processed_chunk_hidden_params = cast( # cast-ok: preserve dynamic mapping behavior
dict[str, object], getattr(processed_chunk, HIDDEN_PARAMS_ATTR)
)
processed_chunk_hidden_params["usage"] = usage
if (reported_usage := _reported_total_usage(chunks=self.chunks)) is not None:
processed_chunk_hidden_params["usage"] = reported_usage
self._last_returned_hidden_params = processed_chunk_hidden_params

# Call post-call streaming deployment hook for final chunk
Expand Down Expand Up @@ -2234,11 +2236,13 @@ async def _finalize_completed_stream(self, cache_hit: bool) -> "ModelResponseStr
if self.received_finish_reason is not None or self.intermittent_finish_reason is not None:
self.chunks.append(processed_chunk)
if self.stream_options is None:
usage: Final = calculate_total_usage(chunks=self.chunks)
usage: Final = _reported_total_usage(chunks=self.chunks)
processed_chunk_hidden_params: Final = cast( # cast-ok: preserve dynamic mapping behavior
dict[str, object], getattr(processed_chunk, HIDDEN_PARAMS_ATTR)
)
processed_chunk_hidden_params["usage"] = usage
self._last_returned_hidden_params = processed_chunk_hidden_params
if usage is not None:
processed_chunk_hidden_params["usage"] = usage
# see sync __next__'s sibling branch: deliberately do NOT restore
# here - this chunk is still this call's own data, and restoring
# before returning it would corrupt the caller's own log
Expand Down Expand Up @@ -2468,7 +2472,13 @@ def _coerce_token_details(
return details_type(**(raw if isinstance(raw, dict) else raw.model_dump()))


def calculate_total_usage(chunks: list[ModelResponse]) -> Usage:
def _reported_total_usage(chunks: Sequence[ModelResponse | ModelResponseStream]) -> Usage | None:
if not any("usage" in chunk and chunk["usage"] is not None for chunk in chunks):
return None
return calculate_total_usage(chunks)


def calculate_total_usage(chunks: Sequence[ModelResponse | ModelResponseStream]) -> Usage:
"""Assume most recent usage chunk has total usage uptil then."""
from litellm.litellm_core_utils.streaming_chunk_builder_utils import (
attach_cache_creation_token_details,
Expand Down
93 changes: 92 additions & 1 deletion tests/unit/litellm_core_utils/test_streaming_handler.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import asyncio
import json
import time
from typing import Final, NoReturn, Optional
from typing import Final, Literal, NoReturn, Optional
from unittest.mock import AsyncMock, MagicMock, Mock, patch

import pytest
Expand Down Expand Up @@ -2298,6 +2298,97 @@ def test_raise_on_model_repetition_tolerates_empty_choices(
wrapper.raise_on_model_repetition()


@pytest.mark.parametrize("sync_mode", [True, False])
@pytest.mark.parametrize("finish", ["separate", "content", "absent"])
@pytest.mark.parametrize("reported_tokens", [None, 0, 17])
@pytest.mark.parametrize("late_usage", [False, True])
@pytest.mark.asyncio
async def test_stream_hidden_usage_preserves_reported_counts_or_estimates(
logging_obj: Logging,
sync_mode: bool,
finish: Literal["separate", "content", "absent"],
reported_tokens: int | None,
late_usage: bool,
) -> None:
model: Final = "gpt-6.1-sol"
reported_usage: Final = (
None
if reported_tokens is None
else Usage(
prompt_tokens=reported_tokens,
completion_tokens=reported_tokens,
total_tokens=2 * reported_tokens,
)
)
content_chunk: Final = ModelResponseStream(
id="chatcmpl-usage-regression",
created=1,
model=model,
choices=[
StreamingChoices(
index=0,
delta=Delta(role="assistant", content="Hello from the streaming response"),
finish_reason="stop" if finish == "content" else None,
)
],
usage=None if late_usage else reported_usage,
)
finish_chunks: Final = (
(
ModelResponseStream(
id=content_chunk.id,
created=content_chunk.created,
model=model,
choices=[StreamingChoices(index=0, delta=Delta(content=""), finish_reason="stop")],
),
)
if finish == "separate"
else ()
)
usage_chunks: Final = (
(
ModelResponseStream(
id=content_chunk.id,
created=content_chunk.created,
model=model,
choices=[],
usage=reported_usage,
),
)
if late_usage and reported_usage is not None
else ()
)
source_chunks: Final = (content_chunk, *finish_chunks, *usage_chunks)
expected: Final = litellm.stream_chunk_builder(
chunks=[chunk.model_copy(deep=True) for chunk in source_chunks],
messages=logging_obj.messages,
)
assert expected is not None
wrapper: Final = CustomStreamWrapper(
completion_stream=ModelResponseListIterator(model_responses=source_chunks),
model=model,
logging_obj=logging_obj,
custom_llm_provider="openai",
stream_options=None,
)
received: Final = tuple(wrapper) if sync_mode else tuple([chunk async for chunk in wrapper])
hidden_usage: Final = received[-1].hidden_params.get("usage")
assert isinstance(hidden_usage, Usage)
assembled: Final = litellm.stream_chunk_builder(chunks=wrapper.chunks, messages=logging_obj.messages)
assert assembled is not None
assert assembled.choices[0].message.content == expected.choices[0].message.content
for usage in (hidden_usage, assembled.usage):
assert usage.prompt_tokens == expected.usage.prompt_tokens
assert usage.completion_tokens == expected.usage.completion_tokens
assert usage.total_tokens == expected.usage.total_tokens
if reported_usage is None:
assert usage.prompt_tokens > 0
assert usage.completion_tokens > 0
else:
assert usage.prompt_tokens == reported_usage.prompt_tokens
assert usage.completion_tokens == reported_usage.completion_tokens


def test_usage_chunk_after_finish_reason_updates_hidden_params(logging_obj):
"""
Test that provider-reported usage from a post-finish_reason chunk
Expand Down
Loading