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(xai): bill web_search from server_side_tool_usage_details
Yang Yang25ad7dcb414a
diff --git a/litellm/llms/xai/chat/transformation.py b/litellm/llms/xai/chat/transformation.pyindex 9d06b609752..e9e9f205f94 100644--- a/litellm/llms/xai/chat/transformation.py+++ b/litellm/llms/xai/chat/transformation.py@@ -18,7 +18,6 @@ from litellm.types.utils import (Choices,ModelResponse,ModelResponseStream,- PromptTokensDetailsWrapper,Usage,)@@ -248,7 +247,7 @@ class XAIChatConfig(OpenAIGPTConfig):XAI API returns empty string for finish_reason when using tools,so we need to fix this after the standard OpenAI transformation.- Also handles X.AI web search usage tracking by extracting num_sources_used.+ Also handles X.AI web search usage tracking."""# First, let the parent class handle the standard transformation@@ -351,25 +350,20 @@ class XAIChatConfig(OpenAIGPTConfig):def _enhance_usage_with_xai_web_search_fields(self, model_response: ModelResponse, raw_response_json: dict) -> None:"""- Extract num_sources_used from X.AI response and map it to web_search_requests.+ Copy usage.server_side_tool_usage_details from the provider usage block+ onto model_response.usage for tool cost calculation."""if not hasattr(model_response, "usage") or model_response.usage is None:returnusage: Final[Usage] = model_response.usage- num_sources_used = None- response_usage: Final = raw_response_json.get("usage", {})- if isinstance(response_usage, dict) and "num_sources_used" in response_usage:- num_sources_used = response_usage.get("num_sources_used")-- # Map num_sources_used to web_search_requests for cost detection- if num_sources_used is not None and num_sources_used > 0:- if usage.prompt_tokens_details is None:- usage.prompt_tokens_details = PromptTokensDetailsWrapper()-- usage.prompt_tokens_details.web_search_requests = int(num_sources_used)- setattr(usage, "num_sources_used", int(num_sources_used))- verbose_logger.debug("X.AI web search sources used: %s", num_sources_used)+ response_usage: Final = raw_response_json.get("usage")+ if not isinstance(response_usage, dict):+ return+ details = response_usage.get("server_side_tool_usage_details")+ if details is not None:+ setattr(usage, "server_side_tool_usage_details", details)+ verbose_logger.debug("X.AI server_side_tool_usage_details: %s", details)@staticmethoddef _normalize_openai_compatible_usage_totals(diff --git a/litellm/llms/xai/cost_calculator.py b/litellm/llms/xai/cost_calculator.pyindex 384388f3300..dcc96625975 100644--- a/litellm/llms/xai/cost_calculator.py+++ b/litellm/llms/xai/cost_calculator.py@@ -4,6 +4,7 @@ Helper util for handling XAI-specific cost calculation- Handles XAI-specific reasoning token billing (billed as part of completion tokens)"""+from collections.abc import Mappingfrom typing import TYPE_CHECKING, Finalfrom litellm.litellm_core_utils.llm_cost_calc.utils import generic_cost_per_token@@ -12,6 +13,9 @@ from litellm.types.utils import Usageif TYPE_CHECKING:from litellm.types.utils import ModelInfo+# https://docs.x.ai/developers/pricing#tools-pricing+_WEB_SEARCH_COST_PER_CALL = 5.0 / 1000.0+def cost_per_token(model: str, usage: Usage) -> tuple[float, float]:"""@@ -56,29 +60,17 @@ def cost_per_web_search_request(usage: "Usage", model_info: "ModelInfo") -> floa"""Calculate the cost of web search requests for X.AI models.- X.AI Live Search costs $25 per 1,000 sources used.- Each source costs $0.025.-- The number of sources is stored in prompt_tokens_details.web_search_requests- by the transformation layer to be compatible with the existing detection system.+ Uses usage.server_side_tool_usage_details.web_search_calls at $5 / 1k calls+ (xAI tools pricing), not legacy num_sources_used / web_search_requests."""- # Cost per source used: $25 per 1,000 sources = $0.025 per source- cost_per_source: Final = 25.0 / 1000.0 # $0.025-- num_sources_used = 0-- if (- hasattr(usage, "prompt_tokens_details")- and usage.prompt_tokens_details is not None- and hasattr(usage.prompt_tokens_details, "web_search_requests")- and usage.prompt_tokens_details.web_search_requests is not None- ):- num_sources_used = int(usage.prompt_tokens_details.web_search_requests)-- # Fallback: try to get from num_sources_used if set directly- elif hasattr(usage, "num_sources_used") and usage.num_sources_used is not None:- num_sources_used = int(usage.num_sources_used)-- total_cost: Final = cost_per_source * num_sources_used-- return total_cost+ _ = model_info+ details = getattr(usage, "server_side_tool_usage_details", None)+ if not isinstance(details, Mapping):+ return 0.0+ try:+ web_search_calls = int(details.get("web_search_calls") or 0)+ except (TypeError, ValueError):+ return 0.0+ if web_search_calls <= 0:+ return 0.0+ return _WEB_SEARCH_COST_PER_CALL * web_search_callsdiff --git a/litellm/responses/utils.py b/litellm/responses/utils.pyindex db2e515609c..659edb6db3b 100644--- a/litellm/responses/utils.py+++ b/litellm/responses/utils.py@@ -1089,12 +1089,23 @@ class ResponseAPILoggingUtils:audio_tokens=getattr(output_tokens_details, "audio_tokens", None),)+ usage_kwargs: dict[str, Any] = {}+ # Keep xAI tool billing fields; dropped if we only pass token fields below.+ if isinstance(usage_input, dict):+ if usage_input.get("server_side_tool_usage_details") is not None:+ usage_kwargs["server_side_tool_usage_details"] = usage_input["server_side_tool_usage_details"]+ else:+ details = getattr(response_api_usage, "server_side_tool_usage_details", None)+ if details is not None:+ usage_kwargs["server_side_tool_usage_details"] = 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,+ **usage_kwargs,)# Preserve cost attribute if it exists on ResponseAPIUsagediff --git a/tests/test_litellm/llms/xai/test_xai_cost_calculator.py b/tests/test_litellm/llms/xai/test_xai_cost_calculator.pyindex 02fe7c8e68f..b166778deaf 100644--- a/tests/test_litellm/llms/xai/test_xai_cost_calculator.py+++ b/tests/test_litellm/llms/xai/test_xai_cost_calculator.py@@ -9,7 +9,6 @@ import sysimport litellmfrom litellm.types.utils import (CompletionTokensDetailsWrapper,- PromptTokensDetailsWrapper,Usage,)@@ -354,75 +353,28 @@ class TestXAICostCalculator:assert math.isclose(prompt_cost, expected_prompt_cost, rel_tol=1e-10)assert math.isclose(completion_cost, expected_completion_cost, rel_tol=1e-10)- def test_web_search_cost_calculation(self):- """Test web search cost calculation for X.AI models."""- # Test with web_search_requests in prompt_tokens_details (primary path)- usage = Usage(- prompt_tokens=100,- completion_tokens=50,- total_tokens=150,- prompt_tokens_details=PromptTokensDetailsWrapper(- text_tokens=100,- web_search_requests=3, # 3 sources used- ),- )-- web_search_cost = cost_per_web_search_request(usage=usage, model_info={})-- # Expected cost: 3 sources * $0.025 per source = $0.075- expected_cost = 3 * (25.0 / 1000.0) # 3 * $0.025-- assert math.isclose(web_search_cost, expected_cost, rel_tol=1e-10)- assert math.isclose(web_search_cost, 0.075, rel_tol=1e-10)-- def test_web_search_cost_fallback_calculation(self):- """Test web search cost calculation using fallback num_sources_used."""- # Test fallback: num_sources_used on usage object- usage = Usage(- prompt_tokens=100,- completion_tokens=50,- total_tokens=150,- )- # Manually set num_sources_used (as done by transformation layer)- setattr(usage, "num_sources_used", 5)-- web_search_cost = cost_per_web_search_request(usage=usage, model_info={})-- # Expected cost: 5 sources * $0.025 per source = $0.125- expected_cost = 5 * (25.0 / 1000.0) # 5 * $0.025-- assert math.isclose(web_search_cost, expected_cost, rel_tol=1e-10)- assert math.isclose(web_search_cost, 0.125, rel_tol=1e-10)-- def test_web_search_no_sources_used(self):- """Test web search cost calculation when no sources are used."""- usage = Usage(- prompt_tokens=100,- completion_tokens=50,- total_tokens=150,- prompt_tokens_details=PromptTokensDetailsWrapper(- text_tokens=100,- web_search_requests=0, # No web search- ),- )-- web_search_cost = cost_per_web_search_request(usage=usage, model_info={})-- # Expected cost: 0 sources * $0.025 per source = $0.0- assert web_search_cost == 0.0-- def test_web_search_cost_without_prompt_tokens_details(self):- """Test web search cost calculation when prompt_tokens_details is None."""- usage = Usage(- prompt_tokens=100,- completion_tokens=50,- total_tokens=150,+ def test_web_search_cost_via_server_side_tool_usage_details(self):+ """usage.server_side_tool_usage_details.web_search_calls at $5/1k."""+ usage = Usage(prompt_tokens=100, completion_tokens=50, total_tokens=150)+ setattr(+ usage,+ "server_side_tool_usage_details",+ {+ "web_search_calls": 3,+ "x_search_calls": 0,+ "code_interpreter_calls": 0,+ "file_search_calls": 0,+ "mcp_calls": 0,+ "document_search_calls": 0,+ },)web_search_cost = cost_per_web_search_request(usage=usage, model_info={})+ assert math.isclose(web_search_cost, 3 * (5.0 / 1000.0), rel_tol=1e-10)- # Expected cost: No web search data = $0.0- assert web_search_cost == 0.0+ def test_web_search_cost_zero_without_details(self):+ usage = Usage(prompt_tokens=100, completion_tokens=50, total_tokens=150)+ assert cost_per_web_search_request(usage=usage, model_info={}) == 0.0def test_grok_4_20_beta_reasoning_cost_calculation(self):"""Test cost calculation for grok-4.20-beta-0309-reasoning model."""