Skip to content

fix(bedrock): bill ConverseStream at the served tier - #52565

Merged
devin-ai-integration[bot] merged 6 commits into
mainfrom
litellm_bedrock_converse_stream_served_tier
Nov 18, 2026
Merged

devin-ai-integration[bot] merged 6 commits into
mainfrom
litellm_bedrock_converse_stream_served_tier

Conversation

@kerry-berri

@kerry-berri kerry-berri commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Handwritten 1-3 sentence description

[insert handwritten description here]

Details

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

TLDR

Problem this solves:

  • ConverseStream dropped the service tier reported by Bedrock.
  • Native passthrough logged Priority streams at the default rate.

How it solves it:

  • Keep the reported tier with stream usage for billing.
  • Preserve requested-tier fallback when no served tier is reported.
  • Keep tier-only metadata out of the chat stream.
  • Retain served tier in sync and async SDK assembly.

User Flow

Before, the proxy logs the default price for a Priority stream.

  1. Send POST http://127.0.0.1:4334/bedrock/model/audit-qwen/converse-stream with serviceTier.type set to priority.
  2. Read the HTTP 200 stream. The usage metadata reports Priority.
  3. Check the proxy log. It records $0.0000104 for 16 input and 2 output tokens.

After, the proxy logs the Priority price for the same stream.

  1. Send the same request to http://127.0.0.1:4333/bedrock/model/audit-qwen/converse-stream.
  2. Read the HTTP 200 stream. The usage metadata reports Priority.
  3. Check the proxy log. It records $0.0000182 for the same token counts.

Pre-Submission checklist

  • I have added meaningful tests
  • The relevant unit tests pass locally
  • My PR passes all required CI/CD checks
  • My PR's scope is as isolated as possible
  • Automated review is complete and findings are addressed

Screenshots / Proof of Fix

Both proxies used real AWS Bedrock in us-east-1, two workers, and the same dedicated Redis. The chat stream now reports the served tier. Messages and Responses still return usage in their existing formats.

Proxy config, startup, and client commands

Set LITELLM_AUDIT_MASTER_KEY locally and configure a Bedrock-capable AWS profile named litellm-dev. The Anthropic route is unused by this probe.

redis-server --bind 127.0.0.1 --port 16387
unset DATABASE_URL DIRECT_URL AWS_BEARER_TOKEN_BEDROCK
export LITELLM_LOCAL_MODEL_COST_MAP=True
export PYTHONPATH="$PWD"
python litellm/proxy/proxy_cli.py --config ~/cost-audit/proxy.yaml \
  --host 127.0.0.1 --port "$PORT" --num_workers 2 --detailed_debug \
  --reload --use_v2_migration_resolver
# In a second terminal, with the master key exported:
python -u ~/cost-audit/probe.py "http://127.0.0.1:$PORT"

proxy.yaml:

model_list:
  - model_name: audit-qwen
    litellm_params:
      model: bedrock/qwen.qwen3-coder-next
      aws_region_name: us-east-1
      aws_profile_name: litellm-dev
  - model_name: audit-claude
    litellm_params:
      model: anthropic/claude-sonnet-5-5
      api_key: os.environ/ANTHROPIC_API_KEY
router_settings:
  redis_host: 127.0.0.1
  redis_port: 16387
general_settings:
  master_key: os.environ/LITELLM_AUDIT_MASTER_KEY
  coordination_redis:
    host: 127.0.0.1
    port: 16387

probe.py:

import json
import os
import sys

import httpx
from botocore.eventstream import EventStreamBuffer

base = sys.argv[1]
client = httpx.Client(
    trust_env=False,
    headers={"Authorization": "Bearer " + os.environ["LITELLM_AUDIT_MASTER_KEY"]},
    timeout=120,
)
chat = {
    "model": "audit-qwen",
    "messages": [{"role": "user", "content": "Reply with exactly the single word Hi."}],
    "max_tokens": 32,
}
for label, extras in (
    ("chat priority", {"service_tier": "priority"}),
    ("chat default stream", {"stream": True}),
    ("chat priority stream", {"stream": True, "service_tier": "priority"}),
    ("chat flex stream", {"stream": True, "service_tier": "flex"}),
    ("chat reserved stream", {"stream": True, "service_tier": "reserved"}),
):
    body = {**chat, **extras}
    if body.get("stream"):
        body["stream_options"] = {"include_usage": True}
    response = client.post(base + "/v1/chat/completions", json=body)
    if response.is_error:
        print(label, response.status_code, response.json().get("error", {}).get("message", "")[:180], flush=True)
        continue
    frames = (
        [json.loads(line[6:]) for line in response.text.splitlines() if line.startswith("data: {")]
        if body.get("stream")
        else [response.json()]
    )
    result = next(frame for frame in reversed(frames) if frame.get("usage"))
    usage = result["usage"]
    print(label, response.status_code, "tier=", result.get("service_tier"),
          "tokens=", (usage["prompt_tokens"], usage["completion_tokens"]),
          "cost=", usage.get("cost", response.headers.get("x-litellm-response-cost")), flush=True)

