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]

fix(streaming): price partial-stream spend rows at the real model and keep prompt and cache fields

mateo-berria3b676278869
diff --git a/litellm/litellm_core_utils/streaming_handler.py b/litellm/litellm_core_utils/streaming_handler.py
index 485091bccd0..3565872f09e 100644
--- a/litellm/litellm_core_utils/streaming_handler.py
+++ b/litellm/litellm_core_utils/streaming_handler.py
@@ -2315,10 +2315,18 @@ class CustomStreamWrapper:
if self.logging_obj is None or not self.chunks:
return
try:
- partial_response: Final = litellm.stream_chunk_builder(chunks=self.chunks)
+ partial_response: Final = litellm.stream_chunk_builder(
+ chunks=self.chunks,
+ messages=self.messages if isinstance(self.messages, list) else None,
+ )
+ if partial_response is None:
+ return
usage: Final = cast(Usage | None, getattr(partial_response, "usage", None))
if usage is None:
return
+ if self.model:
+ partial_response.model = self.model
+ zero_fill_missing_cache_usage_fields(usage)
self.logging_obj.model_call_details["combined_usage_object"] = usage
self.logging_obj.model_call_details["response_cost"] = (
self.logging_obj._response_cost_calculator(result=partial_response) or 0.0
@@ -2439,6 +2447,15 @@ class CustomStreamWrapper:
return chunk
+def zero_fill_missing_cache_usage_fields(usage: Usage) -> None:
+ if getattr(usage, "cache_creation_input_tokens", None) is None:
+ usage.cache_creation_input_tokens = 0 # rebind-ok: in-place zero-fill is the contract
+ if getattr(usage, "cache_read_input_tokens", None) is None:
+ usage.cache_read_input_tokens = 0 # rebind-ok: in-place zero-fill is the contract
+ if usage.prompt_tokens_details is None:
+ usage.prompt_tokens_details = PromptTokensDetailsWrapper(cached_tokens=0) # rebind-ok: zero-fill in place
+
+
_TokenDetails = TypeVar("_TokenDetails", PromptTokensDetailsWrapper, CompletionTokensDetailsWrapper)
diff --git a/litellm/proxy/common_request_processing.py b/litellm/proxy/common_request_processing.py
index a0b69ecb0bf..d430d776350 100644
--- a/litellm/proxy/common_request_processing.py
+++ b/litellm/proxy/common_request_processing.py
@@ -43,6 +43,9 @@ from litellm.litellm_core_utils.llm_response_utils.get_headers import (
get_response_headers,
)
from litellm.litellm_core_utils.safe_json_dumps import safe_dumps
+from litellm.litellm_core_utils.streaming_handler import (
+ zero_fill_missing_cache_usage_fields,
+)
from litellm.proxy._types import ProxyException, UserAPIKeyAuth
from litellm.proxy.auth.auth_checks import can_key_call_resolved_model
from litellm.proxy.auth.auth_utils import check_response_size_is_safe
@@ -324,6 +327,12 @@ async def _bill_partial_streamed_spend_on_disconnect(request_data: dict, respons
return False
if partial_response is None:
return False
+ wrapper_model: Final = getattr(response, "model", None)
+ if isinstance(wrapper_model, str) and wrapper_model:
+ partial_response.model = wrapper_model
+ partial_usage: Final = getattr(partial_response, "usage", None)
+ if isinstance(partial_usage, Usage):
+ zero_fill_missing_cache_usage_fields(partial_usage)
try:
await logging_obj.dispatch_success_handlers(
partial_response,
diff --git a/tests/test_litellm/litellm_core_utils/test_streaming_handler.py b/tests/test_litellm/litellm_core_utils/test_streaming_handler.py
index 05b44fffbc5..a550160cd73 100644
--- a/tests/test_litellm/litellm_core_utils/test_streaming_handler.py
+++ b/tests/test_litellm/litellm_core_utils/test_streaming_handler.py
@@ -3388,6 +3388,110 @@ def test_record_partial_usage_for_failure_noop_without_chunks():
assert "combined_usage_object" not in logging_obj.model_call_details
+def _wrapper_with_partial_chunks(
+ chunk_model: str,
+ usage: Optional[Usage] = None,
+ model: str = "gpt-4o-mini",
+ custom_llm_provider: str = "openai",
+) -> tuple:
+ logging_obj = Logging(
+ model=model,
+ messages=[{"role": "user", "content": "Tell me a long story"}],
+ stream=True,
+ call_type="completion",
+ start_time=time.time(),
+ litellm_call_id="partial-usage-alias",
+ function_id="1245",
+ )
+ logging_obj.model_call_details["custom_llm_provider"] = custom_llm_provider
+ logging_obj.optional_params = {}
+ wrapper = CustomStreamWrapper(
+ completion_stream=None,
+ model=model,
+ logging_obj=logging_obj,
+ custom_llm_provider=custom_llm_provider,
+ )
+ wrapper.chunks = [
+ ModelResponseStream(
+ id="chatcmpl-partial-alias-1",
+ created=1742056047,
+ model=chunk_model,
+ object="chat.completion.chunk",
+ choices=[
+ StreamingChoices(
+ finish_reason=None,
+ index=0,
+ delta=Delta(
+ content="The Roman Empire began when", role="assistant"
+ ),
+ )
+ ],
+ usage=usage,
+ )
+ ]
+ return wrapper, logging_obj
+
+
+def test_record_partial_usage_for_failure_prices_alias_restamped_chunks_at_real_model():
+ wrapper, logging_obj = _wrapper_with_partial_chunks(
+ chunk_model="bedrock-claude-opus-5",
+ usage=Usage(prompt_tokens=40, completion_tokens=5, total_tokens=45),
+ model="us.anthropic.claude-opus-5",
+ custom_llm_provider="bedrock",
+ )
+ assert "bedrock/bedrock-claude-opus-5" not in litellm.model_cost
+
+ wrapper._record_partial_usage_for_failure()
+
+ stashed = logging_obj.model_call_details["combined_usage_object"]
+ assert stashed.completion_tokens == 5
+ rates = litellm.model_cost["us.anthropic.claude-opus-5"]
+ expected = 40 * rates["input_cost_per_token"] + 5 * rates["output_cost_per_token"]
+ assert logging_obj.model_call_details["response_cost"] == pytest.approx(expected)
+
+
+def test_record_partial_usage_for_failure_counts_prompt_tokens_from_request_messages():
+ wrapper, logging_obj = _wrapper_with_partial_chunks(chunk_model="my-public-alias")
+
+ wrapper._record_partial_usage_for_failure()
+
+ stashed = logging_obj.model_call_details["combined_usage_object"]
+ assert stashed.prompt_tokens > 0
+
+
+def test_record_partial_usage_for_failure_zero_fills_missing_cache_fields():
+ wrapper, logging_obj = _wrapper_with_partial_chunks(chunk_model="gpt-4o-mini")
+
+ wrapper._record_partial_usage_for_failure()
+
+ stashed = logging_obj.model_call_details["combined_usage_object"]
+ assert stashed.cache_creation_input_tokens == 0
+ assert stashed.cache_read_input_tokens == 0
+ assert stashed.prompt_tokens_details is not None
+ assert stashed.prompt_tokens_details.cached_tokens == 0
+
+
+def test_record_partial_usage_for_failure_keeps_cache_values_recovered_from_chunks():
+ recovered = Usage(
+ prompt_tokens=40,
+ completion_tokens=5,
+ total_tokens=45,
+ cache_read_input_tokens=7,
+ cache_creation_input_tokens=3,
+ )
+ wrapper, logging_obj = _wrapper_with_partial_chunks(
+ chunk_model="gpt-4o-mini", usage=recovered
+ )
+
+ wrapper._record_partial_usage_for_failure()
+
+ stashed = logging_obj.model_call_details["combined_usage_object"]
+ assert stashed.cache_read_input_tokens == 7
+ assert stashed.cache_creation_input_tokens == 3
+ assert stashed.prompt_tokens_details is not None
+ assert stashed.prompt_tokens_details.cached_tokens == 7
+
+
@pytest.mark.parametrize("sync_mode", [True, False])
@pytest.mark.asyncio
async def test_stream_chunk_builder_raise_at_end_of_stream_still_recovers_usage(
diff --git a/tests/test_litellm/proxy/test_common_request_processing.py b/tests/test_litellm/proxy/test_common_request_processing.py
index 510fb977a61..609d0dfe1b6 100644
--- a/tests/test_litellm/proxy/test_common_request_processing.py
+++ b/tests/test_litellm/proxy/test_common_request_processing.py
@@ -5519,6 +5519,91 @@ class TestStreamingClientDisconnectBilling:
proxy_logging_obj._arelease_max_parallel_requests_on_disconnect.assert_awaited_once()
+ async def _bill_and_collect_success_event(self, prepare=None):
+ recorder = _RecordingSuccessLogger()
+ original_callbacks = litellm.callbacks
+ litellm.callbacks = [recorder]
+ try:
+ response = await self._start_partial_stream()
+ if prepare is not None:
+ prepare(response)
+ billed = await _bill_partial_streamed_spend_on_disconnect(
+ {"litellm_logging_obj": response.logging_obj}, response
+ )
+ assert billed is True
+ for _ in range(50):
+ if recorder.success_events:
+ break
+ await asyncio.sleep(0.1)
+ finally:
+ litellm.callbacks = original_callbacks
+ assert len(recorder.success_events) == 1
+ return recorder.success_events[0]
+
+ @pytest.mark.asyncio
+ async def test_disconnect_billing_prices_alias_restamped_chunks_at_real_model(self):
+ assert "openai/my-public-alias" not in litellm.model_cost
+
+ def restamp_chunks_to_alias(response):
+ for chunk in response.chunks:
+ chunk.model = "my-public-alias"
+
+ event = await self._bill_and_collect_success_event(restamp_chunks_to_alias)
+
+ assert event["response_obj"].model == "gpt-4o-mini"
+ standard_logging_object = event["kwargs"]["standard_logging_object"]
+ assert standard_logging_object["response_cost"] > 0.0
+
+ @pytest.mark.asyncio
+ async def test_disconnect_billing_zero_fills_missing_cache_fields(self):
+ event = await self._bill_and_collect_success_event()
+
+ usage = event["response_obj"].usage
+ assert getattr(usage, "cache_creation_input_tokens", None) == 0
+ assert getattr(usage, "cache_read_input_tokens", None) == 0
+ assert usage.prompt_tokens_details is not None
+ assert usage.prompt_tokens_details.cached_tokens == 0
+
+ @pytest.mark.asyncio
+ async def test_disconnect_billing_keeps_cache_values_recovered_from_chunks(self):
+ from litellm.types.utils import (
+ Delta,
+ ModelResponseStream,
+ StreamingChoices,
+ Usage,
+ )
+
+ def append_usage_chunk(response):
+ response.chunks.append(
+ ModelResponseStream(
+ id=response.chunks[0].id,
+ model="gpt-4o-mini",
+ object="chat.completion.chunk",
+ choices=[
+ StreamingChoices(
+ finish_reason=None,
+ index=0,
+ delta=Delta(content=" and more", role="assistant"),
+ )
+ ],
+ usage=Usage(
+ prompt_tokens=40,
+ completion_tokens=5,
+ total_tokens=45,
+ cache_read_input_tokens=7,
+ cache_creation_input_tokens=3,
+ ),
+ )
+ )
+
+ event = await self._bill_and_collect_success_event(append_usage_chunk)
+
+ usage = event["response_obj"].usage
+ assert getattr(usage, "cache_read_input_tokens", None) == 7
+ assert getattr(usage, "cache_creation_input_tokens", None) == 3
+ assert usage.prompt_tokens_details is not None
+ assert usage.prompt_tokens_details.cached_tokens == 7
+
def _apply_stream_usage_tracking(
data: dict,