Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 94 additions & 0 deletions lambda-strands-agent-bedrock-cdk/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
# AWS Lambda with Strands Agents SDK and Amazon Bedrock

This pattern deploys an AWS Lambda function running a [Strands Agents SDK](https://strandsagents.com/) agent with Amazon Bedrock as the model provider. The agent uses custom Python tools that the model invokes autonomously during reasoning.

Learn more about this pattern at Serverless Land Patterns: https://serverlessland.com/patterns/lambda-strands-agent-bedrock-cdk

Important: this application uses various AWS services and there are costs associated with these services after the Free Tier usage - please see the [AWS Pricing page](https://aws.amazon.com/pricing/) for details. You are responsible for any AWS costs incurred. No warranty is implied in this example.

## Requirements

* [Create an AWS account](https://portal.aws.amazon.com/gp/aws/developer/registration/index.html) if you do not already have one and log in. The IAM user that you use must have sufficient permissions to make necessary AWS service calls and manage AWS resources.
* [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html) installed and configured
* [Git Installed](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
* [Node and NPM](https://nodejs.org/en/download/) installed
* [AWS CDK](https://docs.aws.amazon.com/cdk/latest/guide/cli.html) installed
* [Amazon Bedrock model access](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access.html) enabled for Anthropic Claude Sonnet in your target region

## Architecture

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you please add an architecture diagram?

@NithinChandranR-AWS NithinChandranR-AWS Jul 3, 2026

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added a text diagram and fixed the model resolution handler now reads MODEL_ID from env, and the CDK derives the region prefix automatically.


```
┌──────────┐ ┌───────────────────────────────────────────┐ ┌─────────────────┐
│ │ │ AWS Lambda │ │ │
│ Client │──────▶│ Strands Agents SDK │◀─────▶│ Amazon Bedrock │
│ │ │ ┌─────────┐ ┌────────────────────────┐ │ │ (Claude Sonnet) │
└──────────┘ │ │ Agent │ │ Tools: calculate, ... │ │ └─────────────────┘
│ └─────────┘ └────────────────────────┘ │
└───────────────────────────────────────────┘
```

The pattern creates an AWS Lambda function with the Strands Agents SDK layer. The function uses Amazon Bedrock (Claude Sonnet 4.6) for reasoning and can invoke registered Python tools during the conversation loop. The model ID is derived from the deploy region (`us.`, `eu.`, or `apac.` prefix) so the pattern works in any supported region.

## How it works

1. A client invokes the AWS Lambda function with a JSON payload containing a `prompt` field.
2. The AWS Lambda function initializes a Strands Agents SDK agent with the official AWS Lambda layer (no custom packaging required).
3. The agent uses Amazon Bedrock (Claude Sonnet) as its reasoning engine.
4. When the model decides a tool is needed, the SDK automatically invokes the registered Python tool (e.g., `calculate`) and feeds the result back to the model.
5. The agent returns the final response to the caller.

## Deployment

1. Clone the repository and navigate to the pattern directory:
```bash
git clone https://github.com/aws-samples/serverless-patterns
cd serverless-patterns/lambda-strands-agent-bedrock-cdk
```

2. Install dependencies:
```bash
npm install
```

3. Deploy the stack:
```bash
cdk deploy
```

## Verification

After deployment, verify the stack outputs:

```bash
aws cloudformation describe-stacks --stack-name LambdaStrandsAgentBedrockStack --query 'Stacks[0].Outputs'
```

## Testing

Invoke the AWS Lambda function with a prompt:

```bash
aws lambda invoke \
--function-name $(aws cloudformation describe-stacks \
--stack-name LambdaStrandsAgentBedrockStack \
--query 'Stacks[0].Outputs[?OutputKey==`FunctionName`].OutputValue' \
--output text) \
--cli-binary-format raw-in-base64-out \
--payload '{"prompt": "What is 25 * 47 + 13?"}' \
output.json

cat output.json | python3 -m json.tool
```

Expected output: The agent will use the `calculate` tool to compute `25 * 47 + 13 = 1188` and explain its reasoning.

## Cleanup

```bash
cdk destroy
```

----
Copyright 2026 Amazon.com, Inc. or its affiliates. All Rights Reserved.

SPDX-License-Identifier: MIT-0
12 changes: 12 additions & 0 deletions lambda-strands-agent-bedrock-cdk/bin/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#!/usr/bin/env node
import "source-map-support/register";
import * as cdk from "aws-cdk-lib";
import { LambdaStrandsAgentBedrockStack } from "../lib/lambda-strands-agent-bedrock-stack";

const app = new cdk.App();
new LambdaStrandsAgentBedrockStack(app, "LambdaStrandsAgentBedrockStack", {
env: {
account: process.env.CDK_DEFAULT_ACCOUNT,
region: process.env.CDK_DEFAULT_REGION,
},
});
3 changes: 3 additions & 0 deletions lambda-strands-agent-bedrock-cdk/cdk.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"app": "npx ts-node --prefer-ts-exts bin/app.ts"
}
69 changes: 69 additions & 0 deletions lambda-strands-agent-bedrock-cdk/example-pattern.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
{
"title": "AWS Lambda with Strands Agents SDK and Amazon Bedrock",
"description": "Deploy a Strands Agents SDK agent on AWS Lambda using the official Lambda layer, with Amazon Bedrock as the model provider and custom tool use.",
"language": "Python",
"level": "300",
"framework": "AWS CDK",
"services": {
"from": "lambda",
"to": "bedrock"
},
"introBox": {
"headline": "How it works",
"text": [
"This pattern deploys an AWS Lambda function running a Strands Agents SDK agent with Amazon Bedrock as the model provider. The agent uses custom Python tools that the model can invoke autonomously during reasoning.",
"The Strands Agents SDK is an open source framework from AWS that takes a model-driven approach to building AI agents. Instead of hardcoding task flows, the SDK lets the LLM handle planning and tool usage. The official Lambda layer provides the SDK without custom packaging."
]
},
"gitHub": {
"template": {
"repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/lambda-strands-agent-bedrock-cdk",
"templateURL": "serverless-patterns/lambda-strands-agent-bedrock-cdk",
"projectFolder": "lambda-strands-agent-bedrock-cdk",
"templateFile": "lib/lambda-strands-agent-bedrock-stack.ts"
}
},
"resources": {
"bullets": [
{
"text": "Strands Agents SDK",
"link": "https://strandsagents.com/"
},
{
"text": "Deploying Strands Agents to AWS Lambda",
"link": "https://strandsagents.com/docs/user-guide/deploy/deploy_to_aws_lambda/"
},
{
"text": "Amazon Bedrock",
"link": "https://aws.amazon.com/bedrock/"
},
{
"text": "Serverless ICYMI Q1 2026",
"link": "https://aws.amazon.com/blogs/compute/serverless-icymi-q1-2026/"
}
]
},
"deploy": {
"text": [
"<code>cdk deploy</code>"
],
"file": "lib/lambda-strands-agent-bedrock-stack.ts"
},
"testing": {
"text": [
"See the README for testing instructions."
]
},
"cleanup": {
"text": [
"<code>cdk destroy</code>"
]
},
"authors": [
{
"name": "Nithin Chandran R",
"bio": "Technical Account Manager at AWS",
"linkedin": "nithin-chandran-r"
}
]
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import * as cdk from "aws-cdk-lib";
import * as iam from "aws-cdk-lib/aws-iam";
import * as lambda from "aws-cdk-lib/aws-lambda";
import { Construct } from "constructs";

export class LambdaStrandsAgentBedrockStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);

// Strands Agents official AWS Lambda layer (Python 3.12, x86_64)
const strandsLayer = lambda.LayerVersion.fromLayerVersionArn(
this,
"StrandsAgentsLayer",
`arn:aws:lambda:${this.region}:856699698935:layer:strands-agents-py3_12-x86_64:1`
);

// Agent AWS Lambda function
const agentFn = new lambda.Function(this, "StrandsAgentFn", {
runtime: lambda.Runtime.PYTHON_3_12,
handler: "index.handler",
code: lambda.Code.fromAsset("src/agent"),
timeout: cdk.Duration.minutes(2),
memorySize: 512,
architecture: lambda.Architecture.X86_64,
Comment thread
marcojahn marked this conversation as resolved.
layers: [strandsLayer],
environment: {
MODEL_ID: `${this.region.startsWith('eu') ? 'eu' : this.region.startsWith('ap') ? 'apac' : 'us'}.anthropic.claude-sonnet-4-6`,
},
description: "Strands Agents SDK agent on AWS Lambda with Amazon Bedrock",
});

// Bedrock invoke permissions — wildcard region covers cross-region inference profile routing
agentFn.addToRolePolicy(
new iam.PolicyStatement({
actions: [
"bedrock:InvokeModel",
"bedrock:InvokeModelWithResponseStream",
],
resources: [
`arn:aws:bedrock:*:${this.account}:inference-profile/*anthropic.claude-sonnet-4-6*`,
`arn:aws:bedrock:*::foundation-model/anthropic.claude-sonnet-4-6*`,
],
})
);
Comment thread
marcojahn marked this conversation as resolved.

// Function URL for easy testing
const fnUrl = agentFn.addFunctionUrl({
authType: lambda.FunctionUrlAuthType.AWS_IAM,
});

new cdk.CfnOutput(this, "FunctionName", {
value: agentFn.functionName,
});
new cdk.CfnOutput(this, "FunctionUrl", {
value: fnUrl.url,
});
}
}
15 changes: 15 additions & 0 deletions lambda-strands-agent-bedrock-cdk/package.json
Comment thread
marcojahn marked this conversation as resolved.
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"name": "lambda-strands-agent-bedrock-cdk",
"version": "1.0.0",
"bin": { "app": "bin/app.ts" },
"scripts": { "build": "tsc", "cdk": "cdk" },
"dependencies": {
"aws-cdk-lib": "^2.180.0",
"constructs": "^10.4.2"
},
"devDependencies": {
"@types/node": "^22.0.0",
"ts-node": "^10.9.0",
"typescript": "~5.7.0"
}
}
46 changes: 46 additions & 0 deletions lambda-strands-agent-bedrock-cdk/src/agent/index.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
"""Strands Agents SDK agent deployed on AWS Lambda with Amazon Bedrock."""

import math
from strands import Agent, tool


@tool
def calculate(expression: str) -> str:
"""Evaluate a mathematical expression safely.

Args:
expression: A mathematical expression to evaluate (e.g. '2 + 3 * 4').

Returns:
The result of the calculation.
"""
allowed = set("0123456789+-*/.() ")
if not all(c in allowed for c in expression):
return "Error: expression contains invalid characters"
try:
result = eval(expression, {"__builtins__": {}}, {"math": math}) # noqa: S307
return str(result)
except Exception as e:
return f"Error: {e}"


SYSTEM_PROMPT = """You are a helpful assistant with access to a calculator tool.
When asked math questions, use the calculate tool to compute the answer.
Always show your work by explaining what calculation you performed."""


def handler(event, _context):
"""Lambda handler that runs a Strands agent."""
import os

prompt = event.get("prompt", "What is 25 * 47 + 13?")
model_id = os.environ.get("MODEL_ID", "us.anthropic.claude-sonnet-4-6")

agent = Agent(
system_prompt=SYSTEM_PROMPT,
tools=[calculate],
model=model_id,
)

response = agent(prompt)
return {"statusCode": 200, "body": str(response)}
20 changes: 20 additions & 0 deletions lambda-strands-agent-bedrock-cdk/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"lib": ["es2020"],
"declaration": true,
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"noImplicitThis": true,
"alwaysStrict": true,
"outDir": "build",
"rootDir": ".",
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"esModuleInterop": true
},
"exclude": ["node_modules", "build"]
}