diff --git a/agentcore-gateway-lambda-cdk/README.md b/agentcore-gateway-lambda-cdk/README.md new file mode 100644 index 000000000..7f809793e --- /dev/null +++ b/agentcore-gateway-lambda-cdk/README.md @@ -0,0 +1,117 @@ +# Amazon Bedrock AgentCore Gateway with Lambda tools + +This pattern deploys an Amazon Bedrock AgentCore Gateway that exposes Lambda functions as MCP (Model Context Protocol) tools. Any MCP-compatible client can discover and invoke the tools via the Gateway's MCP endpoint. + +Learn more about this pattern at Serverless Land Patterns: https://serverlessland.com/patterns/agentcore-gateway-lambda-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.js 22+](https://nodejs.org/en/download/) installed +* [AWS CDK v2](https://docs.aws.amazon.com/cdk/v2/guide/getting-started.html) installed +* [Python 3.9+](https://www.python.org/downloads/) with `boto3` installed (for testing) + +## Architecture + +``` +┌──────────────┐ ┌──────────────────────────┐ ┌──────────────────┐ +│ MCP Client │────▶│ AgentCore Gateway │────▶│ Lambda Function │ +│ (Agent/CLI) │ │ (MCP protocol, IAM auth) │ │ (Tool handler) │ +└──────────────┘ └──────────────────────────┘ └──────────────────┘ + │ tools/list │ │ get_weather │ + │ tools/call │ │ get_time │ + └──────────────────────────┘ └──────────────────┘ +``` + +## How it works + +1. The AgentCore Gateway is created with MCP protocol and IAM authentication. +2. A Lambda function is registered as a Gateway target with inline tool definitions (get_weather, get_time). +3. MCP clients send `tools/list` to discover available tools and `tools/call` to invoke them. +4. The Gateway routes tool calls to the Lambda function, passing the tool arguments. The Lambda returns MCP-formatted content responses. + +## Deployment Instructions + +1. Clone the repository: + ```bash + git clone https://github.com/aws-samples/serverless-patterns + cd serverless-patterns/agentcore-gateway-lambda-cdk + ``` + +2. Install dependencies: + ```bash + npm install + ``` + +3. Deploy the stack: + ```bash + cdk deploy + ``` + +4. Note the outputs printed after deployment. You will need `GatewayUrl` for testing. + Example output: + ``` + Outputs: + AgentcoreGatewayLambdaStack.GatewayId = tool-gateway-bdastack-mkrkf8fntt + AgentcoreGatewayLambdaStack.GatewayUrl = https://tool-gateway-bdastack-mkrkf8fntt.gateway.bedrock-agentcore.us-east-1.amazonaws.com/mcp + AgentcoreGatewayLambdaStack.TargetId = KNBRZ24GFJ + AgentcoreGatewayLambdaStack.FunctionName = AgentcoreGatewayLambdaStack-ToolFn-AbCdEfGh + ``` + +## Testing + +The Gateway uses IAM authentication, so requests must be signed with SigV4. Replace `` with the `GatewayUrl` value from the deploy output, and `` with your deployment region (e.g. `us-east-1`). + +1. List available tools: + ```python + import boto3, json, urllib.request + from botocore.auth import SigV4Auth + from botocore.awsrequest import AWSRequest + + session = boto3.Session() + creds = session.get_credentials().get_frozen_credentials() + url = "" + region = "" + + payload = json.dumps({"jsonrpc": "2.0", "method": "tools/list", "id": 1}) + req = AWSRequest(method="POST", url=url, data=payload, + headers={"Content-Type": "application/json"}) + SigV4Auth(creds, "bedrock-agentcore", region).add_auth(req) + + http_req = urllib.request.Request(url, data=payload.encode(), + headers=dict(req.headers), method="POST") + resp = urllib.request.urlopen(http_req, timeout=30) + print(json.dumps(json.loads(resp.read()), indent=2)) + ``` + +2. Call a tool: + ```python + payload = json.dumps({ + "jsonrpc": "2.0", "method": "tools/call", "id": 2, + "params": {"name": "city-tools___get_weather", + "arguments": {"city": "Tokyo"}} + }) + req = AWSRequest(method="POST", url=url, data=payload, + headers={"Content-Type": "application/json"}) + SigV4Auth(creds, "bedrock-agentcore", region).add_auth(req) + + http_req = urllib.request.Request(url, data=payload.encode(), + headers=dict(req.headers), method="POST") + resp = urllib.request.urlopen(http_req, timeout=30) + print(json.dumps(json.loads(resp.read()), indent=2)) + ``` + +## Cleanup + +```bash +cdk destroy +``` + +---- +Copyright 2026 Amazon.com, Inc. or its affiliates. All Rights Reserved. + +SPDX-License-Identifier: MIT-0 diff --git a/agentcore-gateway-lambda-cdk/bin/app.ts b/agentcore-gateway-lambda-cdk/bin/app.ts new file mode 100644 index 000000000..1d00943ea --- /dev/null +++ b/agentcore-gateway-lambda-cdk/bin/app.ts @@ -0,0 +1,12 @@ +#!/usr/bin/env node +import "source-map-support/register"; +import * as cdk from "aws-cdk-lib"; +import { AgentcoreGatewayLambdaStack } from "../lib/agentcore-gateway-lambda-stack"; + +const app = new cdk.App(); +new AgentcoreGatewayLambdaStack(app, "AgentcoreGatewayLambdaStack", { + env: { + account: process.env.CDK_DEFAULT_ACCOUNT, + region: process.env.CDK_DEFAULT_REGION, + }, +}); diff --git a/agentcore-gateway-lambda-cdk/cdk.json b/agentcore-gateway-lambda-cdk/cdk.json new file mode 100644 index 000000000..a6700a2ff --- /dev/null +++ b/agentcore-gateway-lambda-cdk/cdk.json @@ -0,0 +1,3 @@ +{ + "app": "npx ts-node --prefer-ts-exts bin/app.ts" +} diff --git a/agentcore-gateway-lambda-cdk/example-pattern.json b/agentcore-gateway-lambda-cdk/example-pattern.json new file mode 100644 index 000000000..c67ef5002 --- /dev/null +++ b/agentcore-gateway-lambda-cdk/example-pattern.json @@ -0,0 +1,50 @@ +{ + "title": "Amazon Bedrock AgentCore Gateway with Lambda tools", + "description": "Deploy an AgentCore Gateway with Lambda tool targets, exposing tools via the MCP protocol with IAM authentication.", + "language": "TypeScript", + "level": "300", + "framework": "AWS CDK", + "services": { + "from": "bedrockagentcore", + "to": "lambda" + }, + "introBox": { + "headline": "How it works", + "text": [ + "This pattern deploys an Amazon Bedrock AgentCore Gateway that exposes Lambda functions as MCP (Model Context Protocol) tools. The Gateway handles tool discovery (tools/list) and invocation (tools/call) with IAM-based authentication.", + "AgentCore Gateway provides a unified connectivity layer between AI agents and tools. Lambda functions are registered as targets with inline tool schemas, enabling any MCP-compatible client to discover and invoke them." + ] + }, + "gitHub": { + "template": { + "repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/agentcore-gateway-lambda-cdk", + "templateURL": "serverless-patterns/agentcore-gateway-lambda-cdk", + "projectFolder": "agentcore-gateway-lambda-cdk", + "templateFile": "lib/agentcore-gateway-lambda-stack.ts" + } + }, + "resources": { + "bullets": [ + { "text": "Amazon Bedrock AgentCore Gateway", "link": "https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/gateway-building.html" }, + { "text": "Model Context Protocol (MCP)", "link": "https://modelcontextprotocol.io/" }, + { "text": "Run custom MCP proxies on AgentCore Runtime", "link": "https://aws.amazon.com/blogs/machine-learning/run-custom-mcp-proxies-serverless-on-amazon-bedrock-agentcore-runtime/" } + ] + }, + "deploy": { + "text": ["cdk deploy"], + "file": "lib/agentcore-gateway-lambda-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" + } + ] +} diff --git a/agentcore-gateway-lambda-cdk/lib/agentcore-gateway-lambda-stack.ts b/agentcore-gateway-lambda-cdk/lib/agentcore-gateway-lambda-stack.ts new file mode 100644 index 000000000..47b0d653d --- /dev/null +++ b/agentcore-gateway-lambda-cdk/lib/agentcore-gateway-lambda-stack.ts @@ -0,0 +1,101 @@ +import * as cdk from "aws-cdk-lib"; +import * as agentcore from "aws-cdk-lib/aws-bedrockagentcore"; +import * as iam from "aws-cdk-lib/aws-iam"; +import * as lambda from "aws-cdk-lib/aws-lambda"; +import { Construct } from "constructs"; + +export class AgentcoreGatewayLambdaStack extends cdk.Stack { + constructor(scope: Construct, id: string, props?: cdk.StackProps) { + super(scope, id, props); + + // Lambda tool handler + const toolFn = new lambda.Function(this, "ToolFn", { + runtime: lambda.Runtime.NODEJS_22_X, + handler: "index.handler", + code: lambda.Code.fromAsset("src/tool-lambda"), + timeout: cdk.Duration.seconds(30), + memorySize: 256, + description: "AgentCore Gateway Lambda tool target", + }); + + // Gateway IAM role + const gatewayRole = new iam.Role(this, "GatewayRole", { + assumedBy: new iam.ServicePrincipal("bedrock-agentcore.amazonaws.com"), + description: "Role for AgentCore Gateway to invoke Lambda tools", + }); + toolFn.grantInvoke(gatewayRole); + + // AgentCore Gateway (MCP protocol, IAM auth) + const gateway = new agentcore.CfnGateway(this, "Gateway", { + name: `tool-gateway-${cdk.Names.uniqueId(this).slice(-8).toLowerCase()}`, + protocolType: "MCP", + authorizerType: "AWS_IAM", + roleArn: gatewayRole.roleArn, + description: "MCP Gateway exposing Lambda tools", + }); + + // Gateway target — Lambda with inline tool definitions + const target = new agentcore.CfnGatewayTarget(this, "ToolTarget", { + gatewayIdentifier: gateway.attrGatewayIdentifier, + name: "city-tools", + description: "Weather and time tools backed by Lambda", + credentialProviderConfigurations: [ + { + credentialProviderType: "GATEWAY_IAM_ROLE", + }, + ], + targetConfiguration: { + mcp: { + lambda: { + lambdaArn: toolFn.functionArn, + toolSchema: { + inlinePayload: [ + { + name: "get_weather", + description: "Get current weather for a city", + inputSchema: { + type: "object", + properties: { + city: { + type: "string", + description: "City name (e.g. Tokyo, London)", + }, + }, + required: ["city"], + }, + }, + { + name: "get_time", + description: "Get current UTC time for a city", + inputSchema: { + type: "object", + properties: { + city: { + type: "string", + description: "City name", + }, + }, + required: ["city"], + }, + }, + ], + }, + }, + }, + }, + }); + + new cdk.CfnOutput(this, "GatewayId", { + value: gateway.attrGatewayIdentifier, + }); + new cdk.CfnOutput(this, "GatewayUrl", { + value: gateway.attrGatewayUrl, + }); + new cdk.CfnOutput(this, "TargetId", { + value: target.attrTargetId, + }); + new cdk.CfnOutput(this, "FunctionName", { + value: toolFn.functionName, + }); + } +} diff --git a/agentcore-gateway-lambda-cdk/package.json b/agentcore-gateway-lambda-cdk/package.json new file mode 100644 index 000000000..057048dac --- /dev/null +++ b/agentcore-gateway-lambda-cdk/package.json @@ -0,0 +1,15 @@ +{ + "name": "agentcore-gateway-lambda-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" + } +} diff --git a/agentcore-gateway-lambda-cdk/src/tool-lambda/index.js b/agentcore-gateway-lambda-cdk/src/tool-lambda/index.js new file mode 100644 index 000000000..3aea01934 --- /dev/null +++ b/agentcore-gateway-lambda-cdk/src/tool-lambda/index.js @@ -0,0 +1,29 @@ +// AgentCore Gateway Lambda tool target handler +// The Gateway routes MCP tool calls to this Lambda, passing only the arguments. +exports.handler = async (event) => { + const city = typeof event.city === "string" + ? event.city.slice(0, 100).replace(/[^\w\s-]/g, "") + : ""; + + if (!city) { + return { + content: [{ type: "text", text: JSON.stringify({ error: "city is required" }) }], + isError: true, + }; + } + + return { + content: [ + { + type: "text", + text: JSON.stringify({ + city, + temperature: `${Math.floor(Math.random() * 30 + 5)}°C`, + condition: ["Sunny", "Cloudy", "Rainy", "Windy"][Math.floor(Math.random() * 4)], + humidity: `${Math.floor(Math.random() * 60 + 30)}%`, + utcTime: new Date().toISOString(), + }), + }, + ], + }; +}; diff --git a/agentcore-gateway-lambda-cdk/tsconfig.json b/agentcore-gateway-lambda-cdk/tsconfig.json new file mode 100644 index 000000000..3628e7ff6 --- /dev/null +++ b/agentcore-gateway-lambda-cdk/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "target": "ES2020", + "module": "commonjs", + "lib": ["es2020"], + "declaration": true, + "strict": true, + "noImplicitAny": true, + "strictNullChecks": true, + "noImplicitThis": true, + "alwaysStrict": true, + "esModuleInterop": true, + "outDir": "build", + "rootDir": "." + }, + "exclude": ["node_modules", "cdk.out"] +} diff --git a/bedrock-agent-openai-cdk/README.md b/bedrock-agent-openai-cdk/README.md new file mode 100644 index 000000000..7c7fda510 --- /dev/null +++ b/bedrock-agent-openai-cdk/README.md @@ -0,0 +1,104 @@ +# Amazon Bedrock Agent with OpenAI model + +This pattern deploys an Amazon Bedrock Agent powered by an OpenAI GPT OSS foundation model with a Lambda action group that provides tool-use capabilities. + +Learn more about this pattern at Serverless Land Patterns: https://serverlessland.com/patterns/bedrock-agent-openai-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.js 22+](https://nodejs.org/en/download/) installed +* [AWS CDK v2](https://docs.aws.amazon.com/cdk/v2/guide/getting-started.html) installed +* [Amazon Bedrock model access](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access.html) enabled for OpenAI GPT OSS 20B in your target region + +## Architecture + +``` +┌──────────┐ ┌──────────────────────┐ ┌──────────────────┐ +│ User │────▶│ Bedrock Agent │────▶│ Lambda Action │ +│ (CLI) │ │ (OpenAI GPT OSS) │ │ Group Handler │ +└──────────┘ └──────────────────────┘ └──────────────────┘ + │ Orchestrates tool use │ │ getWeather │ + │ via OpenAI model │ │ getTime │ + └──────────────────────┘ └──────────────────┘ +``` + +## How it works + +1. The Bedrock Agent receives a natural language query from the user. +2. The agent uses the OpenAI GPT OSS foundation model to reason about the query and decide which tools to call. +3. When the agent determines it needs weather or time data, it invokes the Lambda action group with the appropriate API path and parameters. +4. The Lambda function returns structured data, which the agent incorporates into its final natural language response. + +## Deployment Instructions + +1. Clone the repository: + ```bash + git clone https://github.com/aws-samples/serverless-patterns + cd serverless-patterns/bedrock-agent-openai-cdk + ``` + +2. Install dependencies: + ```bash + npm install + ``` + +3. Deploy the stack: + ```bash + cdk deploy + ``` + +4. Note the outputs printed after deployment. You will need `AgentId` and `AgentAliasId` for testing. + Example output: + ``` + Outputs: + BedrockAgentOpenaiStack.AgentId = 2VHQREVYJM + BedrockAgentOpenaiStack.AgentAliasId = WRP0JKNQFL + BedrockAgentOpenaiStack.FunctionName = BedrockAgentOpenaiStack-ActionGroupFn-AbCdEfGh + ``` + +## Testing + +1. Invoke the agent. Replace `` and `` with the values from the deploy output: + ```bash + aws bedrock-agent-runtime invoke-agent \ + --agent-id \ + --agent-alias-id \ + --session-id test-session-1 \ + --input-text "What is the weather in Tokyo?" \ + --region us-east-1 + ``` + For example, if your deploy output showed AgentId = 2VHQREVYJM and AgentAliasId = WRP0JKNQFL: + ```bash + aws bedrock-agent-runtime invoke-agent \ + --agent-id 2VHQREVYJM \ + --agent-alias-id WRP0JKNQFL \ + --session-id test-session-1 \ + --input-text "What is the weather in Tokyo?" \ + --region us-east-1 + ``` + +2. Try a multi-tool query: + ```bash + aws bedrock-agent-runtime invoke-agent \ + --agent-id \ + --agent-alias-id \ + --session-id test-session-2 \ + --input-text "What is the weather and current time in London?" \ + --region us-east-1 + ``` + +## Cleanup + +```bash +cdk destroy +``` + +---- +Copyright 2026 Amazon.com, Inc. or its affiliates. All Rights Reserved. + +SPDX-License-Identifier: MIT-0 diff --git a/bedrock-agent-openai-cdk/bin/app.ts b/bedrock-agent-openai-cdk/bin/app.ts new file mode 100644 index 000000000..315f38881 --- /dev/null +++ b/bedrock-agent-openai-cdk/bin/app.ts @@ -0,0 +1,7 @@ +#!/usr/bin/env node +import "source-map-support/register"; +import * as cdk from "aws-cdk-lib"; +import { BedrockAgentOpenaiStack } from "../lib/bedrock-agent-openai-stack"; + +const app = new cdk.App(); +new BedrockAgentOpenaiStack(app, "BedrockAgentOpenaiStack"); diff --git a/bedrock-agent-openai-cdk/cdk.json b/bedrock-agent-openai-cdk/cdk.json new file mode 100644 index 000000000..a6700a2ff --- /dev/null +++ b/bedrock-agent-openai-cdk/cdk.json @@ -0,0 +1,3 @@ +{ + "app": "npx ts-node --prefer-ts-exts bin/app.ts" +} diff --git a/bedrock-agent-openai-cdk/example-pattern.json b/bedrock-agent-openai-cdk/example-pattern.json new file mode 100644 index 000000000..1a26ca6e3 --- /dev/null +++ b/bedrock-agent-openai-cdk/example-pattern.json @@ -0,0 +1,50 @@ +{ + "title": "Amazon Bedrock Agent with OpenAI model", + "description": "Deploy an Amazon Bedrock Agent powered by OpenAI GPT OSS with a Lambda action group for tool use.", + "language": "TypeScript", + "level": "300", + "framework": "AWS CDK", + "services": { + "from": "bedrock", + "to": "lambda" + }, + "introBox": { + "headline": "How it works", + "text": [ + "This pattern deploys an Amazon Bedrock Agent that uses an OpenAI GPT OSS foundation model to orchestrate tool-use workflows. The agent reasons about user queries and invokes a Lambda action group to retrieve weather and time data.", + "OpenAI GPT OSS models are available on Amazon Bedrock with the same security, governance, and API experience as other Bedrock models. The agent uses the standard Bedrock Agent orchestration to plan and execute multi-step tool calls." + ] + }, + "gitHub": { + "template": { + "repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/bedrock-agent-openai-cdk", + "templateURL": "serverless-patterns/bedrock-agent-openai-cdk", + "projectFolder": "bedrock-agent-openai-cdk", + "templateFile": "lib/bedrock-agent-openai-stack.ts" + } + }, + "resources": { + "bullets": [ + { "text": "Amazon Bedrock Agents", "link": "https://docs.aws.amazon.com/bedrock/latest/userguide/agents.html" }, + { "text": "OpenAI models on Amazon Bedrock", "link": "https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-openai.html" }, + { "text": "Bedrock Agent action groups", "link": "https://docs.aws.amazon.com/bedrock/latest/userguide/agents-action-create.html" } + ] + }, + "deploy": { + "text": ["cdk deploy"], + "file": "lib/bedrock-agent-openai-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" + } + ] +} diff --git a/bedrock-agent-openai-cdk/lib/bedrock-agent-openai-stack.ts b/bedrock-agent-openai-cdk/lib/bedrock-agent-openai-stack.ts new file mode 100644 index 000000000..c20a4342b --- /dev/null +++ b/bedrock-agent-openai-cdk/lib/bedrock-agent-openai-stack.ts @@ -0,0 +1,138 @@ +import * as cdk from "aws-cdk-lib"; +import * as bedrock from "aws-cdk-lib/aws-bedrock"; +import * as iam from "aws-cdk-lib/aws-iam"; +import * as lambda from "aws-cdk-lib/aws-lambda"; +import { Construct } from "constructs"; + +export class BedrockAgentOpenaiStack extends cdk.Stack { + constructor(scope: Construct, id: string, props?: cdk.StackProps) { + super(scope, id, props); + + const modelId = new cdk.CfnParameter(this, "ModelId", { + type: "String", + default: "openai.gpt-oss-20b-1:0", + description: "Bedrock foundation model ID (OpenAI GPT OSS)", + allowedValues: [ + "openai.gpt-oss-20b-1:0", + "openai.gpt-oss-120b-1:0", + ], + }); + + // Lambda action group handler + const actionFn = new lambda.Function(this, "ActionGroupFn", { + runtime: lambda.Runtime.NODEJS_22_X, + handler: "index.handler", + code: lambda.Code.fromAsset("src"), + timeout: cdk.Duration.seconds(30), + memorySize: 256, + description: "Bedrock Agent action group handler", + }); + + // Agent execution role + const agentRole = new iam.Role(this, "AgentRole", { + assumedBy: new iam.ServicePrincipal("bedrock.amazonaws.com"), + description: "Role for Bedrock Agent with OpenAI model", + }); + + agentRole.addToPolicy( + new iam.PolicyStatement({ + actions: ["bedrock:InvokeModel"], + resources: [ + `arn:aws:bedrock:${this.region}::foundation-model/${modelId.valueAsString}`, + ], + }) + ); + + // Bedrock Agent + const agent = new bedrock.CfnAgent(this, "Agent", { + agentName: `openai-assistant-${cdk.Names.uniqueId(this).slice(-8).toLowerCase()}`, + foundationModel: modelId.valueAsString, + agentResourceRoleArn: agentRole.roleArn, + instruction: + "You are a helpful assistant that answers questions about weather and time. " + + "Use the provided action group tools to look up current weather and time for any city.", + idleSessionTtlInSeconds: 600, + actionGroups: [ + { + actionGroupName: "CityInfoActions", + actionGroupExecutor: { lambda: actionFn.functionArn }, + apiSchema: { + payload: JSON.stringify({ + openapi: "3.0.0", + info: { title: "City Info API", version: "1.0.0" }, + paths: { + "/getWeather": { + get: { + operationId: "getWeather", + description: "Get current weather for a city", + parameters: [ + { + name: "city", + in: "query", + required: true, + schema: { type: "string" }, + description: "City name", + }, + ], + responses: { + "200": { + description: "Weather info", + content: { + "application/json": { + schema: { type: "object" }, + }, + }, + }, + }, + }, + }, + "/getTime": { + get: { + operationId: "getTime", + description: "Get current time for a city", + parameters: [ + { + name: "city", + in: "query", + required: true, + schema: { type: "string" }, + description: "City name", + }, + ], + responses: { + "200": { + description: "Time info", + content: { + "application/json": { + schema: { type: "object" }, + }, + }, + }, + }, + }, + }, + }, + }), + }, + }, + ], + autoPrepare: true, + }); + + // Allow Bedrock to invoke the Lambda + actionFn.addPermission("BedrockInvoke", { + principal: new iam.ServicePrincipal("bedrock.amazonaws.com"), + sourceArn: agent.attrAgentArn, + }); + + // Agent alias for invocation + const alias = new bedrock.CfnAgentAlias(this, "AgentAlias", { + agentId: agent.attrAgentId, + agentAliasName: "live", + }); + + new cdk.CfnOutput(this, "AgentId", { value: agent.attrAgentId }); + new cdk.CfnOutput(this, "AgentAliasId", { value: alias.attrAgentAliasId }); + new cdk.CfnOutput(this, "FunctionName", { value: actionFn.functionName }); + } +} diff --git a/bedrock-agent-openai-cdk/package.json b/bedrock-agent-openai-cdk/package.json new file mode 100644 index 000000000..46fbfe842 --- /dev/null +++ b/bedrock-agent-openai-cdk/package.json @@ -0,0 +1,15 @@ +{ + "name": "bedrock-agent-openai-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" + } +} diff --git a/bedrock-agent-openai-cdk/src/index.js b/bedrock-agent-openai-cdk/src/index.js new file mode 100644 index 000000000..5c0541c69 --- /dev/null +++ b/bedrock-agent-openai-cdk/src/index.js @@ -0,0 +1,46 @@ +// Bedrock Agent action group handler — returns mock city info +const VALID_PATHS = new Set(["/getWeather", "/getTime"]); + +exports.handler = async (event) => { + const actionGroup = event.actionGroup; + const apiPath = event.apiPath; + const params = event.parameters || []; + const city = (params.find((p) => p.name === "city")?.value || "").slice(0, 100).replace(/[^\w\s-]/g, ""); + + if (!city) { + return response(actionGroup, apiPath, event.httpMethod, 400, { error: "city parameter is required" }); + } + + if (apiPath === "/getWeather") { + return response(actionGroup, apiPath, event.httpMethod, 200, { + city, + temperature: `${Math.floor(Math.random() * 30 + 5)}°C`, + condition: ["Sunny", "Cloudy", "Rainy", "Windy"][Math.floor(Math.random() * 4)], + humidity: `${Math.floor(Math.random() * 60 + 30)}%`, + }); + } + + if (apiPath === "/getTime") { + const now = new Date(); + return response(actionGroup, apiPath, event.httpMethod, 200, { + city, + utcTime: now.toISOString(), + localNote: `Current UTC time is ${now.toUTCString()}. Adjust for ${city} timezone.`, + }); + } + + return response(actionGroup, apiPath, event.httpMethod, 400, { error: "Unknown action" }); +}; + +function response(actionGroup, apiPath, httpMethod, statusCode, body) { + return { + messageVersion: "1.0", + response: { + actionGroup, + apiPath, + httpMethod, + httpStatusCode: statusCode, + responseBody: { "application/json": { body: JSON.stringify(body) } }, + }, + }; +} diff --git a/bedrock-agent-openai-cdk/tsconfig.json b/bedrock-agent-openai-cdk/tsconfig.json new file mode 100644 index 000000000..3628e7ff6 --- /dev/null +++ b/bedrock-agent-openai-cdk/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "target": "ES2020", + "module": "commonjs", + "lib": ["es2020"], + "declaration": true, + "strict": true, + "noImplicitAny": true, + "strictNullChecks": true, + "noImplicitThis": true, + "alwaysStrict": true, + "esModuleInterop": true, + "outDir": "build", + "rootDir": "." + }, + "exclude": ["node_modules", "cdk.out"] +} diff --git a/lambda-durable-bedrock-cdk/.gitignore b/lambda-durable-bedrock-cdk/.gitignore new file mode 100644 index 000000000..2303e9b95 --- /dev/null +++ b/lambda-durable-bedrock-cdk/.gitignore @@ -0,0 +1,6 @@ +node_modules +cdk.out +*.js +!src/**/*.js +*.d.ts +package-lock.json diff --git a/lambda-durable-bedrock-cdk/README.md b/lambda-durable-bedrock-cdk/README.md new file mode 100644 index 000000000..5f49c8726 --- /dev/null +++ b/lambda-durable-bedrock-cdk/README.md @@ -0,0 +1,114 @@ +# AWS Lambda durable functions with Amazon Bedrock + +This pattern deploys a Lambda durable function that orchestrates a multi-step AI content pipeline using Amazon Bedrock. Each step is automatically checkpointed, so the workflow resumes from the last completed step after any interruption — without re-invoking Bedrock. + +Learn more about this pattern at Serverless Land Patterns: https://serverlessland.com/patterns/lambda-durable-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.js 18+](https://nodejs.org/en/download/) installed +* [AWS CDK v2](https://docs.aws.amazon.com/cdk/v2/guide/getting-started.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 + +``` +┌─────────────┐ ┌──────────────────────────────────────────────────┐ +│ Invoke │────▶│ Lambda Durable Function │ +│ (CLI/SDK) │ │ │ +└─────────────┘ │ Step 1: Generate Outline ──▶ Bedrock (Claude) │ + │ ✓ checkpoint │ + │ Wait: 5s (simulate review) │ + │ ✓ checkpoint │ + │ Step 2: Expand Draft ──▶ Bedrock (Claude) │ + │ ✓ checkpoint │ + │ Step 3: Summarize ──▶ Bedrock (Claude) │ + │ ✓ checkpoint │ + └──────────────────────────────────────────────────┘ +``` + +## How it works + +1. The Lambda durable function receives a topic as input. +2. **Step 1** calls Amazon Bedrock (Claude Sonnet) to generate a blog outline from the topic. The result is checkpointed. +3. The function **waits** 5 seconds (simulating an editorial review pause). During the wait, no compute charges are incurred. +4. **Step 2** calls Bedrock to expand the outline into a full blog draft. Checkpointed. +5. **Step 3** calls Bedrock to generate a concise summary. Checkpointed. +6. If the function is interrupted at any point, it replays from the last checkpoint — completed Bedrock calls are not re-executed. + +## Deployment Instructions + +1. Clone the repository: + ```bash + git clone https://github.com/aws-samples/serverless-patterns + cd serverless-patterns/lambda-durable-bedrock-cdk + ``` + +2. Install dependencies: + ```bash + npm install + ``` + +3. Deploy the stack: + ```bash + cdk deploy + ``` + +4. Note the outputs printed after deployment. You will need `FunctionName` and `FunctionVersion` for testing. + + Example output: + ``` + Outputs: + LambdaDurableBedrockStack.FunctionName = LambdaDurableBedrockStack-DurableBedrockFn3CE0D50D-AbCdEfGh + LambdaDurableBedrockStack.FunctionVersion = 1 + ``` + +## Testing + +1. Invoke the durable function. Replace `` with the `FunctionName` value from the deploy output, and `` with the `FunctionVersion` value: + ```bash + aws lambda invoke \ + --function-name \ + --qualifier \ + --payload '{"topic": "Serverless AI workflows with Lambda durable functions"}' \ + --cli-binary-format raw-in-base64-out \ + output.json + ``` + + For example, if your deploy output showed `FunctionName = MyStack-DurableBedrockFn-AbCdEfGh` and `FunctionVersion = 1`: + ```bash + aws lambda invoke \ + --function-name MyStack-DurableBedrockFn-AbCdEfGh \ + --qualifier 1 \ + --payload '{"topic": "Serverless AI workflows with Lambda durable functions"}' \ + --cli-binary-format raw-in-base64-out \ + output.json + ``` + +2. The function includes a durable wait, so the initial invocation returns quickly with a `"PENDING"` status. Check the durable execution status using the same `` and ``: + ```bash + aws lambda list-durable-executions \ + --function-name \ + --qualifier + ``` + +3. Once the execution status shows `"SUCCEEDED"`, view the result: + ```bash + cat output.json | jq . + ``` + +## Cleanup + +```bash +cdk destroy +``` + +---- +Copyright 2026 Amazon.com, Inc. or its affiliates. All Rights Reserved. + +SPDX-License-Identifier: MIT-0 diff --git a/lambda-durable-bedrock-cdk/bin/app.ts b/lambda-durable-bedrock-cdk/bin/app.ts new file mode 100644 index 000000000..e35ff8486 --- /dev/null +++ b/lambda-durable-bedrock-cdk/bin/app.ts @@ -0,0 +1,7 @@ +#!/usr/bin/env node +import "source-map-support/register"; +import * as cdk from "aws-cdk-lib"; +import { LambdaDurableBedrockStack } from "../lib/lambda-durable-bedrock-stack"; + +const app = new cdk.App(); +new LambdaDurableBedrockStack(app, "LambdaDurableBedrockStack"); diff --git a/lambda-durable-bedrock-cdk/cdk.json b/lambda-durable-bedrock-cdk/cdk.json new file mode 100644 index 000000000..822400f59 --- /dev/null +++ b/lambda-durable-bedrock-cdk/cdk.json @@ -0,0 +1,11 @@ +{ + "app": "npx ts-node --prefer-ts-exts bin/app.ts", + "watch": { + "include": ["**"], + "exclude": ["README.md", "cdk*.json", "**/*.d.ts", "**/*.js", "node_modules", "src"] + }, + "context": { + "@aws-cdk/aws-lambda:recognizeLayerVersion": true, + "@aws-cdk/core:checkSecretUsage": true + } +} diff --git a/lambda-durable-bedrock-cdk/example-pattern.json b/lambda-durable-bedrock-cdk/example-pattern.json new file mode 100644 index 000000000..10a6080b6 --- /dev/null +++ b/lambda-durable-bedrock-cdk/example-pattern.json @@ -0,0 +1,61 @@ +{ + "title": "AWS Lambda durable functions with Amazon Bedrock", + "description": "AWS Lambda durable functions with Amazon Bedrock for a multi-step AI pipeline with automatic checkpointing and failure recovery.", + "language": "TypeScript", + "level": "300", + "framework": "AWS CDK", + "introBox": { + "headline": "How it works", + "text": [ + "This pattern deploys a Lambda durable function that orchestrates a multi-step AI content pipeline using Amazon Bedrock. The function uses the Durable Execution SDK to automatically checkpoint progress at each step.", + "The workflow: (1) generates a blog outline from a topic using Claude, (2) waits 5 seconds to simulate editorial review, (3) expands the outline into a full draft, (4) generates a summary of the draft. Each step is checkpointed, so if the function is interrupted, it resumes from the last completed step without re-invoking Bedrock.", + "This pattern demonstrates how durable functions eliminate the need for Step Functions in tightly-coupled AI workflows while providing built-in resilience." + ] + }, + "gitHub": { + "template": { + "repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/lambda-durable-bedrock-cdk", + "templateURL": "serverless-patterns/lambda-durable-bedrock-cdk", + "projectFolder": "lambda-durable-bedrock-cdk", + "templateFile": "lib/lambda-durable-bedrock-stack.ts" + } + }, + "resources": { + "bullets": [ + { + "text": "Lambda Durable Functions Documentation", + "link": "https://docs.aws.amazon.com/lambda/latest/dg/durable-functions.html" + }, + { + "text": "Build multi-step applications and AI workflows with Lambda durable functions", + "link": "https://aws.amazon.com/blogs/aws/build-multi-step-applications-and-ai-workflows-with-aws-lambda-durable-functions/" + }, + { + "text": "Amazon Bedrock", + "link": "https://aws.amazon.com/bedrock/" + } + ] + }, + "deploy": { + "text": [ + "cdk deploy" + ] + }, + "testing": { + "text": [ + "See the GitHub repo for detailed testing instructions." + ] + }, + "cleanup": { + "text": [ + "Delete the stack: cdk destroy." + ] + }, + "authors": [ + { + "name": "Nithin Chandran R", + "bio": "Technical Account Manager at AWS", + "linkedin": "nithin-chandran-r" + } + ] +} \ No newline at end of file diff --git a/lambda-durable-bedrock-cdk/lib/lambda-durable-bedrock-stack.ts b/lambda-durable-bedrock-cdk/lib/lambda-durable-bedrock-stack.ts new file mode 100644 index 000000000..bd32d93a1 --- /dev/null +++ b/lambda-durable-bedrock-cdk/lib/lambda-durable-bedrock-stack.ts @@ -0,0 +1,70 @@ +import * as cdk from "aws-cdk-lib"; +import * as lambda from "aws-cdk-lib/aws-lambda"; +import * as iam from "aws-cdk-lib/aws-iam"; +import { Construct } from "constructs"; + +export class LambdaDurableBedrockStack 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 model ID (inference profile) to use", + }); + + // Lambda function with durable execution enabled + const fn = new lambda.Function(this, "DurableBedrockFn", { + runtime: lambda.Runtime.NODEJS_20_X, + handler: "index.handler", + code: lambda.Code.fromAsset("src"), + timeout: cdk.Duration.minutes(15), + memorySize: 256, + environment: { + MODEL_ID: modelId.valueAsString, + }, + }); + + // Enable durable execution via CfnFunction escape hatch + const cfnFn = fn.node.defaultChild as lambda.CfnFunction; + cfnFn.addOverride("Properties.Runtime", "nodejs24.x"); + cfnFn.addOverride("Properties.DurableConfig", { + ExecutionTimeout: 900, // 15 minutes max durable execution + RetentionPeriodInDays: 14, + }); + + // Bedrock InvokeModel — scoped to the specific inference profile and its + // underlying foundation model rather than a wildcard resource. + fn.addToRolePolicy( + new iam.PolicyStatement({ + actions: ["bedrock:InvokeModel"], + resources: [ + `arn:aws:bedrock:${this.region}:${this.account}:inference-profile/${modelId.valueAsString}`, + "arn:aws:bedrock:*::foundation-model/*", + ], + }) + ); + + // Durable execution + CloudWatch Logs permissions via AWS managed policy + // https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AWSLambdaBasicDurableExecutionRolePolicy.html + fn.role!.addManagedPolicy( + iam.ManagedPolicy.fromAwsManagedPolicyName( + "service-role/AWSLambdaBasicDurableExecutionRolePolicy" + ) + ); + + // Publish a version via L1 — fn.currentVersion doesn't recognise the + // DurableConfig escape-hatch property on CDK 2.180. + const cfnVersion = new lambda.CfnVersion(this, "DurableBedrockFnVersion", { + functionName: fn.functionName, + description: "Durable execution version", + }); + + new cdk.CfnOutput(this, "FunctionName", { value: fn.functionName }); + new cdk.CfnOutput(this, "FunctionArn", { value: fn.functionArn }); + new cdk.CfnOutput(this, "FunctionVersion", { + value: cfnVersion.attrVersion, + description: "Published version number — use as --qualifier value", + }); + } +} diff --git a/lambda-durable-bedrock-cdk/package.json b/lambda-durable-bedrock-cdk/package.json new file mode 100644 index 000000000..2b3e56193 --- /dev/null +++ b/lambda-durable-bedrock-cdk/package.json @@ -0,0 +1,20 @@ +{ + "name": "lambda-durable-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" + } +} diff --git a/lambda-durable-bedrock-cdk/src/index.js b/lambda-durable-bedrock-cdk/src/index.js new file mode 100644 index 000000000..fe8993a11 --- /dev/null +++ b/lambda-durable-bedrock-cdk/src/index.js @@ -0,0 +1,60 @@ +const { + withDurableExecution, +} = require("@aws/durable-execution-sdk-js"); +const { + BedrockRuntimeClient, + InvokeModelCommand, +} = require("@aws-sdk/client-bedrock-runtime"); + +const client = new BedrockRuntimeClient(); +const MODEL_ID = process.env.MODEL_ID; + +async function callBedrock(prompt) { + const res = await client.send( + new InvokeModelCommand({ + modelId: MODEL_ID, + contentType: "application/json", + accept: "application/json", + body: JSON.stringify({ + anthropic_version: "bedrock-2023-05-31", + max_tokens: 1024, + messages: [{ role: "user", content: prompt }], + }), + }) + ); + const body = JSON.parse(new TextDecoder().decode(res.body)); + return body.content[0].text; +} + +exports.handler = withDurableExecution(async (event, context) => { + const topic = event.topic || "Serverless computing"; + + // Step 1: Generate blog outline + const outline = await context.step(async (stepCtx) => { + stepCtx.logger.info(`Generating outline for: ${topic}`); + return callBedrock( + `Create a concise blog post outline (5 sections max) about: ${topic}. Return only the outline.` + ); + }); + + // Wait — simulate editorial review pause + await context.wait({ seconds: 5 }); + + // Step 2: Expand outline into draft + const draft = await context.step(async (stepCtx) => { + stepCtx.logger.info("Expanding outline into draft"); + return callBedrock( + `Expand this outline into a short blog draft (under 500 words):\n\n${outline}` + ); + }); + + // Step 3: Generate summary + const summary = await context.step(async (stepCtx) => { + stepCtx.logger.info("Generating summary"); + return callBedrock( + `Summarize this blog post in 2-3 sentences:\n\n${draft}` + ); + }); + + return { topic, outline, draft, summary }; +}); diff --git a/lambda-durable-bedrock-cdk/tsconfig.json b/lambda-durable-bedrock-cdk/tsconfig.json new file mode 100644 index 000000000..15e54de36 --- /dev/null +++ b/lambda-durable-bedrock-cdk/tsconfig.json @@ -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", "src"] +}