Skip to content

fix(cost): split xai spend rows across input and output instead of booking the total as output - #46320

Merged
klu-berri merged 2 commits into
mainfrom
litellm_fix_xai_stream_cost_split
Oct 15, 2026
Merged

klu-berri merged 2 commits into
mainfrom
litellm_fix_xai_stream_cost_split

Conversation

@klu-berri

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • xai spend rows show input_cost 0 and output_cost = total on every live request, streamed or not
  • streamed xai rows with no xAI-reported cost were re-priced from LiteLLM's own stamped usage.cost

How it solves it:

  • cost_per_token (xai) splits xAI's reported total by our token-math ratio, sum stays xAI's number
  • _stamp_streaming_usage_cost also records _hidden_params["response_cost"], so the spend row reuses the first pricing pass
  • xai suite fixtures now carry cost_in_usd_ticks like real xAI responses, XAI_GROK_4_7_STREAM loses its known_bug

User Flow

Before: an operator reading the spend row for a grok-4.7 call sees the whole charge booked as output

  1. They send POST https://litellm-domain/v1/chat/completions with "model": "xai/grok-4.7", "stream": true
  2. The final SSE chunk carries usage.cost: 0.001554, the right total
  3. GET https://litellm-domain/spend/logs?request_id=... shows spend 0.001554, cost_breakdown.input_cost 0.0, output_cost 0.001554

After: the same row attributes the charge to both directions

  1. They send the same POST https://litellm-domain/v1/chat/completions
  2. The final SSE chunk carries the same xAI total in usage.cost
  3. GET https://litellm-domain/spend/logs?request_id=... shows input_cost 0.000768 (96 fresh + 1152 cached prompt tokens), output_cost 0.000834 (139 completion tokens), spend 0.001602

Linear ticket

Resolves LIT-9540

Pre-Submission checklist

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. uv run pytest tests/unit/<your_test_file>.py -v
  • 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
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

Screenshots / Proof of Fix

Live proxy on localhost:4010 (merge base) and localhost:4011 (PR tip), same config.yaml (xai/grok-4.7, api_key: os.environ/XAI_API_KEY), fresh Postgres each, real xAI calls

Before (origin/main)

  1. curl -s -N http://localhost:4010/v1/chat/completions -H 'Authorization: Bearer sk-proof' -d '{"model":"xai/grok-4.7","messages":[{"role":"user","content":"Say hello in five words."}],"stream":true,"stream_options":{"include_usage":true},"max_tokens":40}' | grep usage | tail -1
    {"usage": {"completion_tokens": 131, "prompt_tokens": 1248, "total_tokens": 1379, "completion_tokens_details": {"reasoning_tokens": 123, ...}, "prompt_tokens_details": {"cached_tokens": 1152, "text_tokens": 1248, ...}, "cost": 0.001554}}
  2. curl -s 'http://localhost:4010/spend/logs?request_id=6054e79e-718a-428a-886d-36aa0eeba9f3' -H 'Authorization: Bearer sk-proof'
    {"model": "xai/grok-4.7", "spend": 0.001554, "prompt_tokens": 1248, "completion_tokens": 131, "cost_breakdown": {"input_cost": 0.0, "output_cost": 0.001554, "total_cost": 0.001554, "cache_read_cost": 0.000576, "reasoning_cost": 0.000738}}

