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
[Feat]: Add Bedrock InvokeAgents as a /chat/completions route on LiteLLM (#11239)
Ishaan Jaff5e6f6ddc520f
diff --git a/docs/my-website/docs/providers/bedrock_agents.md b/docs/my-website/docs/providers/bedrock_agents.mdnew file mode 100644index 00000000000..e6368705feb--- /dev/null+++ b/docs/my-website/docs/providers/bedrock_agents.md@@ -0,0 +1,202 @@+import Tabs from '@theme/Tabs';+import TabItem from '@theme/TabItem';++# Bedrock Agents++Call Bedrock Agents in the OpenAI Request/Response format.+++| Property | Details |+|----------|---------|+| Description | Amazon Bedrock Agents use the reasoning of foundation models (FMs), APIs, and data to break down user requests, gather relevant information, and efficiently complete tasks. |+| Provider Route on LiteLLM | `bedrock/agent/{AGENT_ID}/{ALIAS_ID}` |+| Provider Doc | [AWS Bedrock Agents ↗](https://aws.amazon.com/bedrock/agents/) |++## Quick Start++### Model Format to LiteLLM++To call a bedrock agent through LiteLLM, you need to use the following model format to call the agent.++Here the `model=bedrock/agent/` tells LiteLLM to call the bedrock `InvokeAgent` API.++```shell showLineNumbers title="Model Format to LiteLLM"+bedrock/agent/{AGENT_ID}/{ALIAS_ID}+```++**Example:**+- `bedrock/agent/L1RT58GYRW/MFPSBCXYTW`+- `bedrock/agent/ABCD1234/LIVE`++You can find these IDs in your AWS Bedrock console under Agents.+++### LiteLLM Python SDK++```python showLineNumbers title="Basic Agent Completion"+import litellm++# Make a completion request to your Bedrock Agent+response = litellm.completion(+ model="bedrock/agent/L1RT58GYRW/MFPSBCXYTW", # agent/{AGENT_ID}/{ALIAS_ID}+ messages=[+ {+ "role": "user",+ "content": "Hi, I need help with analyzing our Q3 sales data and generating a summary report"+ }+ ],+)++print(response.choices[0].message.content)+print(f"Response cost: ${response._hidden_params['response_cost']}")+```++```python showLineNumbers title="Streaming Agent Responses"+import litellm++# Stream responses from your Bedrock Agent+response = litellm.completion(+ model="bedrock/agent/L1RT58GYRW/MFPSBCXYTW",+ messages=[+ {+ "role": "user",+ "content": "Can you help me plan a marketing campaign and provide step-by-step execution details?"+ }+ ],+ stream=True,+)++for chunk in response:+ if chunk.choices[0].delta.content:+ print(chunk.choices[0].delta.content, end="")+```+++### LiteLLM Proxy++#### 1. Configure your model in config.yaml++<Tabs>+<TabItem value="config-yaml" label="config.yaml">++```yaml showLineNumbers title="LiteLLM Proxy Configuration"+model_list:+ - model_name: bedrock-agent-1+ litellm_params:+ model: bedrock/agent/L1RT58GYRW/MFPSBCXYTW+ aws_access_key_id: os.environ/AWS_ACCESS_KEY_ID+ aws_secret_access_key: os.environ/AWS_SECRET_ACCESS_KEY+ aws_region_name: us-west-2++ - model_name: bedrock-agent-2+ litellm_params:+ model: bedrock/agent/AGENT456/ALIAS789+ aws_access_key_id: os.environ/AWS_ACCESS_KEY_ID+ aws_secret_access_key: os.environ/AWS_SECRET_ACCESS_KEY+ aws_region_name: us-east-1+```++</TabItem>+</Tabs>++#### 2. Start the LiteLLM Proxy++```bash showLineNumbers title="Start LiteLLM Proxy"+litellm --config config.yaml+```++#### 3. Make requests to your Bedrock Agents++<Tabs>+<TabItem value="curl" label="Curl">++```bash showLineNumbers title="Basic Agent Request"+curl http://localhost:4000/v1/chat/completions \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer $LITELLM_API_KEY" \+ -d '{+ "model": "bedrock-agent-1",+ "messages": [+ {+ "role": "user",+ "content": "Analyze our customer data and suggest retention strategies"+ }+ ]+ }'+```++```bash showLineNumbers title="Streaming Agent Request"+curl http://localhost:4000/v1/chat/completions \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer $LITELLM_API_KEY" \+ -d '{+ "model": "bedrock-agent-2",+ "messages": [+ {+ "role": "user",+ "content": "Create a comprehensive social media strategy for our new product"+ }+ ],+ "stream": true+ }'+```++</TabItem>++<TabItem value="openai-sdk" label="OpenAI Python SDK">++```python showLineNumbers title="Using OpenAI SDK with LiteLLM Proxy"+from openai import OpenAI++# Initialize client with your LiteLLM proxy URL+client = OpenAI(+ base_url="http://localhost:4000",+ api_key="your-litellm-api-key"+)++# Make a completion request to your agent+response = client.chat.completions.create(+ model="bedrock-agent-1",+ messages=[+ {+ "role": "user",+ "content": "Help me prepare for the quarterly business review meeting"+ }+ ]+)++print(response.choices[0].message.content)+```++```python showLineNumbers title="Streaming with OpenAI SDK"+from openai import OpenAI++client = OpenAI(+ base_url="http://localhost:4000",+ api_key="your-litellm-api-key"+)++# Stream agent responses+stream = client.chat.completions.create(+ model="bedrock-agent-2",+ messages=[+ {+ "role": "user",+ "content": "Walk me through launching a new feature beta program"+ }+ ],+ stream=True+)++for chunk in stream:+ if chunk.choices[0].delta.content is not None:+ print(chunk.choices[0].delta.content, end="")+```++</TabItem>+</Tabs>++## Further Reading++- [AWS Bedrock Agents Documentation](https://aws.amazon.com/bedrock/agents/)+- [LiteLLM Authentication to Bedrock](https://docs.litellm.ai/docs/providers/bedrock#boto3---authentication)diff --git a/docs/my-website/sidebars.js b/docs/my-website/sidebars.jsindex 60073bc1e25..8383503e872 100644--- a/docs/my-website/sidebars.js+++ b/docs/my-website/sidebars.js@@ -328,6 +328,7 @@ const sidebars = {label: "Bedrock",items: ["providers/bedrock",+ "providers/bedrock_agents","providers/bedrock_vector_store",]},diff --git a/litellm/llms/bedrock/base_aws_llm.py b/litellm/llms/bedrock/base_aws_llm.pyindex a2832e69eb5..fea2072a0f7 100644--- a/litellm/llms/bedrock/base_aws_llm.py+++ b/litellm/llms/bedrock/base_aws_llm.py@@ -527,6 +527,7 @@ class BaseAWSLLM:api_base: Optional[str],aws_bedrock_runtime_endpoint: Optional[str],aws_region_name: str,+ endpoint_type: Optional[Literal["runtime", "agent"]] = "runtime",) -> Tuple[str, str]:env_aws_bedrock_runtime_endpoint = get_secret("AWS_BEDROCK_RUNTIME_ENDPOINT")if api_base is not None:@@ -540,7 +541,10 @@ class BaseAWSLLM:):endpoint_url = env_aws_bedrock_runtime_endpointelse:- endpoint_url = f"https://bedrock-runtime.{aws_region_name}.amazonaws.com"+ endpoint_url = self._select_default_endpoint_url(+ endpoint_type=endpoint_type,+ aws_region_name=aws_region_name,+ )# Determine proxy_endpoint_urlif env_aws_bedrock_runtime_endpoint and isinstance(@@ -556,6 +560,19 @@ class BaseAWSLLM:return endpoint_url, proxy_endpoint_url+ def _select_default_endpoint_url(+ self, endpoint_type: Optional[Literal["runtime", "agent"]], aws_region_name: str+ ) -> str:+ """+ Select the default endpoint url based on the endpoint type++ Default endpoint url is https://bedrock-runtime.{aws_region_name}.amazonaws.com+ """+ if endpoint_type == "agent":+ return f"https://bedrock-agent-runtime.{aws_region_name}.amazonaws.com"+ else:+ return f"https://bedrock-runtime.{aws_region_name}.amazonaws.com"+def _get_boto_credentials_from_optional_params(self, optional_params: dict, model: Optional[str] = None) -> Boto3CredentialsInfo:diff --git a/litellm/llms/bedrock/chat/invoke_agent/transformation.py b/litellm/llms/bedrock/chat/invoke_agent/transformation.pynew file mode 100644index 00000000000..aa57bb7feb3--- /dev/null+++ b/litellm/llms/bedrock/chat/invoke_agent/transformation.py@@ -0,0 +1,527 @@+"""+Transformation for Bedrock Invoke Agent++https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html+"""+import base64+import json+import uuid+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union++import httpx++from litellm._logging import verbose_logger+from litellm.litellm_core_utils.prompt_templates.common_utils import (+ convert_content_list_to_str,+)+from litellm.llms.base_llm.chat.transformation import BaseConfig, BaseLLMException+from litellm.llms.bedrock.base_aws_llm import BaseAWSLLM+from litellm.llms.bedrock.common_utils import BedrockError+from litellm.types.llms.bedrock_invoke_agents import (+ InvokeAgentChunkPayload,+ InvokeAgentEvent,+ InvokeAgentEventHeaders,+ InvokeAgentEventList,+ InvokeAgentTrace,+ InvokeAgentTracePayload,+ InvokeAgentUsage,+)+from litellm.types.llms.openai import AllMessageValues+from litellm.types.utils import Choices, Message, ModelResponse++if TYPE_CHECKING:+ from litellm.litellm_core_utils.litellm_logging import Logging as _LiteLLMLoggingObj++ LiteLLMLoggingObj = _LiteLLMLoggingObj+else:+ LiteLLMLoggingObj = Any+++class AmazonInvokeAgentConfig(BaseConfig, BaseAWSLLM):+ def __init__(self, **kwargs):+ BaseConfig.__init__(self, **kwargs)+ BaseAWSLLM.__init__(self, **kwargs)++ def get_supported_openai_params(self, model: str) -> List[str]:+ """+ This is a base invoke agent model mapping. For Invoke Agent - define a bedrock provider specific config that extends this class.++ Bedrock Invoke Agents has 0 OpenAI compatible params++ As of May 29th, 2025 - they don't support streaming.+ """+ return []++ def map_openai_params(+ self,+ non_default_params: dict,+ optional_params: dict,+ model: str,+ drop_params: bool,+ ) -> dict:+ """+ This is a base invoke agent model mapping. For Invoke Agent - define a bedrock provider specific config that extends this class.+ """+ return optional_params++ def get_complete_url(+ self,+ api_base: Optional[str],+ api_key: Optional[str],+ model: str,+ optional_params: dict,+ litellm_params: dict,+ stream: Optional[bool] = None,+ ) -> str:+ """+ Get the complete url for the request+ """+ ### SET RUNTIME ENDPOINT ###+ aws_bedrock_runtime_endpoint = optional_params.get(+ "aws_bedrock_runtime_endpoint", None+ ) # https://bedrock-runtime.{region_name}.amazonaws.com+ endpoint_url, _ = self.get_runtime_endpoint(+ api_base=api_base,+ aws_bedrock_runtime_endpoint=aws_bedrock_runtime_endpoint,+ aws_region_name=self._get_aws_region_name(+ optional_params=optional_params, model=model+ ),+ endpoint_type="agent",+ )++ agent_id, agent_alias_id = self._get_agent_id_and_alias_id(model)+ session_id = self._get_session_id(optional_params)++ endpoint_url = f"{endpoint_url}/agents/{agent_id}/agentAliases/{agent_alias_id}/sessions/{session_id}/text"++ return endpoint_url++ def sign_request(+ self,+ headers: dict,+ optional_params: dict,+ request_data: dict,+ api_base: str,+ model: Optional[str] = None,+ stream: Optional[bool] = None,+ fake_stream: Optional[bool] = None,+ ) -> Tuple[dict, Optional[bytes]]:+ 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,+ )++ def _get_agent_id_and_alias_id(self, model: str) -> tuple[str, str]:+ """+ model = "agent/L1RT58GYRW/MFPSBCXYTW"+ agent_id = "L1RT58GYRW"+ agent_alias_id = "MFPSBCXYTW"+ """+ # Split the model string by '/' and extract components+ parts = model.split("/")+ if len(parts) != 3 or parts[0] != "agent":+ raise ValueError(+ "Invalid model format. Expected format: 'model=agent/AGENT_ID/ALIAS_ID'"+ )++ return parts[1], parts[2] # Return (agent_id, agent_alias_id)++ def _get_session_id(self, optional_params: dict) -> str:+ """ """+ return optional_params.get("sessionID", None) or str(uuid.uuid4())++ def transform_request(+ self,+ model: str,+ messages: List[AllMessageValues],+ optional_params: dict,+ litellm_params: dict,+ headers: dict,+ ) -> dict:+ # use the last message content as the query+ query: str = convert_content_list_to_str(messages[-1])+ return {+ "inputText": query,+ "enableTrace": True,+ **optional_params,+ }++ def _parse_aws_event_stream(self, raw_content: bytes) -> InvokeAgentEventList:+ """+ Parse AWS event stream format using boto3/botocore's built-in parser.+ This is the same approach used in the existing AWSEventStreamDecoder.+ """+ try:+ from botocore.eventstream import EventStreamBuffer+ from botocore.parsers import EventStreamJSONParser+ except ImportError:+ raise ImportError("boto3/botocore is required for AWS event stream parsing")++ events: InvokeAgentEventList = []+ parser = EventStreamJSONParser()+ event_stream_buffer = EventStreamBuffer()++ # Add the entire response to the buffer+ event_stream_buffer.add_data(raw_content)++ # Process all events in the buffer+ for event in event_stream_buffer:+ try:+ headers = self._extract_headers_from_event(event)++ event_type = headers.get("event_type", "")++ if event_type == "chunk":+ # Handle chunk events specially - they contain decoded content, not JSON+ message = self._parse_message_from_event(event, parser)+ parsed_event: InvokeAgentEvent = InvokeAgentEvent()+ if message:+ # For chunk events, create a payload with the decoded content+ parsed_event = {+ "headers": headers,+ "payload": {+ "bytes": base64.b64encode(+ message.encode("utf-8")+ ).decode("utf-8")+ }, # Re-encode for consistency+ }+ events.append(parsed_event)++ elif event_type == "trace":+ # Handle trace events normally - they contain JSON+ message = self._parse_message_from_event(event, parser)++ if message:+ try:+ event_data = json.loads(message)+ parsed_event = {+ "headers": headers,+ "payload": event_data,+ }+ events.append(parsed_event)+ except json.JSONDecodeError as e:+ verbose_logger.warning(+ f"Failed to parse trace event JSON: {e}"+ )+ else:+ verbose_logger.debug(f"Unknown event type: {event_type}")++ except Exception as e:+ verbose_logger.error(f"Error processing event: {e}")+ continue++ return events++ def _parse_message_from_event(self, event, parser) -> Optional[str]:+ """Extract message content from an AWS event, adapted from AWSEventStreamDecoder."""+ try:+ response_dict = event.to_response_dict()+ verbose_logger.debug(f"Response dict: {response_dict}")++ # Use the same response shape parsing as the existing decoder+ parsed_response = parser.parse(+ response_dict, self._get_response_stream_shape()+ )+ verbose_logger.debug(f"Parsed response: {parsed_response}")++ if response_dict["status_code"] != 200:+ decoded_body = response_dict["body"].decode()+ if isinstance(decoded_body, dict):+ error_message = decoded_body.get("message")+ elif isinstance(decoded_body, str):+ error_message = decoded_body+ else:+ error_message = ""+ exception_status = response_dict["headers"].get(":exception-type")+ error_message = exception_status + " " + error_message+ raise BedrockError(+ status_code=response_dict["status_code"],+ message=(+ json.dumps(error_message)+ if isinstance(error_message, dict)+ else error_message+ ),+ )++ if "chunk" in parsed_response:+ chunk = parsed_response.get("chunk")+ if not chunk:+ return None+ return chunk.get("bytes").decode()+ else:+ chunk = response_dict.get("body")+ if not chunk:+ return None+ return chunk.decode()++ except Exception as e:+ verbose_logger.debug(f"Error parsing message from event: {e}")+ return None++ def _extract_headers_from_event(self, event) -> InvokeAgentEventHeaders:+ """Extract headers from an AWS event for categorization."""+ try:+ response_dict = event.to_response_dict()+ headers = response_dict.get("headers", {})++ # Extract the event-type and content-type headers that we care about+ return InvokeAgentEventHeaders(+ event_type=headers.get(":event-type", ""),+ content_type=headers.get(":content-type", ""),+ message_type=headers.get(":message-type", ""),+ )+ except Exception as e:+ verbose_logger.debug(f"Error extracting headers: {e}")+ return InvokeAgentEventHeaders(+ event_type="", content_type="", message_type=""+ )++ def _get_response_stream_shape(self):+ """Get the response stream shape for parsing, reusing existing logic."""+ try:+ # Try to reuse the cached shape from the existing decoder+ from litellm.llms.bedrock.chat.invoke_handler import (+ get_response_stream_shape,+ )++ return get_response_stream_shape()+ except ImportError:+ # Fallback: create our own shape+ try:+ from botocore.loaders import Loader+ from botocore.model import ServiceModel++ loader = Loader()+ bedrock_service_dict = loader.load_service_model(+ "bedrock-runtime", "service-2"+ )+ bedrock_service_model = ServiceModel(bedrock_service_dict)+ return bedrock_service_model.shape_for("ResponseStream")+ except Exception as e:+ verbose_logger.warning(f"Could not load response stream shape: {e}")+ return None++ def _extract_response_content(self, events: InvokeAgentEventList) -> str:+ """Extract the final response content from parsed events."""+ response_parts = []++ for event in events:+ headers = event.get("headers", {})+ payload = event.get("payload")++ event_type = headers.get(+ "event_type"+ ) # Note: using event_type not event-type++ if event_type == "chunk" and payload:+ # Extract base64 encoded content from chunk events+ chunk_payload: InvokeAgentChunkPayload = payload # type: ignore+ encoded_bytes = chunk_payload.get("bytes", "")+ if encoded_bytes:+ try:+ decoded_content = base64.b64decode(encoded_bytes).decode(+ "utf-8"+ )+ response_parts.append(decoded_content)+ except Exception as e:+ verbose_logger.warning(f"Failed to decode chunk content: {e}")++ return "".join(response_parts)++ def _extract_usage_info(self, events: InvokeAgentEventList) -> InvokeAgentUsage:+ """Extract token usage information from trace events."""+ usage_info = InvokeAgentUsage(+ inputTokens=0,+ outputTokens=0,+ model=None,+ )++ response_model: Optional[str] = None++ for event in events:+ if not self._is_trace_event(event):+ continue++ trace_data = self._get_trace_data(event)+ if not trace_data:+ continue++ verbose_logger.debug(f"Trace event: {trace_data}")++ # Extract usage from pre-processing trace+ self._extract_and_update_preprocessing_usage(+ trace_data=trace_data,+ usage_info=usage_info,+ )++ # Extract model from orchestration trace+ if response_model is None:+ response_model = self._extract_orchestration_model(trace_data)++ usage_info["model"] = response_model+ return usage_info++ def _is_trace_event(self, event: InvokeAgentEvent) -> bool:+ """Check if the event is a trace event."""+ headers = event.get("headers", {})+ event_type = headers.get("event_type")+ payload = event.get("payload")+ return event_type == "trace" and payload is not None++ def _get_trace_data(self, event: InvokeAgentEvent) -> Optional[InvokeAgentTrace]:+ """Extract trace data from a trace event."""+ payload = event.get("payload")+ if not payload:+ return None++ trace_payload: InvokeAgentTracePayload = payload # type: ignore+ return trace_payload.get("trace", {})++ def _extract_and_update_preprocessing_usage(+ self, trace_data: InvokeAgentTrace, usage_info: InvokeAgentUsage+ ) -> None:+ """Extract usage information from preprocessing trace."""+ pre_processing = trace_data.get("preProcessingTrace", {})+ if not pre_processing:+ return++ model_output = pre_processing.get("modelInvocationOutput", {})+ if not model_output:+ return++ metadata = model_output.get("metadata", {})+ if not metadata:+ return++ usage: Optional[Union[InvokeAgentUsage, Dict]] = metadata.get("usage", {})+ if not usage:+ return++ usage_info["inputTokens"] += usage.get("inputTokens", 0)+ usage_info["outputTokens"] += usage.get("outputTokens", 0)++ def _extract_orchestration_model(+ self, trace_data: InvokeAgentTrace+ ) -> Optional[str]:+ """Extract model information from orchestration trace."""+ orchestration_trace = trace_data.get("orchestrationTrace", {})+ if not orchestration_trace:+ return None++ model_invocation = orchestration_trace.get("modelInvocationInput", {})+ if not model_invocation:+ return None++ return model_invocation.get("foundationModel")++ def _build_model_response(+ self,+ content: str,+ model: str,+ usage_info: InvokeAgentUsage,+ model_response: ModelResponse,+ ) -> ModelResponse:+ """Build the final ModelResponse object."""++ # Create the message content+ message = Message(content=content, role="assistant")++ # Create choices+ choice = Choices(finish_reason="stop", index=0, message=message)++ # Update model response+ model_response.choices = [choice]+ model_response.model = usage_info.get("model", model)++ # Add usage information if available+ if usage_info:+ from litellm.types.utils import Usage++ usage = Usage(+ prompt_tokens=usage_info.get("inputTokens", 0),+ completion_tokens=usage_info.get("outputTokens", 0),+ total_tokens=usage_info.get("inputTokens", 0)+ + usage_info.get("outputTokens", 0),+ )+ setattr(model_response, "usage", usage)++ return model_response++ def transform_response(+ self,+ model: str,+ raw_response: httpx.Response,+ model_response: ModelResponse,+ logging_obj: LiteLLMLoggingObj,+ request_data: dict,+ messages: List[AllMessageValues],+ optional_params: dict,+ litellm_params: dict,+ encoding: Any,+ api_key: Optional[str] = None,+ json_mode: Optional[bool] = None,+ ) -> ModelResponse:+ try:+ # Get the raw binary content+ raw_content = raw_response.content+ verbose_logger.debug(+ f"Processing {len(raw_content)} bytes of AWS event stream data"+ )++ # Parse the AWS event stream format+ events = self._parse_aws_event_stream(raw_content)+ verbose_logger.debug(f"Parsed {len(events)} events from stream")++ # Extract response content from chunk events+ content = self._extract_response_content(events)++ # Extract usage information from trace events+ usage_info = self._extract_usage_info(events)++ # Build and return the model response+ return self._build_model_response(+ content=content,+ model=model,+ usage_info=usage_info,+ model_response=model_response,+ )++ except Exception as e:+ verbose_logger.error(+ f"Error processing Bedrock Invoke Agent response: {str(e)}"+ )+ raise BedrockError(+ message=f"Error processing response: {str(e)}",+ status_code=raw_response.status_code,+ )++ def validate_environment(+ self,+ headers: dict,+ model: str,+ messages: List[AllMessageValues],+ optional_params: dict,+ litellm_params: dict,+ api_key: Optional[str] = None,+ api_base: Optional[str] = None,+ ) -> dict:+ return headers++ def get_error_class(+ self, error_message: str, status_code: int, headers: Union[dict, httpx.Headers]+ ) -> BaseLLMException:+ return BedrockError(status_code=status_code, message=error_message)++ def should_fake_stream(+ self,+ model: Optional[str],+ stream: Optional[bool],+ custom_llm_provider: Optional[str] = None,+ ) -> bool:+ return Truediff --git a/litellm/llms/bedrock/common_utils.py b/litellm/llms/bedrock/common_utils.pyindex 69a249b8424..fc6f52233e1 100644--- a/litellm/llms/bedrock/common_utils.py+++ b/litellm/llms/bedrock/common_utils.py@@ -402,7 +402,9 @@ class BedrockModelInfo(BaseLLMModelInfo):return ["us", "eu", "apac"]@staticmethod- def get_bedrock_route(model: str) -> Literal["converse", "invoke", "converse_like"]:+ def get_bedrock_route(+ model: str,+ ) -> Literal["converse", "invoke", "converse_like", "agent"]:"""Get the bedrock route for the given model."""@@ -414,6 +416,8 @@ class BedrockModelInfo(BaseLLMModelInfo):return "converse_like"elif "converse/" in model:return "converse"+ elif "agent/" in model:+ return "agent"elif (base_model in litellm.bedrock_converse_modelsor alt_model in litellm.bedrock_converse_modelsdiff --git a/litellm/llms/custom_httpx/llm_http_handler.py b/litellm/llms/custom_httpx/llm_http_handler.pyindex 6dfc68f724e..6523184c08c 100644--- a/litellm/llms/custom_httpx/llm_http_handler.py+++ b/litellm/llms/custom_httpx/llm_http_handler.py@@ -271,7 +271,6 @@ class BaseLLMHTTPHandler:):json_mode: bool = optional_params.pop("json_mode", False)extra_body: Optional[dict] = optional_params.pop("extra_body", None)- fake_stream = fake_stream or optional_params.pop("fake_stream", False)provider_config = (provider_config@@ -284,6 +283,14 @@ class BaseLLMHTTPHandler:f"Provider config not found for model: {model} and provider: {custom_llm_provider}")+ fake_stream = (+ fake_stream+ or optional_params.pop("fake_stream", False)+ or provider_config.should_fake_stream(+ model=model, custom_llm_provider=custom_llm_provider, stream=stream+ )+ )+# get config from model, custom llm providerheaders = provider_config.validate_environment(api_key=api_key,diff --git a/litellm/types/llms/bedrock_invoke_agents.py b/litellm/types/llms/bedrock_invoke_agents.pynew file mode 100644index 00000000000..dde9405a720--- /dev/null+++ b/litellm/types/llms/bedrock_invoke_agents.py@@ -0,0 +1,127 @@+"""+Type definitions for AWS Bedrock Invoke Agent API responses.++https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html+"""++from typing import Any, Dict, List, Optional, TypedDict, Union+++class InvokeAgentEventHeaders(TypedDict, total=False):+ """Headers for AWS Invoke Agent events."""++ event_type: str # 'trace', 'chunk', etc.+ content_type: str # 'application/json', etc.+ message_type: str # 'event', etc.+++class InvokeAgentUsage(TypedDict):+ """Token usage information from trace events."""++ inputTokens: int+ outputTokens: int+ model: Optional[str]+++class InvokeAgentMetadata(TypedDict, total=False):+ """Metadata from model invocation."""++ clientRequestId: Optional[str]+ endTime: Optional[str]+ startTime: Optional[str]+ totalTimeMs: Optional[int]+ usage: Optional[InvokeAgentUsage]+++class InvokeAgentModelInvocationInput(TypedDict, total=False):+ """Model invocation input details."""++ foundationModel: Optional[str]+ inferenceConfiguration: Optional[Dict[str, Any]]+ text: Optional[str]+ traceId: Optional[str]+ type: Optional[str]+++class InvokeAgentModelInvocationOutput(TypedDict, total=False):+ """Model invocation output details."""++ metadata: Optional[InvokeAgentMetadata]+ parsedResponse: Optional[Dict[str, Any]]+ rawResponse: Optional[Dict[str, Any]]+ reasoningContent: Optional[Dict[str, Any]]+ traceId: Optional[str]+++class InvokeAgentOrchestrationTrace(TypedDict, total=False):+ """Orchestration trace information."""++ modelInvocationInput: Optional[InvokeAgentModelInvocationInput]+ modelInvocationOutput: Optional[InvokeAgentModelInvocationOutput]+++class InvokeAgentPreProcessingTrace(TypedDict, total=False):+ """Pre-processing trace information."""++ modelInvocationInput: Optional[InvokeAgentModelInvocationInput]+ modelInvocationOutput: Optional[InvokeAgentModelInvocationOutput]+++class InvokeAgentTrace(TypedDict, total=False):+ """Trace information container."""++ orchestrationTrace: Optional[InvokeAgentOrchestrationTrace]+ preProcessingTrace: Optional[InvokeAgentPreProcessingTrace]+++class InvokeAgentCallerChain(TypedDict, total=False):+ """Caller chain information."""++ agentAliasArn: str+++class InvokeAgentTracePayload(TypedDict, total=False):+ """Payload for trace events."""++ agentAliasId: str+ agentId: str+ agentVersion: str+ callerChain: List[InvokeAgentCallerChain]+ eventTime: str+ sessionId: str+ trace: InvokeAgentTrace+++class InvokeAgentChunkPayload(TypedDict, total=False):+ """Payload for chunk events containing response content."""++ bytes: str # Base64 encoded response content+++class InvokeAgentEventPayload(TypedDict, total=False):+ """Union type for different event payload types."""++ # Trace event fields+ agentAliasId: Optional[str]+ agentId: Optional[str]+ agentVersion: Optional[str]+ callerChain: Optional[List[InvokeAgentCallerChain]]+ eventTime: Optional[str]+ sessionId: Optional[str]+ trace: Optional[InvokeAgentTrace]++ # Chunk event fields+ bytes: Optional[str]+++class InvokeAgentEvent(TypedDict, total=False):+ """Complete event structure for AWS Invoke Agent responses."""++ headers: InvokeAgentEventHeaders+ payload: Optional[InvokeAgentEventPayload]+++# Type aliases for convenience+InvokeAgentEventList = List[InvokeAgentEvent]+InvokeAgentTraceEvent = InvokeAgentEvent # When headers.event_type == 'trace'+InvokeAgentChunkEvent = InvokeAgentEvent # When headers.event_type == 'chunk'diff --git a/litellm/utils.py b/litellm/utils.pyindex 632f2151e0e..47638afd11b 100644--- a/litellm/utils.py+++ b/litellm/utils.py@@ -6515,6 +6515,12 @@ class ProviderConfigManager:if bedrock_route == "converse" or bedrock_route == "converse_like":return litellm.AmazonConverseConfig()+ elif bedrock_route == "agent":+ from litellm.llms.bedrock.chat.invoke_agent.transformation import (+ AmazonInvokeAgentConfig,+ )++ return AmazonInvokeAgentConfig()elif bedrock_invoke_provider == "amazon": # amazon titan llmsreturn litellm.AmazonTitanConfig()elif bedrock_invoke_provider == "anthropic":diff --git a/tests/llm_translation/test_bedrock_agents.py b/tests/llm_translation/test_bedrock_agents.pynew file mode 100644index 00000000000..5b0de570c36--- /dev/null+++ b/tests/llm_translation/test_bedrock_agents.py@@ -0,0 +1,64 @@+import os+import sys+import traceback++from dotenv import load_dotenv++import litellm.types++load_dotenv()+import io+import os+import json++sys.path.insert(+ 0, os.path.abspath("../..")+) # Adds the parent directory to the system path+from unittest.mock import AsyncMock, Mock, patch++import pytest++async def test_bedrock_agents():+ litellm._turn_on_debug()+ response = litellm.completion(+ model="bedrock/agent/L1RT58GYRW/MFPSBCXYTW",+ messages=[+ {+ "role": "user",+ "content": "Hi just respond with a ping message"+ }+ ],+ )++ #########################################################+ #########################################################+ print("response from agent=", response.model_dump_json(indent=4))++ # assert that the message content has a response with some length+ assert len(response.choices[0].message.content) > 0+++ # assert we were able to get the response cost+ assert response._hidden_params["response_cost"] is not None and response._hidden_params["response_cost"] > 0++ pass++async def test_bedrock_agents_with_streaming():+ # litellm._turn_on_debug()+ response = litellm.completion(+ model="bedrock/agent/L1RT58GYRW/MFPSBCXYTW",+ messages=[+ {+ "role": "user",+ "content": "Hi who is ishaan cto of litellm, tell me 10 things about him"+ }+ ],+ stream=True,+ )++ for chunk in response:+ print("final chunk=", chunk)++ pass\ No newline at end of filediff --git a/tests/test_litellm/llms/bedrock/invoke_agent/test_bedrock_agent_transformation.py b/tests/test_litellm/llms/bedrock/invoke_agent/test_bedrock_agent_transformation.pynew file mode 100644index 00000000000..ef2bb3757fc--- /dev/null+++ b/tests/test_litellm/llms/bedrock/invoke_agent/test_bedrock_agent_transformation.py@@ -0,0 +1,272 @@+import base64+import json+import os+import sys+import uuid+from unittest.mock import MagicMock, Mock, patch++import pytest+from fastapi.testclient import TestClient++sys.path.insert(+ 0, os.path.abspath("../../../..")+) # Adds the parent directory to the system path++from litellm.llms.bedrock.chat.invoke_agent.transformation import (+ AmazonInvokeAgentConfig,+)+from litellm.types.llms.bedrock_invoke_agents import (+ InvokeAgentEvent,+ InvokeAgentEventHeaders,+ InvokeAgentUsage,+)+from litellm.types.utils import Message, ModelResponse, Usage+++class TestAmazonInvokeAgentConfig:+ """Test suite for AmazonInvokeAgentConfig methods"""++ @pytest.fixture+ def config(self):+ """Create a test instance of AmazonInvokeAgentConfig"""+ return AmazonInvokeAgentConfig()++ @pytest.fixture+ def sample_messages(self):+ """Sample messages for testing"""+ return [+ {"role": "user", "content": "Hello, how can you help me?"},+ {"role": "assistant", "content": "I can help with various tasks."},+ {"role": "user", "content": "What is the weather like?"},+ ]++ @pytest.fixture+ def sample_events(self):+ """Sample events for testing event parsing"""+ return [+ {+ "headers": {"event_type": "chunk"},+ "payload": {+ "bytes": base64.b64encode("Hello ".encode("utf-8")).decode("utf-8")+ },+ },+ {+ "headers": {"event_type": "chunk"},+ "payload": {+ "bytes": base64.b64encode("world!".encode("utf-8")).decode("utf-8")+ },+ },+ {+ "headers": {"event_type": "trace"},+ "payload": {+ "trace": {+ "preProcessingTrace": {+ "modelInvocationOutput": {+ "metadata": {+ "usage": {"inputTokens": 10, "outputTokens": 20}+ }+ }+ },+ "orchestrationTrace": {+ "modelInvocationInput": {+ "foundationModel": "anthropic.claude-v2"+ }+ },+ }+ },+ },+ ]++ def test_get_agent_id_and_alias_id_valid(self, config):+ """Test parsing valid agent model string"""+ model = "agent/L1RT58GYRW/MFPSBCXYTW"+ agent_id, agent_alias_id = config._get_agent_id_and_alias_id(model)++ assert agent_id == "L1RT58GYRW"+ assert agent_alias_id == "MFPSBCXYTW"++ def test_get_agent_id_and_alias_id_invalid_format(self, config):+ """Test parsing invalid agent model string"""+ invalid_models = [+ "invalid/L1RT58GYRW/MFPSBCXYTW", # Wrong prefix+ "agent/L1RT58GYRW", # Missing alias+ "agent/L1RT58GYRW/MFPSBCXYTW/extra", # Too many parts+ "L1RT58GYRW/MFPSBCXYTW", # Missing prefix+ ]++ for invalid_model in invalid_models:+ with pytest.raises(ValueError, match="Invalid model format"):+ config._get_agent_id_and_alias_id(invalid_model)++ @patch(+ "litellm.llms.bedrock.chat.invoke_agent.transformation.convert_content_list_to_str"+ )+ def test_transform_request(self, mock_convert, config, sample_messages):+ """Test transform_request method"""+ mock_convert.return_value = "What is the weather like?"++ model = "agent/TEST123/ALIAS456"+ optional_params = {}+ litellm_params = {}+ headers = {}++ result = config.transform_request(+ model, sample_messages, optional_params, litellm_params, headers+ )++ expected = {+ "inputText": "What is the weather like?",+ "enableTrace": True,+ }+ assert result == expected+ mock_convert.assert_called_once_with(sample_messages[-1])++ def test_extract_response_content(self, config, sample_events):+ """Test _extract_response_content method"""+ result = config._extract_response_content(sample_events)+ assert result == "Hello world!"++ def test_extract_response_content_empty_events(self, config):+ """Test _extract_response_content with empty events"""+ result = config._extract_response_content([])+ assert result == ""++ def test_extract_response_content_no_chunk_events(self, config):+ """Test _extract_response_content with no chunk events"""+ events = [{"headers": {"event_type": "trace"}, "payload": {"some": "data"}}]+ result = config._extract_response_content(events)+ assert result == ""++ def test_is_trace_event(self, config):+ """Test _is_trace_event method"""+ trace_event = {"headers": {"event_type": "trace"}, "payload": {"some": "data"}}+ chunk_event = {"headers": {"event_type": "chunk"}, "payload": {"bytes": "data"}}+ invalid_event = {"headers": {"event_type": "trace"}, "payload": None}++ assert config._is_trace_event(trace_event) is True+ assert config._is_trace_event(chunk_event) is False+ assert config._is_trace_event(invalid_event) is False++ def test_get_trace_data(self, config):+ """Test _get_trace_data method"""+ event = {"payload": {"trace": {"preProcessingTrace": {"some": "data"}}}}+ result = config._get_trace_data(event)+ assert result == {"preProcessingTrace": {"some": "data"}}++ def test_get_trace_data_no_payload(self, config):+ """Test _get_trace_data with no payload"""+ event = {"payload": None}+ result = config._get_trace_data(event)+ assert result is None++ def test_extract_usage_info(self, config, sample_events):+ """Test _extract_usage_info method"""+ result = config._extract_usage_info(sample_events)++ assert result["inputTokens"] == 10+ assert result["outputTokens"] == 20+ assert result["model"] == "anthropic.claude-v2"++ def test_extract_usage_info_empty_events(self, config):+ """Test _extract_usage_info with empty events"""+ result = config._extract_usage_info([])++ assert result["inputTokens"] == 0+ assert result["outputTokens"] == 0+ assert result["model"] is None++ def test_extract_and_update_preprocessing_usage(self, config):+ """Test _extract_and_update_preprocessing_usage method"""+ trace_data = {+ "preProcessingTrace": {+ "modelInvocationOutput": {+ "metadata": {"usage": {"inputTokens": 15, "outputTokens": 25}}+ }+ }+ }+ usage_info = {"inputTokens": 5, "outputTokens": 10, "model": None}++ config._extract_and_update_preprocessing_usage(trace_data, usage_info)++ assert usage_info["inputTokens"] == 20 # 5 + 15+ assert usage_info["outputTokens"] == 35 # 10 + 25++ def test_extract_and_update_preprocessing_usage_no_data(self, config):+ """Test _extract_and_update_preprocessing_usage with missing data"""+ trace_data = {}+ usage_info = {"inputTokens": 5, "outputTokens": 10, "model": None}++ config._extract_and_update_preprocessing_usage(trace_data, usage_info)++ # Should remain unchanged+ assert usage_info["inputTokens"] == 5+ assert usage_info["outputTokens"] == 10++ def test_extract_orchestration_model(self, config):+ """Test _extract_orchestration_model method"""+ trace_data = {+ "orchestrationTrace": {+ "modelInvocationInput": {"foundationModel": "anthropic.claude-v2"}+ }+ }+ result = config._extract_orchestration_model(trace_data)+ assert result == "anthropic.claude-v2"++ def test_extract_orchestration_model_no_data(self, config):+ """Test _extract_orchestration_model with missing data"""+ trace_data = {}+ result = config._extract_orchestration_model(trace_data)+ assert result is None++ def test_build_model_response(self, config):+ """Test _build_model_response method"""+ content = "Hello, world!"+ model = "agent/TEST123/ALIAS456"+ usage_info = {+ "inputTokens": 10,+ "outputTokens": 20,+ "model": "anthropic.claude-v2",+ }+ model_response = ModelResponse()++ result = config._build_model_response(+ content, model, usage_info, model_response+ )++ assert len(result.choices) == 1+ assert result.choices[0].message.content == content+ assert result.choices[0].message.role == "assistant"+ assert result.choices[0].finish_reason == "stop"+ assert result.model == "anthropic.claude-v2"+ assert hasattr(result, "usage")+ assert result.usage.prompt_tokens == 10+ assert result.usage.completion_tokens == 20+ assert result.usage.total_tokens == 30++ @patch(+ "litellm.llms.bedrock.chat.invoke_agent.transformation.convert_content_list_to_str"+ )+ @patch.object(AmazonInvokeAgentConfig, "get_runtime_endpoint")+ @patch.object(AmazonInvokeAgentConfig, "_get_aws_region_name")+ def test_get_complete_url(self, mock_region, mock_endpoint, mock_convert, config):+ """Test get_complete_url method"""+ mock_endpoint.return_value = (+ "https://bedrock-runtime.us-east-1.amazonaws.com",+ None,+ )+ mock_region.return_value = "us-east-1"++ api_base = None+ api_key = None+ model = "agent/L1RT58GYRW/MFPSBCXYTW"+ optional_params = {}+ litellm_params = {}++ result = config.get_complete_url(+ api_base, api_key, model, optional_params, litellm_params+ )++ assert (+ "https://bedrock-runtime.us-east-1.amazonaws.com/agents/L1RT58GYRW/agentAliases/MFPSBCXYTW/sessions"+ in result+ )