Building Production-Grade AI Agents with Amazon Bedrock & Tool Calling

Building Production-Grade AI Agents with Amazon Bedrock & Tool Calling

Learn to build production-grade AI agents in Python using the Amazon Bedrock Converse API and tool calling.

Building Production-Grade AI Agents with Amazon Bedrock Converse API and Tool Use

Description

Learn how to build production-grade AI agents with Amazon Bedrock using the unified Converse API. This guide covers schema definition, tool-calling orchestration loops, error handling, and enterprise best practices.



Introduction

Moving an AI agent from a simple prototype to a production system requires structure, predictability, and fault tolerance. While foundation models excel at reasoning, they cannot interact directly with your business systems (databases, internal APIs, or third-party platforms) without external tools.
The Amazon Bedrock Converse API provides a standardized, model-agnostic interface for executing multi-turn conversations and deterministic tool calling (function calling) across supported models like Anthropic Claude, Amazon Nova, and Meta Llama.
In this article, we will build an end-to-end production-ready agent in Python that connects Amazon Bedrock to external APIs, using the AWS SDK for Python ( boto3 ).

Architecture Overview

A tool-calling loop in Amazon Bedrock follows a four-step interaction lifecycle:
  1. User Request & Schema Pass: The user submits a prompt alongside defined tool schemas ( toolConfig ) to  bedrock-runtime.converse() .
  1. Model Evaluation: Bedrock evaluates whether an available tool is needed. If so, it halts text generation and returns a  stopReason  of  tool_use , specifying the target function name and extracted arguments.
  1. Execution Phase: Your backend receives the  toolUse  block, executes the corresponding function (e.g., querying a database or calling AWS Lambda), and formats the output into a  toolResult  block.
  1. Final Synthesis: The  toolResult  is appended back to the conversation as a  user  role message. Bedrock synthesizes the final user-facing response with a  stopReason  of  end_turn .

Step 1: Defining the Tool Schema

Tools are defined using strict JSON schemas. Clear parameter descriptions and explicitly required properties prevent the model from hallucinating invalid inputs.
# define_tools.py

order_status_tool = {
"toolSpec": {
"name": "get_order_status",
"description": "Retrieves real-time fulfillment status and tracking details for a specific order ID.",
"inputSchema": {
"json": {
"type": "object",
"properties": {
"order_id": {
"type": "string",
"description": "The unique 8-character order identifier (e.g., ORD-98231)."
}
},
"required": ["order_id"]
}
}
}
}

tool_config = {
"tools": [order_status_tool]
}


Step 2: Implementing the Local Executable Functions

Your backend logic acts as the bridge between model decisions and system execution.
# tools_impl.py
import json

def get_order_status(order_id: str) -> dict:
"""Mock implementation of a database/API query."""
# Production note: Replace with DynamoDB, SQL query, or REST API call
database = {
"ORD-98231": {"status": "Shipped", "carrier": "FedEx", "tracking_number": "1Z9999999999999999"},
"ORD-11029": {"status": "Processing", "carrier": None, "tracking_number": None}
}

if order_id in database:
return database[order_id]
return {"error": f"Order ID {order_id} was not found in the system."}

def execute_tool(tool_name: str, tool_inputs: dict) -> dict:
"""Router for executing incoming tool requests."""
if tool_name == "get_order_status":
return get_order_status(tool_inputs.get("order_id"))
else:
return {"error": f"Unknown tool: {tool_name}"}


Step 3: Building the Production Orchestration Loop

In production, agents must handle multi-step tool calls, error states, and execution limits to avoid infinite loops.
# agent.py
import boto3
from botocore.exceptions import ClientError
from define_tools import tool_config
from tools_impl import execute_tool

client = boto3.client("bedrock-runtime", region_name="us-east-1")
MODEL_ID = "anthropic.claude-3-5-sonnet-20240620-v1:0"

def run_agent(user_prompt: str, max_turns: int = 5):
messages = [
{
"role": "user",
"content": [{"text": user_prompt}]
}
]

system_prompt = [{
"text": "You are a professional customer support agent. Always use available tools to look up live order information."
}]

for turn in range(max_turns):
try:
response = client.converse(
modelId=MODEL_ID,
messages=messages,
system=system_prompt,
toolConfig=tool_config
)
except ClientError as e:
print(f"Bedrock API Error: {e}")
break

output_message = response["output"]["message"]
messages.append(output_message)
stop_reason = response.get("stopReason")

# Check if the model requested tool execution
if stop_reason == "tool_use":
tool_requests = [
block for block in output_message["content"] if "toolUse" in block
]

tool_results_content = []
for request in tool_requests:
tool_use = request["toolUse"]
tool_use_id = tool_use["toolUseId"]
tool_name = tool_use["name"]
tool_inputs = tool_use["input"]

print(f"[Agent Action] Invoking tool: {tool_name} with args: {tool_inputs}")

# Execute tool backend
result_data = execute_tool(tool_name, tool_inputs)

# Format the output block back to Bedrock
tool_results_content.append({
"toolResult": {
"toolUseId": tool_use_id,
"content": [{"json": result_data}]
}
})

# Append tool outputs back into the conversation context as 'user' role
messages.append({
"role": "user",
"content": tool_results_content
})

elif stop_reason == "end_turn":
# Extract final text output
final_text = next(
(block["text"] for block in output_message["content"] if "text" in block),
""
)
return final_text

return "Agent reached maximum execution depth without completing the request."

# Example Execution
if __name__ == "__main__":
prompt = "Hi, can you check where my order ORD-98231 is right now?"
result = run_agent(prompt)
print(f"\nFinal Response:\n{result}")


Production Best Practices

To run AI agents reliably at scale, implement these engineering guardrails:
  • Deterministic Tool Schemas: Always set  required  fields and write strict parameter descriptions. Unclear definitions lead to invalid tool calls.
  • Graceful Exception Handling: If a downstream tool fails, pass structured error messages (e.g.,  {"error": "Timeout"} ) inside the  toolResult  block rather than crashing the application process. This gives the model a chance to explain the failure or try an alternative approach.
  • Guardrails Integration: Attach Amazon Bedrock Guardrails to the  converse  API request envelope to automatically redact PII (personally identifiable information) and block harmful prompts before tool execution.
  • Observability & Instrumentation: Log full trace IDs, latency per tool invocation, and token usage using AWS X-Ray or Amazon CloudWatch. Monitoring tool-use frequency helps identify redundant function calls and reduce overall latency.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article