AWS Builder Center
How AI Agents Use Tools and APIs: Building Intelligent Applications with Amazon Bedrock

How AI Agents Use Tools and APIs: Building Intelligent Applications with Amazon Bedrock

Explore how AI agents use tools, APIs, and AWS services to move beyond simple chatbots. Learn how Amazon Bedrock, Python, Boto3, and AWS Lambda enable intelligent applications through practical tool-calling workflows. Discover implementation techniques, real-world use cases, and essential security practices for building reliable AI-powered applications.

Computer Science Engineering Student | Software Development | AI | Cloud Computing | Cybersecurity

How AI Agents Use Tools and APIs: Building Intelligent Applications with Amazon Bedrock

Introduction

In my previous article, we explored how Amazon Bedrock simplifies building generative AI applications using foundation models. But generating intelligent responses is only one part of the journey.
What if an AI application could go beyond answering questions and actually interact with external systems?
AI agents make this possible by connecting foundation models with tools, APIs, databases, and cloud services. They can understand user requests, select appropriate tools, retrieve information, and perform authorized operations.
Let's explore how this works and how we can build a simple AI-powered application using Amazon Bedrock, Python, Boto3, and AWS services.

From Generative AI to AI Agents

In my previous article, Amazon Bedrock: Building Generative AI Applications with Foundation Models on AWS, we explored foundation models, prompt engineering, inference, and Retrieval-Augmented Generation (RAG).
These concepts form the foundation of modern generative AI applications.
However, there is another important step in the evolution of AI applications: enabling them to interact with external systems.
Imagine asking an AI assistant:
  • Is my EC2 instance running?
  • Retrieve customer information from a database.
  • Check whether a particular API is responding.
  • Generate a summary of recent application errors.
  • Create a support ticket based on a user request.
A traditional chatbot might explain how to perform these tasks.
An AI agent can go further by interacting with external systems through tools and APIs.
This changes how we think about AI applications. Instead of simply generating responses, they can understand requests, select appropriate tools, retrieve information, and execute authorized operations.
The real value of an AI agent is not just what it knows, but what it can safely do.

1. Understanding Tool Calling

Tool calling, also known as function calling, allows a foundation model to request external functionality when it needs information or capabilities beyond its existing context.
A tool can be:
  • A Python function.
  • A REST API.
  • A database query.
  • An AWS Lambda function.
  • A cloud monitoring operation.
  • An external service integration.
For example, consider this request:
User: "Check whether my EC2 instance is running."
The AI model understands that it needs information from AWS infrastructure.
Instead of guessing the instance status, it requests an available tool that can retrieve the information.
The application executes the requested function, receives the result, and sends it back to the model. The model then uses the actual result to formulate a response.
An important distinction is that the model generally requests a tool call; the surrounding application or agent runtime executes it according to the configured permissions.
This separation is important because the application remains responsible for validating inputs, enforcing permissions, and controlling which operations can be performed.

2. How Does the Tool-Calling Workflow Work?

A typical tool-calling workflow consists of seven stages.

Step 1: User Request

The user submits a natural-language request.
Example:
"Check the status of my EC2 instance."

Step 2: Intent Understanding

The foundation model interprets the request and identifies the required information.
It determines that an EC2 instance status lookup is needed.

Step 3: Tool Selection

The model selects an appropriate tool from the tools defined by the application.
For example:
get_ec2_instance_status(instance_id)

Step 4: Tool Execution

The application receives the tool request, validates its arguments, and executes the corresponding function.
This function could interact with AWS through Boto3.

Step 5: API Response

The AWS API returns information about the requested resource.
For example:
  • Instance ID
  • Instance state
  • Instance type
  • Availability Zone

Step 6: Result Processing

The application sends the tool result back to the foundation model.
The model uses the returned information to prepare a response.

Step 7: Final Response

The user receives a natural-language response based on the actual API result.
For example:
"Your EC2 instance is currently running."
This process is commonly implemented as an orchestration loop in which the model requests a tool, the application executes it, and the result is returned to the model.

3. How AWS Enables AI Agent Integrations

AWS provides several services that can be combined to build tool-enabled AI applications.
AWS Service
Role in an AI Agent
Amazon Bedrock
Provides access to foundation models
Amazon Bedrock AgentCore
Provides capabilities for building, deploying, and operating AI agents
AWS Lambda
Executes application logic and custom functions
Amazon API Gateway
Exposes APIs to applications and services
Amazon EC2
Provides compute infrastructure that an agent can inspect
Amazon DynamoDB
Stores and retrieves application data
AWS IAM
Controls permissions and resource access
Amazon CloudWatch
Provides logs, metrics, and monitoring
These services can work together to create applications in which an AI model understands a request and interacts with cloud infrastructure through controlled operations.
For this demonstration, we will use Amazon Bedrock's Converse API, Python, Boto3, and Amazon EC2.
The Converse API provides a consistent interface for interacting with supported foundation models and defining tools.

4. Practical Implementation: Building an AWS Monitoring Assistant

Let's build a simple AI-powered AWS monitoring assistant.

Objective

Create an assistant that can answer:
"Is my EC2 instance running?"
The application will:
  1. Receive a user request.
  1. Send the request and available tool definition to Amazon Bedrock.
  1. Allow the model to request an EC2 status lookup.
  1. Execute the requested operation using Boto3.
  1. Return the API result to the model.
  1. Generate a final response.

Architecture

User
|
v
Python Application
|
v
Amazon Bedrock
|
v
Tool Selection
|
v
Boto3
|
v
Amazon EC2 API
|
v
Tool Result
|
v
Amazon Bedrock
|
v
Final Response to User
The model is responsible for selecting the tool, while the Python application controls its execution.

4.1 Prerequisites

Before starting, make sure you have:
  • An AWS account.
  • Access to Amazon Bedrock in a supported AWS Region.
  • An enabled foundation model that supports tool use.
  • Appropriate model access and IAM permissions.
  • Python 3.10 or later.
  • AWS CLI configured with credentials.
Install the required Python package:
pip install boto3
Configure AWS credentials using an appropriate IAM role or AWS CLI profile.
For local development:
aws configure
Avoid hardcoding AWS access keys in your Python scripts. Use an IAM role or a securely configured credentials profile wherever possible.

4.2 Step 1: Connect to Amazon Bedrock

First, create a Bedrock Runtime client using Boto3.
import boto3


REGION = "us-east-1"


bedrock = boto3.client(
"bedrock-runtime",
region_name=REGION
)


MODEL_ID = "YOUR_SUPPORTED_MODEL_ID"
Replace the model ID with an enabled foundation model that supports tool use in your selected Region.
The application uses this client to send conversational requests to Amazon Bedrock.

4.3 Step 2: Create the EC2 Monitoring Function

Next, create a Python function that retrieves information about an EC2 instance.
import boto3
import re


ec2 = boto3.client(
"ec2",
region_name=REGION
)


def get_ec2_instance_status(instance_id):


# Validate the EC2 instance ID format
if not re.fullmatch(r"i-[0-9a-f]{8,17}", instance_id):
raise ValueError("Invalid EC2 instance ID format")


response = ec2.describe_instances(
InstanceIds=[instance_id]
)


reservations = response.get("Reservations", [])


if not reservations or not reservations[0]["Instances"]:
return {"error": "Instance not found"}


instance = reservations[0]["Instances"][0]


return {
"instance_id": instance["InstanceId"],
"state": instance["State"]["Name"],
"instance_type": instance["InstanceType"]
}
This function uses the EC2  DescribeInstances  API through Boto3.
It retrieves the instance's current state and basic information.
The instance ID validation helps reject incorrectly formatted inputs before making an AWS API request.
Notice that this function does not start, stop, or modify any instance. It is a read-only operation.

4.4 Step 3: Define the Tool for Amazon Bedrock

The model needs to know what tools are available and what information each tool requires.
We define the tool using a JSON schema.
tool_config = {
"tools": [
{
"toolSpec": {
"name": "get_ec2_instance_status",
"description": (
"Retrieve the current state and "
"instance type of an EC2 instance."
),
"inputSchema": {
"json": {
"type": "object",
"properties": {
"instance_id": {
"type": "string",
"description": (
"The EC2 instance ID, "
"such as i-0123456789abcdef0"
)
}
},
"required": ["instance_id"]
}
}
}
}
]
}
The schema describes:
  • Tool name.
  • Tool purpose.
  • Expected parameters.
  • Parameter data types.
  • Required inputs.
