diff --git a/bedrock-agent-openai-cdk/README.md b/bedrock-agent-openai-cdk/README.md new file mode 100644 index 000000000..88418b5c5 --- /dev/null +++ b/bedrock-agent-openai-cdk/README.md @@ -0,0 +1,129 @@ +# 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 + +The Bedrock Agent `InvokeAgent` API returns a streaming response, so use the Python SDK (not the CLI). Replace `` and `` with the values from the deploy output: + +```bash +python3 -c " +import boto3, json +client = boto3.client('bedrock-agent-runtime', region_name='us-east-1') +response = client.invoke_agent( + agentId='', + agentAliasId='', + sessionId='test-session-1', + inputText='What is the weather in Tokyo?' +) +for event in response['completion']: + if 'chunk' in event: + print(event['chunk']['bytes'].decode()) +" +``` + +For example, if your deploy output showed AgentId = `2VHQREVYJM` and AgentAliasId = `WRP0JKNQFL`: + +```bash +python3 -c " +import boto3 +client = boto3.client('bedrock-agent-runtime', region_name='us-east-1') +response = client.invoke_agent( + agentId='2VHQREVYJM', + agentAliasId='WRP0JKNQFL', + sessionId='test-session-1', + inputText='What is the weather in Tokyo?' +) +for event in response['completion']: + if 'chunk' in event: + print(event['chunk']['bytes'].decode()) +" +``` + +Try a multi-tool query: + +```bash +python3 -c " +import boto3 +client = boto3.client('bedrock-agent-runtime', region_name='us-east-1') +response = client.invoke_agent( + agentId='', + agentAliasId='', + sessionId='test-session-2', + inputText='What is the weather and current time in London?' +) +for event in response['completion']: + if 'chunk' in event: + print(event['chunk']['bytes'].decode()) +" +``` + +## 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-ruby4-bedrock-cdk/README.md b/lambda-ruby4-bedrock-cdk/README.md new file mode 100644 index 000000000..9e7430a2c --- /dev/null +++ b/lambda-ruby4-bedrock-cdk/README.md @@ -0,0 +1,65 @@ +# AWS Lambda Ruby 4.0 with Amazon Bedrock + +This pattern deploys a Ruby 4.0 Lambda function that invokes Amazon Bedrock (Claude Sonnet) for AI-powered text generation with JSON structured logging. + +Learn more about this pattern at Serverless Land Patterns: https://serverlessland.com/patterns/lambda-ruby4-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 +* [AWS CDK](https://docs.aws.amazon.com/cdk/latest/guide/cli.html) installed +* [Node.js](https://nodejs.org/en/download/) installed +* [Amazon Bedrock model access](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access.html) enabled for Claude Sonnet in your region + +## Deployment Instructions + +1. Create a new directory, navigate to that directory in a terminal and clone the GitHub repository: + ``` + git clone https://github.com/aws-samples/serverless-patterns + ``` +2. Change directory to the pattern directory: + ``` + cd serverless-patterns/lambda-ruby4-bedrock-cdk + ``` +3. Install dependencies: + ``` + npm install + ``` +4. Deploy the stack: + ``` + cdk deploy + ``` + +## How it works + +- A Ruby 4.0 Lambda function is deployed on ARM64 (Graviton) architecture +- The function uses the `aws-sdk-bedrockruntime` gem (bundled in the managed runtime) to invoke Amazon Bedrock +- JSON structured logging is enabled via Lambda advanced logging controls (new feature in Ruby 4.0 runtime) +- The function accepts a `prompt` field in the event payload and returns the AI-generated response + +## Testing + +Invoke the function with a test event: + +```bash +aws lambda invoke \ + --function-name $(aws cloudformation describe-stacks --stack-name LambdaRuby4BedrockStack --query 'Stacks[0].Outputs[?OutputKey==`FunctionName`].OutputValue' --output text) \ + --payload '{"prompt": "Explain serverless computing in 3 sentences."}' \ + --cli-binary-format raw-in-base64-out \ + response.json && cat response.json +``` + +## Cleanup + +``` +cdk destroy +``` + +--- + +Copyright 2026 Amazon.com, Inc. or its affiliates. All Rights Reserved. + +SPDX-License-Identifier: MIT-0 diff --git a/lambda-ruby4-bedrock-cdk/bin/app.ts b/lambda-ruby4-bedrock-cdk/bin/app.ts new file mode 100644 index 000000000..3bca4c7ad --- /dev/null +++ b/lambda-ruby4-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 { LambdaRuby4BedrockStack } from '../lib/lambda-ruby4-bedrock-stack'; + +const app = new cdk.App(); +new LambdaRuby4BedrockStack(app, 'LambdaRuby4BedrockStack'); diff --git a/lambda-ruby4-bedrock-cdk/cdk.json b/lambda-ruby4-bedrock-cdk/cdk.json new file mode 100644 index 000000000..a6700a2ff --- /dev/null +++ b/lambda-ruby4-bedrock-cdk/cdk.json @@ -0,0 +1,3 @@ +{ + "app": "npx ts-node --prefer-ts-exts bin/app.ts" +} diff --git a/lambda-ruby4-bedrock-cdk/example-pattern.json b/lambda-ruby4-bedrock-cdk/example-pattern.json new file mode 100644 index 000000000..98f85deaa --- /dev/null +++ b/lambda-ruby4-bedrock-cdk/example-pattern.json @@ -0,0 +1,52 @@ +{ + "title": "AWS Lambda Ruby 4.0 with Amazon Bedrock", + "description": "Deploy a Ruby 4.0 Lambda function that invokes Amazon Bedrock (Claude) for AI-powered text generation with JSON structured logging.", + "language": "Ruby", + "level": "200", + "framework": "CDK", + "introBox": { + "headline": "How it works", + "text": [ + "This pattern deploys a Ruby 4.0 Lambda function that invokes Amazon Bedrock (Claude Sonnet) for AI text generation.", + "The function uses the AWS SDK for Ruby (aws-sdk-bedrockruntime gem) bundled in the Lambda runtime.", + "JSON structured logging is enabled via Lambda advanced logging controls (new in Ruby 4.0).", + "The function runs on ARM64 (Graviton) for optimal price-performance." + ] + }, + "gitHub": { + "template": { + "repoURL": "https://github.com/aws-samples/serverless-patterns/tree/main/lambda-ruby4-bedrock-cdk", + "templateURL": "serverless-patterns/lambda-ruby4-bedrock-cdk", + "projectFolder": "lambda-ruby4-bedrock-cdk", + "templateFile": "lib/lambda-ruby4-bedrock-stack.ts" + } + }, + "resources": { + "bullets": [ + { "text": "AWS Lambda Ruby 4.0 Runtime", "link": "https://aws.amazon.com/about-aws/whats-new/2026/04/aws-lambda-adds-ruby/" }, + { "text": "Lambda Advanced Logging Controls", "link": "https://aws.amazon.com/blogs/compute/introducing-advanced-logging-controls-for-aws-lambda-functions/" }, + { "text": "Amazon Bedrock Documentation", "link": "https://docs.aws.amazon.com/bedrock/" } + ] + }, + "deploy": { + "text": ["cdk deploy"] + }, + "testing": { + "text": ["See the README for testing instructions."] + }, + "cleanup": { + "text": ["cdk destroy"] + }, + "authors": [ + { + "name": "Nithin Chandran R", + "bio": "Technical Account Manager at AWS, passionate about serverless and AI/ML.", + "linkedin": "nithin-chandran-r" + } + ], + "patternArch": { + "icon1": { "x": 20, "y": 50, "service": "lambda", "label": "Lambda (Ruby 4.0)" }, + "icon2": { "x": 80, "y": 50, "service": "bedrock", "label": "Amazon Bedrock" }, + "line1": { "from": "icon1", "to": "icon2" } + } +} diff --git a/lambda-ruby4-bedrock-cdk/lib/lambda-ruby4-bedrock-stack.ts b/lambda-ruby4-bedrock-cdk/lib/lambda-ruby4-bedrock-stack.ts new file mode 100644 index 000000000..e5f02086a --- /dev/null +++ b/lambda-ruby4-bedrock-cdk/lib/lambda-ruby4-bedrock-stack.ts @@ -0,0 +1,35 @@ +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 * as logs from 'aws-cdk-lib/aws-logs'; +import { Construct } from 'constructs'; + +export class LambdaRuby4BedrockStack extends cdk.Stack { + constructor(scope: Construct, id: string, props?: cdk.StackProps) { + super(scope, id, props); + + const fn = new lambda.Function(this, 'Ruby4BedrockFunction', { + runtime: new lambda.Runtime('ruby4.0', lambda.RuntimeFamily.RUBY), + handler: 'handler.lambda_handler', + code: lambda.Code.fromAsset('src'), + timeout: cdk.Duration.seconds(30), + memorySize: 256, + architecture: lambda.Architecture.ARM_64, + environment: { + MODEL_ID: 'us.anthropic.claude-sonnet-4-20250514-v1:0', + }, + loggingFormat: lambda.LoggingFormat.JSON, + }); + + fn.addToRolePolicy(new iam.PolicyStatement({ + actions: ['bedrock:InvokeModel'], + resources: [ + 'arn:aws:bedrock:*::foundation-model/*', + `arn:aws:bedrock:*:${this.account}:inference-profile/*`, + ], + })); + + new cdk.CfnOutput(this, 'FunctionName', { value: fn.functionName }); + new cdk.CfnOutput(this, 'FunctionArn', { value: fn.functionArn }); + } +} diff --git a/lambda-ruby4-bedrock-cdk/package.json b/lambda-ruby4-bedrock-cdk/package.json new file mode 100644 index 000000000..3bc35d799 --- /dev/null +++ b/lambda-ruby4-bedrock-cdk/package.json @@ -0,0 +1,19 @@ +{ + "name": "lambda-ruby4-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.0.0", + "source-map-support": "^0.5.21" + }, + "devDependencies": { + "typescript": "~5.4.0", + "ts-node": "^10.9.0", + "@types/node": "^20.0.0" + } +} diff --git a/lambda-ruby4-bedrock-cdk/src/handler.rb b/lambda-ruby4-bedrock-cdk/src/handler.rb new file mode 100644 index 000000000..a0d9ff06a --- /dev/null +++ b/lambda-ruby4-bedrock-cdk/src/handler.rb @@ -0,0 +1,28 @@ +require 'aws-sdk-bedrockruntime' +require 'json' + +def lambda_handler(event:, context:) + client = Aws::BedrockRuntime::Client.new + prompt = event['prompt'] || 'What are the benefits of serverless computing?' + + response = client.invoke_model( + model_id: ENV['MODEL_ID'], + content_type: 'application/json', + accept: 'application/json', + body: JSON.generate({ + anthropic_version: 'bedrock-2023-05-31', + max_tokens: 512, + messages: [{ role: 'user', content: prompt }] + }) + ) + + result = JSON.parse(response.body.read) + { + statusCode: 200, + body: JSON.generate({ + response: result.dig('content', 0, 'text'), + model: ENV['MODEL_ID'], + runtime: "ruby#{RUBY_VERSION}" + }) + } +end diff --git a/lambda-ruby4-bedrock-cdk/tsconfig.json b/lambda-ruby4-bedrock-cdk/tsconfig.json new file mode 100644 index 000000000..e29f27462 --- /dev/null +++ b/lambda-ruby4-bedrock-cdk/tsconfig.json @@ -0,0 +1,18 @@ +{ + "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 + }, + "exclude": ["node_modules", "build"] +}