A demonstration LangGraph agent built on AWS Bedrock AgentCore that performs mathematical calculations and data analysis tasks. The agent uses a state graph workflow to classify tasks, perform calculations, analyze data, and format responses.
- Task Classification: Automatically detects math calculations, data analysis, or general queries
- Mathematical Operations: Supports addition, subtraction, multiplication, division, and complex expressions
- Data Analysis: Calculates averages, means, medians, counts, and ranges
- State-Based Workflow: Uses LangGraph to manage agent state and routing
- AWS Account with Bedrock AgentCore access
- Python 3.8+
- AWS CLI configured with appropriate credentials
- AgentCore CLI installed and configured
For more details, refer to the Bedrock AgentCore Starter Toolkit documentation.
It is recommended to run these commands in a Python environment. If you are on Windows, ensure you run these commands inside WSL (Ubuntu distro).
# Create and activate a virtual environment
python3 -m venv .venv
source .venv/bin/activate
# Upgrade pip and install the toolkit
pip install --upgrade pip
pip install bedrock-agentcore-starter-toolkit# Set your AWS profile
export AWS_PROFILE=sandbox # or your profile name, sandbox is just an example
# Configure the AgentCore region
agentcore configure --region us-east-1The agentcore create command generates the necessary configuration files, such as .bedrock_agentcore.yaml.
agentcore createNote
This repository already contains the required .bedrock_agentcore.yaml file. If the file is present, you can skip agentcore create and proceed directly to deployment using:
agentcore deploy- Install agent dependencies:
cd langgraph-math-agent
pip install -r requirements.txt
cd ..- Install dependencies for the Python invocation script:
# From the root directory
pip install -r requirements.txt- Deploy the agent to AWS Bedrock AgentCore:
# If .bedrock_agentcore.yaml exists
agentcore deploy
# If setting up for the first time
agentcore create
agentcore deploy- Update the
AGENT_ARNin your Python scripts with your deployed agent's ARN
The agentcore invoke command allows you to quickly test the agent from the command line.
agentcore invoke '{"prompt": "Calculate 25 + 37"}'agentcore invoke '{"prompt": "What is the average of 10, 20, 30, 40, 50?"}'agentcore invoke '{"prompt": "Hey, I need help with some quick math. Can you add 156 and 289 for me?"}'agentcore invoke '{"prompt": "I have 3 boxes with 12 apples each, and my friend gave me 15 more apples. How many apples do I have in total?"}'agentcore invoke '{"prompt": "My restaurant sold 45 meals on Monday, 67 on Tuesday, 52 on Wednesday, 89 on Thursday, and 110 on Friday. What was my average daily sales?"}'agentcore invoke '{"prompt": "I earn $3500 per month. My rent is $1200, groceries are $400, and utilities are $150. Calculate my remaining balance and tell me the average I spend per day."}'agentcore invoke '{"prompt": "Team A scored: 85, 92, 78, 95, 88. Team B scored: 80, 90, 85, 87, 93. Which team has a better average?"}'agentcore invoke '{"prompt": "Multiply 15 by 23"}'agentcore invoke '{"prompt": "What is 144 divided by 12?"}'You can also invoke the agent programmatically using Python and boto3. See invoke_w_payload.py for a complete example.
import json
import uuid
import boto3
# Replace with your Agent ARN
agent_arn = "arn:aws:bedrock-agentcore:us-east-1:YOUR_ACCOUNT:runtime/YOUR_AGENT_ID"
prompt = "Calculate 100 + 250"
# Initialize the Amazon Bedrock AgentCore client
agent_core_client = boto3.client('bedrock-agentcore', region_name='us-east-1')
# Prepare the payload
payload = json.dumps({"prompt": prompt}).encode()
# Invoke the agent
response = agent_core_client.invoke_agent_runtime(
agentRuntimeArn=agent_arn,
runtimeSessionId=str(uuid.uuid4()),
payload=payload,
qualifier="DEFAULT"
)
# Parse streaming response
content = []
for chunk in response.get("response", []):
content.append(chunk.decode('utf-8'))
# Parse and print the result
result = json.loads(''.join(content))
print(result.get('result', result))Note: All examples assume you have initialized the client as shown in the Basic Example above:
import json
import uuid
import boto3
agent_arn = "arn:aws:bedrock-agentcore:us-east-1:YOUR_ACCOUNT:runtime/YOUR_AGENT_ID"
agent_core_client = boto3.client('bedrock-agentcore', region_name='us-east-1')Basic Calculation:
payload = json.dumps({"prompt": "Calculate 25 + 37"}).encode()
response = agent_core_client.invoke_agent_runtime(
agentRuntimeArn=agent_arn,
runtimeSessionId=str(uuid.uuid4()),
payload=payload,
qualifier="DEFAULT"
)
content = []
for chunk in response.get("response", []):
content.append(chunk.decode('utf-8'))
result = json.loads(''.join(content))
print(result.get('result', result))Data Analysis:
payload = json.dumps({"prompt": "What is the average of 10, 20, 30, 40, 50?"}).encode()
response = agent_core_client.invoke_agent_runtime(
agentRuntimeArn=agent_arn,
runtimeSessionId=str(uuid.uuid4()),
payload=payload,
qualifier="DEFAULT"
)
content = []
for chunk in response.get("response", []):
content.append(chunk.decode('utf-8'))
result = json.loads(''.join(content))
print(result.get('result', result))Conversational Style:
payload = json.dumps({"prompt": "Hey, I need help with some quick math. Can you add 156 and 289 for me?"}).encode()
response = agent_core_client.invoke_agent_runtime(
agentRuntimeArn=agent_arn,
runtimeSessionId=str(uuid.uuid4()),
payload=payload,
qualifier="DEFAULT"
)
content = []
for chunk in response.get("response", []):
content.append(chunk.decode('utf-8'))
result = json.loads(''.join(content))
print(result.get('result', result))Story-Based Problem:
payload = json.dumps({"prompt": "I have 3 boxes with 12 apples each, and my friend gave me 15 more apples. How many apples do I have in total?"}).encode()
response = agent_core_client.invoke_agent_runtime(
agentRuntimeArn=agent_arn,
runtimeSessionId=str(uuid.uuid4()),
payload=payload,
qualifier="DEFAULT"
)
content = []
for chunk in response.get("response", []):
content.append(chunk.decode('utf-8'))
result = json.loads(''.join(content))
print(result.get('result', result))Real-World Scenario:
payload = json.dumps({"prompt": "My restaurant sold 45 meals on Monday, 67 on Tuesday, 52 on Wednesday, 89 on Thursday, and 110 on Friday. What was my average daily sales?"}).encode()
response = agent_core_client.invoke_agent_runtime(
agentRuntimeArn=agent_arn,
runtimeSessionId=str(uuid.uuid4()),
payload=payload,
qualifier="DEFAULT"
)
content = []
for chunk in response.get("response", []):
content.append(chunk.decode('utf-8'))
result = json.loads(''.join(content))
print(result.get('result', result))Complex Calculation:
payload = json.dumps({"prompt": "I earn $3500 per month. My rent is $1200, groceries are $400, and utilities are $150. Calculate my remaining balance and tell me the average I spend per day."}).encode()
response = agent_core_client.invoke_agent_runtime(
agentRuntimeArn=agent_arn,
runtimeSessionId=str(uuid.uuid4()),
payload=payload,
qualifier="DEFAULT"
)
content = []
for chunk in response.get("response", []):
content.append(chunk.decode('utf-8'))
result = json.loads(''.join(content))
print(result.get('result', result))Comparative Analysis:
payload = json.dumps({"prompt": "Team A scored: 85, 92, 78, 95, 88. Team B scored: 80, 90, 85, 87, 93. Which team has a better average?"}).encode()
response = agent_core_client.invoke_agent_runtime(
agentRuntimeArn=agent_arn,
runtimeSessionId=str(uuid.uuid4()),
payload=payload,
qualifier="DEFAULT"
)
content = []
for chunk in response.get("response", []):
content.append(chunk.decode('utf-8'))
result = json.loads(''.join(content))
print(result.get('result', result))You can visualize the LangGraph structure (nodes, edges, state) in two ways:
Invoke the agent with a special prompt to get graph information:
Text Format (default - nicely formatted with boxes):
agentcore invoke '{"prompt": "show graph structure"}'JSON Format:
agentcore invoke '{"prompt": "show graph json"}'Mermaid Diagram Format (for rendering in markdown/viewers):
agentcore invoke '{"prompt": "show graph mermaid"}'Or using Python:
# Text format (default)
payload = json.dumps({"prompt": "show graph"}).encode()
# JSON format
payload = json.dumps({"prompt": "show graph json"}).encode()
# Mermaid format
payload = json.dumps({"prompt": "show graph mermaid"}).encode()
response = agent_core_client.invoke_agent_runtime(
agentRuntimeArn=agent_arn,
runtimeSessionId=str(uuid.uuid4()),
payload=payload,
qualifier="DEFAULT"
)
content = []
for chunk in response.get("response", []):
content.append(chunk.decode('utf-8'))
result = json.loads(''.join(content))
print(result.get('result', result))Supported prompts:
- "show graph" or "show graph structure" - Text format with visual boxes
- "show graph json" - JSON format for programmatic use
- "show graph mermaid" - Mermaid diagram code for rendering
- "visualize graph" - Same as "show graph"
- "graph structure" - Same as "show graph"
- "graph info" - Same as "show graph"
- "show nodes" - Same as "show graph"
- "show edges" - Same as "show graph"
The agent uses a LangGraph state graph with the following nodes:
- Classify: Determines if the task is math, data analysis, or general
- Calculate: Performs mathematical operations
- Analyze: Performs statistical analysis on data
- General: Handles general queries
- Format: Formats the final answer
The workflow routes requests based on the detected task type and returns formatted results.
Workflow Flow:
START → classify → [math|data|general] → calculate/analyze/general → format → END
.
├── langgraph-math-agent/
│ ├── main.py # Main agent implementation
│ ├── requirements.txt # Python dependencies
│ └── graph.md # Graph visualization
├── invoke_w_payload.py # Python invocation script
├── requirements.txt # Root dependencies (e.g., boto3)
└── README.md # This file
langgraph: For building state graphslangchain: For LLM integrationlangchain-aws: For AWS Bedrock integrationbedrock-agentcore: For AgentCore runtimebedrock-agentcore-starter-toolkit: For AgentCore development tools
- Make sure your AWS credentials are properly configured
- Update the
AGENT_ARNin your scripts with your actual agent ARN - The agent supports various mathematical operations and data analysis tasks
- For production use, consider adding error handling and input validation