Repository navigation
fix(xai): bill from the cost xAI reports instead of recomputing it (internal copy of #36281) - #39441
Conversation
xAI states the amount it charged in usage.cost_in_usd_ticks, at 10^10 ticks to the dollar, and that figure covers tokens and every server-side tool invocation together. The xAI chat and responses transformations restate it in USD on usage.cost, the field litellm already carries a provider-stated cost in, and the xAI cost calculator bills from it the way the perplexity calculator does Routing it through usage.cost rather than a private field means the streaming chunk assembler carries it too, and no provider-neutral file has to learn about an xAI wire field Only a finite, non-negative amount is trusted, so an endpoint a caller can point litellm at cannot report a negative amount to subtract from its own recorded spend, and cannot report a NaN, which Usage stores unvalidated and which compares false against every budget threshold, disabling enforcement for the key rather than mispricing one request. Absent a usable figure nothing changes: the existing token math and the $5 per 1,000 web search calls fallback both run as before The web search surcharge is suppressed once the reported total applies, since that total already covers the search calls
…culator Restate xAI's usage.cost_in_usd_ticks as usage.cost on chat and responses replies, streamed ones included, then let the cost calculator own the figure: a deployment with its own input_cost_per_token and output_cost_per_token keeps that price, cost margins apply on chat streams as they already did on non-streamed calls, and only OpenRouter's usage cost becomes the llm_provider-x-litellm-response-cost header, so xAI streams no longer skip the calculator through the header or the stream_chunk_builder hidden response_cost.
…from short-circuiting xAI's reported cost
|
PR #39441: applied |
Greptile SummaryThe PR makes xAI billing use validated provider-reported costs while preserving operator-defined custom pricing and margins.
Confidence Score: 5/5The PR appears safe to merge. No blocking failure remains.
|
| Filename | Overview |
|---|---|
| litellm/cost_calculator.py | Removes provider-stated totals from the usage copy used for custom pricing so configured operator rates take precedence. |
| litellm/litellm_core_utils/streaming_handler.py | Restricts propagation of provider-reported streaming costs into hidden response headers to OpenRouter. |
| litellm/llms/xai/chat/transformation.py | Converts validated xAI cost ticks to USD for non-streaming and streaming chat usage. |
| litellm/llms/xai/common_utils.py | Adds centralized validation and conversion of xAI’s integer cost ticks. |
| litellm/llms/xai/cost_calculator.py | Prefers valid xAI-reported totals and avoids double-charging server-side search costs while retaining fallback pricing. |
| litellm/llms/xai/responses/transformation.py | Restates xAI-reported costs on completed, incomplete, and failed Responses API usage objects. |
| litellm/main.py | Prevents stream aggregation from treating xAI’s reported cost as already finalized, allowing margins and custom pricing to run. |
| tests/test_litellm/litellm_core_utils/test_streaming_handler.py | Covers provider-specific streaming cost propagation, calculator routing, and xAI margins. |
| tests/test_litellm/llms/xai/responses/test_xai_responses_transformation.py | Covers xAI Responses API cost conversion for streaming, non-streaming, missing, and negative values. |
| tests/test_litellm/llms/xai/test_xai_chat_transformation.py | Covers xAI chat cost conversion and preservation through stream aggregation. |
| tests/test_litellm/llms/xai/test_xai_cost_calculator.py | Covers reported-total precedence, validation, fallback pricing, tool costs, and custom pricing. |
| tests/test_litellm/test_main.py | Verifies streamed xAI costs remain calculator-priced and receive configured margins. |
Reviews (2): Last reviewed commit: "Merge remote-tracking branch 'origin/lit..." | Re-trigger Greptile
| """ | ||
| reported_cost: Final = _cost_reported_by_xai(usage) | ||
| if reported_cost is not None: | ||
| return 0.0, reported_cost |
There was a problem hiding this comment.
Low: Provider discount is applied twice
This returns xAI's final reported charge, which already accounts for applicable discounts, but completion_cost() later applies the configured xAI cost_discount_config again. An authenticated user can therefore consume more xAI resources than their key or team budget records in deployments with that discount configured; preserve margins, but skip the generic provider-discount stage when billing from a validated reported cost.
There was a problem hiding this comment.
cost_discount_config is documented as stacking on every cost calculation, and Perplexity's reported usage.cost already goes through that stage. xAI now matches Perplexity.
There was a problem hiding this comment.
Thanks for the detail. I can't automatically confirm this is safe to dismiss, so I'm leaving the thread open for a maintainer to make the call.
PR overviewThis pull request updates xAI billing to use the final cost reported by xAI instead of recomputing the charge locally. One billing issue remains open: deployments with an xAI provider discount configured may apply that discount twice, causing usage to be recorded below its actual cost. An authenticated user could exceed key or team budgets under that configuration, though the impact is limited to affected billing setups. Open issues (1)
Fixed/addressed: 0 · PR risk: 4/10 |
|
bugbot run |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit 95da998. Configure here.
…itellm_internal_copy_36281
|
bugbot run |
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
There was a problem hiding this comment.
✅ Bugbot reviewed your changes and found no new issues!
Comment @cursor review or bugbot run to trigger another review on this PR
Reviewed by Cursor Bugbot for commit 100bc5d. Configure here.
99da04a
into
litellm_internal_staging
Internal copy of #36281 at its head 95da998, commits and authorship intact, so CircleCI's provider suites run on a
litellm_branchTLDR
Problem this solves:
How it solves it:
User Flow
Before: a developer whose Grok request runs an X search sees logged spend below what xAI charged
"model": "grok-4-latest"and"tools": [{"type": "x_search"}]usage.server_side_tool_usage_details.x_search_callsand what xAI charged inusage.cost_in_usd_ticks"stream": truelogs the same short figureAfter: the same request is logged at the amount xAI says it charged, with the operator's own pricing and margins still applied on top
"model": "grok-4-latest"and"tools": [{"type": "x_search"}]usage.server_side_tool_usage_details.x_search_callsand what xAI charged inusage.cost_in_usd_tickscost_in_usd_ticksdivided by 10,000,000,000, X searches included"stream": truelogs that same figure, and a chat completions stream shows it as"cost"in the final chunk'susageinput_cost_per_tokenandoutput_cost_per_tokenkeeps billing at the admin's price, and a margin configured for xai is still added on top of xAI's figure, streamed or notRelevant issues
Fixes #35829: a provider-stated
usage.coston a stream was copied straight into the billed amount for every provider, skipping the cost calculator. The header shortcut is OpenRouter's alone now, and the stream builder leaves xAI's figure to the xAI calculator. #37060 proposed the same allowlist, so this closes it tooLinear ticket
Resolves LIT-6688
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
uv run pytest tests/test_litellm/<your_test_file>.py -v. Leave the suites (make test-unit-*,make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or more@greptileaito re-request a review after pushing changes)Delays in PR merge?
If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).
Screenshots / Proof of Fix
Live proxy on each side, real xAI calls, spend read back from the proxy's own spend log. Both sides use this config, with
LITELLM_MASTER_KEY,DATABASE_URLandXAI_API_KEYin the environment and$KEYset to the master keycost_in_usd_ticksis what xAI charged, at 10,000,000,000 ticks to the dollar. Each side starts from an empty margin config (PATCH /config/cost_margin_configwith{}) and the last two cases set{"xai": 0.5}firstBefore (b3a1dd1)
POST /v1/responses,
grok-4-latestwithx_searchusagein the response body{"input_tokens": 4604, "output_tokens": 1204, "cost_in_usd_ticks": 156066000, "cost": null, "server_side_tool_usage_details": {"web_search_calls": 0, "x_search_calls": 2}}x-litellm-response-costheader on that responsex-litellm-call-id: d024c191-523a-4f3a-a972-83e3ce32bb90){"model": "xai/grok-4-latest", "spend": 0.0056066}POST /v1/responses,
grok-4-latestwithx_search,stream: trueusagein the final SSE chunk{"input_tokens": 3834, "output_tokens": 467, "cost_in_usd_ticks": 127344000, "server_side_tool_usage_details": {"web_search_calls": 0, "x_search_calls": 2}}x-litellm-call-id: 61311396-17dc-490e-b251-c356c395c9c9){"model": "xai/grok-4-latest", "spend": 0.0027344}POST /v1/chat/completions,
grok-4-latestusagein the response body{"prompt_tokens": 198, "completion_tokens": 93, "cost_in_usd_ticks": 2784000, "prompt_tokens_details": {"cached_tokens": 192}}x-litellm-response-costheader on that responsex-litellm-call-id: 5dbccdd5-f8ce-4951-bf4e-88ad9850a024){"model": "xai/grok-4-latest", "spend": 0.0002784}POST /v1/chat/completions,
grok-4-latest,stream: trueusagein the final SSE chunk{"prompt_tokens": 198, "completion_tokens": 83, "prompt_tokens_details": {"cached_tokens": 192}}x-litellm-call-id: 9f9c7d33-844b-4ee9-a99d-2c0f027e8dac){"model": "xai/grok-4-latest", "spend": 0.0002534}POST /v1/chat/completions, deployment priced in config
usagein the response body{"prompt_tokens": 198, "completion_tokens": 126, "cost_in_usd_ticks": 4281000, "prompt_tokens_details": {"cached_tokens": 128}}x-litellm-response-costheader on that responsex-litellm-call-id: dfecd1b6-e84d-4708-8c49-1a2f9c0a4955){"model": "xai/grok-4-latest", "spend": 0.1960256}POST /v1/chat/completions, deployment priced in config,
stream: trueusagein the final SSE chunk{"prompt_tokens": 198, "completion_tokens": 135, "prompt_tokens_details": {"cached_tokens": 192}}x-litellm-call-id: 3ee31dc1-5f62-4026-b229-24f31d9851c5){"model": "xai/grok-4-latest", "spend": 0.1410384}50% xai margin, POST /v1/chat/completions,
stream: trueusagein the final SSE chunk{"prompt_tokens": 198, "completion_tokens": 120, "prompt_tokens_details": {"cached_tokens": 192}}x-litellm-call-id: 78f4b7e7-f58b-4110-b243-df0cc25f6758){"model": "xai/grok-4-latest", "spend": 0.00051885}50% xai margin, POST /v1/responses with
web_search,stream: trueusagein the final SSE chunk{"input_tokens": 11365, "output_tokens": 498, "cost_in_usd_ticks": 233008500, "server_side_tool_usage_details": {"web_search_calls": 2, "x_search_calls": 0}}x-litellm-call-id: a93ce735-5678-4c58-851f-b961e67313a7){"model": "xai/grok-4-latest", "spend": 0.034951275}After (95da998)
POST /v1/responses,
grok-4-latestwithx_searchusagein the response body{"input_tokens": 3886, "output_tokens": 554, "cost_in_usd_ticks": 134873000, "cost": 0.0134873, "server_side_tool_usage_details": {"web_search_calls": 0, "x_search_calls": 2}}x-litellm-response-costheader on that responsex-litellm-call-id: 47c96b65-bdb8-4cbb-bc9d-64fcc060872d){"request_id": "resp_V61fKKquKmrTYOTGAZvDoGIHoHw6BMq4Cx4J4qzHKZnuL0mvQjrReGCVBahsIA1JVkS6SX3Xv2wbLgjFQi0zTHhH-pY3_-ELA1hHlSDH0bmnxz5VoX3UQr86Gs2dhjdYseIZ2Zu2xk32r4Yt6yiK-1Tec6dcOG86gV3MPDCDPtTS4OybPuBImRXJm4rC3fK4kEKUby05_IxcmUHQO79N_Y81ROXd99N6o38PUxSdXVTGaUod6u1wSwEQeAQ6UTlnBIRH9TtS-E3NIqGI8466T48Vz1QnsAHamfHwkOPLjBgCj2UEPsyrId9BFcrhLtKj1G-N2u5y-HsoN66OhGBIYgNbDl7VUbzI-5TewyvECIFWuLVhSukb2adCHN0R0eDFE7n05mN2uvexR4fQUgXxwrt2Q_4qMmU6_keLsIfSfeMsVcBQ3Lc=", "model": "xai/grok-4-latest", "spend": 0.0134873}POST /v1/responses,
grok-4-latestwithx_search,stream: trueusagein the final SSE chunk{"input_tokens": 3873, "output_tokens": 390, "cost_in_usd_ticks": 127250500, "cost": 0.01272505, "server_side_tool_usage_details": {"web_search_calls": 0, "x_search_calls": 2}}x-litellm-call-id: 56216f43-e990-466f-85de-6b71f719c2ba){"request_id": "resp_bGl0ZWxsbTpjdXN0b21fbGxtX3Byb3ZpZGVyOnhhaTttb2RlbF9pZDoxNTFmOGRiMWU4MzgwMzA5NzVkNTM5Yzc4Mjc1NTJkNDRmMWJjZGVjNmE0YTNhMDM2YzMwYThjNGZjMzY0MjcyO3Jlc3BvbnNlX2lkOjc5NzQxMTdiLTExMTUtOTkxMy05ZDhjLTgxYWIzOGRhZjdmYw==", "model": "xai/grok-4-latest", "spend": 0.01272505}POST /v1/chat/completions,
grok-4-latestusagein the response body{"prompt_tokens": 198, "completion_tokens": 113, "cost_in_usd_ticks": 3284000, "cost": 0.0003284, "prompt_tokens_details": {"cached_tokens": 192}}x-litellm-response-costheader on that responsex-litellm-call-id: ffa6e01b-ddce-4685-a656-6ec4b3e792c1){"request_id": "be4c3a3d-7e69-986d-a5fb-5abd89e2cd0b", "model": "xai/grok-4-latest", "spend": 0.0003284}POST /v1/chat/completions,
grok-4-latest,stream: trueusagein the final SSE chunk{"prompt_tokens": 198, "completion_tokens": 88, "cost": 0.0002659, "prompt_tokens_details": {"cached_tokens": 192}}x-litellm-call-id: b7912ab7-39a8-47e8-b458-dcaad274fb61){"request_id": "69ccbc3f-b51d-91d6-941f-4df90136f32d", "model": "xai/grok-4-latest", "spend": 0.0002659}POST /v1/chat/completions, deployment priced in config
usagein the response body{"prompt_tokens": 198, "completion_tokens": 90, "cost_in_usd_ticks": 2709000, "cost": 0.0002709, "prompt_tokens_details": {"cached_tokens": 192}}x-litellm-response-costheader on that responsex-litellm-call-id: b722367b-2490-49d7-9763-758e6a868678){"request_id": "575f08dd-2a76-9241-be83-3602250123f0", "model": "xai/grok-4-latest", "spend": 0.0960384}POST /v1/chat/completions, deployment priced in config,
stream: trueusagein the final SSE chunk{"prompt_tokens": 198, "completion_tokens": 117, "cost": 0.0003384, "prompt_tokens_details": {"cached_tokens": 192}}x-litellm-call-id: 27f5cceb-ff4b-40b5-9c50-ffbdb54171c7){"request_id": "f18ad882-9ac4-9204-8ecc-053e5c823bb8", "model": "xai/grok-4-latest", "spend": 0.1230384}50% xai margin, POST /v1/chat/completions,
stream: trueusagein the final SSE chunk{"prompt_tokens": 198, "completion_tokens": 111, "cost": 0.0003234, "prompt_tokens_details": {"cached_tokens": 192}}x-litellm-call-id: b87b7a1f-5bee-42ea-89de-dd1484a4bc55){"request_id": "77b7a279-588e-9df6-9cad-cbcc02278729", "model": "xai/grok-4-latest", "spend": 0.0004851}50% xai margin, POST /v1/responses with
web_search,stream: trueusagein the final SSE chunk{"input_tokens": 14362, "output_tokens": 462, "cost_in_usd_ticks": 318899000, "cost": 0.0318899, "server_side_tool_usage_details": {"web_search_calls": 3, "x_search_calls": 0}}x-litellm-call-id: e3357e46-be51-40a9-a578-090c7187a06c){"request_id": "resp_bGl0ZWxsbTpjdXN0b21fbGxtX3Byb3ZpZGVyOnhhaTttb2RlbF9pZDoxNTFmOGRiMWU4MzgwMzA5NzVkNTM5Yzc4Mjc1NTJkNDRmMWJjZGVjNmE0YTNhMDM2YzMwYThjNGZjMzY0MjcyO3Jlc3BvbnNlX2lkOmZiOGIwODU4LWMyZmQtOWUxZC1iOGZkLWRjYjdhMjljY2I3MA==", "model": "xai/grok-4-latest", "spend": 0.04783485}At the tip (100bc5d)
100bc5d merges staging 5ad330f into the branch; none of the 105 commits it brings in touch a file this PR changes. The same live rig ran again on that tree, single worker on port 16484 with a fresh database, real xAI, Perplexity and OpenRouter calls, spend read back from the spend log by request start time. Every scenario answered 200 and every relationship above holds: the config-priced deployment bills the configured price, the 50% xAI margin lands on the spend log at 1.5x the figure in the final chunk, x_search bills the tick figure, and the Perplexity, OpenRouter and fallback rows match the base run
x-litellm-response-costusage.costType
🐛 Bug Fix
Changes
Every xAI response states the amount charged in
usage.cost_in_usd_ticks, at 10^10 ticks to the dollar. Per xAI's cost tracking docs that figure is the actual amount billed, after discounts, tokens and every server side tool invocation included. The xAI chat and responses transformations restate it in USD onusage.cost, the field litellm already carries a provider-stated cost in, for unstreamed responses and for the final chunk of a stream. The xAI cost calculator bills that figure when it is present and returns zero for the web search surcharge, since the figure already covers the calls. Without one, the token math and the per-call search rate run exactly as beforeOn
grok-4-latesttoday the rate table lands on xAI's figure to the tick for tokens, cached tokens and web search, so those amounts do not move. The difference shows on the tools the table has no rate for, which xAI's pricing page lists at $5 per 1,000 calls for X search and code execution, $2.50 for collections search and $10 for file attachments, and it shows again whenever the table lags a rate change, as it did until f0849eb brought the grok-4 token prices from $3 and $15 per million down to $1.25 and $2.50 on 2026-08-29The figure has to go through the cost calculator rather than around it, and three paths were letting it around. First, a deployment carrying its own
input_cost_per_tokenandoutput_cost_per_tokenin config was billed the xAI figure, because the provider calculator answered before the deployment's registered price was consulted.completion_costnow strips the provider-stated cost from the usage it prices whenever the deployment has custom pricing, so the operator's price wins, which is the rule the video cost path already follows. Second,CustomStreamWrapperturned anyusage.coston a stream into thex-litellm-response-costheader litellm reads before pricing anything, a fast path OpenRouter relies on because itsusage.costis a USD total meant for exactly that, so that step now runs for OpenRouter only. Third,stream_chunk_buildermirrors a numericusage.costinto the assembled response's hiddenresponse_cost, which the logging object takes as already priced, so a streamed xAI chat request still skipped margins and custom pricing with the header gone. That mirror stays for providers whose figure nothing else prices, the case #39069 leans on, but it now steps aside when the provider's own calculator consumes the reported cost, which today means xAI, so the logging object prices the stream throughxai_cost_per_tokenexactly like an unstreamed request. Every xAI figure reaches its own calculator, which is the fix #35829 asks forOnly the documented shape of the field is trusted, a non-negative integer, with bool refused since it is an int subclass, and the calculator refuses a non-finite
usage.coston top of that. A caller who can setapi_basecontrols the response body, so a negative or NaN amount would otherwise subtract from that caller's recorded spend or disable budget checks for the keyNot touched: the model price maps, and any provider neutral file beyond the three paths above
Caveats
Medium
sonardeployment priced at 0.001 per token billed Perplexity's 0.00501 before and bills 0.007 now)usage.costin the final chunk while the spend log carries the margin or custom price on top of it: with a 50% xAI margin the chunk read 0.0002834 and spend recorded 0.0004251, where beforestream_chunk_builderstamped the billed 0.00045885 there because xAI sent no figure of its ownLow
litellm_proxy/deployment chained in front of an xAI upstream bills the upstream's reported figure (outerx-litellm-response-cost0.0002309, equal to the innerusage.cost) where it used to re-run the token math (0.0003234)cost_discount_configpercentages stack on top of xAI's already discounted figure, the same way they stack on Perplexity's reported total today_CALCULATOR_PRICED_REPORTED_COST_PROVIDERSFinal Attestation
The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR
100bc5d passes /live-pr-risk
Note
Medium Risk
Changes core spend logging and streaming cost shortcuts across xAI and other providers with custom pricing; behavior is heavily tested but incorrect edge cases would misreport customer spend.
Overview
xAI spend now follows what xAI reports: chat and Responses transformations convert
cost_in_usd_ticksinto USD onusage.cost(including streamed final chunks). The xAI cost calculator prefers that total when valid and skips extra web-search line items so tool charges are not double-billed; it still falls back to token/per-call math when no trustworthy figure is present.Streaming and logging paths are tightened so provider
usage.costis not always treated as final billed amount. Only OpenRouter still copies stream usage cost into hidden headers for the fast path. xAI no longer gets that shortcut or a rawresponse_costmirror instream_chunk_builder, so margins and the xAI calculator run the same way as non-streaming calls.When
custom_pricingis enabled,completion_coststrips provider-statedusage.costfrom the usage object passed to token pricing so deployment/operator rates override xAI’s reported total.Reported costs are validated (non-negative finite numbers; bool/negative/NaN rejected) before they affect spend tracking.
Reviewed by Cursor Bugbot for commit 95da998. Bugbot is set up for automated code reviews on this repo. Configure here.