-
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
Open
NithinChandranR-AWS
wants to merge
3
commits into
aws-samples:main
Choose a base branch
from
NithinChandranR-AWS:NithinChandranR-AWS-feature-lambda-strands-agent-bedrock-cdk
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
9689646
feat(lambda-strands-agent-bedrock-cdk): Add Strands Agents SDK on Lam…
NithinChandranR-AWS d4fc566
fix: address marcojahn review comments on PR #3093
NithinChandranR-AWS d612a20
fix(lambda-strands-agent-bedrock-cdk): Read MODEL_ID from env, region…
NithinChandranR-AWS File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
|
|
||
| ``` | ||
| ┌──────────┐ ┌───────────────────────────────────────────┐ ┌─────────────────┐ | ||
| │ │ │ 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 | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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, | ||
| }, | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| { | ||
| "app": "npx ts-node --prefer-ts-exts bin/app.ts" | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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" | ||
| } | ||
| ] | ||
| } |
58 changes: 58 additions & 0 deletions
58
lambda-strands-agent-bedrock-cdk/lib/lambda-strands-agent-bedrock-stack.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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, | ||
|
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*`, | ||
| ], | ||
| }) | ||
| ); | ||
|
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, | ||
| }); | ||
| } | ||
| } | ||
|
marcojahn marked this conversation as resolved.
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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" | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"] | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
can you please add an architecture diagram?
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.
Added a text diagram and fixed the model resolution handler now reads MODEL_ID from env, and the CDK derives the region prefix automatically.