In the rapidly evolving landscape of cloud management, the ability to automate complex tasks using natural language is becoming a game-changer. Amazon Bedrock Agents empower organizations to build sophisticated conversational AI applications that extend the capabilities of Large Language Models (LLMs), transforming how we interact with AWS services. These agents act as intelligent orchestrators, capable of understanding multi-step user requests, reasoning through the necessary actions, maintaining conversational context, and executing tasks across various systems using defined tools.
This article will guide you through the process of setting up and leveraging Amazon Bedrock Agents for seamless AWS operations. We’ll demonstrate how to integrate them with your AWS environment via Action Groups linked to AWS Lambda functions, enabling automated resource management through simple natural language commands. Beyond the foundational setup, we’ll also explore how to build a custom, user-friendly web application, providing an intuitive interface for interacting with and managing your AWS resources without requiring deep technical expertise or direct console access.
Specifically, you will learn to configure a Bedrock Agent to:
- List existing EC2 instances
- List existing S3 buckets
- Create a new EC2 instance with specified parameters
By the end of this tutorial, you’ll have a solid understanding of how to harness the power of LLMs, orchestrated by Bedrock Agents, to perform actions in your AWS account and present these capabilities through an accessible web interface.
Prerequisites
To follow along with this hands-on guide, ensure you have the following:
- AWS Account: An active AWS account with the necessary permissions to create and manage Bedrock Agents, IAM roles, Lambda functions, EC2 instances, and S3 buckets.
- Amazon Bedrock Access: Ensure Amazon Bedrock is enabled in your AWS account and the specific region you plan to use.
- Bedrock Model Access: You’ll need access to a supported model for Bedrock Agents, such as Anthropic Claude. Enable this through the Bedrock console under “Model access.”
Step 1: Enable Bedrock Model Access
Navigate to the “Model access” section (typically in the bottom left) within the Amazon Bedrock console. Click “Modify access,” then select the Anthropic Claude Sonnet 3.5 models, and submit your changes. After a few minutes, these models should become active in your console.
Note: If you are in India, your payment method must be invoice-based, not card-based, to prevent payment errors.
Step 2: Create AWS Lambda Functions
We will implement three distinct Lambda functions, each designed to perform a specific AWS task and return results in a format optimized for Bedrock Agents. It is crucial to deploy these functions in the same AWS region where your Bedrock Agent will be configured.
You can find the complete Python code for these functions in the following GitHub repository:
https://github.com/sauveerk/projects/tree/main/Code/Gen-AI-Bedrock-Agents
Lambda Function 1: List EC2 Instances
- Function Name:
action_group_ec2 - Purpose: Lists the IDs of all EC2 instances in the current AWS region.
- Required IAM Permissions:
ec2:DescribeInstances
Lambda Function 2: List S3 Buckets
- Function Name:
action_group_s3 - Purpose: Lists the S3 buckets accessible in the account.
- Required IAM Permissions:
s3:ListBuckets
Lambda Function 3: Create EC2 Instance
- Function Name:
action_group_create_ec2 - Purpose: Creates a new EC2 server, taking instance type and region as parameters.
- Required IAM Permissions:
ec2:RunInstances,ec2:DescribeInstances
Step 3: Create Bedrock Agent and Action Groups
In the Bedrock console, navigate to “Agents” under “Builder Tools” and click “Create agent.” Assign a descriptive name (e.g., “AWS Resource Manager Agent”) and a description to your agent.
Once created, select your agent and click “Edit” in the Agent Builder. Choose “Create and use a new service role” and define clear instructions for your agent, such as:
You are an AI assistant that can help users manage their AWS resources. You can list EC2 instances, list S3 buckets, and create new EC2 instances.
Under the “Action Groups” section, click “Add.” Provide a name for your action group (e.g., Ec2ManagementActions) and a description (e.g., “Actions for managing EC2 resources”). For “Action group invocation,” select “Define with Function details.”
Select “Quick create a new Lambda function.” This action automatically creates a Lambda function and configures a resource-based policy, allowing the Bedrock agent to invoke it. Name your function and provide a description. For the initial “List EC2 Instances” action group, no specific parameters are required as it only lists existing resources. You can optionally enable confirmation for action group invocation here; it is disabled by default.
Click save to create the action group. Re-open the action group details to find your newly created Lambda function. Click “View” to go to the Lambda console. Copy the Python code for the “List EC2 Instances” function from the GitHub repository mentioned earlier and paste it into this Lambda function, then deploy it.
Remember to adjust the Lambda function’s timeout duration in its configuration. Also, go to the “Permissions” section and add the necessary ec2:DescribeInstances permission to the IAM role used by the Lambda function.
With the Lambda function now ready, you can test it by providing a test event in the Bedrock-expected JSON format:
{
"messageVersion": "1.0",
"function": "bedrock-agent-list-ec2",
"inputText": "",
"sessionId": "888900372248953",
"agent": {
"name": "agent-aws-resources",
"version": "DRAFT",
"id": "VGGUJUPSEC",
"alias": "TSTALIASID"
},
"actionGroup": "action_group_ec2",
"sessionAttributes": {},
"promptSessionAttributes": {}
}
Repeat these steps to add the other two action groups for S3 bucket listing and EC2 instance creation, ensuring you define the necessary parameters for the EC2 creation function. Finally, save your agent in the agent builder.
Step 4: Test the Bedrock Agent
After your agent is fully configured, click the “Prepare” button on the agent details page in the Bedrock console. This compiles the agent’s configuration. Wait until the status changes to “Prepared.”
Use the “Test” panel on the right side of the agent details page to interact with your agent. If you enabled confirmation for your action groups, the agent will first identify the appropriate action and then ask for your approval before proceeding. Confirm these actions.
Upon invoking the action groups and their corresponding Lambda functions, the agent will return the response. You can expand the “Show trace” section to gain insight into the agent’s thought process and the steps it took to fulfill your request.
For example, try prompting the agent to create an EC2 instance:
Create a t2.nano EC2 instance in ap-south-1 region.
Verify in your AWS console that the EC2 instance has indeed been created with the specified parameters. The trace will show how the agent correctly identified and invoked the EC2 creation action group.
If you provide a less specific prompt, like “create an ec2 server,” the agent will intelligently ask you for the missing parameters (e.g., instance type and region) before proceeding.
Part 2: Agentic AI Web App for End Users
While the Bedrock console offers a powerful environment for testing, deploying a custom web application around your agent provides a more intuitive and accessible interface for operations teams or end-users. This section demonstrates how to build a simple Flask web app to interact with your Bedrock Agent programmatically.
The complete application code can be cloned from this GitHub repository:
https://github.com/sauveerk/projects/tree/main/Code/WebApp-Bedrock-Agent
Step 1: Modify Action Group Behavior and Create Agent Alias
To streamline the web application’s interaction, we’ll disable the action confirmation feature for the action groups that list S3 and EC2 servers. Return to your agent’s configuration, edit the relevant action groups, and uncheck the “Enable confirmation of action group function” option, then save the agent and prepare it.
To enable programmatic interaction, you need to create an agent alias. On the agent page, navigate to the “Alias” section and click “Create.” Give your alias a name and select “Create a new version and associate it to this alias.” Click “Create alias.” Test the new alias to confirm that action confirmations are no longer required.
Step 2: Python Program for Agent Invocation
The core of our programmatic interaction lies in a Python function that invokes the Bedrock Agent. Here’s the code snippet for agent_invoke.py:
import boto3
import json
from botocore.exceptions import ClientError
from typing import Optional, Dict, Any
import uuid
def invoke_bedrock_agent(prompt: str) -> Optional[Dict[Any, Any]]:
"""
Invoke a Bedrock agent with the given prompt.
Args:
prompt (str): The prompt to send to the agent
Returns:
Optional[Dict]: The agent's response or None if an error occurs
"""
try:
bedrock_agent_runtime = boto3.client('bedrock-agent-runtime')
except Exception as e:
print(f"Error creating Bedrock client: {str(e)}")
return None
if not prompt or not isinstance(prompt, str):
print("Error: Prompt must be a non-empty string")
return None
try:
session_id = str(uuid.uuid4())
response = bedrock_agent_runtime.invoke_agent(
agentId='<YOUR_AGENT_ID>',
agentAliasId='<YOUR_AGENT_ALIAS_ID>',
sessionId=session_id,
inputText=prompt
)
# Handle the event stream response
full_response = ""
for event in response['completion']:
if 'chunk' in event:
chunk_data = event['chunk']['bytes'].decode('utf-8')
full_response += chunk_data
# Parse the complete response if needed
if full_response:
try:
return json.loads(full_response)
except json.JSONDecodeError:
# If response is not JSON, return as plain text
return {"response": full_response}
else:
print("Error: Empty response from Bedrock Agent")
return None
except ClientError as e:
print(f"AWS API Error: {str(e)}")
return None
except Exception as e:
print(f"Unexpected error: {str(e)}")
return None
def main():
prompt = input("Enter your prompt: ")
response = invoke_bedrock_agent(prompt)
if response:
print("Agent Response:")
if isinstance(response, dict):
print(json.dumps(response, indent=2))
else:
print(response)
else:
print("Failed to get response from agent")
if __name__ == "__main__":
main()
Step 3: Create Python Flask Web App
Organize your project with the following structure:
your_project_directory/
├── app.py
├── agent_invoke.py
└── templates/
└── index.html
Here’s the code for app.py, which handles the web application logic:
from flask import Flask, render_template, request
from agent_invoke import invoke_bedrock_agent
import json
app = Flask(__name__)
def extract_response_text(response):
try:
if isinstance(response, str):
response_dict = json.loads(response)
else:
response_dict = response
# Check for 'response' field in the dictionary
if 'response' in response_dict:
return response_dict['response']
# Check for 'completion' field as fallback
elif 'completion' in response_dict:
return response_dict['completion']
# Return the full response if no known fields are found
return str(response_dict)
except Exception as e:
return f"Error processing response: {str(e)}"
@app.route('/', methods=['GET', 'POST'])
def home():
response = None
if request.method == 'POST':
user_prompt = request.form.get('prompt')
if user_prompt:
raw_response = invoke_bedrock_agent(user_prompt)
response = extract_response_text(raw_response)
return render_template('index.html', response=response)
if __name__ == '__main__':
app.run(debug=True)
And the index.html file, which provides the user interface:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bedrock Agent Interface</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
.container {
display: flex;
flex-direction: column;
gap: 20px;
}
textarea {
width: 100%;
min-height: 100px;
padding: 10px;
margin: 10px 0;
}
button {
padding: 10px 20px;
background-color: #007bff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
.response-box {
border: 1px solid #ccc;
padding: 10px;
min-height: 100px;
white-space: pre-wrap;
}
</style>
</head>
<body>
<div class="container">
<h1>Bedrock Agent Interface</h1>
<form method="POST">
<label for="prompt">Enter your prompt:</label>
<textarea name="prompt" id="prompt" required>{{ request.form.get('prompt', '') }}</textarea>
<button type="submit">Submit</button>
</form>
{% if response %}
<div>
<h2>Agent Response:</h2>
<div class="response-box">{{ response }}</div>
</div>
{% endif %}
</div>
</body>
</html>
Step 4: Test the Web App
Navigate to your project directory in the terminal and run the Flask application:
python app.py
This command starts a local development server, typically accessible at http://localhost:5000 in your web browser.
Try entering prompts like “How many ec2 servers I have” or “Create an ec2 server of type t2.micro in ap-south-1 region.” Observe how the web application interacts with your Bedrock Agent and displays the responses, demonstrating seamless, natural language-driven AWS management.
Step 5: Clean Up Your Resources
To avoid incurring unnecessary AWS costs, remember to clean up all resources created during this tutorial:
- Terminate any EC2 instances launched for testing.
- Delete the Bedrock Agent and its associated Lambda functions and roles.
Step 6: Additional Considerations
- Prompt Quality: The effectiveness of your agent heavily relies on the clarity and specificity of the user prompts. Crafting well-defined instructions significantly improves the agent’s ability to understand intent and select the correct tools.
- Throttling: Be aware of service quotas for LLMs and AWS services. You might encounter throttling errors if requests exceed these limits; implement retry mechanisms where appropriate.
- User Interface (UI) Design: Custom web applications built on Bedrock Agents represent a compelling use case for enhancing operational efficiency. They democratize access to AWS operations, allowing users without deep technical expertise to perform predefined tasks through an intuitive interface.
- Customization vs. Amazon Q: While Amazon Q offers general AWS assistance, Bedrock Agents with custom action groups and knowledge bases provide unparalleled tailoring. A custom web application built atop Bedrock Agents allows for highly specialized, integrated, and controlled operational tools that precisely align with an organization’s unique environment, processes, and user needs, far exceeding generic console-level assistants.
This article has demonstrated the immense potential of integrating Amazon Bedrock Agents with custom web interfaces to create intelligent, natural language-driven automation for AWS operations. By simplifying complex tasks and making cloud management more accessible, organizations can achieve greater efficiency and empower their teams like never before.