Skip to main content
Build a Serverless Web Application using Generative AI

Task 3: Build a Serverless Backend

In this task, you will use AWS Amplify and AWS Lambda to build a serverless function

Introduction

Overview

In this task, you will configure a serverless function using AWS Amplify and AWS Lambda. This function takes an input parameter i.e. ingredients to generate a prompt. It then sends this prompt to Amazon Bedrock via an HTTP POST request to the Claude 3 Sonnet model. The body of the request includes the prompt string within a messages array.

What you will accomplish

In this tutorial, you will:

  • Add Amazon Bedrock as a data source

  • Configure custom business logic handler code

Implementation

10 minutes

A text editor. Here are a few free ones:

Create a Lambda function for handling requests

1. Create a Lambda function

On your local machine, navigate to the ai-recipe-generator/amplify/data folder, and create a file named bedrock.js.

Screenshot of a file directory for the ai-recipe-generator project, showing folders amplify, auth, data, and files such as resource.ts, backend.ts, package.json. The file bedrock.js is highlighted in the data folder.

2. Add the function code

Then, update the file with the following code:

The following code defines a request function that constructs the HTTP request to invoke the Claude 3 Sonnet foundation model in Amazon Bedrock. The response function parses the response and returns the generated recipe.

Bedrock Lambda function code

Add this code to your bedrock.js file

javascript

Add Amazon Bedrock as a data source

2. Update the backend file

Update the amplify/backend.ts file with the following code. Then, save the file.

  • The code adds an HTTP data source for Amazon Bedrock to your API and grant it permissions to invoke the Claude model.

Screenshot of the 'ai-recipe-generator' project directory structure, highlighting the backend.ts file located in the amplify/auth folder.

Backend code

Add this code to your backend.ts file

bash

Conclusion

You have defined a Lambda function using Amplify, and added Amazon Bedrock as an HTTP data source.

Deploy the Backend API

Start Task Four