Skip to content

fix(proxy): preserve streaming cost when restamping model aliases - #41369

Closed
rujunchen wants to merge 1 commit into
BerriAI:mainfrom
rujunchen:fix-streaming-alias-cost
Closed

rujunchen wants to merge 1 commit into
BerriAI:mainfrom
rujunchen:fix-streaming-alias-cost

Conversation

@rujunchen

@rujunchen rujunchen commented Sep 16, 2026 •

Copy link
Copy Markdown

TLDR

Problem this solves:

  • Streaming aliases can overwrite the model used for billing
  • Successful requests then record zero cost despite valid token usage

How it solves it:

  • Shallow-copy outgoing chunks before changing their public model name
  • Keep the original model on chunks retained for accounting

Reproduction

Configure this deployment without custom pricing or base_model:

model_list:
  - model_name: claude-sonnet-4.6
    litellm_params:
      model: anthropic/claude-sonnet-4-6
      api_key: os.environ/ANTHROPIC_API_KEY
curl -N http://localhost:4000/v1/chat/completions \
  -H "Authorization: Bearer $LITELLM_VIRTUAL_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"model":"claude-sonnet-4.6","max_tokens":1024,"stream":true,"stream_options":{"include_usage":true},"messages":[{"role":"user","content":"Hello"}]}'

For the non-streaming control, set stream:false and remove stream_options; it is billed correctly

Root cause

The server-side alias configuration above is valid. The defect occurs when the HTTP streaming path changes a chunk's public model name on an object also retained for billing

  1. CustomStreamWrapper copies chunks containing usage, but retains ordinary text chunks by reference
  2. Before sending each SSE chunk, _restamp_streaming_chunk_model mutates its model from claude-sonnet-4-6 to the requested alias claude-sonnet-4.6. This also changes the retained text chunks; the copied usage chunks keep the original model
  3. At stream completion, _get_model_from_chunks prefers a model differing from the first chunk's model, selecting the dotted alias for the assembled response
  4. Without custom pricing, an explicit base_model, or a preserved provider-reported model, billing uses that response model. anthropic/claude-sonnet-4.6 has no exact price entry in the tested price map. The Claude capability fallback supplies no prices, and missing input/output rates default to zero

Token counts therefore remain correct while the recorded cost becomes zero, displayed as - in the request list. stream_options.include_usage does not fix this model-selection error; the regression covers both settings

The provider-model preservation added in #38656 does not prevent this Anthropic case because the parser's intermediate chunks omit the provider-reported model. Non-streaming requests calculate and store their cost before the HTTP response alias rewrite

How this PR fixes it

Copy the outgoing chunk before changing its top-level model. The retained original keeps the provider model for final accounting, while the client still receives the configured public alias. A shallow copy is sufficient because only the top-level model field changes

User Flow

Before: the streaming request succeeds but its cost is zero

  1. Send the POST above to http://localhost:4000/v1/chat/completions
  2. Open http://localhost:4000/ui/logs/; the successful request has tokens but zero cost, displayed as -

After: the same request is billed using the actual model

  1. Send the POST above to http://localhost:4000/v1/chat/completions
  2. Open http://localhost:4000/ui/logs/; the request has a nonzero cost and still returns the configured alias

Workaround

Until the fix is deployed, the proxy operator can add model_info.base_model to the existing deployment in the server's configuration YAML:

model_list:
  - model_name: claude-sonnet-4.6
    litellm_params:
      model: anthropic/claude-sonnet-4-6
      api_key: os.environ/ANTHROPIC_API_KEY
    model_info:
      base_model: anthropic/claude-sonnet-4-6

model_info belongs in the server configuration, at the same level as litellm_params. Merge base_model into any existing model_info, preserving the deployment's other settings. Clients can keep requesting claude-sonnet-4.6

For this standard-pricing configuration, the explicit base model takes priority over the assembled response model, so billing uses the priced anthropic/claude-sonnet-4-6 entry even if the stream still contains the alias

Apply the configuration through the normal proxy deployment process, restarting or reloading as required. Rerun the streaming curl above and check that the new log entry has a nonzero cost matching its token counts and configured rates; use a non-streaming request as a control

The focused offline replay verified this workaround: the 8-input/23-output-token fixture changed from $0 to $0.000369 using the tested price map. The configuration change has not been validated against a live provider or deployed to production

Relevant issues

Related: #38656 preserves provider-reported model names, but Anthropic's intermediate stream chunks do not supply that field

Affected release

Observed on v1.92.0 and reproduced on main at 3b14631f06. The first affected release has not been established

Linear ticket

Validation

The regression uses synthetic Anthropic events with the real parser, stream wrapper, SSE generator, final success callback, and cost calculator. It checks billing with include_usage enabled and disabled, alongside preservation of the public alias

Before the fix, both billing cases record zero cost and three chunk-preservation checks fail. After the fix, both related test files pass: 91 tests, with 100% changed-line coverage. Ruff, formatting, and the changed test file's quality check pass; the changed production file adds no strict lint or type diagnostics compared with the base

Pre-Submission checklist

  • Added meaningful regression tests
  • Related test files pass locally
  • Required CI/CD checks pass
  • Scope is limited to one bug
  • Greptile confidence is at least 4/5

Screenshots / Proof of Fix

Live-provider before/after proof is pending; provider credentials were unavailable. The checks above use synthetic events and do not claim live end-to-end validation

Type

Bug Fix

Caveats

Low

  • Windows cannot run the POSIX fcntl-based full lint gate
  • Hosted CI and coverage checks, Greptile, Veria, and Bugbot results remain pending

Final Attestation

  • Regression tests fail before the fix and pass afterward

@CLAassistant

CLAassistant commented Sep 16, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@rujunchen
rujunchen marked this pull request as ready for review September 16, 2026 05:27
@rujunchen
rujunchen requested a review from a team September 16, 2026 05:27
@greptile-apps

greptile-apps Bot commented Sep 16, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR separates the client-facing streaming chunk from the chunk retained for accounting

  • Shallow-copies model-bearing chunks before applying the requested public model alias
  • Preserves the provider model on retained chunks so final streaming cost calculation uses the correct identity
  • Adds offline regression coverage with and without streamed usage

Confidence Score: 5/5

The PR appears safe to merge, with the public alias and provider billing identity kept separate

No actionable failures remain; the changed path preserves the retained chunk while serializing a restamped copy, and focused offline tests cover the reported zero-cost regression

Important Files Changed
Filename Overview
litellm/proxy/proxy_server.py Copies outgoing model-bearing chunks before alias restamping, preserving the original provider model for accounting
tests/test_litellm/proxy/proxy_server/test_streaming_helpers.py Verifies retained chunk identity and streaming cost behavior for Anthropic aliases with both usage modes

Reviews (1): Last reviewed commit: "fix(proxy): preserve streaming cost when..." | Re-trigger Greptile

@mateo-berri

Copy link
Copy Markdown
Contributor

#44341 on main stamps the client alias on a copy of each streamed chunk, so pricing keeps the real model. Reopen if something is missing

@mateo-berri mateo-berri closed this Nov 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants