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): merge litellm_internal_staging and keep the stream builder from short-circuiting xAI's reported cost

mateo-berri95da9987799b
diff --cc litellm/main.py
index 724ffe76f81,0128e4defe5..0bca4a7350e
--- a/litellm/main.py
+++ b/litellm/main.py
@@@ -8590,13 -8595,12 +8595,22 @@@ def stream_chunk_builder_text_completio
return TextCompletionResponse(**response)
++_CALCULATOR_PRICED_REPORTED_COST_PROVIDERS: Final = frozenset({LlmProviders.XAI.value})
++
++
++def _reported_cost_is_priced_by_calculator(logging_obj: Optional["Logging"]) -> bool:
++ if logging_obj is None:
++ return False
++ provider: Final[object] = logging_obj.model_call_details.get("custom_llm_provider")
++ return provider in _CALCULATOR_PRICED_REPORTED_COST_PROVIDERS
++
++
def _stream_builder_response_cost(response: ModelResponse, logging_obj: Optional["Logging"]) -> float | None:
usage_cost: Final = getattr(getattr(response, "usage", None), "cost", None)
- numeric_usage_cost: Final = float(usage_cost) if isinstance(usage_cost, (int, float)) else None
- if isinstance(usage_cost, (int, float)):
++ if isinstance(usage_cost, (int, float)) and not _reported_cost_is_priced_by_calculator(logging_obj):
+ return float(usage_cost)
if logging_obj is not None:
- return numeric_usage_cost if litellm.include_cost_in_streaming_usage else None
- if numeric_usage_cost is not None:
- return numeric_usage_cost
+ return None
provider_hint: Final = response._hidden_params.get( # pyright: ignore[reportPrivateUsage] # no public accessor
"custom_llm_provider"
)
diff --cc tests/test_litellm/test_main.py
index 8befa51fb9d,7c2b9d0be05..3c8bf142835
--- a/tests/test_litellm/test_main.py
+++ b/tests/test_litellm/test_main.py
@@@ -3131,9 -3131,9 +3131,9 @@@ def test_stream_chunk_builder_prices_pr
assert response._hidden_params["response_cost"] == pytest.approx(expected_cost)
--def _stream_builder_logging_obj() -> LiteLLMLogging:
++def _stream_builder_logging_obj(model: str = "gpt-4o", custom_llm_provider: str = "openai") -> LiteLLMLogging:
logging_obj: Final = LiteLLMLogging(
-- model="gpt-4o",
++ model=model,
messages=[{"role": "user", "content": "hi"}],
stream=True,
call_type="completion",
@@@ -3142,10 -3142,10 +3142,11 @@@
function_id="test-function-id",
)
logging_obj.update_environment_variables(
-- model="gpt-4o",
++ model=model,
user=None,
optional_params={},
-- litellm_params={"custom_llm_provider": "openai"},
++ litellm_params={"custom_llm_provider": custom_llm_provider},
++ custom_llm_provider=custom_llm_provider,
)
return logging_obj
@@@ -3198,5 -3214,26 +3215,47 @@@ def test_stream_chunk_builder_keeps_pro
)
assert response is not None
- assert response.usage.cost == 0.42
+ assert getattr(response.usage, "cost", None) == pytest.approx(0.5)
+ assert response._hidden_params["response_cost"] == pytest.approx(0.5)
+
+
+ def test_stream_chunk_builder_prices_alias_from_openai_sdk_usage_chunk():
+ from openai.types.completion_usage import CompletionUsage
+
+ usage_chunk: Final = _stream_builder_text_chunk("mantle-claude", "")
+ usage_chunk.usage = CompletionUsage(prompt_tokens=20, completion_tokens=60, total_tokens=80, cost=0.000704)
+ assert type(usage_chunk.usage) is CompletionUsage
+ chunks: Final = [
+ _stream_builder_text_chunk("mantle-claude", "Hello "),
+ _stream_builder_text_chunk("mantle-claude", "world.", finish_reason="stop"),
+ usage_chunk,
+ ]
+
+ response: Final = litellm.stream_chunk_builder(chunks=chunks, messages=[{"role": "user", "content": "hi"}])
+
+ assert response is not None
+ assert response.usage.prompt_tokens == 20
+ assert response.usage.completion_tokens == 60
+ assert getattr(response.usage, "cost", None) == pytest.approx(0.000704)
+ assert response._hidden_params["response_cost"] == pytest.approx(0.000704)
++
++
++def test_stream_chunk_builder_leaves_xai_reported_cost_to_the_calculator(monkeypatch: pytest.MonkeyPatch):
++ monkeypatch.setattr(litellm, "cost_margin_config", {"xai": 0.5})
++ usage_chunk: Final = _stream_builder_text_chunk("grok-4", "")
++ usage_chunk.usage = Usage(prompt_tokens=5, completion_tokens=2, total_tokens=7, cost=0.42)
++ chunks: Final = [
++ _stream_builder_text_chunk("grok-4", "Hello "),
++ _stream_builder_text_chunk("grok-4", "world.", finish_reason="stop"),
++ usage_chunk,
++ ]
++ logging_obj: Final = _stream_builder_logging_obj(model="grok-4", custom_llm_provider="xai")
++
++ response: Final = litellm.stream_chunk_builder(
++ chunks=chunks, messages=[{"role": "user", "content": "hi"}], logging_obj=logging_obj
++ )
++
++ assert response is not None
++ assert getattr(response.usage, "cost", None) == pytest.approx(0.42)
+ assert response._hidden_params.get("response_cost") is None
++ assert logging_obj._response_cost_calculator(result=response) == pytest.approx(0.63)