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(xai): keep Responses API usage schema while billing web search

mateo-berri52f9b4a6e157
diff --git a/litellm/litellm_core_utils/llm_cost_calc/tool_call_cost_tracking.py b/litellm/litellm_core_utils/llm_cost_calc/tool_call_cost_tracking.py
index 3744be5bc79..fa4fc59ab77 100644
--- a/litellm/litellm_core_utils/llm_cost_calc/tool_call_cost_tracking.py
+++ b/litellm/litellm_core_utils/llm_cost_calc/tool_call_cost_tracking.py
@@ -432,7 +432,9 @@ class StandardBuiltInToolCostTracking:
"""
output: Final = response_object.output
for output_item in output:
- _output_type: str | None = getattr(output_item, "type", None)
+ _output_type: str | None = (
+ output_item.get("type") if isinstance(output_item, dict) else getattr(output_item, "type", None)
+ )
if _output_type == output_type:
return True
return False
diff --git a/litellm/llms/xai/responses/transformation.py b/litellm/llms/xai/responses/transformation.py
index c1ebe1705d7..d79e7d4c146 100644
--- a/litellm/llms/xai/responses/transformation.py
+++ b/litellm/llms/xai/responses/transformation.py
@@ -1,7 +1,4 @@
-from collections.abc import Mapping
-from typing import TYPE_CHECKING, Any, Final
-
-import httpx
+from typing import Any, Final
import litellm
from litellm._logging import verbose_logger
@@ -9,30 +6,11 @@ from litellm.constants import XAI_API_BASE
from litellm.exceptions import AuthenticationError
from litellm.llms.openai.responses.transformation import OpenAIResponsesAPIConfig
from litellm.llms.xai.common_utils import XAIModelInfo
-from litellm.llms.xai.cost_calculator import (
- apply_server_side_tool_usage_details_to_usage,
-)
-from litellm.responses.utils import ResponseAPILoggingUtils
from litellm.secret_managers.main import get_secret_str
-from litellm.types.llms.openai import (
- ResponseAPIUsage,
- ResponseCompletedEvent,
- ResponseFailedEvent,
- ResponseIncompleteEvent,
- ResponsesAPIOptionalRequestParams,
- ResponsesAPIResponse,
- ResponsesAPIStreamingResponse,
-)
+from litellm.types.llms.openai import ResponsesAPIOptionalRequestParams
from litellm.types.llms.xai import XAIWebSearchTool, XAIXSearchTool
from litellm.types.router import GenericLiteLLMParams
-from litellm.types.utils import LlmProviders, Usage
-
-if TYPE_CHECKING:
- from litellm.litellm_core_utils.litellm_logging import Logging as _LiteLLMLoggingObj
-
- LiteLLMLoggingObj = _LiteLLMLoggingObj
-else:
- LiteLLMLoggingObj = Any
+from litellm.types.utils import LlmProviders
class XAIResponsesAPIConfig(OpenAIResponsesAPIConfig):
@@ -66,87 +44,6 @@ class XAIResponsesAPIConfig(OpenAIResponsesAPIConfig):
return supported_params
- def transform_response_api_response(
- self,
- model: str,
- raw_response: httpx.Response,
- logging_obj: LiteLLMLoggingObj,
- ) -> ResponsesAPIResponse:
- """
- Attach xAI tool usage details onto a chat Usage object.
-
- Cost calculation normalizes Responses usage via
- ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage, which
- drops non-standard fields unless usage is already a chat Usage instance.
- """
- response: Final = super().transform_response_api_response(
- model=model, raw_response=raw_response, logging_obj=logging_obj
- )
- self._attach_server_side_tool_usage_details_to_usage(response)
- return response
-
- def transform_streaming_response(
- self,
- model: str,
- parsed_chunk: dict, # mutable-ok: OpenAIResponsesAPIConfig override keeps dict signature
- logging_obj: LiteLLMLoggingObj,
- ) -> ResponsesAPIStreamingResponse:
- """
- Preserve xAI tool usage on streaming terminal events for cost logging.
-
- Completed/incomplete/failed events embed a full ResponsesAPIResponse; without
- attaching server_side_tool_usage_details here, stream=true web_search usage is
- dropped when usage is normalized for billing.
- """
- event: Final = super().transform_streaming_response(
- model=model, parsed_chunk=parsed_chunk, logging_obj=logging_obj
- )
- if isinstance(
- event,
- (ResponseCompletedEvent, ResponseIncompleteEvent, ResponseFailedEvent),
- ):
- embedded_response: Final = getattr(event, "response", None)
- if isinstance(embedded_response, ResponsesAPIResponse):
- self._attach_server_side_tool_usage_details_to_usage(embedded_response)
- return event
-
- @staticmethod
- def _server_side_tool_usage_details_from_usage(
- usage: Usage | ResponseAPIUsage | Mapping[str, object] | None,
- ) -> Mapping[str, object] | None:
- if usage is None:
- return None
- if isinstance(usage, Mapping):
- mapping_details: Final = usage.get("server_side_tool_usage_details")
- return mapping_details if isinstance(mapping_details, Mapping) else None
- attr_details: Final = getattr(usage, "server_side_tool_usage_details", None)
- if isinstance(attr_details, Mapping):
- return attr_details
- model_extra: Final = getattr(usage, "model_extra", None) or getattr(usage, "__pydantic_extra__", None)
- if not isinstance(model_extra, Mapping):
- return None
- extra_details: Final = model_extra.get("server_side_tool_usage_details")
- return extra_details if isinstance(extra_details, Mapping) else None
-
- @staticmethod
- def _attach_server_side_tool_usage_details_to_usage(
- response: ResponsesAPIResponse,
- ) -> None:
- if response.usage is None:
- return
-
- details: Final = XAIResponsesAPIConfig._server_side_tool_usage_details_from_usage(response.usage)
- if details is None:
- return
-
- if isinstance(response.usage, Usage):
- apply_server_side_tool_usage_details_to_usage(response.usage, details)
- return
-
- chat_usage: Final = ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage(response.usage)
- apply_server_side_tool_usage_details_to_usage(chat_usage, details)
- response.usage = chat_usage # pyright: ignore[reportAttributeAccessIssue] # extra # rebind-ok: chat Usage
-
def _transform_web_search_tool(self, tool: dict[str, Any]) -> XAIWebSearchTool | dict[str, Any]:
"""
Transform web_search tool to XAI format.
diff --git a/litellm/responses/utils.py b/litellm/responses/utils.py
index 6d2cce5449f..c59f7afd88c 100644
--- a/litellm/responses/utils.py
+++ b/litellm/responses/utils.py
@@ -1041,9 +1041,10 @@ class ResponseAPILoggingUtils:
Both have the same spec with input_tokens, output_tokens, and
input_tokens_details (text_tokens, image_tokens).
- Providers that already converted usage to chat Usage (e.g. xAI Responses
- attaching server_side_tool_usage_details) are returned as-is so the chat
- completions bridge can re-run this helper without dropping extra fields.
+ Usage inputs are returned as-is so re-running this helper never drops
+ fields. Non-standard provider fields (e.g. xAI's
+ server_side_tool_usage_details) are carried onto the returned Usage so
+ provider cost calculators can read them after normalization.
"""
if usage_input is None:
return Usage(
@@ -1095,12 +1096,18 @@ class ResponseAPILoggingUtils:
audio_tokens=getattr(output_tokens_details, "audio_tokens", None),
)
+ extra_usage_fields: Final = {
+ key: value
+ for key, value in (response_api_usage.model_extra or {}).items()
+ if key not in ("input_token_details", "output_token_details")
+ }
chat_usage: Final = Usage(
prompt_tokens=prompt_tokens,
completion_tokens=completion_tokens,
total_tokens=prompt_tokens + completion_tokens,
prompt_tokens_details=prompt_tokens_details,
completion_tokens_details=completion_tokens_details,
+ **extra_usage_fields,
)
# Preserve cost attribute if it exists on ResponseAPIUsage
diff --git a/tests/test_litellm/litellm_core_utils/llm_cost_calc/test_tool_call_cost_tracking.py b/tests/test_litellm/litellm_core_utils/llm_cost_calc/test_tool_call_cost_tracking.py
index 24fd3c94ee3..4d60d2acc14 100644
--- a/tests/test_litellm/litellm_core_utils/llm_cost_calc/test_tool_call_cost_tracking.py
+++ b/tests/test_litellm/litellm_core_utils/llm_cost_calc/test_tool_call_cost_tracking.py
@@ -339,7 +339,7 @@ def test_get_cost_for_vertex_ai_gemini_web_search(model, custom_llm_provider):
for url_citation annotations, not usage.prompt_tokens_details.web_search_requests.
This causes Vertex AI grounding costs to not be tracked.
"""
- from litellm.types.utils import PromptTokensDetailsWrapper, Usage, Choices, Message
+ from litellm.types.utils import Choices, Message, PromptTokensDetailsWrapper, Usage
# Create a realistic ModelResponse like what Vertex AI returns
response = ModelResponse(
@@ -604,3 +604,31 @@ def test_web_search_provider_prefix_fallback_does_not_misprice_non_gemini_model(
# Note: File search integration test removed due to complex annotation detection logic
# The unit tests in test_azure_assistant_cost_tracking.py provide comprehensive coverage
+
+
+def test_response_includes_output_type_reads_dict_output_items():
+ """
+ Regression: output items that fail OpenAI SDK validation (e.g. xAI web_search_call
+ items without an "action" field) stay plain dicts in the output union. The gate must
+ read their "type" key instead of returning False and skipping the web search fee.
+ """
+ from litellm.types.llms.openai import ResponsesAPIResponse
+
+ response = ResponsesAPIResponse.model_validate(
+ {
+ "id": "resp_1",
+ "created_at": 1754900000,
+ "model": "grok-4",
+ "object": "response",
+ "status": "completed",
+ "output": [{"type": "web_search_call", "id": "ws_1", "status": "completed"}],
+ }
+ )
+
+ assert isinstance(response.output[0], dict)
+ assert StandardBuiltInToolCostTracking.response_includes_output_type(
+ response_object=response, output_type="web_search_call"
+ )
+ assert not StandardBuiltInToolCostTracking.response_includes_output_type(
+ response_object=response, output_type="file_search_call"
+ )
diff --git a/tests/test_litellm/llms/xai/responses/test_xai_responses_transformation.py b/tests/test_litellm/llms/xai/responses/test_xai_responses_transformation.py
index e0e526fd38e..871613c9c9a 100644
--- a/tests/test_litellm/llms/xai/responses/test_xai_responses_transformation.py
+++ b/tests/test_litellm/llms/xai/responses/test_xai_responses_transformation.py
@@ -13,12 +13,14 @@ from unittest.mock import MagicMock
sys.path.insert(0, os.path.abspath("../../../../.."))
+import pytest
+
+import litellm
from litellm.llms.xai.responses.transformation import XAIResponsesAPIConfig
+from litellm.responses.utils import ResponseAPILoggingUtils
from litellm.types.llms.openai import (
ResponseAPIUsage,
ResponseCompletedEvent,
- ResponseFailedEvent,
- ResponseIncompleteEvent,
ResponsesAPIOptionalRequestParams,
ResponsesAPIResponse,
)
@@ -291,8 +293,8 @@ class TestXAIResponsesAPITransformation:
assert result["tools"][3]["name"] == "get_weather"
-class TestXAIResponsesToolUsageAttach:
- """Tests for server_side_tool_usage_details attach helpers (cost billing)."""
+class TestXAIResponsesWebSearchBilling:
+ """Web search billing must not change the client-visible Responses usage schema."""
_TOOL_DETAILS = {
"web_search_calls": 2,
@@ -303,138 +305,101 @@ class TestXAIResponsesToolUsageAttach:
"document_search_calls": 0,
}
- def test_server_side_tool_usage_details_from_usage_dict(self):
- details = XAIResponsesAPIConfig._server_side_tool_usage_details_from_usage(
- {"server_side_tool_usage_details": self._TOOL_DETAILS}
- )
- assert details == self._TOOL_DETAILS
-
- def test_server_side_tool_usage_details_from_usage_attr(self):
- usage = Usage(prompt_tokens=1, completion_tokens=1, total_tokens=2)
- setattr(usage, "server_side_tool_usage_details", self._TOOL_DETAILS)
- details = XAIResponsesAPIConfig._server_side_tool_usage_details_from_usage(usage)
- assert details == self._TOOL_DETAILS
-
- def test_server_side_tool_usage_details_from_model_extra(self):
- usage = ResponseAPIUsage(
- input_tokens=10,
- output_tokens=5,
- total_tokens=15,
- server_side_tool_usage_details=self._TOOL_DETAILS,
+ def _raw_response_json(self, include_web_search: bool) -> dict:
+ web_search_output = (
+ [{
+ "type": "web_search_call",
+ "id": "ws_1",
+ "status": "completed",
+ "action": {"type": "search", "query": "grok"},
+ }] if include_web_search else []
)
- details = XAIResponsesAPIConfig._server_side_tool_usage_details_from_usage(usage)
- assert details == self._TOOL_DETAILS
-
- def test_server_side_tool_usage_details_from_usage_none(self):
- assert XAIResponsesAPIConfig._server_side_tool_usage_details_from_usage(None) is None
- assert (
- XAIResponsesAPIConfig._server_side_tool_usage_details_from_usage(
- Usage(prompt_tokens=1, completion_tokens=0, total_tokens=1)
- )
- is None
+ tool_usage = {"server_side_tool_usage_details": self._TOOL_DETAILS} if include_web_search else {}
+ return {
+ "id": "resp_1",
+ "object": "response",
+ "created_at": 1754900000,
+ "model": "grok-4",
+ "status": "completed",
+ "parallel_tool_calls": True,
+ "tool_choice": "auto",
+ "tools": [],
+ "top_p": 1.0,
+ "output": web_search_output
+ + [
+ {
+ "type": "message",
+ "id": "msg_1",
+ "role": "assistant",
+ "status": "completed",
+ "content": [{"type": "output_text", "text": "grok says hi", "annotations": []}],
+ }
+ ],
+ "usage": {
+ "input_tokens": 100,
+ "output_tokens": 20,
+ "total_tokens": 120,
+ "input_tokens_details": {"cached_tokens": 0},
+ "output_tokens_details": {"reasoning_tokens": 0},
+ **tool_usage,
+ },
+ }
+
+ def _transform(self, include_web_search: bool) -> ResponsesAPIResponse:
+ raw_response = MagicMock()
+ raw_response.json.return_value = self._raw_response_json(include_web_search)
+ raw_response.text = "raw"
+ raw_response.headers = {}
+ return XAIResponsesAPIConfig().transform_response_api_response(
+ model="grok-4", raw_response=raw_response, logging_obj=MagicMock()
)
- def test_attach_noop_when_usage_missing(self):
- response = ResponsesAPIResponse.model_construct(id="resp_1", created_at=0, output=[], usage=None)
- XAIResponsesAPIConfig._attach_server_side_tool_usage_details_to_usage(response)
- assert response.usage is None
+ def test_response_usage_keeps_responses_api_schema(self):
+ response = self._transform(include_web_search=True)
- def test_attach_noop_when_details_missing(self):
- usage = ResponseAPIUsage(input_tokens=3, output_tokens=1, total_tokens=4)
- response = ResponsesAPIResponse.model_construct(id="resp_2", created_at=0, output=[], usage=usage)
- XAIResponsesAPIConfig._attach_server_side_tool_usage_details_to_usage(response)
assert isinstance(response.usage, ResponseAPIUsage)
+ assert response.usage.input_tokens == 100
+ assert response.usage.output_tokens == 20
+ assert response.usage.model_extra["server_side_tool_usage_details"] == self._TOOL_DETAILS
- def test_attach_converts_response_api_usage_to_chat_usage(self):
- usage = ResponseAPIUsage(
- input_tokens=100,
- output_tokens=20,
- total_tokens=120,
- server_side_tool_usage_details=self._TOOL_DETAILS,
- )
- response = ResponsesAPIResponse.model_construct(id="resp_3", created_at=0, output=[], usage=usage)
- XAIResponsesAPIConfig._attach_server_side_tool_usage_details_to_usage(response)
-
- assert isinstance(response.usage, Usage)
- assert response.usage.prompt_tokens == 100
- assert response.usage.completion_tokens == 20
- assert getattr(response.usage, "server_side_tool_usage_details") == (self._TOOL_DETAILS)
- assert response.usage.prompt_tokens_details is not None
- assert response.usage.prompt_tokens_details.web_search_requests == 2
-
- def test_attach_updates_existing_chat_usage_in_place(self):
- usage = Usage(prompt_tokens=5, completion_tokens=5, total_tokens=10)
- setattr(usage, "server_side_tool_usage_details", self._TOOL_DETAILS)
- response = ResponsesAPIResponse.model_construct(id="resp_4", created_at=0, output=[], usage=usage)
- XAIResponsesAPIConfig._attach_server_side_tool_usage_details_to_usage(response)
-
- assert response.usage is usage
- assert usage.prompt_tokens_details is not None
- assert usage.prompt_tokens_details.web_search_requests == 2
-
- def test_chat_bridge_retransform_after_attach_keeps_tool_usage(self):
- """completion(..., web_search_options={}) re-converts usage after xAI attach."""
- from litellm.responses.utils import ResponseAPILoggingUtils
-
- usage = ResponseAPIUsage(
- input_tokens=100,
- output_tokens=20,
- total_tokens=120,
- server_side_tool_usage_details=self._TOOL_DETAILS,
- )
- response = ResponsesAPIResponse.model_construct(id="resp_bridge", created_at=0, output=[], usage=usage)
- XAIResponsesAPIConfig._attach_server_side_tool_usage_details_to_usage(response)
- assert isinstance(response.usage, Usage)
+ def test_bridged_usage_keeps_tool_details_for_billing(self):
+ response = self._transform(include_web_search=True)
bridged = ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage(response.usage)
- assert bridged is response.usage
+
+ assert isinstance(bridged, Usage)
+ assert bridged.prompt_tokens == 100
+ assert bridged.completion_tokens == 20
assert getattr(bridged, "server_side_tool_usage_details") == self._TOOL_DETAILS
- assert bridged.prompt_tokens_details is not None
- assert bridged.prompt_tokens_details.web_search_requests == 2
- from_dump = ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage(bridged.model_dump())
- assert from_dump.prompt_tokens == 100
- assert from_dump.completion_tokens == 20
- assert getattr(from_dump, "server_side_tool_usage_details") == self._TOOL_DETAILS
- assert from_dump.prompt_tokens_details is not None
- assert from_dump.prompt_tokens_details.web_search_requests == 2
+ def test_completion_cost_bills_web_search_calls(self):
+ with_search = litellm.completion_cost(
+ completion_response=self._transform(include_web_search=True),
+ model="xai/grok-4",
+ custom_llm_provider="xai",
+ )
+ without_search = litellm.completion_cost(
+ completion_response=self._transform(include_web_search=False),
+ model="xai/grok-4",
+ custom_llm_provider="xai",
+ )
+
+ assert with_search - without_search == pytest.approx(2 * 5.0 / 1000.0)
- def test_transform_streaming_response_completed_attaches_tool_usage(self):
- config = XAIResponsesAPIConfig()
- chunk = {
+ def test_streaming_terminal_event_keeps_schema_and_details(self):
+ parsed_chunk = {
"type": "response.completed",
- "response": {
- "id": "resp_stream",
- "created_at": 1,
- "output": [],
- "usage": {
- "input_tokens": 50,
- "output_tokens": 10,
- "total_tokens": 60,
- "server_side_tool_usage_details": self._TOOL_DETAILS,
- },
- },
+ "sequence_number": 7,
+ "response": self._raw_response_json(include_web_search=True),
}
- event = config.transform_streaming_response(model="grok-4.3", parsed_chunk=chunk, logging_obj=MagicMock())
+
+ event = XAIResponsesAPIConfig().transform_streaming_response(
+ model="grok-4", parsed_chunk=parsed_chunk, logging_obj=MagicMock()
+ )
assert isinstance(event, ResponseCompletedEvent)
- assert isinstance(event.response.usage, Usage)
- assert getattr(event.response.usage, "server_side_tool_usage_details") == (self._TOOL_DETAILS)
- assert event.response.usage.prompt_tokens_details is not None
- assert event.response.usage.prompt_tokens_details.web_search_requests == 2
+ assert isinstance(event.response.usage, ResponseAPIUsage)
+ assert event.response.usage.input_tokens == 100
- def test_transform_streaming_response_non_terminal_event_unchanged(self):
- config = XAIResponsesAPIConfig()
- chunk = {
- "type": "response.output_text.delta",
- "item_id": "msg_1",
- "output_index": 0,
- "content_index": 0,
- "delta": "hi",
- }
- event = config.transform_streaming_response(model="grok-4.3", parsed_chunk=chunk, logging_obj=MagicMock())
- assert getattr(event, "type", None) is not None
- assert not isinstance(
- event,
- (ResponseCompletedEvent, ResponseIncompleteEvent, ResponseFailedEvent),
- )
+ bridged = ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage(event.response.usage)
+ assert getattr(bridged, "server_side_tool_usage_details") == self._TOOL_DETAILS
diff --git a/tests/test_litellm/llms/xai/test_xai_chat_transformation.py b/tests/test_litellm/llms/xai/test_xai_chat_transformation.py
index 5c1f0f704d7..eac5b89e4f3 100644
--- a/tests/test_litellm/llms/xai/test_xai_chat_transformation.py
+++ b/tests/test_litellm/llms/xai/test_xai_chat_transformation.py
@@ -5,6 +5,9 @@ sys.path.insert(
0, os.path.abspath("../../../..")
) # Adds the parent directory to the system path
+import pytest
+
+import litellm
from litellm.llms.xai.chat.transformation import XAIChatConfig
from litellm.types.utils import (
CompletionTokensDetailsWrapper,
@@ -135,3 +138,65 @@ class TestXAIUsageNormalization:
XAIChatConfig._normalize_openai_compatible_usage_totals(usage)
assert usage["total_tokens"] == 200
+
+
+class TestXAIChatWebSearchBilling:
+ _TOOL_DETAILS = {
+ "web_search_calls": 3,
+ "x_search_calls": 0,
+ "code_interpreter_calls": 0,
+ "file_search_calls": 0,
+ "mcp_calls": 0,
+ "document_search_calls": 0,
+ }
+
+ @staticmethod
+ def _response_with_usage() -> ModelResponse:
+ response = ModelResponse(model="grok-4")
+ setattr(
+ response,
+ "usage",
+ Usage(prompt_tokens=100, completion_tokens=20, total_tokens=120),
+ )
+ return response
+
+ def test_enhance_copies_details_and_mirrors_web_search_requests(self):
+ response = self._response_with_usage()
+
+ XAIChatConfig()._enhance_usage_with_xai_web_search_fields(
+ response,
+ {"usage": {"server_side_tool_usage_details": self._TOOL_DETAILS}},
+ )
+
+ usage = response.usage
+ assert getattr(usage, "server_side_tool_usage_details") == self._TOOL_DETAILS
+ assert usage.prompt_tokens_details is not None
+ assert usage.prompt_tokens_details.web_search_requests == 3
+
+ def test_enhance_noop_without_details(self):
+ response = self._response_with_usage()
+
+ XAIChatConfig()._enhance_usage_with_xai_web_search_fields(
+ response, {"usage": {"prompt_tokens": 100}}
+ )
+
+ assert response.usage.prompt_tokens_details is None
+ assert getattr(response.usage, "server_side_tool_usage_details", None) is None
+
+ def test_completion_cost_bills_chat_web_search_calls(self):
+ billed = self._response_with_usage()
+ XAIChatConfig()._enhance_usage_with_xai_web_search_fields(
+ billed,
+ {"usage": {"server_side_tool_usage_details": self._TOOL_DETAILS}},
+ )
+
+ with_search = litellm.completion_cost(
+ completion_response=billed, model="xai/grok-4", custom_llm_provider="xai"
+ )
+ without_search = litellm.completion_cost(
+ completion_response=self._response_with_usage(),
+ model="xai/grok-4",
+ custom_llm_provider="xai",
+ )
+
+ assert with_search - without_search == pytest.approx(3 * 5.0 / 1000.0)
diff --git a/tests/test_litellm/responses/test_responses_utils.py b/tests/test_litellm/responses/test_responses_utils.py
index 7ff690ade13..4f1629eb431 100644
--- a/tests/test_litellm/responses/test_responses_utils.py
+++ b/tests/test_litellm/responses/test_responses_utils.py
@@ -1,19 +1,16 @@
import base64
-import json
import os
import sys
from unittest.mock import MagicMock, patch
import pytest
-from fastapi.testclient import TestClient
sys.path.insert(0, os.path.abspath("../../..")) # Adds the parent directory to the system path
import litellm
-from litellm.llms.base_llm.responses.transformation import BaseResponsesAPIConfig
from litellm.llms.openai.responses.transformation import OpenAIResponsesAPIConfig
from litellm.responses.utils import ResponseAPILoggingUtils, ResponsesAPIRequestUtils
-from litellm.types.llms.openai import ResponsesAPIOptionalRequestParams
+from litellm.types.llms.openai import ResponseAPIUsage, ResponsesAPIOptionalRequestParams
from litellm.types.utils import Usage
@@ -445,8 +442,25 @@ class TestResponseAPILoggingUtils:
assert result.completion_tokens_details.text_tokens == 20
assert result.completion_tokens_details.audio_tokens is None
+ def test_transform_response_api_usage_carries_extra_provider_fields(self):
+ """Non-standard usage fields (e.g. xAI tool details) must survive chat normalization."""
+ details = {"web_search_calls": 2, "x_search_calls": 0}
+ usage = ResponseAPIUsage(
+ input_tokens=100,
+ output_tokens=20,
+ total_tokens=120,
+ server_side_tool_usage_details=details,
+ )
+
+ result = ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage(usage)
+
+ assert isinstance(result, Usage)
+ assert result.prompt_tokens == 100
+ assert result.completion_tokens == 20
+ assert getattr(result, "server_side_tool_usage_details") == details
+
def test_transform_already_chat_usage_passthrough_keeps_tool_details(self):
- """xAI Responses converts usage to chat Usage before the chat bridge re-runs this helper."""
+ """Re-running the bridge on an already-converted chat Usage must not drop fields."""
details = {"web_search_calls": 2, "x_search_calls": 0}
usage = Usage(
prompt_tokens=100,