使用生成式人工智能构建无服务器 Web 应用程序

教程

模块 3:构建无服务器后端

在本模块中,您将使用 AWS Amplify 和 AWS Lambda 构建无服务器函数。

概览

在本模块中,您将使用 AWS Amplify 和 AWS Lambda 配置无服务器函数。此函数使用输入参数(即成分)来生成提示。然后,通过向 Claude 3 Sonnet 模型发出 HTTP POST 请求将此提示发送给 Amazon Bedrock。请求的正文包含消息数组中的提示字符串。

您将学到的内容

  • 添加 Amazon Bedrock 作为数据来源 
  • 配置自定义业务逻辑处理程序代码

实施

 完成时间

10 分钟

 需要

 获取帮助

  • 1.在本地计算机上,导航到 ai-recipe-generator/amplify/data 文件夹,然后创建一个名为 bedrock.js 的文件。 

    2.然后,使用下面的代码更新文件:

    • 以下代码定义了一个请求函数,用于构造 HTTP 请求,以调用 Amazon Bedrock 中的 Claude 3 Sonnet 基础模型。响应函数解析响应并返回生成的配方。
    export function request(ctx) {
        const { ingredients = [] } = ctx.args;
      
        // Construct the prompt with the provided ingredients
        const prompt = `Suggest a recipe idea using these ingredients: ${ingredients.join(", ")}.`;
      
        // Return the request configuration
        return {
          resourcePath: `/model/anthropic.claude-3-sonnet-20240229-v1:0/invoke`,
          method: "POST",
          params: {
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({
              anthropic_version: "bedrock-2023-05-31",
              max_tokens: 1000,
              messages: [
                {
                  role: "user",
                  content: [
                    {
                      type: "text",
                      text: `\n\nHuman: ${prompt}\n\nAssistant:`,
                    },
                  ],
                },
              ],
            }),
          },
        };
      }
      
      export function response(ctx) {
        // Parse the response body
        const parsedBody = JSON.parse(ctx.result.body);
        // Extract the text content from the response
        const res = {
          body: parsedBody.content[0].text,
        };
        // Return the response
        return res;
      }
  • 1.使用以下代码更新 amplify/backend.ts 文件。然后,保存文件。

    • 该代码将 Amazon Bedrock 的 HTTP 数据来源添加到您的 API 中,并授予其调用 Claude 模型的权限。
    import { defineBackend } from "@aws-amplify/backend";
    import { data } from "./data/resource";
    import { PolicyStatement } from "aws-cdk-lib/aws-iam";
    import { auth } from "./auth/resource";
    
    const backend = defineBackend({
      auth,
      data,
    });
    
    const bedrockDataSource = backend.data.resources.graphqlApi.addHttpDataSource(
      "bedrockDS",
      "https://bedrock-runtime.us- east-1.amazonaws.com",
      {
        authorizationConfig: {
          signingRegion: "us-east-1",
          signingServiceName: "bedrock",
        },
      }
    );
    
    bedrockDataSource.grantPrincipal.addToPrincipalPolicy(
      new PolicyStatement({
        resources: [
          "arn:aws:bedrock:us- east-1::foundation-model/anthropic.claude-3-sonnet-20240229-v1:0",
        ],
        actions: ["bedrock:InvokeModel"],
        
      })
    );

结论

您已经使用 Amplify 定义了一个 Lambda 函数,并添加了 Amazon Bedrock 作为 HTTP 数据来源。

部署后端 API

请就我们的表现提供反馈。