response = client.post(base + "/bedrock/model/audit-qwen/converse-stream", json={
    "messages": [{"role": "user", "content": [{"text": chat["messages"][0]["content"]}]}],
    "inferenceConfig": {"maxTokens": chat["max_tokens"]},
    "serviceTier": {"type": "priority"},
})
print("native stream", response.status_code, "response cost header=", response.headers.get("x-litellm-response-cost"))
if response.is_success:
    events = EventStreamBuffer()
    events.add_data(response.content)
    for frame in events:
        if frame.headers.get(":event-type") == "metadata":
            metadata = json.loads(frame.payload)
            usage = metadata["usage"]
            print("native stream metadata", metadata.get("serviceTier"), (usage["inputTokens"], usage["outputTokens"]))
else:
    print(response.text[:250])

response = client.post(base + "/v1/messages", json={
    **chat, "stream": True, "service_tier": "priority",
})
print("messages stream", response.status_code, flush=True)
if response.is_success:
    for line in response.text.splitlines():
        if line.startswith("data: {"):
            event = json.loads(line[6:])
            if event.get("type") == "message_delta":
                print("message_delta", event.get("usage"), flush=True)
else:
    print(response.text[:250], flush=True)

response = client.post(base + "/v1/responses", json={
    "model": chat["model"], "input": chat["messages"][0]["content"], "stream": True,
    "service_tier": "priority", "max_output_tokens": chat["max_tokens"],
})
print("responses stream", response.status_code)
if response.is_success:
    for line in response.text.splitlines():
        if line.startswith("data: {"):
            event = json.loads(line[6:])
            if event.get("type") in {"response.completed", "response.failed", "response.incomplete", "error"}:
                result = event.get("response", {})
                print(event["type"], result.get("service_tier"), result.get("usage"), event.get("error"))
else:
    print(response.text[:250])
Observed before and after output

Before (4874a3c)

From base checkout, with PORT=4334:

  1. Start the proxy with the shared command.
INFO:     Started server process [33655]
INFO:     Started server process [33654]
  1. Run the client probe from the same checkout.

Chat Completions

chat priority 200 tier= priority tokens= (16, 2) cost= 1.82e-05
chat default stream 200 tier= None tokens= (16, 2) cost= 1.0399999999999999e-05
chat priority stream 200 tier= None tokens= (16, 2) cost= 1.82e-05
chat flex stream 200 tier= None tokens= (16, 2) cost= 5.199999999999999e-06
chat reserved stream 400 litellm.BadRequestError: BedrockException - {"message":"The provided model identifier is invalid."}

LiteLLM: model group 'audit-qwen' failed with the error above. No fallback was

Native ConverseStream

native stream 200 response cost header= None
native stream metadata {'type': 'priority'} (16, 2)
INFO:     127.0.0.1:58650 - "POST /bedrock/model/audit-qwen/converse-stream HTTP/1.1" 200 OK
16:11:24 - LiteLLM:DEBUG: litellm_logging.py:2632 - response_cost: 1.0399999999999999e-05

Messages

messages stream 200
message_delta {'input_tokens': 16, 'output_tokens': 2}

Responses

responses stream 200
response.completed None {'input_tokens': 16, 'input_tokens_details': {'cached_tokens': 0, 'cache_write_tokens': 0, 'text_tokens': 16}, 'output_tokens': 2, 'output_tokens_details': {'reasoning_tokens': 0, 'text_tokens': 2}, 'total_tokens': 18, 'cost': 1.82e-05} None

After (5df1e04)

From the PR checkout, with the same Redis and proxy config. The rerun used the local QA Postgres environment. The proxy reloaded after the final code change.

  1. Start the proxy with the existing master key and the command below.
export LITELLM_LOCAL_MODEL_COST_MAP=True PYTHONPATH="$PWD"
.venv/bin/python litellm/proxy/proxy_cli.py --config ~/cost-audit/proxy.yaml \
  --port 4333 --num_workers 2 --detailed_debug --reload --use_v2_migration_resolver
INFO:     Started server process [70383]
INFO:     Started server process [70384]
  1. Run .venv/bin/python -u ~/cost-audit/probe.py http://127.0.0.1:4333 from the same checkout.

