The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
Allow using ARNs when generation images via Bedrock (#15789)
Dmitrii Komarov1dfdcb076281
diff --git a/litellm/llms/bedrock/base_aws_llm.py b/litellm/llms/bedrock/base_aws_llm.pyindex bc0466388f9..4c854437544 100644--- a/litellm/llms/bedrock/base_aws_llm.py+++ b/litellm/llms/bedrock/base_aws_llm.py@@ -1,6 +1,7 @@import hashlibimport jsonimport os+import urllib.parsefrom datetime import datetimefrom typing import (TYPE_CHECKING,@@ -331,16 +332,61 @@ class BaseAWSLLM:return providerreturn None+ @staticmethod+ def get_bedrock_model_id(+ optional_params: dict,+ provider: Optional[BEDROCK_INVOKE_PROVIDERS_LITERAL],+ model: str,+ ) -> str:+ model_id = optional_params.pop("model_id", None)+ if model_id is not None:+ model_id = BaseAWSLLM.encode_model_id(model_id=model_id)+ else:+ model_id = model++ model_id = model_id.replace("invoke/", "", 1)+ if provider == "llama" and "llama/" in model_id:+ model_id = BaseAWSLLM._get_model_id_from_model_with_spec(+ model_id, spec="llama"+ )+ elif provider == "deepseek_r1" and "deepseek_r1/" in model_id:+ model_id = BaseAWSLLM._get_model_id_from_model_with_spec(+ model_id, spec="deepseek_r1"+ )+ return model_id++ @staticmethod+ def _get_model_id_from_model_with_spec(+ model: str,+ spec: str,+ ) -> str:+ """+ Remove `llama` from modelID since `llama` is simply a spec to follow for custom bedrock models+ """+ model_id = model.replace(spec + "/", "")+ return BaseAWSLLM.encode_model_id(model_id=model_id)++ @staticmethod+ def encode_model_id(model_id: str) -> str:+ """+ Double encode the model ID to ensure it matches the expected double-encoded format.+ Args:+ model_id (str): The model ID to encode.+ Returns:+ str: The double-encoded model ID.+ """+ return urllib.parse.quote(model_id, safe="")+@staticmethoddef get_bedrock_embedding_provider(model: str,) -> Optional[BEDROCK_EMBEDDING_PROVIDERS_LITERAL]:"""Helper function to get the bedrock embedding provider from the model-+Handles scenarios like:1. model=cohere.embed-english-v3:0 -> Returns `cohere`- 2. model=amazon.titan-embed-text-v1 -> Returns `amazon`+ 2. model=amazon.titan-embed-text-v1 -> Returns `amazon`3. model=us.twelvelabs.marengo-embed-2-7-v1:0 -> Returns `twelvelabs`4. model=twelvelabs.marengo-embed-2-7-v1:0 -> Returns `twelvelabs`"""@@ -349,20 +395,24 @@ class BaseAWSLLM:parts = model.split(".")# Check if the second part (after potential region) is a known providerif len(parts) >= 2:- potential_provider = parts[1] # e.g., "twelvelabs" from "us.twelvelabs.marengo-embed-2-7-v1:0"+ potential_provider = parts[+ 1+ ] # e.g., "twelvelabs" from "us.twelvelabs.marengo-embed-2-7-v1:0"if potential_provider in get_args(BEDROCK_EMBEDDING_PROVIDERS_LITERAL):return cast(BEDROCK_EMBEDDING_PROVIDERS_LITERAL, potential_provider)-+# Check if the first part is a known provider (standard format)- potential_provider = parts[0] # e.g., "cohere" from "cohere.embed-english-v3:0"+ potential_provider = parts[+ 0+ ] # e.g., "cohere" from "cohere.embed-english-v3:0"if potential_provider in get_args(BEDROCK_EMBEDDING_PROVIDERS_LITERAL):return cast(BEDROCK_EMBEDDING_PROVIDERS_LITERAL, potential_provider)-+# Fallback: check if any provider name appears in the model stringfor provider in get_args(BEDROCK_EMBEDDING_PROVIDERS_LITERAL):if provider in model:return cast(BEDROCK_EMBEDDING_PROVIDERS_LITERAL, provider)-+return Nonedef _get_aws_region_name(@@ -984,20 +1034,23 @@ class BaseAWSLLM:raise ImportError("Missing boto3 to call bedrock. Run 'pip install boto3'.")-+# Filter headers for AWS signature calculation# AWS SigV4 only includes specific headers in signature calculationaws_signature_headers = self._filter_headers_for_aws_signature(headers)sigv4 = SigV4Auth(credentials, "bedrock", aws_region_name)request = AWSRequest(- method="POST", url=endpoint_url, data=data, headers=aws_signature_headers+ method="POST",+ url=endpoint_url,+ data=data,+ headers=aws_signature_headers,)sigv4.add_auth(request)-+# Add back all original headers (including forwarded ones) after signature calculationfor header_name, header_value in headers.items():request.headers[header_name] = header_value-+if (extra_headers is not None and "Authorization" in extra_headers): # prevent sigv4 from overwriting the auth header@@ -1013,16 +1066,27 @@ class BaseAWSLLM:"""aws_signature_headers = {}aws_headers = {- 'host', 'content-type', 'date', 'x-amz-date', 'x-amz-security-token',- 'x-amz-content-sha256', 'x-amz-algorithm', 'x-amz-credential',- 'x-amz-signedheaders', 'x-amz-signature'+ "host",+ "content-type",+ "date",+ "x-amz-date",+ "x-amz-security-token",+ "x-amz-content-sha256",+ "x-amz-algorithm",+ "x-amz-credential",+ "x-amz-signedheaders",+ "x-amz-signature",}-+for header_name, header_value in headers.items():header_lower = header_name.lower()- if header_lower in aws_headers or header_lower.startswith('x-amz-') or header_lower.startswith('x-amzn-'):+ if (+ header_lower in aws_headers+ or header_lower.startswith("x-amz-")+ or header_lower.startswith("x-amzn-")+ ):aws_signature_headers[header_name] = header_value-+return aws_signature_headersdef _sign_request(diff --git a/litellm/llms/bedrock/chat/converse_handler.py b/litellm/llms/bedrock/chat/converse_handler.pyindex 54c603e5960..fd1f6f0c893 100644--- a/litellm/llms/bedrock/chat/converse_handler.py+++ b/litellm/llms/bedrock/chat/converse_handler.py@@ -1,5 +1,4 @@import json-import urllibfrom typing import Any, Optional, Unionimport httpx@@ -84,16 +83,6 @@ class BedrockConverseLLM(BaseAWSLLM):def __init__(self) -> None:super().__init__()- def encode_model_id(self, model_id: str) -> str:- """- Double encode the model ID to ensure it matches the expected double-encoded format.- Args:- model_id (str): The model ID to encode.- Returns:- str: The double-encoded model ID.- """- return urllib.parse.quote(model_id, safe="") # type: ignore-async def async_streaming(self,model: str,diff --git a/litellm/llms/bedrock/chat/invoke_handler.py b/litellm/llms/bedrock/chat/invoke_handler.pyindex 71aadffe5bb..53cbafcbe6a 100644--- a/litellm/llms/bedrock/chat/invoke_handler.py+++ b/litellm/llms/bedrock/chat/invoke_handler.py@@ -3,20 +3,15 @@ TODO: DELETE FILE. Bedrock LLM is no longer used. Goto `litellm/llms/bedrock/cha"""import copy-import jsonimport timeimport types-import urllib.parsefrom functools import partialfrom typing import (- Any,AsyncIterator,Callable,Iterator,- List,Optional,Tuple,- Union,cast,get_args,)@@ -672,16 +667,6 @@ class BedrockLLM(BaseAWSLLM):return model_response- def encode_model_id(self, model_id: str) -> str:- """- Double encode the model ID to ensure it matches the expected double-encoded format.- Args:- model_id (str): The model ID to encode.- Returns:- str: The double-encoded model ID.- """- return urllib.parse.quote(model_id, safe="")-def completion( # noqa: PLR0915self,model: str,@@ -1176,33 +1161,6 @@ class BedrockLLM(BaseAWSLLM):return cast(litellm.BEDROCK_INVOKE_PROVIDERS_LITERAL, provider)return None- def get_bedrock_model_id(- self,- optional_params: dict,- provider: Optional[litellm.BEDROCK_INVOKE_PROVIDERS_LITERAL],- model: str,- ) -> str:- modelId = optional_params.pop("model_id", None)- if modelId is not None:- modelId = self.encode_model_id(model_id=modelId)- else:- modelId = model-- if provider == "llama" and "llama/" in modelId:- modelId = self._get_model_id_for_llama_like_model(modelId)-- return modelId-- def _get_model_id_for_llama_like_model(- self,- model: str,- ) -> str:- """- Remove `llama` from modelID since `llama` is simply a spec to follow for custom bedrock models- """- model_id = model.replace("llama/", "")- return self.encode_model_id(model_id=model_id)-def get_response_stream_shape():global _response_stream_shape_cachediff --git a/litellm/llms/bedrock/chat/invoke_transformations/base_invoke_transformation.py b/litellm/llms/bedrock/chat/invoke_transformations/base_invoke_transformation.pyindex 08a0690716b..e6146f1064e 100644--- a/litellm/llms/bedrock/chat/invoke_transformations/base_invoke_transformation.py+++ b/litellm/llms/bedrock/chat/invoke_transformations/base_invoke_transformation.py@@ -1,7 +1,6 @@import copyimport jsonimport time-import urllib.parsefrom functools import partialfrom typing import TYPE_CHECKING, Any, List, Optional, Tuple, Union, cast, get_args@@ -190,14 +189,16 @@ class AmazonInvokeConfig(BaseConfig, BaseAWSLLM):] = True # cohere requires stream = True in inference paramsrequest_data = {"prompt": prompt, **inference_params}elif provider == "anthropic":- transformed_request = litellm.AmazonAnthropicClaudeConfig().transform_request(- model=model,- messages=messages,- optional_params=optional_params,- litellm_params=litellm_params,- headers=headers,+ transformed_request = (+ litellm.AmazonAnthropicClaudeConfig().transform_request(+ model=model,+ messages=messages,+ optional_params=optional_params,+ litellm_params=litellm_params,+ headers=headers,+ ))-+return transformed_requestelif provider == "nova":return litellm.AmazonInvokeNovaConfig().transform_request(@@ -327,7 +328,9 @@ class AmazonInvokeConfig(BaseConfig, BaseAWSLLM):elif provider == "meta" or provider == "llama" or provider == "deepseek_r1":outputText = completion_response["generation"]elif provider == "mistral":- outputText = litellm.AmazonMistralConfig.get_outputText(completion_response, model_response)+ outputText = litellm.AmazonMistralConfig.get_outputText(+ completion_response, model_response+ )else: # amazon titanoutputText = completion_response.get("results")[0].get("outputText")except Exception as e:@@ -549,48 +552,6 @@ class AmazonInvokeConfig(BaseConfig, BaseAWSLLM):return cast(litellm.BEDROCK_INVOKE_PROVIDERS_LITERAL, provider)return None- def get_bedrock_model_id(- self,- optional_params: dict,- provider: Optional[litellm.BEDROCK_INVOKE_PROVIDERS_LITERAL],- model: str,- ) -> str:- modelId = optional_params.pop("model_id", None)- if modelId is not None:- modelId = self.encode_model_id(model_id=modelId)- else:- modelId = model-- modelId = modelId.replace("invoke/", "", 1)- if provider == "llama" and "llama/" in modelId:- modelId = self._get_model_id_from_model_with_spec(modelId, spec="llama")- elif provider == "deepseek_r1" and "deepseek_r1/" in modelId:- modelId = self._get_model_id_from_model_with_spec(- modelId, spec="deepseek_r1"- )- return modelId-- def _get_model_id_from_model_with_spec(- self,- model: str,- spec: str,- ) -> str:- """- Remove `llama` from modelID since `llama` is simply a spec to follow for custom bedrock models- """- model_id = model.replace(spec + "/", "")- return self.encode_model_id(model_id=model_id)-- def encode_model_id(self, model_id: str) -> str:- """- Double encode the model ID to ensure it matches the expected double-encoded format.- Args:- model_id (str): The model ID to encode.- Returns:- str: The double-encoded model ID.- """- return urllib.parse.quote(model_id, safe="")-def convert_messages_to_prompt(self, model, messages, provider, custom_prompt_dict) -> Tuple[str, Optional[list]]:diff --git a/litellm/llms/bedrock/image/image_handler.py b/litellm/llms/bedrock/image/image_handler.pyindex 1c418f78296..313a1dc17bd 100644--- a/litellm/llms/bedrock/image/image_handler.py+++ b/litellm/llms/bedrock/image/image_handler.py@@ -7,6 +7,7 @@ import httpxfrom pydantic import BaseModelimport litellm+from litellm import BEDROCK_INVOKE_PROVIDERS_LITERALfrom litellm._logging import verbose_loggerfrom litellm.litellm_core_utils.litellm_logging import Logging as LitellmLoggingfrom litellm.llms.bedrock.image.amazon_nova_canvas_transformation import (@@ -183,8 +184,14 @@ class BedrockImageGeneration(BaseAWSLLM):optional_params, model)+ # Use the existing ARN-aware provider detection method+ bedrock_provider = self.get_bedrock_invoke_provider(model)### SET RUNTIME ENDPOINT ###- modelId = model+ modelId = self.get_bedrock_model_id(+ model=model,+ provider=bedrock_provider,+ optional_params=optional_params,+ )_, proxy_endpoint_url = self.get_runtime_endpoint(api_base=api_base,aws_bedrock_runtime_endpoint=boto3_credentials_info.aws_bedrock_runtime_endpoint,@@ -192,7 +199,10 @@ class BedrockImageGeneration(BaseAWSLLM):)proxy_endpoint_url = f"{proxy_endpoint_url}/model/{modelId}/invoke"data = self._get_request_body(- model=model, prompt=prompt, optional_params=optional_params+ model=model,+ prompt=prompt,+ optional_params=optional_params,+ bedrock_provider=bedrock_provider,)# Make POST Request@@ -231,6 +241,7 @@ class BedrockImageGeneration(BaseAWSLLM):def _get_request_body(self,model: str,+ bedrock_provider: Optional[BEDROCK_INVOKE_PROVIDERS_LITERAL],prompt: str,optional_params: dict,) -> dict:@@ -242,9 +253,6 @@ class BedrockImageGeneration(BaseAWSLLM):Returns:dict: The request body to use for the Bedrock Image Generation API"""- # Use the existing ARN-aware provider detection method- bedrock_provider = self.get_bedrock_invoke_provider(model)-if bedrock_provider == "amazon" or bedrock_provider == "nova":# Handle Amazon Nova Canvas modelsprovider = "amazon"diff --git a/tests/test_litellm/llms/bedrock/image/test_bedrock_image_prepare_request.py b/tests/test_litellm/llms/bedrock/image/test_bedrock_image_prepare_request.pynew file mode 100644index 00000000000..22dc0cc8a48--- /dev/null+++ b/tests/test_litellm/llms/bedrock/image/test_bedrock_image_prepare_request.py@@ -0,0 +1,46 @@+from unittest.mock import patch, MagicMock++from litellm.llms.bedrock.image.image_handler import BedrockImageGeneration++def test_bedrock_image_prepare_request_with_arn() -> None:+ dummy_arn = "arn:aws:bedrock:us-east-1:123456789012:application-inference-profile/abcdefghi123"++ image_generation = BedrockImageGeneration()++ with (+ patch("litellm.llms.bedrock.image.image_handler.BedrockImageGeneration._get_boto_credentials_from_optional_params"),+ patch("litellm.llms.bedrock.image.image_handler.BedrockImageGeneration.get_request_headers"),+ ):+ request = image_generation._prepare_request(+ model="amazon.nova-canvas-v1:0",+ prompt="A cute baby sea otter",+ optional_params={+ "model_id": dummy_arn,+ },+ api_base="https://bedrock-runtime.test.com",+ extra_headers=None,+ api_key=None,+ logging_obj=MagicMock(),+ )++ assert request.endpoint_url == "https://bedrock-runtime.test.com/model/arn%3Aaws%3Abedrock%3Aus-east-1%3A123456789012%3Aapplication-inference-profile%2Fabcdefghi123/invoke"+++def test_bedrock_image_prepare_request_without_arn() -> None:+ image_generation = BedrockImageGeneration()++ with (+ patch("litellm.llms.bedrock.image.image_handler.BedrockImageGeneration._get_boto_credentials_from_optional_params"),+ patch("litellm.llms.bedrock.image.image_handler.BedrockImageGeneration.get_request_headers"),+ ):+ request = image_generation._prepare_request(+ model="amazon.nova-canvas-v1:0",+ prompt="A cute baby sea otter",+ optional_params={},+ api_base="https://bedrock-runtime.test.com",+ extra_headers=None,+ api_key=None,+ logging_obj=MagicMock(),+ )++ assert request.endpoint_url == "https://bedrock-runtime.test.com/model/amazon.nova-canvas-v1:0/invoke"