How to build and deploy an AI Agent API using Amazon Bedrock on AWS
Here's a step-by-step guide on how to build and deploy an AI Agent API using Amazon Bedrock on AWS. Bedrock allows you to build generative AI applications using foundation models from providers like Anthropic, AI21, Stability AI, etc., without managing infrastructure.
🚀 Overview
-
Set Up Your AWS Environment
-
Create a Bedrock Agent
-
Create a Lambda Function (optional logic layer)
-
Build an API Gateway Endpoint
-
Deploy and Test Your API
1. 🔧 Set Up AWS Environment
Before starting:
-
Ensure you have an AWS account.
-
Enable Amazon Bedrock in your region (e.g.,
us-east-1
). -
Set up your IAM roles with access to:
-
AmazonBedrockFullAccess
-
AmazonAPIGatewayInvokeFullAccess
-
AWSLambda_FullAccess
(if using Lambda)
-
Install CLI (Optional for scripting)
aws configure
2. 🤖 Create an AI Agent with Amazon Bedrock
-
Go to Amazon Bedrock Console
-
Choose Agents > Create Agent
-
Configure:
-
Agent name
-
Choose Foundation Model (e.g.,
Anthropic Claude
,Titan
) -
Define instructions: This is the prompt that guides your agent.
-
Choose or create an IAM role with access to invoke Bedrock.
-
-
Click Create. Once it's deployed, note the Agent ID and Alias ID.
3. 🔁 Optional: Create a Lambda Function
Use this if you want to preprocess requests or securely pass requests to Bedrock.
import boto3
import json
bedrock = boto3.client('bedrock-agent-runtime', region_name='us-east-1')
def lambda_handler(event, context):
user_input = json.loads(event['body'])['input']
response = bedrock.invoke_agent(
agentId='your-agent-id',
agentAliasId='your-alias-id',
sessionId='example-session',
input={
'text': user_input
}
)
output = response['completion']['content']
return {
'statusCode': 200,
'body': json.dumps({'response': output})
}
4. 🌐 Build an API Gateway Endpoint
Using API Gateway (HTTP API):
-
Go to API Gateway Console
-
Create a new HTTP API
-
Choose Add integration > Lambda function
-
Deploy and note your Invoke URL
Now your API endpoint is public and callable like:
curl -X POST https://<your-api-url>/invoke \
-d '{"input": "What is the weather today?"}'
5. ✅ Deploy and Test
Make sure:
-
Your Lambda has permission to call Bedrock.
-
Bedrock agent is in an ACTIVE state.
-
You're handling sessions and errors in Lambda.
🧠 Bonus: Call Bedrock Directly Without Lambda
If you don't want Lambda, you can call Bedrock from your backend directly:
import boto3
client = boto3.client("bedrock-agent-runtime")
response = client.invoke_agent(
agentId="your-agent-id",
agentAliasId="your-alias-id",
sessionId="session-id",
input={"text": "Tell me a joke."}
)
Comments
Post a Comment