This allows the model to understand how to request the tool.
Defining a tool does not automatically execute it. The application must implement the corresponding function and decide how to handle the model's request.

4.5 Step 4: Implement the Tool-Calling Loop

This is the most important part of the implementation.
The application sends the user's request to Bedrock, checks whether a tool was requested, executes that tool, and returns its result to the model.
import json
from botocore.exceptions import ClientError, BotoCoreError




def run_agent(user_query):


messages = [
{
"role": "user",
"content": [
{"text": user_query}
]
}
]


max_tool_rounds = 5
tool_rounds = 0


while tool_rounds < max_tool_rounds:


response = bedrock.converse(
modelId=MODEL_ID,
messages=messages,
system=[
{
"text": (
"You are an AWS monitoring assistant. "
"Use the available tool to retrieve "
"EC2 instance information. "
"Never invent instance states."
)
}
],
inferenceConfig={
"maxTokens": 500,
"temperature": 0
},
toolConfig=tool_config
)


assistant_message = response["output"]["message"]


messages.append(assistant_message)


if response["stopReason"] == "tool_use":


tool_rounds += 1
tool_results = []


for block in assistant_message["content"]:


if "toolUse" not in block:
continue


tool_use = block["toolUse"]


tool_name = tool_use["name"]
tool_input = tool_use["input"]


try:


if tool_name == "get_ec2_instance_status":


result = get_ec2_instance_status(
tool_input["instance_id"]
)


status = "success"


else:


result = {
"error": "Unknown tool requested"
}


status = "error"


except (
ClientError,
BotoCoreError,
KeyError,
ValueError
) as error:


result = {
"error": str(error)
}


status = "error"


tool_results.append({
"toolResult": {
"toolUseId": tool_use["toolUseId"],
"content": [
{
"text": json.dumps(result)
}
],
"status": status
}
})


if not tool_results:
return "No valid tool request was received."


messages.append({
"role": "user",
"content": tool_results
})


else:


for block in assistant_message["content"]:


if "text" in block:
return block["text"]


return "No text response generated."


return (
"The assistant reached the maximum number "
"of tool-calling rounds."
)

Understanding the Implementation

There are three important parts of this code.
1. Tool Selection
if response["stopReason"] == "tool_use":
This checks whether the model has requested a tool instead of completing its response.
2. Tool Execution
result = get_ec2_instance_status(
tool_input["instance_id"]
)
The application executes the function using the arguments requested by the model.
Before execution, the function validates the instance ID format.
3. Returning the Result
messages.append({
"role": "user",
"content": tool_results
})
The tool result is added to the conversation so that the model can interpret the actual output and generate its final response.
The  toolUseId  connects the tool result to the corresponding tool request.
The loop also includes a maximum number of tool-calling rounds. This prevents the application from continuing indefinitely if the model repeatedly requests tools.

4.6 Step 5: Run the Application

Now we can execute the assistant.
if __name__ == "__main__":


instance_id = input(
"Enter EC2 Instance ID: "
)


query = (
f"Check the status of EC2 instance "
f"{instance_id}"
)


result = run_agent(query)


print("\nAI Assistant Response:")
print(result)

Example Interaction

Enter EC2 Instance ID:
i-0123456789abcdef0


AI Assistant Response:


The EC2 instance i-0123456789abcdef0
is currently running.


Instance Type: t2.micro
Note: This is an illustrative output. Actual results depend on the EC2 instance, AWS account, Region, model response, and permissions.
At this point, we have a basic AI-powered monitoring assistant that can understand a natural-language request, select a tool, retrieve information from AWS, and generate a response based on the returned result.

5. Extending the Architecture with AWS Lambda and API Gateway

The previous example executes the EC2 operation directly from the Python application.
For a more modular architecture, we can move the business logic into AWS Lambda and expose it through Amazon API Gateway.
This separates the AI application from the underlying cloud operations.
For example:
  1. Amazon Bedrock identifies the required operation.
  1. The application invokes an authorized API endpoint.
  1. API Gateway receives the request.
  1. AWS Lambda validates the request and executes the operation.
  1. Lambda communicates with the relevant AWS service.
  1. The result is returned to the application.
  1. Amazon Bedrock generates the final response.
