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)!: leave out span cost when the price lookup failed (#44187)

Max Azatian77880a0653c4
diff --git a/litellm/integrations/arize/_utils.py b/litellm/integrations/arize/_utils.py
index 3f89ac6978f..f719dacd148 100644
--- a/litellm/integrations/arize/_utils.py
+++ b/litellm/integrations/arize/_utils.py
@@ -884,7 +884,7 @@ def _set_session_and_user_attrs(span: "Span", kwargs: dict, standard_logging_pay
safe_set_attribute(span, "litellm.key_alias", str(key_alias))
-def _set_response_cost_attr(span: "Span", standard_logging_payload) -> None:
+def _set_response_cost_attr(span: "Span", standard_logging_payload: Mapping[str, object] | None) -> None:
"""Emit cost attributes from the StandardLoggingPayload when present.
Uses the OpenInference `llm.cost.total` key so Arize / Phoenix can
@@ -892,15 +892,22 @@ def _set_response_cost_attr(span: "Span", standard_logging_payload) -> None:
single total in `StandardLoggingPayload.response_cost`, so we cannot
split it into prompt/completion. We also keep the legacy
`llm.response.cost` key for back-compat with any consumer querying it.
+ When the price lookup failed, the call's total is unknown, so no cost is
+ emitted and the backend does not record the call as free. A guardrail fee
+ in `response_cost` stays on the guardrail span, as in OTel v2.
"""
if not isinstance(standard_logging_payload, dict):
return
cost: Final = standard_logging_payload.get("response_cost")
- if cost is None:
+ cost_lookup_failed: Final = (
+ standard_logging_payload.get("response_cost_failure_debug_info") is not None
+ and standard_logging_payload.get("cache_hit") is not True
+ )
+ if not isinstance(cost, (int, float, str)) or cost_lookup_failed:
return
try:
cost_value: Final = float(cost)
- except (TypeError, ValueError):
+ except ValueError:
return
safe_set_attribute(span, "llm.cost.total", cost_value)
safe_set_attribute(span, "llm.response.cost", cost_value)
diff --git a/litellm/integrations/otel/model/payloads.py b/litellm/integrations/otel/model/payloads.py
index 5bca8e01aec..e15072c009b 100644
--- a/litellm/integrations/otel/model/payloads.py
+++ b/litellm/integrations/otel/model/payloads.py
@@ -481,6 +481,7 @@ class LLMCallSpanData:
embedding_output: Final = (
EmbeddingOutput.from_response(response) if operation is GenAIOperation.EMBEDDINGS else None
)
+ cost_lookup_failed: Final = payload.get("response_cost_failure_debug_info") is not None and not cache_hit
return cls(
operation=operation,
provider=resolve_provider(as_str(payload.get("custom_llm_provider"))),
@@ -491,7 +492,7 @@ class LLMCallSpanData:
usage=LLMUsage.from_standard_logging_payload(payload),
finish_reasons=finish_reasons,
error=_parse_error(payload),
- response_cost=as_float(payload.get("response_cost")),
+ response_cost=None if cost_lookup_failed else as_float(payload.get("response_cost")),
cost=LLMCost.from_breakdown(cast("Mapping[str, object] | None", payload.get("cost_breakdown"))),
server=None if cache_hit else ServerInfo.from_api_base(context.api_base),
identity=context.identity,
diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.py
index 8d5be388eff..e2eed3cf6d5 100644
--- a/litellm/litellm_core_utils/litellm_logging.py
+++ b/litellm/litellm_core_utils/litellm_logging.py
@@ -1939,6 +1939,8 @@ class Logging(LiteLLMLoggingBaseClass):
used for consistent cost calculation across response headers + logging integrations.
"""
+ self.model_call_details.pop("response_cost_failure_debug_information", None)
+
if cache_hit is None:
cache_hit = self.model_call_details.get("cache_hit", False)
@@ -2099,15 +2101,17 @@ class Logging(LiteLLMLoggingBaseClass):
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
+ previous_failure_debug_info: Final = self.model_call_details.get(debug_key)
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:
+ if previous_failure_debug_info is None:
self.model_call_details.pop(debug_key, None)
+ else:
+ self.model_call_details[debug_key] = previous_failure_debug_info
def _record_zero_cost_diagnostic(
self,
diff --git a/tests/unit/integrations/arize/test_arize_utils.py b/tests/unit/integrations/arize/test_arize_utils.py
index 0d833b90148..31699359bbe 100644
--- a/tests/unit/integrations/arize/test_arize_utils.py
+++ b/tests/unit/integrations/arize/test_arize_utils.py
@@ -1,5 +1,6 @@
import json
-from typing import Optional
+from collections.abc import Mapping
+from typing import Final, Optional
# Adds the grandparent directory to sys.path to allow importing project modules
@@ -7,6 +8,7 @@ import asyncio
import httpx
import pytest
+from opentelemetry.sdk.trace import TracerProvider
import litellm
from litellm.integrations._types.open_inference import (
@@ -17,7 +19,7 @@ from litellm.integrations._types.open_inference import (
from litellm.integrations.arize._utils import _coerce_response_obj_for_attrs, _parse_passthrough_response
from litellm.integrations.arize.arize import ArizeLogger
from litellm.integrations.custom_logger import CustomLogger
-from litellm.types.utils import Choices, StandardCallbackDynamicParams
+from litellm.types.utils import Choices, ModelResponse, StandardCallbackDynamicParams
def test_arize_set_attributes():
@@ -1015,6 +1017,55 @@ def test_arize_emits_response_cost():
assert attrs["llm.response.cost"] == 0.0012345 # legacy key still emitted
+_PRICE_LOOKUP_FAILED: Final = {"error_str": "This model isn't mapped yet. model=openai/unpriced-model", "traceback_str": ""}
+
+
+ ("cost_fields", "expected_cost"),
+ [
+ pytest.param({"response_cost": 0.0}, 0.0, id="free-model"),
+ pytest.param(
+ {"response_cost": 0.0, "response_cost_failure_debug_info": _PRICE_LOOKUP_FAILED},
+ None,
+ id="unpriced",
+ ),
+ pytest.param(
+ {"response_cost": 0.0, "response_cost_failure_debug_info": _PRICE_LOOKUP_FAILED, "cache_hit": True},
+ 0.0,
+ id="unpriced-cache-hit",
+ ),
+ pytest.param({"response_cost": "not-a-number"}, None, id="malformed-cost"),
+ pytest.param(
+ {"response_cost": 0.002, "response_cost_failure_debug_info": _PRICE_LOOKUP_FAILED},
+ None,
+ id="unpriced-with-guardrail-fee",
+ ),
+ ],
+)
+def test_arize_cost_attrs_tell_unpriced_call_from_free_call(
+ cost_fields: Mapping[str, object], expected_cost: float | None
+) -> None:
+ span: Final = TracerProvider().get_tracer(__name__).start_span("litellm_request")
+ kwargs: Final = {
+ "model": "unpriced-model",
+ "messages": [{"role": "user", "content": "hi"}],
+ "standard_logging_object": {"model_parameters": {}, "metadata": {}, "call_type": "completion", **cost_fields},
+ "optional_params": {},
+ "litellm_params": {"custom_llm_provider": "openai"},
+ }
+ response_obj: Final = ModelResponse(
+ usage={"total_tokens": 30, "completion_tokens": 20, "prompt_tokens": 10},
+ choices=[Choices(message={"role": "assistant", "content": "ok"})],
+ model="unpriced-model",
+ id="r4",
+ )
+
+ ArizeLogger.set_arize_attributes(span, kwargs, response_obj)
+
+ assert span.attributes.get("llm.cost.total") == expected_cost
+ assert span.attributes.get("llm.response.cost") == expected_cost
+
+
def test_arize_passthrough_bedrock_anthropic_normalization():
"""Bedrock-Anthropic passthrough: input/output text must be set so the
span renders something other than raw provider attrs."""
diff --git a/tests/unit/integrations/otel/test_otel_v2_emitter.py b/tests/unit/integrations/otel/test_otel_v2_emitter.py
index 0905e9e7c30..6e29b2e9c68 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 collections.abc import Mapping
from typing import Final
import pytest
@@ -23,6 +24,7 @@ from litellm.integrations.otel.plumbing import context as ctx_mod # noqa: E402
from litellm.integrations.otel.plumbing import providers # noqa: E402
from litellm.integrations.otel.emitter import SpanEmitter, attribute_budget, span_attribute_limit # noqa: E402
from litellm.integrations.otel.emitter import stamp_error # noqa: E402
+from litellm.integrations.otel.mappers import LangfuseMapper # noqa: E402 # after the opentelemetry importorskip
from litellm.integrations.otel.mappers.utils import MAX_TOOL_DEFINITION_ATTRS_PER_SPAN # noqa: E402
from litellm.integrations.otel.model.payloads import ( # noqa: E402
GuardrailSpanData,
@@ -91,6 +93,61 @@ def test_llm_call_span_cost_breakdown():
assert f"{LiteLLM.COST_PREFIX}margin_total_amount" not in a
+_PRICE_LOOKUP_FAILED: Final = {"error_str": "This model isn't mapped yet. model=openai/unpriced-model", "traceback_str": ""}
+
+
+ ("cost_fields", "expected_cost"),
+ [
+ pytest.param({"response_cost": 0.0}, 0.0, id="free-model"),
+ pytest.param(
+ {"response_cost": 0.0, "response_cost_failure_debug_info": _PRICE_LOOKUP_FAILED},
+ None,
+ id="unpriced",
+ ),
+ pytest.param(
+ {"response_cost": 0.0, "response_cost_failure_debug_info": _PRICE_LOOKUP_FAILED, "cache_hit": True},
+ 0.0,
+ id="unpriced-cache-hit",
+ ),
+ ],
+)
+def test_llm_call_span_tells_unpriced_call_from_free_call(
+ cost_fields: Mapping[str, object], expected_cost: float | None
+) -> None:
+ engine, exporter = _engine()
+ data: Final = LLMCallSpanData.from_standard_logging_payload(_payload(**cost_fields))
+
+ engine.emit(SpanRole.LLM_CALL, data)
+
+ (span,) = exporter.get_finished_spans()
+ assert span.attributes.get(f"{LiteLLM.COST_PREFIX}total") == expected_cost
+ langfuse_cost_details: Final = LangfuseMapper().map(data).get("langfuse.observation.cost_details")
+ langfuse_cost: Final = json.loads(langfuse_cost_details)["total"] if langfuse_cost_details is not None else None
+ assert langfuse_cost == expected_cost
+
+
+def test_unpriced_call_keeps_the_guardrail_charge_on_the_guardrail_span() -> None:
+ engine, exporter = _engine()
+ payload: Final = _payload(
+ response_cost=0.002,
+ response_cost_failure_debug_info=_PRICE_LOOKUP_FAILED,
+ cost_breakdown={"guardrail_cost": 0.002, "total_cost": 0.002},
+ )
+
+ engine.emit(SpanRole.LLM_CALL, LLMCallSpanData.from_standard_logging_payload(payload))
+ engine.emit(
+ SpanRole.GUARDRAIL,
+ GuardrailSpanData.from_logging_entry(
+ {"guardrail_name": "bedrock", "guardrail_status": "success", "guardrail_cost": 0.002}
+ ),
+ )
+
+ llm_span, guardrail_span = exporter.get_finished_spans()
+ assert f"{LiteLLM.COST_PREFIX}total" not in llm_span.attributes
+ assert guardrail_span.attributes[LiteLLM.GUARDRAIL_COST] == 0.002
+
+
def test_tracer_scope_carries_litellm_version():
from litellm._version import version as litellm_version
diff --git a/tests/unit/litellm_core_utils/test_litellm_logging.py b/tests/unit/litellm_core_utils/test_litellm_logging.py
index 00c2b1ad8a8..9d651b4ae3e 100644
--- a/tests/unit/litellm_core_utils/test_litellm_logging.py
+++ b/tests/unit/litellm_core_utils/test_litellm_logging.py
@@ -11014,6 +11014,87 @@ def test_uncached_price_leaves_no_failure_debug_info_for_unpriced_model():
assert "response_cost_failure_debug_information" not in logging_obj.model_call_details
+PR44187_PRICED_MODEL: Final = "lit44187-priced-model"
+PR44187_INPUT_COST: Final = 1e-6
+PR44187_OUTPUT_COST: Final = 2e-6
+PR44187_START_TIME: Final = datetime.datetime(2026, 10, 20)
+
+
+def pr44187_priced_model() -> Iterator[str]:
+ litellm.register_model(
+ model_cost={
+ PR44187_PRICED_MODEL: {
+ "input_cost_per_token": PR44187_INPUT_COST,
+ "output_cost_per_token": PR44187_OUTPUT_COST,
+ "litellm_provider": "openai",
+ "mode": "chat",
+ }
+ },
+ persist_across_reloads=False,
+ )
+ try:
+ yield PR44187_PRICED_MODEL
+ finally:
+ litellm.model_cost.pop(PR44187_PRICED_MODEL, None)
+
+
+def _pr44187_logging_obj(model: str) -> LitellmLogging:
+ logging_obj: Final = LitellmLogging(
+ model=model,
+ messages=[{"role": "user", "content": "Hi"}],
+ stream=True,
+ call_type="completion",
+ start_time=PR44187_START_TIME,
+ litellm_call_id="lit44187-late-priced-stream",
+ function_id="fn",
+ )
+ logging_obj.update_environment_variables(
+ model=model, user="", optional_params={}, litellm_params={"metadata": {}}, custom_llm_provider="openai"
+ )
+ return logging_obj
+
+
+def _pr44187_response(model: str) -> ModelResponse:
+ return ModelResponse(
+ model=model,
+ choices=[litellm.Choices(message=litellm.Message(role="assistant", content="hello"))],
+ usage=litellm.Usage(prompt_tokens=10, completion_tokens=20, total_tokens=30),
+ )
+
+
+def test_a_later_successful_price_clears_an_earlier_price_failure(pr44187_priced_model: str):
+ logging_obj: Final = _pr44187_logging_obj("openai/lit44187-deployment-name")
+ stream_start_cost: Final = logging_obj.response_cost_calculator(
+ result=_pr44187_response("lit44187-deployment-name"), litellm_model_name="openai/lit44187-deployment-name"
+ )
+ assert stream_start_cost is None
+ assert logging_obj.model_call_details["response_cost_failure_debug_information"] is not None
+
+ final_cost: Final = logging_obj.response_cost_calculator(
+ result=_pr44187_response(pr44187_priced_model), litellm_model_name=pr44187_priced_model
+ )
+
+ assert final_cost == pytest.approx(10 * PR44187_INPUT_COST + 20 * PR44187_OUTPUT_COST)
+ assert logging_obj.model_call_details.get("response_cost_failure_debug_information") is None
+
+
[email protected]("uncached_model_is_priced", [True, False], ids=["uncached-priced", "uncached-unpriced"])
+def test_uncached_price_keeps_an_earlier_price_failure(pr44187_priced_model: str, uncached_model_is_priced: bool):
+ uncached_model: Final = pr44187_priced_model if uncached_model_is_priced else "lit44187-other-unpriced-model"
+ logging_obj: Final = _pr44187_logging_obj(uncached_model)
+ logging_obj.response_cost_calculator(
+ result=_pr44187_response("lit44187-deployment-name"), litellm_model_name="openai/lit44187-deployment-name"
+ )
+ earlier_failure: Final = logging_obj.model_call_details["response_cost_failure_debug_information"]
+ assert earlier_failure is not None
+
+ uncached: Final = logging_obj.uncached_price(result=_pr44187_response(uncached_model))
+
+ assert (uncached.cost is not None) is uncached_model_is_priced
+ assert logging_obj.model_call_details["response_cost_failure_debug_information"] == earlier_failure
+
+
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