Repository navigation
feat(bedrock): route OpenAI models to bedrock-runtime's native Chat Completions API #43264
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
1bbf9fb
feat(bedrock): route OpenAI models to bedrock-runtime's native Chat C…
6matt 5678141
fix(bedrock): bridge function-tools + reasoning requests to native Re…
6matt 4b67e19
style(bedrock): add __init__ return annotation for ruff strict gate (…
6matt 25d0ab3
refactor(bedrock): drive tools+reasoning bridge from a price-map flag…
6matt 59e1bf6
fix(bedrock): stop callers forging Bedrock request-attribution metada…
6matt 55f819c
test(bedrock): cover native-chat dispatch/params; type __init__; regi…
6matt 582fe71
fix(bedrock): stop extra_body from overriding the authorized model on…
6matt 33c4c47
Merge remote-tracking branch 'upstream/main' into feat/bedrock-native…
6matt 4466a96
test(bedrock): cover native-chat config to 100%; justify model-pin mu…
6matt cab8ae0
style(bedrock): keep the model-pin line single-line for ruff format
6matt bdcc4ae
style(bedrock): ruff-format the native-chat test file
6matt 0d9ceab
test(bedrock): assert SigV4-signed body carries the pinned model
6matt c7d2829
test(bedrock): assert exact model field in signed body; drop redundan…
6matt b6959df
Merge remote-tracking branch 'upstream/main' into feat/bedrock-native…
6matt 7719625
fix(bedrock): revert tools+reasoning price-map flag to a version check
6matt ad1f2a4
fix(cost-map): dedupe perceptron-mk1.5, keep newer capability flags
6matt File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
191 changes: 191 additions & 0 deletions
191
litellm/llms/bedrock/chat/openai_native/transformation.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,191 @@ | ||
| """Amazon Bedrock Runtime - native OpenAI Chat Completions API. | ||
|
|
||
| AWS serves the newer OpenAI models on ``bedrock-runtime`` through an | ||
| OpenAI-compatible surface at | ||
| ``https://bedrock-runtime.{region}.{dns_suffix}/openai/v1/chat/completions``, | ||
| alongside Converse. Without this config the ``bedrock`` provider translates every | ||
| chat request into Converse, which is lossy for OpenAI-family models (verbosity, | ||
| reasoning items/tokens, ``prompt_cache_key``, OpenAI tool shapes). | ||
|
|
||
| This is the Chat Completions sibling of ``BedrockOpenAIResponsesConfig`` | ||
| (litellm/llms/bedrock/responses/transformation.py). Payloads and SSE follow the | ||
| OpenAI Chat spec, so it inherits ``OpenAIGPT5Config`` -- the same param mapper the | ||
| ``openai`` provider uses for the gpt-5/gpt-6 reasoning series -- and overrides only | ||
| the endpoint URL, authentication, and AWS SigV4 signing. Inheriting GPT5Config is | ||
| what makes the config reject-safe: bedrock-runtime enforces the reasoning-model | ||
| rules verbatim (only ``temperature=1``, no ``top_p``/``logprobs`` while reasoning), | ||
| and GPT5Config already drops or validates exactly those. A model that is not a | ||
| reasoning-series model falls back to the plain OpenAIGPT param mapping. | ||
|
|
||
| Auth: Bearer token (litellm_params.api_key or the standard AWS_BEARER_TOKEN_BEDROCK) | ||
| when present; otherwise AWS SigV4 (service "bedrock") over the standard credential | ||
| chain, signed via BaseAWSLLM._sign_request once the body is final. | ||
|
|
||
| Model IDs: bedrock-runtime serves these models only through a cross-Region | ||
| inference profile, so the body carries ``us.openai.gpt-6-luna`` / | ||
| ``global.openai.gpt-6-luna`` verbatim; the bare ``openai.gpt-6-luna`` is rejected | ||
| ("on-demand throughput isn't supported ... Retry ... with the ID or ARN of an | ||
| inference profile"). | ||
| """ | ||
|
|
||
| from typing import Final | ||
|
|
||
| import httpx | ||
|
|
||
| from litellm.llms.base_llm.chat.transformation import BaseLLMException | ||
| from litellm.llms.bedrock.base_aws_llm import BaseAWSLLM | ||
| from litellm.llms.bedrock.common_utils import BedrockError | ||
| from litellm.llms.bedrock.request_metadata import ( | ||
| bedrock_request_metadata_headers, | ||
| merge_bedrock_invoke_headers, | ||
| ) | ||
| from litellm.llms.bedrock.responses.transformation import resolve_bedrock_bearer_token | ||
| from litellm.llms.openai.chat.gpt_5_transformation import ( | ||
| OpenAIGPT5Config, | ||
| is_gpt_reasoning_series_name, | ||
| ) | ||
| from litellm.llms.openai.chat.gpt_transformation import OpenAIGPTConfig | ||
| from litellm.secret_managers.main import get_secret_str | ||
| from litellm.types.llms.openai import AllMessageValues | ||
|
|
||
| BEDROCK_RUNTIME_OPENAI_CHAT_PATH: Final = "/openai/v1/chat/completions" | ||
| # The same base suffixes the Responses config strips, plus the chat path itself, | ||
| # so an explicit api_base carrying any of them collapses to the runtime host. | ||
| BEDROCK_RUNTIME_OPENAI_BASE_SUFFIXES: Final = ( | ||
| "/openai/v1/chat/completions", | ||
| "/openai/v1/responses", | ||
| "/v1/chat/completions", | ||
| "/openai/v1", | ||
| "/v1", | ||
| ) | ||
|
|
||
|
|
||
| class BedrockOpenAIChatConfig(OpenAIGPT5Config, BaseAWSLLM): | ||
| """Chat Completions config for the OpenAI models on the bedrock-runtime endpoint.""" | ||
|
|
||
| def __init__(self) -> None: | ||
| OpenAIGPT5Config.__init__(self) | ||
| BaseAWSLLM.__init__(self) | ||
|
|
||
| @property | ||
| def custom_llm_provider(self) -> str | None: | ||
| return "bedrock" | ||
|
|
||
| def get_error_class(self, error_message: str, status_code: int, headers: dict | httpx.Headers) -> BaseLLMException: | ||
| # bedrock-runtime returns x-amzn-RequestId; BedrockError preserves it. | ||
| return BedrockError(status_code=status_code, message=error_message, headers=headers) | ||
|
|
||
| def map_openai_params( | ||
| self, | ||
| non_default_params: dict, | ||
| optional_params: dict, | ||
| model: str, | ||
| drop_params: bool, | ||
| ) -> dict: | ||
| # The reasoning-series mapper (temperature/top_p/logprobs guards) is correct only | ||
| # for gpt-5/gpt-6; anything else on this surface takes the plain OpenAI mapping. | ||
| if is_gpt_reasoning_series_name(model): | ||
| return super().map_openai_params(non_default_params, optional_params, model, drop_params) | ||
| return OpenAIGPTConfig().map_openai_params(non_default_params, optional_params, model, drop_params) | ||
|
|
||
| def get_supported_openai_params(self, model: str) -> list: | ||
| if is_gpt_reasoning_series_name(model): | ||
| return super().get_supported_openai_params(model) | ||
| return OpenAIGPTConfig().get_supported_openai_params(model) | ||
|
|
||
| def transform_request( | ||
| self, | ||
| model: str, | ||
| messages: list[AllMessageValues], | ||
| optional_params: dict, | ||
| litellm_params: dict, | ||
| headers: dict, | ||
| ) -> dict: | ||
| # AWS auth params ride in optional_params for signing; they must not reach the | ||
| # request body (the endpoint rejects "Unknown parameter: 'aws_region_name'"). | ||
| inference_params: Final = { | ||
| key: value for key, value in optional_params.items() if key not in self.aws_authentication_params | ||
| } | ||
| return super().transform_request( | ||
| model=model, | ||
| messages=messages, | ||
| optional_params=inference_params, | ||
| litellm_params=litellm_params, | ||
| headers=headers, | ||
| ) | ||
|
|
||
| def get_complete_url( | ||
| self, | ||
| api_base: str | None, | ||
| api_key: str | None, | ||
| model: str, | ||
| optional_params: dict, | ||
| litellm_params: dict, | ||
| stream: bool | None = None, | ||
| ) -> str: | ||
| region: Final = self._get_aws_region_name(optional_params=optional_params, model=model) | ||
| override: Final = ( | ||
| api_base | ||
| or optional_params.get("aws_bedrock_runtime_endpoint") | ||
| or get_secret_str("AWS_BEDROCK_RUNTIME_ENDPOINT") | ||
| ) | ||
| # Partition-aware: bedrock-runtime is amazonaws.com.cn in China and other | ||
| # suffixes in GovCloud/ISO, so defer to the shared endpoint builder. | ||
| host: Final = ( | ||
| override or self._select_default_endpoint_url(endpoint_type="runtime", aws_region_name=region) | ||
| ).rstrip("/") | ||
| base: Final = next( | ||
| (host[: -len(suffix)] for suffix in BEDROCK_RUNTIME_OPENAI_BASE_SUFFIXES if host.endswith(suffix)), | ||
| host, | ||
| ) | ||
| return f"{base}{BEDROCK_RUNTIME_OPENAI_CHAT_PATH}" | ||
|
|
||
| def validate_environment( | ||
| self, | ||
| headers: dict, | ||
| model: str, | ||
| messages: list[AllMessageValues], | ||
| optional_params: dict, | ||
| litellm_params: dict, | ||
| api_key: str | None = None, | ||
| api_base: str | None = None, | ||
| ) -> dict: | ||
| headers.setdefault("Content-Type", "application/json") | ||
| bearer: Final = resolve_bedrock_bearer_token(api_key) | ||
| if bearer: | ||
| headers["Authorization"] = f"Bearer {bearer}" | ||
| # The X-Amzn-Bedrock-Request-Metadata header lands in AWS billing/CloudTrail records, | ||
| # so the proxy owns it: caller-supplied copies are dropped and only the trusted pairs | ||
| # derived from litellm_params are signed, exactly as the Invoke OpenAI path does. | ||
| owned_names, metadata_headers = bedrock_request_metadata_headers(litellm_params) | ||
| return merge_bedrock_invoke_headers(headers, (), metadata_headers, owned_names) | ||
|
|
||
| def sign_request( | ||
| self, | ||
| headers: dict, | ||
| optional_params: dict, | ||
| request_data: dict, | ||
| api_base: str, | ||
| api_key: str | None = None, | ||
| model: str | None = None, | ||
| stream: bool | None = None, | ||
| fake_stream: bool | None = None, | ||
| ) -> tuple[dict, bytes | None]: | ||
| # The model rides in the body on this surface (not the URL), and extra_body is merged | ||
| # over the body before signing, so extra_body={"model": ...} would otherwise invoke a | ||
| # model the key isn't authorized for. Pin the authorized model back before signing. | ||
| if model is not None: | ||
| request_data["model"] = model # rebind-ok: request_data is the body the handler signs | ||
| if resolve_bedrock_bearer_token(api_key): | ||
| # Bedrock API keys are Bearer credentials; SigV4 on top would be wrong. | ||
| return headers, None | ||
| return self._sign_request( | ||
| service_name="bedrock", | ||
| headers=headers, | ||
| optional_params=optional_params, | ||
| request_data=request_data, | ||
| api_base=api_base, | ||
| model=model, | ||
| stream=stream, | ||
| fake_stream=fake_stream, | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.