strands-py Documentation

TypeScript repository by @strands-agents. Model Context Protocol (MCP) server & tools.

0 stars TypeScript TypeScript 1 file ยท ~24,450 tokens
RAW Doc

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

strands-py

Open-source repository strands-agents/strands-py

Repository Details

Note: High-volume repository documentation is actively indexed and synchronized by YakaAI.

2. Official Technical Reference & Guides (strands-agents/docs)

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',
  description: 'Description of what this tool does',
  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:
  repository: ${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com/strands-agents-weather 
  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


File: site/src/content/blog/evaluating-ai-agents-practical-guide-strands-evals.mdx


title: "Evaluating AI agents for production: A practical guide to Strands Evals"
date: 2026-03-18
authors:


Moving AI agents from prototypes to production surfaces a challenge that traditional testing is unable to address. Agents are flexible, adaptive, and context-aware by design, but the same qualities that make them powerful also make them difficult to evaluate systematically.

Traditional software testing relies on deterministic outputs: same input, same expected output, every time. AI agents break this assumption. They generate natural language, make context-dependent decisions, and produce varied outputs even from identical inputs. How do you systematically evaluate something that is not deterministic?

In this post, we show how to evaluate AI agents systematically using Strands Evals. We walk through the core concepts, built-in evaluators, multi-turn simulation capabilities and practical approaches and patterns for integration. Strands Evals provides a structured framework for evaluating AI agents built with the Strands Agents SDK, offering evaluators, simulation tools, and reporting capabilities. Whether you need to verify that your agent uses the right tools, produces helpful responses, or guides users toward their goals, the framework provides infrastructure to measure and track these qualities systematically.

Why evaluating AI agents is different

When you ask an agent "What is the weather like in Tokyo?", many valid responses exist, and no single answer is definitively correct. The agent might report temperature in Celsius or Fahrenheit, include humidity and wind, or only focus on temperature. These variations could be correct and helpful, which is exactly why traditional assertion-based testing falls short. Beyond text generation, agents also take action. A well-designed agent calls tools, retrieves information, and makes decisions throughout a conversation. Evaluating the final response alone misses whether the agent took appropriate steps to reach that response.

Even correct responses can fall short. A response might be factually accurate but unhelpful, or helpful but unfaithful to source materials. No single metric captures these different quality dimensions. Conversations add another layer of complexity because they unfold over time. In multi-turn interactions, earlier responses affect later ones. An agent might handle individual queries well but fail to maintain a coherent context across a conversation. Testing single turns in isolation misses these interaction patterns.

These characteristics demand evaluation that requires judgment rather than keyword comparison. Large language model (LLM)-based evaluation addresses this need. By using language models as evaluators, we can assess qualities like helpfulness, coherence, and faithfulness that resist mechanical checking. Strands Evals embraces this flexibility while still offering rigorous, repeatable quality assessments.

Core concepts of Strands Evals

Strands Evals follows a pattern that should feel familiar to anyone who has written unit tests but adapts it for the judgment-based evaluation that AI agents require. The framework introduces three foundational concepts that work together: Cases, Experiments, and Evaluators.

A Case represents a single test scenario. It contains the input that you want to test, perhaps a user's query like "What is the weather in Paris?", along with optional expected outputs, expected tool sequences known as trajectories, and metadata. Cases are the atomic unit of evaluation. Each one defines one scenario that you want your agent to handle correctly.

python
from strands_evals import Case

case = Case(
    name="Weather Query",
    input="What is the weather like in Tokyo?",
    expected_output="Should include temperature and conditions",
    expected_trajectory=["weather_api"]
)

An Experiment bundles multiple Cases together with one or more evaluators. Think of it as a test suite in traditional testing. The Experiment orchestrates the evaluation process. It takes each Case, runs your agent on it, and applies the configured evaluators to score the results.

Evaluators are the judges. They examine what your agent produced (the actual output and trajectory) and compare it against what was expected. Unlike simple assertion checks, evaluators in Strands Evals are primarily LLM-based. They use language models to make nuanced judgments about quality, relevance, helpfulness, and other qualities that cannot be reduced to string comparison.

Separating these concerns helps keep the framework flexible. You can define what to test with Cases, how to test it with evaluators, and the framework handles orchestration and reporting through Experiments. Each piece can be configured independently so that you can build evaluation suites that are tailored to your specific needs.

The task function: connecting agents to evaluation

Cases define your scenarios, and evaluators provide judgment. But how does your agent actually connect to this evaluation system? That is where the Task Function comes in.

A Task Function is a callable that you provide to the Experiment. It receives a Case and returns the results of running that case through your system. This interface enables two fundamentally different evaluation patterns.

Online evaluation involves invoking your agent live during the evaluation run. Your Task Function creates an agent, sends it the case input, captures the response and execution trace, and returns them for evaluation. This pattern is recommended during development when you want to test changes immediately, or in continuous integration and delivery (CI/CD) pipelines where you need to verify agent behavior before deployment.

python
from strands import Agent

def online_task(case):
    agent = Agent(tools=[search_tool, calculator_tool])
    result = agent(case.input)

    return {
        "output": str(result),
        "trajectory": agent.session
    }

Offline evaluation works with historical data. Instead of invoking an agent, your Task Function retrieves previously recorded traces from logs, databases, or observability systems. It parses these traces into the format that evaluators expect and returns them for judgment. This pattern works well when you need to evaluate production traffic, perform historical analysis, or compare agent versions against the same set of real user interactions.

python
def offline_task(case):
    trace = load_trace_from_database(case.session_id)
    session = session_mapper.map_to_session(trace)

    return {
        "output": extract_final_response(trace),
        "trajectory": session
    }

Whether you are testing a new agent implementation or analyzing months of production data, the same evaluators and reporting infrastructure apply. The Task Function adapts your data source to the evaluation system.

Built-in evaluators for comprehensive assessment

With your Task Function connecting agent output to the evaluation system, you can now decide which aspects of quality to measure. Strands Evals ships with ten built-in evaluators, each designed to assess a different dimension of agent quality.

Rubric-based evaluators

The most flexible evaluators let you define custom criteria through natural language rubrics.

  • OutputEvaluator judges the final response that your agent produces. You provide a rubric, a description of what good looks like, and the evaluators use an LLM to score the output against that criteria. This works well for general quality checks where you want to define specific standards for your use case.
python
from strands_evals.evaluators import OutputEvaluator

output_evaluator = OutputEvaluator(
    rubric="Score 1.0 if the response correctly answers the question and is well-structured. "
           "Score 0.5 if partially correct. Score 0.0 if incorrect or irrelevant."
)
  • TrajectoryEvaluator extends this to examine the sequence of actions (typically tool calls) that your agent took. Beyond just looking at the final answer, you can verify that the agent used appropriate tools in a logical order. The evaluators include three built-in scoring functions for comparing actual versus expected trajectories: exact match, in-order match, and any-order match. These scorers are provided as tools to the evaluation LLM, which chooses the most appropriate one based on your rubric.
  • InteractionsEvaluator handles multi-agent systems where multiple components communicate. It evaluates sequences of interactions between agents or system components. This is useful when your architecture involves orchestrators, sub-agents, or complex tool chains.

Semantic evaluators

Some quality dimensions are common enough that Strands Evals provides pre-built evaluators with carefully designed prompts and scoring scales.

  • HelpfulnessEvaluator assesses responses from the user's perspective using a seven-point scale ranging from "Not helpful at all" to "Above and beyond." It evaluates whether the response actually addresses the user's needs, not only whether it is technically correct.
  • FaithfulnessEvaluator checks whether the response is grounded in the conversation history. This is particularly important for Retrieval Augmented Generation (RAG) systems where you need to make sure that the agent doesn't hallucinate information. The five-point scale ranges from "Not at all" faithful to "Completely yes."
  • HarmfulnessEvaluator performs safety checks, helping determine whether responses contain harmful, inappropriate, or dangerous content. It provides binary yes/no judgments for clear decision-making.

Tool-level evaluators

When your agent uses tools, you often need to evaluate not only the final outcome, but the quality of individual tool invocations.

  • ToolSelectionAccuracyEvaluator examines each tool call in context and judges whether selecting that particular tool was justified given the conversation state. It answers: "At this point in the conversation, was it reasonable to call this tool?"
  • ToolParameterAccuracyEvaluator goes deeper, checking whether the parameters passed to each tool were correct and appropriate. It helps catch subtle errors where the right tool was chosen but called with wrong or incomplete arguments.

Session-level evaluators

  • GoalSuccessRateEvaluator takes the broadest view, evaluating entire conversation sessions to determine whether the user ultimately achieved their goal. For task-oriented agents, success is defined by outcomes rather than a single response.

Choosing the right evaluators

The choice depends on what matters most for your application. A customer service agent might prioritize helpfulness and goal success. A research assistant might emphasize faithfulness. Start with a small set of evaluators that cover your core quality dimensions, then add more as you learn how your agent fails.

Simulating users for multi-turn testing

The previously mentioned evaluators work well for single-turn interactions where you provide an input, get an output, and evaluate it. Multi-turn conversations present a harder challenge. Real users don't follow scripts. They ask follow-up questions, change direction, and express confusion. How do you test this? Strands Evals includes an ActorSimulator that creates AI-powered simulated users to drive multi-turn conversations with your agent.

ActorSimulator starts with a test case that defines what the user wants to achieve. From this, it generates a realistic user profile using an LLM, including personality traits, expertise level, communication style, and a specific goal. This profile shapes how the simulated user behaves throughout the conversation.

python
from strands_evals import Case, ActorSimulator
from strands import Agent

case = Case(
    input="I need help setting up a new bank account",
    metadata={"task_description": "Successfully open a checking account"}
)

user_sim = ActorSimulator.from_case_for_user_simulator(
    case=case,
    max_turns=10
)

During the interaction, the simulated user sends messages to your agent, receives responses, and decides what to say next. This loop continues until either the goal is achieved, indicated by emitting a special stop token, or the maximum turn count is reached.

python
agent = Agent(system_prompt="You are a helpful banking assistant.")

user_message = case.input
while user_sim.has_next():
    agent_response = agent(user_message)
    user_result = user_sim.act(str(agent_response))
    user_message = str(user_result.structured_output.message)

You can then pass the resulting conversation transcript to session-level evaluators like GoalSuccessRateEvaluator to assess whether your agent successfully helped the simulated user achieve their goal. Instead of manually writing multi-turn scripts, you define goals and let the simulator create realistic interaction patterns. It might ask unexpected follow-up questions, express confusion, or take the conversation in directions that you didn't anticipate, catching edge cases that scripted tests can miss.

Evaluation levels: understanding the hierarchy

Whether using simulated or real conversations, different evaluators operate at different granularities. Strands Evals uses a TraceExtractor to parse session data into the format that each evaluator needs.

Session level evaluation looks at the complete conversation from beginning to end. The evaluator receives the full history, the tool executions, and understands the entire context. GoalSuccessRateEvaluator works at this level because determining goal achievement requires understanding the whole interaction.

Trace level evaluation focuses on individual turns, each user prompt, and agent response pair. Evaluators at this level receive the conversation history up to that point and judge the specific response. Helpfulness, Faithfulness, and Harmfulness evaluators work here because these qualities can be assessed turn by turn.

Tool level evaluation drills down to individual tool invocations. Each tool call is evaluated in context, with access to the available tools, the conversation so far, and the specific arguments passed. Tool Selection and Tool Parameter evaluators operate at this granularity.

You can use the hierarchical design to compose evaluation suites that check quality at multiple levels simultaneously. Within a single evaluation run, you can verify that individual tool calls are sensible, responses are helpful, and overall goals are achieved.

Ground truth and expected behaviors

At many different evaluation levels, evaluators can benefit from having reference points for comparison. Strands Evals provides first-class support for ground truth through three expected fields on Cases.

The expected_output field specifies what the agent should say. This is useful when there are correct answers or standard response formats. The expected_trajectory field defines the sequence of tools or actions that the agent should take. You might require that a customer service agent checks account status before making changes, or that a research agent queries multiple sources before synthesizing. Not every Case needs every field. You define expectations based on what matters for your evaluation goals. When expected values are provided, evaluators receive both expected and actual results, enabling comparison-based scoring alongside standalone quality assessment.

Putting it all together

Let's walk through a typical evaluation workflow to see how these concepts come together.

First, you define your test cases, meaning the scenarios you want your agent to handle well. They might come from real user queries, synthetic generation, or edge cases that you have identified.

python
from strands_evals import Experiment, Case
from strands_evals.evaluators import OutputEvaluator, TrajectoryEvaluator
from strands_evals.extractors.tools_use_extractor import extract_agent_tools_used

cases = [
    Case(
        name="Weather Query",
        input="What is the weather like in Tokyo?",
        expected_output="Should include temperature and conditions",
        expected_trajectory=["weather_api"]
    ),
    Case(
        name="Calculator Usage",
        input="What is 15% of 847?",
        expected_output="127.05",
        expected_trajectory=["calculator"]
    )
]

Next, you configure evaluators with appropriate rubrics or settings.

python
output_evaluator = OutputEvaluator(
    rubric="Score 1.0 if the response is accurate and directly answers the question. "
           "Score 0.5 if partially correct. Score 0.0 if incorrect or irrelevant."
)

trajectory_evaluator = TrajectoryEvaluator(
    rubric="Verify the agent used appropriate tools for the task."
)

Then, you create an experiment bundling cases and evaluators.

python
experiment = Experiment(
    cases=cases,
    evaluators=[output_evaluator, trajectory_evaluator]
)

Finally, you run the evaluation with your Task Function and examine the results.

python
from strands_evals.types.evaluation_report import EvaluationReport

def my_task(case):
    agent = Agent(tools=[weather_tool, calculator_tool])
    result = agent(case.input)
    return {
        "output": str(result),
        "trajectory": extract_agent_tools_used(agent.messages)
    }

reports = experiment.run_evaluations(my_task)

EvaluationReport.flatten(reports).display()

The EvaluationReport provides overall scores, per-case breakdowns, pass/fail status, and detailed reasoning from each evaluator. You can display results interactively in the console, export to JSON for further analysis, or integrate into CI/CD pipelines. For larger test suites, Strands Evals supports asynchronous evaluation with configurable parallelism:

python
reports = await experiment.run_evaluations_async(my_task, max_workers=10)

Generating test cases at scale

The previous workflow assumes that you have test cases ready. Creating comprehensive test suites by hand is tedious as your agent's capabilities grow. Strands Evals includes an ExperimentGenerator that uses LLMs to create test cases and evaluation rubrics from high-level descriptions.

python
from strands_evals.generators import ExperimentGenerator
from strands_evals.evaluators import OutputEvaluator

generator = ExperimentGenerator(
    input_type=str,
    output_type=str,
    include_expected_output=True
)

experiment = await generator.from_context_async(
    context="A customer service agent for an e-commerce platform",
    task_description="Handle customer inquiries about orders, returns, and products",
    num_cases=20,
    evaluator=OutputEvaluator
)

The generator creates diverse test cases covering different aspects of the specified context, with appropriate difficulty levels. It can also generate evaluation rubrics that are tailored to the task. Generated cases are particularly valuable during early development when you want broad coverage but have not yet identified specific failure patterns. As your evaluation practice matures, supplement generated Cases with hand-crafted scenarios targeting known edge cases.

Integrating evaluation into your workflow

Evaluation helps deliver the most value as part of your regular development workflow. During development, run evaluations frequently as you make changes. Fast feedback helps you catch regressions early and understand how changes affect different quality dimensions.

In CI/CD pipelines, include evaluation as a quality gate before deployment. Set score thresholds that must be met for a build to pass. This helps prevent quality regressions from reaching production. For production monitoring, use offline evaluation to assess real user interactions periodically. This reveals patterns that development testing might miss: unusual queries, edge cases you did not anticipate, or gradual drift in agent behavior. Track evaluation results over time. Trending metrics help you understand whether quality is improving or degrading.

Best practices for agent evaluation

  • Start small and iterate: Begin with a handful of test cases covering your most critical user scenarios. As you observe how your agent fails in practice, add targeted cases that address those specific failure modes. A focused test suite that catches real problems is more valuable than a large suite with poor coverage.
  • Match Evaluators to your quality goals: Choose evaluators that directly measure what matters for your use case. A customer-facing agent might prioritize HelpfulnessEvaluator and GoalSuccessRateEvaluator, while a research assistant might weigh FaithfulnessEvaluator more heavily. Avoid the temptation to add every available evaluator, as this increases cost and can dilute focus.
  • Write clear, specific rubrics: Rubric-based evaluators are only as good as the rubrics you provide. Avoid vague criteria like "good response" in favor of specific, measurable standards. Include examples of what constitutes high, medium, and low scores. Test your rubrics on sample outputs before running full evaluations.
  • Combine online and offline evaluation: Use online evaluation during development for fast feedback on code changes. Complement this with offline evaluation of production traces to catch issues that only appear with real user behavior. The two approaches reveal different types of problems.
  • Set meaningful thresholds: Define pass/fail thresholds based on your actual quality requirements, not arbitrary numbers. A 0.8 threshold means nothing if your users need 0.95 accuracy. Analyze evaluation results to understand what scores correlate with good user outcomes, then set thresholds accordingly.
  • Track trends over time: Individual evaluation runs provide snapshots, but trends reveal the trajectory. Store evaluation results and track key metrics across releases. Gradual degradation can be harder to notice than sudden failures, but equally damaging.
  • Invest in test case diversity: Cover the full range of inputs that your agent will encounter: common queries, edge cases, adversarial inputs, and multi-turn conversations. Use the ExperimentGenerator for broad coverage, then supplement with hand-crafted Cases targeting known weaknesses.
  • Evaluate at multiple levels: Session-level success can mask tool-level problems, and the reverse. An agent might achieve user goals through inefficient or incorrect intermediate steps. Compose evaluation suites that check quality at session, trace, and tool levels to get a complete picture.

Conclusion

Building reliable AI agents requires more than intuition and spot checks. It requires systematic evaluation that tracks quality across multiple dimensions over time. Strands Evals helps provide this foundation through a framework designed specifically for the unique challenges of agent evaluation.

Task Functions separate agent invocation from evaluation logic, enabling both online testing during development and offline analysis of production traces. LLM-based evaluators provide the judgment that quality assessment requires. Hierarchical evaluation levels allow assessment at multiple granularities, from individual tool calls to complete conversation sessions. And the user simulator transforms multi-turn testing from a scripting exercise into realistic user behavior simulation.

These capabilities help you build confidence in your AI agents through evidence rather than assumptions. You can measure whether changes improve or degrade quality, catch regressions before they reach production, and demonstrate to stakeholders that your agents meet defined quality standards.

We encourage you to explore Strands Evals for your agent evaluation needs. The samples repository contains practical examples that you can adapt to your own use cases. Start with a few test cases representing your most important user scenarios, add evaluators that match your quality criteria, and run evaluations as part of your development workflow. Over time, expand your test suite to cover more scenarios. Systematic evaluation is the foundation that helps you ship AI agents with confidence.


File: site/src/content/blog/interleaved-thinking-claude-4.mdx


title: "Using Strands Agents with Claude 4 Interleaved Thinking"
date: 2025-06-13
authors:


When we introduced the Strands Agents SDK, our goal was to make agentic development simple and flexible by embracing a model-driven approach. Today, we're excited to highlight how you can use Claude 4's interleaved thinking beta feature with Strands to further simplify how you write AI agents to solve complex tasks with tools. With a model-driven approach, developers no longer need to define a rigid workflow to call tools and parse model responses at each step to complete a task. With Strands Agents, you equip a model with tools and a prompt, letting it plan, chain thoughts, call tools, and reflect. Strands manages an event loop around model calls until it considers the task completed, returning a response to the client. Let's consider how it works with this simple example (assuming you have completed the quickstart):

python
from strands import Agent
from strands_tools import http_request, python_repl

agent = Agent(
    model="us.anthropic.claude-sonnet-4-20250514-v1:0",
    tools=[http_request, python_repl]
)

prompt="""
Which of the following cities is closest to the ISS?
Portland, Vancouver, Seattle, or New York?

Include the current altitude of the ISS, and the distance and vector from the closest city to the ISS.
"""

agent(prompt)

Strands has everything it needs to provide an answer, equipped with Claude 4 Sonnet, its prompt, and tools to generate Python code and make HTTP requests. Here's how the event loop works.

First, Strands structures your prompt and any previous conversation history into a format the language model (like Claude) can understand. Then, Strands automatically loads available toolsโ€”these can be MCP Server tools or custom Python functions decorated with @tool. Your Python docstrings become tool descriptions, and type hints define the parameter schemas. In this example, we use two built-in tools from the strands-agents-tools package. The SDK manages errors (like rate limiting or context overflows), performs retries when needed, and emits detailed traces and metrics for observability.

With this setup complete, Strands manages an event loop that invokes the model, handles tool calling, and manages the conversation until the model provides a final answer.

  1. Model invocation and reasoning: The event loop calls the language model with the current conversation state, prompt, and tools. The model streams its responses, including step-by-step reasoning that you can observe as it "thinks out loud."
  2. Tool use detection and execution: If the model decides it needs to call a tool (to fetch data, perform a calculation, etc.), the event loop detects this request, validates it, and executes the corresponding Python function or MCP Server tool with the parameters provided by the model.
  3. Context update: The result of the tool execution is appended to the ongoing conversation, allowing the model to incorporate the new information into its next iteration.

You will see this loop in action when running the ISS example with Python. The model makes a plan to use its tools, including API calls for real-time data about the ISS and using its Python REPL (Read evaluate print loop) to calculate distances and vectors. The agent will respond with an answer to the question, including a statement like "The ISS is currently positioned over the western Pacific Ocean, making the western North American cities (Vancouver, Seattle, Portland) much closer than New York. Vancouver's slightly more northern latitude gives it the advantage over Seattle and Portland."

The model makes a plan to use its tools, involving API calls for real-time data about the ISS and using its Python REPL to calculate distances and vectors. It then generates an answer and shows its work. The following is example output from this agent running locally.

text
To answer this question, I need to:
1. Get the current position of the ISS (International Space Station)
2. Get the coordinates of the four cities: Portland, Vancouver, Seattle, and New York
3. Calculate the distance from each city to the ISS
4. Determine which is closest and provide the requested information
First, I need to find an API that provides the current ISS position. There are several free APIs available for this, such as:
- http://api.open-notify.org/iss-now.json (provides current ISS position)
- Others that might provide more detailed information
Let me start by getting the current ISS position.I'll help you find which city is closest to the ISS by getting the current position of the International Space Station and calculating distances. Let me start by fetching the current ISS location.
Tool #1: http_request
Great! I got the current ISS position:
- Latitude: -24.4214ยฐ
- Longitude: 14.4347ยฐ
- Timestamp: 1749832513
Now I need to get the altitude of the ISS. The basic API doesn't provide altitude, but I know the ISS orbits at approximately 400-420 km altitude. Let me try to find a more detailed API or use a known average.
Actually, let me try another API that might give more details about the ISS:Now let me get more detailed information about the ISS including its altitude:
Tool #2: http_request
Perfect! Now I have more detailed ISS information:
- Name: ISS
- Latitude: -24.844251408166ยฐ
- Longitude: 14.692696204258ยฐ
- Altitude: 422.41885597014 km
- Velocity: 27570.247286017 km/h
- Timestamp: 1749832520
Now I need to calculate the distances from each city to the ISS. For this, I'll need the coordinates of each city and then calculate 3D distances considering the ISS altitude.
The cities I need coordinates for:
1. Portland (I'll assume Portland, Oregon)
2. Vancouver (I'll assume Vancouver, BC, Canada)
3. Seattle, Washington
4. New York, New York
Let me use Python to calculate these distances. Perfect! Now I have the current ISS data. Let me calculate the distances from each city to the ISS using Python:
Tool #3: python_repl
Current ISS Position:
Latitude: -24.844251408166ยฐ
Longitude: 14.692696204258ยฐ
Altitude: 422.42 km
Portland:
  Coordinates: 45.5152ยฐ, -122.6784ยฐ
  3D Distance to ISS: 15588.43 km
  Surface Distance: 15582.71 km
Vancouver:
  Coordinates: 49.2827ยฐ, -123.1207ยฐ
  3D Distance to ISS: 15484.80 km
  Surface Distance: 15479.03 km
Seattle:
  Coordinates: 47.6062ยฐ, -122.3321ยฐ
  3D Distance to ISS: 15493.28 km
  Surface Distance: 15487.52 km
New York:
  Coordinates: 40.7128ยฐ, -74.006ยฐ
  3D Distance to ISS: 11680.55 km
  Surface Distance: 11672.91 km
CLOSEST CITY: New York
Distance: 11680.55 km
Great! Now I have all the distances calculated. New York is the closest city to the ISS. Now I need to calculate the vector from New York to the ISS. A vector would include both the direction and magnitude. I should calculate:
1. The bearing (direction) from New York to the ISS
2. The elevation angle
3. The distance (which I already have)
Let me calculate these additional details.Now let me calculate the vector (direction and elevation) from New York to the ISS:
Tool #4: python_repl
==================================================
FINAL RESULTS
==================================================
International Space Station Current Status:
โ€ข Altitude: 422.42 km above Earth
โ€ข Position: -24.8443ยฐ, 14.6927ยฐ
โ€ข Location: Over the South Atlantic Ocean
Distance Analysis:
โ€ข Portland, OR: 15588.43 km
โ€ข Vancouver, BC: 15484.80 km
โ€ข Seattle, WA: 15493.28 km
โ€ข New York, NY: 11680.55 km
CLOSEST CITY: NEW YORK
โ€ข Distance: 11680.55 km
โ€ข Bearing: 110.1ยฐ (ESE)
โ€ข Elevation angle: 2.1ยฐ above horizon
Vector from New York to ISS:
โ€ข Direction: 110.1ยฐ bearing (ESE)
โ€ข Elevation: 2.1ยฐ above horizontal
โ€ข Distance: 11680.55 km
Perfect! I now have all the information requested. Let me summarize the key findings:
1. **Current ISS altitude**: 422.42 km above Earth
2. **Closest city**: New York is closest to the ISS
3. **Distance and vector**:
   - Distance: 11,680.55 km
   - Direction: 110.1ยฐ bearing (East-Southeast)
   - Elevation: 2.1ยฐ above horizon
The ISS is currently positioned over the South Atlantic Ocean at coordinates -24.8443ยฐ, 14.6927ยฐ. Among the four cities, New York is significantly closer than the other three cities (which are all on the US/Canadian west coast and much farther from the ISS's current position).## Answer: **New York** is the closest city to the ISS
### Current ISS Status:
- **Altitude:** 422.42 km above Earth
- **Position:** 24.84ยฐS, 14.69ยฐE (over the South Atlantic Ocean)
### Distance Comparison:
- **New York, NY:** 11,680.55 km โœ… **CLOSEST**
- **Vancouver, BC:** 15,484.80 km
- **Seattle, WA:** 15,493.28 km
- **Portland, OR:** 15,588.43 km
### Vector from New York to ISS:
- **Distance:** 11,680.55 km
- **Direction:** 110.1ยฐ bearing (East-Southeast)
- **Elevation:** 2.1ยฐ above the horizon
The ISS is currently positioned over the South Atlantic Ocean, making New York significantly closer than the three Pacific Northwest cities. New York is about 4,800 km closer to the ISS than the nearest west coast city (Vancouver).

Supercharging the Strands event loop with Claude 4's interleaved thinking

Claude 4 introduces a beta feature called "interleaved thinking" which fits perfectly with Strands' model-driven approach. This enables Claude to reflect after a tool call and adjust its plan dynamically without needing to complete the current event loop iteration. Interleaved thinking expands on the model's ability to self-reflect, correct errors, and orchestrate a workflow of reasoning and tool use.

If you're using Amazon Bedrock as your Strands model provider, you can turn on interleaved thinking by specifying the additional request fields parameter to Bedrock:

python
from strands import Agent
from strands_tools import http_request, python_repl
from strands.models import BedrockModel

model = BedrockModel(
    model_id="us.anthropic.claude-sonnet-4-20250514-v1:0",
    additional_request_fields={
        "anthropic_beta": ["interleaved-thinking-2025-05-14"],
        "thinking": {"type": "enabled", "budget_tokens": 8000},
    },
)

agent = Agent(
    model=model,
    tools=[http_request, python_repl]
)

If you enable tracing with Strands, you'll see additional blocks of "reasoningContent" in your trace, like in the following image, including reasoning when Claude 4 decides to interleave thinking after tool calls.

For example, in this response there is an erroneous calculation from a tool call, which Claude could identify and fix immediately, before continuing to the next iteration of the event loop.

text
City Rankings (closest to farthest):
1       Vancouver: 12027.19 km
2       Seattle: 12144.49 km
3       Portland: 12195.86 km
4       New York: 15432.29 km
The calculation for longitude difference looks wrong - it's showing 243.6443ยฐ which is more than 180ยฐ. This happens because we're dealing with the international date line. Let me correct this calculation to show the actual shortest path. Let me correct the longitude calculation to show the actual shortest path:
Tool #6: python_repl
CORRECTED VECTOR CALCULATION:
ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹ใƒ‹
ISS Current Altitude: 418.15 km above Earth's surface
Closest City: Vancouver, BC
Distance to ISS: 12027.19 km
Vector from Vancouver to ISS:
- **Distance:** 12027.19 km
- **Direction:** 110.1ยฐ bearing (East-Southeast)
- **Elevation:** 2.1ยฐ above the horizon

Compared to the traditional ReAct method, the interleaved thinking approach is faster and more fluid. You can think of ReAct like a detective taking notes and making deductions step by step, whereas interleaved thinking is more like a domain expert mentally juggling facts while explaining a concept. In other words, thought and action happen in one thinking block, not another complete loop.

Here's another example where Claude was able to reduce the number of tool calls by noticing it could calculate the answer from the information retrieved in its first API call, which otherwise would have only been determined in a second iteration of the event loop.

text
Let me start by getting the ISS position. I'll help you find which city is closest to the ISS by getting the current ISS position and calculating distances. Let me start by fetching the current ISS location.
Tool #1: http_request
Great! I got the ISS position. Now I need to get the altitude of the ISS. The Open Notify API doesn't provide altitude in the basic position endpoint, but I know the ISS typically orbits at around 400-420 km altitude. Let me check if there's another endpoint that provides more detailed information.
Actually, let me use Python to calculate the distances between the ISS and each city. I'll need to: Define the coordinates of each city, Calculate the distance from each city to the ISS position, Account for the ISS altitude in the calculation
The ISS position shows:
โƒ       Latitude: 44.7381ยฐ
โƒ       Longitude: 169.1833ยฐ
This puts the ISS somewhere over the Pacific Ocean, likely between Russia and Alaska.

These examples only scratch the surface of what you can build with Strands and Claude 4 using interleaved thinking. We've published additional agent samples tackling more complex problems and equipped with numerous tools, like this one demonstrating interleaved thinking. Using these examples, you'll see more dynamic reasoning from Claude, like learning from a failed tool call and retrying with refined parameters, or coming up with new strategies on the fly instead of looping the same strategy across multiple tool calls.

We built Strands Agents to simplify agent development by embracing models like Claude 4 that do a great job of breaking down problems into tool workflows that achieve results. We can't wait to see what you build with Strands. Join the discussion at https://github.com/strands-agents/sdk-python.

Jawhny Cooke, Vadim Omeltchenko, and Mark Roy contributed to this post.


File: site/src/content/blog/introducing-strands-agent-sops.mdx


title: "Introducing Strands Agent SOPs โ€“ Natural Language Workflows for AI Agents"
date: 2025-11-20
authors:


Modern AI can write code, compose symphonies, and solve complex reasoning problems. So why is it still so hard to get them to reliably do what you want?

Building reliable AI agents that consistently perform complex tasks remains challenging. While modern language models excel at reasoning and problem-solving, translating that capability into predictable workflows often requires extensive state machines to orchestrate agent behavior. A code-defined workflow gives maximum control over the behavior of an agent, but changing the system requires writing hundreds of lines of code to account for a new behavior. This represents one extreme of the control-flexibility spectrum for developing agents.

At the other end of this spectrum, Model-Driven agents do away with code-defined behavior entirely, performing their own orchestration instead. In place of thousands of lines of code defining workflows, we give the agent autonomy to decide its own path to solving a problem. Model-Driven agents are resilient to unexpected inputsโ€”their non-deterministic nature enables flexible adaptation to any situation. However, this flexibility comes at a cost: it is difficult to steer the agent in a reliable manner to consistently accomplish a goal.

What if there was a way to get the best of both worlds?

Enter Agent SOPs (Standard Operating Procedures): a standardized markdown format for defining AI agent workflows in natural language that acts as a powerful middle-ground between flexibility and control. These natural language instruction sets transform complex processes into reusable, shareable workflows that work across different AI systems and teams. By combining structured guidance with the flexibility that makes AI agents powerful, Agent SOPs enable teams to encode proven workflows into reusable templates and apply them consistently wherever intelligent automation is needed. This concept, which emerged from innovation within Amazon's internal builder community, has rapidly spread across the company as teams discover its potential to steer agent behavior.

From Internal Innovation to Open Source

At Amazon, we have a thriving community of tens of thousands of builders who actively experiment with and innovate on the use of AI in their daily work. This community spans AWS service teams, Amazon retail operations, logistics, and research groups, united by a culture of rapid experimentation and knowledge sharing around AI-powered development tools.

When agentic AI coding assistants first became available internally, our builders immediately began pushing the boundaries of what was possible. Teams started leveraging them to automate everything from code reviews and documentation generation to incident response and system monitoring. But as adoption scaled, we ran into multiple problems:

Inconsistent behavior was perhaps the most frustrating challenge. The same agent that performed flawlessly during development produced wildly different results when handling real-world scenarios. Without structured guidance, agents made different decisions about tool usage, task prioritization, and output formatting, leading to unpredictable outcomes that undermined confidence and frustrated users.

Prompt engineering complexity created another barrier to adoption. Crafting effective prompts for sophisticated workflows required deep expertise in both the domain and language model behavior. Teams spent weeks perfecting prompts for complex tasks, only to discover their instructions didn't transfer well to different models or use cases. Developers became hesitant to update prompts because they couldn't predict how changes would affect output, leading to long delays as (human) evaluations were performed before any modifications could be made.

The breakthrough came when we realized we needed something that hit a "determin-ish-tic" sweet spot: structured enough to ensure consistent outcomes, but flexible enough to leverage the intelligence that makes AI agents valuable. That insight led our community to develop Agent SOPs, a standardized markdown format for defining AI agent workflows that balances reliability with adaptability.

Our community rapidly adopted the concept because it solved real problems that every team was facing. Teams discovered they could generate an initial automation in minutes without any prompt engineering expertise, creating workflows that were immediately useful, understandable, and easily shareable. The structured approach dramatically reduced the trial-and-error process of prompt development while preserving the intelligence that made AI automation valuable. Teams could iterate on specific behaviors of an SOP with higher confidence of not breaking existing functionality, making improvements faster and more predictable.

Today, Amazon teams use thousands of SOPs across a variety of different use cases, from code reviews and documentation generation to incident response and system monitoring. The consistent format made it easy to share successful approaches between teams while adapting them for different contexts and requirements. What started as a simple solution to prompt engineering problems became a powerful way to democratize AI expertise across our entire organization.

Now we're making Agent SOPs available as open source because we believe this approach can benefit the broader AI development community. By sharing both the concept and practical examples, we hope to accelerate the adoption of reliable AI workflows across the industry.

What Are Agent SOPs?

Agent SOPs use a standardized markdown format with key features that enable repeatable and understandable behavior from AI agents:

  1. Structured steps with RFC 2119 constraints โ€“ Each workflow step uses RFC 2119 keywords like MUST, SHOULD, and MAY to provide precise control over agent behavior without rigid scripting, ensuring reliable execution while preserving the agent's reasoning ability.
  2. Parameterized inputs โ€“ Rather than hardcoding specific values, SOPs accept parameters that customize behavior for different projects, teams, or requirements. This transforms single-use prompts into flexible templates that can be applied broadly while maintaining consistency.
  3. Easy authoring through AI assistance โ€“ Teams can create new SOPs in minutes. Coding agents can read the SOP format specification and generate new workflows based on natural language descriptions, making the creation process accessible to anyone regardless of prompt engineering expertise.
  4. Progress tracking and resumability โ€“ Agent SOPs can instruct agents to document their progress as they work, making it easy to understand what's happening and resume if something breaks. This transparency was crucial for debugging prompts and building developer trust in AI automation.

The format is simple but highly versatile, working anywhere natural language instructions are accepted. Agent frameworks like Strands can embed SOPs as system prompts, development tools like Kiro and Cursor can use them for structured workflows, and AI models like Claude and GPT-4 can execute them directly. While different models may vary in their ability to follow instructions precisely, the standardized format provides a consistent foundation for workflow automation.

Walkthrough: Running the Codebase Summary SOP

Let's walk through how Agent SOPs work in practice by running the codebase-summary SOP. In this example, we will use Kiro CLI, but you can try this walkthrough in any AI agent that supports Model Context Protocol (MCP) servers.

First, install the strands-agents-sops Python package:

bash
pip install strands-agents-sops

Next, update your MCP server configuration to include the strands-agents-sops MCP server:

json
{
  "mcpServers" : {
    "strands-agents-sops" : {
      "command" : "strands-agents-sops",
      "args" : []
    }
  }
}

This MCP server makes SOPs available as MCP prompts that can be invoked by your AI assistant. In Kiro CLI, we can confirm that the pre-packaged Agent SOPs are now available via the /prompts command:

text
[strands-agents-sop] > /prompts


Usage: You can use a prompt by typing '@<prompt name> [...args]'


Prompt                               Description                              Arguments (* = required)
โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”โ–”
strands-agents-sop (MCP):
- code-assist                        This sop guides the implementation of... user_input
- code-task-generator                This sop generates structured code ta... user_input
- codebase-summary                   This sop analyzes a codebase and gene... user_input
- pdd                                This sop guides you through the proce... user_input

Next, we invoke the codebase-summary SOP:

text
@codebase-summary

Kiro CLI reads the SOP and asks for required and optional parameters:

text
> I'll help you run the codebase summary SOP. Let me gather the required parameters first.

Please provide the following parameters for the codebase analysis:

Required Parameters:
โ€ข **codebase_path**: Path to the codebase to analyze (default: current directory)

Optional Parameters:
โ€ข **output_dir**: Directory where documentation will be stored (default: ".sop/summary")
โ€ข **consolidate**: Whether to create a consolidated documentation file (default: false)
โ€ข **consolidate_target**: Target file for consolidation like "AGENTS.md", "README.md", "CONTRIBUTING.md" (default: "AGENTS.md")
โ€ข **consolidate_prompt**: Description of how to structure the consolidated content
โ€ข **check_consistency**: Whether to check for inconsistencies across documents (default: true)
โ€ข **check_completeness**: Whether to identify areas lacking sufficient detail (default: true)
โ€ข **update_mode**: Whether to update existing documentation based on recent commits (default: false)

You can provide these parameters in any of these ways:
โ€ข Direct input in your response
โ€ข File path containing the configuration
โ€ข Just specify what you want to change from defaults

What parameters would you like to use for this codebase analysis?

We provide the requested parameters in natural language. In this example, we'll run this SOP on the strands-agents-sop python source code:

text
[strands-agents-sop] > codebase_path: ~/github/agent-sop/python
consolidate: true
consolidate_target: README.md

The agent then follows the SOP's structured steps, starting with setting up the directory structure. You can see that the agent validates the codebase path exists, because the SOP constraints specify that the agent MUST validate the path exists before proceeding:

text
## Step 1: Setup and Directory Structure

...

> โœ… Validated codebase path exists and is accessible
โœ… Created directory .summary/
โœ… Full analysis will be performed (not in update mode)

The SOP's steps and constraints guide the agent through systematic analysis of the codebase, analyzing the codebase structure, generating documentation files, reviewing and consolidating the documentation into a README.md file, and ending with providing a summary:

text
## Step 6: Summary and Next Steps

## Summary

โœ… Documentation generation complete!

### What Was Accomplished

โ€ข **Analyzed** Python package with 4 core modules and 5 SOP files
โ€ข **Generated** comprehensive documentation ecosystem in .summary/ directory:
  โ€ข index.md: Knowledge base index with AI assistant instructions
  โ€ข codebase_info.md: Project overview and structure
  โ€ข architecture.md: System design and patterns
  โ€ข components.md: Module responsibilities and functionality
  โ€ข interfaces.md: APIs, CLI, and integration points
  โ€ข data_models.md: SOP format and data structures
  โ€ข workflows.md: Build process and operational procedures
  โ€ข dependencies.md: External requirements and usage
  โ€ข review_notes.md: Quality assessment and recommendations
โ€ข **Consolidated** all information into user-friendly README.md
โ€ข **Identified** system as modular CLI tool with MCP server capabilities

### Key Findings

โ€ข **Architecture**: Clean modular design with dynamic SOP loading
โ€ข **Integration**: Multiple interfaces (Python imports, MCP protocol, CLI, Anthropic skills)
โ€ข **Content Management**: File-based SOP storage with build-time synchronization
โ€ข **Dependencies**: Minimal external requirements (only MCP library)
โ€ข **Extensibility**: Easy to add new SOPs without code changes

<summary continues...>

Using this SOP, by invoking a single prompt, our agent was able to produce comprehensive codebase documentation without additional human interaction. The SOP's constraints ensured consistent structure and completeness while the agent's intelligence adapted the content to the specific codebase characteristics.

SOP Chaining: Building Complete Development Workflows

SOP Chaining enables agents to execute complex, multi-phase workflows by connecting focused SOPs into intelligent sequences. The initial SOP repository includes a complete development workflow chain that demonstrates SOPs working together to take you from understanding an existing codebase to implementing new features:

  1. codebase-summary analyzes codebases and generates comprehensive documentation that helps both humans and AI agents understand system architecture, components, and workflows. This SOP typically serves as the foundation, providing context for subsequent automation.
  2. pdd implements "prompt-driven development" methodology (an internal predecessor to Kiro's spec-driven development), taking the user from a rough idea through systematic research, requirements clarification, solution design, and implementation planning. Use this after understanding your codebase to tackle complex feature planning.
  3. code-task-generator breaks down high-level requirements into actionable development tasks, showing how SOPs can handle creative and analytical work that requires understanding context and making informed decisions about scope and priority. Use this as a standalone tool or in conjunction with the output of the pdd SOP.
  4. code-assist implements a test-driven development workflow that guides agents through feature implementation using structured exploration, planning, coding, and commit phases. This SOP shows how to balance automated execution with human oversight.

SOP Chaining works through artifact handoffs: codebase-summary creates documentation files that pdd references when designing features, pdd produces specifications that code-task-generator uses to create task lists, and code-assist implements those tasks with full awareness of previously established architecture and requirements. Each SOP condenses its discoveries into focused outputs that become streamlined inputs for the next step.

This chaining approach enables workflows far beyond what a single agent could handle. Rather than overwhelming one agent with an entire development cycleโ€”causing it to lose focus and deviate from expected behaviorโ€”you can decompose complex problems into manageable pieces. When developing Agent SOPs, this modular approach lets you build and test each component independently, then chain them together into sophisticated workflows. The sequential structure eliminates redundant work (no repeated codebase analysis or information gathering) while maintaining the intelligent adaptation that makes agents valuable, ultimately enabling automation at a scale that would be difficult with monolithic approaches.

Agent SOP Integrations

Agent SOPs are not tied to a specific agentic product and work in many environments:

Strands Agents

Agent SOPs can be used as the system prompts for your Strands agents. Simply install the PyPI package, then import an SOP as an agent's system prompt. Here is an example of a code-assist CLI agent:

python
from strands import Agent
from strands_tools import editor, shell
from strands_agents_sops import code_assist

agent = Agent(
  system_prompt=code_assist,
  tools=[editor, shell]
)

agent("Start code-assist sop")

while(True):
  agent(input("\nInput: "))

After executing this Python script, you may see an output that looks something like this:

text
I'll help you implement a code task using the test-driven development workflow. Let me gather the required parameters to get started.

Please provide the following information:

**Required:**
- **task_description**: What would you like to implement? (You can provide a detailed specification, requirements, acceptance criteria, or even a rough idea that we'll refine together. You can also provide a file path or URL if the description is in a document)

**Optional:**
- **additional_context**: Any supplementary information that would help with understanding the implementation context (can also be a file path or URL)
- **documentation_dir**: Directory for planning documents (default: ".sop/planning")
- **repo_root**: Root directory of the repository (default: current working directory)
- **task_name**: A short, descriptive name for the task (I'll generate one if not provided)
- **mode**: Interaction mode:
  - "interactive" (default): I'll collaborate with you and ask for confirmation at each step
  - "auto": I'll execute autonomously after setup with no further interaction required

Please provide these details so we can begin the implementation process.

Building on the codebase-summary example from earlier, you can create a Strands agent that automatically keeps your documentation current:

python
from strands import Agent
from strands_tools import editor, shell, git
from strands_agents_sops import codebase_summary

doc_agent = Agent(
 system_prompt=codebase_summary,
 tools=[editor, shell, git]
)

# Run in update mode to refresh docs based on recent commits
doc_agent("Run codebase-summary with update_mode: true")

This enables continuous documentation maintenance without manual intervention, automatically updating your codebase summary as new changes are made.

Claude Skills

Agent SOPs are fully compatible with Claude's Skills system, allowing you to teach Claude specialized workflows that can be reused across conversations and projects.

Each Agent SOP can be automatically converted to Anthropic's Skills format:

bash
# Generate Skills format from SOPs
strands-agents-sops skills

# Or specify custom output directory
strands-agents-sops skills --output-dir my-skills

This creates individual skill directories:

text
skills/
โ”œโ”€โ”€ code-assist/
โ”‚   โ””โ”€โ”€ SKILL.md
โ”œโ”€โ”€ codebase-summary/
โ”‚   โ””โ”€โ”€ SKILL.md
โ”œโ”€โ”€ code-task-generator/
โ”‚   โ””โ”€โ”€ SKILL.md
โ””โ”€โ”€ pdd/
    โ””โ”€โ”€ SKILL.md

You can then follow Anthropic's documentation to start using these SOPs as skills.

Additional Product Integrations

Agent SOPs work across a wide variety of AI development environments. While different LLMs may vary in their instruction-following capabilities, the standardized format provides consistent results across platforms. Here are additional ways teams are using Agent SOPs:

Kiro IDE steering files and hooks โ€“ SOPs can be integrated into Kiro IDE's workflow system to provide structured guidance for specific development tasks.

Custom commands in Claude Code and Cursor โ€“ SOPs make great custom commands to invoke specific SOPs for common development workflows.

Python modules โ€“ Programmatic access enables integration into custom applications and larger automation systems.

Authoring Agent SOPs

One of the most powerful aspects of Agent SOPs is how easy it is to create them through conversational authoring. We provide an Agent SOP format rule that steers AI models to capture your natural workflow description and transform it into the standardized format. Let's walk through authoring a simple SOP for processing meeting notes to illustrate.

Depending on which AI application you use, you can install the Agent SOP format as a steering file or rule. However, for the purposes of this walkthrough, let's have Kiro CLI read the Agent SOP rule directly:

text
[strands-agents-sop] > Run `strands-agents-sops rule`
...
> The command executed successfully and displayed the Agent SOP format specification.
...

Now that Kiro CLI understands the Agent SOP format, we simply describe what we want in natural language to our AI assistant:

text
[strands-agents-sop] > I want to create an Agent SOP that takes meeting notes and generates action items, decisions made, and follow-up tasks with assigned owners and deadlines.

The AI assistant, having access to the SOP format specification, generates a first draft Agent SOP in seconds. It creates appropriate parameters, structures the workflow into logical steps, and adds RFC 2119 constraints to make the SOP reliable and repeatable.

Since it's written in natural language, the Agent SOP is easy to read. We can try running it in a separate session and come back and chat with our agent to iterate on improving the SOP. For example, we could refine this SOP to use a specific folder structure, logging action items in both a meeting notes folder and a follow ups folder, and adding decisions made to a project-specific decision log.

This same approach works for any workflow you want to automate. Simply describe the process in natural language, and let AI assistance handle the technical details of SOP creation. Note, if you want your SOP to use specific MCP tools, you will need to have those MCP servers loaded while authoring the SOP.

Conclusion

Agent SOPs resolve the fundamental tension between reliability and flexibility that has limited AI automation adoption. By combining structured guidance with intelligent reasoning, they enable teams to capture expertise quickly and apply it consistently across different AI systems and contexts. The semi-deterministic sweet spot that made Agent SOPs successful at Amazon is now available for customers everywhere to build more reliable and capable AI systems.

Ready to get started?

  • Visit the Agent SOPs GitHub repository for complete documentation and examples
  • Install the package: pip install strands-agents-sops
  • Start the MCP server: strands-agents-sops
  • Try the codebase-summary SOP on your next project
  • Chain SOPs together for sophisticated development workflows

We're excited to see how customers use Agent SOPs to solve their unique automation challenges and what innovative workflows emerge from the broader community.