Skip to content

fix(streaming): preserve provider model for cost calculation - #38656

Merged
mateo-berri merged 3 commits into
BerriAI:litellm_internal_stagingfrom
aaaaaandrew:litellm_preserve_stream_selected_model
Aug 28, 2026
Merged

mateo-berri merged 3 commits into
BerriAI:litellm_internal_stagingfrom
aaaaaandrew:litellm_preserve_stream_selected_model

Conversation

@aaaaaandrew

@aaaaaandrew aaaaaandrew commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Streaming routers like Fireworks FireRouter can serve a different model than the route name says
  • LiteLLM discards that identity when assembling the stream, so cost is computed from the route name (or not at all)

How it solves it:

  • Keeps the requested route public: chunks and the assembled response are byte-identical to before
  • Captures the provider-reported chunk model in private metadata (provider_response_model)
  • Prices that model after explicit overrides (custom pricing and base_model still win)

User Flow

Before: a user streams through a FireRouter route and the spend log records 0 instead of the served model's price

  1. An admin configures firerouter-deepseek-kimi pointing at fireworks_ai/accounts/fireworks/routers/firerouter/deepseek-v4-flash-0731/kimi-k3
  2. A user sends POST https://litellm-domain/v1/chat/completions with "model": "firerouter-deepseek-kimi", "stream": true, and "stream_options": {"include_usage": true}
  3. The stream returns 200, every chunk carries "model": "firerouter-deepseek-kimi", and the usage chunk reports 90 prompt and 10 completion tokens
  4. The Logs page at https://litellm-domain/ui/?page=logs shows that call with spend 0.0, while the identical request without stream bills 2.64e-05, so streamed FireRouter traffic rides free

After: the same streamed call bills the model FireRouter actually served

  1. An admin configures firerouter-deepseek-kimi pointing at fireworks_ai/accounts/fireworks/routers/firerouter/deepseek-v4-flash-0731/kimi-k3
  2. A user sends POST https://litellm-domain/v1/chat/completions with "model": "firerouter-deepseek-kimi", "stream": true, and "stream_options": {"include_usage": true}
  3. The stream returns 200 with the same chunks: "model" still reads "firerouter-deepseek-kimi" everywhere
  4. The Logs page shows spend 1.54e-05, DeepSeek V4 Flash's price for 90 prompt and 10 completion tokens

Relevant issues

Linear ticket

Resolves LIT-6364

