teachers_assistant.py Documentation

Official TypeScript developer resources and documentation for strands-agents/teachers_assistant.py. Verified technical context for AI.

0 stars TypeScript TypeScript 1 file ยท ~9,784 tokens
RAW Doc

1. Project Overview & Quickstart (strands-agents/teachers_assistant.py)

teachers_assistant.py

Open-source repository strands-agents/teachers_assistant.py

Repository Details

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.

text
[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

bash
npm install

Building and Previewing

Generate the static site:

bash
npm run build

Run a local development server at http://localhost:4321/:

bash
npm run dev

Writing 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 @api shorthand: [@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-audit to assess a published page before rewriting.
  • /docs-writer to draft a new page or rewrite an existing one. Step 7 of the skill runs docs-reviewer automatically.
  • /docs-reviewer <draft> on its own when you want a voice/style sign-off without a rewrite.
  • /docs-planner to 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:

text
/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

  1. Check the roadmap โ€” See if your idea aligns with our direction
  2. Fork the docs repository
  3. Create your design โ€” Add a new file: designs/NNNN-feature-name.md using the template below
  4. Submit a pull request โ€” We'll review and discuss
  5. Iterate based on feedback โ€” Address comments and questions
  6. Get approval โ€” Once approved and merged, implement the feature
  7. Reference the design โ€” Link to it in your implementation PR

Design document template

markdown
# [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 guidance

Accepted 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

bash
npm install

Run

bash
npm start

What 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 (/ping and /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

text
.
โ”œโ”€โ”€ 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 file

Quick Start

1. Install Dependencies

bash
npm install

2. Test Locally

Build and start the server:

bash
npm run build
npm start

In another terminal, test the health check:

bash
curl http://localhost:8080/ping

Test the agent:

bash
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:

bash
docker build -t my-agent-service .

Run the container:

bash
docker run -p 8081:8080 my-agent-service

Test in another terminal:

bash
curl http://localhost:8081/ping

Deployment to AWS

Step 1: Create IAM Role

Option A: Automated Script (Recommended)

Make the script executable and run it:

bash
chmod +x create-iam-role.sh
./create-iam-role.sh

The 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

bash
# 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-service

Step 3: Create ECR Repository

bash
aws ecr create-repository \
  --repository-name ${ECR_REPO} \
  --region ${AWS_REGION}

Step 4: Build and Push Docker Image

Login to ECR:

bash
aws ecr get-login-password --region ${AWS_REGION} | \
  docker login --username AWS --password-stdin \
  ${ACCOUNTID}.dkr.ecr.${AWS_REGION}.amazonaws.com

Build, Tag, and push:

bash
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}:latest

Step 5: Create AgentCore Runtime

bash
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:

bash
aws bedrock-agentcore-control get-agent-runtime \
  --agent-runtime-id my-agent-service-XXXXXXXXXX \
  --region ${AWS_REGION} \
  --query 'status' \
  --output text

Replace XXXXXXXXXX with your runtime ID from the create command output.

Step 7: Test Your Deployment

  1. Update invoke.ts with your AWS Account ID and runtime ID
  2. Run the test:
bash
npm run test:invoke

Expected output:

text
Response: {"response":{"type":"agentResult","stopReason":"endTurn",...}}

Customization

Adding More Tools

Add custom tools to the agent configuration in index.ts:

typescript
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:

  1. Build and push new Docker image:
bash
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
  1. Update the runtime:
bash
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}
  1. Wait a minute and test with npm run test:invoke

Troubleshooting

TypeScript Compilation Errors

Clean and rebuild:

bash
rm -rf dist node_modules
npm install
npm run build

Docker Build Fails

Ensure Docker is running:

bash
docker info

Build without cache:

bash
docker build --no-cache -t my-agent-service .

ECR Authentication Expired

Re-authenticate:

bash
aws ecr get-login-password --region ${AWS_REGION} | \
  docker login --username AWS --password-stdin \
  ${ACCOUNTID}.dkr.ecr.${AWS_REGION}.amazonaws.com

View CloudWatch Logs

bash
aws logs tail /aws/bedrock-agentcore/runtimes/my-agent-service-XXXXXXXXXX-DEFAULT \
  --region ${AWS_REGION} \
  --since 1h \
  --follow

Additional Resources

Support

For issues or questions:


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

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:

  1. /weather - A standard endpoint that returns weather information based on the provided prompt
  2. /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:
    • Podman installed and running
    • (or) Docker installed and running
  • Amazon Bedrock Anthropic Claude 4 model enabled in your AWS environment

Project Structure

  • chart/ - Contains the Helm chart
    • values.yaml - Helm chart default values
  • docker/ - Contains the Dockerfile and application code for the container:
    • Dockerfile - Docker image definition
    • app/ - Application code
    • requirements.txt - Python dependencies for the container & local development

Create EKS Auto Mode cluster

Set environment variables

bash
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-demo

Create EKS Auto Mode cluster

bash
eksctl create cluster --name $CLUSTER_NAME --enable-auto-mode

Configure kubeconfig context

bash
aws eks update-kubeconfig --name $CLUSTER_NAME

Building and Pushing Docker Image to ECR

Follow these steps to build the Docker image and push it to Amazon ECR:

  1. Authenticate to Amazon ECR:
bash
aws ecr get-login-password --region ${AWS_REGION} | docker login --username AWS --password-stdin ${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com
  1. Create the ECR repository if it doesn't exist:
bash
aws ecr create-repository --repository-name strands-agents-weather --region ${AWS_REGION}
  1. Build the Docker image:
bash
docker build --platform linux/amd64 -t strands-agents-weather:latest docker/
  1. Tag the image for ECR:
bash
docker tag strands-agents-weather:latest ${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com/strands-agents-weather:latest
  1. Push the image to ECR:
bash
docker push ${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com/strands-agents-weather:latest

Configure EKS Pod Identity to access Amazon Bedrock

Create an IAM policy to allow InvokeModel & InvokeModelWithResponseStream to all Amazon Bedrock models

bash
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.json

Create an EKS Pod Identity association

bash
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-weather

Deploy strands-agents-weather application

Deploy the helm chart with the image from ECR

bash
helm install strands-agents-weather ./chart \
  --set image.repository=${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com/strands-agents-weather --set image.tag=latest

Wait for Deployment to be available (Pods Running)

bash
kubectl wait --for=condition=available deployments strands-agents-weather --all

Test the Agent

Using kubernetes port-forward

text
kubectl --namespace default port-forward service/strands-agents-weather 8080:80 &

Call the weather service

text
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

text
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

bash
cat <<EOF | kubectl apply -f -
apiVersion: eks.amazonaws.com/v1
kind: IngressClassParams
metadata:
  name: alb
spec:
  scheme: internet-facing
EOF
bash
cat <<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
EOF

Update helm deployment to create Ingress using the IngressClass created

bash
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=alb

Get the ALB URL

bash
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

bash
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

bash
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

bash
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
EOF

Cleanup

Uninstall helm chart

bash
helm uninstall strands-agents-weather

Delete EKS Auto Mode cluster

bash
eksctl delete cluster --name $CLUSTER_NAME --wait

Delete IAM policy

bash
aws iam delete-policy --policy-arn arn:aws:iam::$AWS_ACCOUNT_ID:policy/strands-agents-weather-bedrock-policy

File: 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 TypeScript
  • bin/ - Contains the CDK app entry point and deployment scripts:
    • cdk-app.ts - Main CDK application entry point
    • package_for_lambda.py - Python script that packages Lambda code and dependencies into deployment archives
  • lambda/ - Contains the Python Lambda function code
  • packaging/ - Directory used to store Lambda deployment assets and dependencies

Setup and Deployment

  1. Install dependencies:
bash
# 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:
  1. Package the lambda:
bash
python ./bin/package_for_lambda.py
  1. Bootstrap your AWS environment (if not already done):
bash
npx cdk bootstrap
  1. Deploy the lambda:
text
npx cdk deploy

Usage

After deployment, you can invoke the Lambda function using the AWS CLI or AWS Console. The function requires proper AWS authentication to be invoked.

bash
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.json

If you have jq installed, you can output the response from output.json like so:

bash
jq -r '.' ./output.json

Otherwise, open output.json to view the result.

Cleanup

To remove all resources created by this example:

bash
npx cdk destroy

Additional 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:

  1. /weather - A standard endpoint that returns weather information based on the provided prompt
  2. /weather-streaming - A streaming endpoint that delivers weather information in real-time as it's being generated

Prerequisites

  • AWS CLI installed and configured
  • Node.js (v18.x or later)
  • Python 3.12 or later
  • Either:
    • Podman installed and running
    • (or) Docker installed and running

Project Structure

  • lib/ - Contains the CDK stack definition in TypeScript
  • bin/ - 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 definition
    • app/ - Application code
    • requirements.txt - Python dependencies for the container & local development

Setup and Deployment

  1. Install dependencies:
bash
# 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
  1. Bootstrap your AWS environment (if not already done):
bash
npx cdk bootstrap
  1. Ensure podman is started (one time):
bash
podman machine init
podman machine start
  1. Package & deploy via CDK:
bash
CDK_DOCKER=podman npx cdk deploy

Usage

After deployment, you can access the weather service using the Application Load Balancer URL that is output after deployment:

bash
# 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:

bash
# 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:

bash
python ./docker/app/app.py

Then, set the SERVICE_URL to point to your local server

bash
SERVICE_URL=127.0.0.1:8000

and you can use the curl commands above to test locally.

Local testing (container)

Build & run the container:

bash
podman build ./docker/ -t agent_container
podman run -p 127.0.0.1:8000:8000 -t agent_container

Then, set the SERVICE_URL to point to your local server

bash
SERVICE_URL=127.0.0.1:8000

and you can use the curl commands above to test locally.

Cleanup

To remove all resources created by this example:

bash
npx cdk destroy

Additional Resources


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:

  1. /weather - A standard endpoint that returns weather information based on the provided prompt
  2. /weather-streaming - A streaming endpoint that delivers weather information in real-time as it's being generated

Prerequisites

  • AWS CLI installed and configured
  • Node.js (v18.x or later)
  • Python 3.12 or later

Project Structure

  • lib/ - Contains the CDK stack definition in TypeScript
  • bin/ - 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

  1. Install dependencies:
bash
# 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:
  1. Bootstrap your AWS environment (if not already done):
bash
npx cdk bootstrap
  1. Deploy the stack:
bash
npx cdk deploy

How It Works

This deployment:

  1. Creates an EC2 instance in a public subnet with a public IP
  2. Uploads the application code to S3 as CDK assets
  3. 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:

bash
# 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:

bash
# 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:

bash
python app/app.py

Then, set the SERVICE_URL to point to your local server

bash
SERVICE_URL=127.0.0.1:8000

and you can use the curl commands above to test locally.

Cleanup

To remove all resources created by this example:

bash
npx cdk destroy

Callouts 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


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:

  1. /weather - A standard endpoint that returns weather information based on the provided prompt
  2. /weather-streaming - A streaming endpoint that delivers weather information in real-time as it's being generated

Prerequisites

  • AWS CLI installed and configured
  • Node.js (v18.x or later)
  • Python 3.12 or later
  • Either:
    • Podman installed and running
    • (or) Docker installed and running

Project Structure

  • lib/ - Contains the CDK stack definition in TypeScript
  • bin/ - 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 definition
    • app/ - Application code
    • requirements.txt - Python dependencies for the container & local development

Setup and Deployment

  1. Install dependencies:
bash
# 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
  1. Bootstrap your AWS environment (if not already done):
bash
npx cdk bootstrap
  1. Ensure podman is started (one time):
bash
podman machine init
podman machine start
  1. Package & deploy via CDK:
bash
CDK_DOCKER=podman npx cdk deploy

Usage

After deployment, you can access the weather service using the App Runner Service URL that is output after deployment:

bash
# 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:

bash
# 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:

bash
python ./docker/app/app.py

Then, set the SERVICE_URL to point to your local server

bash
SERVICE_URL=127.0.0.1:8000

and you can use the curl commands above to test locally.

Local testing (container)

Build & run the container:

bash
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_container

Then, set the SERVICE_URL to point to your local server

bash
SERVICE_URL=127.0.0.1:8000

and you can use the curl commands above to test locally.

Cleanup

To remove all resources created by this example:

bash
npx cdk destroy

Additional Resources