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(otel): report cache hits at zero cost with a cache-hit flag in V1 and V2 spans (#43604)

devin-ai-integration[bot]8226b2be9ad2
diff --git a/litellm/caching/caching_handler.py b/litellm/caching/caching_handler.py
index 063faa70f2f..7089ff78835 100644
--- a/litellm/caching/caching_handler.py
+++ b/litellm/caching/caching_handler.py
@@ -346,6 +346,7 @@ class LLMCachingHandler:
if litellm.cache is not None and self._is_call_type_supported_by_cache(original_function=original_function):
verbose_logger.debug("Checking Async Cache")
+ logging_obj.reset_caching_details()
cached_result = await self._retrieve_from_cache(
call_type=call_type,
kwargs=kwargs,
@@ -357,7 +358,7 @@ class LLMCachingHandler:
verbose_logger.debug("Cache Hit!")
cache_hit: Final = True
end_time: Final = datetime.datetime.now()
- model, custom_llm_provider, _, _ = litellm.get_llm_provider(
+ provider_model, custom_llm_provider, _, _ = litellm.get_llm_provider(
model=model,
custom_llm_provider=kwargs.get("custom_llm_provider", None),
api_base=kwargs.get("api_base", None),
@@ -366,7 +367,7 @@ class LLMCachingHandler:
cache_duration_ms: Final = (cache_check_end_time - cache_check_start_time) * 1000
self._update_litellm_logging_obj_environment(
logging_obj=logging_obj,
- model=model,
+ model=provider_model,
kwargs=kwargs,
cached_result=cached_result,
is_async=True,
@@ -381,7 +382,7 @@ class LLMCachingHandler:
call_type=call_type,
kwargs=kwargs,
logging_obj=logging_obj,
- model=model,
+ model=provider_model,
custom_llm_provider=kwargs.get("custom_llm_provider", None),
args=args,
)
@@ -467,6 +468,7 @@ class LLMCachingHandler:
new_kwargs["cache_key"] = litellm.cache.get_cache_key(**new_kwargs)
self.request_kwargs = _drop_logging_obj_from_kwargs(new_kwargs)
print_verbose("Checking Sync Cache")
+ logging_obj.reset_caching_details()
with response_cache_phase("get"):
cached_result = litellm.cache.get_cache(**new_kwargs)
if is_response_without_output(cached_result):
diff --git a/litellm/integrations/opentelemetry.py b/litellm/integrations/opentelemetry.py
index 90383ddb60d..fb0723289ee 100644
--- a/litellm/integrations/opentelemetry.py
+++ b/litellm/integrations/opentelemetry.py
@@ -6,9 +6,10 @@ from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field
from datetime import datetime
from types import MappingProxyType
-from typing import TYPE_CHECKING, Any, Final, TypedDict, cast
+from typing import TYPE_CHECKING, Any, Final, cast
from pydantic import ConfigDict, TypeAdapter
+from typing_extensions import ReadOnly, TypedDict
import litellm
from litellm._logging import verbose_logger
@@ -106,6 +107,14 @@ _JSON_OBJECT: Final = TypeAdapter(Mapping[str, object], config=ConfigDict(hide_i
# Cap on credential-scoped providers held at once; each one owns an exporter thread.
_MAX_DYNAMIC_TRACER_PROVIDERS: Final = 256
+
+class _CacheHitView(TypedDict, total=False):
+ cache_hit: ReadOnly[object]
+ saved_cache_cost: ReadOnly[object]
+
+
+_CACHE_HIT_VIEW: Final = TypeAdapter(_CacheHitView)
+
# Dedicated so a slow exporter shutdown cannot starve the shared logging executor.
_PROVIDER_SHUTDOWN_EXECUTOR: Final = ThreadPoolExecutor(max_workers=4, thread_name_prefix="OtelProviderShutdown")
@@ -2434,6 +2443,8 @@ class OpenTelemetry(OTELGenAISemconvMixin, CustomLogger):
litellm_params=litellm_params,
)
# Cost breakdown tracking
+ cache_view: Final = _CACHE_HIT_VIEW.validate_python(standard_logging_payload)
+ cache_hit: Final = cache_view.get("cache_hit") is True
cost_breakdown: Final[CostBreakdown | None] = standard_logging_payload.get("cost_breakdown")
if cost_breakdown:
for key, value in cost_breakdown.items():
@@ -2443,6 +2454,11 @@ class OpenTelemetry(OTELGenAISemconvMixin, CustomLogger):
key=f"gen_ai.cost.{key}",
value=value,
)
+ self.safe_set_attribute(span=span, key=LiteLLM.CACHE_HIT, value=cache_hit)
+ if cache_hit:
+ saved_cache_cost: Final = cache_view.get("saved_cache_cost")
+ if isinstance(saved_cache_cost, (int, float)):
+ self.safe_set_attribute(span=span, key=LiteLLM.SAVED_CACHE_COST, value=saved_cache_cost)
#############################################
########## LLM Request Attributes ###########
#############################################
diff --git a/litellm/integrations/otel/emitter.py b/litellm/integrations/otel/emitter.py
index a4cb0a84541..8779153959f 100644
--- a/litellm/integrations/otel/emitter.py
+++ b/litellm/integrations/otel/emitter.py
@@ -100,23 +100,19 @@ def _carried_keys(
return frozenset(key for key, _value in attributes)
-def attribute_budget(span: Span, reserved: int, overwrites: frozenset[str] = frozenset()) -> int | None:
- """How many mapped attributes fit on ``span`` next to what it already carries and ``reserved`` more.
-
- ``overwrites`` are the mapped keys already present on ``span``: setting one
- replaces the value in place and consumes no slot against the limit, so only
- the genuinely new pre-existing keys reduce the budget. Counting the
- overwritten ones too reserves slots the fit can never spend and sheds
- indexed message attributes for nothing.
- """
+def carried_keys(span: Span) -> frozenset[str]:
+ """The attribute keys ``span`` already holds, empty for a span that exposes none."""
+ if not isinstance(span, ReadableSpan):
+ return frozenset()
+ return _carried_keys(span.attributes or ())
+
+
+def attribute_budget(span: Span, reserved: int) -> int | None:
+ """How many new attribute keys fit on ``span`` next to what it already carries and ``reserved`` more."""
limit: Final = span_attribute_limit(span)
if limit is None:
return None
- if not isinstance(span, ReadableSpan):
- return limit - reserved
- existing_keys: Final = _carried_keys(span.attributes or ())
- fresh: Final = len(existing_keys - overwrites) if overwrites else len(existing_keys)
- return limit - fresh - reserved
+ return limit - len(carried_keys(span)) - reserved
def stamp_error(
@@ -303,8 +299,14 @@ class SpanEmitter:
)
stamped_later: Final = error_attributes(error) if error else _NO_ATTRIBUTES
reserved: Final = len(stamped_later.keys() - mapped.keys())
- for key, value in fit_indexed_messages(mapped, attribute_budget(span, reserved, frozenset(mapped))).items():
- span.set_attribute(key, value)
+ overwrites: Final = carried_keys(span) & mapped.keys()
+ fitted: Final = fit_indexed_messages(
+ MappingProxyType({key: value for key, value in mapped.items() if key not in overwrites}),
+ attribute_budget(span, reserved),
+ )
+ for key, value in mapped.items():
+ if key in overwrites or key in fitted:
+ span.set_attribute(key, value)
if error:
stamped: Final = stamp_error(span, error)
if stamped is not None and self._event_recorder is not None and role is SpanRole.LLM_CALL:
diff --git a/litellm/integrations/otel/logger.py b/litellm/integrations/otel/logger.py
index 9eb9cb40caf..73448221acb 100644
--- a/litellm/integrations/otel/logger.py
+++ b/litellm/integrations/otel/logger.py
@@ -538,8 +538,12 @@ class OpenTelemetryV2(CustomLogger):
# logger is a success/failure callback only, so ``pre_call`` never reaches it
# and no carrier exists. The payload plus the request-level provider-handoff
# stamp (``upstream_started``) is the affirmative signal of a real call; a
- # gate rejection carries ``is_no_upstream_call`` and gets no span.
- if carrier is None and (call.is_no_upstream_call or not call.upstream_started or call.payload is None):
+ # gate rejection carries ``is_no_upstream_call`` and gets no span. A cache
+ # hit never hands off to a provider, so ``cache_hit`` substitutes for the
+ # upstream stamp, since the payload proves the call completed.
+ if carrier is None and (
+ call.is_no_upstream_call or call.payload is None or (not call.upstream_started and not call.cache_hit)
+ ):
return None
try:
return self._finish_carrier(carrier, call, start_time, end_time)
diff --git a/litellm/integrations/otel/mappers/genai.py b/litellm/integrations/otel/mappers/genai.py
index 0ac8b47e239..4e07d090edd 100644
--- a/litellm/integrations/otel/mappers/genai.py
+++ b/litellm/integrations/otel/mappers/genai.py
@@ -91,6 +91,8 @@ class GenAIMapper:
f"{LiteLLM.COST_PREFIX}margin_fixed_amount": lambda d: d.cost.margin_fixed_amount,
f"{LiteLLM.COST_PREFIX}margin_percent": lambda d: d.cost.margin_percent,
f"{LiteLLM.COST_PREFIX}margin_total_amount": lambda d: d.cost.margin_total_amount,
+ LiteLLM.CACHE_HIT: lambda d: d.cache_hit,
+ LiteLLM.SAVED_CACHE_COST: lambda d: d.saved_cache_cost,
LiteLLM.REQUEST_STREAMING: lambda d: d.is_streaming,
LiteLLM.REQUEST_ROUTE: lambda d: d.request_route,
LiteLLM.REQUEST_PURPOSE: lambda d: d.request_purpose,
diff --git a/litellm/integrations/otel/model/metadata.py b/litellm/integrations/otel/model/metadata.py
index cbbb1a9f6d4..a3151c24519 100644
--- a/litellm/integrations/otel/model/metadata.py
+++ b/litellm/integrations/otel/model/metadata.py
@@ -249,6 +249,10 @@ class LLMCallEvent:
# ``InternalCallOrigin`` such as ``autorouter_classifier``), ``None`` for the
# caller's own provider attempt.
purpose: str | None
+ # True for a response served from the litellm response cache. A cache hit
+ # never hands off to a provider, so ``upstream_started`` stays False even
+ # though the call completed and is worth a span.
+ cache_hit: bool
# A best-effort ``"{operation} {model}"`` name known at ``pre_call`` time. The
# span is renamed from the typed payload at close (``finish_span``); this only
# needs to be reasonable for a span that never gets closed (a leak).
@@ -273,6 +277,7 @@ class LLMCallEvent:
upstream_started=kwargs.get("api_call_start_time") is not None,
upstream_start_seconds=_epoch_seconds(kwargs.get("api_call_start_time")),
purpose=internal_call_origin(payload, kwargs),
+ cache_hit=bool(payload.get("cache_hit")) if payload else False, # pyright: ignore[reportUnknownMemberType] # TypedDict .get on a str key is partially unknown
provisional_span_name=f"{operation.value} {model}".strip(),
time_to_first_chunk_seconds=time_to_first_chunk_seconds(kwargs),
trace=trace,
diff --git a/litellm/integrations/otel/model/payloads.py b/litellm/integrations/otel/model/payloads.py
index 101e6285946..5bca8e01aec 100644
--- a/litellm/integrations/otel/model/payloads.py
+++ b/litellm/integrations/otel/model/payloads.py
@@ -441,6 +441,8 @@ class LLMCallSpanData:
embedding_output: EmbeddingOutput | None = None
promoted_metadata: Mapping[str, str] = field(default_factory=lambda: _EMPTY_METADATA)
routing_attributes: Mapping[str, RoutingAttributeValue] = field(default_factory=lambda: MappingProxyType({}))
+ cache_hit: bool | None = None
+ saved_cache_cost: float | None = None
@classmethod
def from_standard_logging_payload(
@@ -456,6 +458,7 @@ class LLMCallSpanData:
metadata_keys: tuple[str, ...] = (),
) -> LLMCallSpanData:
params: Final = cast(Mapping[str, object], payload.get("model_parameters") or {})
+ cache_hit: Final = as_bool(payload.get("cache_hit")) is True # pyright: ignore[reportUnknownMemberType] # TypedDict .get on a str key is partially unknown
# The single parse of the request's metadata — the request-vs-provider
# model split, the response model, api base, and identity all come from
# here rather than being re-derived from the raw payload dicts.
@@ -490,7 +493,7 @@ class LLMCallSpanData:
error=_parse_error(payload),
response_cost=as_float(payload.get("response_cost")),
cost=LLMCost.from_breakdown(cast("Mapping[str, object] | None", payload.get("cost_breakdown"))),
- server=ServerInfo.from_api_base(context.api_base),
+ server=None if cache_hit else ServerInfo.from_api_base(context.api_base),
identity=context.identity,
promoted_metadata=allowlisted_metadata(context.identity.metadata, metadata_keys),
is_streaming=as_bool(payload.get("stream")),
@@ -507,6 +510,8 @@ class LLMCallSpanData:
session_id=session_id or None,
embedding_output=embedding_output if capture_content else None,
routing_attributes=routing_decision_attributes(decision),
+ cache_hit=cache_hit,
+ saved_cache_cost=as_float(payload.get("saved_cache_cost")) if cache_hit else None, # pyright: ignore[reportUnknownMemberType] # TypedDict .get on a str key is partially unknown
)
diff --git a/litellm/integrations/otel/model/semconv.py b/litellm/integrations/otel/model/semconv.py
index 38cf7266593..b7f955a75ed 100644
--- a/litellm/integrations/otel/model/semconv.py
+++ b/litellm/integrations/otel/model/semconv.py
@@ -340,6 +340,8 @@ class LiteLLM:
# semconv key for an MCP server's *name* (the convention uses ``server.address``
# for its network location), so it lives under the vendor namespace.
MCP_SERVER_NAME: Final = "litellm.mcp.server.name"
+ CACHE_HIT: Final = "litellm.cache_hit"
+ SAVED_CACHE_COST: Final = "litellm.saved_cache_cost"
class Metric:
diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.py
index 438b38f3f09..457a17ab8fe 100644
--- a/litellm/litellm_core_utils/litellm_logging.py
+++ b/litellm/litellm_core_utils/litellm_logging.py
@@ -13,6 +13,7 @@ import sys
import time
import traceback
from collections.abc import Awaitable, Callable, Iterable, Iterator, Mapping, Sequence
+from dataclasses import dataclass
from datetime import datetime as dt_object
from functools import lru_cache
from types import MappingProxyType, TracebackType
@@ -558,6 +559,12 @@ def mask_api_base_credentials(api_base: str) -> str:
return api_base[:key_end] + "*" * 5 + api_base[-4:]
+@dataclass(frozen=True, slots=True)
+class UncachedPrice:
+ cost: float | None
+ cost_breakdown: CostBreakdown | None
+
+
def _timestamp_seconds(moment: object) -> float | None:
if isinstance(moment, datetime.datetime):
return moment.timestamp()
@@ -811,6 +818,10 @@ class Logging(LiteLLMLoggingBaseClass):
new_call.sync_streaming_chunks = []
return new_call
+ def reset_caching_details(self) -> None:
+ """Forget an earlier cache lookup's result, so a call that looks up again reports only its latest."""
+ self.caching_details = None
+
def set_response_timing_metrics(self, timing_metrics: Mapping[str, float]) -> None:
"""Keep ``_response_ms`` / ``litellm_overhead_time_ms`` for a result that has no ``_hidden_params``."""
self.response_timing_metrics = dict(timing_metrics)
@@ -1890,6 +1901,7 @@ class Logging(LiteLLMLoggingBaseClass):
cache_hit: bool | None = None,
litellm_model_name: str | None = None,
router_model_id: str | None = None,
+ ignore_stamped_cost: bool = False,
) -> float | None:
"""
Calculate response cost using result + logging object variables.
@@ -1925,7 +1937,9 @@ class Logging(LiteLLMLoggingBaseClass):
):
hidden_params: Final = result_hidden_params
if (
- "response_cost" in hidden_params and hidden_params["response_cost"] is not None
+ not ignore_stamped_cost
+ and "response_cost" in hidden_params
+ and hidden_params["response_cost"] is not None
): # use cost if already calculated
self._record_zero_cost_diagnostic(
priced_result,
@@ -2051,6 +2065,20 @@ class Logging(LiteLLMLoggingBaseClass):
_response_cost_calculator = response_cost_calculator
+ def uncached_price(self, result: object) -> UncachedPrice:
+ previous_cost_breakdown: Final = self.cost_breakdown
+ previous_billed_token_rates: Final = self.billed_token_rates
+ debug_key: Final = "response_cost_failure_debug_information"
+ had_failure_debug_info: Final = debug_key in self.model_call_details
+ try:
+ cost: Final = self.response_cost_calculator(result=result, cache_hit=False, ignore_stamped_cost=True)
+ return UncachedPrice(cost=cost, cost_breakdown=self.cost_breakdown)
+ finally:
+ self.cost_breakdown = previous_cost_breakdown
+ self.billed_token_rates = previous_billed_token_rates
+ if not had_failure_debug_info:
+ self.model_call_details.pop(debug_key, None)
+
def _record_zero_cost_diagnostic(
self,
result: object,
@@ -6909,6 +6937,36 @@ def _autorouter_savings_for_payload(
return None
+_CACHE_HIT_ZEROED_AMOUNTS: Final = MappingProxyType(
+ {
+ "cache_read_cost": CostBreakdown(cache_read_cost=0.0),
+ "cache_creation_cost": CostBreakdown(cache_creation_cost=0.0),
+ "reasoning_cost": CostBreakdown(reasoning_cost=0.0),
+ "original_cost": CostBreakdown(original_cost=0.0),
+ "discount_amount": CostBreakdown(discount_amount=0.0),
+ "margin_fixed_amount": CostBreakdown(margin_fixed_amount=0.0),
+ "margin_total_amount": CostBreakdown(margin_total_amount=0.0),
+ }
+)
+
+
+def _cache_hit_cost_breakdown(served: CostBreakdown | None) -> CostBreakdown:
+ """Every amount at 0, keeping the pricing basis and rates a fresh call would have had, which savings reports read."""
+ zero_costs: Final = CostBreakdown(input_cost=0.0, output_cost=0.0, total_cost=0.0, tool_usage_cost=0.0)
+ if served is None:
+ return zero_costs
+ zeroed_additional_costs: Final = (
+ CostBreakdown(additional_costs=dict.fromkeys(served["additional_costs"], 0.0))
+ if "additional_costs" in served
+ else CostBreakdown()
+ )
+ return functools.reduce(
+ lambda breakdown, zeroed: breakdown | zeroed,
+ (_CACHE_HIT_ZEROED_AMOUNTS[key] for key in served if key in _CACHE_HIT_ZEROED_AMOUNTS),
+ served | zero_costs | zeroed_additional_costs,
+ )
+
+
def get_standard_logging_object_payload(
kwargs: dict | None,
init_response_obj: object,
@@ -6992,17 +7050,10 @@ def get_standard_logging_object_payload(
"user", None
) # maintain backwards compatibility with old request body check
- saved_cache_cost: float = 0.0
if cache_hit is True or served_from_cache(init_response_obj):
id = f"{id}_cache_hit{time.time()}" # do not duplicate the request id
- if cache_hit is True:
- saved_cache_cost = (
- logging_obj.response_cost_calculator(
- result=init_response_obj,
- cache_hit=False,
- )
- or 0.0
- )
+ uncached_price: Final = logging_obj.uncached_price(result=init_response_obj) if cache_hit is True else None
+ saved_cache_cost: Final = (uncached_price.cost if uncached_price is not None else None) or 0.0
## Get model cost information ##
base_model = get_base_model_from_metadata(model_call_details=kwargs)
@@ -7019,7 +7070,7 @@ def get_standard_logging_object_payload(
# clean up litellm hidden params
clean_hidden_params: Final = StandardLoggingPayloadSetup.get_hidden_params(hidden_params)
- if clean_hidden_params["response_cost"] is None and raw_response_cost is not None:
+ if cache_hit is True or (clean_hidden_params["response_cost"] is None and raw_response_cost is not None):
clean_hidden_params["response_cost"] = llm_response_cost
if clean_hidden_params["litellm_overhead_time_ms"] is None and status == "success":
# /v1/messages dict results and the bridge stream wrappers keep it on the logging object;
@@ -7081,7 +7132,14 @@ def get_standard_logging_object_payload(
):
model_name = response_model_name
- request_cost_breakdown: Final = cost_breakdown_with_guardrail(logging_obj.cost_breakdown, guardrail_cost)
+ request_cost_breakdown: Final = cost_breakdown_with_guardrail(
+ (
+ _cache_hit_cost_breakdown(uncached_price.cost_breakdown)
+ if uncached_price is not None
+ else logging_obj.cost_breakdown
+ ),
+ guardrail_cost,
+ )
captured_baseline: Final = logging_obj.baseline_observation
autorouter_savings: Final = (
None
diff --git a/litellm/proxy/common_request_processing.py b/litellm/proxy/common_request_processing.py
index 74ee87c772b..e52f11641b0 100644
--- a/litellm/proxy/common_request_processing.py
+++ b/litellm/proxy/common_request_processing.py
@@ -1663,19 +1663,26 @@ def _totals_to_zero(response_cost: float | str | None) -> bool:
return False
+def _is_cache_hit(litellm_logging_obj: LiteLLMLoggingObj) -> bool:
+ caching_details: Final = litellm_logging_obj.caching_details
+ return caching_details is not None and caching_details.get("cache_hit") is True
+
+
def _get_cost_breakdown_from_logging_obj(
litellm_logging_obj: LiteLLMLoggingObj | None,
response_cost: float | str | None = None,
) -> CostBreakdownHeaderValues:
"""Extract discount, margin, and per-component cost information from logging object's cost breakdown.
- A non-inference call that priced at zero never records a breakdown, so its components are
- reported as zero here. Any such call that did price normally (retrieving a background response,
- and the cost poller's read of one) reports the breakdown it stored, or nothing at all when the
- breakdown has not landed yet.
+ A cache hit reports every component as zero. A non-inference call that priced at zero never
+ records a breakdown, so its components are reported as zero too. Any such call that did price
+ normally (retrieving a background response, and the cost poller's read of one) reports the
+ breakdown it stored, or nothing at all when the breakdown has not landed yet.
"""
if not litellm_logging_obj or not hasattr(litellm_logging_obj, "cost_breakdown"):
return CostBreakdownHeaderValues()
+ if _is_cache_hit(litellm_logging_obj):
+ return _ZERO_COST_BREAKDOWN
cost_breakdown: Final = litellm_logging_obj.cost_breakdown
if not cost_breakdown:
@@ -1705,6 +1712,13 @@ def _header_value(value: float | None) -> str | None:
return str(value) if value is not None else None
+def _response_cost_header_value(hidden_params: Mapping[str, object]) -> float | str:
+ if hidden_params.get("cache_hit") is True:
+ return 0.0
+ response_cost: Final = hidden_params.get("response_cost")
+ return response_cost if isinstance(response_cost, (int, float, str)) and response_cost else ""
+
+
def cost_headers(
response_cost: float | str | None, litellm_logging_obj: LiteLLMLoggingObj | None
) -> Mapping[str, str | None]:
@@ -2084,18 +2098,12 @@ class ProxyBaseLLMRequestProcessing:
Build LiteLLM proxy response headers for routes that call the LLM directly
(e.g. Google native :generateContent) instead of base_process_llm_request.
"""
- if isinstance(response, dict):
- hidden_params = get_hidden_params_dict(response)
- else:
- hidden_params = getattr(response, "_hidden_params", None) or {}
- if not isinstance(hidden_params, dict):
- hidden_params = {}
-
+ hidden_params: Final = get_hidden_params_dict(response)
model_id: Final = ProxyBaseLLMRequestProcessing._get_model_id_from_response(hidden_params, request_data)
cache_key: Final = hidden_params.get("cache_key", None) or ""
api_base: Final = hidden_params.get("api_base", None) or ""
- response_cost: Final = hidden_params.get("response_cost", None) or ""
+ response_cost: Final = _response_cost_header_value(hidden_params)
fastest_response_batch_completion: Final = hidden_params.get("fastest_response_batch_completion", None)
additional_headers: Final = hidden_params.get("additional_headers", {}) or {}
@@ -2640,7 +2648,7 @@ class ProxyBaseLLMRequestProcessing:
cache_key=hidden_params.get("cache_key") or "",
api_base=hidden_params.get("api_base") or "",
version=version,
- response_cost=hidden_params.get("response_cost") or "",
+ response_cost=_response_cost_header_value(hidden_params),
model_region=getattr(user_api_key_dict, "allowed_model_region", ""),
fastest_response_batch_completion=hidden_params.get("fastest_response_batch_completion"),
request_data=self.data,
@@ -2685,13 +2693,17 @@ class ProxyBaseLLMRequestProcessing:
hold the attribute at all, and Google :generateContent carries
``_hidden_params`` but no synchronously-populated ``response_cost``. In both
cases the cost is read back from the logging object instead, recomputing from
- the same calculator only when it has not been stored yet.
+ the same calculator only when it has not been stored yet. A response served
+ from the cache costs 0, which the calculator cannot tell from a fresh call, and any
+ other zero or unknown cost comes back empty so no cost header is sent.
"""
+ if _is_cache_hit(logging_obj):
+ return 0.0
stored_cost: Final = logging_obj.model_call_details.get("response_cost")
if isinstance(stored_cost, (int, float)):
- return float(stored_cost)
+ return float(stored_cost) or ""
recomputed_cost: Final = logging_obj.response_cost_calculator(result=response)
- return recomputed_cost if isinstance(recomputed_cost, (int, float)) else ""
+ return recomputed_cost or "" if isinstance(recomputed_cost, (int, float)) else ""
def _debug_log_request_payload(self) -> None:
"""Log request payload at DEBUG level, truncating if too large."""
@@ -2900,7 +2912,7 @@ class ProxyBaseLLMRequestProcessing:
cache_key, api_base, response_cost = (
hidden_params.get("cache_key", None) or "",
hidden_params.get("api_base", None) or "",
- hidden_params.get("response_cost", None) or "",
+ _response_cost_header_value(hidden_params),
)
fastest_response_batch_completion, additional_headers = (
hidden_params.get("fastest_response_batch_completion", None),
@@ -3170,7 +3182,7 @@ class ProxyBaseLLMRequestProcessing:
recover_response_cost: Final = not response_cost and hidden_params.get("response_cost") is None
computed_cost_for_headers: Final = (
- self._response_cost_from_logging_obj(response=response, logging_obj=logging_obj) or ""
+ self._response_cost_from_logging_obj(response=response, logging_obj=logging_obj)
if recover_response_cost
else response_cost
)
diff --git a/tests/integration/observability/test_otel_cache_hit_cost.py b/tests/integration/observability/test_otel_cache_hit_cost.py
new file mode 100644
index 00000000000..76c21b529ef
--- /dev/null
+++ b/tests/integration/observability/test_otel_cache_hit_cost.py
@@ -0,0 +1,370 @@
+import json
+import os
+import re
+import uuid
+from collections.abc import Callable, Iterator, Mapping
+from dataclasses import dataclass
+from pathlib import Path
+from types import MappingProxyType
+from typing import Final
+
+import httpx
+import pytest
+import yaml
+from integration._support.client import Gateway, eventually, gateway_from_environment, list_value, object_value
+from integration._support.database import read_rows
+from integration._support.otlp_sink import Span, owned_sinks, recorded_spans
+from integration._support.process import owned_proxy_process
+from integration._support.wire import Reply, Request, Wire, wire_server
+from pydantic import JsonValue, TypeAdapter
+from redis import Redis
+
+INPUT_PRICE: Final = 0.001
+OUTPUT_PRICE: Final = 0.002
+PROMPT_TOKENS: Final = 7
+COMPLETION_TOKENS: Final = 2
+CHAT_PRICE: Final = PROMPT_TOKENS * INPUT_PRICE + COMPLETION_TOKENS * OUTPUT_PRICE
+EMBEDDING_PRICE: Final = PROMPT_TOKENS * INPUT_PRICE
+CLIENT: Final = 3
+COST_HEADERS: Final = ("x-litellm-response-cost", "x-litellm-response-cost-input", "x-litellm-response-cost-output")
+JSON_OBJECT: Final = TypeAdapter(dict[str, JsonValue])
+MARKER: Final = re.compile(rb"cache-hit-cost-[0-9a-f]{32}")
+
+
+def _sse(frames: tuple[Mapping[str, JsonValue], ...]) -> Reply:
+ return Reply(
+ content_type="text/event-stream",
+ chunks=(*(b"data: " + json.dumps(frame).encode() + b"\n\n" for frame in frames), b"data: [DONE]\n\n"),
+ )
+
+
+def _answer(marker: str) -> str:
+ return "answer to " + marker
+
+
+def _embedding_value(marker: str) -> float:
+ return float(int(marker[-12:], 16))
+
+
+def _chat_reply(stream: bool, marker: str) -> Reply:
+ identity: Final = "chatcmpl-" + uuid.uuid4().hex
+ message: Final = {"role": "assistant", "content": _answer(marker)}
+ usage: Final = {
+ "prompt_tokens": PROMPT_TOKENS,
+ "completion_tokens": COMPLETION_TOKENS,
+ "total_tokens": PROMPT_TOKENS + COMPLETION_TOKENS,
+ }
+ if not stream:
+ return Reply(
+ body=json.dumps(
+ {
+ "id": identity,
+ "object": "chat.completion",
+ "created": 1,
+ "model": "gpt-4o-mini",
+ "choices": [{"index": 0, "message": message, "finish_reason": "stop"}],
+ "usage": usage,
+ }
+ ).encode()
+ )
+ chunk: Final = {"id": identity, "object": "chat.completion.chunk", "created": 1, "model": "gpt-4o-mini"}
+ return _sse(
+ (
+ {**chunk, "choices": [{"index": 0, "delta": message}]},
+ {**chunk, "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]},
+ {**chunk, "choices": [], "usage": usage},
+ )
+ )
+
+
+def _responses_reply(marker: str) -> Reply:
+ identity: Final = "resp_" + uuid.uuid4().hex
+ return Reply(
+ body=json.dumps(
+ {
+ "id": identity,
+ "object": "response",
+ "created_at": 1,
+ "status": "completed",
+ "model": "gpt-4o-mini",
+ "output": [
+ {
+ "id": "msg_" + identity,
+ "type": "message",
+ "role": "assistant",
+ "status": "completed",
+ "content": [{"type": "output_text", "text": _answer(marker), "annotations": []}],
+ }
+ ],
+ "usage": {
+ "input_tokens": PROMPT_TOKENS,
+ "output_tokens": COMPLETION_TOKENS,
+ "total_tokens": PROMPT_TOKENS + COMPLETION_TOKENS,
+ },
+ }
+ ).encode()
+ )
+
+
+def _embedding_reply(marker: str) -> Reply:
+ return Reply(
+ body=json.dumps(
+ {
+ "object": "list",
+ "data": [{"object": "embedding", "index": 0, "embedding": [_embedding_value(marker), 0.5, 0.75]}],
+ "model": "text-embedding-3-small",
+ "usage": {"prompt_tokens": PROMPT_TOKENS, "total_tokens": PROMPT_TOKENS},
+ }
+ ).encode()
+ )
+
+
+def _provider(request: Request) -> Reply:
+ found: Final = MARKER.search(request.body)
+ assert found is not None, request.body
+ marker: Final = found.group().decode()
+ if request.target.endswith("/embeddings"):
+ return _embedding_reply(marker)
+ if request.target.endswith("/responses"):
+ return _responses_reply(marker)
+ return _chat_reply(JSON_OBJECT.validate_json(request.body).get("stream") is True, marker)
+
+
+@dataclass(frozen=True, slots=True)
+class Route:
+ path: str
+ stream: bool
+ price: float
+ body: Callable[[str, str], Mapping[str, JsonValue]]
+ cached: Callable[[str], str] = _answer
+
+
+ROUTES: Final[Mapping[str, Route]] = MappingProxyType(
+ {
+ "chat": Route(
+ "/v1/chat/completions",
+ False,
+ CHAT_PRICE,
+ lambda model, marker: {"model": model, "messages": [{"role": "user", "content": marker}]},
+ ),
+ "chat_stream": Route(
+ "/v1/chat/completions",
+ True,
+ CHAT_PRICE,
+ lambda model, marker: {
+ "model": model,
+ "messages": [{"role": "user", "content": marker}],
+ "stream": True,
+ "stream_options": {"include_usage": True},
+ },
+ ),
+ "messages": Route(
+ "/v1/messages",
+ False,
+ CHAT_PRICE,
+ lambda model, marker: {"model": model, "max_tokens": 16, "messages": [{"role": "user", "content": marker}]},
+ ),
+ "responses": Route("/v1/responses", False, CHAT_PRICE, lambda model, marker: {"model": model, "input": marker}),
+ "embeddings": Route(
+ "/v1/embeddings",
+ False,
+ EMBEDDING_PRICE,
+ lambda model, marker: {"model": model, "input": marker},
+ lambda marker: repr(_embedding_value(marker)),
+ ),
+ }
+)
+
+
+@dataclass(frozen=True, slots=True)
+class Served:
+ call_id: str
+ headers: httpx.Headers
+
+
+@dataclass(frozen=True, slots=True)
+class Rig:
+ proxy: Gateway
+ sink: str
+ chat_model: str
+ embedding_model: str
+ upstream: Wire
+ otel_v2: bool
+
+ def send(self, route: str, marker: str) -> Served:
+ chosen: Final = ROUTES[route]
+ model: Final = self.embedding_model if route == "embeddings" else self.chat_model
+ with self.proxy.client.stream(
+ "POST",
+ chosen.path,
+ json=dict(chosen.body(model, marker)),
+ headers={"Authorization": f"Bearer {self.proxy.key}"},
+ ) as response:
+ body: Final = response.read()
+ assert response.status_code == 200, body
+ return Served(response.headers["x-litellm-call-id"], response.headers)
+
+ def upstream_calls(self, marker: str) -> int:
+ return sum(1 for request in self.upstream.drain() if marker.encode() in request.body)
+
+ def cost_span(self, call_id: str) -> Span:
+ def matching() -> tuple[Span, ...]:
+ return tuple(span for span in recorded_spans(self.sink)[1] if self._is_cost_span(span, call_id))
+
+ found: Final = eventually(matching, lambda spans: len(spans) >= 1, seconds=30)
+ assert len(found) == 1, found
+ return found[0]
+
+ def _is_cost_span(self, span: Span, call_id: str) -> bool:
+ if span["attributes"].get("litellm.call_id") != call_id:
+ return False
+ if self.otel_v2:
+ return span["kind"] == CLIENT and "gen_ai.operation.name" in span["attributes"]
+ return span["name"] == "litellm_request"
+
+ def total_cost(self, span: Span) -> float:
+ return _number(span["attributes"].get("litellm.cost.total" if self.otel_v2 else "gen_ai.cost.total_cost"))
+
+
+def _number(value: JsonValue) -> float:
+ assert isinstance(value, (int, float, str)) and not isinstance(value, bool), value
+ return float(value)
+
+
+def _config(provider: Wire, sink: str, chat_model: str, embedding_model: str) -> dict[str, JsonValue]:
+ config: Final = object_value(yaml.safe_load(Path("tests/integration/proxy_config.yaml").read_text()))
+ priced: Final = {"input_cost_per_token": INPUT_PRICE, "output_cost_per_token": OUTPUT_PRICE}
+ return {
+ **config,
+ "model_list": [
+ *list_value(config.get("model_list") or []),
+ {
+ "model_name": chat_model,
+ "litellm_params": {
+ "model": "openai/gpt-4o-mini",
+ "api_key": "integration-provider-key",
+ "api_base": provider.url + "/v1",
+ **priced,
+ },
+ },
+ {
+ "model_name": embedding_model,
+ "litellm_params": {
+ "model": "openai/text-embedding-3-small",
+ "api_key": "integration-provider-key",
+ "api_base": provider.url + "/v1",
+ **priced,
+ },
+ },
+ ],
+ "litellm_settings": {**object_value(config["litellm_settings"]), "callbacks": ["otel"]},
+ "callback_settings": {"otel": {"exporter": "http/json", "endpoint": sink, "use_simple_processor": True}},
+ }
+
+
[email protected](scope="module")
+def provider() -> Iterator[Wire]:
+ with wire_server(_provider) as wire:
+ yield wire
+
+
+def _rig(provider: Wire, directory: Path, otel_v2: bool) -> Iterator[Rig]:
+ chat_model: Final = "cachecost-chat-" + uuid.uuid4().hex[:12]
+ embedding_model: Final = "cachecost-embed-" + uuid.uuid4().hex[:12]
+ with owned_sinks(directory / "sinks") as sinks:
+ path: Final = directory / f"cache-hit-cost-{uuid.uuid4().hex}.yaml"
+ path.write_text(yaml.safe_dump(_config(provider, sinks.operator, chat_model, embedding_model)))
+ v1_exporter: Final = {"OTEL_EXPORTER": "http/json", "OTEL_ENDPOINT": sinks.operator}
+ exporter: Final = {"LITELLM_OTEL_V2": "1"} if otel_v2 else v1_exporter
+ with (
+ gateway_from_environment() as gateway,
+ owned_proxy_process(
+ gateway,
+ directory,
+ exporter,
+ config=path,
+ remove_environment=() if otel_v2 else ("LITELLM_OTEL_V2",),
+ workers=2,
+ ) as owned,
+ ):
+ yield Rig(owned.gateway, sinks.operator, chat_model, embedding_model, provider, otel_v2)
+
+
[email protected](scope="module")
+def v1(provider: Wire, tmp_path_factory: pytest.TempPathFactory) -> Iterator[Rig]:
+ yield from _rig(provider, tmp_path_factory.mktemp("cache-hit-cost-v1"), otel_v2=False)
+
+
[email protected](scope="module")
+def v2(provider: Wire, tmp_path_factory: pytest.TempPathFactory) -> Iterator[Rig]:
+ yield from _rig(provider, tmp_path_factory.mktemp("cache-hit-cost-v2"), otel_v2=True)
+
+
+def _spend_row(call_id: str) -> Mapping[str, JsonValue]:
+ rows: Final = eventually(
+ lambda: read_rows(
+ 'SELECT spend, cache_hit, metadata FROM "LiteLLM_SpendLogs" WHERE litellm_call_id=%s', (call_id,)
+ ),
+ lambda found: len(found) == 1,
+ seconds=70,
+ )
+ return rows[0]
+
+
+def _breakdown_total(row: Mapping[str, JsonValue]) -> float:
+ return _number(object_value(object_value(row["metadata"])["cost_breakdown"])["total_cost"])
+
+
+def _cache_holds(needle: str) -> bool:
+ with Redis(host=os.environ["REDIS_HOST"], port=int(os.environ["REDIS_PORT"])) as store:
+ return any(needle.encode() in _bytes(store.get(key)) for key in store.scan_iter(count=1000, _type="STRING"))
+
+
+def _bytes(value: object) -> bytes:
+ return value if isinstance(value, bytes) else b""
+
+
+def _miss_then_hit(rig: Rig, route: str) -> tuple[Served, Served]:
+ marker: Final = "cache-hit-cost-" + uuid.uuid4().hex
+ miss: Final = rig.send(route, marker)
+ eventually(lambda: _cache_holds(ROUTES[route].cached(marker)), bool, seconds=30)
+ hit: Final = rig.send(route, marker)
+ assert rig.upstream_calls(marker) == 1
+ return miss, hit
+
+
[email protected]("route", tuple(ROUTES))
+def test_a_v1_cache_hit_exports_zero_cost_and_answers_zero_cost_headers(v1: Rig, route: str) -> None:
+ price: Final = ROUTES[route].price
+ miss, hit = _miss_then_hit(v1, route)
+
+ hit_span: Final = v1.cost_span(hit.call_id)
+ assert v1.total_cost(hit_span) == 0, hit_span
+ assert hit_span["attributes"].get("litellm.cache_hit") is True, hit_span
+ assert _number(hit_span["attributes"].get("litellm.saved_cache_cost")) == pytest.approx(price), hit_span
+
+ assert {name: hit.headers.get(name) for name in COST_HEADERS} == dict.fromkeys(COST_HEADERS, "0.0"), hit.headers
+
+ hit_row: Final = _spend_row(hit.call_id)
+ assert (_number(hit_row["spend"]), hit_row["cache_hit"]) == (0, "True"), hit_row
+ assert _breakdown_total(hit_row) == 0, hit_row
+ assert _number(_spend_row(miss.call_id)["spend"]) == pytest.approx(price)
+
+ miss_span: Final = v1.cost_span(miss.call_id)
+ assert v1.total_cost(miss_span) == pytest.approx(price), miss_span
+ assert miss_span["attributes"].get("litellm.cache_hit") is False, miss_span
+
+
[email protected]("route", tuple(ROUTES))
+def test_a_v2_cache_hit_exports_an_llm_span_at_zero_cost(v2: Rig, route: str) -> None:
+ price: Final = ROUTES[route].price
+ miss, hit = _miss_then_hit(v2, route)
+
+ hit_span: Final = v2.cost_span(hit.call_id)
+ assert v2.total_cost(hit_span) == 0, hit_span
+ assert hit_span["attributes"].get("litellm.cache_hit") is True, hit_span
+ assert _number(hit_span["attributes"].get("litellm.saved_cache_cost")) == pytest.approx(price), hit_span
+
+ miss_span: Final = v2.cost_span(miss.call_id)
+ assert v2.total_cost(miss_span) == pytest.approx(price), miss_span
+ assert miss_span["attributes"].get("litellm.cache_hit") is False, miss_span
diff --git a/tests/unit/caching/test_caching_handler.py b/tests/unit/caching/test_caching_handler.py
index 7d6b1e15fc6..388e4c42ea0 100644
--- a/tests/unit/caching/test_caching_handler.py
+++ b/tests/unit/caching/test_caching_handler.py
@@ -15,6 +15,7 @@ from pydantic import TypeAdapter
import litellm
from litellm import aembedding, completion, embedding, aresponses, responses
+from litellm.litellm_core_utils.logging_worker import GLOBAL_LOGGING_WORKER
from litellm.caching.caching import Cache
from litellm.responses.streaming_iterator import CachedResponsesAPIStreamingIterator
@@ -303,6 +304,93 @@ async def test_cache_hit_reports_zero_response_cost(copilot_response_cache: Cach
assert second._hidden_params["response_cost"] == 0
+async def test_async_cache_hits_never_use_up_a_deployment_tpm_limit(copilot_response_cache: Cache) -> None:
+ router: Final = litellm.Router(
+ model_list=[
+ {
+ "model_name": "tpm-limited",
+ "litellm_params": {
+ "model": "openai/gpt-4o-mini",
+ "api_key": "sk-test",
+ "mock_response": "cached answer",
+ "tpm": 100,
+ },
+ }
+ ],
+ routing_strategy="usage-based-routing-v2",
+ num_retries=0,
+ )
+ messages: Final = [{"role": "user", "content": "tpm limit and cache hits"}]
+
+ async def call_and_settle() -> litellm.ModelResponse:
+ response: Final = await router.acompletion(model="tpm-limited", messages=messages, caching=True)
+ await asyncio.gather(*_PENDING_CACHE_WRITES)
+ await asyncio.wait_for(GLOBAL_LOGGING_WORKER.flush(), timeout=10)
+ return response
+
+ first: Final = await call_and_settle()
+ hits: Final = [await call_and_settle() for _ in range(8)]
+
+ assert first.usage.total_tokens * len(hits) > 100
+ assert all(hit._hidden_params["cache_hit"] is True for hit in hits)
+
+
+def _logging_obj_left_with_a_cache_hit(messages: list[dict[str, str]]) -> LiteLLMLogging:
+ logging_obj: Final = LiteLLMLogging(
+ litellm_call_id=str(uuid.uuid4()),
+ call_type=CallTypes.acompletion.value,
+ model="gpt-4o-mini",
+ messages=messages,
+ function_id=str(uuid.uuid4()),
+ stream=False,
+ start_time=datetime.now(),
+ )
+ logging_obj.caching_details = {"cache_hit": True, "cache_duration_ms": 1.0}
+ return logging_obj
+
+
+async def test_async_cache_miss_clears_the_hit_an_earlier_lookup_left_on_the_call(
+ copilot_response_cache: Cache,
+) -> None:
+ messages: Final = [{"role": "user", "content": f"never cached {uuid.uuid4()}"}]
+ logging_obj: Final = _logging_obj_left_with_a_cache_hit(messages)
+ handler: Final = LLMCachingHandler(
+ original_function=litellm.acompletion, request_kwargs={}, start_time=datetime.now()
+ )
+
+ response: Final = await handler.async_get_cache(
+ model="gpt-4o-mini",
+ original_function=litellm.acompletion,
+ logging_obj=logging_obj,
+ start_time=datetime.now(),
+ call_type=CallTypes.acompletion.value,
+ kwargs={"model": "gpt-4o-mini", "messages": messages, "caching": True},
+ )
+
+ assert response is not None and response.cached_result is None
+ assert logging_obj.caching_details is None
+
+
+def test_sync_cache_miss_clears_the_hit_an_earlier_lookup_left_on_the_call(copilot_response_cache: Cache) -> None:
+ messages: Final = [{"role": "user", "content": f"never cached {uuid.uuid4()}"}]
+ logging_obj: Final = _logging_obj_left_with_a_cache_hit(messages)
+ handler: Final = LLMCachingHandler(original_function=completion, request_kwargs={}, start_time=datetime.now())
+
+ response: Final = handler.sync_get_cache(
+ model="gpt-4o-mini",
+ original_function=completion,
+ logging_obj=logging_obj,
+ start_time=datetime.now(),
+ call_type=CallTypes.completion.value,
+ kwargs={"model": "gpt-4o-mini", "messages": messages, "caching": True},
+ )
+
+ assert response.cached_result is None
+ assert logging_obj.caching_details is None
+
+
chat_completion_response = litellm.ModelResponse(
id=str(uuid.uuid4()),
choices=[
diff --git a/tests/unit/integrations/otel/test_otel_v2_components.py b/tests/unit/integrations/otel/test_otel_v2_components.py
index bc230a8bcb2..3f4389765d3 100644
--- a/tests/unit/integrations/otel/test_otel_v2_components.py
+++ b/tests/unit/integrations/otel/test_otel_v2_components.py
@@ -2,6 +2,7 @@
baggage helpers, metrics, the typed coercion helpers, mapper branches, span-name
builders, and the registry validator's failure paths. Needs the OTel SDK."""
+from typing import Final
import contextlib
import json
import threading
@@ -358,6 +359,18 @@ def test_genai_mapper_cost_breakdown_absent():
assert not any(k.startswith(LiteLLM.COST_PREFIX) and k != f"{LiteLLM.COST_PREFIX}total" for k in attrs)
+def test_genai_mapper_cache_hit_attrs():
+ from litellm.integrations.otel.model.semconv import LiteLLM
+
+ attrs: Final = GenAIMapper().map(replace(_full_llm_call(), cache_hit=True, saved_cache_cost=0.002))
+ assert attrs[LiteLLM.CACHE_HIT] is True
+ assert attrs[LiteLLM.SAVED_CACHE_COST] == 0.002
+
+ uncached: Final = GenAIMapper().map(_full_llm_call())
+ assert LiteLLM.CACHE_HIT not in uncached
+ assert LiteLLM.SAVED_CACHE_COST not in uncached
+
+
def test_llm_cost_from_breakdown_maps_costbreakdown_keys():
cost = LLMCost.from_breakdown(
{
diff --git a/tests/unit/integrations/otel/test_otel_v2_emitter.py b/tests/unit/integrations/otel/test_otel_v2_emitter.py
index 949eb97bccd..0905e9e7c30 100644
--- a/tests/unit/integrations/otel/test_otel_v2_emitter.py
+++ b/tests/unit/integrations/otel/test_otel_v2_emitter.py
@@ -2,6 +2,7 @@
legacy dual-emit, hierarchy, error status, and idempotency. Needs the OTel SDK."""
import json
+from typing import Final
import pytest
@@ -642,25 +643,71 @@ def test_preset_message_key_the_fit_sheds_still_never_overflows_the_span():
assert len(finished.attributes) <= SpanLimits().max_span_attributes
-def test_attribute_budget_counts_only_keys_the_fit_does_not_overwrite():
+def test_preset_keys_the_mappers_overwrite_shed_no_message_attribute(monkeypatch):
"""Pre-set attributes the mapped set overwrites consume no slot against the span limit.
A boundary-opened LLM-call span already carries a few stamped attributes,
- most of which the mappers re-emit under the same keys. Charging those
- against the budget reserves slots the fit can never spend and sheds
- indexed message attributes for nothing.
+ most of which the mappers re-emit under the same keys, so a span sized to
+ exactly its mapped attributes keeps every indexed message.
"""
+ monkeypatch.setenv("OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT", "1000")
+ full: Final = _conversation_span(["genai", "openinference"], _conversation_payload(6)).attributes
+ monkeypatch.setenv("OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT", str(len(full)))
+ cfg: Final = OpenTelemetryV2Config(
+ exporter="in_memory",
+ legacy_compat=False,
+ mapper_names=["genai", "openinference"],
+ capture_message_content="span_only",
+ )
+ provider, exporter = providers.in_memory_provider(cfg)
+ engine: Final = SpanEmitter(providers.get_tracer(provider, "litellm-test"), cfg)
+ span: Final = engine.start_span(SpanRole.LLM_CALL, "chat gpt-4o")
+ span.set_attribute("gen_ai.request.model", "gpt-4o")
+ span.set_attribute("llm.input_messages.1.message.role", "stale-role")
+ engine.finish_span(
+ SpanRole.LLM_CALL,
+ span,
+ LLMCallSpanData.from_standard_logging_payload(_conversation_payload(6), capture_content=True),
+ )
+ (finished,) = exporter.get_finished_spans()
+ assert finished.dropped_attributes == 0
+ assert dict(finished.attributes) == dict(full)
+
+
+def test_a_preset_message_key_the_fit_sheds_never_overflows_an_exact_limit(monkeypatch):
+ monkeypatch.setenv("OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT", "1000")
+ full: Final = _conversation_span(["genai", "openinference"], _conversation_payload(6)).attributes
+ limit: Final = len(full) - 2
+ monkeypatch.setenv("OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT", str(limit))
+ cfg: Final = OpenTelemetryV2Config(
+ exporter="in_memory",
+ legacy_compat=False,
+ mapper_names=["genai", "openinference"],
+ capture_message_content="span_only",
+ )
+ provider, exporter = providers.in_memory_provider(cfg)
+ engine: Final = SpanEmitter(providers.get_tracer(provider, "litellm-test"), cfg)
+ span: Final = engine.start_span(SpanRole.LLM_CALL, "chat gpt-4o")
+ span.set_attribute("llm.input_messages.1.message.role", "stale-role")
+ engine.finish_span(
+ SpanRole.LLM_CALL,
+ span,
+ LLMCallSpanData.from_standard_logging_payload(_conversation_payload(6), capture_content=True),
+ )
+ (finished,) = exporter.get_finished_spans()
+ assert finished.dropped_attributes == 0
+ assert len(finished.attributes) <= limit
+ assert finished.attributes.get("llm.input_messages.1.message.role") != "stale-role"
+
+
+def test_attribute_budget_charges_every_key_the_span_already_carries():
cfg = OpenTelemetryV2Config(exporter="in_memory")
provider, _exporter = providers.in_memory_provider(cfg)
span = providers.get_tracer(provider, "litellm-test").start_span("s")
span.set_attribute("gen_ai.request.model", "gpt-4o")
span.set_attribute("litellm.metadata.user_api_key_alias", "edge-key")
try:
- assert attribute_budget(span, 0) == SpanLimits().max_span_attributes - 2
- assert (
- attribute_budget(span, 0, frozenset({"gen_ai.request.model"}))
- == SpanLimits().max_span_attributes - 1
- )
+ assert attribute_budget(span, 1) == SpanLimits().max_span_attributes - 3
finally:
span.end()
diff --git a/tests/unit/integrations/otel/test_otel_v2_logger.py b/tests/unit/integrations/otel/test_otel_v2_logger.py
index 6a9a963948e..10e12981ec1 100644
--- a/tests/unit/integrations/otel/test_otel_v2_logger.py
+++ b/tests/unit/integrations/otel/test_otel_v2_logger.py
@@ -494,6 +494,49 @@ def test_no_span_when_pre_call_never_ran():
assert exporter.get_finished_spans() == () # no phantom LLM span
+def test_cache_hit_without_pre_call_emits_zero_cost_span():
+ """A response served from the litellm cache never hands off to a provider,
+ so ``pre_call`` never runs and ``api_call_start_time`` is never stamped,
+ but the completed call's payload still warrants a span, carrying the cache
+ attributes rather than being dropped like a gate rejection."""
+ logger, exporter = _logger()
+ payload: Final = _payload(
+ cache_hit=True,
+ response_cost=0.0,
+ saved_cache_cost=0.002,
+ cost_breakdown={"input_cost": 0.0, "output_cost": 0.0, "total_cost": 0.0, "tool_usage_cost": 0.0},
+ )
+ asyncio.run(
+ logger.async_log_success_event(_kwargs(payload=payload), None, None, None)
+ )
+ (span,) = exporter.get_finished_spans()
+ assert span.attributes[LiteLLM.CACHE_HIT] is True
+ assert span.attributes[LiteLLM.SAVED_CACHE_COST] == 0.002
+ assert {
+ name: span.attributes[f"{LiteLLM.COST_PREFIX}{name}"] for name in ("total", "input", "output", "tool_usage")
+ } == {"total": 0.0, "input": 0.0, "output": 0.0, "tool_usage": 0.0}
+ assert "server.address" not in span.attributes
+
+
+def test_cache_miss_span_reports_cache_hit_false():
+ logger, exporter = _logger()
+ _emit_llm(logger, _kwargs(payload=_payload(cache_hit=False, saved_cache_cost=0.0)))
+ (span,) = exporter.get_finished_spans()
+ assert span.attributes[LiteLLM.CACHE_HIT] is False
+ assert LiteLLM.SAVED_CACHE_COST not in span.attributes
+
+
+def test_cache_miss_without_pre_call_still_emits_no_span():
+ """The cache-hit relaxation is not a general loosening: a success callback
+ with no ``pre_call`` carrier and no cache hit still emits nothing."""
+ logger, exporter = _logger()
+ payload: Final = _payload(cache_hit=False, response_cost=0.002)
+ asyncio.run(
+ logger.async_log_success_event(_kwargs(payload=payload), None, None, None)
+ )
+ assert exporter.get_finished_spans() == ()
+
+
def test_real_llm_failure_still_emitted():
"""A genuine LLM failure: ``pre_call`` ran (the call was attempted), so the
CLIENT span is opened at the boundary and closed ERROR."""
diff --git a/tests/unit/integrations/test_opentelemetry.py b/tests/unit/integrations/test_opentelemetry.py
index 9ba09085ce8..b40c1a96500 100644
--- a/tests/unit/integrations/test_opentelemetry.py
+++ b/tests/unit/integrations/test_opentelemetry.py
@@ -478,6 +478,75 @@ class TestOpenTelemetryCostBreakdown(unittest.TestCase):
assert ("gen_ai.cost.tool_usage_cost", 0.0001) not in call_args_list
assert ("gen_ai.cost.original_cost", 0.004) not in call_args_list
+ def test_cache_hit_span_carries_cache_indicator_and_saved_cost(self):
+ """
+ A cache-hit span reports litellm.cache_hit and litellm.saved_cache_cost so cost
+ attribution can tell a cache-served response apart from a billed call.
+ """
+ otel: Final = OpenTelemetry()
+ mock_span: Final = MagicMock()
+
+ kwargs: Final = {
+ "model": "gpt-4",
+ "messages": [{"role": "user", "content": "Hello"}],
+ "optional_params": {},
+ "litellm_params": {"custom_llm_provider": "openai"},
+ "standard_logging_object": {
+ "id": "test-id",
+ "call_type": "completion",
+ "metadata": {},
+ "cache_hit": True,
+ "saved_cache_cost": 0.003,
+ "cost_breakdown": {"input_cost": 0.0, "output_cost": 0.0, "total_cost": 0.0, "tool_usage_cost": 0.0},
+ },
+ }
+
+ response_obj: Final = {
+ "id": "test-response-id",
+ "model": "gpt-4",
+ "choices": [],
+ "usage": {"prompt_tokens": 10, "completion_tokens": 20, "total_tokens": 30},
+ }
+
+ otel.set_attributes(span=mock_span, kwargs=kwargs, response_obj=response_obj)
+
+ mock_span.set_attribute.assert_any_call("litellm.cache_hit", True)
+ mock_span.set_attribute.assert_any_call("litellm.saved_cache_cost", 0.003)
+ mock_span.set_attribute.assert_any_call("gen_ai.cost.total_cost", 0.0)
+ mock_span.set_attribute.assert_any_call("gen_ai.cost.input_cost", 0.0)
+ mock_span.set_attribute.assert_any_call("gen_ai.cost.output_cost", 0.0)
+
+ def test_non_cache_hit_span_reports_cache_hit_false(self):
+ otel: Final = OpenTelemetry()
+ mock_span: Final = MagicMock()
+
+ kwargs: Final = {
+ "model": "gpt-4",
+ "messages": [{"role": "user", "content": "Hello"}],
+ "optional_params": {},
+ "litellm_params": {"custom_llm_provider": "openai"},
+ "standard_logging_object": {
+ "id": "test-id",
+ "call_type": "completion",
+ "metadata": {},
+ "cache_hit": False,
+ },
+ }
+
+ response_obj: Final = {
+ "id": "test-response-id",
+ "model": "gpt-4",
+ "choices": [],
+ "usage": {"prompt_tokens": 10, "completion_tokens": 20, "total_tokens": 30},
+ }
+
+ otel.set_attributes(span=mock_span, kwargs=kwargs, response_obj=response_obj)
+
+ call_args_list: Final = [call[0] for call in mock_span.set_attribute.call_args_list]
+ assert ("litellm.cache_hit", False) in call_args_list
+ assert all(key != "litellm.saved_cache_cost" for key, _value in call_args_list)
+ assert all(not key.startswith("gen_ai.cost.") for key, _value in call_args_list)
+
class TestOpenTelemetryProviderInitialization(unittest.TestCase):
"""Test suite for verifying provider initialization respects existing providers"""
diff --git a/tests/unit/litellm_core_utils/test_litellm_logging.py b/tests/unit/litellm_core_utils/test_litellm_logging.py
index f314c45dae2..3d164b59bfe 100644
--- a/tests/unit/litellm_core_utils/test_litellm_logging.py
+++ b/tests/unit/litellm_core_utils/test_litellm_logging.py
@@ -40,6 +40,7 @@ from litellm.litellm_core_utils.litellm_logging import (
StandardLoggingPayloadSetup,
_extract_response_obj_and_hidden_params,
_get_status_fields,
+ get_standard_logging_object_payload,
set_callbacks,
)
from litellm.litellm_core_utils.logging_worker import GLOBAL_LOGGING_WORKER
@@ -52,6 +53,7 @@ from litellm.proxy.utils import InternalUsageCache
from litellm.types.llms.openai import ResponseAPIUsage, ResponseCompletedEvent, ResponsesAPIResponse
from litellm.types.utils import (
CallTypes,
+ CostBreakdown,
ImageResponse,
LiteLLMRealtimeStreamLoggingObject,
ModelResponse,
@@ -7400,6 +7402,75 @@ def test_payload_guardrail_cost_merges_into_existing_cost_breakdown(logging_obj)
assert logging_obj.cost_breakdown["total_cost"] == pytest.approx(0.0000429)
+def test_cache_hit_payload_keeps_zero_components_beside_guardrail_cost(logging_obj):
+ logging_obj.set_cost_breakdown(
+ input_cost=0.00003,
+ output_cost=0.0000129,
+ total_cost=0.0000429,
+ cost_for_built_in_tools_cost_usd_dollar=0.0,
+ )
+ payload: Final = _build_success_payload(logging_obj, {**_guardrail_kwargs(response_cost=0.0), "cache_hit": True})
+
+ assert payload is not None
+ assert payload["response_cost"] == pytest.approx(0.0003)
+ assert payload["cost_breakdown"] == {
+ "input_cost": 0.0,
+ "output_cost": 0.0,
+ "tool_usage_cost": 0.0,
+ "service_tier": None,
+ "data_residency": None,
+ "vertex_location": None,
+ "guardrail_cost": pytest.approx(0.0003),
+ "total_cost": pytest.approx(0.0003),
+ }
+
+
+def test_cache_hit_payload_keeps_the_served_pricing_basis_with_every_amount_at_zero(logging_obj):
+ logging_obj.set_cost_breakdown(
+ input_cost=0.00003,
+ output_cost=0.0000129,
+ total_cost=0.0000474,
+ cost_for_built_in_tools_cost_usd_dollar=0.0000011,
+ additional_costs={"azure_model_router_flat_cost": 0.00014},
+ original_cost=0.00005,
+ discount_percent=0.1,
+ discount_amount=0.000005,
+ margin_percent=0.05,
+ margin_fixed_amount=0.000001,
+ margin_total_amount=0.0000035,
+ cache_read_cost=0.000002,
+ cache_creation_cost=0.000003,
+ reasoning_cost=0.000004,
+ service_tier="priority",
+ data_residency="eu",
+ vertex_location="europe-west4",
+ )
+ kwargs: Final = {"litellm_call_id": "hit-basis-call", "model": "gpt-4o", "messages": [], "cache_hit": True}
+
+ payload: Final = _build_success_payload(logging_obj, kwargs)
+
+ assert payload is not None
+ assert payload["cost_breakdown"] == {
+ "input_cost": 0.0,
+ "output_cost": 0.0,
+ "total_cost": 0.0,
+ "tool_usage_cost": 0.0,
+ "additional_costs": {"azure_model_router_flat_cost": 0.0},
+ "original_cost": 0.0,
+ "discount_percent": 0.1,
+ "discount_amount": 0.0,
+ "margin_percent": 0.05,
+ "margin_fixed_amount": 0.0,
+ "margin_total_amount": 0.0,
+ "cache_read_cost": 0.0,
+ "cache_creation_cost": 0.0,
+ "reasoning_cost": 0.0,
+ "service_tier": "priority",
+ "data_residency": "eu",
+ "vertex_location": "europe-west4",
+ }
+
+
def test_payload_without_guardrail_cost_is_unchanged(logging_obj):
kwargs = {
"litellm_call_id": "no-guardrail-call",
@@ -10187,6 +10258,245 @@ def test_signoz_dispatch_requires_an_endpoint(monkeypatch):
is_otel_v2_enabled.cache_clear()
+def _lit8679_priced_logging_obj(deployment_id: str, litellm_call_id: str) -> LitellmLogging:
+ logging_obj: Final = LitellmLogging(
+ model="gpt-5.4-nano",
+ messages=[{"role": "user", "content": "Hi"}],
+ stream=False,
+ call_type="completion",
+ start_time=time.time(),
+ litellm_call_id=litellm_call_id,
+ function_id="fn",
+ )
+ logging_obj.update_environment_variables(
+ model="gpt-5.4-nano",
+ user="",
+ optional_params={},
+ litellm_params={"metadata": {"model_group": "lit8679-group", "model_info": {"id": deployment_id}}},
+ custom_llm_provider="openai",
+ )
+ return logging_obj
+
+
+def test_uncached_price_recomputes_price_past_a_zero_stamp():
+ """A probe for the price a cache-served response would have had ignores the 0.0 stamped on it."""
+ deployment_id: Final = "lit8679-uncached-cost-deployment"
+ litellm.register_model(
+ model_cost={
+ deployment_id: {
+ "litellm_provider": "openai",
+ "mode": "chat",
+ "input_cost_per_token": 1e-06,
+ "output_cost_per_token": 2e-06,
+ }
+ },
+ persist_across_reloads=False,
+ )
+ try:
+ logging_obj: Final = _lit8679_priced_logging_obj(deployment_id, "lit8679-uncached")
+ oracle_logging_obj: Final = _lit8679_priced_logging_obj(deployment_id, "lit8679-oracle")
+ cached_response: Final = ModelResponse(
+ model="gpt-5.4-nano",
+ choices=[litellm.Choices(message=litellm.Message(role="assistant", content="cached"))],
+ usage=litellm.Usage(prompt_tokens=10, completion_tokens=20, total_tokens=30),
+ )
+ cached_response._hidden_params = {"cache_hit": True, "cache_key": "lit8679-key", "response_cost": 0.0}
+ fresh_response: Final = ModelResponse(
+ model="gpt-5.4-nano",
+ choices=[litellm.Choices(message=litellm.Message(role="assistant", content="cached"))],
+ usage=litellm.Usage(prompt_tokens=10, completion_tokens=20, total_tokens=30),
+ )
+
+ cost: Final = logging_obj.uncached_price(result=cached_response).cost
+ uncached_price: Final = oracle_logging_obj._response_cost_calculator(result=fresh_response)
+
+ assert cost == uncached_price
+ assert cost is not None and cost > 0.0
+ assert logging_obj.cost_breakdown is None
+ finally:
+ litellm.model_cost.pop(deployment_id, None)
+
+
+def test_uncached_price_leaves_no_pricing_state_on_the_call():
+ """The uncached price probe leaves no cost breakdown or billed rates behind on the cache-hit call."""
+ deployment_id: Final = "lit8679-probe-state-deployment"
+ litellm.register_model(
+ model_cost={
+ deployment_id: {
+ "litellm_provider": "openai",
+ "mode": "chat",
+ "input_cost_per_token": 1e-06,
+ "output_cost_per_token": 2e-06,
+ }
+ },
+ persist_across_reloads=False,
+ )
+ try:
+ logging_obj: Final = _lit8679_priced_logging_obj(deployment_id, "lit8679-probe-state")
+ cached_response: Final = ModelResponse(
+ model="gpt-5.4-nano",
+ choices=[litellm.Choices(message=litellm.Message(role="assistant", content="cached"))],
+ usage=litellm.Usage(prompt_tokens=10, completion_tokens=20, total_tokens=30),
+ )
+ cached_response._hidden_params = {"cache_hit": True, "cache_key": "lit8679-key", "response_cost": 0.0}
+ assert (logging_obj.cost_breakdown, logging_obj.billed_token_rates) == (None, None)
+
+ cost: Final = logging_obj.uncached_price(result=cached_response).cost
+
+ assert cost is not None and cost > 0.0
+ assert (logging_obj.cost_breakdown, logging_obj.billed_token_rates) == (None, None)
+ finally:
+ litellm.model_cost.pop(deployment_id, None)
+
+
+def _assert_zeroed_copy(hit_breakdown: CostBreakdown | None, fresh_breakdown: CostBreakdown) -> None:
+ basis_and_rates: Final = ("service_tier", "data_residency", "vertex_location", "discount_percent", "margin_percent")
+ assert hit_breakdown is not None and hit_breakdown.keys() == fresh_breakdown.keys()
+ assert all(hit_breakdown[key] == fresh_breakdown[key] for key in basis_and_rates if key in hit_breakdown)
+ assert all(value == 0.0 for key, value in hit_breakdown.items() if key not in basis_and_rates)
+
+
+def test_payload_saved_cache_cost_keeps_uncached_price_when_result_stamped_zero():
+ """A cache-hit payload still reports what the call would have cost, not the 0.0 stamped on the served response."""
+ deployment_id: Final = "lit8679-saved-cost-deployment"
+ litellm.register_model(
+ model_cost={
+ deployment_id: {
+ "litellm_provider": "openai",
+ "mode": "chat",
+ "input_cost_per_token": 1e-06,
+ "output_cost_per_token": 2e-06,
+ }
+ },
+ persist_across_reloads=False,
+ )
+ try:
+ logging_obj: Final = _lit8679_priced_logging_obj(deployment_id, "lit8679-payload")
+ oracle_logging_obj: Final = _lit8679_priced_logging_obj(deployment_id, "lit8679-payload-oracle")
+ response: Final = ModelResponse(
+ model="gpt-5.4-nano",
+ choices=[litellm.Choices(message=litellm.Message(role="assistant", content="cached"))],
+ usage=litellm.Usage(prompt_tokens=10, completion_tokens=20, total_tokens=30),
+ )
+ response._hidden_params = {"cache_hit": True, "cache_key": "lit8679-key", "response_cost": 0.0}
+ fresh_response: Final = ModelResponse(
+ model="gpt-5.4-nano",
+ choices=[litellm.Choices(message=litellm.Message(role="assistant", content="cached"))],
+ usage=litellm.Usage(prompt_tokens=10, completion_tokens=20, total_tokens=30),
+ )
+ logging_obj.model_call_details["cache_hit"] = True
+ now: Final = datetime.datetime.now()
+ payload: Final = get_standard_logging_object_payload(
+ kwargs={
+ "model": "gpt-5.4-nano",
+ "messages": [],
+ "cache_hit": True,
+ "litellm_params": logging_obj.litellm_params,
+ },
+ init_response_obj=response,
+ start_time=now,
+ end_time=now,
+ logging_obj=logging_obj,
+ status="success",
+ )
+ uncached_price: Final = oracle_logging_obj._response_cost_calculator(result=fresh_response)
+
+ assert payload is not None
+ assert payload["saved_cache_cost"] == uncached_price
+ assert payload["saved_cache_cost"] > 0.0
+ assert payload["response_cost"] == 0.0
+ assert logging_obj.cost_breakdown is None
+ assert oracle_logging_obj.cost_breakdown is not None
+ _assert_zeroed_copy(payload["cost_breakdown"], oracle_logging_obj.cost_breakdown)
+ finally:
+ litellm.model_cost.pop(deployment_id, None)
+
+
+def test_cache_hit_payload_reports_zero_cost_though_the_call_priced_the_response_as_fresh():
+ """The proxy prices a /v1/messages body for its cost header before the success callback learns it was a cache
+ hit, and a replayed stream's assembled response carries its original price, so the call holds full-price numbers
+ that the hit's payload must not export."""
+ deployment_id: Final = "lit8679-stale-breakdown-deployment"
+ litellm.register_model(
+ model_cost={
+ deployment_id: {
+ "litellm_provider": "openai",
+ "mode": "chat",
+ "input_cost_per_token": 1e-06,
+ "output_cost_per_token": 2e-06,
+ }
+ },
+ persist_across_reloads=False,
+ )
+ try:
+ logging_obj: Final = _lit8679_priced_logging_obj(deployment_id, "lit8679-stale-breakdown")
+ response: Final = ModelResponse(
+ model="gpt-5.4-nano",
+ choices=[litellm.Choices(message=litellm.Message(role="assistant", content="cached"))],
+ usage=litellm.Usage(prompt_tokens=10, completion_tokens=20, total_tokens=30),
+ )
+ header_price: Final = logging_obj.response_cost_calculator(result=response)
+ response._hidden_params["response_cost"] = header_price
+ logging_obj.model_call_details["cache_hit"] = True
+ now: Final = datetime.datetime.now()
+ payload: Final = get_standard_logging_object_payload(
+ kwargs={
+ "model": "gpt-5.4-nano",
+ "messages": [],
+ "cache_hit": True,
+ "response_cost": 0.0,
+ "litellm_params": logging_obj.litellm_params,
+ },
+ init_response_obj=response,
+ start_time=now,
+ end_time=now,
+ logging_obj=logging_obj,
+ status="success",
+ )
+
+ assert header_price is not None and header_price > 0.0
+ assert logging_obj.cost_breakdown is not None
+ assert payload is not None
+ assert payload["response_cost"] == 0.0
+ assert payload["hidden_params"]["response_cost"] == 0.0
+ _assert_zeroed_copy(payload["cost_breakdown"], logging_obj.cost_breakdown)
+ assert payload["saved_cache_cost"] == header_price
+ finally:
+ litellm.model_cost.pop(deployment_id, None)
+
+
+def test_uncached_price_leaves_no_failure_debug_info_for_unpriced_model():
+ """A probe that cannot price the model returns None without stamping the pricing failure on the cache-hit call."""
+ logging_obj: Final = LitellmLogging(
+ model="lit8679-model-with-no-price",
+ messages=[{"role": "user", "content": "Hi"}],
+ stream=False,
+ call_type="completion",
+ start_time=time.time(),
+ litellm_call_id="lit8679-unpriced-probe",
+ function_id="fn",
+ )
+ logging_obj.update_environment_variables(
+ model="lit8679-model-with-no-price",
+ user="",
+ optional_params={},
+ litellm_params={"metadata": {}},
+ custom_llm_provider="openai",
+ )
+ cached_response: Final = ModelResponse(
+ model="lit8679-model-with-no-price",
+ choices=[litellm.Choices(message=litellm.Message(role="assistant", content="cached"))],
+ usage=litellm.Usage(prompt_tokens=10, completion_tokens=20, total_tokens=30),
+ )
+ cached_response._hidden_params = {"cache_hit": True, "cache_key": "lit8679-key", "response_cost": 0.0}
+ assert "response_cost_failure_debug_information" not in logging_obj.model_call_details
+
+ cost: Final = logging_obj.uncached_price(result=cached_response).cost
+
+ assert cost is None
+ assert "response_cost_failure_debug_information" not in logging_obj.model_call_details
+
+
def test_enterprise_alerting_loggers_resolves_real_classes():
from litellm_enterprise.enterprise_callbacks.pagerduty.pagerduty import PagerDutyAlerting
from litellm_enterprise.enterprise_callbacks.send_emails.resend_email import ResendEmailLogger
diff --git a/tests/unit/proxy/test_common_request_processing.py b/tests/unit/proxy/test_common_request_processing.py
index 6cc4e22a26a..679e1bfd85a 100644
--- a/tests/unit/proxy/test_common_request_processing.py
+++ b/tests/unit/proxy/test_common_request_processing.py
@@ -25,6 +25,7 @@ from litellm.litellm_core_utils.bug_report import (
build_bug_report,
)
from litellm.types.router import RouterRateLimitError, RouterRateLimitErrorBasic
+from litellm.types.utils import CachingDetails
from litellm.constants import (
CLIENT_REQUESTED_MODEL_SCOPE_KEY,
MAX_LITELLM_CALL_ID_LENGTH,
@@ -11637,3 +11638,98 @@ class TestResponseCostFromLoggingObjForBridgedMessages:
assert logging_obj.cost_breakdown is not None
assert logging_obj.cost_breakdown["output_cost"] == pytest.approx(expected_output)
assert logging_obj.cost_breakdown["reasoning_cost"] == pytest.approx(expected_reasoning)
+
+
+class TestResponseCostFromLoggingObjForCacheHits:
+ BODY: Final = MappingProxyType(
+ {
+ "id": "msg_cached",
+ "type": "message",
+ "role": "assistant",
+ "model": "claude-haiku-5-5",
+ "content": [{"type": "text", "text": "cached answer"}],
+ "stop_reason": "end_turn",
+ "usage": {"input_tokens": 1200, "output_tokens": 400},
+ }
+ )
+
+ @staticmethod
+ def _logging_obj():
+ from litellm.litellm_core_utils.litellm_logging import Logging
+
+ logging_obj: Final = Logging(
+ model="claude-haiku-5-5",
+ messages=[{"role": "user", "content": "hi"}],
+ stream=False,
+ call_type="anthropic_messages",
+ start_time=datetime.datetime.now(),
+ litellm_call_id=str(uuid.uuid4()),
+ function_id="cache-hit-header",
+ )
+ logging_obj.optional_params = {}
+ return logging_obj
+
+ def test_a_v1_messages_cache_hit_costs_nothing_though_its_usage_prices_as_a_fresh_call(self):
+ fresh_cost: Final = ProxyBaseLLMRequestProcessing._response_cost_from_logging_obj(
+ response=dict(self.BODY), logging_obj=self._logging_obj()
+ )
+ hit: Final = self._logging_obj()
+ hit.caching_details = {"cache_hit": True, "cache_duration_ms": 2.0}
+
+ hit_cost: Final = ProxyBaseLLMRequestProcessing._response_cost_from_logging_obj(
+ response=dict(self.BODY), logging_obj=hit
+ )
+
+ assert fresh_cost is not None and fresh_cost > 0
+ assert hit_cost == 0.0
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ ("hidden_params", "caching_details", "expected_header"),
+ (
+ (
+ {"cache_hit": True, "response_cost": 0.0},
+ CachingDetails(cache_hit=True, cache_duration_ms=2.0),
+ "0.0",
+ ),
+ ({"response_cost": 0.0}, None, None),
+ ),
+ )
+ async def test_only_a_cache_hit_sends_zero_cost_headers(
+ self,
+ hidden_params: dict[str, object],
+ caching_details: CachingDetails | None,
+ expected_header: str | None,
+ ):
+ response: Final = litellm.ModelResponse()
+ response._hidden_params = hidden_params
+ logging_obj: Final = self._logging_obj()
+ logging_obj.caching_details = caching_details
+
+ headers: Final = await ProxyBaseLLMRequestProcessing.build_litellm_proxy_success_headers_from_llm_response(
+ response=response,
+ request_data={"model": "gpt-5.4-mini"},
+ request=Request({"type": "http", "method": "POST", "headers": []}),
+ user_api_key_dict=ProxyUserAPIKeyAuth(api_key="sk-test"),
+ logging_obj=logging_obj,
+ version=None,
+ proxy_logging_obj=ProxyLogging(user_api_key_cache=DualCache()),
+ )
+
+ cost_headers: Final = (
+ "x-litellm-response-cost",
+ "x-litellm-response-cost-original",
+ "x-litellm-response-cost-input",
+ "x-litellm-response-cost-output",
+ )
+ assert {name: headers.get(name) for name in cost_headers} == dict.fromkeys(cost_headers, expected_header)
+
+ def test_a_fresh_zero_cost_v1_messages_call_still_sends_no_cost_header(self):
+ logging_obj: Final = self._logging_obj()
+ logging_obj.model_call_details["response_cost"] = 0.0
+
+ cost: Final = ProxyBaseLLMRequestProcessing._response_cost_from_logging_obj(
+ response=dict(self.BODY), logging_obj=logging_obj
+ )
+
+ assert cost == ""