Building a Calculator Agent with Amazon Bedrock AgentCore
Deploy production-ready AI agents in minutes with Amazon Bedrock AgentCore Runtime.
What is AgentCore?
Amazon Bedrock AgentCore is a suite of services that simplifies deploying AI agents to production. Instead of weeks configuring infrastructure, you get production-ready agents with just 2 commands.
Amazon Bedrock AgentCore Services
- Amazon Bedrock AgentCore Identity - Secure credential management for API keys and tokens
- Amazon Bedrock AgentCore Memory - State persistence and conversation history
- Amazon Bedrock AgentCore Code Interpreter - Secure code execution sandbox
- Amazon Bedrock AgentCore Browser - Cloud browser automation
- Amazon Bedrock AgentCore Gateway - API management and tool discovery
- Amazon BedrockAgentCore Observability - Monitoring, tracing, and debugging
Calculator Agent with AgentCore Runtime
This project demonstrates AgentCore Runtime by building a calculator agent that handles mathematical computations using the Strands Agents framework with automatic scaling and session isolation.
Key Benefits
- 10 minutes from code to production endpoint
- Serverless - no infrastructure management
- Auto-scaling - handles traffic spikes automatically
- Session-aware - maintains conversation context across invocations
- Built-in security - AWS security best practices included
Core Components
Amazon Bedrock AgentCore Runtime: Provides a secure serverless runtime for deploying and scaling dynamic agents using any framework with any model provider.
Strands Agents: An agent framework that build production-ready, multi-agent AI systems in a few lines of code.
Prerequisites
Before you begin, verify that you have:
- AWS Account
- Python 3.10+ environment
- AWS CLI configured with
aws configure - AWS Permissions: Attach the BedrockAgentCoreFullAccess AWS managed policy and the starter toolkit policy
- Model Access: Anthropic Claude 3.5 Haiku (or the model of your preference) enabled in the Amazon Bedrock console
New AWS customers receive up to $200 in credits
Get started at no cost with the AWS Free Tier.
Step 1: AWS Account Setup
Create AWS Account and Configure Permissions
If you're using admin access, you can skip the detailed permissions setup. Otherwise, follow these steps to create an AWS IAM user and attach the BedrockAgentCoreFullAccess AWS managed policy.
Configure the AWS CLI
Run the following command in your terminal:
aws configureEnter your credentials:
AWS Access Key ID [None]: (from your downloaded CSV file)AWS Secret Access Key [None]: (from your downloaded CSV file)Default region name [None]: (your AWS Region)Default output format [None]:json
Step 2: Set Up Project and Install Dependencies
Create a project folder and install the required packages:
mkdir agentcore-calculator-agent
cd agentcore-calculator-agent
python3 -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activateInstall the necessary dependencies:
pip install --upgrade pip
pip install bedrock-agentcore strands-agents bedrock-agentcore-starter-toolkit strands-agents-toolsRequired packages:
bedrock-agentcore- Amazon Bedrock AgentCore SDKstrands-agents- Strands Agents SDKbedrock-agentcore-starter-toolkit- Amazon Bedrock AgentCore starter toolkitstrands-agents-tools- Tools for Strands Agents including calculator functionality
Verify installation:
agentcore --helpStep 3: Create Your Agent
Create a deployment folder to keep your agent code organized:
mkdir deployment
cd deploymentCreate my_agent.py:
from bedrock_agentcore import BedrockAgentCoreApp
from strands import Agent
import os
from strands_tools import calculator
# System prompt for the agent
SYSTEM_PROMPT = "You are a helpful assistant that can perform calculations. Use the calculate tool for any math problems."
# Model configuration from environment variable
MODEL_ID = os.getenv("MODEL_ID", "us.anthropic.claude-3-5-haiku-20241022-v1:0")
# Global agent instance for reuse across invocations
agent = None
def create_agent(tools):
"""Create agent with lazy loading pattern for performance"""
global agent
if agent is None:
agent = Agent(
model=MODEL_ID,
tools=[tools],
system_prompt=SYSTEM_PROMPT
)
return agent
# Initialize the Bedrock Agent Core application
app = BedrockAgentCoreApp()
@app.entrypoint
def invoke(payload):
"""AgentCore Runtime entry point"""
agent = create_agent(calculator)
prompt = payload.get("prompt", "Hello!")
result = agent(prompt)
return {
"response": result.message.get('content', [{}])[0].get('text', str(result))
}
if __name__ == "__main__":
app.run()Create requirements.txt:
bedrock-agentcore
bedrock-agentcore-starter-toolkit
strands-agents
strands-agents-toolsStep 4: Understanding the Calculator Agent Code
The agent implements several key components:
AgentCore Runtime Entry Point
The @app.entrypoint decorator makes your agent deployable to AgentCore Runtime. This is the only difference between a local script and a cloud-deployed agent.
Agent Initialization with Lazy Loading
The agent is initialized once per session to preserve state and avoid performance costs. Amazon Bedrock AgentCore Runtime provides dedicated containers with up to 8 hours lifetime or 15 minutes of inactivity timeout.
Calculator Tool
The agent includes a calculator tool from strands-tools for performing mathematical operations.
Step 5: Test the agent code locally
python my_agent.pyTest
# In another terminal, test with curl
curl -X POST http://localhost:8080/invocations \
-H "Content-Type: application/json" \
-d '{
"prompt": "Hello world!"
}'Step 6: Configure and Deploy to AgentCore Runtime
The AgentCore starter toolkit will automatically create all necessary AWS resources for you, including IAM roles with least-privilege permissions, following AWS security best practices. This is much safer than creating overly permissive roles manually.
Configure the Agent
agentcore configure -e my_agent.pyWhen prompted:
- Execution Role: Press Enter to auto-create a role with minimal required permissions
- ECR Repository: Press Enter to auto-create
- Requirements File: Confirm the detected requirements.txt
- OAuth Configuration: Type
no - Request Header Allowlist: Type
no
Deploy the Agent
agentcore launchThis command:
- Creates an IAM execution role with minimal required permissions
- Builds your container using AWS CodeBuild (no Docker required locally)
- Creates Amazon ECR repository
- Deploys your agent to Amazon Bedrock AgentCore Runtime
- Configures CloudWatch logging
Note the Agent ARN from the output - you'll need it for programmatic invocation.
Check Deployment Status
agentcore statusFind Your Resources
View your resources in the AWS Console:
| Resource | Location |
|---|---|
| Agent Logs | CloudWatch → Log groups → /aws/bedrock-agentcore/runtimes/{agent-id}-DEFAULT |
| Container Images | ECR → Repositories → bedrock-agentcore-{agent-name} |
| Build Logs | CodeBuild → Build history |
| IAM Role | IAM → Roles → Search for "BedrockAgentCore" |
Step 7: Test Your Deployed Agent
Simple Invocation
Test your deployed agent with the simplest possible command:
agentcore invoke '{"prompt": "What is 50 plus 30?"}'Test Conversation Memory
Test that the agent maintains context within a session:
agentcore invoke '{"prompt": "Now multiply that result by 2"}'AgentCore Runtime automatically provides session isolation and memory management.
Step 8: Invoke from Production Applications
For production applications, use the InvokeAgentRuntime operation from AWS SDK.
# Invoke the agent
response = client.invoke_agent_runtime(
agentRuntimeArn=agent_arn,
runtimeSessionId=session_id, #Must be 33+ characters
payload=payload,
qualifier="DEFAULT"
)Use invoke_agent.py application to test the agent.
Run the script to test both calculation capabilities and memory:
# Set your agent ARN (get from agentcore status)
export AGENT_ARN="YOUR-ARN"
# Run the test script
python invoke_agent.pyThe script will test:
- Basic calculations
- Memory persistence within a session
- Mathematical operations
- Conversation context retention
Key Points for Production Use:
- Agent ARN: Get this from
agentcore statusoutput - Session IDs: Must be 33+ characters for session persistence
- Authentication: Uses your AWS credentials (IAM roles, access keys, etc.)
For more troubleshooting information, see Troubleshoot Amazon Bedrock AgentCore Runtime.
Step 9: Clean Up
When you're done experimenting, clean up all resources:
agentcore destroyThis removes:
- AgentCore Runtime deployment
- ECR repository and images
- Auto-created IAM roles
- CloudWatch log groups
Resources
Documentation
- What is Amazon Bedrock AgentCore?
- AgentCore Runtime How It Works
- AgentCore Memory Guide
- AgentCore Gateway Documentation
- Programmatic Agent Invocation