* feat(cdk): reorganize CDK samples into python/ and typescript/ folders - Move existing Python CDK samples to cdk/python/ - Add TypeScript CDK samples folder with knowledge-base-rag-agent - Update cdk/README.md with language comparison table - Update parent README with new paths and TypeScript mention - Add cdk/python/README.md for Python-specific guidance 🤖 Assisted by Amazon Q Developer * docs: add Jerad Engebreth to CONTRIBUTORS.md 🤖 Assisted by Amazon Q Developer * fix(cdk/typescript): document known vulnerabilities and fix npm workspaces build - Add Known Dependency Vulnerabilities section to README documenting upstream issues in aws-amplify (fast-xml-parser, lodash) - Add build/test scripts to Lambda layer package.json to fix npm workspaces build command 🤖 Assisted by Amazon Q Developer * fix(security): add HEALTHCHECK and non-root USER to Dockerfile - Add HEALTHCHECK instruction for container orchestration - Create non-root appuser for security best practices - Addresses CKV_DOCKER_2, CKV_DOCKER_3 security findings * fix(security): address CodeQL findings for insecure randomness and HTML sanitization - Replace Math.random() with crypto.randomBytes() for session ID generation - Use iterative sanitization loop to handle nested/obfuscated HTML tags - Addresses CodeQL insecure randomness and incomplete sanitization findings * fix(security): improve HTML sanitization to address CodeQL findings - Handle closing tags with spaces like </script > - Add data: and vbscript: URL scheme blocking - Use tag-based approach instead of content-matching regex - Add more dangerous tags (form, input, button, etc.) * remove unused import * fix(lint): fix import ordering and remove extra blank lines - Sort imports alphabetically (logging before os) - Remove extra blank line in knowledge_base.py - Consistent import grouping (stdlib, then third-party) * fix(security): use HTML entity encoding instead of regex-based sanitization - Replace regex-based tag stripping with HTML entity encoding - Encode all special characters (&, <, >, ", ', /, `, =) - This approach is CodeQL-compliant and more secure - Regex-based HTML filtering is inherently flawed * fix(lint): add __all__ to fix F401 unused import warnings - Add __all__ exports to infra_utils/__init__.py files - Explicitly declares AgentCoreRole as public API * style: apply ruff formatting to all Python files in 04-infrastructure-as-code - Format 32 Python files with ruff - Includes CDK Python samples, Terraform samples, and TypeScript agent code * refactor: rename project from bedrock-agentcore-template to knowledge-base-rag-agent - Update package.json names for root and infrastructure packages - Update README and docs with new project name and paths - Update CloudWatch, SNS, KMS, and Cognito resource names - Regenerate package-lock.json with new package names * refactor: complete project rename to knowledge-base-rag-agent - Update README title and all documentation headers - Update TypeScript stack descriptions and resource names - Update Python agent module docstrings - Update Dockerfile header comment - Update Lambda function package description - Rename runtime to knowledge_base_rag_agent - Rename memory to knowledge_base_rag_agent_memory - Rename API to Knowledge Base RAG Agent API - Update Secrets Manager secret name * fix: correct Docker references and fix Lambda bundling - Update README and docs to clarify Docker is for AgentCore Runtime container, not Lambda bundling - Add @aws-lambda-powertools/logger dependency for Lambda function - Add esbuild as dev dependency for NodejsFunction bundling - Fix S3 bucket deployment to use single deployment with auto content-type detection - Deploy config.json separately with prune:false to preserve other files --------- Co-authored-by: Jerad Engebreth <awsjerad@amazon.com>
End-to-End Weather Agent with Tools and Memory - CDK
This CDK stack deploys a complete Amazon Bedrock AgentCore Runtime with a sophisticated weather-based activity planning agent. This demonstrates the full power of AgentCore by integrating Browser tool, Code Interpreter, Memory, and S3 storage in a single deployment.
Table of Contents
- Overview
- Architecture
- Prerequisites
- Deployment
- Testing
- Sample Queries
- How It Works
- Cleanup
- Troubleshooting
Overview
This CDK stack creates a comprehensive AgentCore deployment that showcases:
Core Components
- AgentCore Runtime: Hosts a Strands agent with multiple tools
- Browser Tool: Web automation for scraping weather data from weather.gov
- Code Interpreter: Python code execution for weather analysis
- Memory: Stores user activity preferences
- S3 Bucket: Stores generated activity recommendations
- ECR Repository: Container image storage
- IAM Roles: Comprehensive permissions for all components
Agent Capabilities
The Weather Activity Planner agent can:
- Scrape Weather Data: Uses browser automation to fetch 8-day forecasts from weather.gov
- Analyze Weather: Generates and executes Python code to classify days as GOOD/OK/POOR
- Retrieve Preferences: Accesses user activity preferences from memory
- Generate Recommendations: Creates personalized activity suggestions based on weather and preferences
- Store Results: Saves recommendations as Markdown files in S3
Use Cases
- Weather-based activity planning
- Automated web scraping and data analysis
- Multi-tool agent orchestration
- Memory-driven personalization
- Asynchronous task processing
Architecture
The architecture demonstrates a complete AgentCore deployment with multiple integrated tools:
Core Components:
- User: Sends weather-based activity planning queries
- AWS CodeBuild: Builds the ARM64 Docker container image with the agent code
- Amazon ECR Repository: Stores the container image
- AgentCore Runtime: Hosts the Weather Activity Planner Agent
- Weather Agent: Strands agent that orchestrates multiple tools
- Invokes Amazon Bedrock LLMs for reasoning and code generation
- Browser Tool: Web automation for scraping weather data from weather.gov
- Code Interpreter Tool: Executes Python code for weather analysis
- Memory: Stores user activity preferences (30-day retention)
- S3 Bucket: Stores generated activity recommendations
- IAM Roles: Comprehensive permissions for all components
Workflow:
- User sends query: "What should I do this weekend in Richmond VA?"
- Agent extracts city and uses Browser Tool to scrape 8-day forecast
- Agent generates Python code and uses Code Interpreter to classify weather
- Agent retrieves user preferences from Memory
- Agent generates personalized recommendations
- Agent stores results in S3 bucket using use_aws tool
Prerequisites
AWS Account Setup
-
AWS Account: You need an active AWS account with appropriate permissions
-
AWS CLI: Install and configure AWS CLI with your credentials
aws configure -
Python 3.10+ and AWS CDK v2 installed
# Install CDK npm install -g aws-cdk # Verify installation cdk --version -
CDK version 2.218.0 or later (for BedrockAgentCore support)
-
Bedrock Model Access: Enable access to Amazon Bedrock models in your AWS region
-
Required Permissions: Your AWS user/role needs permissions for:
- CloudFormation stack operations
- ECR repository management
- IAM role creation
- Lambda function creation
- CodeBuild project creation
- BedrockAgentCore resource creation (Runtime, Browser, CodeInterpreter, Memory)
- S3 bucket operations (for CDK assets and results storage)
Deployment
CDK vs CloudFormation
This is the CDK version of the end-to-end weather agent. If you prefer CloudFormation, see the CloudFormation version.
Option 1: Quick Deploy (Recommended)
# Install dependencies
pip install -r requirements.txt
# Bootstrap CDK (first time only)
cdk bootstrap
# Deploy
cdk deploy
Option 2: Step by Step
# 1. Create and activate Python virtual environment
python3 -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
# 2. Install Python dependencies
pip install -r requirements.txt
# 3. Bootstrap CDK in your account/region (first time only)
cdk bootstrap
# 4. Synthesize the CloudFormation template (optional)
cdk synth
# 5. Deploy the stack
cdk deploy --require-approval never
# 6. Get outputs
cdk list
Deployment Time
- Expected Duration: 15-20 minutes
- Main Steps:
- Stack creation: ~2 minutes
- Docker image build (CodeBuild): ~10-12 minutes
- Runtime and tools provisioning: ~3-5 minutes
- Memory initialization: ~1 minute
Testing
Using AWS CLI
# Get the Runtime ARN from CDK outputs
RUNTIME_ARN=$(aws cloudformation describe-stacks \
--stack-name WeatherAgentDemo \
--region us-east-1 \
--query 'Stacks[0].Outputs[?OutputKey==`AgentRuntimeArn`].OutputValue' \
--output text)
# Get the S3 bucket name
BUCKET_NAME=$(aws cloudformation describe-stacks \
--stack-name WeatherAgentDemo \
--region us-east-1 \
--query 'Stacks[0].Outputs[?OutputKey==`ResultsBucketName`].OutputValue' \
--output text)
# Invoke the agent
aws bedrock-agentcore invoke-agent-runtime \
--agent-runtime-arn $RUNTIME_ARN \
--qualifier DEFAULT \
--payload $(echo '{"prompt": "What should I do this weekend in Richmond VA?"}' | base64) \
response.json
# View the immediate response
cat response.json
# Wait a few minutes for processing, then check S3 for results
aws s3 ls s3://$BUCKET_NAME/
# Download the results
aws s3 cp s3://$BUCKET_NAME/results.md ./results.md
cat results.md
Using AWS Console
- Navigate to Bedrock AgentCore Console
- Go to "Runtimes" in the left navigation
- Find your runtime (name starts with
WeatherAgentDemo_) - Click on the runtime name
- Click "Test" button
- Enter test payload:
{ "prompt": "What should I do this weekend in Richmond VA?" } - Click "Invoke"
- View the immediate response
- Wait 2-3 minutes for background processing
- Navigate to S3 Console to download results.md from the results bucket
Sample Queries
Try these queries to test the weather agent:
-
Weekend Planning:
{"prompt": "What should I do this weekend in Richmond VA?"} -
Specific City:
{"prompt": "Plan activities for next week in San Francisco"} -
Different Location:
{"prompt": "What outdoor activities can I do in Seattle this week?"} -
Vacation Planning:
{"prompt": "I'm visiting Austin next week. What should I plan based on the weather?"}
How It Works
Step-by-Step Workflow
-
User Query: "What should I do this weekend in Richmond VA?"
-
City Extraction: Agent extracts "Richmond VA" from the query
-
Weather Scraping (Browser Tool):
- Navigates to weather.gov
- Searches for Richmond VA
- Clicks "Printable Forecast"
- Extracts 8-day forecast data (date, high, low, conditions, wind, precipitation)
- Returns JSON array of weather data
-
Code Generation (LLM):
- Agent generates Python code to classify weather days
- Classification rules:
- GOOD: 65-80°F, clear, no rain
- OK: 55-85°F, partly cloudy, slight rain
- POOR: <55°F or >85°F, cloudy/rainy
-
Code Execution (Code Interpreter):
- Executes the generated Python code
- Returns list of tuples:
[('2025-09-16', 'GOOD'), ('2025-09-17', 'OK'), ...]
-
Preference Retrieval (Memory):
- Fetches user activity preferences from memory
- Preferences stored by weather type:
{ "good_weather": ["hiking", "beach volleyball", "outdoor picnic"], "ok_weather": ["walking tours", "outdoor dining", "park visits"], "poor_weather": ["indoor museums", "shopping", "restaurants"] }
-
Recommendation Generation (LLM):
- Combines weather analysis with user preferences
- Creates day-by-day activity recommendations
- Formats as Markdown document
-
Storage (S3 via use_aws tool):
- Saves recommendations to S3 bucket as
results.md - User can download and review recommendations
- Saves recommendations to S3 bucket as
Asynchronous Processing
The agent runs asynchronously to handle long-running tasks:
- Immediate response: "Processing started..."
- Background processing: Completes all steps
- Results available in S3 after ~2-3 minutes
Cleanup
Using CDK (Recommended)
cdk destroy
Using AWS CLI
# Step 1: Empty the S3 bucket (required before deletion)
BUCKET_NAME=$(aws cloudformation describe-stacks \
--stack-name WeatherAgentDemo \
--region us-east-1 \
--query 'Stacks[0].Outputs[?OutputKey==`ResultsBucketName`].OutputValue' \
--output text)
aws s3 rm s3://$BUCKET_NAME --recursive
# Step 2: Terminate any active browser sessions
# Get the Browser ID
BROWSER_ID=$(aws cloudformation describe-stacks \
--stack-name WeatherAgentDemo \
--region us-east-1 \
--query 'Stacks[0].Outputs[?OutputKey==`BrowserId`].OutputValue' \
--output text)
# List active sessions
aws bedrock-agentcore list-browser-sessions \
--browser-id $BROWSER_ID \
--region us-east-1
# Terminate each active session (replace SESSION_ID with actual session ID from list command)
# Repeat this command for each active session
aws bedrock-agentcore terminate-browser-session \
--browser-id $BROWSER_ID \
--session-id SESSION_ID \
--region us-east-1
# Step 3: Delete the stack
aws cloudformation delete-stack \
--stack-name WeatherAgentDemo \
--region us-east-1
# Wait for deletion to complete
aws cloudformation wait stack-delete-complete \
--stack-name WeatherAgentDemo \
--region us-east-1
Important: Browser sessions are automatically created when the agent uses the browser tool. Always terminate active sessions before deleting the stack to avoid deletion failures.
Using AWS Console
- Navigate to S3 Console
- Find the bucket (name format:
<stack-name>-results-<account-id>) - Empty the bucket
- Navigate to Bedrock AgentCore Console
- Go to "Browsers" in the left navigation
- Find your browser (name starts with
WeatherAgentDemo_browser) - Click on the browser name
- In the "Sessions" tab, terminate any active sessions
- Navigate to CloudFormation Console
- Select the
WeatherAgentDemostack - Click "Delete"
- Confirm deletion
Troubleshooting
CDK Bootstrap Required
If you see bootstrap errors:
cdk bootstrap aws://ACCOUNT-NUMBER/REGION
Permission Issues
Ensure your IAM user/role has:
CDKToolkitpermissions or equivalent- Permissions to create all resources in the stack
iam:PassRolefor service roles
Python Dependencies
Install dependencies in the project directory:
pip install -r requirements.txt
Build Failures
Check CodeBuild logs in the AWS Console:
- Go to CodeBuild console
- Find the build project (name contains "weather-agent-build")
- Check build history and logs
Browser Session Issues
If deployment fails due to browser sessions:
- List active sessions using AWS CLI
- Terminate all active sessions
- Retry deployment or cleanup
Memory Initialization Issues
If memory initialization fails:
- Check Lambda function logs in CloudWatch
- Verify IAM permissions for memory access
- Retry deployment