After (38450d6)

  1. curl -s -N http://localhost:4011/v1/chat/completions -H 'Authorization: Bearer sk-proof' -d '{"model":"xai/grok-4.7","messages":[{"role":"user","content":"Say hello in five words."}],"stream":true,"stream_options":{"include_usage":true},"max_tokens":40}' | grep usage | tail -1
    {"usage": {"completion_tokens": 139, "prompt_tokens": 1248, "total_tokens": 1387, "completion_tokens_details": {"reasoning_tokens": 132, ...}, "prompt_tokens_details": {"cached_tokens": 1152, "text_tokens": 1248, ...}, "cost": 0.001602}}
  2. curl -s 'http://localhost:4011/spend/logs?request_id=3e54407d-02d2-4a47-85bf-26253d8969b2' -H 'Authorization: Bearer sk-proof'
    {"model": "xai/grok-4.7", "spend": 0.001602, "prompt_tokens": 1248, "completion_tokens": 139, "cost_breakdown": {"input_cost": 0.0007679999999999999, "output_cost": 0.000834, "total_cost": 0.001602, "cache_read_cost": 0.000576, "reasoning_cost": 0.0007920000000000001}}

Check: 96 × $2/M + 1152 × $0.5/M = $0.000768 input, 139 × $6/M = $0.000834 output, sum $0.001602 = xAI's cost_in_usd_ticks for that call

Suite: tests/integration/cost_calculation xai cases, 7 passed on the tip. xai-grok-4.7-stream on main with the fix stashed: input_cost 0.0 != expected 0.00368

Type

🐛 Bug Fix

Caveats (if any)

Medium

  • The split of xAI's total is derived from our cost map rates, xAI sends one number only. When our grok rates drift from xAI's, the split drifts with them while spend stays xAI's invoice

Low

  • cost_per_token falls back to (0.0, reported) for an xai model missing from the cost map, same as before
  • /v1/responses streams stamp usage.cost the same way (_stamp_responses_usage_cost) but are not changed here, they were not re-priced in the suite

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

Link to Devin session: https://app.devin.ai/sessions/e4ef6bdad80443da875abe630a4ece6c
Open in Devin Desktop: https://app.devin.ai/desktop/session/e4ef6bdad80443da875abe630a4ece6c?variant=devin
Requested by: @kerrylu-berri

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
…n math

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@devin-ai-integration

Copy link
Copy Markdown
Contributor

I'll fix CI failures and address comments from users with write access. I'll skip comments containing "(aside)".

  • Disable automatic comment, CI, and merge conflict monitoring

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@klu-berri

Copy link
Copy Markdown
Contributor Author

@litellm-stampbot

@litellm-stampbot

Copy link
Copy Markdown

litellm-stampbot: risk high

Not approved at 38450d6. risk is high, a human reviewer is needed.

Rules (stampbot/risk_rules.yml):

  • low: no rule flagged it

Judge (gpt-6-luna): high, scoped behavior change, shared helper, moderate diff

  • tier: high (confidence 1.00)
  • change_kind: scoped_behavior_change (confidence 0.91)
  • blast_radius: shared_helper (confidence 0.65)
  • complexity: moderate (confidence 0.88)

Pushes do not re-run this check. Comment @litellm-stampbot again to re-check the new head.

@litellm-stampbot litellm-stampbot Bot added the risk:high Sensitive, broad, or high-risk change label Oct 13, 2026
@codspeed

codspeed Bot commented Oct 13, 2026

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_fix_xai_stream_cost_split (38450d6) with main (365c488)1

Open in CodSpeed

Footnotes

  1. No successful run was found on main (29202d2) during the generation of this report, so 365c488 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@codecov

codecov Bot commented Oct 13, 2026

Copy link
Copy Markdown

Codecov Report

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

Files with missing lines Patch % Lines
litellm/llms/xai/cost_calculator.py 92.30% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@kerry-berri kerry-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

@klu-berri
klu-berri merged commit 44e94eb into main Oct 15, 2026
88 checks passed
@klu-berri
klu-berri deleted the litellm_fix_xai_stream_cost_split branch October 15, 2026 00:02
@mateo-berri

Copy link
Copy Markdown
Contributor

Main CircleCI job integration-cost fails test_case_bills_expected_cost[xai-grok-5-provider_reported_cost] since this merged, as cases/misc.py still expects input_cost 0.0 (pipeline 91241) https://app.circleci.com/pipelines/github/BerriAI/litellm/91241

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants