-
Notifications
You must be signed in to change notification settings - Fork 1k
New pattern - Step Functions to Bedrock InvokeModel (CDK) #3083
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-sfn-bedrock-invokemodel-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
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,6 @@ | ||
| *.js | ||
| *.d.ts | ||
| node_modules | ||
| cdk.out | ||
| cdk.context.json | ||
| package-lock.json |
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 @@ | ||
| *.ts | ||
| !*.d.ts | ||
| cdk.out |
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,83 @@ | ||
| # AWS Step Functions Express workflow with optimized integration for Amazon Bedrock InvokeModel | ||
|
|
||
| This pattern deploys a Step Functions Express workflow that invokes Amazon Bedrock (Claude Sonnet) directly using the optimized integration. Deployed with AWS CDK. | ||
|
|
||
| Learn more about this pattern at Serverless Land Patterns: https://serverlessland.com/patterns/sfn-bedrock-invokemodel-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 | ||
| - [AWS CDK](https://docs.aws.amazon.com/cdk/latest/guide/cli.html) installed | ||
| - [Node.js](https://nodejs.org/) 20.x or later | ||
| - [Amazon Bedrock model access](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access.html) enabled for a model of your choice (Anthropic Claude Sonnet is the default in this pattern) in your AWS account | ||
|
|
||
| ## How it works | ||
|
|
||
| Step Functions has an optimized integration with Amazon Bedrock that lets you call `bedrock:InvokeModel` directly from a workflow state. The optimized integration provides native error handling, automatic retries, and direct payload mapping without intermediate compute. | ||
|
|
||
| **Key points:** | ||
| - Uses `arn:aws:states:::bedrock:invokeModel` resource (optimized integration) | ||
| - Express workflow for synchronous execution (lower cost, sub-5-minute executions) | ||
| - Built-in retry with exponential backoff for transient failures | ||
| - `resultSelector` extracts just the response text, model, and usage from the Bedrock response | ||
|
|
||
| ``` | ||
| ┌──────────────────────┐ ┌──────────────────────┐ | ||
| │ │ │ │ | ||
| │ Step Functions │────────▶│ Amazon Bedrock │ | ||
| │ (Express) │ │ Claude Sonnet │ | ||
| │ │◀────────│ │ | ||
| └──────────────────────┘ └──────────────────────┘ | ||
| ``` | ||
|
|
||
| ## Deployment | ||
|
|
||
| 1. Install dependencies: | ||
| ```bash | ||
| cd sfn-bedrock-invokemodel-cdk | ||
| npm install | ||
| ``` | ||
|
|
||
| 2. Deploy the stack: | ||
| ```bash | ||
| cdk deploy | ||
| ``` | ||
|
|
||
| ## Testing | ||
|
|
||
| Start a synchronous execution of the Express workflow: | ||
|
|
||
| ```bash | ||
| aws stepfunctions start-sync-execution \ | ||
| --state-machine-arn $(aws cloudformation describe-stacks \ | ||
| --stack-name SfnBedrockInvokemodelStack \ | ||
| --query 'Stacks[0].Outputs[?OutputKey==`StateMachineArn`].OutputValue' \ | ||
| --output text) \ | ||
| --input '{"prompt": "What are the benefits of Step Functions native Bedrock integration?"}' \ | ||
| --query '{status: status, output: output}' \ | ||
| --output json | ||
| ``` | ||
|
|
||
| The response includes the generated text, model ID, and token usage: | ||
|
|
||
| ```json | ||
| { | ||
| "status": "SUCCEEDED", | ||
| "output": "{\"response\": \"...\", \"model\": \"claude-...\", \"usage\": {\"input_tokens\": 15, \"output_tokens\": 200}}" | ||
| } | ||
| ``` | ||
|
|
||
| ## 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,7 @@ | ||
| #!/usr/bin/env node | ||
| import "source-map-support/register"; | ||
| import * as cdk from "aws-cdk-lib"; | ||
| import { SfnBedrockInvokemodelStack } from "../lib/sfn-bedrock-invokemodel-stack"; | ||
|
|
||
| const app = new cdk.App(); | ||
| new SfnBedrockInvokemodelStack(app, "SfnBedrockInvokemodelStack"); |
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 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,52 @@ | ||
| { | ||
| "title": "AWS Step Functions Express integration with Amazon Bedrock InvokeModel", | ||
| "description": "Invoke Amazon Bedrock directly from Step Functions using the native InvokeModel optimized integration. Deployed with AWS CDK.", | ||
| "language": "TypeScript", | ||
| "level": "200", | ||
| "framework": "AWS CDK", | ||
| "introBox": { | ||
| "headline": "How it works", | ||
| "text": [ | ||
| "This pattern deploys a Step Functions Express workflow that invokes Amazon Bedrock (Claude Sonnet) directly using the bedrock:InvokeModel optimized integration.", | ||
| "The optimized integration provides native error handling, automatic retries, and direct payload mapping without intermediate compute.", | ||
| "The workflow accepts a prompt string as input, sends it to Bedrock, and returns the generated response with usage metadata.", | ||
| "Built-in retry logic handles transient failures with exponential backoff." | ||
| ] | ||
| }, | ||
| "gitHub": { | ||
| "template": { | ||
| "repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/sfn-bedrock-invokemodel-cdk", | ||
| "templateURL": "serverless-patterns/sfn-bedrock-invokemodel-cdk", | ||
| "projectFolder": "sfn-bedrock-invokemodel-cdk", | ||
| "templateFile": "lib/sfn-bedrock-invokemodel-stack.ts" | ||
| } | ||
| }, | ||
| "resources": { | ||
| "bullets": [ | ||
| { "text": "Step Functions optimized integration for Amazon Bedrock", "link": "https://aws.amazon.com/about-aws/whats-new/2023/11/aws-step-functions-optimized-integration-bedrock/" }, | ||
| { "text": "Build generative AI apps using Step Functions and Bedrock", "link": "https://aws.amazon.com/blogs/aws/build-generative-ai-apps-using-aws-step-functions-and-amazon-bedrock/" }, | ||
| { "text": "Amazon Bedrock documentation", "link": "https://docs.aws.amazon.com/bedrock/latest/userguide/" } | ||
| ] | ||
| }, | ||
| "deploy": { | ||
| "text": ["<code>cdk deploy</code>"] | ||
| }, | ||
| "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" | ||
| } | ||
| ], | ||
| "patternArch": { | ||
| "icon1": { "x": 20, "y": 50, "service": "sfn", "label": "Step Functions" }, | ||
| "icon2": { "x": 80, "y": 50, "service": "bedrock", "label": "Amazon Bedrock" }, | ||
| "line1": { "from": "icon1", "to": "icon2" } | ||
| } | ||
| } |
88 changes: 88 additions & 0 deletions
88
sfn-bedrock-invokemodel-cdk/lib/sfn-bedrock-invokemodel-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,88 @@ | ||
| import * as cdk from "aws-cdk-lib"; | ||
| import * as sfn from "aws-cdk-lib/aws-stepfunctions"; | ||
| import * as tasks from "aws-cdk-lib/aws-stepfunctions-tasks"; | ||
| import * as bedrock from "aws-cdk-lib/aws-bedrock"; | ||
| import * as logs from "aws-cdk-lib/aws-logs"; | ||
| import * as iam from "aws-cdk-lib/aws-iam"; | ||
| import { Construct } from "constructs"; | ||
|
|
||
| export class SfnBedrockInvokemodelStack extends cdk.Stack { | ||
| constructor(scope: Construct, id: string, props?: cdk.StackProps) { | ||
| super(scope, id, props); | ||
|
|
||
| const modelId = new cdk.CfnParameter(this, "BedrockModelId", { | ||
| type: "String", | ||
| default: "us.anthropic.claude-sonnet-4-20250514-v1:0", | ||
| description: "Bedrock inference profile model ID", | ||
| }); | ||
|
|
||
| // Construct inference profile ARN for the model | ||
| const inferenceProfileArn = `arn:aws:bedrock:${this.region}:${this.account}:inference-profile/${modelId.valueAsString}`; | ||
| const model = bedrock.ProvisionedModel.fromProvisionedModelArn( | ||
| this, | ||
| "Model", | ||
| inferenceProfileArn | ||
| ); | ||
|
|
||
| // Step Functions task: invoke Bedrock directly (no Lambda needed) | ||
| const invokeModel = new tasks.BedrockInvokeModel(this, "InvokeModel", { | ||
| model, | ||
| body: sfn.TaskInput.fromObject({ | ||
| anthropic_version: "bedrock-2023-05-31", | ||
| max_tokens: 1024, | ||
| messages: [ | ||
| { | ||
| role: "user", | ||
| content: sfn.JsonPath.stringAt("$.prompt"), | ||
| }, | ||
| ], | ||
| }), | ||
| resultSelector: { | ||
| "response.$": "$.Body.content[0].text", | ||
| "model.$": "$.Body.model", | ||
| "usage.$": "$.Body.usage", | ||
| }, | ||
| }); | ||
|
|
||
| // Add retry for transient failures | ||
| invokeModel.addRetry({ | ||
| errors: ["States.TaskFailed"], | ||
| interval: cdk.Duration.seconds(20), | ||
| maxAttempts: 3, | ||
| backoffRate: 2, | ||
| }); | ||
|
|
||
| const logGroup = new logs.LogGroup(this, "LogGroup", { | ||
| logGroupName: "/aws/stepfunctions/sfn-bedrock-invokemodel", | ||
| retention: logs.RetentionDays.TWO_WEEKS, | ||
| removalPolicy: cdk.RemovalPolicy.DESTROY, | ||
| }); | ||
|
|
||
| const stateMachine = new sfn.StateMachine(this, "StateMachine", { | ||
| stateMachineName: "sfn-bedrock-invokemodel", | ||
| definitionBody: sfn.DefinitionBody.fromChainable(invokeModel), | ||
| stateMachineType: sfn.StateMachineType.EXPRESS, | ||
| timeout: cdk.Duration.minutes(5), | ||
| logs: { | ||
| destination: logGroup, | ||
| level: sfn.LogLevel.ALL, | ||
| includeExecutionData: true, | ||
| }, | ||
| }); | ||
|
|
||
| // Grant Bedrock access (inference profile + foundation model) | ||
| stateMachine.addToRolePolicy( | ||
| new iam.PolicyStatement({ | ||
| actions: ["bedrock:InvokeModel"], | ||
| resources: [ | ||
| `arn:aws:bedrock:${this.region}:${this.account}:inference-profile/${modelId.valueAsString}`, | ||
| "arn:aws:bedrock:*::foundation-model/*", | ||
| ], | ||
| }) | ||
| ); | ||
|
|
||
| new cdk.CfnOutput(this, "StateMachineArn", { value: stateMachine.stateMachineArn }); | ||
| new cdk.CfnOutput(this, "StateMachineName", { value: stateMachine.stateMachineName! }); | ||
| new cdk.CfnOutput(this, "LogGroupName", { value: logGroup.logGroupName }); | ||
| } | ||
| } | ||
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": "sfn-bedrock-invokemodel-cdk", | ||
| "version": "1.0.0", | ||
| "bin": { "app": "bin/app.ts" }, | ||
| "scripts": { "build": "tsc", "cdk": "cdk" }, | ||
| "dependencies": { | ||
| "aws-cdk-lib": "2.236.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,22 @@ | ||
| { | ||
| "compilerOptions": { | ||
| "target": "ES2020", | ||
| "module": "commonjs", | ||
| "lib": ["es2020"], | ||
| "declaration": true, | ||
| "strict": true, | ||
| "noImplicitAny": true, | ||
| "strictNullChecks": true, | ||
| "noImplicitThis": true, | ||
| "alwaysStrict": true, | ||
| "noUnusedLocals": false, | ||
| "noUnusedParameters": false, | ||
| "noImplicitReturns": true, | ||
| "noFallthroughCasesInSwitch": false, | ||
| "inlineSourceMap": true, | ||
| "inlineSources": true, | ||
| "experimentalDecorators": true, | ||
| "strictPropertyInitialization": false | ||
| }, | ||
| "exclude": ["cdk.out"] | ||
| } |
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.
That model will be EOL in a few months, please select a more recent one. https://docs.aws.amazon.com/bedrock/latest/userguide/model-card-anthropic-claude-sonnet-4.html
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.
This is already using claude-sonnet-4 (us.anthropic.claude-sonnet-4-20250514-v1:0) which is the latest -- released May 2025. The page you linked actually confirms it's current. No change needed here I think?