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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(langfuse): log Responses API token usage instead of zeros (#42212)
devin-ai-integration[bot]c5ac1845b0b6
diff --git a/litellm/integrations/langfuse/langfuse.py b/litellm/integrations/langfuse/langfuse.pyindex faba4f5eb20..42f605443c7 100644--- a/litellm/integrations/langfuse/langfuse.py+++ b/litellm/integrations/langfuse/langfuse.py@@ -29,9 +29,10 @@ from litellm.litellm_core_utils.initialize_dynamic_callback_params import ()from litellm.litellm_core_utils.redact_messages import redact_user_api_key_infofrom litellm.llms.custom_httpx.http_handler import get_httpx_client+from litellm.responses.utils import ResponseAPILoggingUtilsfrom litellm.secret_managers.main import str_to_boolfrom litellm.types.integrations.langfuse import *-from litellm.types.llms.openai import HttpxBinaryResponseContent, ResponsesAPIResponse+from litellm.types.llms.openai import HttpxBinaryResponseContent, ResponseAPIUsage, ResponsesAPIResponsefrom litellm.types.utils import (EmbeddingResponse,ImageResponse,@@ -108,6 +109,27 @@ class _UsageObject(Protocol):def get(self, key: Literal["cache_creation_input_tokens", "cache_read_input_tokens"], /) -> int | None: ...+def _chat_usage(raw_usage: _UsageObject | None) -> _UsageObject | None:+ """Chat-shaped view of a response's usage.++ /v1/responses carries ResponseAPIUsage (input_tokens/output_tokens), and an+ assembled /v1/responses stream carries a plain dict of chat usage fields.+ Any other usage object, or a dict whose token counts are not integers, is+ returned unchanged.+ """+ if isinstance(raw_usage, ResponseAPIUsage):+ return ResponseAPILoggingUtils.transform_response_api_usage_to_chat_usage(raw_usage)+ usage_fields: Final = _object_mapping(raw_usage)+ if usage_fields is None or not (+ ResponseAPILoggingUtils.is_response_api_usage(usage_fields) or "prompt_tokens" in usage_fields+ ):+ return raw_usage+ try:+ return ResponseAPILoggingUtils.transform_response_api_usage_to_chat_usage(usage_fields)+ except ValueError:+ return raw_usage++def _extract_cache_read_input_tokens(usage_obj) -> int:"""Extract cache_read_input_tokens from usage object.@@ -815,7 +837,8 @@ class LangFuseLogger:if response_obj is not None:if hasattr(response_obj, "id") and response_obj.get("id", None) is not None:generation_id = _logging_id(start_time, response_obj)- _usage_obj: Final[_UsageObject | None] = getattr(response_obj, "usage", None)+ _raw_usage_obj: Final[_UsageObject | None] = getattr(response_obj, "usage", None)+ _usage_obj: Final = _chat_usage(_raw_usage_obj)if _usage_obj:# Safely get usage values, defaulting None to 0 for Langfuse compatibility.diff --git a/tests/e2e/coverage_registry/logging.yaml b/tests/e2e/coverage_registry/logging.yamlindex 9a851587fce..69cad8eb22e 100644--- a/tests/e2e/coverage_registry/logging.yaml+++ b/tests/e2e/coverage_registry/logging.yaml@@ -28,3 +28,4 @@- {id: logging.niche_integrations.success.logs_spend, module: logging, tier: P2, event: success, assertions: [logs_spend], exercised_on: [chat_completions], source: grammar, rationale: "SMOKE cohort: athina/galileo/deepeval/langtrace/weave/lunary/humanloop/traceloop/helicone/argilla/newrelic/sqs/supabase/dynamodb/agentops/lago/etc"}- {id: logging.niche_integrations.failure.logs_spend, module: logging, tier: P2, event: failure, assertions: [logs_spend], exercised_on: [chat_completions], source: grammar, rationale: "SMOKE niche failure path"}- {id: logging.langfuse.success.logs_spend, module: logging, tier: P1, event: success, assertions: [logs_spend], exercised_on: [chat_completions], source: "integrations/langfuse/langfuse_otel.py", rationale: "Team-scoped Langfuse delivery via /team/callback; LangChain-ecosystem evals spend"}+- {id: logging.langfuse.success.logs_usage, module: logging, tier: P1, event: success, assertions: [logs_usage], exercised_on: [responses], source: "integrations/langfuse/langfuse.py", rationale: "Classic Langfuse SDK generations must carry token usage on the /v1/responses path; ResponseAPIUsage read as chat Usage logs all zeros (LIT-8238)"}diff --git a/tests/e2e/logging/test_responses_langfuse_usage_e2e.py b/tests/e2e/logging/test_responses_langfuse_usage_e2e.pynew file mode 100644index 00000000000..4dfd5d0ec33--- /dev/null+++ b/tests/e2e/logging/test_responses_langfuse_usage_e2e.py@@ -0,0 +1,158 @@+"""Live e2e: Langfuse token usage on the /v1/responses path.++Covers logging.langfuse.success.logs_usage: a key-scoped ``langfuse``+(classic SDK) callback must log non-zero input/output tokens to the Langfuse+generation for a /v1/responses call, streamed or not. A ResponsesAPIResponse+carries ResponseAPIUsage (input_tokens/output_tokens), and an assembled stream+carries a plain dict of chat usage fields; the logger must normalize both+before building usage_details, or Langfuse shows 0 input / 0 output while+cost is still right.+"""++from __future__ import annotations++import pytest+from e2e_config import CHEAP_OPENAI_MODEL, unique_marker+from e2e_metadata import Domain, Mode, Provider, Route, Subject, meta+from lifecycle import ResourceManager+from logging_client import (+ LangfuseCreds,+ LoggingClient,+ first_ok,+ load_langfuse_creds,+)+from models import (+ KeyLoggingCallback,+ KeyLoggingCallbackVars,+ KeyMetadata,+ ResponsesApiResponse,+ ResponsesStreamEvent,+ ResponsesUsage,+)+from pydantic import BaseModel, ConfigDict, TypeAdapter++pytestmark = pytest.mark.e2e+++class _LangfuseUsageDetails(BaseModel):+ model_config = ConfigDict(extra="ignore")++ input: int | None = None+ output: int | None = None+ total: int | None = None+ cache_read_input_tokens: int | None = None+++_USAGE_DETAILS_ADAPTER: TypeAdapter[_LangfuseUsageDetails] = TypeAdapter(_LangfuseUsageDetails)++[email protected](scope="session")+def langfuse_creds() -> LangfuseCreds:+ return load_langfuse_creds()+++def _completed_usage(stream_events: list[str]) -> ResponsesUsage | None:+ """Usage the proxy relayed on the stream's response.completed event."""+ for raw in stream_events:+ event = ResponsesStreamEvent.model_validate_json(raw)+ if event.type == "response.completed" and event.response is not None:+ return event.response.usage+ return None+++class TestResponsesLangfuseUsage:+ @pytest.mark.covers("logging.langfuse.success.logs_usage", exercised_on=["responses"])+ @pytest.mark.parametrize(+ "stream",+ [+ pytest.param(+ False,+ marks=meta(+ Subject(+ domain=Domain.OBSERVABILITY,+ route=Route.RESPONSES,+ providers=(Provider.OPENAI,),+ models=(CHEAP_OPENAI_MODEL,),+ mode=Mode.NONSTREAM,+ )+ ),+ id="non_streaming",+ ),+ pytest.param(+ True,+ marks=meta(+ Subject(+ domain=Domain.OBSERVABILITY,+ route=Route.RESPONSES,+ providers=(Provider.OPENAI,),+ models=(CHEAP_OPENAI_MODEL,),+ mode=Mode.STREAM,+ )+ ),+ id="streaming",+ ),+ ],+ )+ def test_responses_call_logs_nonzero_token_usage(+ self, client: LoggingClient, langfuse_creds: LangfuseCreds, resources: ResourceManager, stream: bool+ ) -> None:+ key_alias = f"lf-resp-key-{unique_marker()}"+ key = client.key_with_alias(+ key_alias,+ models=[CHEAP_OPENAI_MODEL],+ metadata=KeyMetadata(+ logging=[+ KeyLoggingCallback(+ callback_name="langfuse",+ callback_type="success",+ callback_vars=KeyLoggingCallbackVars(+ langfuse_public_key=langfuse_creds.public_key,+ langfuse_secret_key=langfuse_creds.secret_key,+ langfuse_host=langfuse_creds.host,+ ),+ )+ ]+ ),+ )+ resources.defer(lambda: client.delete_key(key))++ marker = unique_marker()+ outcome = first_ok(+ client,+ lambda: client.responses_raw(+ key, CHEAP_OPENAI_MODEL, f"reply with one word {marker}", max_output_tokens=64, stream=stream+ ),+ )+ usage = (+ _completed_usage(outcome.stream_events)+ if stream+ else ResponsesApiResponse.model_validate_json(outcome.body).usage+ )+ assert usage is not None and usage.input_tokens > 0, (+ f"the /v1/responses reply must report input_tokens, got {outcome.body[:300]} "+ f"with {len(outcome.stream_events)} stream events"+ )++ observation = client.poll_langfuse_observation(+ langfuse_creds,+ key_alias=key_alias,+ prompt_marker=marker,+ )+ assert observation is not None, (+ f"the key's /v1/responses call (marker {marker}) never reached Langfuse within the deadline"+ )+ assert observation.usage_details is not None, (+ f"the Langfuse generation must carry usageDetails, got {observation.model_dump_json()}"+ )+ details = _USAGE_DETAILS_ADAPTER.validate_python(observation.usage_details)+ cache_read = details.cache_read_input_tokens or 0+ assert details.input is not None and details.input > 0, (+ f"usageDetails.input must be non-zero, got {details.model_dump()}"+ )+ assert details.input + cache_read == usage.input_tokens, (+ f"usageDetails.input {details.input} + cache_read {cache_read} must equal the proxy's "+ f"input_tokens {usage.input_tokens}"+ )+ assert details.output == usage.output_tokens, (+ f"usageDetails.output {details.output} must equal the proxy's output_tokens {usage.output_tokens}"+ )diff --git a/tests/e2e/models.py b/tests/e2e/models.pyindex 21fa015525a..b2b35d953d0 100644--- a/tests/e2e/models.py+++ b/tests/e2e/models.py@@ -477,6 +477,35 @@ class ChatResponse(BaseModel):guardrail_information: list[GuardrailInformationEntry] | None = None+class ResponsesInputTokensDetails(BaseModel):+ cached_tokens: int | None = None+++class ResponsesUsage(BaseModel):+ """`/v1/responses` usage shape: input/output tokens, not prompt/completion."""++ input_tokens: int+ output_tokens: int+ total_tokens: int | None = None+ input_tokens_details: ResponsesInputTokensDetails | None = None+++class ResponsesApiResponse(BaseModel):+ model_config = ConfigDict(extra="ignore")++ id: str | None = None+ usage: ResponsesUsage | None = None+++class ResponsesStreamEvent(BaseModel):+ """One `/v1/responses` SSE event; `response.completed` carries the final response."""++ model_config = ConfigDict(extra="ignore")++ type: str+ response: ResponsesApiResponse | None = None++# ---------- anthropic /v1/messages + count_tokens ----------diff --git a/tests/unit/integrations/test_langfuse.py b/tests/unit/integrations/test_langfuse.pyindex 6d09c42df76..aff69b6403b 100644--- a/tests/unit/integrations/test_langfuse.py+++ b/tests/unit/integrations/test_langfuse.py@@ -5,7 +5,7 @@ import threadingimport timeimport typesimport unittest-from typing import Final, Optional+from typing import Finalfrom unittest.mock import MagicMock, Mock, patchimport httpx@@ -29,9 +29,10 @@ from litellm.types.utils import (TextCompletionResponse,)-# Import LangfuseUsageDetails directly from the module where it's definedfrom litellm.types.integrations.langfuse import *+from litellm.responses.utils import ResponseAPILoggingUtils+from litellm.types.llms.openai import InputTokensDetails, ResponseAPIUsage, ResponsesAPIResponseclass TestLangfuseUsageDetails(unittest.TestCase):@@ -328,7 +329,103 @@ class TestLangfuseUsageDetails(unittest.TestCase):mock_add_prompt_params.assert_called_once()- def _build_standard_logging_payload(self, trace_id: Optional[str] = None):+ def _responses_api_usage(self) -> ResponseAPIUsage:+ return ResponseAPIUsage(+ input_tokens=16,+ output_tokens=21,+ total_tokens=37,+ input_tokens_details=InputTokensDetails(cached_tokens=4),+ )++ def _log_responses_api_generation(self, response_obj: ResponsesAPIResponse) -> dict[str, int]:+ self.use_real_langfuse_client()++ kwargs = {+ "model": "gpt-5.5",+ "messages": [{"role": "user", "content": "Test"}],+ "litellm_params": {"metadata": {}},+ "optional_params": {},+ "litellm_call_id": "test-call-id-responses-api-usage",+ "standard_logging_object": self._build_standard_logging_payload(),+ "response_cost": 0.0,+ }++ fixed_time = datetime.datetime(2024, 1, 1, 12, 0, 0)++ self.logger._log_langfuse_v2(+ user_id="test-user",+ metadata={},+ litellm_params=kwargs["litellm_params"],+ output={"role": "assistant", "content": "Response"},+ start_time=fixed_time,+ end_time=fixed_time + datetime.timedelta(seconds=1),+ kwargs=kwargs,+ optional_params=kwargs["optional_params"],+ input={"messages": kwargs["messages"]},+ response_obj=response_obj,+ level="DEFAULT",+ litellm_call_id=kwargs["litellm_call_id"],+ )++ return json.loads(self.exported_generation().attributes["langfuse.observation.usage_details"])++ def test_log_langfuse_v2_responses_api_usage(self):+ """+ Regression test: a /v1/responses response carries ResponseAPIUsage+ (input_tokens/output_tokens), which must be normalized to a chat Usage+ before Langfuse usage_details are read, or generations log 0 tokens.+ """+ response_obj = ResponsesAPIResponse(id="resp_123", created_at=0, output=[], usage=self._responses_api_usage())++ usage_details = self._log_responses_api_generation(response_obj)++ # input is reduced by cache_read_input_tokens per Langfuse docs+ assert usage_details == {+ "input": 12,+ "output": 21,+ "total": 37,+ "cache_creation_input_tokens": 0,+ "cache_read_input_tokens": 4,+ }++ def test_log_langfuse_v2_streamed_responses_api_usage(self):+ """+ Regression test: an assembled /v1/responses stream reaches the logger+ with its usage already converted to a plain dict of chat usage fields,+ the shape litellm_logging stores on the completed response.+ """+ response_obj = ResponsesAPIResponse(id="resp_123", created_at=0, output=[])+ streamed_usage = ResponseAPILoggingUtils.transform_response_api_usage_to_chat_usage(+ self._responses_api_usage()+ ).model_dump()+ setattr(response_obj, "usage", streamed_usage)++ usage_details = self._log_responses_api_generation(response_obj)++ assert usage_details == {+ "input": 12,+ "output": 21,+ "total": 37,+ "cache_creation_input_tokens": 0,+ "cache_read_input_tokens": 4,+ }++ def test_log_langfuse_v2_malformed_responses_api_usage_still_logs(self):+ """A usage dict whose token counts fail validation is logged as zero usage, not dropped."""+ response_obj = ResponsesAPIResponse(id="resp_123", created_at=0, output=[])+ setattr(response_obj, "usage", {"input_tokens": 16, "output_tokens": None})++ usage_details = self._log_responses_api_generation(response_obj)++ assert usage_details == {+ "input": 0,+ "output": 0,+ "total": 0,+ "cache_creation_input_tokens": 0,+ "cache_read_input_tokens": 0,+ }++ def _build_standard_logging_payload(self, trace_id: str | None = None):payload = {"id": "payload-id","call_type": "completion",