This architecture is useful when multiple applications need access to the same backend functionality.
It also provides a natural place to implement authentication, validation, rate limiting, and centralized logging.
The important point is that API Gateway and Lambda do not replace the tool-calling process. They provide an additional layer through which the application can securely access backend functionality.

6. Security Considerations When Building AI Agents

Connecting AI agents to external systems introduces additional security responsibilities.
An agent that can access APIs or cloud resources must be designed carefully.

6.1 Apply Least-Privilege Access

Never give an AI agent unrestricted AWS permissions.
For the EC2 example, the execution identity should have only the required read permission.
An illustrative IAM policy is:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ec2:DescribeInstances"
],
"Resource": "*"
}
]
}
This allows the required EC2 read operation without granting permissions to start, stop, or terminate instances.
For this particular API action,  "Resource": "*"  is required because  DescribeInstances  does not support resource-level permissions. The policy should still be limited to the necessary actions.

6.2 Validate Tool Inputs

Never blindly trust arguments generated by a model.
Validate:
  • Instance IDs.
  • API parameters.
  • User authorization.
  • Input length and format.
  • Requested operation.
Input validation should happen in the application before the requested operation is executed.

6.3 Require Human Approval for Sensitive Actions

For destructive or high-impact operations, introduce an approval mechanism.
For example, an agent should not automatically terminate an EC2 instance simply because a prompt requests it.
Sensitive actions should require appropriate authorization and, where necessary, explicit human approval.

6.4 Protect Sensitive Information

Avoid exposing credentials, access tokens, passwords, or confidential information through prompts, logs, and tool responses.
Use secure credential management and return only the information required by the model.

6.5 Monitor Tool Execution

Use Amazon CloudWatch and appropriate AWS audit services to monitor application behavior, failures, and API activity.
Monitoring helps identify unexpected operations, repeated failures, unusual access patterns, and performance issues.
Security should be part of the architecture from the beginning, not something added after deployment.

7. Common Challenges in Tool-Enabled AI Applications

Building an agent that can call tools is relatively straightforward. Building one that behaves reliably is more challenging.
Challenge
Possible Solution
Incorrect tool selection
Improve tool descriptions and schemas
Invalid API parameters
Validate inputs before execution
API failures
Implement error handling and retries
Slow responses
Use timeouts and optimize API calls
Excessive permissions
Apply least-privilege IAM policies
Unexpected tool execution
Use an explicit tool allowlist
Incorrect final responses
Ground responses in actual tool results
Another important consideration is cost.
Each model invocation, API operation, and supporting AWS service may introduce additional costs. A tool-calling workflow can require multiple model requests for a single user interaction.
Therefore, developers should monitor latency, token usage, API consumption, and overall execution costs.

8. Key Takeaways

AI agents become significantly more useful when they can interact with external systems.
The combination of foundation models, tool calling, APIs, and cloud infrastructure allows developers to build applications that can:
  • Retrieve real-time information.
  • Interact with databases.
  • Monitor cloud resources.
  • Automate repetitive workflows.
  • Connect different software systems.
  • Execute controlled operations.
Amazon Bedrock provides the foundation-model integration, while services such as Lambda, API Gateway, EC2, DynamoDB, IAM, and CloudWatch can support the surrounding application architecture.
However, the goal should not simply be to give AI agents access to more tools.
The goal should be to give them the right tools, with the right permissions, and a reliable execution process.

9. Conclusion

We are moving from applications that simply respond to questions toward applications that can understand requests and interact with the systems around them.
Tool calling is an important part of this transition.
By combining Amazon Bedrock with Python, Boto3, and AWS services, developers can build AI-powered applications that connect natural-language understanding with real-world execution.
But as these systems become more capable, reliability, security, observability, and controlled access become equally important.
An intelligent AI agent is not just one that knows what to do. It is one that can perform the right action safely, verify the result, and explain what happened.

Let's Discuss!

If you were building an AI agent on AWS, which integration would you implement first?
  • Database access using Amazon DynamoDB.
  • Cloud monitoring using Amazon CloudWatch.
  • Infrastructure management using Amazon EC2.
  • External API integrations using API Gateway.
I'd love to hear what you are building and how you are exploring AI agents!

References and Further Reading

Code examples are educational starting points. Test them in a controlled AWS environment and review IAM permissions, model availability, and service configuration before using them in production.
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