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(proxy): track streamed passthrough Responses cost

william-xuec8655c382516
diff --git a/litellm/proxy/pass_through_endpoints/llm_provider_handlers/openai_passthrough_logging_handler.py b/litellm/proxy/pass_through_endpoints/llm_provider_handlers/openai_passthrough_logging_handler.py
index f79b589f6b3..28aa09d5a94 100644
--- a/litellm/proxy/pass_through_endpoints/llm_provider_handlers/openai_passthrough_logging_handler.py
+++ b/litellm/proxy/pass_through_endpoints/llm_provider_handlers/openai_passthrough_logging_handler.py
@@ -26,7 +26,7 @@ from litellm.proxy.pass_through_endpoints.llm_provider_handlers.base_passthrough
from litellm.proxy.pass_through_endpoints.success_handler import (
PassThroughEndpointLogging,
)
-from litellm.types.llms.openai import ResponsesAPIResponse
+from litellm.types.llms.openai import ResponseCompletedEvent, ResponsesAPIResponse
from litellm.types.passthrough_endpoints.pass_through_endpoints import (
EndpointType,
PassthroughStandardLoggingPayload,
@@ -464,7 +464,7 @@ class OpenAIPassthroughLoggingHandler(BasePassthroughLoggingHandler):
def _build_complete_streaming_response(
self,
- all_chunks: list,
+ all_chunks: list[str],
litellm_logging_obj: LiteLLMLoggingObj,
model: str,
) -> ModelResponse | TextCompletionResponse | None:
@@ -518,6 +518,15 @@ class OpenAIPassthroughLoggingHandler(BasePassthroughLoggingHandler):
verbose_proxy_logger.error("Error building complete streaming response: %s", e)
return None
+ @staticmethod
+ def _build_complete_streaming_responses_response(all_chunks: list[str]) -> ResponsesAPIResponse | None:
+ for chunk_str in reversed(all_chunks):
+ try:
+ return ResponseCompletedEvent.model_validate_json(chunk_str.removeprefix("data: ")).response
+ except ValueError:
+ continue
+ return None
+
@staticmethod
def _handle_logging_openai_collected_chunks(
litellm_logging_obj: LiteLLMLoggingObj,
@@ -536,13 +545,19 @@ class OpenAIPassthroughLoggingHandler(BasePassthroughLoggingHandler):
# Extract model from request body
model: Final = request_body.get("model", "gpt-4o")
+ is_responses: Final = OpenAIPassthroughLoggingHandler.is_openai_responses_route(url_route)
+
# Build complete response from chunks using our streaming handler
handler: Final = OpenAIPassthroughLoggingHandler()
handler_instance: Final = handler
- complete_response: Final = handler._build_complete_streaming_response(
- all_chunks=all_chunks,
- litellm_logging_obj=litellm_logging_obj,
- model=model,
+ complete_response: Final = (
+ handler._build_complete_streaming_responses_response(all_chunks=all_chunks)
+ if is_responses
+ else handler._build_complete_streaming_response(
+ all_chunks=all_chunks,
+ litellm_logging_obj=litellm_logging_obj,
+ model=model,
+ )
)
if complete_response is None:
@@ -554,10 +569,19 @@ class OpenAIPassthroughLoggingHandler(BasePassthroughLoggingHandler):
custom_llm_provider: Final = litellm_logging_obj.model_call_details.get("custom_llm_provider", "openai")
# Calculate cost using LiteLLM's cost calculator
- response_cost: Final = litellm.completion_cost(
- completion_response=complete_response,
- model=model,
- custom_llm_provider=custom_llm_provider,
+ response_cost: Final = (
+ litellm.completion_cost(
+ completion_response=complete_response,
+ model=model,
+ custom_llm_provider=custom_llm_provider,
+ call_type="responses",
+ )
+ if is_responses
+ else litellm.completion_cost(
+ completion_response=complete_response,
+ model=model,
+ custom_llm_provider=custom_llm_provider,
+ )
)
# Preserve existing litellm_params to maintain metadata tags
diff --git a/tests/test_litellm/proxy/pass_through_endpoints/llm_provider_handlers/test_openai_passthrough_logging_handler.py b/tests/test_litellm/proxy/pass_through_endpoints/llm_provider_handlers/test_openai_passthrough_logging_handler.py
index 401ea2ef589..9e5da39af88 100644
--- a/tests/test_litellm/proxy/pass_through_endpoints/llm_provider_handlers/test_openai_passthrough_logging_handler.py
+++ b/tests/test_litellm/proxy/pass_through_endpoints/llm_provider_handlers/test_openai_passthrough_logging_handler.py
@@ -519,6 +519,80 @@ class TestOpenAIPassthroughLoggingHandler:
assert result is None # Placeholder implementation
+ @patch(f"{OpenAIPassthroughLoggingHandler.__module__}.get_standard_logging_object_payload")
+ @patch("litellm.completion_cost", return_value=3.3e-06)
+ def test_streaming_responses_cost_uses_completed_response(
+ self, mock_completion_cost, mock_get_standard_logging
+ ):
+ response_id = "resp_PROOFSENTINEL0123456789abcdef"
+ completed_event = {
+ "type": "response.completed",
+ "sequence_number": 8,
+ "response": {
+ "id": response_id,
+ "object": "response",
+ "created_at": 1786374786,
+ "status": "completed",
+ "model": "gpt-4o-mini-2024-07-18",
+ "output": [
+ {
+ "id": "msg_abc",
+ "type": "message",
+ "status": "completed",
+ "role": "assistant",
+ "content": [
+ {
+ "type": "output_text",
+ "text": "OK",
+ "annotations": [],
+ }
+ ],
+ }
+ ],
+ "usage": {
+ "input_tokens": 14,
+ "input_tokens_details": {"cached_tokens": 0},
+ "output_tokens": 2,
+ "output_tokens_details": {"reasoning_tokens": 0},
+ "total_tokens": 16,
+ },
+ "error": None,
+ "incomplete_details": None,
+ "instructions": None,
+ "metadata": {},
+ "parallel_tool_calls": True,
+ "temperature": 1.0,
+ "tool_choice": "auto",
+ "tools": [],
+ "top_p": 1.0,
+ },
+ }
+ logging_obj = self._create_mock_logging_obj()
+
+ result = OpenAIPassthroughLoggingHandler._handle_logging_openai_collected_chunks(
+ litellm_logging_obj=logging_obj,
+ passthrough_success_handler_obj=MagicMock(),
+ url_route="https://api.openai.com/v1/responses",
+ request_body={"model": "gpt-4o-mini", "stream": True},
+ endpoint_type=MagicMock(),
+ start_time=self.start_time,
+ all_chunks=[f"data: {json.dumps(completed_event)}", "data: [DONE]"],
+ end_time=self.end_time,
+ )
+
+ response = result["result"]
+ assert response.id == response_id
+ assert response.model == "gpt-4o-mini-2024-07-18"
+ assert response.usage.input_tokens == 14
+ assert response.usage.output_tokens == 2
+ assert result["kwargs"]["response_cost"] == 3.3e-06
+ mock_completion_cost.assert_called_once_with(
+ completion_response=response,
+ model="gpt-4o-mini",
+ custom_llm_provider="openai",
+ call_type="responses",
+ )
+
@patch("litellm.completion_cost")
@patch(
"litellm.litellm_core_utils.litellm_logging.get_standard_logging_object_payload"