使用 AWS Bedrock、Lambda 和 API Gateway 构建生产就绪的文本到文本 API

发布: (2025年12月31日 GMT+8 08:20)
9 min read
原文: Dev.to

Source: Dev.to – Building a Production‑Ready Text‑to‑Text API with AWS Bedrock, Lambda & API Gateway

请提供您希望翻译的正文内容,我将按照要求保留源链接、格式和代码块进行简体中文翻译。

项目概述

本项目演示了如何使用 AWS BedrockAmazon Titan Text 设计并部署一个 可投入生产的文本到文本 AI API,通过 Amazon API Gateway 安全地对外提供,并由 AWS Lambda 提供动力。

目标是展示组织如何将生成式 AI 能力集成到真实的业务系统中,同时保持:

  • 安全性
  • 可扩展性
  • 成本控制
  • 可观测性

商业使用案例

许多组织希望利用生成式 AI 来实现:

  • 内部协作助手
  • 自动化内容生成
  • 文本摘要
  • 数据解释
  • 客户支持自动化

直接将基础模型暴露给应用程序可能会带来安全、成本和治理风险。

本项目通过以下方式解决这些问题:

  1. 将基础模型抽象为受控的 API。
  2. 强制使用一致的提示词和参数。
  3. 集中管理访问、日志记录和成本控制。

其结果是一个 安全的 AI 服务层,可在多个团队和应用之间重复使用。

架构概览

Architecture diagram

流程

  1. 客户端 – 将文本输入发送到 API 端点。
  2. API 网关 – 验证并路由请求。
  3. Lambda – 处理请求并调用 AWS Bedrock。
  4. Amazon Titan – 生成文本响应。
  5. 客户端 – 接收响应。

🛠️ 使用的工具和服务

服务使用原因
AWS Bedrock完全托管的服务,用于访问基础模型;无需管理基础设施;企业级安全;按使用量付费。
Amazon Titan Text (amazon.titan-text-express-v1)快速且成本高效的文本生成;适用于文本到文本的使用场景;在低温度下表现确定性;为企业工作负载而构建。
AWS Lambda无服务器计算用于业务逻辑;处理请求验证和 AI 调用;自动扩展。
Amazon API Gateway安全地将 AI 服务以 REST API 形式公开;提供身份验证、限流和监控;作为应用程序的公共接口。
Python (Boto3)用于调用 Bedrock 的 AWS SDK;轻量且适合生产环境。

🧠 为什么这种设计很重要

  • 无状态 AI 调用 – 基础模型不保留记忆。
  • 显式控制 – 提示词和参数集中管理。
  • 安全优先 – 通过 IAM 控制对 Bedrock 的访问。
  • 成本管理 – 强制执行令牌上限和模型选择。
  • 可复用性 – 多个应用可以共享同一 API。

这与在受监管和企业环境中构建 AI 平台的方式相吻合。

Source:

🧩 AWS Lambda:文本到文本处理逻辑

此示例展示了一个 Python AWS Lambda 函数,它:

  1. 从 API Gateway 接收文本。
  2. 调用 Amazon Bedrock(Titan Text 模型)。
  3. 返回生成的响应。

Lambda 充当您应用程序与基础模型之间的受控 AI 服务层。

1. 创建 Lambda 函数

步骤操作
1打开 AWS Management Console → Lambda
2点击 Create function
3选择 Author from scratch
4输入名称(例如 bedrock-text-to-text)。
5选择 Python 3.x 作为运行时。
6保持默认设置并点击 Create function

2. 添加函数代码

将默认代码替换为来自 GitHub 仓库 的实现。

import json
import boto3
import os

# Initialise Bedrock client
bedrock = boto3.client(
    "bedrock-runtime",
    region_name=os.getenv("AWS_REGION")
)

def lambda_handler(event, context):
    """Handle API‑Gateway request, invoke Titan Text, and return the result."""
    # 1️⃣ Extract the text payload from the request body
    body = json.loads(event.get("body", "{}"))
    user_input = body.get("input", "")

    if not user_input:
        return {
            "statusCode": 400,
            "body": json.dumps({"error": "Missing 'input' in request body"})
        }

    # 2️⃣ Build the request payload for Titan Text
    payload = {
        "prompt": user_input,
        "temperature": 0.0,
        "maxTokens": 1024,
        "topP": 0.9,
        "stopSequences": []
    }

    # 3️⃣ Invoke the model
    try:
        response = bedrock.invoke_model(
            body=json.dumps(payload).encode("utf-8"),
            modelId="amazon.titan-text-express-v1",
            contentType="application/json",
            accept="application/json"
        )
        result = json.loads(response["body"].read())
        generated_text = result.get("completion", "")

        return {
            "statusCode": 200,
            "body": json.dumps({"output": generated_text})
        }

    # 4️⃣ Error handling
    except Exception as e:
        print(f"Error invoking Bedrock: {e}")
        return {
            "statusCode": 500,
            "body": json.dumps({"error": "Internal server error"})
        }