Chat Completions

chat priority 200 tier= priority tokens= (16, 2) cost= 1.82e-05
chat default stream 200 tier= None tokens= (16, 2) cost= 1.0399999999999999e-05
chat priority stream 200 tier= priority tokens= (16, 2) cost= 1.82e-05
chat flex stream 200 tier= flex tokens= (16, 2) cost= 5.199999999999999e-06
chat reserved stream 400 litellm.BadRequestError: BedrockException - {"message":"The provided model identifier is invalid."}

LiteLLM: model group 'audit-qwen' failed with the error above. No fallback was 

Native ConverseStream

native stream 200 response cost header= None
native stream metadata {'type': 'priority'} (16, 2)
INFO:     127.0.0.1:55054 - "POST /bedrock/model/audit-qwen/converse-stream HTTP/1.1" 200 OK
19:44:30 - LiteLLM:DEBUG: litellm_logging.py:2632 - response_cost: 1.82e-05

Messages

messages stream 200
message_delta {'input_tokens': 16, 'output_tokens': 2}

Responses

responses stream 200
response.completed None {'input_tokens': 16, 'input_tokens_details': {'cached_tokens': 0, 'cache_write_tokens': 0, 'text_tokens': 16}, 'output_tokens': 2, 'output_tokens_details': {'reasoning_tokens': 0, 'text_tokens': 2}, 'total_tokens': 18, 'cost': 1.82e-05} None
Live chat stream shape before and after the review fix

I ran the same proxy setup above on the previously reviewed commit, using port 4334 and the PR checkout's Python environment. Both proxies used two workers. Run the probe against each address to count SSE frames.

.venv/bin/python ~/cost-audit/probe-chunks.py http://127.0.0.1:4334
.venv/bin/python ~/cost-audit/probe-chunks.py http://127.0.0.1:4333

probe-chunks.py:

import json
import os
import sys

import httpx

for include_usage in (False, True):
    payload = {
        "model": "audit-qwen",
        "messages": [{"role": "user", "content": "Reply with exactly the single word Hi."}],
        "max_tokens": 32,
        "stream": True,
        "service_tier": "priority",
    }
    if include_usage:
        payload["stream_options"] = {"include_usage": True}
    response = httpx.post(
        sys.argv[1] + "/v1/chat/completions",
        json=payload,
        headers={"Authorization": "Bearer " + os.environ["LITELLM_AUDIT_MASTER_KEY"]},
        timeout=120,
        trust_env=False,
    )
    response.raise_for_status()
    frames = [json.loads(line[6:]) for line in response.text.splitlines() if line.startswith("data: {")]
    usage = [chunk for chunk in frames if chunk.get("usage")]
    tier_only = [chunk for chunk in frames if chunk.get("service_tier") and not chunk.get("usage")]
    print("include_usage=", include_usage, "status=", response.status_code,
          "finish=", [choice["finish_reason"] for chunk in frames for choice in chunk["choices"]
                      if choice.get("finish_reason")],
          "tier_only_frames=", len(tier_only), "usage_frames=", len(usage),
          "served_tier=", usage[-1].get("service_tier") if usage else None, flush=True)

Before the review fix, at 4ea4eaccb91d3a7b6fe462199167fb01686f8bd0:

include_usage= False status= 200 finish= ['stop'] tier_only_frames= 1 usage_frames= 0 served_tier= None
include_usage= True status= 200 finish= ['stop'] tier_only_frames= 1 usage_frames= 1 served_tier= priority

At 5df1e0476e519df3f81494524be3a63aa8561c94:

include_usage= False status= 200 finish= ['stop'] tier_only_frames= 0 usage_frames= 0 served_tier= None
include_usage= True status= 200 finish= ['stop'] tier_only_frames= 0 usage_frames= 1 served_tier= priority
Live SDK assembled completion

Save this as ~/cost-audit/probe-assembled.py and run these commands from each checkout with the same AWS profile.

export PYTHONPATH="$PWD" LITELLM_LOCAL_MODEL_COST_MAP=True
python ~/cost-audit/probe-assembled.py
python ~/cost-audit/probe-assembled.py --async
import asyncio
import sys

import litellm

model = "bedrock/converse/qwen.qwen3-coder-next"
region = "us-east-1"
request = dict(
    model=model,
    messages=[{"role": "user", "content": "Reply with exactly the single word Hi."}],
    max_tokens=32,
    aws_region_name=region,
    aws_profile_name="litellm-dev",
    stream=True,
    complete_response=True,
    service_tier="priority",
)
response = (
    asyncio.run(litellm.acompletion(**request))
    if "--async" in sys.argv
    else litellm.completion(**request)
)
print("served_tier=", response.model_dump().get("service_tier"),
      "tokens=", (response.usage.prompt_tokens, response.usage.completion_tokens),
      "cost=", litellm.completion_cost(completion_response=response, model=model, region_name=region))

