Repository navigation
refactor(bedrock): send Converse chat requests through the shared HTTP client - #50495
ryan-crabbe-berri wants to merge 4 commits into
Conversation
Merging this PR will not alter performance1 warning
Comparing |
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
|
bugbot run |
[Medium impact] The PR changes Bedrock Converse request handling and a small set of operator AWS-auth paths. Protect the final FindingsSummaryConverse requests now use
Acknowledgments by Reviews (1) · Last reviewed commit: "refactor(bedrock): keep Converse runtime..." · Reviewed by Greptile |
|
|
||
| def converse_attempt(fallback: NativeOutputFallback | None) -> NativeOutputAttemptResult: | ||
| return bedrock_converse_chat_completion.completion( | ||
| return base_llm_http_handler.completion( |
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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!
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.
❌ 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) |
There was a problem hiding this comment.
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)
Reviewed by Cursor Bugbot for commit 4767ad6. Configure here.
|
#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 |


Handwritten 1-3 sentence description
[insert handwritten description here]
Details
TLDR
User Flow
Before: a caller can stamp someone else's identity on their Bedrock usage in the AWS billing record
bedrock_request_metadata_fields: ["user_api_key_alias"]so AWS Cost Explorer shows who spent what"model": "bedrock-claude"and their own virtual key"extra_headers": {"X-Amzn-Bedrock-Request-Metadata": "{\"user_api_key_alias\":\"someone-else\"}"}to the bodysomeone-elseAfter: the same request reaches AWS with the developer's real identity
bedrock_request_metadata_fields: ["user_api_key_alias"]so AWS Cost Explorer shows who spent what"model": "bedrock-claude"and their own virtual keyX-Amzn-Bedrock-Request-MetadataheaderAnother 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
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 is the merge base
98acc01e0d9. After is6d2643ac1e5, 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 tip4767ad655b9is the same one that was tested. Both trees were frozen withgit archiveand 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_settingsandgeneral_settings.coordination_redis, and a fresh Postgres database. Two worker PIDs were serving on both sides.--reloadwas dropped because on this checkout it collapses the proxy to one worker, and a frozen tree needs no reload.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).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.test_converse_empty_messages_returns_client_error, which goes through the/bedrockpassthrough route (not touched here) and flakes between pass and503 {}claudeCLI 2.1.319 through the proxy, give 15 passed and 1 skipped (long_context_1mcarries 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/messagesand/v1/responses, streaming and not, with tools,response_formatjson_schema,reasoning_effort, image input, Nova, thebedrock/converse/prefix, amodel_idinference 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)
timeout: 0.001), and the fallback fires withx-litellm-attempted-fallbacks: 13. SDK matrix with wire capture, 91 cells and 251 variants
Each cell runs
litellm.completionandlitellm.acompletionagainst 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)
extra_body={"performanceConfig": ...}fails with Bedrock 400 "extra_body: Extra inputs are not permitted", because it gets nested underadditionalModelRequestFieldsanthropic-betavalue fails with 400, because sync puts the unfiltered beta list in the body while async filters itbedrock_request_metadata_fieldsset, a caller'sX-Amzn-Bedrock-Request-Metadataheader 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)
{"user_api_key_alias": "forged"}, while the body saysalias-1After (6d2643ac1e5, rebased to 4767ad6 with this PR's files unchanged)
1. Existing Bedrock Converse e2e tests against the live proxy
2. Live end-user flows on all three LLM endpoints
timeout: 0.001non-stream message now readslitellm.Timeout: BedrockException: Timeout Error - litellm.Timeout: Connection timed out...instead oflitellm.Timeout: Connection timed out..., still with status 408 and the same error typetimeout: 0.001non-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 timeout3. SDK matrix with wire capture, 91 cells and 251 variants
extra_bodyfields 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 sentaws_*value shows up in any request body, URL, logged payload or hidden paramsllm_provider-*response headersnodename nor servname provided). All 13 were rerun and match Before4. Forged billing identity
{"user_api_key_alias":"alias-1"}, the same identity as the bodyUnit 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 throughlitellm.completionandlitellm.acompletionwith 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, ignoringmodel_id, keeping the nova prefix, dropping response headers, skipping the beta filter, signingconverse_likerequests, signing on the event loop, ignoring a bearerapi_key, and ignoringstream_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
BedrockConverseLLMclass is deletedlitellm.main.bedrock_converse_chat_completionLow
extra_bodynow merges into the top of the Bedrock bodyanthropic-betavalues out of the body the same way async calls dobedrock_request_metadata_fieldson, Converse now also sends the metadata headerBedrockException: Timeout Error -prefix in the messageFinal Attestation
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.pypath. Calls go throughbase_llm_http_handler.completionwith a newAmazonConverseRuntimeConfigthat 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_overridesin the HTTP handler). Converse dispatch applies filtered anthropic-beta headers before the request is sent.Breaking surface:
litellm.main.bedrock_converse_chat_completionand directBedrockConverseLLMimports are gone; proxy S3 config and agent-runtime passthrough now useBaseAWSLLMfor credentials.Behavioral fixes bundled in the new stack include proxy-owned
X-Amzn-Bedrock-Request-Metadatawhen metadata forwarding is enabled (forged caller headers no longer win), sync anthropic-beta filtering aligned with async, andextra_bodymerged at the top level instead of being rejected as nestedadditionalModelRequestFields.Reviewed by Cursor Bugbot for commit 4767ad6. Bugbot is set up for automated code reviews on this repo. Configure here.