Skip to content

refactor(bedrock): send Converse chat requests through the shared HTTP client - #50495

Open
ryan-crabbe-berri wants to merge 4 commits into
mainfrom
litellm_bedrock_converse_shared_http_handler
Open

ryan-crabbe-berri wants to merge 4 commits into
mainfrom
litellm_bedrock_converse_shared_http_handler

Conversation

@ryan-crabbe-berri

@ryan-crabbe-berri ryan-crabbe-berri commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

Handwritten 1-3 sentence description

[insert handwritten description here]

Details

TLDR

  • Bedrock chat calls used their own private copy of the "send it to AWS" code.
  • Every other Bedrock route already used the shared one, so fixes kept missing this route.
  • Now this route uses the shared code too, and the old copy is deleted.
  • Requests sent to AWS are byte-for-byte the same, checked across 251 live calls.
  • Three old quirks go away, including a caller being able to fake their identity in AWS billing.

User Flow

Before: a caller can stamp someone else's identity on their Bedrock usage in the AWS billing record

  1. The proxy admin turns on bedrock_request_metadata_fields: ["user_api_key_alias"] so AWS Cost Explorer shows who spent what
  2. A developer sends POST https://litellm-domain/v1/chat/completions with "model": "bedrock-claude" and their own virtual key
  3. They add "extra_headers": {"X-Amzn-Bedrock-Request-Metadata": "{\"user_api_key_alias\":\"someone-else\"}"} to the body
  4. The proxy forwards that header to Bedrock as is and signs it, so AWS records the spend under someone-else

After: the same request reaches AWS with the developer's real identity

  1. The proxy admin turns on bedrock_request_metadata_fields: ["user_api_key_alias"] so AWS Cost Explorer shows who spent what
  2. A developer sends POST https://litellm-domain/v1/chat/completions with "model": "bedrock-claude" and their own virtual key
  3. They add the same forged X-Amzn-Bedrock-Request-Metadata header
  4. The proxy drops their header and sends its own, so AWS records the spend under the developer's real key alias