At the merge base, the async SDK raised the coroutine error below. The same error persisted at 266a2c810dfacdc86e564394cf2fe9ec1df1115a, where the sync SDK also lost the tier.

served_tier= None tokens= (16, 2) cost= 1.82e-05
litellm.exceptions.APIConnectionError: litellm.APIConnectionError: 'coroutine' object is not iterable

After at 5df1e0476e519df3f81494524be3a63aa8561c94, sync and async respectively:

served_tier= priority tokens= (16, 2) cost= 1.82e-05
served_tier= priority tokens= (16, 2) cost= 1.82e-05

AWS served the requested Priority tier. The sync and async regression test supplies Flex on a Priority request and checks the response and the Flex price. Before the async fix, its async case failed with the same coroutine error and its sync case passed.

The same regression tests failed on the base for both SDK modes and for passthrough billing, then passed on the fix. AWS returned the requested tier in the live runs. The SDK regression supplies a different served tier to verify that the served tier takes precedence.

Type

Bug fix

Final Attestation

  • The tests cover a served tier that differs from the requested tier, absent served metadata, native passthrough spend, and stream chunks.

🟢 Devin Review found nothing to fix · View findings · Follow Devin's work

Devin Review


Note

Medium Risk
Changes Bedrock streaming usage chunks and completion assembly paths that drive billing and proxy cost logging; scope is provider-specific and well-tested.

Overview
Fixes Bedrock ConverseStream billing and tier metadata so costs follow the served serviceTier from stream metadata (e.g. flex vs priority), not the default rate or a dropped tier.

Streaming handler attaches service_tier when usage arrives on Bedrock chunks, and on the final usage-only chunk records it internally instead of emitting an extra SSE frame with empty choices. Invoke handler maps serviceTier.type from converse stream events onto responses via _with_served_service_tier.

SDK complete_response path skips chunk assembly when the stream result is still an awaitable, and for Bedrock CustomStreamWrapper builds the full response from the wrapper’s accumulated chunks (including async drain), preserving tier for stream_chunk_builder and completion_cost.

New unit tests cover tier-priced streaming, assembled completions, and passthrough logging.

Reviewed by Cursor Bugbot for commit 5df1e04. Bugbot is set up for automated code reviews on this repo. Configure here.

kerry-berri and others added 2 commits November 18, 2026 16:06
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@veria-ai

veria-ai Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

No security issues were found in this pull request.

Reviews

@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

@codspeed

codspeed Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

1 warning

⚠️ 2 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 45 untouched benchmarks


Comparing litellm_bedrock_converse_stream_served_tier (5df1e04) with main (facccd8)1

Open in CodSpeed

Footnotes

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

@codecov

codecov Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@greptile-apps

greptile-apps Bot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge. No new actionable issues were found.

Summary

Bedrock streaming now keeps the served service tier for billing and assembled SDK responses without adding an empty chat-stream frame.

  • Bedrock stream usage keeps the tier Bedrock served for billing.
  • Full Bedrock stream responses keep the tier Bedrock served.

Reviews (6) · Last reviewed commit: "fix(bedrock): share stream assembly acro..." · Reviewed by Greptile

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

@devin-ai-integration devin-ai-integration 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.

✅ Devin Review: No Issues Found

Devin Review analyzed this PR and found no bugs or issues to report.

Devin Review

greptile-apps[bot]

This comment was marked as resolved.

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

Copy link
Copy Markdown
Contributor Author

bugbot run

1 similar comment
@kerry-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@devin-ai-integration devin-ai-integration Bot added the run-all-unit-shards Run the full unit test matrix instead of only the core shards label Nov 18, 2026

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

Stale Bugbot comment from a previous run.

Comment thread litellm/utils.py Resolved
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@kerry-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.

Stale Bugbot comment from a previous run.

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
@kerry-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 5df1e04. Configure here.

@kerry-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@devin-ai-integration
devin-ai-integration Bot enabled auto-merge (squash) November 18, 2026 20:51
@devin-ai-integration
devin-ai-integration Bot merged commit b478b81 into main Nov 18, 2026
102 checks passed
@devin-ai-integration
devin-ai-integration Bot deleted the litellm_bedrock_converse_stream_served_tier branch November 18, 2026 21:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

run-all-unit-shards Run the full unit test matrix instead of only the core shards

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants