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]

_transform_response_api_usage_to_chat_usage

Ishaan Jaff51dc24a40548
diff --git a/litellm/cost_calculator.py b/litellm/cost_calculator.py
index 1d10fa1f9e1..fb49c079812 100644
--- a/litellm/cost_calculator.py
+++ b/litellm/cost_calculator.py
@@ -44,7 +44,8 @@ from litellm.llms.vertex_ai.cost_calculator import cost_router as google_cost_ro
from litellm.llms.vertex_ai.image_generation.cost_calculator import (
cost_calculator as vertex_ai_image_cost_calculator,
)
-from litellm.types.llms.openai import HttpxBinaryResponseContent
+from litellm.responses.utils import ResponseAPILoggingUtils
+from litellm.types.llms.openai import HttpxBinaryResponseContent, ResponsesAPIResponse
from litellm.types.rerank import RerankBilledUnits, RerankResponse
from litellm.types.utils import (
CallTypesLiteral,
@@ -601,6 +602,14 @@ def completion_cost( # noqa: PLR0915
_usage = usage_obj.model_dump()
else:
_usage = usage_obj
+
+ if ResponseAPILoggingUtils._is_response_api_usage(_usage):
+ _usage = (
+ ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage(
+ _usage
+ ).model_dump()
+ )
+
# get input/output tokens from completion_response
prompt_tokens = _usage.get("prompt_tokens", 0)
completion_tokens = _usage.get("completion_tokens", 0)
@@ -799,6 +808,7 @@ def response_cost_calculator(
TextCompletionResponse,
HttpxBinaryResponseContent,
RerankResponse,
+ ResponsesAPIResponse,
],
model: str,
custom_llm_provider: Optional[str],
diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.py
index 7adecc511d1..8a07ac9a8eb 100644
--- a/litellm/litellm_core_utils/litellm_logging.py
+++ b/litellm/litellm_core_utils/litellm_logging.py
@@ -1015,6 +1015,7 @@ class Logging(LiteLLMLoggingBaseClass):
or isinstance(result, RerankResponse)
or isinstance(result, FineTuningJob)
or isinstance(result, LiteLLMBatch)
+ or isinstance(result, ResponsesAPIResponse)
):
## HIDDEN PARAMS ##
hidden_params = getattr(result, "_hidden_params", {})
diff --git a/litellm/responses/streaming_iterator.py b/litellm/responses/streaming_iterator.py
index ae592d8c411..b99d81309a5 100644
--- a/litellm/responses/streaming_iterator.py
+++ b/litellm/responses/streaming_iterator.py
@@ -1,4 +1,6 @@
+import asyncio
import json
+from datetime import datetime
from typing import Any, AsyncIterator, Dict, Optional, Union
import httpx
@@ -11,6 +13,8 @@ from litellm.types.llms.openai import (
)
from litellm.utils import CustomStreamWrapper
+COMPLETED_OPENAI_CHUNK_TYPE = "response.completed"
+
class ResponsesAPIStreamingIterator:
"""
@@ -33,14 +37,13 @@ class ResponsesAPIStreamingIterator:
self.stream_iterator = response.aiter_lines()
self.finished = False
self.responses_api_provider_config = responses_api_provider_config
+ self.completed_response: Optional[ResponsesAPIStreamingResponse] = None
+ self.start_time = datetime.now()
def __aiter__(self):
return self
async def __anext__(self) -> ResponsesAPIStreamingResponse:
- if self.finished:
- raise StopAsyncIteration
-
try:
# Get the next chunk from the stream
try:
@@ -75,6 +78,19 @@ class ResponsesAPIStreamingIterator:
logging_obj=self.logging_obj,
)
)
+ # Store the completed response
+ if (
+ openai_responses_api_chunk
+ and openai_responses_api_chunk.type
+ == COMPLETED_OPENAI_CHUNK_TYPE
+ ):
+ self.completed_response = openai_responses_api_chunk
+ await self.logging_obj.async_success_handler(
+ result=self.completed_response,
+ start_time=self.start_time,
+ end_time=datetime.now(),
+ cache_hit=None,
+ )
return openai_responses_api_chunk
return ResponsesAPIStreamingResponse(
diff --git a/litellm/types/llms/openai.py b/litellm/types/llms/openai.py
index 55f05b5cdca..ddca244b467 100644
--- a/litellm/types/llms/openai.py
+++ b/litellm/types/llms/openai.py
@@ -735,6 +735,8 @@ class ResponsesAPIRequestParams(ResponsesAPIOptionalRequestParams, total=False):
class OutputTokensDetails(BaseModel):
reasoning_tokens: int
+ model_config = {"extra": "allow"}
+
class ResponseAPIUsage(BaseModel):
input_tokens: int
@@ -743,12 +745,14 @@ class ResponseAPIUsage(BaseModel):
output_tokens: int
"""The number of output tokens."""
- output_tokens_details: OutputTokensDetails
+ output_tokens_details: Optional[OutputTokensDetails]
"""A detailed breakdown of the output tokens."""
total_tokens: int
"""The total number of tokens used."""
+ model_config = {"extra": "allow"}
+
class ResponsesAPIResponse(BaseModel):
id: str
diff --git a/tests/llm_responses_api_testing/test_openai_responses_api.py b/tests/llm_responses_api_testing/test_openai_responses_api.py
index 54464c05099..32e2e4f80f6 100644
--- a/tests/llm_responses_api_testing/test_openai_responses_api.py
+++ b/tests/llm_responses_api_testing/test_openai_responses_api.py
@@ -1,10 +1,14 @@
import os
import sys
import pytest
+import asyncio
+from typing import Optional
sys.path.insert(0, os.path.abspath("../.."))
import litellm
+from litellm.integrations.custom_logger import CustomLogger
import json
+from litellm.types.utils import StandardLoggingPayload
@pytest.mark.asyncio
@@ -29,3 +33,87 @@ async def test_basic_openai_responses_api_streaming():
async for event in response:
print("litellm response=", json.dumps(event, indent=4, default=str))
+
+
+class TestCustomLogger(CustomLogger):
+ def __init__(
+ self,
+ ):
+ self.standard_logging_object: Optional[StandardLoggingPayload] = None
+
+ async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):
+ print("in async_log_success_event")
+ self.standard_logging_object = kwargs["standard_logging_object"]
+ pass
+
+
+async def test_basic_openai_responses_api_streaming_with_logging():
+ litellm._turn_on_debug()
+ litellm.set_verbose = True
+ test_custom_logger = TestCustomLogger()
+ litellm.callbacks = [test_custom_logger]
+ response = await litellm.aresponses(
+ model="gpt-4o",
+ input="hi",
+ stream=True,
+ )
+
+ async for event in response:
+ print("litellm response=", json.dumps(event, indent=4, default=str))
+
+ print("sleeping for 2 seconds...")
+ await asyncio.sleep(2)
+ print(
+ "standard logging payload=",
+ json.dumps(test_custom_logger.standard_logging_object, indent=4, default=str),
+ )
+
+
+async def test_basic_openai_responses_api_non_streaming_with_logging():
+ litellm._turn_on_debug()
+ litellm.set_verbose = True
+ test_custom_logger = TestCustomLogger()
+ litellm.callbacks = [test_custom_logger]
+ response = await litellm.aresponses(
+ model="gpt-4o",
+ input="hi",
+ )
+
+ print("litellm response=", json.dumps(response, indent=4, default=str))
+ print("response hidden params=", response._hidden_params)
+
+ print("sleeping for 2 seconds...")
+ await asyncio.sleep(2)
+ print(
+ "standard logging payload=",
+ json.dumps(test_custom_logger.standard_logging_object, indent=4, default=str),
+ )
+
+ assert test_custom_logger.standard_logging_object is not None
+
+ # validate token counts match OpenAI response
+ assert (
+ test_custom_logger.standard_logging_object["prompt_tokens"]
+ == response["usage"]["input_tokens"]
+ )
+ assert (
+ test_custom_logger.standard_logging_object["completion_tokens"]
+ == response["usage"]["output_tokens"]
+ )
+ assert (
+ test_custom_logger.standard_logging_object["total_tokens"]
+ == response["usage"]["input_tokens"] + response["usage"]["output_tokens"]
+ )
+
+ # validate spend > 0
+ assert test_custom_logger.standard_logging_object["response_cost"] > 0
+
+ # validate response id matches OpenAI
+
+ # validate model matches
+
+ # validate messages matches
+
+ # validate responses matches