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]

Merge remote-tracking branch 'origin/litellm_internal_staging' into litellm_fix_openai_cache_token_details_loss

mateo-berri728824768218
diff --cc litellm/litellm_core_utils/llm_cost_calc/utils.py
index 6f344d687c8,aeef604510b..524190c7950
--- a/litellm/litellm_core_utils/llm_cost_calc/utils.py
+++ b/litellm/litellm_core_utils/llm_cost_calc/utils.py
@@@ -734,8 -745,8 +745,8 @@@ def generic_cost_per_token
video_tokens = prompt_tokens_details["video_tokens"]
# Check for double-counting: sum of details > prompt_tokens means overlap
- total_details = text_tokens + cache_hit + audio_tokens + cache_creation + image_tokens + video_tokens
- has_double_counting = (cache_hit > 0 or cache_creation > 0) and total_details > usage.prompt_tokens
+ total_details: Final = text_tokens + cache_hit + audio_tokens + cache_creation + image_tokens + video_tokens
- has_double_counting: Final = cache_hit > 0 and total_details > usage.prompt_tokens
++ has_double_counting: Final = (cache_hit > 0 or cache_creation > 0) and total_details > usage.prompt_tokens
if (text_tokens == 0 and prompt_tokens_details["image_count"] == 0) or has_double_counting:
text_tokens = usage.prompt_tokens - cache_hit - audio_tokens - cache_creation - image_tokens - video_tokens
diff --cc litellm/litellm_core_utils/streaming_handler.py
index d5a08035bf4,c09c767483d..8c67bfd97cd
--- a/litellm/litellm_core_utils/streaming_handler.py
+++ b/litellm/litellm_core_utils/streaming_handler.py
@@@ -6,20 -6,9 +6,9 @@@ import loggin
import threading
import time
import traceback
+ from collections.abc import AsyncIterator, Callable, Iterator
from dataclasses import dataclass
- from typing import (
- Any,
- AsyncIterator,
- Callable,
- Dict,
- Iterator,
- List,
- NoReturn,
- Optional,
- TypeVar,
- Union,
- cast,
- )
-from typing import Any, Final, NoReturn, Union, cast
++from typing import Any, Final, NoReturn, TypeVar, Union, cast
import anyio
import httpx
@@@ -35,12 -24,8 +24,9 @@@ from litellm.litellm_core_utils.redact_
from litellm.litellm_core_utils.thread_pool_executor import executor
from litellm.types.llms.openai import OpenAIChatCompletionChunk
from litellm.types.router import GenericLiteLLMParams
- from litellm.types.utils import (
- Delta,
- )
- from litellm.types.utils import GenericStreamingChunk as GChunk
from litellm.types.utils import (
+ CompletionTokensDetailsWrapper,
+ Delta,
LlmProviders,
ModelResponse,
ModelResponseStream,
@@@ -2257,21 -2233,7 +2235,21 @@@ class CustomStreamWrapper
return chunk
+_TokenDetails = TypeVar("_TokenDetails", PromptTokensDetailsWrapper, CompletionTokensDetailsWrapper)
+
+
+def _coerce_token_details(
- usage: Union[dict, BaseModel], field: str, details_type: type[_TokenDetails]
++ usage: dict | BaseModel, field: str, details_type: type[_TokenDetails]
+) -> _TokenDetails | None:
+ raw = usage.get(field) if isinstance(usage, dict) else getattr(usage, field, None)
+ if raw is None:
+ return None
+ if isinstance(raw, details_type):
+ return raw
+ return details_type(**(raw if isinstance(raw, dict) else raw.model_dump()))
+
+
- def calculate_total_usage(chunks: List[ModelResponse]) -> Usage:
+ def calculate_total_usage(chunks: list[ModelResponse]) -> Usage:
"""Assume most recent usage chunk has total usage uptil then."""
prompt_tokens: int = 0
completion_tokens: int = 0
@@@ -2287,16 -2247,8 +2265,16 @@@
prompt_tokens = usage.get("prompt_tokens", 0) or 0
if "completion_tokens" in usage:
completion_tokens = usage.get("completion_tokens", 0) or 0
+ prompt_tokens_details = (
+ _coerce_token_details(usage, "prompt_tokens_details", PromptTokensDetailsWrapper)
+ or prompt_tokens_details
+ )
+ completion_tokens_details = (
+ _coerce_token_details(usage, "completion_tokens_details", CompletionTokensDetailsWrapper)
+ or completion_tokens_details
+ )
- returned_usage_chunk = Usage(
+ returned_usage_chunk: Final = Usage(
prompt_tokens=prompt_tokens,
completion_tokens=completion_tokens,
total_tokens=prompt_tokens + completion_tokens,
diff --cc tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.py
index e14b00cfeac,0114db381cf..6edde02769b
--- a/tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.py
+++ b/tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.py
@@@ -994,44 -994,189 +994,232 @@@ def test_cost_field_in_usage_chunks()
assert usage.completion_tokens == 5
+def test_prompt_tokens_details_survive_later_usage_chunk_without_details():
+ """Regression for #34801: a trailing usage chunk that omits
+ `prompt_tokens_details` must not wipe the OpenAI cache-read/cache-write split,
+ otherwise those tokens get re-priced at the uncached input rate."""
+ from litellm.types.utils import PromptTokensDetailsWrapper
+
+ chunk_with_details = ModelResponseStream(
+ id="chatcmpl-1",
+ created=1745513206,
+ model="openai/gpt-5.6-sol",
+ choices=[
+ StreamingChoices(finish_reason=None, index=0, delta=Delta(content="Hi"))
+ ],
+ usage=Usage(
+ prompt_tokens=6017,
+ completion_tokens=4,
+ total_tokens=6021,
+ prompt_tokens_details=PromptTokensDetailsWrapper(
+ cached_tokens=6004, cache_write_tokens=10
+ ),
+ ),
+ )
+ chunk_without_details = ModelResponseStream(
+ id="chatcmpl-1",
+ created=1745513207,
+ model="openai/gpt-5.6-sol",
+ choices=[
+ StreamingChoices(finish_reason="stop", index=0, delta=Delta(content=""))
+ ],
+ usage=Usage(prompt_tokens=6017, completion_tokens=4, total_tokens=6021),
+ )
+
+ chunks = [chunk_with_details, chunk_without_details]
+ usage = ChunkProcessor(chunks=chunks).calculate_usage(
+ chunks=chunks, model="openai/gpt-5.6-sol", completion_output="Hi"
+ )
+
+ assert usage.prompt_tokens == 6017
+ assert usage.prompt_tokens_details is not None
+ assert usage.prompt_tokens_details.cached_tokens == 6004
+ assert usage.prompt_tokens_details.cache_write_tokens == 10
++
++
+ def test_get_combined_tool_content_custom_tool_call():
+ from litellm.litellm_core_utils.streaming_chunk_builder_utils import ChunkProcessor
+ from litellm.types.utils import ChatCompletionMessageCustomToolCall
+
+ processor = ChunkProcessor.__new__(ChunkProcessor)
+ tool_call_chunks = [
+ {
+ "choices": [
+ {
+ "delta": {
+ "tool_calls": [
+ {
+ "index": 0,
+ "id": "call_TBs",
+ "type": "custom",
+ "custom": {"name": "ApplyPatch", "input": ""},
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {"choices": [{"delta": {"tool_calls": [{"index": 0, "custom": {"input": "*** Begin Patch\n"}}]}}]},
+ {"choices": [{"delta": {"tool_calls": [{"index": 0, "custom": {"input": "*** End Patch\n"}}]}}]},
+ ]
+ combined = processor.get_combined_tool_content(tool_call_chunks)
+ assert len(combined) == 1
+ assert isinstance(combined[0], ChatCompletionMessageCustomToolCall)
+ assert combined[0].model_dump() == {
+ "id": "call_TBs",
+ "type": "custom",
+ "custom": {"name": "ApplyPatch", "input": "*** Begin Patch\n*** End Patch\n"},
+ }
+
+
+ def test_get_combined_tool_content_custom_tool_call_without_type_field():
+ """Delta coercion classifies a tool-call chunk as custom from its ``custom`` payload
+ alone (``type`` may never arrive on any chunk). The assembler must use the same
+ evidence; requiring ``type == "custom"`` dropped the whole tool call from the
+ combined message (it matched neither the custom nor the function branch)."""
+ from litellm.litellm_core_utils.streaming_chunk_builder_utils import ChunkProcessor
+ from litellm.types.utils import ChatCompletionMessageCustomToolCall
+
+ processor = ChunkProcessor.__new__(ChunkProcessor)
+ tool_call_chunks = [
+ {
+ "choices": [
+ {
+ "delta": {
+ "tool_calls": [
+ {
+ "index": 0,
+ "id": "call_TBs",
+ "custom": {"name": "ApplyPatch", "input": "*** Begin"},
+ }
+ ]
+ }
+ }
+ ]
+ },
+ {"choices": [{"delta": {"tool_calls": [{"index": 0, "custom": {"input": " Patch"}}]}}]},
+ ]
+ combined = processor.get_combined_tool_content(tool_call_chunks)
+ assert len(combined) == 1
+ assert isinstance(combined[0], ChatCompletionMessageCustomToolCall)
+ assert combined[0].model_dump() == {
+ "id": "call_TBs",
+ "type": "custom",
+ "custom": {"name": "ApplyPatch", "input": "*** Begin Patch"},
+ }
+
+
+ def _tool_call_delta_chunk(tool_call: dict[str, object] | ChatCompletionDeltaToolCall) -> dict[str, object]:
+ return {"choices": [{"delta": {"tool_calls": [tool_call]}}]}
+
+
+ def test_get_combined_tool_content_joins_many_dict_shaped_argument_fragments_in_order():
+ processor = ChunkProcessor.__new__(ChunkProcessor)
+ first_fragments = [f"a{i};" for i in range(300)]
+ second_fragments = [f"b{i};" for i in range(300)]
+ header_chunks = [
+ _tool_call_delta_chunk({"index": 0, "id": "call_a", "type": "function", "function": {"name": "tool_a"}}),
+ _tool_call_delta_chunk({"index": 1, "id": "call_b", "type": "function", "function": {"name": "tool_b"}}),
+ _tool_call_delta_chunk({"index": 2, "id": "call_c", "type": "function", "function": {"name": "tool_c"}}),
+ ]
+ fragment_chunks = [
+ _tool_call_delta_chunk({"index": index, "function": {"arguments": fragment}})
+ for first, second in zip(first_fragments, second_fragments)
+ for index, fragment in ((0, first), (1, second))
+ ]
+
+ combined = processor.get_combined_tool_content(header_chunks + fragment_chunks)
+
+ assert [tool_call.id for tool_call in combined] == ["call_a", "call_b", "call_c"]
+ assert combined[0].function.name == "tool_a"
+ assert combined[0].function.arguments == "".join(first_fragments)
+ assert combined[1].function.name == "tool_b"
+ assert combined[1].function.arguments == "".join(second_fragments)
+ assert combined[2].function.arguments == "{}"
+
+
+ def test_get_combined_tool_content_joins_fragments_across_many_parallel_tool_calls():
+ processor = ChunkProcessor.__new__(ChunkProcessor)
+ indexes = range(40)
+ header_chunks = [
+ _tool_call_delta_chunk(
+ {"index": index, "id": f"call_{index}", "type": "function", "function": {"name": f"tool_{index}"}}
+ )
+ for index in indexes
+ ]
+ fragment_chunks = [
+ _tool_call_delta_chunk({"index": index, "function": {"arguments": f"{index}.{position};"}})
+ for position in range(5)
+ for index in indexes
+ ]
+
+ combined = processor.get_combined_tool_content(header_chunks + fragment_chunks)
+
+ assert [tool_call.id for tool_call in combined] == [f"call_{index}" for index in indexes]
+ for index, tool_call in zip(indexes, combined):
+ assert tool_call.function.arguments == "".join(f"{index}.{position};" for position in range(5))
+
+
+ def test_get_combined_tool_content_joins_many_object_shaped_argument_fragments_in_order():
+ processor = ChunkProcessor.__new__(ChunkProcessor)
+ first_fragments = [f"x{i}|" for i in range(300)]
+ second_fragments = [f"y{i}|" for i in range(300)]
+ header_chunks = [
+ _tool_call_delta_chunk(
+ ChatCompletionDeltaToolCall(
+ id="call_x", type="function", index=0, function=Function(name="tool_x", arguments="")
+ )
+ ),
+ _tool_call_delta_chunk(
+ ChatCompletionDeltaToolCall(
+ id="call_y", type="function", index=1, function=Function(name="tool_y", arguments="")
+ )
+ ),
+ ]
+ fragment_chunks = [
+ _tool_call_delta_chunk(ChatCompletionDeltaToolCall(index=index, function=Function(arguments=fragment)))
+ for first, second in zip(first_fragments, second_fragments)
+ for index, fragment in ((0, first), (1, second))
+ ]
+
+ combined = processor.get_combined_tool_content(header_chunks + fragment_chunks)
+
+ assert [tool_call.id for tool_call in combined] == ["call_x", "call_y"]
+ assert combined[0].function.name == "tool_x"
+ assert combined[0].function.arguments == "".join(first_fragments)
+ assert combined[1].function.name == "tool_y"
+ assert combined[1].function.arguments == "".join(second_fragments)
+
+
+ def test_get_combined_tool_content_joins_many_custom_tool_input_fragments_in_order():
+ from types import SimpleNamespace
+
+ from litellm.types.utils import ChatCompletionMessageCustomToolCall
+
+ processor = ChunkProcessor.__new__(ChunkProcessor)
+ dict_fragments = [f"d{i}," for i in range(200)]
+ object_fragments = [f"o{i}," for i in range(200)]
+ header_chunks = [
+ _tool_call_delta_chunk({"index": 0, "id": "call_d", "type": "custom", "custom": {"name": "apply_patch"}}),
+ _tool_call_delta_chunk(
+ SimpleNamespace(index=1, id="call_o", type="custom", custom=SimpleNamespace(name="run_script", input=""))
+ ),
+ ]
+ fragment_chunks = [
+ _tool_call_delta_chunk(tool_call)
+ for dict_fragment, object_fragment in zip(dict_fragments, object_fragments)
+ for tool_call in (
+ {"index": 0, "custom": {"input": dict_fragment}},
+ SimpleNamespace(index=1, custom=SimpleNamespace(input=object_fragment)),
+ )
+ ]
+
+ combined = processor.get_combined_tool_content(header_chunks + fragment_chunks)
+
+ assert [tool_call.id for tool_call in combined] == ["call_d", "call_o"]
+ assert isinstance(combined[0], ChatCompletionMessageCustomToolCall)
+ assert combined[0].custom.name == "apply_patch"
+ assert combined[0].custom.input == "".join(dict_fragments)
+ assert isinstance(combined[1], ChatCompletionMessageCustomToolCall)
+ assert combined[1].custom.name == "run_script"
+ assert combined[1].custom.input == "".join(object_fragments)