Pre-Submission checklist

  • I have added meaningful tests
  • The handful of test files covering my change pass locally
  • My PR passes all required CI/CD checks (GitHub checks green at the tip; the ci/circleci: contexts come from a mirror-branch run of the legacy suites, red only on failures a per-test diff shows are identical to litellm_internal_staging's own latest pipeline, zero attributable to this PR)
  • My PR's scope is as isolated as possible
  • I have received a Greptile Confidence Score of at least 4/5 (5/5 at c11a1f0)

Screenshots / Proof of Fix

Shared setup: live proxy at each hash with Postgres spend logs, model firerouter-deepseek-kimi mapped to fireworks_ai/accounts/fireworks/routers/firerouter/deepseek-v4-flash-0731/kimi-k3, plus gpt-5.5 as a non-Fireworks control. Three real calls per leg:

# streamed FireRouter
curl -sD - http://localhost:36599/v1/chat/completions -H "Authorization: Bearer $MASTER_KEY" -H 'Content-Type: application/json' \
  -d '{"model": "firerouter-deepseek-kimi", "messages": [{"role": "user", "content": "Return only the number 8437"}], "stream": true, "stream_options": {"include_usage": true}}'
# non-streaming FireRouter: same body without the stream fields
# streamed control: same stream body with "model": "gpt-5.5"

Before (3300fc3)

  1. Streamed FireRouter: 200, 11 chunks all "model":"firerouter-deepseek-kimi", usage 90 prompt / 15 completion, spend row 0. The assembled response carries only the public alias, which is not in the cost map, so the cost silently computes as nothing. The same stream priced through litellm.completion_cost, where the response carries the route string, bills 0.000495, kimi-k3's rates (90 x 3e-06 + 15 x 1.5e-05), though FireRouter served DeepSeek V4 Flash
  2. Non-streaming FireRouter: 200, x-litellm-response-cost: 2.64e-05, spend row 2.64e-05
  3. Streamed gpt-5.5: 200, spend row 0.000665 for 13 prompt / 20 completion
                request_id                 |       model_group        |  spend   | prompt_tokens | completion_tokens
-------------------------------------------+--------------------------+----------+---------------+-------------------
 chatcmpl-e0c331d22d5b4695994ac49df999342b | firerouter-deepseek-kimi |        0 |            90 |                15
 chatcmpl-019ce08674874021a5cecb6e085927c6 | firerouter-deepseek-kimi | 2.64e-05 |            90 |                10
 chatcmpl-EHwJcOUsMkeXrWTeZN11LFWvYUMvl    | gpt-5.5                  | 0.000665 |            13 |                20

After (c11a1f0)

  1. Streamed FireRouter: 200, chunks byte-identical (all "model":"firerouter-deepseek-kimi"), usage 90 prompt / 10 completion, spend row 1.54e-05 = 90 x 1.4e-07 + 10 x 2.8e-07, DeepSeek V4 Flash's price for exactly those tokens
  2. Non-streaming FireRouter: unchanged, x-litellm-response-cost: 2.64e-05 and spend row 2.64e-05
  3. Streamed gpt-5.5: unchanged formula, spend row 0.000695 for 13 prompt / 21 completion
                request_id                 |       model_group        |  spend   | prompt_tokens | completion_tokens
-------------------------------------------+--------------------------+----------+---------------+-------------------
 chatcmpl-013e044dde0144719e7e1dd92771fc61 | firerouter-deepseek-kimi | 1.54e-05 |            90 |                10
 chatcmpl-b063d48f609e463dac133458e6869c2d | firerouter-deepseek-kimi | 2.64e-05 |            90 |                10
 chatcmpl-EHwPPeKOZwIqf3cF9pUwteWtMBcme    | gpt-5.5                  | 0.000695 |            13 |                21

Type

Bug Fix

Caveats

Low

  • The cost map holds two disagreeing entries for this model (fireworks_ai/deepseek-v4-flash-0731 vs fireworks_ai/accounts/fireworks/models/deepseek-v4-flash-0731), so non-streaming (priced by the route name) and streaming (priced by the provider-reported name) use different entries until LIT-6408 aligns them
  • Providers whose chunks echo the requested model (Bedrock) or carry no model (Vertex Gemini) keep existing behavior: the private field then adds nothing new
  • Explicit custom pricing and base_model still take precedence, and region prefixing stays scoped to response-derived names as on the base branch, so a base_model deployment cannot drift onto a regional cost-map key

Final Attestation

  • The tests check the right things, including edge cases and regressions

  • c11a1f0 passes /live-pr-risk. CircleCI at the tip (mirror pipeline 88691) is red on 8 legacy-suite jobs; every failed test also fails on litellm_internal_staging's own latest pipeline at the same test list (zero PR-attributable), and using_litellm_on_windows fails there while passing here

@CLAassistant

CLAassistant commented Aug 28, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@greptile-apps

greptile-apps Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR preserves the provider-selected model in private streaming metadata so routed responses retain their public model alias while cost calculation uses the serving model.

  • Carries the latest nonempty provider model through normalized streaming chunks.
  • Selects the first identity differing from the route during stream assembly, covering router-to-concrete-to-router streams.
  • Gives explicit custom pricing and base_model precedence over provider-response metadata.
  • Adds regression coverage for stream assembly, Fireworks routing, Azure Model Router transitions, regional Bedrock pricing, and explicit pricing overrides.

Confidence Score: 5/5

The PR appears safe to merge.

The previously reported stale first-chunk identity issue is addressed by selecting the first provider identity that differs from the route, with regression coverage confirming that router-to-concrete-to-router streams price the concrete serving model; no blocking failure remains.

Important Files Changed

Filename Overview
litellm/cost_calculator.py Uses the private provider-response model for pricing while preserving explicit pricing, base-model, and applicable regional precedence.
litellm/litellm_core_utils/streaming_chunk_builder_utils.py Assembles provider-model metadata by selecting the first stream identity that differs from the initial route identity, completing the previously requested fix.
litellm/litellm_core_utils/streaming_handler.py Tracks the latest nonempty provider model privately across chunks without changing the public response model.
tests/test_litellm/litellm_core_utils/test_streaming_handler.py Adds regression coverage for private model propagation and router-to-concrete-to-router cost selection.
tests/test_litellm/llms/fireworks_ai/chat/test_fireworks_ai_chat_transformation.py Verifies routed Fireworks streams retain their public route while accounting uses the selected provider model.
tests/test_litellm/test_cost_calculator.py Covers provider-model pricing precedence, explicit overrides, and Bedrock region handling.

Reviews (2): Last reviewed commit: "fix(cost_calculator): scope region_name ..." | Re-trigger Greptile

Comment thread litellm/cost_calculator.py Resolved
@codecov

codecov Bot commented Aug 28, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@codspeed

codspeed Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing aaaaaandrew:litellm_preserve_stream_selected_model (c11a1f0) with litellm_internal_staging (c5cdd2e)1

Open in CodSpeed

Footnotes

  1. No successful run was found on litellm_internal_staging (2ef77f3) during the generation of this report, so c5cdd2e was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

The unconditional region read let a base_model or custom pricing
deployment resolve to the regional cost-map key: a bedrock kimi
base_model shifted to regional rates and vertex claude-opus-5 with a
us-east5 key priced 0.0. Region now applies only when the model name
comes from the provider response (provider_response_model or the
response's own model), matching the base branch. Restores the BerriAI#38069
regression test and adds region-on-provider-model and base-model-free
cases
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

return next(
(model for model in models if model != first_chunk_model),
models[0] if models else None,
)

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.

Cost pick uses first chunk not route

Medium Severity

_get_provider_response_model treats the first chunk's public model as the route and then takes the first hidden identity that differs from it. Wrapper state also overwrites provider_response_model whenever a later chunk carries a model string, including a terminal reversion to the route. When the first emitted chunk already uses the serving model (Azure mutates self.model from the incoming chunk), a later route-named chunk is chosen instead, so assembled spend is priced from the route rather than the serving model.

Additional Locations (2)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit c11a1f0. Configure here.

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.

Azure public chunk models mirror the raw ones, so the selection matches pre-existing _get_model_from_chunks semantics; the hypothesized ordering reproduces base pricing, never worse.

@mateo-berri

Copy link
Copy Markdown
Contributor

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!

1 issue from previous review remains unresolved.

Fix All in Cursor

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit c11a1f0. Configure here.

@mateo-berri mateo-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. Thanks for the contribution!

@mateo-berri
mateo-berri merged commit d4f6b44 into BerriAI:litellm_internal_staging Aug 28, 2026
118 of 126 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants