-
Notifications
You must be signed in to change notification settings - Fork 1k
New pattern - lambda-strands-agent-bedrock-cdk #3093
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,84 @@ | ||
| # 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 | ||
|
|
||
| The pattern creates an AWS Lambda function with the Strands Agents SDK layer. The function uses Amazon Bedrock (Claude Sonnet) for reasoning and can invoke registered Python tools during the conversation loop. | ||
|
|
||
| ## How it works | ||
|
|
||
| 1. A client invokes the Lambda function with a JSON payload containing a `prompt` field. | ||
| 2. The Lambda function initializes a Strands Agents SDK agent with the official 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 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 |
| 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, | ||
| }, | ||
| }); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| { | ||
| "app": "npx ts-node --prefer-ts-exts bin/app.ts" | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,51 @@ | ||
| { | ||
| "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": ["cdk deploy"], | ||
| "file": "lib/lambda-strands-agent-bedrock-stack.ts" | ||
| }, | ||
| "testing": { | ||
| "text": ["See the README for testing instructions."] | ||
| }, | ||
| "cleanup": { | ||
| "text": ["cdk destroy"] | ||
| }, | ||
| "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 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 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, | ||
| layers: [strandsLayer], | ||
| environment: { | ||
| MODEL_ID: "us.anthropic.claude-sonnet-4-20250514-v1:0", | ||
| }, | ||
| description: "Strands Agents SDK agent on Lambda with Bedrock", | ||
| }); | ||
|
|
||
| // Bedrock invoke permissions | ||
| agentFn.addToRolePolicy( | ||
| new iam.PolicyStatement({ | ||
| actions: [ | ||
| "bedrock:InvokeModel", | ||
| "bedrock:InvokeModelWithResponseStream", | ||
| ], | ||
| resources: [ | ||
| `arn:aws:bedrock:*:${this.account}:inference-profile/us.anthropic.claude-sonnet-4-20250514-v1:0`, | ||
| `arn:aws:bedrock:*::foundation-model/anthropic.claude-sonnet-4-20250514-v1:0`, | ||
| ], | ||
| }) | ||
| ); | ||
|
Comment on lines
+33
to
+44
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The Lambda execution role grants
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Good catch and thank you for the feedback, I've scoped to the specific inference-profile and foundation-model ARNs now. |
||
|
|
||
| // 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, | ||
| }); | ||
| } | ||
| } | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The README has a clear Testing section but no separate guidance to confirm the stack deployed successfully (e.g., checking stack status or that the function URL output was produced).
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Added a Verification section with a describe-stacks command to confirm outputs after deploy. |
| 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" | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| """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.""" | ||
| prompt = event.get("prompt", "What is 25 * 47 + 13?") | ||
|
|
||
| agent = Agent( | ||
| system_prompt=SYSTEM_PROMPT, | ||
| tools=[calculate], | ||
| ) | ||
|
|
||
| response = agent(prompt) | ||
| return {"statusCode": 200, "body": str(response)} |
| 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"] | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The comment describes the Strands layer as "ARM64", but the layer ARN ends in
-x86_64and the function is configured witharchitecture: lambda.Architecture.X86_64.Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fixed it, comment now says x86_64 to match the layer ARN and architecture config.