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): fold reasoning_tokens into completion_tokens to satisfy OpenAI invariant

mateo-berric1708ddbba21
diff --git a/litellm/llms/xai/chat/transformation.py b/litellm/llms/xai/chat/transformation.py
index 64b4a545acb..b1c0aaccf1d 100644
--- a/litellm/llms/xai/chat/transformation.py
+++ b/litellm/llms/xai/chat/transformation.py
@@ -223,8 +223,57 @@ class XAIChatConfig(OpenAIGPTConfig):
self._enhance_usage_with_xai_web_search_fields(response, raw_response_json)
except Exception as e:
verbose_logger.debug(f"Error extracting X.AI web search usage: {e}")
+
+ # X.AI excludes reasoning_tokens from completion_tokens, breaking the
+ # OpenAI invariant total_tokens == prompt_tokens + completion_tokens.
+ # OpenAI o1/o3 fold reasoning into completion_tokens; align X.AI to
+ # match so downstream consumers (including litellm's own usage tests)
+ # see a self-consistent Usage object. Cost calc already accounts for
+ # reasoning tokens separately in xai.cost_calculator.
+ self._fold_reasoning_tokens_into_completion(response)
return response
+ @staticmethod
+ def _fold_reasoning_tokens_into_completion(model_response: ModelResponse) -> None:
+ """Reconcile xAI Usage to the OpenAI invariant.
+
+ xAI returns ``completion_tokens`` covering only visible output and
+ accounts ``reasoning_tokens`` separately, while still rolling them
+ into ``total_tokens``. OpenAI's published contract (o1/o3) includes
+ reasoning in ``completion_tokens``. Tests that assert
+ ``total_tokens == prompt_tokens + completion_tokens`` (e.g.
+ ``_usage_format_tests``) fail on the raw xAI shape.
+
+ This helper is idempotent: if ``completion_tokens`` already covers
+ the gap, no change is made.
+ """
+ usage = getattr(model_response, "usage", None)
+ if usage is None:
+ return
+
+ details = getattr(usage, "completion_tokens_details", None)
+ reasoning_tokens = (
+ int(getattr(details, "reasoning_tokens", 0) or 0) if details else 0
+ )
+ if reasoning_tokens <= 0:
+ return
+
+ prompt_tokens = int(getattr(usage, "prompt_tokens", 0) or 0)
+ completion_tokens = int(getattr(usage, "completion_tokens", 0) or 0)
+ total_tokens = int(getattr(usage, "total_tokens", 0) or 0)
+
+ # Already consistent — nothing to do.
+ if total_tokens == prompt_tokens + completion_tokens:
+ return
+
+ # Only fold when xAI's accounting (total = prompt + completion +
+ # reasoning) explains the gap. This guards against double-counting
+ # if xAI ever changes their semantics.
+ if total_tokens != prompt_tokens + completion_tokens + reasoning_tokens:
+ return
+
+ usage.completion_tokens = completion_tokens + reasoning_tokens
+
def _enhance_usage_with_xai_web_search_fields(
self, model_response: ModelResponse, raw_response_json: dict
) -> None:
diff --git a/litellm/llms/xai/cost_calculator.py b/litellm/llms/xai/cost_calculator.py
index 0cfcfe98415..df5a7beffa3 100644
--- a/litellm/llms/xai/cost_calculator.py
+++ b/litellm/llms/xai/cost_calculator.py
@@ -26,15 +26,27 @@ def cost_per_token(model: str, usage: Usage) -> Tuple[float, float]:
Tuple[float, float] - prompt_cost_in_usd, completion_cost_in_usd
"""
# XAI-specific completion cost calculation
- # For XAI models, completion is billed as (visible completion tokens + reasoning tokens)
+ # For XAI models, completion is billed as (visible completion tokens + reasoning tokens).
+ # The transformation layer normalises Usage to the OpenAI invariant
+ # (completion_tokens includes reasoning_tokens), so detect that and avoid
+ # double-counting. Fall back to the raw xAI shape (visible-only completion +
+ # reasoning kept in completion_tokens_details) for callers that bypass the
+ # transformation, e.g. proxy logs replayed straight into cost calc.
+ prompt_tokens = int(getattr(usage, "prompt_tokens", 0) or 0)
completion_tokens = int(getattr(usage, "completion_tokens", 0) or 0)
+ total_tokens = 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
)
- total_completion_tokens = completion_tokens + reasoning_tokens
+ already_normalised = total_tokens == prompt_tokens + completion_tokens
+ total_completion_tokens = (
+ completion_tokens
+ if already_normalised
+ else completion_tokens + reasoning_tokens
+ )
modified_usage = Usage(
prompt_tokens=usage.prompt_tokens,
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 5a236de900e..a8bbb880c5b 100644
--- a/tests/test_litellm/llms/xai/test_xai_chat_transformation.py
+++ b/tests/test_litellm/llms/xai/test_xai_chat_transformation.py
@@ -6,6 +6,98 @@ sys.path.insert(
) # Adds the parent directory to the system path
from litellm.llms.xai.chat.transformation import XAIChatConfig
+from litellm.types.utils import (
+ CompletionTokensDetailsWrapper,
+ ModelResponse,
+ Usage,
+)
+
+
+class TestXAIReasoningTokenFolding:
+ """xAI breaks the OpenAI invariant total = prompt + completion by accounting
+ reasoning_tokens separately. ``_fold_reasoning_tokens_into_completion``
+ re-aligns Usage so downstream consumers see the OpenAI shape (o1/o3
+ semantics: completion_tokens includes reasoning)."""
+
+ @staticmethod
+ def _make_response(
+ prompt_tokens: int,
+ completion_tokens: int,
+ total_tokens: int,
+ reasoning_tokens: int = 0,
+ ) -> ModelResponse:
+ details = (
+ CompletionTokensDetailsWrapper(reasoning_tokens=reasoning_tokens)
+ if reasoning_tokens
+ else None
+ )
+ usage = Usage(
+ prompt_tokens=prompt_tokens,
+ completion_tokens=completion_tokens,
+ total_tokens=total_tokens,
+ completion_tokens_details=details,
+ )
+ response = ModelResponse()
+ setattr(response, "usage", usage)
+ return response
+
+ def test_should_fold_when_total_explained_by_reasoning_gap(self):
+ # Real xAI live shape captured 2026-05-04: prompt=14, completion=10,
+ # total=336, reasoning=312. 14+10+312 == 336.
+ response = self._make_response(
+ prompt_tokens=14,
+ completion_tokens=10,
+ total_tokens=336,
+ reasoning_tokens=312,
+ )
+
+ XAIChatConfig._fold_reasoning_tokens_into_completion(response)
+
+ usage = response.usage
+ assert usage.completion_tokens == 322
+ assert usage.total_tokens == usage.prompt_tokens + usage.completion_tokens
+
+ def test_should_not_fold_when_already_normalised(self):
+ # OpenAI-normalised shape: completion already includes reasoning.
+ response = self._make_response(
+ prompt_tokens=14,
+ completion_tokens=322,
+ total_tokens=336,
+ reasoning_tokens=312,
+ )
+
+ XAIChatConfig._fold_reasoning_tokens_into_completion(response)
+
+ # Idempotent — no double-fold.
+ assert response.usage.completion_tokens == 322
+
+ def test_should_skip_when_no_reasoning_tokens(self):
+ response = self._make_response(
+ prompt_tokens=14,
+ completion_tokens=10,
+ total_tokens=24,
+ reasoning_tokens=0,
+ )
+
+ XAIChatConfig._fold_reasoning_tokens_into_completion(response)
+
+ assert response.usage.completion_tokens == 10
+
+ def test_should_skip_when_gap_does_not_match_reasoning(self):
+ # Defensive guard: if xAI ever changes accounting and the gap stops
+ # equalling reasoning_tokens, refuse to fold rather than corrupt.
+ response = self._make_response(
+ prompt_tokens=14,
+ completion_tokens=10,
+ total_tokens=999,
+ reasoning_tokens=312,
+ )
+
+ XAIChatConfig._fold_reasoning_tokens_into_completion(response)
+
+ # No fold; original values preserved.
+ assert response.usage.completion_tokens == 10
+ assert response.usage.total_tokens == 999
class TestXAIParallelToolCalls:
@@ -14,9 +106,7 @@ class TestXAIParallelToolCalls:
def test_get_supported_openai_params_includes_parallel_tool_calls(self):
"""Test that parallel_tool_calls is in supported parameters."""
config = XAIChatConfig()
- supported_params = config.get_supported_openai_params(
- "xai/grok-4.20"
- )
+ supported_params = config.get_supported_openai_params("xai/grok-4.20")
assert "parallel_tool_calls" in supported_params
def test_transform_request_preserves_parallel_tool_calls(self):
diff --git a/tests/test_litellm/llms/xai/test_xai_cost_calculator.py b/tests/test_litellm/llms/xai/test_xai_cost_calculator.py
index 0463199f7e6..a8aae346224 100644
--- a/tests/test_litellm/llms/xai/test_xai_cost_calculator.py
+++ b/tests/test_litellm/llms/xai/test_xai_cost_calculator.py
@@ -107,10 +107,11 @@ class TestXAICostCalculator:
def test_grok_4_cost_calculation(self):
"""Test cost calculation for grok-4 model."""
+ # xAI raw API shape: total_tokens = prompt + visible completion + reasoning
usage = Usage(
prompt_tokens=10,
completion_tokens=200,
- total_tokens=210,
+ total_tokens=360,
completion_tokens_details=CompletionTokensDetailsWrapper(
accepted_prediction_tokens=0,
audio_tokens=0,
@@ -133,10 +134,11 @@ class TestXAICostCalculator:
def test_grok_3_fast_beta_cost_calculation(self):
"""Test cost calculation for grok-3-fast-beta model."""
+ # xAI raw API shape: total_tokens = prompt + visible completion + reasoning
usage = Usage(
prompt_tokens=20,
completion_tokens=300,
- total_tokens=320,
+ total_tokens=520,
completion_tokens_details=CompletionTokensDetailsWrapper(
accepted_prediction_tokens=0,
audio_tokens=0,
@@ -174,10 +176,11 @@ class TestXAICostCalculator:
def test_edge_case_large_reasoning_tokens(self):
"""Test cost calculation when reasoning_tokens is larger than completion_tokens."""
+ # xAI raw API shape: total_tokens = prompt + visible completion + reasoning
usage = Usage(
prompt_tokens=12,
completion_tokens=50, # Less than reasoning_tokens
- total_tokens=62,
+ total_tokens=162,
completion_tokens_details=CompletionTokensDetailsWrapper(
accepted_prediction_tokens=0,
audio_tokens=0,
@@ -201,10 +204,11 @@ class TestXAICostCalculator:
def test_tiered_pricing_above_128k_tokens(self):
"""Test tiered pricing for tokens above 128k."""
# Test with grok-4-fast-reasoning which has tiered pricing
+ # xAI raw API shape: total_tokens = prompt + visible completion + reasoning
usage = Usage(
prompt_tokens=150000, # Above 128k threshold
completion_tokens=100000, # Above 128k threshold
- total_tokens=250000,
+ total_tokens=300000,
completion_tokens_details=CompletionTokensDetailsWrapper(
accepted_prediction_tokens=0,
audio_tokens=0,
@@ -230,10 +234,11 @@ class TestXAICostCalculator:
def test_tiered_pricing_below_128k_tokens(self):
"""Test that regular pricing is used for tokens below 128k threshold."""
# Test with grok-4-fast-reasoning which has tiered pricing
+ # xAI raw API shape: total_tokens = prompt + visible completion + reasoning
usage = Usage(
prompt_tokens=100000, # Below 128k threshold
completion_tokens=50000,
- total_tokens=150000,
+ total_tokens=160000,
completion_tokens_details=CompletionTokensDetailsWrapper(
accepted_prediction_tokens=0,
audio_tokens=0,
@@ -258,10 +263,11 @@ class TestXAICostCalculator:
def test_tiered_pricing_grok_4_latest(self):
"""Test tiered pricing for grok-4-latest model."""
+ # xAI raw API shape: total_tokens = prompt + visible completion + reasoning
usage = Usage(
prompt_tokens=200000, # Above 128k threshold
completion_tokens=100000,
- total_tokens=300000,
+ total_tokens=350000,
completion_tokens_details=CompletionTokensDetailsWrapper(
accepted_prediction_tokens=0,
audio_tokens=0,
@@ -286,10 +292,11 @@ class TestXAICostCalculator:
def test_tiered_pricing_output_tokens_below_128k(self):
"""Test that output tokens get tiered rate when input tokens > 128k, even if output tokens < 128k."""
+ # xAI raw API shape: total_tokens = prompt + visible completion + reasoning
usage = Usage(
prompt_tokens=150000, # Above 128k threshold
completion_tokens=50000, # Below 128k threshold
- total_tokens=200000,
+ total_tokens=210000,
completion_tokens_details=CompletionTokensDetailsWrapper(
accepted_prediction_tokens=0,
audio_tokens=0,
@@ -331,6 +338,39 @@ 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_already_normalised_usage_does_not_double_count_reasoning(self):
+ """Cost calc receives Usage post-transformation (OpenAI invariant).
+
+ After XAIChatConfig.transform_response folds reasoning_tokens into
+ completion_tokens, the Usage block satisfies
+ ``total_tokens == prompt_tokens + completion_tokens``. Cost calc must
+ detect this and skip the reasoning_tokens add-on, otherwise it
+ double-bills the reasoning tokens.
+ """
+ # OpenAI-normalised shape: completion_tokens already includes the
+ # 100 reasoning tokens (so 100 visible + 100 reasoning -> 200).
+ usage = Usage(
+ prompt_tokens=12,
+ completion_tokens=200,
+ total_tokens=212,
+ completion_tokens_details=CompletionTokensDetailsWrapper(
+ accepted_prediction_tokens=0,
+ audio_tokens=0,
+ reasoning_tokens=100,
+ rejected_prediction_tokens=0,
+ text_tokens=None,
+ ),
+ )
+
+ prompt_cost, completion_cost = cost_per_token(model="grok-3-mini", usage=usage)
+
+ # Bill exactly what completion_tokens reports — no double-add.
+ expected_prompt_cost = 12 * 3e-7
+ expected_completion_cost = 200 * 5e-7
+
+ 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)