Another caller can no longer charge their usage to someone else's name in the AWS billing record.

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • 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. Leave the suites (make test-unit-*, make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or more
  • 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

Delays 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 is the merge base 98acc01e0d9. After is 6d2643ac1e5, which is this branch before a clean rebase onto newer main. The rebase changed none of this PR's files, so the PR's diff at the tip 4767ad655b9 is the same one that was tested. Both trees were frozen with git archive and run side by side. Three things were run on each side, all against real AWS Bedrock with the same AWS account and the same models.

Shared setup: proxy command, config, env var names

The proxy ran from each frozen tree with 2 workers, a dedicated Redis wired into router_settings and general_settings.coordination_redis, and a fresh Postgres database. Two worker PIDs were serving on both sides. --reload was dropped because on this checkout it collapses the proxy to one worker, and a frozen tree needs no reload.

PYTHONPATH=$TREE:$TREE/litellm-proxy-extras:$TREE/enterprise LITELLM_LOCAL_MODEL_COST_MAP=True \
  python litellm/proxy/proxy_cli.py --config config.yaml \
  --num_workers 2 --detailed_debug --use_v2_migration_resolver --port 4617   # 4627 for After

Env var names (values never shown): LITELLM_MASTER_KEY, DATABASE_URL, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN, AWS_REGION, E2E_AWS_PROFILE, OPENAI_API_KEY (one redacted-thinking cell only).

model_list:
  - model_name: conv-haiku
    litellm_params:
      model: bedrock/us.anthropic.claude-haiku-5-5
      aws_region_name: us-east-1
      aws_profile_name: os.environ/E2E_AWS_PROFILE
  - model_name: conv-prefix-haiku
    litellm_params:
      model: bedrock/converse/us.anthropic.claude-haiku-5-5
      aws_region_name: us-east-1
      aws_profile_name: os.environ/E2E_AWS_PROFILE
  - model_name: conv-nova
    litellm_params:
      model: bedrock/us.amazon.nova-2-lite-v1:0
      aws_region_name: us-east-1
      aws_profile_name: os.environ/E2E_AWS_PROFILE
  - model_name: conv-model-id
    litellm_params:
      model: bedrock/converse/anthropic.claude-haiku-5-5
      model_id: arn:aws:bedrock:us-east-1:<account>:inference-profile/us.anthropic.claude-haiku-5-5
      aws_region_name: us-east-1
      aws_profile_name: os.environ/E2E_AWS_PROFILE
  - model_name: conv-arn-region
    litellm_params:
      model: bedrock/converse/arn:aws:bedrock:us-west-2:<account>:inference-profile/us.anthropic.claude-haiku-5-5
      aws_profile_name: os.environ/E2E_AWS_PROFILE
  - model_name: conv-region-path
    litellm_params:
      model: bedrock/us-west-2/us.anthropic.claude-haiku-5-5
      aws_profile_name: os.environ/E2E_AWS_PROFILE
  - model_name: conv-bad-model
    litellm_params:
      model: bedrock/converse/us.anthropic.claude-does-not-exist-9-9
      aws_region_name: us-east-1
      aws_profile_name: os.environ/E2E_AWS_PROFILE
  - model_name: conv-bad-with-fallback
    litellm_params:
      model: bedrock/converse/us.anthropic.claude-does-not-exist-9-9
      aws_region_name: us-east-1
      aws_profile_name: os.environ/E2E_AWS_PROFILE

general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
  database_url: os.environ/DATABASE_URL
  store_model_in_db: true
  store_prompts_in_spend_logs: true
  proxy_batch_write_at: 5
  coordination_redis:
    host: 127.0.0.1
    port: 4618

litellm_settings:
  drop_params: true
  request_timeout: 600

router_settings:
  routing_strategy: simple-shuffle
  redis_host: 127.0.0.1
  redis_port: 4618
  num_retries: 2
  fallbacks:
    - conv-bad-with-fallback: ["conv-haiku"]

Before (98acc01)

1. Existing Bedrock Converse e2e tests against the live proxy

Commands as run

Env: LITELLM_PROXY_URL=http://127.0.0.1:4617, LITELLM_MASTER_KEY, the AWS env above, E2E_PROVIDER_EDGE_HOST_REACHABLE=1, REDIS_HOST, REDIS_PORT.

L=tests/e2e/llm_translation
python -P -m pytest -p no:cacheprovider \
  $L/test_chat_completions_regression_e2e.py $L/test_chat_tool_round_trip_e2e.py $L/test_responses_e2e.py \
  $L/test_bedrock_provider_matrix_e2e.py $L/test_bedrock_native_e2e.py $L/test_messages_bedrock_e2e.py \
  $L/test_messages_beta_headers_e2e.py $L/test_messages_prompt_caching_and_tool_search_e2e.py $L/test_reasoning_effort_e2e.py \
  $L/test_cache_control.py $L/test_bedrock_converse_redacted_thinking_e2e.py $L/test_bedrock_kimi_k3_messages_e2e.py \
  -k "converse or bedrock" -n 3 -rA

python -P -m pytest -p no:cacheprovider tests/e2e/claude_code/*/test_bedrock_converse.py -n 2 -rA
  1. llm_translation Bedrock Converse selection gives 39 passed and 1 failed. The failure is test_converse_empty_messages_returns_client_error, which goes through the /bedrock passthrough route (not touched here) and flakes between pass and 503 {}
  2. Claude Code compatibility cells, driving the real claude CLI 2.1.319 through the proxy, give 15 passed and 1 skipped (long_context_1m carries a skip marker in the tree)

2. Live end-user flows on all three LLM endpoints

38 flows, each a real request with the virtual key. They cover /v1/chat/completions, /v1/messages and /v1/responses, streaming and not, with tools, response_format json_schema, reasoning_effort, image input, Nova, the bedrock/converse/ prefix, a model_id inference profile, the region taken from an ARN or a path segment, a fallback from a bad model id, and four error cases (unknown model, bad param, huge max_tokens, timeout: 0.001). Afterwards each flow's spend log row is checked for model, provider, tokens and positive spend.

Representative requests (each flow's body is replayed the same way)
curl -sS -D - http://127.0.0.1:4617/v1/chat/completions -H "Authorization: Bearer $LITELLM_MASTER_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"model":"conv-haiku","messages":[{"role":"user","content":"Reply with exactly the single word: pong"}],"max_tokens":40,"stream":true,"stream_options":{"include_usage":true}}'

curl -sS -D - http://127.0.0.1:4617/v1/messages -H "Authorization: Bearer $LITELLM_MASTER_KEY" \
  -H 'Content-Type: application/json' -H 'anthropic-version: 2023-06-01' \
  -d '{"model":"conv-prefix-haiku","max_tokens":64,"messages":[{"role":"user","content":"Reply with exactly the single word: pong"}]}'

curl -sS -D - http://127.0.0.1:4617/v1/responses -H "Authorization: Bearer $LITELLM_MASTER_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"model":"conv-haiku","input":"Reply with exactly the single word: pong","stream":true}'
  1. 38/38 flows pass, and every successful flow has a spend log row with positive spend and token counts
  2. Errors come back as 400 (unknown model, bad param) and 408 (timeout: 0.001), and the fallback fires with x-litellm-attempted-fallbacks: 1

3. SDK matrix with wire capture, 91 cells and 251 variants

Each cell runs litellm.completion and litellm.acompletion against live Bedrock, stream and non-stream, and records the exact URL, headers and JSON body that left the process, plus the response, usage, cost, response headers, callbacks and error class. Cells cover every auth style (profile, static keys, session token, bearer token, deprecated boto3 client), api_base, aws_bedrock_runtime_endpoint, model_id, the region in the model path, tools and tool round trips, structured output and its json-tool fallback, the strict-tools retry, thinking, prompt caching, images, PDFs, a guardrail, stream_chunk_size, fake_stream, passed-in HTTP clients, timeouts and eight error shapes. main was run twice to measure the noise floor, and the only difference between the two runs was one known Nova stream flake.

How one cell captures the wire (harness excerpt)
original_send, original_async_send = httpx.Client.send, httpx.AsyncClient.send

def record(request: httpx.Request) -> None:
    sent.append({"url": str(request.url), "headers": sorted(request.headers), "body": json.loads(request.content)})

def send(self, request, **kwargs):
    record(request)
    return original_send(self, request, **kwargs)

async def async_send(self, request, **kwargs):
    record(request)
    return await original_async_send(self, request, **kwargs)

httpx.Client.send, httpx.AsyncClient.send = send, async_send
response = litellm.completion(model="bedrock/us.anthropic.claude-haiku-5-5", messages=[...],
                              aws_profile_name=PROFILE, aws_region_name="us-west-2", max_tokens=40)
  1. 207 of 251 variants succeed and 44 fail. Of the 44 failures, 36 are deliberate error cells, and 8 fail for reasons that are real on main
  2. extra_body={"performanceConfig": ...} fails with Bedrock 400 "extra_body: Extra inputs are not permitted", because it gets nested under additionalModelRequestFields
  3. A sync call with an unsupported anthropic-beta value fails with 400, because sync puts the unfiltered beta list in the body while async filters it
  4. With bedrock_request_metadata_fields set, a caller's X-Amzn-Bedrock-Request-Metadata header is forwarded and signed as is (see case 4)

4. Forged billing identity (the User Flow above)

Script as run (PYTHONPATH pointed at each tree)
import asyncio, json, httpx, litellm

seen = []
original_send = httpx.AsyncClient.send

async def send(self, request, **kwargs):
    body = json.loads(request.content)
    seen.append((request.headers.get("x-amzn-bedrock-request-metadata"), body.get("requestMetadata")))
    return await original_send(self, request, **kwargs)

httpx.AsyncClient.send = send
litellm.bedrock_request_metadata_fields = ["user_api_key_alias", "cost_center"]

async def main():
    await litellm.acompletion(
        model="bedrock/us.anthropic.claude-haiku-4-5-20251001-v1:0",
        messages=[{"role": "user", "content": "say hi"}],
        max_tokens=5,
        aws_profile_name="<sso profile>",
        aws_region_name="us-west-2",
        metadata={"user_api_key_alias": "alias-1", "spend_logs_metadata": {"cost_center": "cc-42"}},
        extra_headers={"X-Amzn-Bedrock-Request-Metadata": json.dumps({"user_api_key_alias": "forged"})},
    )

asyncio.run(main())
print(seen)
  1. Bedrock answers 200
  2. The signed header that reaches AWS is {"user_api_key_alias": "forged"}, while the body says alias-1

After (6d2643ac1e5, rebased to 4767ad6 with this PR's files unchanged)

1. Existing Bedrock Converse e2e tests against the live proxy

  1. llm_translation Bedrock Converse selection gives 40 passed. The passthrough flake passed this time
  2. Claude Code compatibility cells give 15 passed and 1 skipped, the same skip

2. Live end-user flows on all three LLM endpoints

  1. 38/38 flows pass, and every successful flow has a spend log row with positive spend and token counts
  2. The Bedrock region, operation and model id hit by every flow match Before exactly
  3. Errors come back with the same status codes and the same fallback header
  4. The timeout: 0.001 non-stream message now reads litellm.Timeout: BedrockException: Timeout Error - litellm.Timeout: Connection timed out... instead of litellm.Timeout: Connection timed out..., still with status 408 and the same error type
  5. The timeout: 0.001 non-stream spend row now carries the prompt cost, like the stream row already did Before. The request now goes out on an already-open connection, so the timeout hits after Bedrock received it, and the existing rule bills a read timeout

3. SDK matrix with wire capture, 91 cells and 251 variants

  1. The URL, headers and body sent to Bedrock are identical to Before in 247 of 251 variants
  2. The four that differ are the intended changes: extra_body fields now go at the top of the body (the cell now gets a 200), sync drops the unsupported beta from the body like async did (the cell now gets a 200), and with metadata forwarding on, the proxy's own metadata header is sent
  3. No new secret or aws_* value shows up in any request body, URL, logged payload or hidden params
  4. Every variant that succeeded Before still succeeds, with the same finish reason, tool calls, usage fields, positive cost and llm_provider-* response headers
  5. Error classes and status codes match Before, except a sync call to a host that doesn't resolve, which now gives 503 like the async call already did instead of 500
  6. The first After run had 13 variants fail on a DNS blip reaching AWS (nodename nor servname provided). All 13 were rerun and match Before

4. Forged billing identity

  1. Bedrock answers 200
  2. The signed header that reaches AWS is {"user_api_key_alias":"alias-1"}, the same identity as the body

Unit tests and mutation check

tests/unit/llms/bedrock/chat/test_converse_runtime.py (107 tests) replaces the old handler's tests. Each behavior that had a test still has one, and they now go through litellm.completion and litellm.acompletion with an injected HTTP client. Three tests were dropped because they only covered internals that no longer exist. Each of these mutations of the new module turns at least one test red: leaving transport params in the body, ignoring the region in the model path, signing for a different region than the URL, always using /converse, ignoring model_id, keeping the nova prefix, dropping response headers, skipping the beta filter, signing converse_like requests, signing on the event loop, ignoring a bearer api_key, and ignoring stream_chunk_size. Run against main, the forged-header test fails for sync and async and the sync beta test fails, while the "nothing leaks into the body" test passes on both trees, as it should.

Type

Refactoring
Bug Fix

Caveats (if any)

Medium

  • The internal BedrockConverseLLM class is deleted
    • So is litellm.main.bedrock_converse_chat_completion
    • Code importing either one directly breaks
    • The S3 config loader and the agent-runtime passthrough now use the shared AWS auth class
  • Logging callbacks now receive the Converse request as a dict, not a JSON string
    • This matches every other provider on the shared client

Low

  • A caller's extra_body now merges into the top of the Bedrock body
    • Before, it was always rejected with a 400
  • Sync calls now filter anthropic-beta values out of the body the same way async calls do
  • With bedrock_request_metadata_fields on, Converse now also sends the metadata header
    • Bedrock accepts it, and it replaces any caller-supplied value
  • Timeout errors gain a BedrockException: Timeout Error - prefix in the message
    • Status 408 and the error type are unchanged
  • A sync call to an unreachable host now raises 503 instead of 500, matching async
  • A passed-in async HTTP client now gets the request timeout
    • Before, it sent with no timeout at all
  • The web search interception hook now runs on async non-stream Converse calls
    • It only runs when an operator enables it for Bedrock, as it already does on invoke
  • Not covered live: the native structured-output rejection retry and the buffered retry after a stream permission denial
    • The test account never triggers either one, so unit tests cover both

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

Note

Medium Risk
Large refactor of the primary Bedrock Converse path (signing, URLs, streaming, and auth), though parity is heavily tested; direct imports of removed handler symbols will break at upgrade.

Overview
Bedrock Converse no longer uses the deleted BedrockConverseLLM / converse_handler.py path. Calls go through base_llm_http_handler.completion with a new AmazonConverseRuntimeConfig that handles SigV4 signing, regional runtime URLs, stripping transport-only params from the body, and custom streaming.

Shared AWS credential resolution is centralized via with_aws_credential_fallbacks (replacing _aws_signing_overrides in the HTTP handler). Converse dispatch applies filtered anthropic-beta headers before the request is sent.

Breaking surface: litellm.main.bedrock_converse_chat_completion and direct BedrockConverseLLM imports are gone; proxy S3 config and agent-runtime passthrough now use BaseAWSLLM for credentials.

Behavioral fixes bundled in the new stack include proxy-owned X-Amzn-Bedrock-Request-Metadata when metadata forwarding is enabled (forged caller headers no longer win), sync anthropic-beta filtering aligned with async, and extra_body merged at the top level instead of being rejected as nested additionalModelRequestFields.

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

@codspeed

codspeed Bot commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

1 warning

⚠️ 1 benchmark is 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

✅ 43 untouched benchmarks


Comparing litellm_bedrock_converse_shared_http_handler (4767ad6) with main (e9b1c11)

Open in CodSpeed

@codecov

codecov Bot commented Nov 7, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@ryan-crabbe-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@ryan-crabbe-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@greptile-apps

greptile-apps Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 3/5

[Medium impact] The PR changes Bedrock Converse request handling and a small set of operator AWS-auth paths.

Protect the final requestMetadata body and supply the required live QA before merging.

Findings

  1. P1 Security Callers can forge billing identity ▶
  2. P2 Required live proof is outdated ▶

Summary

Converse requests now use BaseLLMHTTPHandler through AmazonConverseRuntimeConfig.

  • Bedrock Converse chats now use the shared HTTP client.
  • Bedrock support tools now use the shared AWS auth class.

Acknowledgments by ryan-crabbe-berri were excluded as intentional changes. These include deleted internal imports, callback payloads changing from JSON strings to dictionaries, top-level extra_body, beta filtering, metadata-header replacement, timeout-message changes, DNS errors returning 503, injected async-client timeouts, and the newly reached web-search hook. The overwritten identity body reported above is distinct from those acknowledged changes.

Reviews (1) · Last reviewed commit: "refactor(bedrock): keep Converse runtime..." · Reviewed by Greptile

Comment thread litellm/main.py

def converse_attempt(fallback: NativeOutputFallback | None) -> NativeOutputAttemptResult:
return bedrock_converse_chat_completion.completion(
return base_llm_http_handler.completion(

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.

P1 security Callers can forge billing identity

With metadata forwarding enabled, a caller can send extra_body.requestMetadata containing a forged user_api_key_alias. The shared handler merges it after Converse adds trusted identity, then signs the overwritten body. Reapply resolve_bedrock_request_metadata after the merge to protect reserved fields.

How this was verified: The shared handler merges caller fields after the Converse transform, then signs the overwritten body.

Knowledge Base Used: Provider adapters and capabilities

return json.dumps(data) if signed_json_body is None else signed_json_body.decode()


class AmazonConverseRuntimeConfig(AmazonConverseConfig, SignsRequestsWithAWS):

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.

P2 Required live proof is outdated

The supplied before run uses 98acc01e0d9, which predates the current merge base. The after run uses 6d2643ac1e5, before the rebase. The repository requires live proof on the current base and latest product commit. Rerun before at e9b1c110985 and after at 4767ad655b9 before merging. Claims that the files are unchanged do not satisfy that requirement.

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!

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

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 4767ad6. Configure here.

if path_region is not None and "aws_region_name" not in params
else params
)
return _AWS._get_aws_region_name(optional_params=dict(region_params), model=model, model_id=model_id)

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.

Path region loses to litellm_params

Medium Severity

get_complete_url merges aws_region_name from litellm_params into params before _region runs, so a region embedded in the model path is skipped whenever that fallback is present. The old handler injected the path region whenever optional_params lacked aws_region_name, so bedrock/us-west-2/... still targeted us-west-2 even if the deployment stored another region in litellm_params. Calls now hit the fallback region instead, which can 4xx or bill the wrong region.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 4767ad6. Configure here.

@mateo-berri

Copy link
Copy Markdown
Contributor

#50964 handles Bedrock Converse extra_body inside transform_request. This PR pops extra_body before that runs, so the five extra_body tests there fail once both merge

This branch has not been deployed

No deployments
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.

2 participants