Skip to content

fix(xai): bill from the cost xAI reports instead of recomputing it (internal copy of #36281) - #39441

Merged
mateo-berri merged 4 commits into
litellm_internal_stagingfrom
litellm_internal_copy_36281
Sep 3, 2026
Merged

mateo-berri merged 4 commits into
litellm_internal_stagingfrom
litellm_internal_copy_36281

Conversation

@mateo-berri

@mateo-berri mateo-berri commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Internal copy of #36281 at its head 95da998, commits and authorship intact, so CircleCI's provider suites run on a litellm_ branch

TLDR

Problem this solves:

  • xAI reports what it charged, LiteLLM ignores it and recomputes from tokens
  • Server side tools LiteLLM has no rate for, X search included, bill nothing
  • Every xAI rate change needs a matching LiteLLM edit before spend is right again
  • A provider-stated cost on a stream skipped custom pricing and margins

How it solves it:

  • Bill the amount xAI reports, on chat and responses, streamed or not
  • Fall back to today's token and per-call math when xAI reports nothing
  • A deployment priced in config keeps billing at the operator's price
  • Margins still apply on top, because the figure goes through the cost calculator
  • The streaming cost header is OpenRouter's alone now, and a streamed xAI figure goes through the xAI calculator instead of the stream builder's shortcut

User Flow

Before: a developer whose Grok request runs an X search sees logged spend below what xAI charged

  1. They send POST https://litellm-domain/v1/responses with "model": "grok-4-latest" and "tools": [{"type": "x_search"}]
  2. The response reports the searches it ran in usage.server_side_tool_usage_details.x_search_calls and what xAI charged in usage.cost_in_usd_ticks
  3. They open https://litellm-domain/ui/?page=logs and the request is logged at the token math alone, with nothing added for the X searches
  4. Their xAI console shows the larger amount, because xAI bills $5 per 1,000 X searches, and the same gap opens for every other server side tool xAI adds or reprices
  5. Resending with "stream": true logs the same short figure

After: the same request is logged at the amount xAI says it charged, with the operator's own pricing and margins still applied on top

  1. They send POST https://litellm-domain/v1/responses with "model": "grok-4-latest" and "tools": [{"type": "x_search"}]
  2. The response reports the searches it ran in usage.server_side_tool_usage_details.x_search_calls and what xAI charged in usage.cost_in_usd_ticks
  3. https://litellm-domain/ui/?page=logs shows the request at exactly cost_in_usd_ticks divided by 10,000,000,000, X searches included
  4. That figure matches the xAI console line for the same request
  5. Resending with "stream": true logs that same figure, and a chat completions stream shows it as "cost" in the final chunk's usage
  6. A deployment the admin priced in config with input_cost_per_token and output_cost_per_token keeps billing at the admin's price, and a margin configured for xai is still added on top of xAI's figure, streamed or not

Relevant issues

Fixes #35829: a provider-stated usage.cost on 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 too

Linear ticket

Resolves LIT-6688

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. 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
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review (Greptile reviews automatically once the PR is opened; only comment @greptileai to 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_URL and XAI_API_KEY in the environment and $KEY set to the master key

model_list:
  - model_name: grok-4-latest
    litellm_params:
      model: xai/grok-4-latest
      api_key: os.environ/XAI_API_KEY
  - model_name: grok-custom-priced
    litellm_params:
      model: xai/grok-4-latest
      api_key: os.environ/XAI_API_KEY
      input_cost_per_token: 0.001
      output_cost_per_token: 0.001

general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
  database_url: os.environ/DATABASE_URL
litellm --config qa_config.yaml --port 33754   # merge base
litellm --config qa_config.yaml --port 30325   # this PR

cost_in_usd_ticks is what xAI charged, at 10,000,000,000 ticks to the dollar. Each side starts from an empty margin config (PATCH /config/cost_margin_config with {}) and the last two cases set {"xai": 0.5} first

Before (b3a1dd1)

POST /v1/responses, grok-4-latest with x_search

  1. Send the request and read usage in the response body
curl -s -D - http://localhost:33754/v1/responses -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{"model":"grok-4-latest","input":"In one sentence, what did the LiteLLM account post on X most recently? Use x_search.","tools":[{"type":"x_search"}],"stream":false}'
{"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}}
  1. The x-litellm-response-cost header on that response
x-litellm-response-cost: 0.0056066
  1. Read the spend log for that call (x-litellm-call-id: d024c191-523a-4f3a-a972-83e3ce32bb90)
curl -s http://localhost:33754/spend/logs -H "Authorization: Bearer $KEY" | jq '.[] | select(.metadata.litellm_call_id == "d024c191-523a-4f3a-a972-83e3ce32bb90") | {model, spend}'
{"model": "xai/grok-4-latest", "spend": 0.0056066}

POST /v1/responses, grok-4-latest with x_search, stream: true

  1. Send the request and read usage in the final SSE chunk
curl -s -D - http://localhost:33754/v1/responses -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{"model":"grok-4-latest","input":"In one sentence, what did the LiteLLM account post on X most recently? Use x_search.","tools":[{"type":"x_search"}],"stream":true}'
{"input_tokens": 3834, "output_tokens": 467, "cost_in_usd_ticks": 127344000, "server_side_tool_usage_details": {"web_search_calls": 0, "x_search_calls": 2}}
  1. Read the spend log for that call (x-litellm-call-id: 61311396-17dc-490e-b251-c356c395c9c9)
curl -s http://localhost:33754/spend/logs -H "Authorization: Bearer $KEY" | jq '.[] | select(.metadata.litellm_call_id == "61311396-17dc-490e-b251-c356c395c9c9") | {model, spend}'
{"model": "xai/grok-4-latest", "spend": 0.0027344}

POST /v1/chat/completions, grok-4-latest

  1. Send the request and read usage in the response body
curl -s -D - http://localhost:33754/v1/chat/completions -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{"model":"grok-4-latest","messages":[{"role":"user","content":"Reply with the single word OK"}],"max_tokens":50,"stream":false,"stream_options":{"include_usage":true}}'
{"prompt_tokens": 198, "completion_tokens": 93, "cost_in_usd_ticks": 2784000, "prompt_tokens_details": {"cached_tokens": 192}}
  1. The x-litellm-response-cost header on that response
x-litellm-response-cost: 0.0002784
  1. Read the spend log for that call (x-litellm-call-id: 5dbccdd5-f8ce-4951-bf4e-88ad9850a024)
curl -s http://localhost:33754/spend/logs -H "Authorization: Bearer $KEY" | jq '.[] | select(.metadata.litellm_call_id == "5dbccdd5-f8ce-4951-bf4e-88ad9850a024") | {model, spend}'
{"model": "xai/grok-4-latest", "spend": 0.0002784}

POST /v1/chat/completions, grok-4-latest, stream: true

  1. Send the request and read usage in the final SSE chunk
curl -s -D - http://localhost:33754/v1/chat/completions -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{"model":"grok-4-latest","messages":[{"role":"user","content":"Reply with the single word OK"}],"max_tokens":50,"stream":true,"stream_options":{"include_usage":true}}'
{"prompt_tokens": 198, "completion_tokens": 83, "prompt_tokens_details": {"cached_tokens": 192}}
  1. Read the spend log for that call (x-litellm-call-id: 9f9c7d33-844b-4ee9-a99d-2c0f027e8dac)
curl -s http://localhost:33754/spend/logs -H "Authorization: Bearer $KEY" | jq '.[] | select(.metadata.litellm_call_id == "9f9c7d33-844b-4ee9-a99d-2c0f027e8dac") | {model, spend}'
{"model": "xai/grok-4-latest", "spend": 0.0002534}

POST /v1/chat/completions, deployment priced in config

  1. Send the request and read usage in the response body
curl -s -D - http://localhost:33754/v1/chat/completions -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{"model":"grok-custom-priced","messages":[{"role":"user","content":"Reply with the single word OK"}],"max_tokens":50,"stream":false,"stream_options":{"include_usage":true}}'
{"prompt_tokens": 198, "completion_tokens": 126, "cost_in_usd_ticks": 4281000, "prompt_tokens_details": {"cached_tokens": 128}}
  1. The x-litellm-response-cost header on that response
x-litellm-response-cost: 0.19602560000000002
  1. Read the spend log for that call (x-litellm-call-id: dfecd1b6-e84d-4708-8c49-1a2f9c0a4955)
curl -s http://localhost:33754/spend/logs -H "Authorization: Bearer $KEY" | jq '.[] | select(.metadata.litellm_call_id == "dfecd1b6-e84d-4708-8c49-1a2f9c0a4955") | {model, spend}'
{"model": "xai/grok-4-latest", "spend": 0.1960256}

POST /v1/chat/completions, deployment priced in config, stream: true

  1. Send the request and read usage in the final SSE chunk
curl -s -D - http://localhost:33754/v1/chat/completions -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{"model":"grok-custom-priced","messages":[{"role":"user","content":"Reply with the single word OK"}],"max_tokens":50,"stream":true,"stream_options":{"include_usage":true}}'
{"prompt_tokens": 198, "completion_tokens": 135, "prompt_tokens_details": {"cached_tokens": 192}}
  1. Read the spend log for that call (x-litellm-call-id: 3ee31dc1-5f62-4026-b229-24f31d9851c5)
curl -s http://localhost:33754/spend/logs -H "Authorization: Bearer $KEY" | jq '.[] | select(.metadata.litellm_call_id == "3ee31dc1-5f62-4026-b229-24f31d9851c5") | {model, spend}'
{"model": "xai/grok-4-latest", "spend": 0.1410384}

50% xai margin, POST /v1/chat/completions, stream: true

  1. Set a 50% margin on xai, then send the two requests below
curl -s -X PATCH http://localhost:33754/config/cost_margin_config -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{"xai": 0.5}'
{"message":"Cost margin configuration updated successfully","status":"success","values":{"xai":0.5}}
  1. Send the request and read usage in the final SSE chunk
curl -s -D - http://localhost:33754/v1/chat/completions -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{"model":"grok-4-latest","messages":[{"role":"user","content":"Reply with the single word OK"}],"max_tokens":50,"stream":true,"stream_options":{"include_usage":true}}'
{"prompt_tokens": 198, "completion_tokens": 120, "prompt_tokens_details": {"cached_tokens": 192}}
  1. Read the spend log for that call (x-litellm-call-id: 78f4b7e7-f58b-4110-b243-df0cc25f6758)
curl -s http://localhost:33754/spend/logs -H "Authorization: Bearer $KEY" | jq '.[] | select(.metadata.litellm_call_id == "78f4b7e7-f58b-4110-b243-df0cc25f6758") | {model, spend}'
{"model": "xai/grok-4-latest", "spend": 0.00051885}

50% xai margin, POST /v1/responses with web_search, stream: true

  1. Send the request and read usage in the final SSE chunk
curl -s -D - http://localhost:33754/v1/responses -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{"model":"grok-4-latest","input":"In one sentence, what is the latest LiteLLM release? Use web search.","tools":[{"type":"web_search"}],"stream":true}'
{"input_tokens": 11365, "output_tokens": 498, "cost_in_usd_ticks": 233008500, "server_side_tool_usage_details": {"web_search_calls": 2, "x_search_calls": 0}}
  1. Read the spend log for that call (x-litellm-call-id: a93ce735-5678-4c58-851f-b961e67313a7)
curl -s http://localhost:33754/spend/logs -H "Authorization: Bearer $KEY" | jq '.[] | select(.metadata.litellm_call_id == "a93ce735-5678-4c58-851f-b961e67313a7") | {model, spend}'
{"model": "xai/grok-4-latest", "spend": 0.034951275}

After (95da998)

POST /v1/responses, grok-4-latest with x_search

  1. Send the request and read usage in the response body
curl -s -D - http://localhost:30325/v1/responses -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{"model":"grok-4-latest","input":"In one sentence, what did the LiteLLM account post on X most recently? Use x_search.","tools":[{"type":"x_search"}],"stream":false}'
{"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}}
  1. The x-litellm-response-cost header on that response
x-litellm-response-cost: 0.0134873
  1. Read the spend log for that call (x-litellm-call-id: 47c96b65-bdb8-4cbb-bc9d-64fcc060872d)
curl -s http://localhost:30325/spend/logs -H "Authorization: Bearer $KEY" | jq '.[] | select(.metadata.litellm_call_id == "47c96b65-bdb8-4cbb-bc9d-64fcc060872d") | {request_id, model, spend}'
{"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-latest with x_search, stream: true

  1. Send the request and read usage in the final SSE chunk
curl -s -D - http://localhost:30325/v1/responses -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{"model":"grok-4-latest","input":"In one sentence, what did the LiteLLM account post on X most recently? Use x_search.","tools":[{"type":"x_search"}],"stream":true}'
{"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}}
  1. Read the spend log for that call (x-litellm-call-id: 56216f43-e990-466f-85de-6b71f719c2ba)
curl -s http://localhost:30325/spend/logs -H "Authorization: Bearer $KEY" | jq '.[] | select(.metadata.litellm_call_id == "56216f43-e990-466f-85de-6b71f719c2ba") | {request_id, model, spend}'
{"request_id": "resp_bGl0ZWxsbTpjdXN0b21fbGxtX3Byb3ZpZGVyOnhhaTttb2RlbF9pZDoxNTFmOGRiMWU4MzgwMzA5NzVkNTM5Yzc4Mjc1NTJkNDRmMWJjZGVjNmE0YTNhMDM2YzMwYThjNGZjMzY0MjcyO3Jlc3BvbnNlX2lkOjc5NzQxMTdiLTExMTUtOTkxMy05ZDhjLTgxYWIzOGRhZjdmYw==", "model": "xai/grok-4-latest", "spend": 0.01272505}

POST /v1/chat/completions, grok-4-latest

  1. Send the request and read usage in the response body
curl -s -D - http://localhost:30325/v1/chat/completions -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{"model":"grok-4-latest","messages":[{"role":"user","content":"Reply with the single word OK"}],"max_tokens":50,"stream":false,"stream_options":{"include_usage":true}}'
{"prompt_tokens": 198, "completion_tokens": 113, "cost_in_usd_ticks": 3284000, "cost": 0.0003284, "prompt_tokens_details": {"cached_tokens": 192}}
  1. The x-litellm-response-cost header on that response
x-litellm-response-cost: 0.0003284
  1. Read the spend log for that call (x-litellm-call-id: ffa6e01b-ddce-4685-a656-6ec4b3e792c1)
curl -s http://localhost:30325/spend/logs -H "Authorization: Bearer $KEY" | jq '.[] | select(.metadata.litellm_call_id == "ffa6e01b-ddce-4685-a656-6ec4b3e792c1") | {request_id, model, spend}'
{"request_id": "be4c3a3d-7e69-986d-a5fb-5abd89e2cd0b", "model": "xai/grok-4-latest", "spend": 0.0003284}

POST /v1/chat/completions, grok-4-latest, stream: true

  1. Send the request and read usage in the final SSE chunk
curl -s -D - http://localhost:30325/v1/chat/completions -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{"model":"grok-4-latest","messages":[{"role":"user","content":"Reply with the single word OK"}],"max_tokens":50,"stream":true,"stream_options":{"include_usage":true}}'
{"prompt_tokens": 198, "completion_tokens": 88, "cost": 0.0002659, "prompt_tokens_details": {"cached_tokens": 192}}
  1. Read the spend log for that call (x-litellm-call-id: b7912ab7-39a8-47e8-b458-dcaad274fb61)
curl -s http://localhost:30325/spend/logs -H "Authorization: Bearer $KEY" | jq '.[] | select(.metadata.litellm_call_id == "b7912ab7-39a8-47e8-b458-dcaad274fb61") | {request_id, model, spend}'
{"request_id": "69ccbc3f-b51d-91d6-941f-4df90136f32d", "model": "xai/grok-4-latest", "spend": 0.0002659}

POST /v1/chat/completions, deployment priced in config

  1. Send the request and read usage in the response body
curl -s -D - http://localhost:30325/v1/chat/completions -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{"model":"grok-custom-priced","messages":[{"role":"user","content":"Reply with the single word OK"}],"max_tokens":50,"stream":false,"stream_options":{"include_usage":true}}'
{"prompt_tokens": 198, "completion_tokens": 90, "cost_in_usd_ticks": 2709000, "cost": 0.0002709, "prompt_tokens_details": {"cached_tokens": 192}}
  1. The x-litellm-response-cost header on that response
x-litellm-response-cost: 0.0960384
  1. Read the spend log for that call (x-litellm-call-id: b722367b-2490-49d7-9763-758e6a868678)
curl -s http://localhost:30325/spend/logs -H "Authorization: Bearer $KEY" | jq '.[] | select(.metadata.litellm_call_id == "b722367b-2490-49d7-9763-758e6a868678") | {request_id, model, spend}'
{"request_id": "575f08dd-2a76-9241-be83-3602250123f0", "model": "xai/grok-4-latest", "spend": 0.0960384}

POST /v1/chat/completions, deployment priced in config, stream: true

  1. Send the request and read usage in the final SSE chunk
curl -s -D - http://localhost:30325/v1/chat/completions -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{"model":"grok-custom-priced","messages":[{"role":"user","content":"Reply with the single word OK"}],"max_tokens":50,"stream":true,"stream_options":{"include_usage":true}}'
{"prompt_tokens": 198, "completion_tokens": 117, "cost": 0.0003384, "prompt_tokens_details": {"cached_tokens": 192}}
  1. Read the spend log for that call (x-litellm-call-id: 27f5cceb-ff4b-40b5-9c50-ffbdb54171c7)
curl -s http://localhost:30325/spend/logs -H "Authorization: Bearer $KEY" | jq '.[] | select(.metadata.litellm_call_id == "27f5cceb-ff4b-40b5-9c50-ffbdb54171c7") | {request_id, model, spend}'
{"request_id": "f18ad882-9ac4-9204-8ecc-053e5c823bb8", "model": "xai/grok-4-latest", "spend": 0.1230384}

50% xai margin, POST /v1/chat/completions, stream: true

  1. Set a 50% margin on xai, then send the two requests below
curl -s -X PATCH http://localhost:30325/config/cost_margin_config -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{"xai": 0.5}'
{"message":"Cost margin configuration updated successfully","status":"success","values":{"xai":0.5}}
  1. Send the request and read usage in the final SSE chunk
curl -s -D - http://localhost:30325/v1/chat/completions -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{"model":"grok-4-latest","messages":[{"role":"user","content":"Reply with the single word OK"}],"max_tokens":50,"stream":true,"stream_options":{"include_usage":true}}'
{"prompt_tokens": 198, "completion_tokens": 111, "cost": 0.0003234, "prompt_tokens_details": {"cached_tokens": 192}}
  1. Read the spend log for that call (x-litellm-call-id: b87b7a1f-5bee-42ea-89de-dd1484a4bc55)
curl -s http://localhost:30325/spend/logs -H "Authorization: Bearer $KEY" | jq '.[] | select(.metadata.litellm_call_id == "b87b7a1f-5bee-42ea-89de-dd1484a4bc55") | {request_id, model, spend}'
{"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: true

  1. Send the request and read usage in the final SSE chunk
curl -s -D - http://localhost:30325/v1/responses -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' -d '{"model":"grok-4-latest","input":"In one sentence, what is the latest LiteLLM release? Use web search.","tools":[{"type":"web_search"}],"stream":true}'
{"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}}
  1. Read the spend log for that call (x-litellm-call-id: e3357e46-be51-40a9-a578-090c7187a06c)
curl -s http://localhost:30325/spend/logs -H "Authorization: Bearer $KEY" | jq '.[] | select(.metadata.litellm_call_id == "e3357e46-be51-40a9-a578-090c7187a06c") | {request_id, model, spend}'
{"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

scenario status x-litellm-response-cost final usage.cost spend log
chat, grok-4-latest 200 0.0003009 0.0003009 0.0003009
chat stream, grok-4-latest 200 n/a 0.0002484 0.0002484
chat, config-priced 0.001/token 200 0.21103840000000001 0.0005584 0.2110384
chat stream, config-priced 0.001/token 200 n/a 0.0003384 0.1230384
responses, web_search 200 0.0235021 0.0235021 0.0235021
responses stream, web_search 200 n/a 0.0227996 0.0227996
responses, x_search 200 0.0135369 0.0135369 0.0135369
/v1/messages 200 0.0004134 n/a 0.0004134
/v1/messages stream 200 n/a n/a 0.0002934
litellm_proxy/ chained hop 200 0.0002934 0.0002934 no row
litellm_proxy/ chained hop, stream 200 n/a 0.0003084 no row
perplexity sonar 200 0.00501 0.00501 0.00501
perplexity sonar, stream 200 n/a 0.00501 0.00501
sonar config-priced 0.001/token 200 0.007 0.00501 0.007
sonar config-priced, stream 200 n/a 0.007 0.007
openrouter gpt 200 8.4e-06 8.4e-06 8.4e-06
openrouter gpt, stream 200 n/a 8.4e-06 8.4e-06
broken-grok -> fallback 200 0.0003759 0.0003759 0.0003759
broken-grok -> fallback, stream 200 n/a 0.0005359 0.0005359
50% xai margin, chat stream 200 n/a 0.0003459 0.00051885
50% xai margin, responses stream 200 n/a 0.0230549 0.03458235
50% xai margin, config-priced chat 200 0.18305760000000001 0.0003359 0.1830576
fresh virtual key, chat 200 0.0004284 0.0004284 0.0004284
key info / delete / health / readiness spend 0.0004284, delete then 401, 200, 200

Type

🐛 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 on usage.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 before

On grok-4-latest today 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-29

The 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_token and output_cost_per_token in config was billed the xAI figure, because the provider calculator answered before the deployment's registered price was consulted. completion_cost now 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, CustomStreamWrapper turned any usage.cost on a stream into the x-litellm-response-cost header litellm reads before pricing anything, a fast path OpenRouter relies on because its usage.cost is a USD total meant for exactly that, so that step now runs for OpenRouter only. Third, stream_chunk_builder mirrors a numeric usage.cost into the assembled response's hidden response_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 through xai_cost_per_token exactly like an unstreamed request. Every xAI figure reaches its own calculator, which is the fix #35829 asks for

Only 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.cost on top of that. A caller who can set api_base controls the response body, so a negative or NaN amount would otherwise subtract from that caller's recorded spend or disable budget checks for the key

Not touched: the model price maps, and any provider neutral file beyond the three paths above

Caveats

Medium

  • A custom-priced Perplexity deployment now bills the operator's price, not Perplexity's total (a sonar deployment priced at 0.001 per token billed Perplexity's 0.00501 before and bills 0.007 now)
  • Chat streams show xAI's figure as usage.cost in 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 before stream_chunk_builder stamped the billed 0.00045885 there because xAI sent no figure of its own

Low

  • On requests the rate table already prices exactly, the amount is unchanged
  • Trusting the reported total stops litellm cross checking xAI's arithmetic
  • A litellm_proxy/ deployment chained in front of an xAI upstream bills the upstream's reported figure (outer x-litellm-response-cost 0.0002309, equal to the inner usage.cost) where it used to re-run the token math (0.0003234)
  • cost_discount_config percentages stack on top of xAI's already discounted figure, the same way they stack on Perplexity's reported total today
  • The stream builder's raw mirror is keyed on the provider, so the next provider that prices its own reported cost has to join _CALCULATOR_PRICED_REPORTED_COST_PROVIDERS

Final 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_ticks into USD on usage.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.cost is 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 raw response_cost mirror in stream_chunk_builder, so margins and the xAI calculator run the same way as non-streaming calls.

When custom_pricing is enabled, completion_cost strips provider-stated usage.cost from 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.

Acacian and others added 3 commits September 1, 2026 07:09
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.
@devin-ai-integration devin-ai-integration Bot added the risk:high Sensitive, broad, or high-risk change label Sep 2, 2026
@devin-ai-integration

Copy link
Copy Markdown
Contributor

PR #39441: applied risk:high (touches billing/cost calculation in litellm/cost_calculator.py, main.py, and core streaming handler; 12 files, 679 lines). No enterprise label, so Linear routing skipped.

@codspeed

codspeed Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_internal_copy_36281 (100bc5d) with litellm_internal_staging (c19d49d)

Open in CodSpeed

@greptile-apps

greptile-apps Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

The PR makes xAI billing use validated provider-reported costs while preserving operator-defined custom pricing and margins.

  • Converts xAI cost ticks to USD for chat and Responses API results, including final streaming events.
  • Routes streamed xAI costs through the provider calculator instead of treating them as already priced.
  • Preserves token and tool-call fallback pricing when xAI does not report a usable cost.
  • Restricts the streaming cost-header shortcut to OpenRouter.

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Important Files Changed

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

Comment thread litellm/main.py Resolved
Comment thread litellm/cost_calculator.py Resolved
"""
reported_cost: Final = _cost_reported_by_xai(usage)
if reported_cost is not None:
return 0.0, reported_cost

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@veria-ai

veria-ai Bot commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

PR overview

This 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

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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.

@mateo-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@codecov

codecov Bot commented Sep 3, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.76543% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/llms/xai/responses/transformation.py 96.00% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ 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.

@tin-berri tin-berri left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@mateo-berri
mateo-berri merged commit 99da04a into litellm_internal_staging Sep 3, 2026
122 of 127 checks passed
@mateo-berri
mateo-berri deleted the litellm_internal_copy_36281 branch September 3, 2026 05:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk:high Sensitive, broad, or high-risk change run-ci

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Provider-reported usage.cost is trusted verbatim as USD spend with no unit validation — causes astronomical phantom spend

3 participants