Repository navigation
Conversation
… streams Qwen3 and Mistral Large 3 stream OpenAI chat.completion.chunk JSON over invoke-with-response-stream, with the token counts only in the amazon-bedrock-invocationMetrics trailer. The shared Bedrock event stream decoder had no branch for those chunks, so the pass-through logged no text and no completion tokens. Decode them with the OpenAI chunk parser and fold the trailer into usage when the chunk carries none
[Medium impact] The change reaches Bedrock invoke streaming usage and spend logging across mapped and unmapped model IDs. The required live QA must cover the latest billing change before merging. Findings
|
…ounts A trailer without inputTokenCount or outputTokenCount now leaves usage to LiteLLM's own count, as before, instead of failing the stream. The Kimi token count test now runs through a fake HTTP transport, and the pass-through helper types its choices
# Conflicts: # tests/unit/llms/bedrock/passthrough/test_bedrock_passthrough_transformation.py
…on invoke streams
|
bugbot run |
…haped pass-through streams
|
bugbot run |
… streams from unmapped model ids A model id the invoke resolver does not know, such as an application inference profile ARN, streams through the generic decoder, which keeps no usage for Anthropic- or Llama-shaped events. Fold the amazon-bedrock-invocationMetrics trailer into those chunks so the spend row carries Bedrock's counts instead of LiteLLM's own estimate
| bedrock_usage: Final = ( | ||
| invocation_metrics_usage(event) if bills_invocation_metrics and generic_chunk.get("usage") is None else None | ||
| ) | ||
| return _with_invoke_trace( | ||
| response_chunk if bedrock_usage is None else response_chunk.model_copy(update={"usage": bedrock_usage}), trace |
There was a problem hiding this comment.
Live proof predates billing change
This code adds reported token counts to unmapped invoke streams, but live proof stops at 6865eee3d57. The repository requires live QA at the latest product commit, c865e9cb1494b5f9642ddf45c5f29dc9041a08d6. Before merging, rerun this billing path through the proxy against real Bedrock calls and record the results.
Rule Used: Apply this rule only to PRs that fix LLM translation bugs or add LLM translation features. LLM translation means converting requests, responses, streaming events, tool calls, and errors between the API a caller uses on LiteLLM (any endpoint or SDK fu... (source)
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
There was a problem hiding this comment.
Re-ran live at c865e9c on real Bedrock. Qwen3, Mistral Large 3 and 21 unmapped ids bill Bedrock's counts, with the rows in the proof
|
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 c865e9c. Configure here.
Handwritten 1-3 sentence description
Streaming Qwen3 or Mistral Large 3 through the Bedrock invoke pass-through only billed the prompt, since LiteLLM couldn't read the OpenAI-style chunks those models stream back. Now it reads them and bills the token counts Bedrock reports, same as the non-streamed call
Details
TLDR
Problem this solves:
How it solves it:
Decisions and alternatives
usage(the caller sentstream_options.include_usage), it wins over theamazon-bedrock-invocationMetricstrailer. The two agreed on every live call below. The alternative was to always read the trailerbedrock/invoke/moonshotai...already had its own OpenAI chunk decoder for the chat route. It now shares the new helper, so a Kimi chat stream withoutstream_options.include_usagelogs Bedrock's own counts where main logged LiteLLM's estimate, 35 prompt tokens against 15 in the re-run below. The proxy addsinclude_usageby default, so this shows only withgeneral_settings.always_include_stream_usage: falseor through the SDK. With it, the chat, messages, and responses rows match main belowchoices[].messageinstead ofchoices[].delta, so its chat stream text is still empty, same as main. That stream now writes a spend row with Bedrock's token counts, where main wrote none. Bedrock charges for those tokens, so the row matches the AWS bill. The alternatives were to also readchoices[].messageso the text arrives, which is a separate bug with its own fix, or to leave the row unbilled until then, which hides a charge AWS still makes/v1/chat/completionsfor OpenAI-shaped models onbedrock/invoke/, such as gpt-oss. Their chunks now go through the same parser and end-of-stream check as other OpenAI-shaped streams, so a stream that ends without afinish_reasonfails and can trigger a fallback, where main ended it asstopwith empty text. Live, gpt-oss onbedrock/invoke/answers 400 on both legs before any chunk arrives, because Bedrock rejects the request'smodelfield, a separate bug. The alternative was to end such a stream quietly, which returns a cut-off answer as completeabortfinish or anerrorchunk, the collector skips that chunk and still writes the spend row from the chunks before it, counted by LiteLLM. Main wrote a prompt-only row for such a stream, and without this the new parser's error would drop the row. No live stream sent either chunk, so unit tests cover it. The alternatives were to drop the row, which hides a charge, or to read Bedrock's counts off the failed chunk, which no stream has shown carrying themUser Flow
Before: a developer streaming Qwen3 or Mistral Large 3 through the Bedrock pass-through gets the full answer, but the proxy bills only the prompt
messagesbody/invokewithout streaming logs 20 and 15 at $0.000012After: the same stream bills both sides, matching the non-streamed call
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
uv run pytest tests/unit/<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 moreDelays 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
Before ran at the merge base 030bfe2 and After at fbc852b, with later re-runs below. Each leg is one proxy with 2 workers and its own Postgres database, calling real Bedrock in us-west-2. The legs ran without Redis, since nothing the change touches is shared across workers.
Last updated: c865e9c. QA ran on fbc852b. Changes since QA: a count fallback, kept rows for aborted streams, Bedrock's counts for unmapped invoke ids, and two merges of main. Verification: the re-runs below
Shared setup: config.yaml, proxy command, env vars and shell helpers
Every case sends
Count from 1 to 5.withmax_tokens40, and each spend lookup uses the request's ownx-litellm-call-idresponse header, saved with-D <case>Env vars:
AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY,AWS_SESSION_TOKEN,LITELLM_MASTER_KEY,DATABASE_URLpython litellm/proxy/proxy_cli.py --config config.yaml --port $PORT --num_workers 2Spend rows read back through
GET /spend/logs?request_id=, as prompt / completion tokens and spend/invoke/invoke/v1/messagesstream/v1/responsesstreamEach After row matches the counts in Bedrock's last event. Mistral and Kimi answers vary per run, so their counts move between legs
A direct Bedrock call reports the same counts as the After rows
A direct boto3 call to Bedrock with the same body, outside the proxy, reports 20 / 15 for Qwen3 and 11 / 14 for Mistral Large 3
direct_bedrock.py, run with the same AWS env vars as the proxyBefore (030bfe2)
Qwen3 stream
Other cases
Before: every other case's commands and output
After (fbc852b)
Qwen3 stream
Other cases
After: every other case's commands and output
Other Bedrock models that stream OpenAI-shaped chunks
Spend rows for the other models
The decoder change reaches every Bedrock invoke model whose stream sends OpenAI-shaped chunks, so /live-pr-risk ran six more models through the same two proxies. The pass-through streams send the same
messagesbody as above, Mistral 7B sends itspromptbody, and the two chat streams go through/v1/chat/completionswithinclude_usage. The full commands and output for both legs are in this gistMistral 7B streams the older
outputsshape, which this PR does not touch, and its rows match between legs apart from answer lengthRe-run at a32e9b0
Kimi and three-turn rows for both legs
Every After row matches the counts in that stream's last event, across three-turn Qwen3 and Mistral Large 3 conversations. Before bills only LiteLLM's estimate of the prompt. These paths are unchanged since a32e9b0
Both legs used
general_settings.always_include_stream_usage: false, so the Kimi chat stream's row has to come from Bedrock's last event. Each conversation turn resends the whole history through the pass-through. The full commands and output for both legs are in this gistRe-run at c865e9c
Qwen3 and Mistral Large 3 still bill their streams' counts, and 21 more unmapped invoke ids now bill Bedrock's counts where main wrote no row
Rows for both legs, and Qwen3 commands and output
A Claude stream behind an application inference profile ARN answered 403 on both legs, since the QA role cannot invoke one, so the unit test covers that shape
Each leg is one proxy with 2 workers on its own Postgres database, set up as above with the sweep models in config.yaml. All 37 Bedrock chat ids in the cost map that LiteLLM maps to no provider were tried, except the 6
us-gov.ids, which need GovCloud. The config, both case scripts and every row for both legs are in this gistBedrock rejected the other 10 ids in this account on both legs, so they have no counts to bill:
claude-sonnet-4-5-20250929-v1:0(400),deepseek.r1-v1:0(400),eu.deepseek.v3.2(400),global.zai.glm-5.3(403),us.deepseek.v3.2(400),us.writer.palmyra-x4-v1:0(404),us.writer.palmyra-x5-v1:0(404),us.zai.glm-5.3(403),writer.palmyra-x4-v1:0(400),writer.palmyra-x5-v1:0(400)Ids that keep their own decoder bill the same on both legs, which decision 11 relies on. Nova's last event reports 0 / 0 in Bedrock's invocation metrics, so only its own usage is right. The commit only reads the response stream, so the request sent to Bedrock is unchanged, and its
invoke_handler.pypart only moves the trailer read into a function the chat route calls the same way. Commands and output are files 7 to 11 of the gistBefore (551a18b)
After (c865e9c)
Observations from the run, each the same on both legs, so this PR leaves them alone
bedrock/invoke/Qwen3 and Mistral 3 chat streams answer 400bedrock/invoke/chat answers 400Type
🐛 Bug Fix
✅ Test
Caveats (if any)
High
Low
include_usagebill at the full input price, since Bedrock's last event has no cache countsmoonshotai.kimi-k3andmoonshotai.kimi-k3.1have a cache read price, so their cached tokens bill 10x and 20x that rateus.deepseek.r1-v1:0bills Bedrock's counts but logs empty response text. Main wrote no row for itFinal Attestation
Bugbot summary