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: normalize provider-specific cache token fields in OTel v2 usage (#39202)

yucheng-berri4b87fd5718ed
diff --git a/litellm/integrations/otel/model/payloads.py b/litellm/integrations/otel/model/payloads.py
index d35405538f6..e8ed269f6cb 100644
--- a/litellm/integrations/otel/model/payloads.py
+++ b/litellm/integrations/otel/model/payloads.py
@@ -6,6 +6,7 @@ import json
from collections.abc import Mapping
from dataclasses import dataclass, field
from enum import Enum
+from types import MappingProxyType
from typing import TYPE_CHECKING, ClassVar, Final, cast
from urllib.parse import urlsplit
@@ -62,6 +63,31 @@ if TYPE_CHECKING:
# --- typed sub-structures ---------------------------------------------------- #
+def _cache_token_value(*values: object) -> int | None:
+ explicit_zero = False
+ invalid_before_zero = False
+ for raw_value in values:
+ if raw_value is None:
+ continue
+ if isinstance(raw_value, bool):
+ parsed = None
+ else:
+ try:
+ parsed = as_int(raw_value)
+ except (OverflowError, ValueError):
+ parsed = None
+ if parsed is None:
+ if not explicit_zero:
+ invalid_before_zero = True
+ elif parsed > 0:
+ return parsed
+ elif parsed == 0:
+ explicit_zero = True
+ elif not explicit_zero:
+ invalid_before_zero = True
+ return 0 if explicit_zero and not invalid_before_zero else None
+
+
@dataclass(frozen=True)
class LLMRequestParams:
temperature: float | None = None
@@ -104,12 +130,25 @@ class LLMUsage:
metadata: Final[Mapping[str, object]] = payload.get("metadata") or {}
raw_usage: Final = metadata.get("usage_object")
usage_object: Final[Mapping[str, object]] = raw_usage if isinstance(raw_usage, Mapping) else {}
+ raw_details: Final = usage_object.get("prompt_tokens_details")
+ prompt_details: Final[Mapping[str, object]] = (
+ raw_details if isinstance(raw_details, Mapping) else MappingProxyType({})
+ )
return cls(
input_tokens=as_int(payload.get("prompt_tokens")),
output_tokens=as_int(payload.get("completion_tokens")),
total_tokens=as_int(payload.get("total_tokens")),
- cache_creation_input_tokens=as_int(usage_object.get("cache_creation_input_tokens")),
- cache_read_input_tokens=as_int(usage_object.get("cache_read_input_tokens")),
+ cache_creation_input_tokens=_cache_token_value(
+ usage_object.get("cache_creation_input_tokens"),
+ prompt_details.get("cache_write_tokens"),
+ prompt_details.get("cache_creation_tokens"),
+ prompt_details.get("cache_creation_input_tokens"),
+ ),
+ cache_read_input_tokens=_cache_token_value(
+ usage_object.get("cache_read_input_tokens"),
+ prompt_details.get("cached_tokens"),
+ usage_object.get("prompt_cache_hit_tokens"),
+ ),
)
diff --git a/tests/test_litellm/integrations/otel/test_otel_v2_sources_of_truth.py b/tests/test_litellm/integrations/otel/test_otel_v2_sources_of_truth.py
index ca628aa3405..99d706a9c44 100644
--- a/tests/test_litellm/integrations/otel/test_otel_v2_sources_of_truth.py
+++ b/tests/test_litellm/integrations/otel/test_otel_v2_sources_of_truth.py
@@ -541,6 +541,74 @@ def test_llm_call_adapter_extracts_cache_tokens_from_usage_object():
assert data.usage.cache_read_input_tokens == 3
+def test_llm_call_adapter_normalizes_nested_cache_tokens():
+ cases: Final = (
+ ({"prompt_tokens_details": {"cached_tokens": 3}}, 3, None),
+ ({"prompt_cache_hit_tokens": 11}, 11, None),
+ ({"prompt_tokens_details": {"cache_write_tokens": 7}}, None, 7),
+ ({"prompt_tokens_details": {"cache_creation_tokens": 13}}, None, 13),
+ ({"prompt_tokens_details": {"cache_creation_input_tokens": 17}}, None, 17),
+ )
+ for usage_object, expected_read, expected_creation in cases:
+ case_payload = _sample_payload(metadata={"usage_object": usage_object})
+ data = LLMCallSpanData.from_standard_logging_payload(case_payload)
+ assert data.usage.cache_read_input_tokens == expected_read
+ assert data.usage.cache_creation_input_tokens == expected_creation
+
+
+def test_llm_call_adapter_prefers_nested_count_over_zero_top_level():
+ payload = _sample_payload(
+ metadata={
+ "usage_object": {
+ "cache_read_input_tokens": 0,
+ "cache_creation_input_tokens": 0,
+ "prompt_tokens_details": {"cached_tokens": 5, "cache_write_tokens": 7},
+ }
+ }
+ )
+ data = LLMCallSpanData.from_standard_logging_payload(payload)
+ assert data.usage.cache_read_input_tokens == 5
+ assert data.usage.cache_creation_input_tokens == 7
+
+
+def test_llm_call_adapter_ignores_invalid_cache_values_before_valid_fallbacks():
+ payload = _sample_payload(
+ metadata={
+ "usage_object": {
+ "cache_read_input_tokens": -1,
+ "cache_creation_input_tokens": "5.0",
+ "prompt_tokens_details": {"cached_tokens": 5, "cache_write_tokens": 7},
+ }
+ }
+ )
+ data = LLMCallSpanData.from_standard_logging_payload(payload)
+ assert data.usage.cache_read_input_tokens == 5
+ assert data.usage.cache_creation_input_tokens == 7
+
+
+def test_llm_call_adapter_ignores_non_finite_cache_values():
+ payload = _sample_payload(
+ metadata={
+ "usage_object": {
+ "prompt_tokens_details": {"cached_tokens": float("nan")},
+ }
+ }
+ )
+ data = LLMCallSpanData.from_standard_logging_payload(payload)
+ assert data.usage.cache_read_input_tokens is None
+
+
+def test_llm_call_adapter_preserves_explicit_zero_and_omits_missing_cache_tokens():
+ for usage_object, expected_read, expected_creation in (
+ ({"prompt_tokens_details": {"cached_tokens": 0}}, 0, None),
+ ({}, None, None),
+ ):
+ case_payload = _sample_payload(metadata={"usage_object": usage_object})
+ data = LLMCallSpanData.from_standard_logging_payload(case_payload)
+ assert data.usage.cache_read_input_tokens == expected_read
+ assert data.usage.cache_creation_input_tokens == expected_creation
+
+
def test_llm_call_adapter_cache_tokens_none_without_usage_object():
data = LLMCallSpanData.from_standard_logging_payload(_sample_payload())
assert data.usage.cache_creation_input_tokens is None