Skip to content

A project to develop code for testing AWS AgentCore

Notifications You must be signed in to change notification settings

trackit/agentcore-demo

Repository files navigation

LangGraph Math Agent for AWS Bedrock AgentCore

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.

Features

  • 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

Prerequisites

  • AWS Account with Bedrock AgentCore access
  • Python 3.8+
  • AWS CLI configured with appropriate credentials
  • AgentCore CLI installed and configured

Getting Started with AgentCore

For more details, refer to the Bedrock AgentCore Starter Toolkit documentation.

1. Environment Setup

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

2. Configuration

# 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-1

3. Initialization

The agentcore create command generates the necessary configuration files, such as .bedrock_agentcore.yaml.

agentcore create

Note

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

Installation

Agent Dependencies

  1. Install agent dependencies:
cd langgraph-math-agent
pip install -r requirements.txt
cd ..

Python Invocation Script Dependencies

  1. Install dependencies for the Python invocation script:
# From the root directory
pip install -r requirements.txt

Agent Deployment

  1. 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
  1. Update the AGENT_ARN in your Python scripts with your deployed agent's ARN

Usage

Using AgentCore CLI

The agentcore invoke command allows you to quickly test the agent from the command line.

Basic Calculation

agentcore invoke '{"prompt": "Calculate 25 + 37"}'

Data Analysis

agentcore invoke '{"prompt": "What is the average of 10, 20, 30, 40, 50?"}'

Conversational Style

agentcore invoke '{"prompt": "Hey, I need help with some quick math. Can you add 156 and 289 for me?"}'

Story-Based Problem

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?"}'

Real-World Scenario

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?"}'

Complex Calculation

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."}'

Comparative Analysis

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?"}'

Multiplication

agentcore invoke '{"prompt": "Multiply 15 by 23"}'

Division

agentcore invoke '{"prompt": "What is 144 divided by 12?"}'

Using Python (boto3)

You can also invoke the agent programmatically using Python and boto3. See invoke_w_payload.py for a complete example.

Basic 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))

More Python Examples

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))

Visualizing the Graph Structure

You can visualize the LangGraph structure (nodes, edges, state) in two ways:

Via AgentCore Invocation

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"

Agent Workflow

The agent uses a LangGraph state graph with the following nodes:

  1. Classify: Determines if the task is math, data analysis, or general
  2. Calculate: Performs mathematical operations
  3. Analyze: Performs statistical analysis on data
  4. General: Handles general queries
  5. 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

Project Structure

.
├── 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

Dependencies

  • langgraph: For building state graphs
  • langchain: For LLM integration
  • langchain-aws: For AWS Bedrock integration
  • bedrock-agentcore: For AgentCore runtime
  • bedrock-agentcore-starter-toolkit: For AgentCore development tools

Notes

  • Make sure your AWS credentials are properly configured
  • Update the AGENT_ARN in 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

About

A project to develop code for testing AWS AgentCore

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages