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): satisfy type-discipline gate on web search billing

Yang Yangda69b5bfe8b4
diff --git a/litellm/llms/xai/chat/transformation.py b/litellm/llms/xai/chat/transformation.py
index 1129872163c..ae5849812bf 100644
--- a/litellm/llms/xai/chat/transformation.py
+++ b/litellm/llms/xai/chat/transformation.py
@@ -1,4 +1,4 @@
-from collections.abc import AsyncIterator, Iterator
+from collections.abc import AsyncIterator, Iterator, Mapping
from typing import Any, Final
import httpx
@@ -363,8 +363,8 @@ class XAIChatConfig(OpenAIGPTConfig):
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:
+ details: Final = response_usage.get("server_side_tool_usage_details")
+ if isinstance(details, Mapping):
apply_server_side_tool_usage_details_to_usage(usage, details)
verbose_logger.debug("X.AI server_side_tool_usage_details: %s", details)
diff --git a/litellm/llms/xai/cost_calculator.py b/litellm/llms/xai/cost_calculator.py
index 0f117c586f1..6479757aded 100644
--- a/litellm/llms/xai/cost_calculator.py
+++ b/litellm/llms/xai/cost_calculator.py
@@ -14,7 +14,7 @@ if TYPE_CHECKING:
from litellm.types.utils import ModelInfo
# https://docs.x.ai/developers/pricing#tools-pricing — default when unset in model map
-_DEFAULT_WEB_SEARCH_COST_PER_CALL = 5.0 / 1000.0
+_DEFAULT_WEB_SEARCH_COST_PER_CALL: Final = 5.0 / 1000.0
def apply_server_side_tool_usage_details_to_usage(usage: Usage, details: Mapping[str, object] | None) -> None:
@@ -26,14 +26,14 @@ def apply_server_side_tool_usage_details_to_usage(usage: Usage, details: Mapping
return
setattr(usage, "server_side_tool_usage_details", details)
try:
- web_search_calls = int(details.get("web_search_calls") or 0)
+ web_search_calls: Final = int(details.get("web_search_calls") or 0)
except (TypeError, ValueError):
return
if web_search_calls <= 0:
return
- if usage.prompt_tokens_details is None:
- usage.prompt_tokens_details = PromptTokensDetailsWrapper()
- usage.prompt_tokens_details.web_search_requests = web_search_calls
+ prompt_tokens_details: Final = usage.prompt_tokens_details or PromptTokensDetailsWrapper()
+ setattr(prompt_tokens_details, "web_search_requests", web_search_calls)
+ setattr(usage, "prompt_tokens_details", prompt_tokens_details)
def cost_per_token(model: str, usage: Usage) -> tuple[float, float]:
@@ -55,9 +55,11 @@ def cost_per_token(model: str, usage: Usage) -> tuple[float, float]:
prompt_tokens: Final = int(getattr(usage, "prompt_tokens", 0) or 0)
completion_tokens: Final = int(getattr(usage, "completion_tokens", 0) or 0)
total_tokens: Final = int(getattr(usage, "total_tokens", 0) or 0)
- reasoning_tokens = 0
- if hasattr(usage, "completion_tokens_details") and usage.completion_tokens_details:
- reasoning_tokens = int(getattr(usage.completion_tokens_details, "reasoning_tokens", 0) or 0)
+ reasoning_tokens: Final = (
+ int(getattr(usage.completion_tokens_details, "reasoning_tokens", 0) or 0)
+ if hasattr(usage, "completion_tokens_details") and usage.completion_tokens_details
+ else 0
+ )
already_normalised: Final = total_tokens == prompt_tokens + completion_tokens
total_completion_tokens: Final = completion_tokens if already_normalised else completion_tokens + reasoning_tokens
@@ -82,22 +84,23 @@ def _web_search_cost_per_call_from_model_info(model_info: "ModelInfo") -> float:
Prefer ``search_context_cost_per_query`` (same shape as Gemini/Anthropic web
search pricing in the model cost map). Fall back to current xAI list pricing.
"""
- search_costs = model_info.get("search_context_cost_per_query") or {}
- if isinstance(search_costs, Mapping):
- for key in (
- "search_context_size_medium",
- "search_context_size_low",
- "search_context_size_high",
- ):
- value = search_costs.get(key)
- if value is None:
- continue
- try:
- cost = float(value)
- except (TypeError, ValueError):
- continue
- if cost > 0:
- return cost
+ search_costs: Final = model_info.get("search_context_cost_per_query")
+ if not isinstance(search_costs, Mapping):
+ return _DEFAULT_WEB_SEARCH_COST_PER_CALL
+ for key in (
+ "search_context_size_medium",
+ "search_context_size_low",
+ "search_context_size_high",
+ ):
+ value = search_costs.get(key)
+ if value is None:
+ continue
+ try:
+ cost = float(value)
+ except (TypeError, ValueError):
+ continue
+ if cost > 0:
+ return cost
return _DEFAULT_WEB_SEARCH_COST_PER_CALL
@@ -109,11 +112,11 @@ def cost_per_web_search_request(usage: "Usage", model_info: "ModelInfo") -> floa
Per-call rate comes from model_info.search_context_cost_per_query when set,
otherwise the default xAI tools rate ($5 / 1k calls).
"""
- details = getattr(usage, "server_side_tool_usage_details", None)
+ details: Final = 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)
+ web_search_calls: Final = int(details.get("web_search_calls") or 0)
except (TypeError, ValueError):
return 0.0
if web_search_calls <= 0:
diff --git a/litellm/llms/xai/responses/transformation.py b/litellm/llms/xai/responses/transformation.py
index 3dc11cd2d92..4c11f456b31 100644
--- a/litellm/llms/xai/responses/transformation.py
+++ b/litellm/llms/xai/responses/transformation.py
@@ -79,7 +79,7 @@ class XAIResponsesAPIConfig(OpenAIResponsesAPIConfig):
ResponseAPILoggingUtils._transform_response_api_usage_to_chat_usage, which
drops non-standard fields unless usage is already a chat Usage instance.
"""
- response = super().transform_response_api_response(
+ 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)
@@ -88,7 +88,7 @@ class XAIResponsesAPIConfig(OpenAIResponsesAPIConfig):
def transform_streaming_response(
self,
model: str,
- parsed_chunk: dict,
+ parsed_chunk: dict, # mutable-ok: OpenAIResponsesAPIConfig override keeps dict signature
logging_obj: LiteLLMLoggingObj,
) -> ResponsesAPIStreamingResponse:
"""
@@ -98,12 +98,14 @@ class XAIResponsesAPIConfig(OpenAIResponsesAPIConfig):
attaching server_side_tool_usage_details here, stream=true web_search usage is
dropped when usage is normalized for billing.
"""
- event = super().transform_streaming_response(model=model, parsed_chunk=parsed_chunk, logging_obj=logging_obj)
+ event: Final = super().transform_streaming_response(
+ model=model, parsed_chunk=parsed_chunk, logging_obj=logging_obj
+ )
if isinstance(
event,
(ResponseCompletedEvent, ResponseIncompleteEvent, ResponseFailedEvent),
):
- embedded_response = getattr(event, "response", None)
+ 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
@@ -115,16 +117,16 @@ class XAIResponsesAPIConfig(OpenAIResponsesAPIConfig):
if usage is None:
return None
if isinstance(usage, Mapping):
- details = usage.get("server_side_tool_usage_details")
- else:
- details = getattr(usage, "server_side_tool_usage_details", None)
- if details is None:
- model_extra = getattr(usage, "model_extra", None) or getattr(usage, "__pydantic_extra__", None)
- if isinstance(model_extra, Mapping):
- details = model_extra.get("server_side_tool_usage_details")
- if not isinstance(details, 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
- return details
+ 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(
@@ -133,7 +135,7 @@ class XAIResponsesAPIConfig(OpenAIResponsesAPIConfig):
if response.usage is None:
return
- details = XAIResponsesAPIConfig._server_side_tool_usage_details_from_usage(response.usage)
+ details: Final = XAIResponsesAPIConfig._server_side_tool_usage_details_from_usage(response.usage)
if details is None:
return
@@ -143,7 +145,7 @@ class XAIResponsesAPIConfig(OpenAIResponsesAPIConfig):
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 # type: ignore[assignment]
+ setattr(response, "usage", chat_usage)
def _transform_web_search_tool(self, tool: dict[str, Any]) -> XAIWebSearchTool | dict[str, Any]:
"""
diff --git a/litellm/responses/utils.py b/litellm/responses/utils.py
index 27dd4230923..c923831b3de 100644
--- a/litellm/responses/utils.py
+++ b/litellm/responses/utils.py
@@ -1033,7 +1033,7 @@ class ResponseAPILoggingUtils:
@staticmethod
def _transform_response_api_usage_to_chat_usage(
- usage_input: dict | ResponseAPIUsage | Usage | None,
+ usage_input: Mapping[str, object] | ResponseAPIUsage | Usage | None,
) -> Usage:
"""
Transforms ResponseAPIUsage or ImageUsage to a Usage object.