3. 调整 Lambda 设置

设置推荐值备注
Timeout30 秒(或更高)为模型调用提供足够时间。
Memory256 MiB对大多数文本到文本工作负载足够。
Environment VariablesAWS_REGION(如果未自动设置)Bedrock 客户端所需。

现在,Lambda 已准备好通过 API Gateway 接收文本,将其转发给 Amazon Titan Text,并返回生成的输出。 🎉

🔐 所需的 IAM 权限

Lambda 执行角色必须被授权调用 Bedrock 模型。(Lambda 已经拥有写入 CloudWatch 日志的权限。)

  1. 在 Lambda 控制台,进入 Configuration → Permissions
  2. 点击 Role name 打开 IAM 角色。
  3. 附加以下内联策略(或将其添加到已有策略中):
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AllowInvokeTitanText",
      "Effect": "Allow",
      "Action": [
        "bedrock:InvokeModel"
      ],
      "Resource": [
        "arn:aws:bedrock:*:*:model/amazon.titan-text-express-v1"
      ]
    }
  ]
}

提示: 如果计划使用其他 Bedrock 模型,请将它们的 ARN 添加到 Resource 数组中。

📡 通过 API Gateway 暴露 Lambda

  1. 创建新 API – 在 API Gateway 中,选择 REST API(或选择 HTTP API 以获得更轻量的实现)。
  2. 添加 POST 方法 – 创建 /generate 资源并添加 POST 方法。
  3. 配置集成 – 将 Integration type 设置为 Lambda Function,并选择您创建的 Lambda。
  4. 启用 CORS (如果 API 将被浏览器调用)
  5. (可选)附加授权器 – 如 CognitoJWT 等,以强制身份验证。
  6. 部署 API – 部署到某个阶段(例如 prod)。

🚀 测试端到端流程

curl -X POST https://<api-id>.execute-api.<region>.amazonaws.com/prod/generate \
  -H "Content-Type: application/json" \
  -d '{"input":"Explain the benefits of serverless architectures in 2 sentences."}'

预期的 JSON 响应

{
  "output": "Serverless architectures eliminate the need to manage infrastructure, allowing developers to focus on code. They also provide automatic scaling and pay‑as‑you‑go pricing, reducing operational costs."
}

📚 进一步阅读与资源

{
  "Resource": [
    "arn:aws:bedrock:us-east-1::foundation-model/amazon.titan-text-express-v1"
  ]
}

Source:

🌐 API 网关请求示例

  1. 创建 API – 在 API Gateway 控制台点击 Create APIREST APIBuild

    创建 API 界面

  2. 创建资源 – 在 Resources 中点击 Create resource,输入名称并创建。

    创建资源界面

  3. 创建方法 – 点击 Create Method,选择 POST,选择 Lambda function 集成,启用 Lambda proxy integration,并选择你的 Lambda。

    创建方法界面

  4. 部署 API – 点击 Deploy API,创建一个新阶段,命名并部署。

    部署 API 界面

  5. 复制调用 URL – 在 Stage details 页面,复制 Invoke URL,使用任意客户端(例如 Postman)进行测试。

    测试 API 界面

测试请求(Postman)

POST https://05q0if5orb.execute-api.us-east-1.amazonaws.com/prod/text
Content-Type: application/json

{
  "text": "what is Amazon Bedrock"
}

✅ API 响应示例

{
  "response": "\nAmazon Bedrock is the name of AWS’s managed service for managing the underlying infrastructure that powers your intelligent bot. It is a collection of services that you can use to build, deploy, and scale intelligent bots at scale. Amazon Bedrock is a managed service that makes foundation models from leading AI startup and Amazon’s own Titan models available through APIs. For up‑to‑date information on Amazon Bedrock and how 3P models are approved, endorsed or selected please see the provided documentation and relevant FAQs."
}

🧠 为什么这种 Lambda 设计很重要

  • 将基础模型置于安全的 API 之后。
  • 强制使用一致的参数(temperature、token 限制)。
  • 防止客户端直接访问 Bedrock。
  • 实现日志记录、监控和治理。

这种模式常用于构建企业 AI 平台。

📦 示例用例

  • 文本摘要 API
  • AI 驱动的内容生成服务
  • 分析解释引擎
  • 内部 AI 助手后端
  • 安全的生成式 AI 微服务
Back to Blog

相关文章

阅读更多 »

好吧,AI现在变得奇怪地好。

AI的演变 几年前,“AI”指的是一个连“hello”都听不懂的聊天机器人,或者一个推荐引擎,它会误以为因为你买了一个行李箱…