1. Project Overview & Quickstart (strands-agents/computer_science_assistant.py)
computer_science_assistant.py
Open-source repository strands-agents/computer_science_assistant.py
Repository Details
- Repository: strands-agents/computer_science_assistant.py
- Primary Language: Code
Note: High-volume repository documentation is actively indexed and synchronized by YakaAI.
2. Official Technical Reference & Guides (strands-agents/docs)
File: README.md
Strands Agents Documentation
A model-driven approach to building AI agents in just a few lines of code.
[Documentation](https://strandsagents.com/)
โ [Samples](https://github.com/strands-agents/samples)
โ [Python SDK](https://github.com/strands-agents/sdk-python)
โ [Tools](https://github.com/strands-agents/tools)
โ [Agent Builder](https://github.com/strands-agents/agent-builder)
โ [MCP Server](https://github.com/strands-agents/mcp-server)This repository contains the documentation for the Strands Agents SDK, a simple yet powerful framework for building and running AI agents. The documentation is built using Astro with the Starlight theme and provides guides, examples, and API references.
The official documentation is available online at: https://strandsagents.com.
Local Development
Prerequisites
- Python 3.10+
- Node.js 20+, npm
Setup and Installation
npm installBuilding and Previewing
Generate the static site:
npm run buildRun a local development server at http://localhost:4321/:
npm run devWriting Documentation
Documentation lives in docs/ as Markdown files. The site structure is driven by src/config/navigation.yml (navigation) and rendered by Astro at build time.
- Pages are written in standard Markdown โ no Astro-specific syntax needed for content edits
- Use
<Tabs>/<Tab label="...">for language-switching code blocks (auto-imported, no import needed) - Use
--8<-- "path/to/file.ts:snippet_name"to include code snippets from external files - Link to other pages using relative file paths (e.g.
../tools/index.md) โ they resolve automatically - Link to API reference pages using the
@apishorthand:[@api/python/strands.agent.agent](#AgentResult)
For a full reference on customizations, components, and the migration status, see Site Architecture.
Using the `docs-` skills
The repo ships four agent skills that cover the documentation workflow: docs-planner, docs-audit, docs-writer, and docs-reviewer. They live under .agents/skills/ (with symlinks at .claude/skills/ and .kiro/skills/). See site/AGENTS.md for triggers and scopes.
Use them piecemeal when you already know the scope:
/docs-auditto assess a published page before rewriting./docs-writerto draft a new page or rewrite an existing one. Step 7 of the skill runsdocs-reviewerautomatically./docs-reviewer <draft>on its own when you want a voice/style sign-off without a rewrite./docs-plannerto prioritize the backlog when you don't yet know what to touch.
Or chain them with a /goal directive to drive a full update from a single SDK change. /goal is a usage convention, not a built-in command: you set the target and the workflow, the skills do the work. For example:
/goal https://github.com/strands-agents/sdk-typescript/commit/<sha>
1. /docs-planner: pick the top item touched by this commit.
2. /docs-audit: find issues on that page.
3. /docs-writer: fix them.
4. /docs-reviewer: sign off, or send back. Default to step 3 for voice/style/code
fixes; bounce to step 2 (or step 1) if the finding is structural. Cap retries at
3, then escalate.
The goal is complete when docs-reviewer returns a "Ship it" verdict and the
resulting commit is on a branch ready for PR.This pattern is useful when the change is narrow (one feature, one or two pages) and you want the skills to handle planner โ audit โ write โ review without you re-prompting at every step.
These skills are a work in progress. If outputs are wrong, insufficient, or unexpected, contribute updates to
.agents/.
Contributing โค๏ธ
We welcome contributions! See our Contributing Guide for details on:
- Reporting bugs & features
- Development setup
- Contributing via Pull Requests
- Code of Conduct
- Reporting of security issues
License
This project is licensed under the Apache License 2.0 - see the LICENSE file for details.
Security
See CONTRIBUTING for more information.
File: designs/README.md
Design Documents
This folder contains design documents for significant features and changes to Strands Agents. These documents capture the context, decision, and consequences of architectural choices.
For lightweight architecture decision records, see DECISIONS.md.
What is a design document?
A design document proposes a significant change or new feature. It describes the problem, proposed solution, and tradeoffs. Once approved and merged, it becomes an accepted design and part of the project's decision history.
When to write a design document
Write a design document for:
- New major features affecting multiple parts of the SDK
- Breaking changes to existing APIs
- Architectural changes requiring design discussion
- Large contributions (> 1 week of work)
- Features that introduce new concepts
Skip the design process for bug fixes, small improvements, documentation updates, and new extensions in your own repository.
How to submit a feature proposal
- Check the roadmap โ See if your idea aligns with our direction
- Fork the docs repository
- Create your design โ Add a new file:
designs/NNNN-feature-name.mdusing the template below - Submit a pull request โ We'll review and discuss
- Iterate based on feedback โ Address comments and questions
- Get approval โ Once approved and merged, implement the feature
- Reference the design โ Link to it in your implementation PR
Design document template
# [Feature Name]
**Status**: Proposed | Accepted | Deprecated | Superseded
**Date**: YYYY-MM-DD
**Issue**: Issue Link
## Context
What is the issue that we're seeing that is motivating this decision or change?
- What task are you trying to accomplish?
- What makes it difficult or impossible today?
- Who experiences this problem?
## Decision
What is the change that we're proposing and/or doing?
- Changes to the API (with code examples)
- How it integrates with existing features
- Expected behavior and usage patterns
## Developer Experience
Show what the developer experience looks like:
- Code examples showing typical usage
- Configuration or setup required
- Error messages and edge cases
## Alternatives Considered
What other approaches did you consider? Why did you choose this one?
## Consequences
What becomes easier or more difficult to do because of this change?
## Willingness to Implement
Are you willing to implement this if approved?
Yes / No / Maybe with guidanceAccepted Designs
No designs have been accepted yet.
File: site/docs/examples/typescript/structured_output/README.md
Structured Output Example
Demonstrates how to use structured output with Strands Agents to get type-safe, validated responses using Zod schemas.
Prerequisites
- Node.js 20+
- AWS credentials configured for Amazon Bedrock
Setup
npm installRun
npm startWhat It Covers
- Basic structured output with Zod schemas
- Complex nested schemas
See the Structured Output documentation for more details.
File: site/docs/examples/typescript/deploy_to_bedrock_agentcore/README.md
TypeScript Agent Deployment to Amazon Bedrock AgentCore Runtime
This example demonstrates deploying a TypeScript-based Strands agent to Amazon Bedrock AgentCore Runtime using Express and Docker.
What's Included
This example includes a complete, ready-to-deploy agent service with:
- Express-based HTTP server with required AgentCore endpoints (
/pingand/invocations) - Calculator tool demonstrating custom tool implementation
- Amazon Bedrock integration for LLM inference
- Docker configuration for containerized deployment via AgentCore
- IAM role automation scripts for AWS permissions setup
- Test script for invoking the deployed agent
Prerequisites
Before you begin, ensure you have:
- Node.js 20+
- Docker installed and running
- AWS CLI configured with valid credentials
- AWS account with appropriate permissions
- ECR repository access
Project Structure
.
โโโ index.ts # Main agent service implementation
โโโ invoke.ts # Test script for deployed agent
โโโ package.json # Node.js dependencies and scripts
โโโ tsconfig.json # TypeScript configuration
โโโ Dockerfile # Container configuration
โโโ create-iam-role.sh # IAM role automation script
โโโ README.md # This fileQuick Start
1. Install Dependencies
npm install2. Test Locally
Build and start the server:
npm run build
npm startIn another terminal, test the health check:
curl http://localhost:8080/pingTest the agent:
echo -n "What is 5 plus 3?" | curl -X POST http://localhost:8080/invocations \
-H "Content-Type: application/octet-stream" \
--data-binary @-3. Test with Docker
Build the Docker image:
docker build -t my-agent-service .Run the container:
docker run -p 8081:8080 my-agent-serviceTest in another terminal:
curl http://localhost:8081/pingDeployment to AWS
Step 1: Create IAM Role
Option A: Automated Script (Recommended)
Make the script executable and run it:
chmod +x create-iam-role.sh
./create-iam-role.shThe script will output the Role ARN. Save this for deployment.
Option B: Manual Setup
Create the role manually using AWS CLI or Console following the steps outlined in the above script.
Step 2: Set Environment Variables
# Get your AWS Account ID
export ACCOUNTID=$(aws sts get-caller-identity --query Account --output text)
# Set your preferred region
export AWS_REGION=ap-southeast-2
# Get the IAM Role ARN
export ROLE_ARN=$(aws iam get-role \
--role-name BedrockAgentCoreRuntimeRole \
--query 'Role.Arn' \
--output text)
# Set ECR repository name
export ECR_REPO=my-agent-serviceStep 3: Create ECR Repository
aws ecr create-repository \
--repository-name ${ECR_REPO} \
--region ${AWS_REGION}Step 4: Build and Push Docker Image
Login to ECR:
aws ecr get-login-password --region ${AWS_REGION} | \
docker login --username AWS --password-stdin \
${ACCOUNTID}.dkr.ecr.${AWS_REGION}.amazonaws.comBuild, Tag, and push:
docker build -t ${ECR_REPO} .
docker tag ${ECR_REPO}:latest \
${ACCOUNTID}.dkr.ecr.${AWS_REGION}.amazonaws.com/${ECR_REPO}:latest
docker push ${ACCOUNTID}.dkr.ecr.${AWS_REGION}.amazonaws.com/${ECR_REPO}:latestStep 5: Create AgentCore Runtime
aws bedrock-agentcore-control create-agent-runtime \
--agent-runtime-name my_agent_service \
--agent-runtime-artifact containerConfiguration={containerUri=${ACCOUNTID}.dkr.ecr.${AWS_REGION}.amazonaws.com/${ECR_REPO}:latest} \
--role-arn ${ROLE_ARN} \
--network-configuration networkMode=PUBLIC \
--protocol-configuration serverProtocol=HTTP \
--region ${AWS_REGION}Step 6: Verify Deployment
Wait about a minute, then check the status:
aws bedrock-agentcore-control get-agent-runtime \
--agent-runtime-id my-agent-service-XXXXXXXXXX \
--region ${AWS_REGION} \
--query 'status' \
--output textReplace XXXXXXXXXX with your runtime ID from the create command output.
Step 7: Test Your Deployment
- Update
invoke.tswith your AWS Account ID and runtime ID - Run the test:
npm run test:invokeExpected output:
Response: {"response":{"type":"agentResult","stopReason":"endTurn",...}}Customization
Adding More Tools
Add custom tools to the agent configuration in index.ts:
const myCustomTool = strands.tool({
name: 'my_tool',
inputSchema: z.object({
// Define your input schema
}),
callback: (input) => {
// Implement your tool logic
},
})
const agent = new strands.Agent({
model: new strands.BedrockModel({
region: 'ap-southeast-2',
}),
tools: [calculatorTool, myCustomTool], // Add your tool here
})Updating Your Deployment
After making code changes:
- Build and push new Docker image:
docker build -t ${ACCOUNTID}.dkr.ecr.${AWS_REGION}.amazonaws.com/${ECR_REPO}:latest . --no-cache
docker push ${ACCOUNTID}.dkr.ecr.${AWS_REGION}.amazonaws.com/${ECR_REPO}:latest- Update the runtime:
aws bedrock-agentcore-control update-agent-runtime \
--agent-runtime-id "my-agent-service-XXXXXXXXXX" \
--agent-runtime-artifact "{\"containerConfiguration\": {\"containerUri\": \"${ACCOUNTID}.dkr.ecr.${AWS_REGION}.amazonaws.com/${ECR_REPO}:latest\"}}" \
--role-arn "${ROLE_ARN}" \
--network-configuration "{\"networkMode\": \"PUBLIC\"}" \
--protocol-configuration serverProtocol=HTTP \
--region ${AWS_REGION}- Wait a minute and test with
npm run test:invoke
Troubleshooting
TypeScript Compilation Errors
Clean and rebuild:
rm -rf dist node_modules
npm install
npm run buildDocker Build Fails
Ensure Docker is running:
docker infoBuild without cache:
docker build --no-cache -t my-agent-service .ECR Authentication Expired
Re-authenticate:
aws ecr get-login-password --region ${AWS_REGION} | \
docker login --username AWS --password-stdin \
${ACCOUNTID}.dkr.ecr.${AWS_REGION}.amazonaws.comView CloudWatch Logs
aws logs tail /aws/bedrock-agentcore/runtimes/my-agent-service-XXXXXXXXXX-DEFAULT \
--region ${AWS_REGION} \
--since 1h \
--followAdditional Resources
- Full Documentation - Complete deployment guide with detailed explanations
- Amazon Bedrock AgentCore Documentation
- Strands TypeScript SDK
- Express.js Documentation
- Docker Documentation
Support
For issues or questions:
- Check the full documentation for detailed troubleshooting
- Consult the Strands documentation
File: site/docs/examples/python/multi_agent_example/index.md
Multi-Agent Example
This directory contains the implementation files for the Multi-Agent Example architecture, where specialized agents work together under the coordination of a central orchestrator.
Implementation Files
- teachers_assistant.py - The main orchestrator agent that routes queries to specialized agents
- math_assistant.py - Specialized agent for handling mathematical queries
- language_assistant.py - Specialized agent for language translation tasks
- english_assistant.py - Specialized agent for English grammar and comprehension
- computer_science_assistant.py - Specialized agent for computer science and programming tasks
- no_expertise.py - General assistant for queries outside specific domains
Documentation
For detailed information about how this multi-agent architecture works, please see the multi_agent_example.md documentation file.
File: site/docs/examples/deploy_to_eks/README.md
Amazon EKS Deployment Example
Introduction
This is an example that demonstrates how to deploy a Python application to Amazon EKS.
The example deploys a weather forecaster application that runs as a containerized service in Amazon EKS with an Application Load Balancer. The application is built with FastAPI and provides two weather endpoints:
/weather- A standard endpoint that returns weather information based on the provided prompt/weather-streaming- A streaming endpoint that delivers weather information in real-time as it's being generated
Prerequisites
- AWS CLI installed and configured
- eksctl (v0.208.x or later) installed
- Helm (v3 or later) installed
- kubectl installed
- Either:
- Amazon Bedrock Anthropic Claude 4 model enabled in your AWS environment
Project Structure
chart/- Contains the Helm chartvalues.yaml- Helm chart default values
docker/- Contains the Dockerfile and application code for the container:Dockerfile- Docker image definitionapp/- Application coderequirements.txt- Python dependencies for the container & local development
Create EKS Auto Mode cluster
Set environment variables
export AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query 'Account' --output text)
export AWS_REGION=us-east-1
export CLUSTER_NAME=eks-strands-agents-demoCreate EKS Auto Mode cluster
eksctl create cluster --name $CLUSTER_NAME --enable-auto-modeConfigure kubeconfig context
aws eks update-kubeconfig --name $CLUSTER_NAMEBuilding and Pushing Docker Image to ECR
Follow these steps to build the Docker image and push it to Amazon ECR:
- Authenticate to Amazon ECR:
aws ecr get-login-password --region ${AWS_REGION} | docker login --username AWS --password-stdin ${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com- Create the ECR repository if it doesn't exist:
aws ecr create-repository --repository-name strands-agents-weather --region ${AWS_REGION}- Build the Docker image:
docker build --platform linux/amd64 -t strands-agents-weather:latest docker/- Tag the image for ECR:
docker tag strands-agents-weather:latest ${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com/strands-agents-weather:latest- Push the image to ECR:
docker push ${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com/strands-agents-weather:latestConfigure EKS Pod Identity to access Amazon Bedrock
Create an IAM policy to allow InvokeModel & InvokeModelWithResponseStream to all Amazon Bedrock models
cat > bedrock-policy.json << EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"bedrock:InvokeModel",
"bedrock:InvokeModelWithResponseStream"
],
"Resource": "*"
}
]
}
EOF
aws iam create-policy \
--policy-name strands-agents-weather-bedrock-policy \
--policy-document file://bedrock-policy.json
rm -f bedrock-policy.jsonCreate an EKS Pod Identity association
eksctl create podidentityassociation --cluster $CLUSTER_NAME \
--namespace default \
--service-account-name strands-agents-weather \
--permission-policy-arns arn:aws:iam::$AWS_ACCOUNT_ID:policy/strands-agents-weather-bedrock-policy \
--role-name eks-strands-agents-weatherDeploy strands-agents-weather application
Deploy the helm chart with the image from ECR
helm install strands-agents-weather ./chart \
--set image.repository=${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com/strands-agents-weather --set image.tag=latestWait for Deployment to be available (Pods Running)
kubectl wait --for=condition=available deployments strands-agents-weather --allTest the Agent
Using kubernetes port-forward
kubectl --namespace default port-forward service/strands-agents-weather 8080:80 &Call the weather service
curl -X POST \
http://localhost:8080/weather \
-H 'Content-Type: application/json' \
-d '{"prompt": "What is the weather in Seattle?"}'Call the weather streaming endpoint
curl -X POST \
http://localhost:8080/weather-streaming \
-H 'Content-Type: application/json' \
-d '{"prompt": "What is the weather in New York in Celsius?"}'Expose Agent through Application Load Balancer
Create an IngressClass to configure an Application Load Balancer
cat <<EOF | kubectl apply -f -
apiVersion: eks.amazonaws.com/v1
kind: IngressClassParams
metadata:
name: alb
spec:
scheme: internet-facing
EOFcat <<EOF | kubectl apply -f -
apiVersion: networking.k8s.io/v1
kind: IngressClass
metadata:
name: alb
annotations:
ingressclass.kubernetes.io/is-default-class: "true"
spec:
controller: eks.amazonaws.com/alb
parameters:
apiGroup: eks.amazonaws.com
kind: IngressClassParams
name: alb
EOFUpdate helm deployment to create Ingress using the IngressClass created
helm upgrade strands-agents-weather ./chart \
--set image.repository=${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com/strands-agents-weather --set image.tag=latest \
--set ingress.enabled=true \
--set ingress.className=albGet the ALB URL
export ALB_URL=$(kubectl get ingress strands-agents-weather -o jsonpath='{.status.loadBalancer.ingress[0].hostname}')
echo "The shared ALB is available at: http://$ALB_URL"Wait for ALB to be active
aws elbv2 wait load-balancer-available --load-balancer-arns $(aws elbv2 describe-load-balancers --query 'LoadBalancers[?DNSName==`'"$ALB_URL"'`].LoadBalancerArn' --output text)Call the weather service Application Load Balancer endpoint
curl -X POST \
http://$ALB_URL/weather \
-H 'Content-Type: application/json' \
-d '{"prompt": "What is the weather in Portland?"}'Configure High Availability and Resiliency
- Increase replicas to 3
- Topology Spread Constraints: Spread workload across multi-az
- Pod Disruption Budgets: Tolerate minAvailable of 1
helm upgrade strands-agents-weather ./chart -f - <<EOF
image:
tag: latest
ingress:
enabled: true
className: alb
replicaCount: 3
topologySpreadConstraints:
- maxSkew: 1
minDomains: 3
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: DoNotSchedule
labelSelector:
matchLabels:
app.kubernetes.io/name: strands-agents-weather
- maxSkew: 1
topologyKey: kubernetes.io/hostname
whenUnsatisfiable: ScheduleAnyway
labelSelector:
matchLabels:
app.kubernetes.io/instance: strands-agents-weather
podDisruptionBudget:
enabled: true
minAvailable: 1
EOFCleanup
Uninstall helm chart
helm uninstall strands-agents-weatherDelete EKS Auto Mode cluster
eksctl delete cluster --name $CLUSTER_NAME --waitDelete IAM policy
aws iam delete-policy --policy-arn arn:aws:iam::$AWS_ACCOUNT_ID:policy/strands-agents-weather-bedrock-policyFile: site/docs/examples/cdk/deploy_to_lambda/README.md
AWS CDK Lambda Deployment Example
Introduction
This is a TypeScript-based CDK (Cloud Development Kit) example that demonstrates how to deploy a Python function to AWS Lambda. The example deploys a weather forecaster application that requires AWS authentication to invoke the Lambda function.
Prerequisites
- AWS CLI installed and configured
- Node.js (v18.x or later)
- Python 3.12 or later
- jq (optional) for formatting JSON output
Project Structure
lib/- Contains the CDK stack definition in TypeScriptbin/- Contains the CDK app entry point and deployment scripts:cdk-app.ts- Main CDK application entry pointpackage_for_lambda.py- Python script that packages Lambda code and dependencies into deployment archives
lambda/- Contains the Python Lambda function codepackaging/- Directory used to store Lambda deployment assets and dependencies
Setup and Deployment
- Install dependencies:
# Install Node.js dependencies including CDK and TypeScript locally
npm install
# Create a Python virtual environment (optional but recommended)
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
# Install Python dependencies for the local development
pip install -r requirements.txt
# Install Python dependencies for lambda with correct architecture
pip install -r requirements.txt --python-version 3.12 --platform manylinux2014_aarch64 --target ./packaging/_dependencies --only-binary=:all:- Package the lambda:
python ./bin/package_for_lambda.py- Bootstrap your AWS environment (if not already done):
npx cdk bootstrap- Deploy the lambda:
npx cdk deployUsage
After deployment, you can invoke the Lambda function using the AWS CLI or AWS Console. The function requires proper AWS authentication to be invoked.
aws lambda invoke --function-name AgentFunction \
--region us-east-1 \
--cli-binary-format raw-in-base64-out \
--payload '{"prompt": "What is the weather in New York?"}' \
output.jsonIf you have jq installed, you can output the response from output.json like so:
jq -r '.' ./output.jsonOtherwise, open output.json to view the result.
Cleanup
To remove all resources created by this example:
npx cdk destroyAdditional Resources
File: site/docs/examples/cdk/deploy_to_fargate/README.md
AWS CDK Fargate Deployment Example
Introduction
This is a TypeScript-based CDK (Cloud Development Kit) example that demonstrates how to deploy a Python application to AWS Fargate. The example deploys a weather forecaster application that runs as a containerized service in AWS Fargate with an Application Load Balancer. The application is built with FastAPI and provides two weather endpoints:
/weather- A standard endpoint that returns weather information based on the provided prompt/weather-streaming- A streaming endpoint that delivers weather information in real-time as it's being generated
Prerequisites
Project Structure
lib/- Contains the CDK stack definition in TypeScriptbin/- Contains the CDK app entry point and deployment scripts:cdk-app.ts- Main CDK application entry point
docker/- Contains the Dockerfile and application code for the container:Dockerfile- Docker image definitionapp/- Application coderequirements.txt- Python dependencies for the container & local development
Setup and Deployment
- Install dependencies:
# Install Node.js dependencies including CDK and TypeScript locally
npm install
# Create a Python virtual environment (optional but recommended)
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
# Install Python dependencies for the local development
pip install -r ./docker/requirements.txt- Bootstrap your AWS environment (if not already done):
npx cdk bootstrap- Ensure podman is started (one time):
podman machine init
podman machine start- Package & deploy via CDK:
CDK_DOCKER=podman npx cdk deployUsage
After deployment, you can access the weather service using the Application Load Balancer URL that is output after deployment:
# Get the service URL from the CDK output
SERVICE_URL=$(aws cloudformation describe-stacks --stack-name AgentFargateStack --query "Stacks[0].Outputs[?ExportName=='AgentServiceEndpoint'].OutputValue" --output text)The service exposes a REST API endpoint that you can call using curl or any HTTP client:
# Call the weather service
curl -X POST \
http://$SERVICE_URL/weather \
-H 'Content-Type: application/json' \
-d '{"prompt": "What is the weather in New York?"}'
# Call the streaming endpoint
curl -X POST \
http://$SERVICE_URL/weather-streaming \
-H 'Content-Type: application/json' \
-d '{"prompt": "What is the weather in New York in Celsius?"}'Local testing (python)
You can run the python app directly for local testing via:
python ./docker/app/app.pyThen, set the SERVICE_URL to point to your local server
SERVICE_URL=127.0.0.1:8000and you can use the curl commands above to test locally.
Local testing (container)
Build & run the container:
podman build ./docker/ -t agent_container
podman run -p 127.0.0.1:8000:8000 -t agent_containerThen, set the SERVICE_URL to point to your local server
SERVICE_URL=127.0.0.1:8000and you can use the curl commands above to test locally.
Cleanup
To remove all resources created by this example:
npx cdk destroyAdditional Resources
- AWS CDK TypeScript Documentation
- AWS Fargate Documentation
- Docker Documentation
- TypeScript Documentation
File: site/docs/examples/cdk/deploy_to_ec2/README.md
AWS CDK EC2 Deployment Example
Introduction
This is a TypeScript-based CDK (Cloud Development Kit) example that demonstrates how to deploy a Python application to AWS EC2. The example deploys a weather forecaster application that runs as a service on an EC2 instance. The application provides two weather endpoints:
/weather- A standard endpoint that returns weather information based on the provided prompt/weather-streaming- A streaming endpoint that delivers weather information in real-time as it's being generated
Prerequisites
Project Structure
lib/- Contains the CDK stack definition in TypeScriptbin/- Contains the CDK app entry point and deployment scripts:cdk-app.ts- Main CDK application entry point
app/- Contains the application code:app.py- FastAPI application code
requirements.txt- Python dependencies for the application
Setup and Deployment
- Install dependencies:
# Install Node.js dependencies including CDK and TypeScript locally
npm install
# Create a Python virtual environment (optional but recommended)
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
# Install Python dependencies for the local development
pip install -r ./requirements.txt
# Install Python dependencies for the app distribution
pip install -r requirements.txt --python-version 3.12 --platform manylinux2014_aarch64 --target ./packaging/_dependencies --only-binary=:all:- Bootstrap your AWS environment (if not already done):
npx cdk bootstrap- Deploy the stack:
npx cdk deployHow It Works
This deployment:
- Creates an EC2 instance in a public subnet with a public IP
- Uploads the application code to S3 as CDK assets
- Uses a user data script to:
- Install Python and other dependencies
- Download the application code from S3
- Set up the application as a systemd service using uvicorn
Usage
After deployment, you can access the weather service using the Application Load Balancer URL that is output after deployment:
# Get the service URL from the CDK output
SERVICE_URL=$(aws cloudformation describe-stacks --stack-name AgentEC2Stack --region us-east-1 --query "Stacks[0].Outputs[?ExportName=='Ec2ServiceEndpoint'].OutputValue" --output text)The service exposes a REST API endpoint that you can call using curl or any HTTP client:
# Call the weather service
curl -X POST \
http://$SERVICE_URL/weather \
-H 'Content-Type: application/json' \
-d '{"prompt": "What is the weather in New York?"}'
# Call the streaming endpoint
curl -X POST \
http://$SERVICE_URL/weather-streaming \
-H 'Content-Type: application/json' \
-d '{"prompt": "What is the weather in New York in Celsius?"}'Local testing
You can run the python app directly for local testing via:
python app/app.pyThen, set the SERVICE_URL to point to your local server
SERVICE_URL=127.0.0.1:8000and you can use the curl commands above to test locally.
Cleanup
To remove all resources created by this example:
npx cdk destroyCallouts and considerations
Note that this example demonstrates a simple deployment approach with some important limitations:
- The application code is deployed only during the initial instance creation via user data script
- Updating the application requires implementing a custom update mechanism
- The example exposes the application directly on port 8000 without a load balancer
- For production workloads, consider using ECS/Fargate/App Runner which provides built-in support for application updates, scaling, and high availability
Additional Resources
- AWS CDK TypeScript Documentation
- Amazon EC2 Documentation
- FastAPI Documentation
- TypeScript Documentation
File: site/docs/examples/cdk/deploy_to_apprunner/README.md
AWS CDK App Runner Deployment Example
Introduction
This is a TypeScript-based CDK (Cloud Development Kit) example that demonstrates how to deploy a Python application to AWS App Runner. The example deploys a weather forecaster application that runs as a containerized service in AWS App Runner. The application is built with FastAPI and provides two weather endpoints:
/weather- A standard endpoint that returns weather information based on the provided prompt/weather-streaming- A streaming endpoint that delivers weather information in real-time as it's being generated
Prerequisites
Project Structure
lib/- Contains the CDK stack definition in TypeScriptbin/- Contains the CDK app entry point and deployment scripts:cdk-app.ts- Main CDK application entry point
docker/- Contains the Dockerfile and application code for the container:Dockerfile- Docker image definitionapp/- Application coderequirements.txt- Python dependencies for the container & local development
Setup and Deployment
- Install dependencies:
# Install Node.js dependencies including CDK and TypeScript locally
npm install
# Create a Python virtual environment (optional but recommended)
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
# Install Python dependencies for the local development
pip install -r ./docker/requirements.txt- Bootstrap your AWS environment (if not already done):
npx cdk bootstrap- Ensure podman is started (one time):
podman machine init
podman machine start- Package & deploy via CDK:
CDK_DOCKER=podman npx cdk deployUsage
After deployment, you can access the weather service using the App Runner Service URL that is output after deployment:
# Get the service URL from the CDK output
SERVICE_URL=$(aws cloudformation describe-stacks --stack-name AgentAppRunnerStack --query "Stacks[0].Outputs[?ExportName=='AppRunnerServiceUrl'].OutputValue" --output text)The service exposes a REST API endpoint that you can call using curl or any HTTP client:
# Call the weather service
curl -X POST \
https://$SERVICE_URL/weather \
-H 'Content-Type: application/json' \
-d '{"prompt": "What is the weather in New York?"}'
# Call the streaming endpoint
curl -X POST \
https://$SERVICE_URL/weather-streaming \
-H 'Content-Type: application/json' \
-d '{"prompt": "What is the weather in New York in Celsius?"}'Local testing (python)
You can run the python app directly for local testing via:
python ./docker/app/app.pyThen, set the SERVICE_URL to point to your local server
SERVICE_URL=127.0.0.1:8000and you can use the curl commands above to test locally.
Local testing (container)
Build & run the container:
podman build --platform linux/amd64 -t agent_container ./docker/
podman run -p 127.0.0.1:8000:8000 \
-v ~/.aws:/home/appuser/.aws:ro \
-e AWS_PROFILE=default \
-t agent_containerThen, set the SERVICE_URL to point to your local server
SERVICE_URL=127.0.0.1:8000and you can use the curl commands above to test locally.
Cleanup
To remove all resources created by this example:
npx cdk destroy