

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 构建
<a name="build"></a>

要开始使用 Amazon Bedrock 构建模型，请先从您的用例开始。然后选择一个 API 和一个端点，然后开始以编程方式使用模型。

**根据您的用例选择 API**

Amazon Bedrock 提供了四种主要的 API 模式来在 Amazon Bedrock 中执行推理。[回应](bedrock-mantle.md)、[聊天完成、](bedrock-mantle.md)[调用](inference-invoke.md)和[交谈](conversation-inference.md)。阅读有关 APIs 支持的更多信息。


| **场景** | **推荐的 API** | 
| --- | --- | 
| 从兼容 OpenAI API 的端点迁移 | 使用兼容 OpenAI APIs：[响应 API 或[聊天](https://platform.openai.com/docs/api-reference/chat)完成 API](https://platform.openai.com/docs/api-reference/responses) | 
| 使用与 OpenAI 兼容端点不兼容的模型 | [使用原生 Amazon Bedrock APIs：C [onverse 和 Inv](conversation-inference.md) oke](inference-invoke.md) 阅读更多有关为您的用例选择合适 APIs 的方法的信息。 | 

**为 Amazon Bedrock 选择端点**

确定要使用哪个 API 后，就可以确定要用于以编程方式与 Amazon Bedrock 进行交互的终端节点。阅读有关 APIs 支持的更多信息。


| **Endpoint** | **支持的 APIs** | 
| --- | --- | 
| bedrock-mantle.\$1 | [响应 API](bedrock-mantle.md)、[聊天完成 API](bedrock-mantle.md) | 
| bedrock-runtime.\$1 | [调用 API](inference-invoke.md)、[Converse API](conversation-inference.md)、[聊天完成](inference-chat-completions.md) API | 

**选择模型**

您可以根据您使用的终端节点查看 Amazon Bedrock 支持的型号列表。


| **Endpoint** | **API** | **描述** | 
| --- | --- | --- | 
| bedrock-runtime.\$1 | ListFoundationModels | 返回 Bedrock 中所有可用基础模型的列表。提供有关多个模型的摘要信息，包括其模型 IDs、提供商名称、支持的模式（文本、图像、嵌入）、 input/output 格式以及它们是否支持流媒体或自定义。使用 GetFoundationModel API 通过特定基础模型的模型 ID 检索有关该模型的详细信息。 | 
| bedrock-mantle.\$1 | client.models.list | 兼容 OpenAI 的 API，用于发现可用模型。检索可用于响应 API 和聊天完成 API 的模型列表。 | 

# APIs 由 Amazon Bedrock 支持
<a name="apis"></a>

**支持推理 APIs **

Amazon Bedrock 提供了四种主要的 API 模式来在 Amazon Bedrock [中执行推理](inference.md)。


| **API 方法** | **服务终端节点** | **最适合的用例** | **关键功能** | 
| --- | --- | --- | --- | 
| [响应 API](bedrock-mantle.md)（推荐） | bedrock-mantle.<suffix> | 有状态的对话 | 将 Response API 用于需要使用内置工具（搜索、代码解释器）、多模式输入和有状态对话的现代代理应用程序 | 
| [聊天完成](bedrock-mantle.md) | bedrock-mantle.<suffix>（推荐）和 bedrock-runtime.<suffix> | 无状态多回合聊天 | 使用 [Chat Completions API](inference-chat-completions.md) 执行轻量级、无状态、以文本为重点的任务，在这些任务中，您需要完全控制聊天记录管理和降低延迟。 | 
| [匡威方法](conversation-inference.md) | bedrock-runtime.<suffix> | 多轮聊天/标准化 | [Converse API](conversation-inference.md) 提供了一个统一的接口，用于与 Amazon Bedrock 中的所有模型进行交互。 | 
| [调用方法](inference-invoke.md) | bedrock-runtime.<suffix> | 单笔交易/大型有效负载 | Invoke API 提供对模型的直接访问，从而更好地控制请求和响应格式。 | 

注意：后缀是 `{region}.amazonaws.com`

阅读有关 [Amazon Bedrock APIs 支持的](inference-api.md)更多信息。

**在之间做出决定 APIs**

您使用的 API 取决于您的用例。


| **使用场景** | **推荐的 API** | 
| --- | --- | 
| 从兼容 OpenAI API 的端点迁移 | 使用兼容 OpenAI APIs：[响应 API](https://platform.openai.com/docs/api-reference/responses) 或[聊天完成](inference-chat-completions.md) API。根据OpenAI的说法，[推荐](https://platform.openai.com/docs/guides/migrate-to-responses)的长期API是响应API。 | 
| 使用与 OpenAI 兼容端点不兼容的模型 | [使用原生 Amazon Bedrock APIs：C [onverse 和调](conversation-inference.md)用。](inference-invoke.md)有关更多信息，请参阅 [使用 API 提交提示并生成响应](inference-api.md)。 | 
| 所有型号均采用一致的接口 | [Converse API](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html)-适用于所有支持消息的模型。只需编写一次代码，即可将其用于不同的模型。有关示例代码，请参阅[匡威 API 示例](https://docs.aws.amazon.com/bedrock/latest/userguide/conversation-inference.html#message-inference-examples)。 | 
| 完全控制直接访问模型 | [调用 API](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html)-通过更好地控制请求和响应格式，提供对模型的直接访问。用于生成文本、图像和嵌入内容。有关示例代码，请参阅[调用模型代码示例](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-invoke.html#inference-example-invoke)。 | 
| Amazon Bedrock 的新手 | 从[响应 API](bedrock-mantle.md) 开始 | 

**每个 API 和端点支持的模型**

首先，浏览我们的[模型](models.md)以决定要使用的模型。确定要使用的模型后，您可以看到 APIs 它支持的模型，并根据该模型选择要使用的端点。`bedrock-mantle`支持 “回复” 和 “聊天完成” API。`bedrock-runtime`支持调用和交谈 API。

# Amazon Bedrock 支持的终端节点
<a name="endpoints"></a>

Amazon Bedrock 支持各种终端节点，具体取决于您是要执行控制平面运算符还是[推理](inference.md)操作。

**控制平面操作**

Amazon Bedrock 控制平面操作可用于终端节点：`bedrock.{region}.amazonaws.com.`它可用于管理资源，例如列出可用[模型](models.md)、创建[自定义模型](custom-models.md)任务和管理[预配置吞吐](prov-throughput.md)量。在此处阅读有关我们的控制平面 API 的[更多信息](https://docs.aws.amazon.com/general/latest/gr/bedrock.html)。

**推理操作**

Amazon Bedrock 支持以下两个主要端点，用于以编程方式执行推理：


| **Endpoint** | **支持的 APIs** | **描述** | 
| --- | --- | --- | 
| bedrock-mantle.\$1region\$1.api.aws | [响应 API](bedrock-mantle.md)/[聊天完成 API](bedrock-mantle.md) | 特定区域的终端节点，用于使用兼容 OpenAI 的终端节点对托管在 Amazon Bedrock 中的模型发出推理请求。 | 
| bedrock-runtime.\$1region\$1.amazonaws.com | [InvokeModel](inference-invoke.md)/[Converse](conversation-inference.md)/[聊天完成](inference-chat-completions.md) | 特定区域的终端节点，用于使用 /Converse/Chat 完成功能对托管在 Amazon Bedrock 中的模型发出推理请求。 InvokeModel APIs在此处阅读有关 Amazon Bedrock Runtime 的 APIs [更多信息](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Amazon_Bedrock_Runtime.html)。 | 

**您应该使用哪个服务端点进行推理？**

您使用的终端节点取决于您的用例。


| **Endpoint** | **功能和用例** | 
| --- | --- | 
| bedrock-mantle |  支持兼容 OpenAI APIs （[响应 API](bedrock-mantle.md)、[聊天完成 API）。](bedrock-mantle.md) **用于：从使用**兼容 OpenAI APIs 的其他型号轻松迁移。 **功能：**支持客户端和服务器端工具与 Lambda 函数一起使用，并在您的应用程序中配置了 ready-to-use工具。 **推荐对象：A** mazon Bedrock 的新用户。  | 
| bedrock-runtime |  支持 Amazon Bedrock 原生 APIs （[调用 API](inference-invoke.md)、C [onverse API](conversation-inference.md)）。还支持兼容 OpenAI 的[聊天完成 AP](inference-chat-completions.md) I。 **用于：**运行 Amazon Bedrock 支持的任何型号。C [onverse API](conversation-inference.md) 提供了一个统一的接口，用于与 Amazon Bedrock 中的所有模型进行交互，而 [Invoke API](inference-invoke.md) 则提供对模型的直接访问，从而更有能力控制请求和响应格式。您还可以使用[聊天完成 API](inference-chat-completions.md) 与您的模型互动。 **功能：**仅支持客户端工具与 Lambda 函数一起使用，且未预 ready-to-use先配置工具。允许您在调用模型时跟踪使用情况和成本。  | 

如果您不熟悉 Amazon Bedrock，我们建议您从`bedrock-mantle`终端节点开始。

# 项目 API
<a name="projects"></a>

[Amazon Bedrock Projects API 使用兼容 OpenAI 的方式，为您的生成人工智能工作负载提供应用程序级隔离。 APIs](bedrock-mantle.md)项目使您能够通过改进整个组织的访问控制、成本跟踪和可观察性来组织和管理 AI 应用程序。

**注意**  
项目只能与使用兼容 OpenAI APIs 的模型与[基岩](bedrock-mantle.md)地幔端点搭配使用。如果您使用的是 bedrock-runtime 端点，请使用推理配置文件代替标记和可观察性。

## 什么是项目？
<a name="projects-what-is"></a>

项目是一个逻辑边界，用于在 Amazon Bedrock 中隔离应用程序、环境或实验等工作负载。项目提供以下功能：
+ **访问隔离**：使用 [AWS Identity and Access Management (IAM) 策略控制谁可以访问](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html)特定项目资源
+ **成本监控**：使用 [AWS 标签和 AWS](https://docs.aws.amazon.com/whitepapers/latest/tagging-best-practices/what-are-tags.html) Cost [Explorer](https://docs.aws.amazon.com/cost-management/latest/userguide/ce-what-is.html) 跟踪项目层面的支出

项目允许您在生产环境中管理多个生成式 AI 工作负载，而无需创建单独的 AWS 账户或组织，从而在维护安全和治理的同时降低运营复杂性。

每个 AWS 账户都有一个默认项目，所有推理请求都与该项目相关联。您可以使用项目 API 在自己的账户中创建更多项目。

## 何时使用项目
<a name="projects-when-to-use"></a>

当你需要执行以下操作时，你应该使用项目 API：
+ **按业务结构整理**：根据您的组织分类（例如业务部门、团队、应用程序或成本中心）管理 Bedrock 的使用情况
+ **隔离敏感数据**：确保其他应用程序无法访问来自一个应用程序的提示、响应和上下文数据
+ **准确跟踪成本**：监控人工智能支出并将其分配给特定团队、项目或环境
+ **强制执行访问策略**：应用精细的 IAM 权限来控制谁可以访问特定 AI 工作负载
+ **扩展生产工作负载**：在明确的运营界限和监控的情况下运行多个生产应用程序

## 项目与推理配置文件
<a name="projects-vs-inference-profiles"></a>

Projects API 和[推理配置文件](inference-profiles-create.md)都在 Amazon Bedrock 中提供隔离、标记和访问控制功能，但它们因您使用的 API 而异。如果你使用与 OpenAI 兼容的 b [edrock- APIs mantle](endpoints.md) 端点（使用 Mantle 推理引擎），请使用 Projects API。如果您将 Invo [ke 或 Converse APIs 与基底运行时端点一起使用，请使用推](endpoints.md)理配置文件。虽然你可以将 Chat Completions API 与 bedrock-mantle 或基岩运行时端点一起使用，但我们建议你使用 Mantle 端点。


| 功能 | 项目 API | 推理配置文件 | 
| --- | --- | --- | 
| 支持的 APIs | 兼容 OpenAI APIs （回复、聊天完成） | Native Bedrock APIs （调用、Converse）、兼容 OpenAI 的 API（聊天完成） | 
| 端点 | bedrock-mantle.\$1region\$1.api.aws | bedrock-runtime.\$1region\$1.amazonaws.com | 
| 使用场景 | 使用兼容 OpenAI 的端点的应用程序 | 使用原生 Bedrock 的应用程序 APIs | 
| 访问控制 | 在 IAM 策略中将项目作为资源 | 推理配置文件上的 IAM 策略 ARN | 
| 成本跟踪 | 项目上的 AWS 标签 | 推理配置文件上的 AWS 标签 | 

## 项目与 AWS 账户
<a name="projects-vs-aws-accounts"></a>

[AWS 账户](https://docs.aws.amazon.com/accounts/latest/reference/accounts-welcome.html)和 [AWS Org](https://docs.aws.amazon.com/controltower/latest/userguide/organizations.html) anizations 代表基础设施级别的账单和所有权界限。项目代表单个账户内的工作负载和应用程序边界。

使用项目代替单独的 AWS 账户可提供：
+ **更快的设置**：通过 API 调用在几秒钟内创建项目
+ **降低复杂性**：管理多个工作负载，避免账户扩张
+ **简化操作**：在一个账户内进行集中管理
+ **降低开销**：无需跨账户 IAM 角色或资源共享

## 项目入门
<a name="projects-getting-started"></a>

本页将引导您创建第一个项目、将其与推理请求关联以及管理项目资源。

### 先决条件
<a name="projects-prerequisites"></a>

在开始之前，请确保您满足以下条件：
+ 具有亚马逊 Bedrock 访问权限的 AWS 账户
+ 创建和管理 Bedrock 项目的 IAM 权限
+ 已安装 Python 3.7 或更高版本
+ 安装的 OpenAI Python SDK：`pip install openai boto3`
+ 用于 Amazon Bedrock 身份验证的 [API 密钥](api-keys.md)

### 步骤 1：设置您的环境
<a name="projects-setup-environment"></a>

使用您的 Amazon Bedrock 凭证配置您的环境变量：

```
export OPENAI_API_KEY="<your-bedrock-key>"
export OPENAI_BASE_URL="https://bedrock-mantle.<your-region>.api.aws/v1"
```

`<your-region>`替换为您的 AWS 区域（例如 us-east-1、us-west-2）。

**注意**  
Amazon Bedrock 提供[两种类型的密钥](https://docs.aws.amazon.com/bedrock/latest/userguide/api-keys-how.html)：短期密钥和长期密钥。虽然您可以使用长期 API 密钥来探索 Amazon Bedrock，但对于安全要求更高的应用程序，我们建议使用短期密钥。如果您在 Projects 中使用长期密钥，请注意，附加到长期密钥的默认策略仅允许您获取和列出项目，但不允许获取和列create/update/archive出项目。如果您希望使用长期密钥来管理项目，则必须为密钥分配其他 IAM 策略才能启用这些操作。

### 第 2 步：发现可用型号
<a name="projects-discover-models"></a>

使用 `list()` API 检索与 Projects API 兼容的模型列表：

```
curl -X GET $OPENAI_BASE_URL/models \
  -H "Authorization: Bearer $OPENAI_API_KEY"
```

### 第 3 步：创建您的第一个项目
<a name="projects-create-first"></a>

使用带有成本监控和可观察性标签的 Create Project API 创建项目。请注意，目前软件开发工具包中仅支持 cURL。

```
curl -X POST $OPENAI_BASE_URL/organization/projects \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Project ABC",
    "tags": {
      "Project": "CustomerChatbot",
      "Environment": "Production",
      "Owner": "TeamAlpha",
      "CostCenter": "21524"
    }
  }' -v
```

响应：

```
{
  "arn": "arn:aws:bedrock-mantle:ap-northeast-1:673693429514:project/proj_5d5ykleja6cwpirysbb7",
  "created_at": 1772135628,
  "id": "proj_5d5ykleja6cwpirysbb7",
  "name": "Project ABC",
  "object": "organization.project",
  "status": "active",
  "tags": {
    "Owner": "TeamAlpha",
    "Project": "CustomerChatbot",
    "Environment": "Production",
    "CostCenter": "21524"
  }
}
```

**重要注意事项：**
+ Amazon Bedrock 忽略了 OpenAI API 规范中的地理参数。
+ 该区域由您的终端节点配置决定。
+ arn 字段特定于 Amazon Bedrock，它提供了 IAM 策略附件的 ARN。
+ 标签可以在项目创建过程中指定，并在所有项目响应中返回。

### 步骤 4：将推理请求与您的项目关联
<a name="projects-associate-inference"></a>

要将您的项目与推理请求相关联，请在创建客户端时提供项目 ID：

------
#### [ cURL ]

```
curl -X POST $OPENAI_BASE_URL/responses \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -H "OpenAI-Project: proj_5d5ykleja6cwpirysbb7" \
  -d '{
    "model": "openai.gpt-oss-120b",
    "input": "Explain the benefits of using projects in Amazon Bedrock"
  }'
```

------
#### [ Python ]

```
from openai import OpenAI
client = OpenAI(project="proj_5d5ykleja6cwpirysbb7")
```

------

向该客户端提出的所有推理请求都将与指定的项目相关联，从而确保适当的隔离、成本跟踪和访问控制。

### 第 5 步：验证您的项目设置
<a name="projects-verify-setup"></a>

列出所有项目以验证您的项目是否已成功创建：

```
curl -X GET $OPENAI_BASE_URL/organization/projects \
  -H "Authorization: Bearer $OPENAI_API_KEY"
```

响应：

```
{
  "data": [
    {
      "arn": "arn:aws:bedrock-mantle:ap-northeast-1:673693429514:project/default",
      "created_at": 1764460800,
      "id": "default",
      "name": "default",
      "object": "organization.project",
      "status": "active",
      "tags": {}
    },
    {
      "arn": "arn:aws:bedrock-mantle:ap-northeast-1:673693429514:project/proj_2z766pfxmkij5vwubv75",
      "created_at": 1771823259,
      "id": "proj_2z766pfxmkij5vwubv75",
      "name": "Project ABC",
      "object": "organization.project",
      "status": "active",
      "tags": {}
    }
  ],
  "first_id": "default",
  "has_more": false,
  "last_id": "proj_znaruqn723npmjqnxqfd",
  "object": "list"
}
```

### 后续步骤
<a name="projects-next-steps"></a>

现在你已经创建了第一个项目，你可以：
+ **配置访问控制**：附加 IAM 策略以限制项目访问权限
+ **设置成本跟踪**：为成本分配添加 AWS 标签
+ **启用监控**：配置 CloudWatch 指标和警报
+ **创建其他项目**：按团队、环境或应用程序组织工作负载

## 处理 项目
<a name="projects-working-with"></a>

本页提供有关在整个生命周期中管理项目的详细信息。

### 创建项目
<a name="projects-creating"></a>

#### 基本项目创建
<a name="projects-basic-creation"></a>

创建一个带有名称、描述和标签的项目：

```
curl -X POST $OPENAI_BASE_URL/v1/organization/projects \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Development Environment",
    "tags": {
      "Project": "InternalTools",
      "Environment": "Development",
      "Owner": "TeamAlpha",
      "CostCenter": "30156"
    }
  }'
```

每个账户最多可以有 1000 个项目。

#### 推荐的命名约定
<a name="projects-naming-conventions"></a>

使用能反映您的组织结构的清晰描述性名称：
+ **按应用分类**： CustomerChatbot-Prod、-Dev InternalSearch
+ **按团队划分**： TeamAlpha-制作， DataScience-实验
+ **按环境划**分：生产-WebApp、暂存-MobileApp
+ **按成本中心**划分： CostCenter-2152-产量

### 列出项目
<a name="projects-listing"></a>

#### 列出所有项目
<a name="projects-list-all"></a>

检索您账户中的所有项目：

```
curl -X GET $OPENAI_BASE_URL/organization/projects \
  -H "Authorization: Bearer $OPENAI_API_KEY"
```

### 检索项目详情
<a name="projects-retrieving-details"></a>

获取有关特定项目的详细信息：

```
curl -X GET $OPENAI_BASE_URL/organization/projects/proj_5d5ykleja6cwpirysbb7 \
  -H "Authorization: Bearer $OPENAI_API_KEY"
```

### 更新项目
<a name="projects-updating"></a>

修改项目属性，例如名称：

```
curl -X POST $OPENAI_BASE_URL/organization/projects/proj_5d5ykleja6cwpirysbb7 \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Production Chatbot v2"
  }'
```

### 管理项目标签
<a name="projects-managing-tags"></a>

添加新标签或更新现有标签值：

```
curl -X POST $OPENAI_BASE_URL/organization/projects/proj_5d5ykleja6cwpirysbb7 \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "add_tags": {
      "Application": "WebApp",
      "Version": "2.0",
      "Team": "Engineering"
    }
  }'
```

按密钥移除特定标签：

```
curl -X POST $OPENAI_BASE_URL/organization/projects/proj_5d5ykleja6cwpirysbb7 \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "remove_tag_keys": ["Version", "OldTagKey"]
  }'
```

**重要提示**  
**没有完全替换**：没有一次替换整个标签集的操作。必须明确指定要添加哪些标签和要删除哪些标签。
**错误处理**：实施正确的错误处理和验证

### 存档项目
<a name="projects-archiving"></a>

存档不再使用的项目：

```
curl -X POST $OPENAI_BASE_URL/organization/projects/proj_abc123/archive \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json"
```

**重要**  
存档的项目不能用于新的推理请求，但历史数据和指标的访问时间最长可达 30 天。

### 使用具有不同内容的项目 APIs
<a name="projects-using-apis"></a>

------
#### [ Responses API ]

```
from openai import OpenAI

client = OpenAI(project="proj_abc123")

response = client.responses.create(
    model="openai.gpt-oss-120b",
    input="What are the key features of Amazon Bedrock?"
)
print(response)
```

------
#### [ Chat Completions API ]

```
from openai import OpenAI

client = OpenAI(project="proj_abc123")

response = client.chat.completions.create(
    model="openai.gpt-oss-120b",
    messages=[
        {"role": "user", "content": "Explain how projects improve security"}
    ]
)

print(response.choices[0].message.content)
```

------

### 最佳实践
<a name="projects-best-practices"></a>

#### 推荐的项目结构
<a name="projects-recommended-structure"></a>

**每个应用程序一个项目**：为每个不同的应用程序或服务创建单独的项目。

```
├── CustomerChatbot-Production
├── CustomerChatbot-Staging
├── CustomerChatbot-Development
├── InternalSearch-Production
└── InternalSearch-Development
```
+ **单独的环境**：为开发、暂存和生产环境使用不同的项目。
+ **实验隔离**:为实验创建专门的项目，然后 proof-of-concepts.

#### 项目生命周期管理
<a name="projects-lifecycle-management"></a>
+ **尽早创建项目**：在部署应用程序之前设置项目
+ **使用一致的命名**：遵循组织命名惯例
+ **记录项目目的**：包括清晰的描述
+ **定期审计**：定期审查和存档未使用的项目
+ **监控使用情况**：跟踪项目指标以确定优化机会

# API 密钥
<a name="api-keys"></a>

您可以通过生成 Amazon Bedrock API 密钥并在向 Amazon Bedrock API 发出请求时使用它来验证您的身份，从而轻松调用 Amazon Bedrock API。

**注意**  
出于审计和合规目的，所有 API 调用均已登录 AWS CloudTrail。Amazon Bedrock API 密钥作为授权标头传递给 API 请求，不会被记录下来。  
Amazon Bedrock API 密钥仅限于 [Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Amazon_Bedrock.html) 和 [Amazon Bedrock 运行时](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Amazon_Bedrock_Runtime.html)操作。您无法将这样的密钥与以下 API 操作结合使用：  
[InvokeModelWithBidirectionalStream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModelWithBidirectionalStream.html).
[Amazon Bedrock 代理](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Agents_for_Amazon_Bedrock.html)或 [Amazon Bedrock 代理运行时](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Agents_for_Amazon_Bedrock.html) API 操作。
[Amazon Bedrock 数据自动化](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Data_Automation_for_Amazon_Bedrock.html)或 [Amazon Bedrock 数据自动化运行时](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Runtime_for_Amazon_Bedrock_Data_Automation) API 操作。

Amazon Bedrock 允许您生成以下类型的 Amazon Bedrock API 密钥：
+ **短期** – 创建一个 Amazon Bedrock API 密钥，该密钥的持续时间与您的会话持续时间相同（不超过 12 小时）。您应该已为 [IAM 主体](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction_identity-management.html#intro-structure-terms)设置了适当的 Amazon Bedrock 使用权限。对于需要定期更改凭证以提高安全性的生产环境，此选项比长期密钥更受青睐。

  短期密钥具有以下属性：
  + 以下值中时间较短者有效：
    + 12 小时
    + 用于生成密钥的 IAM 主体所生成会话的持续时间。
  + 继承用于生成密钥的主体所附加的权限。
  + 只能在您生成它的 AWS 区域中使用。
+ **长期** – 创建 Amazon Bedrock API 密钥，并提供在 Amazon Bedrock 中发出基本 API 请求的权限。这个简单的一键式选项可让您快速开始探索 Amazon Bedrock API，无需了解底层安全基础设施或手动配置 AWS Identity and Access Management 权限。如果您是第一次试用 Amazon Bedrock，可以试试[开始使用 Amazon Bedrock API 密钥：生成 30 天密钥并发出第一个 API 调用](getting-started-api-keys.md)中的示例，获取创建长期密钥并开始使用 Amazon Bedrock 的简单教程。
**警告**  
我们强烈建议限制使用 Amazon Bedrock API 密钥来探索 Amazon Bedrock。当您准备将 Amazon Bedrock 整合到具有更高安全要求的应用程序中时，应切换到短期凭证。有关更多信息，请参阅《IAM 用户指南》中的[长期访问密钥的替代方案](https://docs.aws.amazon.com/IAM/latest/UserGuide/security-creds-programmatic-access.html#security-creds-alternatives-to-long-term-access-keys)。

选择一个主题以了解有关 Amazon Bedrock API 密钥的更多信息。不同类型的 Amazon Bedrock 密钥有多种选项以及自定义方法。有关如何生成长期 Amazon Bedrock API 密钥并将其用于探索目的的快速入门教程，请参阅[开始使用 Amazon Bedrock API 密钥：生成 30 天密钥并发出第一个 API 调用](getting-started-api-keys.md)。

**Topics**
+ [Amazon Bedrock API 密钥的工作方式](api-keys-how.md)
+ [亚马逊 Bedrock API 密钥支持的区域和 AWS 软件开发套件 (SDKs)](api-keys-supported.md)
+ [生成 Amazon Bedrock API 密钥](api-keys-generate.md)
+ [使用 Amazon Bedrock API 密钥](api-keys-use.md)
+ [修改长期和短期 Amazon Bedrock API 密钥的权限](api-keys-modify.md)
+ [处理泄露的长期和短期 Amazon Bedrock API 密钥](api-keys-revoke.md)
+ [控制生成和使用 Amazon Bedrock API 密钥的权限](api-keys-permissions.md)

# Amazon Bedrock API 密钥的工作方式
<a name="api-keys-how"></a>

下图将默认的凭证获取过程与 Amazon Bedrock API 密钥的使用情况进行了对比：

![\[默认 API 设置过程与使用 Amazon Bedrock API 密钥的 API 设置过程的对比\]](http://docs.aws.amazon.com/zh_cn/bedrock/latest/userguide/images/setup/setup-api.png)


图中最左边的流程说明了在 AWS IAM Identity Center 或 IAM 中创建身份的默认过程。通过此过程，您可以将 IAM 策略附加到该身份，以提供执行 API 操作的权限，然后为该身份生成常规 AWS 凭证。接着，您可以使用凭证在 AWS 中发出 API 调用。

蓝色节点表示还有两个流需要专门向 Amazon Bedrock 进行身份验证。这两个流都涉及创建一个 Amazon Bedrock API 密钥，您可以使用该密钥进行身份验证，以便使用 Amazon Bedrock 操作。您可以生成以下类型的密钥：
+ **短期密钥** – 一种安全选项，允许授予临时访问权限以便使用 Amazon Bedrock。

  短期密钥具有以下属性：
  + 以下值中时间较短者有效：
    + 12 小时
    + 用于生成密钥的 IAM 主体所生成会话的持续时间。
  + 继承用于生成密钥的主体所附加的权限。
  + 只能在您生成它的 AWS 区域中使用。
+ **长期密钥** – 仅推荐用于探索 Amazon Bedrock。您可以设置密钥到期的时间。当您生成长期密钥时，它会在底层创建适合您的 IAM 用户，附加您选择的 IAM 策略，并将密钥与用户关联。生成密钥后，您可以使用 IAM 服务[修改 IAM 用户的权限](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage-attach-detach.html)。
**警告**  
我们强烈建议限制使用 Amazon Bedrock API 密钥来探索 Amazon Bedrock。当您准备将 Amazon Bedrock 整合到具有更高安全要求的应用程序中时，应切换到短期凭证。有关更多信息，请参阅《IAM 用户指南》中的[长期访问密钥的替代方案](https://docs.aws.amazon.com/IAM/latest/UserGuide/security-creds-programmatic-access.html#security-creds-alternatives-to-long-term-access-keys)。

# 亚马逊 Bedrock API 密钥支持的区域和 AWS 软件开发套件 (SDKs)
<a name="api-keys-supported"></a>

以下列表显示了 AWS 区域 支持 API 密钥的：
+ ap-northeast-1
+ ap-northeast-2
+ ap-northeast-3
+ ap-south-1
+ ap-south-2
+ ap-southeast-1
+ ap-southeast-2
+ ca-central-1
+ eu-central-1
+ eu-central-2
+ eu-north-1
+ eu-south-1
+ eu-south-2
+ eu-west-1
+ eu-west-2
+ eu-west-3
+ sa-east-1
+ us-east-1
+ us-gov-east-1
+ us-gov-west-1
+ us-west-2

**注意**  
Amazon Bedrock API 密钥仅限于 [Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Amazon_Bedrock.html) 和 [Amazon Bedrock 运行时](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Amazon_Bedrock_Runtime.html)操作。您无法将这样的密钥与以下 API 操作结合使用：  
[InvokeModelWithBidirectionalStream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModelWithBidirectionalStream.html).
[Amazon Bedrock 代理](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Agents_for_Amazon_Bedrock.html)或 [Amazon Bedrock 代理运行时](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Agents_for_Amazon_Bedrock.html) API 操作。
[Amazon Bedrock 数据自动化](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Data_Automation_for_Amazon_Bedrock.html)或 [Amazon Bedrock 数据自动化运行时](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Runtime_for_Amazon_Bedrock_Data_Automation) API 操作。

以下内容 AWS SDKs支持 Amazon Bedrock API 密钥：
+ Python
+ Javascript
+ Java

# 生成 Amazon Bedrock API 密钥
<a name="api-keys-generate"></a>

您可以使用 AWS 管理控制台或 AWS API 生成 Amazon Bedrock API 密钥。我们建议您使用 AWS 管理控制台，通过几个步骤轻松生成 Amazon Bedrock API 密钥。

**警告**  
我们强烈建议限制使用 Amazon Bedrock API 密钥来探索 Amazon Bedrock。当您准备将 Amazon Bedrock 整合到具有更高安全要求的应用程序中时，应切换到短期凭证。有关更多信息，请参阅《IAM 用户指南》中的[长期访问密钥的替代方案](https://docs.aws.amazon.com/IAM/latest/UserGuide/security-creds-programmatic-access.html#security-creds-alternatives-to-long-term-access-keys)。

**Topics**
+ [使用控制台生成 Amazon Bedrock API 密钥](#api-keys-generate-console)
+ [使用 API 生成长期 Amazon Bedrock API 密钥](#api-keys-generate-api-long-term)
+ [使用客户端库生成短期 Amazon Bedrock API 密钥](#api-keys-generate-short-term)
+ [设置短期 Amazon Bedrock API 密钥的自动刷新](#api-keys-refresh-short-term)

## 使用控制台生成 Amazon Bedrock API 密钥
<a name="api-keys-generate-console"></a>

要使用控制台生成 Amazon Bedrock API 密钥，请执行以下操作：

1. 采用有权使用 Amazon Bedrock 控制台的 IAM 身份登录 AWS 管理控制台。然后，通过以下网址打开 Amazon Bedrock 控制台：[https://console.aws.amazon.com/bedrock](https://console.aws.amazon.com/bedrock)。

1. 在左侧导航窗格中，选择 **API 密钥**。

1. 生成以下类型的密钥之一：
   + **短期 API 密钥** – 在**短期 API 密钥**选项卡中，选择**生成短期 API 密钥**。密钥将在您的控制台会话过期（且不超过 12 小时）时过期，并允许您调用生成密钥的 AWS 区域。您可以直接在生成的密钥中修改区域。
   + **长期 API 密钥** – 在**长期 API 密钥**选项卡中，选择**生成长期 API 密钥**。

     1. 在 **API 密钥过期**部分中，选择密钥过期的时间。

     1. （可选）默认情况下，[AmazonBedrockLimitedAccess](security-iam-awsmanpol.md#security-iam-awsmanpol-AmazonBedrockLimitedAccess) AWS 托管策略（授予 Amazon Bedrock API 核心操作的访问权限）会附加到与密钥关联的 IAM 用户。要选择更多要附加到用户的策略，请展开**高级权限**部分，然后选择要添加的策略。

     1. 选择**生成**。
**警告**  
我们强烈建议限制使用 Amazon Bedrock API 密钥来探索 Amazon Bedrock。当您准备将 Amazon Bedrock 整合到具有更高安全要求的应用程序中时，应切换到短期凭证。有关更多信息，请参阅《IAM 用户指南》中的[长期访问密钥的替代方案](https://docs.aws.amazon.com/IAM/latest/UserGuide/security-creds-programmatic-access.html#security-creds-alternatives-to-long-term-access-keys)。



## 使用 API 生成长期 Amazon Bedrock API 密钥
<a name="api-keys-generate-api-long-term"></a>

在 API 中创建长期 Amazon Bedrock API 密钥的常见步骤如下：

1. 通过使用 [IAM 端点](https://docs.aws.amazon.com/general/latest/gr/iam-service.html)发送 [CreateUser](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateUser.html) 请求来创建 IAM 用户。

1. 通过使用 [IAM 端点](https://docs.aws.amazon.com/general/latest/gr/iam-service.html)发送 [AttachUserPolicy](https://docs.aws.amazon.com/IAM/latest/APIReference/API_AttachUserPolicy.html) 请求，将 [AmazonBedrockLimitedAccess](security-iam-awsmanpol.md#security-iam-awsmanpol-AmazonBedrockLimitedAccess) 附加到 IAM 用户。您可以重复此步骤，根据需要将其他托管策略或自定义策略附加到用户。
**注意**  
作为最佳安全实践，我们强烈建议您将 IAM 策略附加到 IAM 用户，以限制对 Amazon Bedrock API 密钥的使用。有关限时策略以及限制可使用密钥的 IP 地址的示例，请参阅[通过将内联策略附加到 IAM 用户，从而控制访问密钥的使用](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-keys_inline-policy.html)。

1. 通过使用 [IAM 端点](https://docs.aws.amazon.com/general/latest/gr/iam-service.html)发送 [CreateServiceSpecificCredential](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateServiceSpecificCredential.html.html) 请求，并将 `bedrock.amazonaws.com` 指定为 `ServiceName`，生成长期 Amazon Bedrock API 密钥。
   + 响应中返回的 `ServiceApiKeyValue` 是长期 Amazon Bedrock API 密钥。
   + 响应中返回的 `ServiceSpecificCredentialId` 可用于执行与密钥相关的 API 操作。

要了解如何生成长期 Amazon Bedrock API 密钥，请选择与您的首选方法对应的选项卡，然后按照以下步骤操作：

------
#### [ CLI ]

要创建长期 Amazon Bedrock API 密钥，请使用 AWS Identity and Access Management API 操作。首先，确保满足先决条件：

**先决条件**  
确保您的设置允许 AWS CLI 自动识别您的 AWS 凭证。要了解更多信息，请参阅[配置 AWS CLI 设置](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)。

打开一个终端，并运行以下命令：

1. 创建 IAM 用户。您可以用自己选择的名称替换下面的名称：

   ```
   aws iam create-user --user-name bedrock-api-user
   ```

1. 将 [AmazonBedrockLimitedAccess](security-iam-awsmanpol.md#security-iam-awsmanpol-AmazonBedrockLimitedAccess) 附加到用户。对于要添加到 API 密钥中的其他任何 AWS 托管策略或自定义策略的 ARN，您可以重复此步骤：

   ```
   aws iam attach-user-policy --user-name bedrock-api-user --policy-arn arn:aws:iam::aws:policy/AmazonBedrockLimitedAccess
   ```

1. 创建长期 Amazon Bedrock API 密钥，并将 *\$1\$1NUMBER-OF-DAYS\$1* 替换为您希望密钥持续使用的天数：

   ```
   aws iam create-service-specific-credential \
       --user-name bedrock-api-user \
       --service-name bedrock.amazonaws.com \
       --credential-age-days ${NUMBER-OF-DAYS}
   ```

------
#### [ Python ]

要创建长期 Amazon Bedrock API 密钥，请使用 AWS Identity and Access Management API 操作。首先，确保满足先决条件：

**先决条件**  
确保您的设置允许 Python 自动识别您的 AWS 凭证。要了解更多信息，请参阅[配置 AWS CLI 设置](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)。

运行以下脚本创建 IAM 用户，附加用于执行 Amazon Bedrock 操作的权限，并生成与该用户关联的长期 Amazon Bedrock API 密钥：

```
import boto3
from datetime import datetime, timedelta

# Replace with name for your IAM user
username = "bedrock-api-user"
# Add any AWS-managed or custom policies that you want to the user
bedrock_policies = [
    "arn:aws:iam::aws:policy/AmazonBedrockLimitedAccess",        # Limited access
#    "arn:aws:iam::aws:policy/AmazonBedrockMarketplaceAccess",   # Optional: Access to Amazon Bedrock Marketplace actions
]
# Set the key expiration time to a number of your choice
expiration_time_in_days = 30

iam_client = boto3.client("iam")
    
# Create IAM user
user = iam_client.create_iam_user(username)

# Attach policies to user
for policy_arn in bedrock_policies:
    iam_client.attach_managed_policy(username, policy_arn)

# Create long-term Amazon Bedrock API key and return it
service_credentials = iam_client.create_service_specific_credential(
    user_name=username, 
    service_name="bedrock",
    credential_age_days=expiration_time_in_days
) 
api_key = service_credentials["ServiceApiKeyValue"]
print(api_key)
```

------

## 使用客户端库生成短期 Amazon Bedrock API 密钥
<a name="api-keys-generate-short-term"></a>

短期密钥具有以下属性：
+ 以下值中时间较短者有效：
  + 12 小时
  + 用于生成密钥的 IAM 主体所生成会话的持续时间。
+ 继承用于生成密钥的主体所附加的权限。
+ 只能在您生成它的 AWS 区域中使用。

对于长时间运行的应用程序，[aws-bedrock-token-generator](https://github.com/aws/aws-bedrock-token-generator-js/blob/main/README.md) 客户端库可以在系统刷新凭证时，根据需要创建新的 Amazon Bedrock 短期 API 密钥。有关更多信息，请参阅[设置短期 Amazon Bedrock API 密钥的自动刷新](#api-keys-refresh-short-term)。

**先决条件**
+ 对于用于生成密钥的 IAM 主体，确保已设置了使用 Amazon Bedrock 的适当权限。出于实验目的，您可以将 AWS 托管的 [AmazonBedrockLimitedAccess](security-iam-awsmanpol.md#security-iam-awsmanpol-AmazonBedrockLimitedAccess) 策略附加到主体。您可以参考 [IAM 中的安全最佳实践](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)来保护您的凭证。
+ 确保您的设置允许 Python 自动识别您的 AWS 凭证。检索凭证的默认方法遵循定义的层次结构。您可以在 [AWS SDK 和工具标准化凭证提供商](https://docs.aws.amazon.com/sdkref/latest/guide/standardized-credentials.html)中查看特定开发工具包或工具的层次结构。
+ 安装 Amazon Bedrock 令牌生成器。选择与您的首选方法对应的选项卡，然后按照以下步骤操作：

------
#### [ Python ]

打开一个终端，并运行以下命令：

```
pip install aws-bedrock-token-generator
```

------
#### [ Javascript ]

打开一个终端，并运行以下命令：

```
npm install @aws/bedrock-token-generator
```

------
#### [ Java ]

如果您使用 Maven，请将以下依赖项添加到 `pom.xml`：

```
<dependency>
    <groupId>software.amazon.bedrock</groupId>
    <artifactId>aws-bedrock-token-generator</artifactId>
    <version>1.1.0</version>
</dependency>
```

如果您使用 Gradle，请将以下内容添加到 `build.gradle`：

```
implementation 'software.amazon.bedrock:aws-bedrock-token-generator:1.1.0'
```

------

**示例**  
要查看使用令牌生成器生成短期 Amazon Bedrock API 密钥（使用不同语言的默认凭证）的示例，请选择与您的首选方法对应的选项卡，然后按照以下步骤操作：

------
#### [ Python ]

```
from aws_bedrock_token_generator import provide_token

token = provide_token()
print(f"Token: {token}")
```

------
#### [ Javascript ]

```
import { getTokenProvider } from "@aws/bedrock-token-generator";

// Create a token provider that uses default credentials and region providers.
// You can configure it to use other credential providers.
const provideToken = getTokenProvider();

async function example() {
    
  const token = await provideToken();

  // Use the token for API calls. The token has a default expiration of 12 hour.
  // If the expiresInSeconds parameter is specified during token creation, the 
  // expiration can be configured up to a maximum of 12 hours. However, the actual 
  // token validity period will always be the minimum of the requested expiration 
  // time and the AWS credentials' expiry time
  console.log(`Bearer Token: ${token}`);
}
```

------
#### [ Java ]

```
import software.amazon.bedrock.token.BedrockTokenGenerator;

// Credentials and region will be picked up from the default provider chain
BedrockTokenGenerator tokenGenerator = BedrockTokenGenerator.builder().build();
tokenGenerator.getToken();
```

------

要在生成令牌时查看不同使用案例的更多示例，请参阅以下链接：
+ [Python](https://github.com/aws/aws-bedrock-token-generator-python/blob/main/README.md)
+ [Javascript](https://github.com/aws/aws-bedrock-token-generator-js/blob/main/README.md)
+ [Java](https://github.com/aws/aws-bedrock-token-generator-java/blob/main/README.md)

## 设置短期 Amazon Bedrock API 密钥的自动刷新
<a name="api-keys-refresh-short-term"></a>

您可以在 `aws-bedrock-token-generator` 软件包的帮助下创建脚本，以便每当目前的短期密钥过期时，以编程方式重新生成新的短期密钥。首先，确保满足[使用客户端库生成短期 Amazon Bedrock API 密钥](#api-keys-generate-short-term)中的先决条件。要查看用于检索令牌并发出 Converse 请求的示例脚本，请选择与首选方法对应的选项卡，然后按照以下步骤操作：

------
#### [ Python ]

```
from aws_bedrock_token_generator import provide_token
import requests

def get_new_token():
    url = "https://bedrock-runtime.us-west-2.amazonaws.com/model/us.anthropic.claude-3-5-haiku-20241022-v1:0/converse"
    payload = {
        "messages": [
            {
                "role": "user",
                "content": [{"text": "Hello"}]
            }
        ]
    }

    # Create a token provider that uses default credentials and region providers.
    # You can configure it to use other credential providers.
    # https://github.com/aws/aws-bedrock-token-generator-python/blob/main/README.md
    # It can be used for each API call as it is inexpensive.
    token = provide_token()

    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {token}"
    }

    response = requests.post(url, headers=headers, json=payload)
    print(response.json())

if __name__ == "__main__":
    get_new_token()
```

------
#### [ Javascript ]

```
import { getTokenProvider } from "@aws/bedrock-token-generator";

// Create a token provider that uses default credentials and region providers.
// You can configure it to use other credential providers.
// https://github.com/aws/aws-bedrock-token-generator-js/blob/main/README.md
// This can be created just once. Use await provideToken() to fetch the token
const provideToken = getTokenProvider();

async function example() {
    const url = "https://bedrock-runtime.us-east-1.amazonaws.com/model/us.anthropic.claude-3-5-haiku-20241022-v1:0/converse";
    const payload = {
        messages: [
            {
                role: "user",
                content: [{ text: "Hello" }]
            }
        ]
    };
    const headers = {
        "Content-Type": "application/json",
        // provideToken retrieves a valid token. It can be used for each API call as it is inexpensive.
        "Authorization": `Bearer ${await provideToken()}`
    };
    await fetch(url, {
        method: 'POST',
        headers: headers,
        body: JSON.stringify(payload)
    })
}
```

------
#### [ Java ]

```
package com.amazon.bedrocktoken;

import software.amazon.bedrock.token.BedrockTokenGenerator;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class GetNewToken {
    public static void main(String[] args) throws Exception {
        // Use default credentials and region from environment/profile chain
        // Create a token generator that uses default credentials and region providers.
        // You can configure it to use other credential providers.
        // https://github.com/aws/aws-bedrock-token-generator-java/blob/main/README.md
        BedrockTokenGenerator tokenGenerator = BedrockTokenGenerator.builder().build();

        // getToken() retrieves a valid token. It can be used for each API call as it is inexpensive.
        String token = tokenGenerator.getToken();

        String url = "https://bedrock-runtime.us-west-2.amazonaws.com/model/us.anthropic.claude-3-5-haiku-20241022-v1:0/converse";
        String payload = "{\n" +
                "    \"messages\": [\n" +
                "        {\n" +
                "            \"role\": \"user\",\n" +
                "            \"content\": [{ \"text\": \"Hello\" }]\n" +
                "        }\n" +
                "    ]\n" +
                "}";

        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create(url))
            .header("Content-Type", "application/json")
            .header("Authorization", "Bearer " + token)
            .POST(HttpRequest.BodyPublishers.ofString(payload))
            .build();

        HttpClient client = HttpClient.newHttpClient();
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

        System.out.println(response.body());
    }
}
```

------

# 使用 Amazon Bedrock API 密钥
<a name="api-keys-use"></a>

您可以通过以下方式使用 Amazon Bedrock API 密钥：
+ **设置为环境变量** – Amazon Bedrock 服务可识别环境变量 `AWS_BEARER_TOKEN_BEDROCK`。您可以通过以下选项来设置密钥：
  + 打开终端进行设置：
    + **MacOS/Linux**

      ```
      export AWS_BEARER_TOKEN_BEDROCK=${api-key}
      ```
    + **Windows**

      ```
      setx AWS_BEARER_TOKEN_BEDROCK "${api-key}"
      ```
  + 在发出 API 请求之前，将密钥设置为代码中的环境变量。例如，您可以在发出请求之前包含以下几行：
    + **Python**

      ```
      import os                      
      os.environ['AWS_BEARER_TOKEN_BEDROCK'] = "${api-key}"
      ```
+ **在请求中指定** – 您可以通过以下方式将 Amazon Bedrock API 密钥包含在授权标头中（将 *\$1AWS\$1BEARER\$1TOKEN\$1BEDROCK* 替换为实际值）：
  + **在直接 HTTP 请求中** – 包括以下内容作为授权标头：

    ```
    Authorization: Bearer $AWS_BEARER_TOKEN_BEDROCK
    ```
  + **作为支持的 SDK 中的参数** – 在设置客户端时在参数中指定值。例如，在使用 [OpenAI Python SDK](https://github.com/openai/openai-python?tab=readme-ov-file#usage) 设置客户端时，可以在 `api_key` 字段中指定密钥。

**注意**  
Amazon Bedrock API 密钥仅限于 [Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Amazon_Bedrock.html) 和 [Amazon Bedrock 运行时](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Amazon_Bedrock_Runtime.html)操作。您无法将这样的密钥与以下 API 操作结合使用：  
[InvokeModelWithBidirectionalStream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModelWithBidirectionalStream.html)。
[Amazon Bedrock 代理](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Agents_for_Amazon_Bedrock.html)或 [Amazon Bedrock 代理运行时](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Agents_for_Amazon_Bedrock.html) API 操作。
[Amazon Bedrock 数据自动化](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Data_Automation_for_Amazon_Bedrock.html)或 [Amazon Bedrock 数据自动化运行时](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Runtime_for_Amazon_Bedrock_Data_Automation) API 操作。

要查看使用 API 密钥发送 [Converse](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html) 请求以生成响应的示例，请选择与首选方法对应的选项卡，然后按照以下步骤操作：

------
#### [ Python ]

以下示例说明如何通过 适用于 Python (Boto3) 的 AWS SDK 发送 API 请求。如果您尚未将 API 密钥设置为 `AWS_BEARER_TOKEN_BEDROCK` 环境变量，请在以下代码中替换 *\$1\$1api-key\$1* 来指定密钥：

```
import os
import boto3
                        
# If you already set the API key as an environment variable, you can comment this line out                        
os.environ['AWS_BEARER_TOKEN_BEDROCK'] = "${api-key}"

# Create an Amazon Bedrock client
client = boto3.client(
    service_name="bedrock-runtime",
    region_name="us-east-1" # If you've configured a default region, you can omit this line
)

# Define the model and message
model_id = "us.anthropic.claude-3-5-haiku-20241022-v1:0"
messages = [{"role": "user", "content": [{"text": "Hello"}]}]

response = client.converse(
    modelId=model_id,
    messages=messages,
)
```

------
#### [ HTTP Client (requests package in Python) ]

**先决条件：**通过打开终端并运行以下命令来安装 `requests` 软件包：

```
python3 -m pip install requests
```

以下示例说明如何通过 HTTP 客户端直接发送 API 请求。在标头中指定 *\$1\$1api-key\$1*。

```
import requests

url = "https://bedrock-runtime.us-east-1.amazonaws.com/model/us.anthropic.claude-3-5-haiku-20241022-v1:0/converse"

payload = {
    "messages": [
        {
            "role": "user",
            "content": [{"text": "Hello"}]
        }
    ]
}

headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer ${api-key}"
}

response = requests.request("POST", url, json=payload, headers=headers)

print(response.text)
```

------
#### [ HTTP request using cURL ]

以下示例说明如何使用 cURL 直接发送 API 请求。如果您没有将 API 密钥设置为 AWS\$1BEARER\$1TOKEN\$1BEDROCK 环境变量，则必须将示例中的 `$AWS_BEARER_TOKEN_BEDROCK` 替换为密钥的字面值。

```
curl -X POST "https://bedrock-runtime.us-east-1.amazonaws.com/model/us.anthropic.claude-3-5-haiku-20241022-v1:0/converse" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AWS_BEARER_TOKEN_BEDROCK" \
  -d '{
    "messages": [
        {
            "role": "user",
            "content": [{"text": "Hello"}]
        }
    ]
  }'
```

------

# 修改长期和短期 Amazon Bedrock API 密钥的权限
<a name="api-keys-modify"></a>

当您生成长期 Amazon Bedrock API 密钥时，需要创建与该密钥关联的 IAM 用户。要更改与密钥关联的权限，请通过 IAM 服务修改 IAM 用户的权限。有关更多信息，请参阅《IAM 用户指南》中的[添加和删​​除 IAM 身份权限](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage-attach-detach.html)。

**注意**  
如果您在中生成了长期密钥 AWS 管理控制台，[AmazonBedrockLimitedAccess](security-iam-awsmanpol.md#security-iam-awsmanpol-AmazonBedrockLimitedAccess)则默认情况下会附加到该密钥。如果您计划修改权限，请先移除此策略，然后再设置自定义权限。

## 修改 API 密钥权限的示例
<a name="api-keys-modify-example"></a>

以下步骤说明如何用限制性更强的[AmazonBedrockLimitedAccess](security-iam-awsmanpol.md#security-iam-awsmanpol-AmazonBedrockLimitedAccess)替换：

1. 使用有权使用 Amazon Bedrock 控制台的 IAM 身份登录。 AWS 管理控制台 然后，在 [https://console.aws.amazon.com/](https://console.aws.amazon.com/bedrock)bedrock 上打开 Amazon Bedrock 控制台。

1. 从左侧导航窗格中选择 **API 密钥**。

1. 选择**长期 API 密钥**选项卡。

1. 选择您的 API 密钥，然后选择**在 IAM 控制台中管理**。

1. 选择 “**权限**” 选项卡，选择**AmazonBedrockLimitedAccess**策略，然后选择 “**删除**”。
**注意**  
此时，您已经从 APi 密钥中删除了所有权限，您将无法对其进行任何操作。

1. 在**权限策略**部分中，从**添加权限**下拉列表内选择**创建内联策略**。

1. 在**策略编辑器**中，选择 **JSON**。然后将下面的策略粘贴到编辑器中：

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": [
                   "bedrock:CallWithBearerToken"
               ],
               "Resource": "*"
           },
           {
               "Effect": "Allow",
               "Action": [
                   "bedrock:InvokeModel*"
               ],
               "Resource": [
                   "arn:aws:bedrock:us-west-2:111122223333:inference-profile/us.anthropic.claude-3-haiku-20240307-v1:0"
               ]
           },
           {
               "Effect": "Allow",
               "Action": [
                   "bedrock:InvokeModel*"
               ],
               "Resource": [
                   "arn:aws:bedrock:us-east-1::foundation-model/anthropic.claude-3-haiku-20240307-v1:0",
                   "arn:aws:bedrock:us-west-2::foundation-model/anthropic.claude-3-haiku-20240307-v1:0"
               ],
               "Condition": {
                   "StringLike": {
                       "bedrock:InferenceProfileArn": "arn:aws:bedrock:us-west-2:111122223333:inference-profile/us.anthropic.claude-3-haiku-20240307-v1:0"
                   }
               }
           }
       ]
   }
   ```

------

1. 选择**下一步**，提供**策略名称**，然后选择**创建策略**。

1. 使用此 API 密钥，用户现在只能使用美国西部（俄勒冈州）的美国 Anthropic Claude 3 Haiku 推理配置文件运行推理。

# 处理泄露的长期和短期 Amazon Bedrock API 密钥
<a name="api-keys-revoke"></a>

如果您的 API 密钥遭到泄露，则应撤销其使用权限。您可以使用多种方法来撤销 Amazon Bedrock API 密钥的权限：
+ 对于长期的 Amazon Bedrock API 密钥 [UpdateServiceSpecificCredential[ResetServiceSpecificCredential](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ResetServiceSpecificCredential.html.html)](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateServiceSpecificCredential.html.html)，您可以通过以下[DeleteServiceSpecificCredential](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteServiceSpecificCredential.html.html)方式使用、或撤消权限：
  + 将密钥状态设置为非活动。您后续可以重新激活密钥。
  + 重置密钥。此操作会为密钥生成一个新密码。
  + 永久删除密钥。
**注意**  
要通过 API 执行这些操作，您必须使用 AWS 凭证进行身份验证，而不是使用 Amazon Bedrock API 密钥进行身份验证。
+ 对于长期和短期 Amazon Bedrock API 密钥，您可以附加 IAM 策略来撤销权限。

**Topics**
+ [更改长期 Amazon Bedrock API 密钥的状态](#api-keys-change-status)
+ [重置长期 Amazon Bedrock API 密钥](#api-keys-reset)
+ [删除长期 Amazon Bedrock API 密钥](#api-keys-delete)
+ [附加 IAM 策略以移除 Amazon Bedrock API 密钥的使用权限](#api-keys-iam-policies)

## 更改长期 Amazon Bedrock API 密钥的状态
<a name="api-keys-change-status"></a>

如果您需要防止暂时使用密钥，请将其停用。准备好再次使用密钥后，可将其重新激活。

选择与您的首选方法对应的选项卡，然后按照以下步骤操作：

------
#### [ Console ]

**停用密钥**

1. 使用有权使用 Amazon Bedrock 控制台的 IAM 身份登录。 AWS 管理控制台 然后，在 [https://console.aws.amazon.com/](https://console.aws.amazon.com/bedrock)bedrock 上打开 Amazon Bedrock 控制台。

1. 在左侧导航窗格中，选择 **API 密钥**。

1. 在**长期 API 密钥**部分中，选择**状态**为**非活动**的密钥。

1. 选择**操作**。

1. 选择**停用**。

1. 要进行确认，请选择**停用 API 密钥**。密钥的**状态**变为**非活动**。

**重新激活密钥**

1. 使用有权使用 Amazon Bedrock 控制台的 IAM 身份登录。 AWS 管理控制台 然后，在 [https://console.aws.amazon.com/](https://console.aws.amazon.com/bedrock)bedrock 上打开 Amazon Bedrock 控制台。

1. 在左侧导航窗格中，选择 **API 密钥**。

1. 在**长期 API 密钥**部分中，选择**状态**为**非活动**的密钥。

1. 选择**操作**。

1. 选择**激活**。

1. 要进行确认，请选择**激活 API 密钥**。密钥的**状态**变为**活动**。

------
#### [ Python ]

要使用 API 停用密钥，请使用 [IAM 终端节点](https://docs.aws.amazon.com/general/latest/gr/iam-service.html)发送[UpdateServiceSpecificCredential](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateServiceSpecificCredential.html.html)请求并指定`Status`为`Inactive`。您可以使用以下代码段停用密钥，*\$1\$1ServiceSpecificCredentialId\$1*替换为创建密钥时返回的值。

```
import boto3
                        
iam_client = boto3.client("iam")
                      
iam_client.update_service_specific_credential(
    service_specific_credential_id=${ServiceSpecificCredentialId},
    status="Inactive"
)
```

要使用 API 重新激活密钥，请使用 [IAM 终端节点](https://docs.aws.amazon.com/general/latest/gr/iam-service.html)发送[UpdateServiceSpecificCredential](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateServiceSpecificCredential.html.html)请求并指定`Status`为`Active`。您可以使用以下代码片段重新激活密钥，*\$1\$1ServiceSpecificCredentialId\$1*替换为创建密钥时返回的值。

```
import boto3
                        
iam_client = boto3.client("iam")
                      
iam_client.update_service_specific_credential(
    service_specific_credential_id=${ServiceSpecificCredentialId},
    status="Active"
)
```

------

## 重置长期 Amazon Bedrock API 密钥
<a name="api-keys-reset"></a>

如果您的密钥值发生泄露或您不再拥有密钥，请将其重置。密钥必须尚未过期。如果密钥已经过期，请删除它，然后创建新密钥。

选择与您的首选方法对应的选项卡，然后按照以下步骤操作：

------
#### [ Console ]

**重置密钥**

1. 使用有权使用 Amazon Bedrock 控制台的 IAM 身份登录。 AWS 管理控制台 然后，在 [https://console.aws.amazon.com/](https://console.aws.amazon.com/bedrock)bedrock 上打开 Amazon Bedrock 控制台。

1. 在左侧导航窗格中，选择 **API 密钥**。

1. 在**长期 API 密钥**部分中，选择一个密钥。

1. 选择**操作**。

1. 选择**重置密钥**。

1. 选择**下一步**。

------
#### [ Python ]

要使用 API 重置密钥，请使用 [IAM 终端节点](https://docs.aws.amazon.com/general/latest/gr/iam-service.html)发送[ResetServiceSpecificCredential](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ResetServiceSpecificCredential.html.html)请求。您可以使用以下代码片段来重置密钥，*\$1\$1ServiceSpecificCredentialId\$1*替换为创建密钥时返回的值。

```
import boto3
            
iam_client = boto3.client("iam")
          
iam_client.reset_service_specific_credential(
    service_specific_credential_id=${ServiceSpecificCredentialId}
)
```

------

## 删除长期 Amazon Bedrock API 密钥
<a name="api-keys-delete"></a>

如果您不再需要密钥或者密钥已过期，请删除它。

选择与您的首选方法对应的选项卡，然后按照以下步骤操作：

------
#### [ Console ]

**删除密钥**

1. 使用有权使用 Amazon Bedrock 控制台的 IAM 身份登录。 AWS 管理控制台 然后，在 [https://console.aws.amazon.com/](https://console.aws.amazon.com/bedrock)bedrock 上打开 Amazon Bedrock 控制台。

1. 在左侧导航窗格中，选择 **API 密钥**。

1. 在**长期 API 密钥**部分中，选择一个密钥。

1. 选择**操作**。

1. 选择**删除**。

1. 确认删除操作。

**API 密钥与 IAM 用户关联**  
删除此 API 密钥不会删除以此密钥作为所有者创建的 IAM 用户。您可以在下一步中从 IAM 控制台中删除 IAM 用户。

------
#### [ Python ]

要使用 API 删除密钥，请使用 [IAM 终端节点](https://docs.aws.amazon.com/general/latest/gr/iam-service.html)发送[DeleteServiceSpecificCredential](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteServiceSpecificCredential.html.html)请求。您可以使用以下代码段删除密钥，*\$1\$1ServiceSpecificCredentialId\$1*替换为创建密钥时返回的值。

```
import boto3
            
iam_client = boto3.client("iam")
          
iam_client.delete_service_specific_credential(
    service_specific_credential_id=${ServiceSpecificCredentialId}
)
```

------

## 附加 IAM 策略以移除 Amazon Bedrock API 密钥的使用权限
<a name="api-keys-iam-policies"></a>

本部分提供了一些 IAM 策略，您可以用来限制对 Amazon Bedrock API 密钥的访问。

### 拒绝某个身份使用 Amazon Bedrock API 密钥进行调用的能力
<a name="api-keys-iam-policies-deny-call-with-bearer-token"></a>

允许身份使用 Amazon Bedrock API 密钥进行调用的操作是 `bedrock:CallWithBearerToken`。为了防止身份使用 Amazon Bedrock API 密钥进行调用，您可以根据密钥类型为身份附加一个 IAM 策略：
+ **长期密钥** – 将策略附加到与密钥关联的 IAM 用户。
+ **短期密钥** – 将策略附加到用于生成密钥的 IAM 角色。

您可以附加到 IAM 身份的 IAM 策略如下所示：

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": {
    "Effect": "Deny",
    "Action": "bedrock:CallWithBearerToken",
    "Resource": "*"
  }
}
```

------

### 使 IAM 角色会话失效
<a name="api-keys-iam-policies-invalidate-session"></a>

如果短期密钥发生泄露，您可以通过让用于生成该密钥的角色会话失效来阻止使用该密钥。要使角色会话失效，请将以下策略附加到生成密钥的 IAM 身份。*2014-05-07T23:47:00Z*替换为您希望会话失效的时间。

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": {
    "Effect": "Deny",
    "Action": "*",
    "Resource": "*",
    "Condition": {
      "DateLessThan": {"aws:TokenIssueTime": "2014-05-07T23:47:00Z"}
    }
  }
}
```

------

# 控制生成和使用 Amazon Bedrock API 密钥的权限
<a name="api-keys-permissions"></a>

Amazon Bedrock API 密钥的生成和使用由 Amazon Bedrock 和 IAM 服务中的操作和条件密钥控制。

**控制 Amazon Bedrock API 密钥的生成**  
ia [m: CreateServiceSpecificCredential 操作控制特定于服务的密钥（例如长期的 A](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsidentityandaccessmanagementiam.html#awsidentityandaccessmanagementiam-actions-as-permissions) mazon Bedrock API 密钥）的生成。您可以将此操作作为一种资源，将操作范围限定为 IAM 用户，以便限制可以为其生成密钥的用户。

您可以使用以下条件密钥对 `iam:CreateServiceSpecificCredential` 操作的权限施加条件：
+ [iam: ServiceSpecificCredentialAgeDays](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html#ck_ServiceSpecificCredentialAgeDays) — 允许您在条件中指定密钥的到期时间（以天为单位）。例如，您可以使用此条件密钥仅允许创建将在 90 天内过期的 API 密钥。
+ [iam: ServiceSpecificCredentialServiceName](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_iam-condition-keys.html#ck_ServiceSpecificCredentialAgeDays) — 允许您在条件中指定服务的名称。例如，您可以使用此条件密钥仅允许创建 Amazon Bedrock 的 API 密钥，不允许创建其他服务的 API 密钥。

**控制 Amazon Bedrock API 密钥的使用**  
[基石：CallWithBearerToken](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonbedrock.html#amazonbedrock-actions-as-permissions)操作控制短期或长期的 Amazon Bedrock API 密钥的使用。

您可以使用带有[字符串条件运算符](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String)的 `bedrock:bearerTokenType` 条件密钥，指定要申请 `bedrock:CallWithBearerToken` 权限的持有者令牌的类型。可以指定以下值之一：
+ `SHORT_TERM` – 在条件中指定短期 Amazon Bedrock API 密钥。
+ `LONG_TERM` – 在条件中指定长期 Amazon Bedrock API 密钥。

下表汇总了如何防止身份生成或使用 Amazon Bedrock API 密钥：


****  

| 用途 | 长期密钥 | 短期密钥 | 
| --- | --- | --- | 
| 防止生成密钥 | 将拒绝 iam:CreateServiceSpecificCredential 操作的策略附加到 IAM 身份。 | 不适用 | 
| 防止使用密钥 | 向与密钥关联的 IAM 用户附加拒绝 bedrock:CallWithBearerToken 操作的策略。 | 向您不希望其使用密钥的 IAM 身份附加拒绝 bedrock:CallWithBearerToken 操作的策略。 | 

**警告**  
由于短期 Amazon Bedrock API 密钥使用会话中的现有凭证，因此您可以通过拒绝对生成密钥的身份执行 `bedrock:CallWithBearerToken` 操作来防止使用密钥。但是，您无法防止生成短期密钥。

## 控制生成和使用 API 密钥的策略示例
<a name="api-keys-permissions-examples"></a>

关于控制生成和使用 API 密钥的 IAM 策略示例，请从以下主题中进行选择：

**Topics**
+ [防止身份生成长期密钥和使用 Amazon Bedrock API 密钥](#api-keys-permissions-examples-prevent-generation-and-use)
+ [防止身份使用短期 API 密钥](#api-keys-permissions-examples-prevent-use-short-term)
+ [防止身份使用长期 API 密钥](#api-keys-permissions-examples-prevent-use-long-term)
+ [明确禁止身份使用短期 API 密钥](#api-keys-permissions-examples-deny-use-short-term-explicitly)
+ [明确禁止身份使用长期 API 密钥](#api-keys-permissions-examples-deny-use-long-term-explicitly)
+ [仅当 Amazon Bedrock 密钥在 90 天内过期时，才允许创建这些密钥](#api-keys-permissions-examples-allow-bedrock-keys-expire-within-90-days)

### 防止身份生成长期密钥和使用 Amazon Bedrock API 密钥
<a name="api-keys-permissions-examples-prevent-generation-and-use"></a>

为防止 IAM 身份生成长期 Amazon Bedrock API 密钥和使用任何 Amazon Bedrock API 密钥，请将以下策略附加到身份：

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid":"DenyBedrockShortAndLongTermAPIKeys",
      "Effect": "Deny",
      "Action": [
        "iam:CreateServiceSpecificCredential",
        "bedrock:CallWithBearerToken"
      ],
      "Resource": [
        "*"
      ]
    }
  ]
}
```

------

**警告**  
您无法防止生成短期密钥。
此策略将禁止为所有支持创建特定 AWS 服务凭证的服务创建凭证。有关更多信息，请参阅 [IAM 用户的服务特定凭证](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_service-specific-creds.html)。

### 防止身份使用短期 API 密钥
<a name="api-keys-permissions-examples-prevent-use-short-term"></a>

要防止 IAM 身份使用短期 Amazon Bedrock API 密钥，请将以下策略附加到该身份：

### 防止身份使用长期 API 密钥
<a name="api-keys-permissions-examples-prevent-use-long-term"></a>

要防止 IAM 身份使用长期 Amazon Bedrock API 密钥，请将以下策略附加到该身份：

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Deny",
            "Action": "bedrock:CallWithBearerToken",
            "Resource": "*",
            "Condition": {
                "StringEquals": {
                    "bedrock:bearerTokenType": "LONG_TERM"
                }
            }
        }
    ]
}
```

------

### 明确禁止身份使用短期 API 密钥
<a name="api-keys-permissions-examples-deny-use-short-term-explicitly"></a>

要明确禁止 IAM 身份使用短期 Amazon Bedrock API 密钥，但允许使用其他 API 密钥，请将以下策略附加到该身份：

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Deny",
            "Action": "bedrock:CallWithBearerToken",
            "Resource": "*",
            "Condition": {
                "StringEquals": {
                    "bedrock:bearerTokenType": "SHORT_TERM"
                }
            }
        },
        {
            "Effect": "Allow",
            "Action": "bedrock:CallWithBearerToken",
            "Resource": "*"
        }
    ]
}
```

------

### 明确禁止身份使用长期 API 密钥
<a name="api-keys-permissions-examples-deny-use-long-term-explicitly"></a>

要明确禁止 IAM 身份使用长期 Amazon Bedrock API 密钥，但允许使用其他 API 密钥，请将以下策略附加到该身份：

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Deny",
            "Action": "bedrock:CallWithBearerToken",
            "Resource": "*",
            "Condition": {
                "StringEquals": {
                    "bedrock:bearerTokenType": "LONG_TERM"
                }
            }
        },
        {
            "Effect": "Allow",
            "Action": "bedrock:CallWithBearerToken",
            "Resource": "*"
        }
    ]
}
```

------

### 仅当 Amazon Bedrock 密钥在 90 天内过期时，才允许创建这些密钥
<a name="api-keys-permissions-examples-allow-bedrock-keys-expire-within-90-days"></a>

要允许 IAM 身份仅在长期 API 密钥用于 Amazon Bedrock 且过期时间不超过 90 天的情况下创建这样的密钥，请将以下策略附加到该身份：

------
#### [ JSON ]

****  

```
{
   "Version":"2012-10-17",		 	 	 
   "Statement": [
       {
           "Effect": "Allow",
           "Action": "iam:CreateServiceSpecificCredential",
           "Resource": "arn:aws:iam::123456789012:user/username",
           "Condition": {
               "StringEquals": {
                   "iam:ServiceSpecificCredentialServiceName": "bedrock.amazonaws.com"
               },
               "NumericLessThanEquals": {
                   "iam:ServiceSpecificCredentialAgeDays": "90"
               }
           }
       }
   ]
}
```

------

# 使用模型推理提交提示并生成响应
<a name="inference"></a>

推理是指根据提供给模型的输入生成输出的过程。

Amazon Bedrock 提供了一套基础模型，您可以使用这些模型生成以下模式的输出。要查看基础模型支持的模式，请参阅 [Amazon Bedrock 中支持的根基模型](models-supported.md)。


****  

| 输出模式 | 说明 | 使用案例示例 | 
| --- | --- | --- | 
| 文本 | 提供文本输入并生成各种类型的文本 | 聊天 question-and-answering、头脑风暴、摘要、代码生成、表格创建、数据格式化、重写 | 
| Image | 提供文本或输入图像并生成或修改图像 | 图像生成、图像编辑、图像变体 | 
| 视频 | 提供文字或参考图像并生成视频 | 生成视频，将图像转换为视频 | 
| 嵌入 | 提供文本、图像或同时提供文本和图像，然后生成表示输入的数值向量。可以将输出向量与其他嵌入向量进行比较，以确定语义相似度（对于文本）或视觉相似度（对于图像）。 | 文本和图像搜索、查询、分类、推荐、个性化、[知识库创建](knowledge-base.md) | 

**Topics**
+ [了解不同模型推理方法的使用案例](inference-methods.md)
+ [Amazon Bedrock 中推理的工作原理](inference-how.md)
+ [利用推理参数影响响应生成](inference-parameters.md)
+ [支持运行模型推理的区域和模型](inference-supported.md)
+ [运行模型推理的先决条件](inference-prereq.md)
+ [使用操场在控制台中生成响应](playgrounds.md)
+ [使用模型推理增强模型响应](inference-reasoning.md)
+ [针对延迟优化模型推理](latency-optimized-inference.md)
+ [使用生成响应 OpenAI APIs](bedrock-mantle.md)
+ [使用 API 提交提示并生成响应](inference-api.md)
+ [从模型中获取经过验证的 JSON 结果](structured-output.md)
+ [使用“计算机使用”工具完成 Amazon Bedrock 模型响应](computer-use.md)

# 了解不同模型推理方法的使用案例
<a name="inference-methods"></a>

您可以通过以下方法直接运行模型推理：


****  

| 方法 | 使用案例 | 
| --- | --- | 
| [Amazon Bedrock 控制台演练场](playgrounds.md) | 在用户友好的图形界面中运行推理。便于探索。 | 
| [Converse 或 [ConverseStream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ConverseStream.html)](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html) | 使用统一的 API 实现对话式应用程序，用于模型输入。 | 
| [InvokeModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html) 或 [InvokeModelWithResponseStream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModelWithResponseStream.html) | 提交单个提示并同步生成响应。对于实时生成响应或搜索查询很有用。 | 
| [StartAsyncInvoke](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_StartAsyncInvoke.html) | 提交单个提示并异步生成响应。对于大规模生成响应很有用。 | 
| [CreateModelInvocationJob](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_CreateModelInvocationJob.html) | 准备提示数据集并批量生成响应。 | 
| [响应 API](https://platform.openai.com/docs/api-reference/responses) | 对于需要使用内置工具（搜索、代码解释器）、多模态输入和有状态对话的现代代理应用程序，请使用 Responses API。 | 
| [聊天完成次数](https://platform.openai.com/docs/api-reference/chat) | 使用 Chat Completions API 执行轻量级、无状态、以文本为重点的任务，在这些任务中，您需要完全控制聊天记录管理和降低延迟。 | 

以下 Amazon Bedrock 功能还使用模型推理作为更大工作流中的一个步骤：
+ 在您提交[CreateEvaluationJob](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_CreateEvaluationJob.html)请求后，[模型评估](evaluation.md)使用模型调用过程来评估不同模型的性能。
+ 在使用 [https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_RetrieveAndGenerate.html](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_RetrieveAndGenerate.html) API 根据从知识库中检索到的结果生成响应时，[知识库](knowledge-base.md)会使用模型调用。
+ [代理](agents.md)会使用模型调用在 [https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_InvokeAgent.html) 请求期间的不同阶段生成响应。
+ [流](flows.md)包括使用模型调用的 Amazon Bedrock 资源，例如提示、知识库和代理。

在测试了具有不同提示和推理参数的不同基础模型之后，您可以将应用程序配置为按照所需的规格调 APIs 用这些模型。

# Amazon Bedrock 中推理的工作原理
<a name="inference-how"></a>

向模型提交输入时，模型可以预测接下来的词元序列，并将该序列作为输出返回。借助 Amazon Bedrock，您可以使用所选的基础模型运行推理。在运行推理时，您需要提供以下输入：
+ **提示** – 提供给模型的输入，以便模型生成响应。有关编写提示的信息，请参阅[提示工程概念](prompt-engineering-guidelines.md)。有关防范提示注入攻击的信息，请参阅 [提示注入安全](prompt-injection.md)。
+ **模型** – 您向模型发出请求，要求根据提示运行推理。您选择的模型还会指定吞吐量级别，该级别定义了您可以处理的输入和输出词元的数量和速率。您可以向以下类型的模型提出请求：
  + **基础模型** – 用于进行推理的基础模型。请求会发送到单个 AWS 区域。有关模型 ID，请参阅 [Amazon Bedrock 中支持的根基模型](models-supported.md)。有关 Amazon Bedrock 中可用的基础模型的更多信息，请参阅 [Amazon Bedrock 基础模型信息](foundation-models-reference.md)。
  + **推理配置文件** – 用于运行推理的基础模型。请求会发送到位于多个 AWS 区域中的模型。有关推理配置文件 ID 的信息，请参阅[支持推理配置文件的区域和模型](inference-profiles-support.md)。
**注意**  
模型因其在区域和 API 方法中的基础模型和推理配置文件的可用性而异。有关更多信息，请参阅 [Amazon Bedrock 中支持的根基模型](models-supported.md)和[基础模型参考](foundation-models-reference.md)中的各个模型页面。
  + **预配置吞吐量** – 您已为其购买专用吞吐量的基础模型。有关更多信息，请参阅 [利用 Amazon Bedrock 中的预调配吞吐量增加模型调用容量](prov-throughput.md)。
  + **自定义模型** – 一种基础模型，其权重已通过模型自定义进行了修改。有关更多信息，请参阅 [针对使用案例自定义模型以提高其性能](custom-models.md)。
+ **推理参数** – 一组可以调整以限制或影响模型响应的值。有关推理参数的信息，请参阅[利用推理参数影响响应生成](inference-parameters.md)和[基础模型的推理请求参数和响应字段](model-parameters.md)。

## 调用不同 AWS 区域的模型
<a name="inference-how-regions"></a>

在调用模型时，您可以选择要在其中调用该模型的 AWS 区域。您可以发出的请求的频率和大小的配额取决于所选区域。您可以在 [Amazon Bedrock 服务配额](https://docs.aws.amazon.com/general/latest/gr/bedrock.html#limits_bedrock)中搜索以下配额：
+ *\$1\$1Model\$1* 每分钟的按需模型推理请求数
+ *\$1\$1Model\$1* 的按需 InvokeModel 每分钟词元数

您也可以调用推理配置文件，而不用调用基础模型本身。推理配置文件定义了一个模型以及该配置文件可以将模型请求路由到的一个或多个区域。通过调用包含多个区域的推理配置文件，您可以提高吞吐量。有关更多信息，请参阅 [通过跨区域推理提高吞吐量](cross-region-inference.md)。要查看您可以使用推理配置文件发出请求的频率和大小的配额，请在 [Amazon Bedrock 服务配额](https://docs.aws.amazon.com/general/latest/gr/bedrock.html#limits_bedrock)中搜索以下配额：
+ *\$1\$1Model\$1* 的跨区域 InvokeModel 每分钟请求数
+ *\$1\$1Model\$1* 的跨区域 InvokeModel 每分钟词元数
+ *\$1\$1Model\$1* 每分钟的全局跨区域 InvokeModel 请求数
+ *\$1\$1Model\$1* 的全局跨区域 InvokeModel 每分钟词元数

向某个区域发出的请求可以在共享相同父区域的本地区域之外处理。例如，向美国东部（弗吉尼亚州北部）（us-east-1）发出的请求可以在与之关联的任何本地区域之外处理，例如美国亚特兰大（us-east-1-atl-2a）。

使用跨区域推理时，同样的原则也适用。例如，向美国 Anthropic Claude 3 Haiku 推理配置文件发出的请求，可以在父区域位于美国的任何本地区域 [例如美国西雅图（us-west-2-sea-1a）] 进行处理。向 AWS 添加新的本地区域时，也会将这些区域添加到相应的跨区域推理端点。

要查看本地端点及其关联的父区域的列表，请参阅 [AWS 本地区域站点](https://aws.amazon.com/about-aws/global-infrastructure/localzones/locations/)。

当您在 Amazon Bedrock 中调用跨区域推理配置文件时，您的请求来自源区域，该请求会自动路由到该配置文件中定义的目标区域之一，并对性能进行优化。全局跨区域推理配置文件的目标区域包括所有商业区域。

随着 AWS 添加更多可以处理请求的商业区域，特定模型的全球跨区域推理配置文件会随着时间推移而发生变化。但是，如果推理配置文件与地理位置（例如美国、欧盟或亚太地区）相关联，其目标区域列表将永远不会更改。AWS 可能会创建包含新区域的新推理配置文件。您可以通过将设置中的 ID 更改为新 ID 来更新系统，以使用这些推理配置文件。

**注意**  
跨区域推理配置文件中的目标区域可以包括**可选区域**，这些区域是您必须在 AWS 账户 或组织级别明确启用的区域。欲了解更多信息，请参阅[在您的账户中启用或禁用 AWS 区域](https://docs.aws.amazon.com/accounts/latest/reference/manage-acct-regions.html)。使用跨区域推理配置文件时，您的推理请求可以路由到配置文件中的任何目标区域，即使您没有在账户中选择加入此类区域也是如此。

服务控制策略（SCP）和 AWS Identity and Access Management（IAM）策略协同工作，控制可以在哪些区域运行跨区域推理。使用 SCP 时，您可以控制 Amazon Bedrock 可以使用哪些区域进行推理；使用 IAM 策略时，您可以定义哪些用户或角色有权运行推理。如果跨区域推理配置文件中的任何目标区域在您的 SCP 中被屏蔽，则即使其他区域仍然获得允许，请求也会失败。为了确保高效使用跨区域推理，您可以更新您的 SCP 和 IAM 策略，以便在所选推理配置文件中包含的所有目标区域，允许执行所有必需的 Amazon Bedrock 推理操作（例如 `bedrock:InvokeModel*` 或 `bedrock:CreateModelInvocationJob`）。要了解更多信息，请参阅 [https://aws.amazon.com/blogs/machine-learning/enable-amazon-bedrock-cross-region-inference-in-multi-account-environments/](https://aws.amazon.com/blogs/machine-learning/enable-amazon-bedrock-cross-region-inference-in-multi-account-environments/) 在多账户环境中启用 Amazon Bedrock 跨区域推理。

# 利用推理参数影响响应生成
<a name="inference-parameters"></a>

运行模型推理时，您可以调整推理参数以影响模型响应。推理参数可以更改模型在生成过程中考虑的可能输出池，也可以限制最终响应。

推理参数的默认值和范围取决于模型。要了解不同模型的推理参数，请参阅[基础模型的推理请求参数和响应字段](model-parameters.md)。

以下类别的参数是不同模型中的常见参数：

**Topics**
+ [随机性和多样性](#inference-randomness)
+ [长度](#inference-length)

## 随机性和多样性
<a name="inference-randomness"></a>

对于任何给定序列，模型都能确定序列中下一个词元选项的概率分布。为了生成输出中的每个词元，模型会从该分布中采样。随机性和多样性是指模型响应中的变体数量。您可以通过限制或调整分布来控制这些因素。基础模型通常支持使用以下参数控制响应的随机性和多样性。
+ **温度** – 影响预测输出的概率分布形状，还会影响模型选择概率较低输出的可能性。
  + 选择较低的值可影响模型选择概率较高的输出。
  + 选择较高的值可影响模型选择概率较低的输出。

  从技术角度来说，温度可调节下一个词元的概率质量函数。温度越低，函数曲线越陡，响应的确定性越高；温度越高，函数曲线越平，响应的随机性越高。
+ **排名前 K** – 模型为下一个词元考虑的最有可能的候选项数量。
  + 选择较低的值可减小池的大小，并将选项限制为可能性更高的输出。
  + 选择较高的值以增加池的大小，并允许模型考虑不太可能的输出。

  例如，如果为“排名前 K”选择的值是 50，则模型会从 50 个最有可能作为序列中下一个词元的词元中进行选择。
+ **排名前 P** – 模型为下一个词元考虑的最有可能的候选项所占百分比。
  + 选择较低的值可减小池的大小，并将选项限制为可能性更高的输出。
  + 选择较高的值以增加池的大小，并允许模型考虑不太可能的输出。

  从技术角度来说，模型会计算一组响应的累积概率分布，并且只考虑分布中的排名前 P%。

  例如，如果为“排名前 P”选择的值是 0.8，则模型会从可能作为序列中下一个词元的词元概率分布的前 80% 中进行选择。

下表总结了这些参数的作用。


****  

| 参数 | 较低值的作用 | 较高值的作用 | 
| --- | --- | --- | 
| 温度 | 增加概率较高词元的可能性 降低概率较低词元的可能性 | 增加概率较低词元的可能性降低概率较高词元的可能性 | 
| 排名前 K | 移除概率较低的词元 | 允许概率较低的词元 | 
| 排名前 P | 移除概率较低的词元 | 允许概率较低的词元 | 

为了方便理解这些参数，我们以 **I hear the hoof beats of "** 这个示例提示为例来解释一下。假设模型确定以下三个字词作为下一个词元的候选项。模型还为每个字词分配一个概率。

```
{
    "horses": 0.7,
    "zebras": 0.2,
    "unicorns": 0.1
}
```
+ 如果设置较高的**温度**，概率分布会变平，概率差异会变小，从而增加选择“unicorns”的概率，降低选择“horses”的概率。
+ 如果将**排名前 K** 设置为 2，模型只会考虑最有可能的前 2 个候选项，即：“horses”和“zebras”。
+ 如果将**排名前 P** 设置为 0.7，模型只会考虑“horses”，因为只有它是位于概率分布前 70% 的候选项。如果将**排名前 P** 设置为 0.9，则模型会考虑“horses”和“zebras”，因为它们位于概率分布的前 90%。

## 长度
<a name="inference-length"></a>

基础模型通常支持使用参数限制响应的长度。下面提供了这些参数的示例。
+ **响应长度** – 一个精确的值，用于指定要在生成的响应中返回的词元数量下限或上限。
+ **惩罚** – 用于指定对响应中的输出进行惩罚的程度。示例包括以下内容。
  + 响应的长度。
  + 响应中的重复词元。
  + 词元在响应中的出现频率。
  + 响应中的词元类型。
+ **停止序列** – 用于指定可阻止模型生成更多词元的字符序列。如果模型生成了您指定的停止序列，则将在该序列之后停止生成。

# 支持运行模型推理的区域和模型
<a name="inference-supported"></a>

Amazon Bedrock 支持的所有模型及所有区域中，均支持使用基础模型进行模型推理。要查看 Amazon Bedrock 支持的区域和模型，请参阅 [Amazon Bedrock 中支持的根基模型](models-supported.md)。

您还可以使用基础模型以外的 Amazon Bedrock 资源运行模型推理。请参阅以下页面，查看不同资源的区域和模型可用性：
+ [支持推理配置文件的区域和模型](inference-profiles-support.md)
+ [提示管理器支持的区域和模型](prompt-management-supported.md)
**注意**  
[InvokeModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html) 和 [InvokeModelWithResponseStream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModelWithResponseStream.html) 仅适用于以下提示：来自提示管理，且其配置指定了 Anthropic Claude 或 Meta Llama 模型。
+ [支持微调的型号和区域](custom-model-fine-tuning.md#custom-model-supported)
+ [使用自定义模型导入功能将自定义的开源模型导入 Amazon Bedrock 中](model-customization-import-model.md)
+ [Amazon Bedrock 护栏支持的区域和模型](guardrails-supported.md)

# 运行模型推理的先决条件
<a name="inference-prereq"></a>

对于要运行模型推理的角色，您需要允许该角色执行模型调用 API 操作。如果您的角色附加了[AmazonBedrockFullAccess](security-iam-awsmanpol.md#security-iam-awsmanpol-AmazonBedrockFullAccess)AWS托管策略，则可以跳过此部分。否则，请为该角色授予以下权限，使其能够对 Amazon Bedrock 中所有支持的资源使用、、[Converse](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html) 和[ConverseStream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ConverseStream.html)操作：[InvokeModel[InvokeModelWithResponseStream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModelWithResponseStream.html)](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html)

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "ModelInvocationPermissions",
            "Effect": "Allow",
            "Action": [
                "bedrock:InvokeModel",
                "bedrock:InvokeModelWithResponseStream",
                "bedrock:GetInferenceProfile",
                "bedrock:ListInferenceProfiles",
                "bedrock:RenderPrompt",
                "bedrock:GetCustomModel",
                "bedrock:ListCustomModels",
                "bedrock:GetImportedModel",
                "bedrock:ListImportedModels",
                "bedrock:GetProvisionedModelThroughput",
                "bedrock:ListProvisionedModelThroughputs",
                "bedrock:GetGuardrail",
                "bedrock:ListGuardrails",
                "bedrock:ApplyGuardrail"
            ],
            "Resource": "*"
        }
    ]
}
```

------

要进一步限制权限，您可以忽略操作，或者指定用于筛选权限的资源和条件键。有关操作、资源和条件键的更多信息，请参阅《服务授权参考》**中的以下主题：
+ [Amazon Bedrock 定义的操作](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonbedrock.html#amazonbedrock-actions-as-permissions) – 了解操作、您可以在 `Resource` 字段中限定范围的资源类型，以及 `Condition` 字段中可用于筛选权限的条件键。
+ [Amazon Bedrock 定义的资源类型](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonbedrock.html#amazonbedrock-resources-for-iam-policies) – 了解 Amazon Bedrock 中的资源类型。
+ [Amazon Bedrock 的条件键](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonbedrock.html#amazonbedrock-policy-keys) – 了解 Amazon Bedrock 中的条件键。

以下列表总结了根据您的使用案例，您是否需要该操作：
+ `bedrock:InvokeModel` – 执行模型调用所必需的操作。允许该角色调用[InvokeModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html)和[匡威](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html) API 操作。
+ `bedrock:InvokeModelWithResponseStream` – 执行模型调用并返回流式处理响应所必需的操作。允许该角色调用[InvokeModelWithResponseStream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModelWithResponseStream.html)和[匡威](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html)流 API 操作。
+ 以下操作允许角色使用基础模型以外的 Amazon Bedrock 资源运行推理：
  + `bedrock:GetInferenceProfile` – 使用[推理配置文件](inference-profiles.md)运行推理所必需的操作。
  + `bedrock:RenderPrompt` – 从[提示管理器](prompt-management.md)调用提示所必需的操作。
  + `bedrock:GetCustomModel` – 使用[自定义模型](custom-models.md)运行推理所必需的操作。
  + `bedrock:GetImportedModel` – 使用[导入的模型](model-customization-import-model.md)运行推理所必需的操作。
  + `bedrock:GetProvisionedModelThroughput` – 使用[预配置吞吐量](prov-throughput.md)运行推理所必需的操作。
+ 以下操作允许角色在 Amazon Bedrock 控制台中，查看基础模型以外的 Amazon Bedrock 资源并进行选择：
  + `bedrock:ListInferenceProfiles` – 在 Amazon Bedrock 控制台中选择[推理配置文件](custom-models.md)所必需的操作。
  + `bedrock:ListCustomModels` – 在 Amazon Bedrock 控制台中选择[自定义模型](custom-models.md)所必需的操作。
  + `bedrock:ListImportedModels` – 在 Amazon Bedrock 控制台中选择[导入的模型](model-customization-import-model.md)所必需的操作。
  + `bedrock:ListProvisionedModelThroughputs` – 在 Amazon Bedrock 控制台中选择[预配置吞吐量](prov-throughput.md)所必需的操作。
+ 以下操作允许角色在模型调用期间，访问并应用 [Amazon Bedrock 护栏](guardrails.md)中的护栏：
  + `bedrock:GetGuardrail` – 在模型调用期间使用护栏所必需的操作。
  + `bedrock:ApplyGuardrail` – 在模型调用期间应用护栏所必需的操作。
  + `bedrock:ListGuardrails` – 在 Amazon Bedrock 控制台中选择护栏所必需的操作。

# 使用操场在控制台中生成响应
<a name="playgrounds"></a>

Amazon Bedrock playgrounds 是一款工具 AWS 管理控制台 ，它提供了一个可视化界面，用于尝试在不同的模型上运行推理并使用不同的配置。您可以在将不同的模型和值集成到应用程序之前，使用操场测试这些模型和值。

在操场上运行提示等同于在 API 中发[InvokeModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html)出[InvokeModelWithResponseStream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModelWithResponseStream.html)、、[Converse](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html) 或[ConverseStream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ConverseStream.html)请求。

Amazon Bedrock 提供以下操场供您尝试：
+ **聊天/文本** – 提交文本提示并生成响应，或通过语音进行交互。您可以选择以下一种模式：
  + **聊天** - 提交文本提示或通过语音进行交互。对于文本提示，您还可以添加图像或文档来补充提示的内容。您提交的后续提示将包含您之前的提示作为上下文，因此提示和响应的顺序类似于对话。
  + **单个提示** – 提交单个文本提示并生成对它的响应。
**注意**  
Speech-to-speech 诸如 Amazon Nova Sonic 之类的型号仅在聊天模式下可用。模型不支持比较 speech-to-speech模式。
+ **图像** – 提交文本提示以生成图像。您也可以提交图像提示并指定是对其进行编辑还是生成其变体。
+ **多模式（预览）**-提交文本提示并生成多模式内容。它还支持聊天和单一提示模式。

以下流程介绍了如何在操场中提交提示、您可以调整的选项以及模型生成响应后您可以采取的操作。

**使用操场**

1. 如果您还没有使用过模型，请先针对要使用的模型请求模型访问权限。有关更多信息，请参阅 [访问 Amazon Bedrock 基础模型](model-access.md)。

1. 使用有权使用 Amazon Bedrock 控制台的 IAM 身份登录。 AWS 管理控制台 然后，在 [https://console.aws.amazon.com/](https://console.aws.amazon.com/bedrock)bedrock 上打开 Amazon Bedrock 控制台。

1. 在导航窗格的 “测试” 下，选择 Playgro **und**。

1. 如果您位于**聊天/文本**操场中，请选择**模式**。

1. 选择**选择模型**，然后选择要使用的提供商、模型和吞吐量。有关增加吞吐量的更多信息，请参阅[通过跨区域推理提高吞吐量](cross-region-inference.md)和[利用 Amazon Bedrock 中的预调配吞吐量增加模型调用容量](prov-throughput.md)。

1. 提交以下信息以生成响应：
   + 提示 – 一句或几句文字，用于为模型设定场景、问题或任务。有关创建提示的信息，请参阅[提示工程概念](prompt-engineering-guidelines.md)。

     某些模型（请参阅[支持的模型和模型功能](conversation-inference-supported-models-features.md)）允许您通过以下方式包含文件：
     + 选择附件图标，然后选择要上传的文件。
     + 选择附件图标，然后选择要上传的 Amazon S3 对象。
     + 将文件拖动到提示上。

     添加文件以补充提示内容。您可以在提示文本中引用该文件。例如，您可以编写 **Summarize this document for me** 或 **Tell me what's in this image**。您可以包含以下类型的文件：
     + **文档** – 添加文档以补充提示。有关支持的文件类型的列表，请参阅中的`format`字段[DocumentBlock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_DocumentBlock.html)。
**警告**  
文档名称容易受到提示注入的影响，因为模型可能会意外将其解读为说明。因此，我们建议您指定一个中性名称。
     + **图像** – 添加图像以补充提示内容（如果模型支持多模态图像和文本输入）。有关支持的文件类型的列表，请参阅中的`format`字段[ImageBlock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ImageBlock.html)。
     + **视频** – 添加视频以补充提示内容（如果模型支持多模态视频和文本输入）。有关支持的文件类型的列表，请参阅中的`format`字段[VideoBlock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_VideoBlock.html)。
**注意**  
内容限制因底层 API 操作和模型而异。有关更多信息，请参阅 [API 限制](inference-api-restrictions.md)。
   + 配置 – 您可以调整来修改模型响应的设置。配置包含以下内容：
     + 推理参数 – 影响或限制模型生成响应的方式的值。有关更多信息，请参阅 [利用推理参数影响响应生成](inference-parameters.md)。要查看特定模型的推理参数，请参阅[基础模型的推理请求参数和响应字段](model-parameters.md)。
     + 系统提示 – 向模型提供有关它应执行的任务或应采用的角色的说明或上下文的提示。有关更多信息以及支持系统提示的模型列表，请参阅[使用 Converse API 操作进行对话](conversation-inference.md)。
     + 防护机制 – 过滤掉提示和模型响应中的有害或不需要的内容。有关更多信息，请参阅 [使用 Amazon Bedrock 护栏检测和筛选掉有害内容](guardrails.md)。

1. （可选）如果模型支持流式传输，则默认行为是流式传输响应。您可以通过选择选项图标（![\[Vertical ellipsis icon representing a menu or more options.\]](http://docs.aws.amazon.com/zh_cn/bedrock/latest/userguide/images/icons/vertical-ellipsis.png)）和修改**流式传输首选项**选项来关闭流式传输。

1. （可选）某些文本生成模型支持比较评估，您可以通过执行以下操作来比较来自不同模型的响应：

   1. 启用**比较模式**。

   1. 选择**选择模型**，然后选择要使用的提供商、模型和吞吐量。

   1. 选择配置图标（![\[Three horizontal sliders with adjustable circular controls for settings or parameters.\]](http://docs.aws.amazon.com/zh_cn/bedrock/latest/userguide/images/icons/configurations.png)）以修改要使用的配置。

   1. 要添加更多模型进行比较，请选择右侧的 \$1 图标，选择一个模型，然后根据需要修改配置。

1. （可选）如果模型支持提示缓存，则可以打开**配置**面板，然后启用**提示缓存**，以允许对输入和模型响应进行缓存，从而降低成本并减少延迟。有关更多信息，请参阅 [用于加快模型推理速度的提示缓存](prompt-caching.md)。

1. 要运行提示，请选择**运行**。Amazon Bedrock 不会存储您提供的任何文本、图像或文档。数据仅用于生成响应。
**注意**  
如果响应违反了内容审核政策，则 Amazon Bedrock 不会显示该响应。如果您已开启流式传输，Amazon Bedrock 会在生成违反政策的内容时清除整个响应。要了解更多详细信息，请导航至 Amazon Bedrock 控制台，选择**提供商**，然后阅读**内容限制**部分下的文本。

1. 模型返回响应。如果您使用的是游乐场的聊天模式，则可以提交提示以回复回复并生成其他响应。

1. 生成响应后，您可以选择以下选项：
   + 要将响应导出为 JSON 文件，请选择选项图标（![\[Vertical ellipsis icon representing a menu or more options.\]](http://docs.aws.amazon.com/zh_cn/bedrock/latest/userguide/images/icons/vertical-ellipsis.png)），然后选择**导出为 JSON**。
   + 要查看您发出的 API 请求，请选择选项图标（![\[Vertical ellipsis icon representing a menu or more options.\]](http://docs.aws.amazon.com/zh_cn/bedrock/latest/userguide/images/icons/vertical-ellipsis.png)），然后选择**查看 API 请求**。
   + 在游乐场的聊天模式下，您可以在 “**模型指标” 部分中查看指标**。可供使用的模型指标如下：
     + **延迟** – Amazon Bedrock 接收到请求的时间点，与返回响应的时间点（针对非流式响应）或响应流完成的时间点（针对流式响应）之间的时长。
     + **输入词元计数** – 在推理期间以输入形式输入到模型中的词元数量。
     + **输出词元计数** – 响应提示时生成的词元数量。更长、更像对话的响应需要更多词元。
     + **成本** – 处理输入和生成输出词元的成本。

     要设置您希望响应匹配的指标标准，请选择**定义指标标准**并定义模型要匹配的条件。应用标准后，**模型指标**部分将显示响应满足的标准数量和标准。

     如果不满足标准，您可以选择其他模型，重写提示，或者修改配置并重新运行提示。

# 使用模型推理增强模型响应
<a name="inference-reasoning"></a>

某些基础模型能够执行模型推理，因而可以执行较大型的复杂任务，并将其分解为较小型、较简单的步骤。这个过程通常被称为思维链（CoT）推理。思维链推理通常可以让模型有机会在做出反应之前进行思考，从而提高模型的准确性。模型推理对于多步分析、数学问题和复杂推理任务等任务最为有用。

例如，在处理数学单词问题时，模型可以首先识别相关变量，然后根据给定的信息构造方程，最后求解这些方程以得出解。这种策略不仅可以最大限度地减少错误，还可以使推理过程更加透明和易于理解，从而提高基础模型的输出质量。

并非所有任务都需要模型推理，而且会带来额外的开销，包括延迟和输出词元的增加。不需要额外解释的简单任务不适合 CoT 推理。

请注意，并非所有模型都允许您配置为模型推理分配的输出词元数量。

模型推理适用于以下模型。


| 基础模型 | 模型 ID | 词元数量 | 推理配置 | 
| --- | --- | --- | --- | 
| Anthropic Claude Opus 4 | anthropic.claude-opus-4-20250514-v1:0 | 此模型将有 32768 个词元，包括输出词元和推理词元。 | 可使用可配置的词元预算，为此模型启用或禁用推理。默认情况下，禁用推理。 | 
| Anthropic Claude Sonnet 4 | anthropic.claude-sonnet-4-20250514-v1:0 | 此模型将有 65536 个词元，包括输出词元和推理词元。 | 可使用可配置的词元预算，为此模型启用或禁用推理。默认情况下，禁用推理。 | 
| Anthropic Claude 3.7 Sonnet | anthropic.claude-3-7-sonnet-20250219-v1:0 | 此模型将有 65536 个词元，包括输出词元和推理词元。 | 可使用可配置的词元预算，为此模型启用或禁用推理。默认情况下，禁用推理。 | 
| DeepSeek DeepSeek-R1 | deepseek.r1-v1:0 | 此模型将有 8192 个词元，包括输出词元和推理词元。无法配置思考词元的数量，并且输出词元的最大数量不得超过 8192。 | 此模型始终启用推理。此模型不支持开启和关闭推理功能的切换。 | 

# 针对延迟优化模型推理
<a name="latency-optimized-inference"></a>

**注意**  
延迟优化推理功能处于预览版 Amazon Bedrock ，可能会发生变化。

中针对基础模型进行了延迟优化的推理， Amazon Bedrock 可缩短响应时间，提高了 AI 应用程序的响应速度。优化版本的 [https://docs.aws.amazon.com/nova/latest/userguide/what-is-nova.html](https://docs.aws.amazon.com/nova/latest/userguide/what-is-nova.html)、[Anthropic 的 Claude 3.5 Haiku 模型](https://aws.amazon.com/bedrock/claude/)和 [Meta 的 Llama 3.1 405B 与 70B 模型](https://aws.amazon.com/bedrock/llama/)能显著减少延迟，并且不影响准确度。

无需进行额外的设置或模型微调即可访问延迟优化功能，进而能够立即增强现有应用程序并缩短响应时间。您可以在调用 Amazon Bedrock 运行时 API 时将“延迟”参数设置为“已优化”。如果您选择“标准”作为调用选项，则您的请求将由标准推理功能处理。默认情况下，所有请求都通过“标准”选项进行路由。

```
"performanceConfig" : {
    "latency" : "standard | optimized" 
}
```

一旦您达到模型延迟优化功能的使用配额，我们将尝试以标准延迟处理请求。在此类情况下，将按标准延迟费率收取请求费用。已处理请求的延迟配置在 API 响应和 AWS CloudTrail 日志中可见。您还可以在 Amazon CloudWatch 日志中的 “model-id\$1延迟优化” 下查看延迟优化请求的指标。

延迟优化推理功能可通过[跨区域推理](https://docs.aws.amazon.com/bedrock/latest/userguide/cross-region-inference.html)用于在美国东部（俄亥俄州）和美国西部（俄勒冈州）区域推出的 Meta 的 Llama 3.1 70B 和 405B，以及 Anthropic 的 Claude 3.5 Haiku。

延迟优化推理功能可通过[跨区域推理](https://docs.aws.amazon.com/bedrock/latest/userguide/cross-region-inference.html)用于在美国东部（弗吉尼亚州北部）美国东部（俄亥俄州）和美国西部（俄勒冈州）区域推出的 Amazon Nova Pro。

有关定价的更多信息，请访问[定价页面](https://aws.amazon.com/bedrock/pricing/)。

**注意**  
 Llama 3.1 405B 的延迟优化推理功能目前支持输入和输出令牌总数高达 11K 的请求。对于词元数量较多的请求，我们将回退到标准模式。

下表显示了支持延迟优化的推理配置文件：


| Provider | 模型 | 模型 ID | 跨区域推理配置文件支持 | 
| --- | --- | --- | --- | 
| Amazon | Nova Pro | 亚马逊。 nova-pro-v1:0 |  us-east-1 us-east-2  | 
| Anthropic | Claude 3.5 Haiku | anthropic.claude-3-5-haiku-20241022-v1:0 |  us-east-2 us-west-2  | 
| Meta | Llama 3.1 405B Instruct | meta.llama3-1-405 1:0 b-instruct-v |  us-east-2  | 
| Meta | Llama 3.1 70B Instruct | meta.llama3-1-70 1:0 b-instruct-v |  us-east-2 us-west-2  | 

有关推理配置文件的更多信息，请参阅 [支持推理配置文件的区域和模型](inference-profiles-support.md)。

# 使用生成响应 OpenAI APIs
<a name="bedrock-mantle"></a>

Amazon Bedrock 为模型推断提供了OpenAI兼容的 API 端点，该端点由 Mantle 提供支持，Mantle 是一款用于大规模机器学习模型服务的分布式推理引擎。这些终端节点允许您在 Amazon Bedrock 模型中使用熟悉的工具，使您只需更新基本 URL OpenAI SDKs 和 API 密钥即可迁移现有应用程序，只需更新您的基本 URL 和 API 密钥即可。

主要优势包括：
+ **异步推理** — 通过响应 API 支持长时间运行的推理工作负载
+ **状态对话管理** — 自动重建上下文，无需在每个请求中手动传递对话历史记录
+ **简化工具使用** — 简化了代理工作流程的集成
+ **灵活的响应模式** — Support 支持直播和非直播响应
+ **易于迁移** — 与现有 OpenAI SDK 代码库兼容

## 支持的区域和终端节点
<a name="bedrock-mantle-supported"></a>

Amazon Bedrock 在以下 AWS 地区上市：


| 区域名称 | 区域 | 端点 | 
| --- | --- | --- | 
| 美国东部（俄亥俄州） | us-east-2 | bedrock-mantle.us-east-2.api.aws | 
| 美国东部（弗吉尼亚州北部） | us-east-1 | bedrock-mantle.us-east-1.api.aws | 
| 美国西部（俄勒冈州） | us-west-2 | bedrock-mantle.us-west-2.api.aws | 
| 亚太地区（雅加达） | ap-southeast-3 | bedrock-mantle.ap-southeast-3.api.aws | 
| 亚太地区（孟买） | ap-south-1 | bedrock-mantle.ap-south-1.api.aws | 
| 亚太地区（东京） | ap-northeast-1 | bedrock-mantle.ap-northeast-1.api.aws | 
| 欧洲地区（法兰克福） | eu-central-1 | bedrock-mantle.eu-central-1.api.aws | 
| 欧洲地区（爱尔兰） | eu-west-1 | bedrock-mantle.eu-west-1.api.aws | 
| 欧洲（伦敦） | eu-west-2 | bedrock-mantle.eu-west-2.api.aws | 
| 欧洲地区（米兰） | eu-south-1 | bedrock-mantle.eu-south-1.api.aws | 
| 欧洲地区（斯德哥尔摩） | eu-north-1 | bedrock-mantle.eu-north-1.api.aws | 
| 南美洲（圣保罗） | sa-east-1 | bedrock-mantle.sa-east-1.api.aws | 

## 先决条件
<a name="bedrock-mantle-prereq"></a>

使用前 OpenAI APIs，请确保您具备以下条件：
+ **身份验证**-您可以使用以下方式进行身份验证：
  + 亚马逊 Bedrock API 密钥（OpenAI软件开发工具包所必需的）
  + AWS 凭证（支持 HTTP 请求）
+ **OpenAI软件开发工具包**（可选）— 如果使用基于 SDK 的OpenAI请求，请安装 Python 开发工具包。
+ **环境变量**-设置以下环境变量：
  + `OPENAI_API_KEY`— 设置为你的 Amazon Bedrock API 密钥
  + `OPENAI_BASE_URL`— 设置为您所在地区的 Amazon Bedrock 终端节点（例如，` https://bedrock-mantle.us-east-1.api.aws/v1`）

## 模型 API
<a name="bedrock-mantle-models"></a>

模型 API 允许您在由 Mantle 提供支持的 Amazon Bedrock 中发现可用模型。使用此 API 检索可用于响应 API 和聊天完成 API 的模型列表。有关完整的 API 详细信息，请参阅[OpenAI模型文档](https://platform.openai.com/docs/api-reference/models)。

### 列出可用型号
<a name="bedrock-mantle-models-list"></a>

要列出可用型号，请选择首选方法的选项卡，然后按照以下步骤操作：

------
#### [ OpenAI SDK (Python) ]

```
# List all available models using the OpenAI SDK
# Requires OPENAI_API_KEY and OPENAI_BASE_URL environment variables

from openai import OpenAI

client = OpenAI()

models = client.models.list()

for model in models.data:
    print(model.id)
```

------
#### [ HTTP request ]

向以下地址发出 GET 请求`/v1/models`：

```
# List all available models
# Requires OPENAI_API_KEY and OPENAI_BASE_URL environment variables

curl -X GET $OPENAI_BASE_URL/models \
   -H "Authorization: Bearer $OPENAI_API_KEY"
```

------

## 响应 API
<a name="bedrock-mantle-responses"></a>

Responses API 提供有状态的对话管理，支持直播、后台处理和多回合互动。有关完整的 API 详细信息，请参阅[OpenAI响应文档](https://platform.openai.com/docs/api-reference/responses)。

### 基本请求
<a name="bedrock-mantle-responses-create"></a>

要创建响应，请选择首选方法的选项卡，然后按照以下步骤操作：

------
#### [ OpenAI SDK (Python) ]

```
# Create a basic response using the OpenAI SDK
# Requires OPENAI_API_KEY and OPENAI_BASE_URL environment variables

from openai import OpenAI

client = OpenAI()

response = client.responses.create(
    model="openai.gpt-oss-120b",
    input=[
        {"role": "user", "content": "Hello! How can you help me today?"}
    ]
)

print(response)
```

------
#### [ HTTP request ]

向以下地址发出 POST 请求`/v1/responses`：

```
# Create a basic response
# Requires OPENAI_API_KEY and OPENAI_BASE_URL environment variables

curl -X POST $OPENAI_BASE_URL/responses \
   -H "Content-Type: application/json" \
   -H "Authorization: Bearer $OPENAI_API_KEY" \
   -d '{
    "model": "openai.gpt-oss-120b",
    "input": [
        {"role": "user", "content": "Hello! How can you help me today?"}
    ]
}'
```

------

### 直播回复
<a name="bedrock-mantle-responses-streaming"></a>

要以增量方式接收响应事件，请选择首选方法的选项卡，然后按照以下步骤操作：

------
#### [ OpenAI SDK (Python) ]

```
# Stream response events incrementally using the OpenAI SDK
# Requires OPENAI_API_KEY and OPENAI_BASE_URL environment variables

from openai import OpenAI

client = OpenAI()

stream = client.responses.create(
    model="openai.gpt-oss-120b",
    input=[{"role": "user", "content": "Tell me a story"}],
    stream=True
)

for event in stream:
    print(event)
```

------
#### [ HTTP request ]

向发出 POST 请求`/v1/responses`，`stream`设置为`true`：

```
# Stream response events incrementally
# Requires OPENAI_API_KEY and OPENAI_BASE_URL environment variables

curl -X POST $OPENAI_BASE_URL/responses \
   -H "Content-Type: application/json" \
   -H "Authorization: Bearer $OPENAI_API_KEY" \
   -d '{
    "model": "openai.gpt-oss-120b",
    "input": [
        {"role": "user", "content": "Tell me a story"}
    ],
    "stream": true
}'
```

------

## 聊天完成 API
<a name="bedrock-mantle-chat-completions"></a>

聊天完成 API 会生成对话回复。有关 API 的完整详细信息，请参阅[OpenAI聊天完成文档。](https://platform.openai.com/docs/api-reference/chat/create)

### 创建聊天补全
<a name="bedrock-mantle-chat-completions-create"></a>

要创建聊天完成功能，请选择首选方法的选项卡，然后按照以下步骤操作：

------
#### [ OpenAI SDK (Python) ]

使用环境变量配置OpenAI客户端：

```
# Create a chat completion using the OpenAI SDK
# Requires OPENAI_API_KEY and OPENAI_BASE_URL environment variables

from openai import OpenAI

client = OpenAI()

completion = client.chat.completions.create(
    model="openai.gpt-oss-120b",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Hello!"}
    ]
)

print(completion.choices[0].message)
```

------
#### [ HTTP request ]

向以下地址发出 POST 请求`/v1/chat/completions`：

```
# Create a chat completion
# Requires OPENAI_API_KEY and OPENAI_BASE_URL environment variables

curl -X POST $OPENAI_BASE_URL/chat/completions \
   -H "Content-Type: application/json" \
   -H "Authorization: Bearer $OPENAI_API_KEY" \
   -d '{
    "model": "openai.gpt-oss-120b",
    "messages": [
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Hello!"}
    ]
}'
```

------

### 启用直播
<a name="bedrock-mantle-chat-completions-streaming"></a>

要逐步接收回复，请选择首选方法的选项卡，然后按照以下步骤操作：

------
#### [ OpenAI SDK (Python) ]

```
# Stream chat completion responses incrementally using the OpenAI SDK
# Requires OPENAI_API_KEY and OPENAI_BASE_URL environment variables

from openai import OpenAI

client = OpenAI()

stream = client.chat.completions.create(
    model="openai.gpt-oss-120b",
    messages=[{"role": "user", "content": "Tell me a story"}],
    stream=True
)

for chunk in stream:
    if chunk.choices[0].delta.content is not None:
        print(chunk.choices[0].delta.content, end="")
```

------
#### [ HTTP request ]

向发出 POST 请求`/v1/chat/completions`，` stream`设置为`true`：

```
# Stream chat completion responses incrementally
# Requires OPENAI_API_KEY and OPENAI_BASE_URL environment variables

curl -X POST $OPENAI_BASE_URL/chat/completions \
   -H "Content-Type: application/json" \
   -H "Authorization: Bearer $OPENAI_API_KEY" \
   -d '{
    "model": "openai.gpt-oss-120b",
    "messages": [
        {"role": "user", "content": "Tell me a story"}
    ],
    "stream": true
}'
```

------

# 使用 API 提交提示并生成响应
<a name="inference-api"></a>

Amazon Bedrock 提供以下 API 操作来执行模型推理：
+ [InvokeModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html)— 提交提示并生成响应。请求正文特定于模型。要生成直播响应，请使用[InvokeModelWithResponseStream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModelWithResponseStream.html)。
+ [Converse](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html) – 提交提示并使用所有模型统一的结构生成响应。可以在 `additionalModelRequestFields` 字段中指定特定于模型的请求字段。您还可以包含系统提示和之前的对话以了解上下文。要生成直播响应，请使用[ConverseStream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ConverseStream.html)。
+ [StartAsyncInvoke](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_StartAsyncInvoke.html)— 提交提示并异步生成响应，以后可以检索。用于生成视频。
+ [InvokeModelWithBidirectionalStream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModelWithBidirectionalStream.html) – 
+ OpenAI 聊天补全 API – 使用 Amazon Bedrock 支持的模型和 [OpenAI 聊天补全 API](https://platform.openai.com/docs/api-reference/chat/create) 生成响应。

**注意**  
限制适用于以下操作：`InvokeModel`、`InvokeModelWithResponseStream``Converse`、和`ConverseStream`。有关详细信息，请参阅 [API 限制](inference-api-restrictions.md)。

要进行模型推理，您需要确定以下参数：
+ 模型 ID：在 `modelId` 字段中用于推理的模型或推理配置文件的 ID 或 Amazon 资源名称（ARN）。下表描述了如何 IDs 查找不同类型的资源：  
****    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/bedrock/latest/userguide/inference-api.html)
+ 请求正文：包含模型的推理参数和其他配置。每个基础模型都有自己的推理参数。自定义模型或预调配模型的推理参数取决于创建模型时所依据的基础模型。有关更多信息，请参阅 [基础模型的推理请求参数和响应字段](model-parameters.md)。

选择一个主题来学习如何使用模型调用 APIs。

**Topics**
+ [使用以下命令提交单个提示 InvokeModel](inference-invoke.md)
+ [使用 OpenAI 聊天补全 API 调用模型](inference-chat-completions.md)
+ [使用 Converse API 操作进行对话](conversation-inference.md)
+ [API 限制](inference-api-restrictions.md)

# 使用以下命令提交单个提示 InvokeModel
<a name="inference-invoke"></a>

您可以使用[InvokeModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html)和 [InvokeModelWithResponseStream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModelWithResponseStream.html)API 操作并指定模型，在单个提示上运行推理。Amazon Bedrock 各模型的不同之处，在于是接受文本、图像还是视频输入，以及能否生成文本、图像或嵌入的输出。某些模型可以在流中返回响应。要查看模型对输入、输出和流式传输的支持，请执行以下操作之一：
+ 对于 [Amazon Bedrock 中支持的根基模型](models-supported.md)，查看模型的**输入模式**、**输出模式**或**支持的流式传输**列中的值。
+ 发送带有模型 ID 的[GetFoundationModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_GetFoundationModel.html)请求并检查`inputModalities``outputModalities`、和`responseStreamingSupported`字段中的值。

使用 [Amazon Bedrock 运行时终端节点发送[InvokeModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html)或[InvokeModelWithResponseStream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModelWithResponseStream.html)请求，根据提示运行](https://docs.aws.amazon.com/general/latest/gr/bedrock.html#br-rt)模型推理。

**注意**  
限制适用于以下操作：`InvokeModel`、`InvokeModelWithResponseStream``Converse`、和`ConverseStream`。有关详细信息，请参阅 [API 限制](inference-api-restrictions.md)。

以下字段是必填字段：


****  

| 字段 | 使用案例 | 
| --- | --- | 
| modelId | 指定要使用的模型、推理配置文件或提示管理器中的提示。要了解如何查找此值，请参阅[使用 API 提交提示并生成响应](inference-api.md)。 | 
| body | 为模型指定推理参数。要查看不同模型的推理参数，请参阅[基础模型的推理请求参数和响应字段](model-parameters.md)。如果在 modelId 字段中指定提示管理器中的提示，可省略此字段（如果包含，则将忽略此字段）。 | 

以下字段是可选字段：


****  

| 字段 | 使用案例 | 
| --- | --- | 
| accept | 为请求正文指定媒体类型。有关更多信息，请参阅 [Swagger 网站](https://swagger.io/specification/)上的媒体类型。 | 
| contentType | 为响应正文指定媒体类型。有关更多信息，请参阅 [Swagger 网站](https://swagger.io/specification/)上的媒体类型。 | 
| performanceConfigLatency | 指定是否对模型的延迟进行优化。有关更多信息，请参阅[针对延迟优化模型推理](latency-optimized-inference.md)。 | 
| guardrailIdentifier | 指定要应用于提示和响应的护栏。有关更多信息，请参阅[测试护栏](guardrails-test.md)。 | 
| guardrailVersion | 指定要应用于提示和响应的护栏。有关更多信息，请参阅[测试护栏](guardrails-test.md)。 | 
| trace | 指定是否返回您指定的护栏的轨迹。有关更多信息，请参阅 [测试护栏](guardrails-test.md)。 | 
| 服务等级 | 为请求指定服务级别。有关更多信息，请参阅 [用于优化性能和成本的服务分层](service-tiers-inference.md)。 | 

## 调用模型代码示例
<a name="inference-example-invoke"></a>

本主题提供了一些在 [InvokeModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html)API 中使用单个提示运行推理的基本示例。有关使用不同模型的更多示例，请访问以下资源：
+ 在[使用 Amazon Bedrock Runtime 的代码示例 AWS SDKs](service_code_examples_bedrock-runtime.md)主题下选择一个示例。
+ 有关所需模型的推理参数参考，请访问[基础模型的推理请求参数和响应字段](model-parameters.md)。

以下示例假设您已设置编程访问权限，以便在运行这些示例时自动对 AWS CLI 和适用于 Python 的 SDK (Boto3) 进行默认 AWS 区域 身份验证。有关设置编程访问权限的信息，请参阅[开始使用 API](getting-started-api.md)。

**注意**  
在尝试示例之前，请先回顾以下几点：  
您应当在美国东部（弗吉尼亚州北部）（us-east-1）测试这些示例，该区域支持示例中用到的所有模型。
`body` 参数可能很大，因此，对于某些 CLI 示例，系统会要求您创建一个 JSON 文件，并将该文件提供到 `--body` 参数中，而不是在命令行中指定。
对于图像和视频示例，系统会要求您使用自己的图像和视频。这些示例假设您的图像文件已命名*image.png*，您的视频文件已命名*video.mp4*。
您可能需要将图像或视频转换为 base64 编码的字符串，或将其上传到 Amazon S3 位置。在这些示例中，您需要将占位符替换为实际的 base64 编码字符串或 S3 位置。

下面展开一个部分来尝试一些基本的代码示例。

### 使用文本提示生成文本
<a name="w2aac13c32c33c17c19c13b1"></a>

以下示例使用 Amazon Titan Text Premier模型，生成对文本提示的文字响应。选择与您的首选方法对应的选项卡，然后按照以下步骤操作：

------
#### [ CLI ]

在终端中运行以下命令，并在名为的文件中找到生成的响应*invoke-model-output.txt*。

```
aws bedrock-runtime invoke-model \
    --model-id amazon.titan-text-premier-v1:0 \
    --body '{
        "inputText": "Describe the purpose of a 'hello world' program in one line.",
        "textGenerationConfig": {
            "maxTokenCount": 512,
            "temperature": 0.5
        }
    }' \
    --cli-binary-format raw-in-base64-out \
    invoke-model-output.txt
```

------
#### [ Python ]

运行以下 Python 代码示例，以生成文字响应：

```
# Use the native inference API to send a text message to Amazon Titan Text.

import boto3
import json

from botocore.exceptions import ClientError

# Create a Bedrock Runtime client in the AWS Region of your choice.
client = boto3.client("bedrock-runtime", region_name="us-east-1")

# Set the model ID, e.g., Titan Text Premier.
model_id = "amazon.titan-text-premier-v1:0"

# Define the prompt for the model.
prompt = "Describe the purpose of a 'hello world' program in one line."

# Format the request payload using the model's native structure.
native_request = {
    "inputText": prompt,
    "textGenerationConfig": {
        "maxTokenCount": 512,
        "temperature": 0.5,
    },
}

# Convert the native request to JSON.
request = json.dumps(native_request)

try:
    # Invoke the model with the request.
    response = client.invoke_model(modelId=model_id, body=request)

except (ClientError, Exception) as e:
    print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}")
    exit(1)

# Decode the response body.
model_response = json.loads(response["body"].read())

# Extract and print the response text.
response_text = model_response["results"][0]["outputText"]
print(response_text)
```

------

### 使用服务层生成带有文本提示的文本
<a name="w2aac13c32c33c17c19c13b3"></a>

以下示例使用带有服务层的 OpenAI GPT 模型生成对文本提示的文本响应，以确定请求的优先级。选择与您的首选方法对应的选项卡，然后按照以下步骤操作：

------
#### [ CLI ]

在终端中运行以下命令并在响应中验证服务层。

```
aws bedrock-runtime invoke-model \
    --model-id openai.gpt-oss-120b-1:0 \
    --body '{
        "messages": [
            {
                "role": "user",
                "content": "Describe the purpose of a '\''hello world'\'' program in one line."
            }
        ],
        "max_tokens": 512,
        "temperature": 0.7
    }' \
    --content-type application/json \
    --accept application/json \
    --service-tier priority \
    --cli-binary-format raw-in-base64-out
```

------
#### [ Python ]

运行以下 Python 代码示例，生成包含服务层的文本响应：

```
import boto3
import json

# Create a Bedrock Runtime client
bedrock_runtime = boto3.client(
    service_name="bedrock-runtime",
    region_name="us-east-1"
)

# Define the model ID and request body
model_id = "openai.gpt-oss-120b-1:0"
body = json.dumps({
    "messages": [
        {
            "role": "user",
            "content": "Describe the purpose of a 'hello world' program in one line."
        }
    ],
    "max_tokens": 512,
    "temperature": 0.7
})

# Make the request with service tier
response = bedrock_runtime.invoke_model(
    modelId=model_id,
    body=body,
    contentType="application/json",
    accept="application/json",
    serviceTier="priority"
)

# Parse and print the response
response_body = json.loads(response["body"])
print(response_body)
```

------

### 使用文本提示生成图像
<a name="w2aac13c32c33c17c19c13b5"></a>

以下代码示例通过 Stable Diffusion XL 1.0 模型，使用文本提示生成图像。选择与您的首选方法对应的选项卡，然后按照以下步骤操作：

------
#### [ CLI ]

在终端中运行以下命令，并在名为的文件中找到生成的响应*invoke-model-output.txt*。在响应的 `base64` 字段中，可以找到表示图像的字节。

```
aws bedrock-runtime invoke-model \
    --model-id stability.stable-diffusion-xl-v1 \
    --body '{
        "text_prompts": [{"text": "A stylized picture of a cute old steampunk robot."}],
        "style_preset": "photographic",
        "seed": 0,
        "cfg_scale": 10,
        "steps": 30
    }' \
    --cli-binary-format raw-in-base64-out \
    invoke-model-output.txt
```

------
#### [ Python ]

运行以下 Python 代码示例生成图像并在名为的文件夹中找到生成的*stability\$11.png*图像文件*output*。

```
# Use the native inference API to create an image with Amazon Titan Image Generator

import base64
import boto3
import json
import os
import random

# Create a Bedrock Runtime client in the AWS Region of your choice.
client = boto3.client("bedrock-runtime", region_name="us-east-1")

# Set the model ID, e.g., Titan Image Generator G1.
model_id = "amazon.titan-image-generator-v2:0"

# Define the image generation prompt for the model.
prompt = "A stylized picture of a cute old steampunk robot."

# Generate a random seed.
seed = random.randint(0, 2147483647)

# Format the request payload using the model's native structure.
native_request = {
    "taskType": "TEXT_IMAGE",
    "textToImageParams": {"text": prompt},
    "imageGenerationConfig": {
        "numberOfImages": 1,
        "quality": "standard",
        "cfgScale": 8.0,
        "height": 512,
        "width": 512,
        "seed": seed,
    },
}

# Convert the native request to JSON.
request = json.dumps(native_request)

# Invoke the model with the request.
response = client.invoke_model(modelId=model_id, body=request)

# Decode the response body.
model_response = json.loads(response["body"].read())

# Extract the image data.
base64_image_data = model_response["images"][0]

# Save the generated image to a local folder.
i, output_dir = 1, "output"
if not os.path.exists(output_dir):
    os.makedirs(output_dir)
while os.path.exists(os.path.join(output_dir, f"titan_{i}.png")):
    i += 1

image_data = base64.b64decode(base64_image_data)

image_path = os.path.join(output_dir, f"titan_{i}.png")
with open(image_path, "wb") as file:
    file.write(image_data)

print(f"The generated image has been saved to {image_path}")
```

------

### 根据文本生成嵌入内容
<a name="w2aac13c32c33c17c19c13b9"></a>

以下示例使用 Amazon Titan Text Embeddings V2 模型，为文本输入生成二进制嵌入。选择与您的首选方法对应的选项卡，然后按照以下步骤操作：

------
#### [ CLI ]

在终端中运行以下命令，并在名为的文件中找到生成的响应*invoke-model-output.txt*。生成的嵌入位于 `binary` 字段中。

```
aws bedrock-runtime invoke-model \
    --model-id amazon.titan-embed-text-v2:0 \
    --body '{
        "inputText": "What are the different services that you offer?",
        "embeddingTypes": ["binary"]
    }' \
    --cli-binary-format raw-in-base64-out \
    invoke-model-output.txt
```

------
#### [ Python ]

运行以下 Python 代码示例，为提供的文本生成嵌入：

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Shows how to generate an embedding with the Amazon Titan Text Embeddings V2 Model
"""

import json
import logging
import boto3


from botocore.exceptions import ClientError


logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)


def generate_embedding(model_id, body):
    """
    Generate an embedding with the vector representation of a text input using Amazon Titan Text Embeddings G1 on demand.
    Args:
        model_id (str): The model ID to use.
        body (str) : The request body to use.
    Returns:
        response (JSON): The embedding created by the model and the number of input tokens.
    """

    logger.info("Generating an embedding with Amazon Titan Text Embeddings V2 model %s", model_id)

    bedrock = boto3.client(service_name='bedrock-runtime')

    accept = "application/json"
    content_type = "application/json"

    response = bedrock.invoke_model(
        body=body, modelId=model_id, accept=accept, contentType=content_type
    )

    response_body = json.loads(response.get('body').read())

    return response_body


def main():
    """
    Entrypoint for Amazon Titan Embeddings V2 - Text example.
    """

    logging.basicConfig(level=logging.INFO,
                        format="%(levelname)s: %(message)s")

    model_id = "amazon.titan-embed-text-v2:0"
    input_text = "What are the different services that you offer?"


    # Create request body.
    body = json.dumps({
        "inputText": input_text,
        "embeddingTypes": ["binary"]
    })


    try:

        response = generate_embedding(model_id, body)

        print(f"Generated an embedding: {response['embeddingsByType']['binary']}") # returns binary embedding
        print(f"Input text: {input_text}")
        print(f"Input Token count:  {response['inputTextTokenCount']}")

    except ClientError as err:
        message = err.response["Error"]["Message"]
        logger.error("A client error occurred: %s", message)
        print("A client error occured: " +
              format(message))

    else:
        print(f"Finished generating an embedding with Amazon Titan Text Embeddings V2 model {model_id}.")


if __name__ == "__main__":
    main()
```

------

### 根据图像生成嵌入内容
<a name="w2aac13c32c33c17c19c13c11"></a>

以下示例使用 Amazon Titan Multimodal Embeddings G1 模型，为图像输入生成嵌入。选择与您的首选方法对应的选项卡，然后按照以下步骤操作：

------
#### [ CLI ]

打开终端，执行以下操作：

1. 将当前文件夹*image.png*中标题的图像转换为 base64 编码的字符串，然后*image.txt*通过运行以下命令将其写入标题为的文件中：

   ```
   base64 -i image.png -o image.txt
   ```

1. 创建一个名为的 JSON 文件*image-input-embeddings-output.json*并粘贴*\$1\$1image-base64\$1*以下 JSON，替换为该*image.txt*文件的内容（确保字符串末尾没有新行）：

   ```
   {
       "inputImage": "${image-base64}",
       "embeddingConfig": {
           "outputEmbeddingLength": 256
       }
   }
   ```

1. 运行以下命令，将*image-input-embeddings-output.json*文件指定为正文。

   ```
   aws bedrock-runtime invoke-model \
       --model-id amazon.titan-embed-image-v1 \
       --body file://image-input-embeddings-output.json \
       --cli-binary-format raw-in-base64-out \
       invoke-model-output.txt
   ```

1. 在*invoke-model-output.txt*文件中找到生成的嵌入内容。

------
#### [ Python ]

在以下 Python 脚本中，*/path/to/image*替换为实际图像的路径。然后，运行脚本生成嵌入：

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Shows how to generate embeddings from an image with the Amazon Titan Multimodal Embeddings G1 model (on demand).
"""

import base64
import json
import logging
import boto3

from botocore.exceptions import ClientError

class EmbedError(Exception):
    "Custom exception for errors returned by Amazon Titan Multimodal Embeddings G1"

    def __init__(self, message):
        self.message = message

logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)


def generate_embeddings(model_id, body):
    """
    Generate a vector of embeddings for an image input using Amazon Titan Multimodal Embeddings G1 on demand.
    Args:
        model_id (str): The model ID to use.
        body (str) : The request body to use.
    Returns:
        response (JSON): The embeddings that the model generated, token information, and the
        reason the model stopped generating embeddings.
    """

    logger.info("Generating embeddings with Amazon Titan Multimodal Embeddings G1 model %s", model_id)

    bedrock = boto3.client(service_name='bedrock-runtime')

    accept = "application/json"
    content_type = "application/json"

    response = bedrock.invoke_model(
        body=body, modelId=model_id, accept=accept, contentType=content_type
    )

    response_body = json.loads(response.get('body').read())

    finish_reason = response_body.get("message")

    if finish_reason is not None:
        raise EmbedError(f"Embeddings generation error: {finish_reason}")

    return response_body


def main():
    """
    Entrypoint for Amazon Titan Multimodal Embeddings G1 example.
    """

    logging.basicConfig(level=logging.INFO,
                        format="%(levelname)s: %(message)s")

    # Read image from file and encode it as base64 string.
    with open("/path/to/image", "rb") as image_file:
        input_image = base64.b64encode(image_file.read()).decode('utf8')

    model_id = 'amazon.titan-embed-image-v1'
    output_embedding_length = 256

    # Create request body.
    body = json.dumps({
        "inputImage": input_image,
        "embeddingConfig": {
            "outputEmbeddingLength": output_embedding_length
        }
    })


    try:

        response = generate_embeddings(model_id, body)

        print(f"Generated image embeddings of length {output_embedding_length}: {response['embedding']}")

    except ClientError as err:
        message = err.response["Error"]["Message"]
        logger.error("A client error occurred: %s", message)
        print("A client error occured: " +
              format(message))
        
    except EmbedError as err:
        logger.error(err.message)
        print(err.message)

    else:
        print(f"Finished generating image embeddings with Amazon Titan Multimodal Embeddings G1 model {model_id}.")


if __name__ == "__main__":
    main()
```

------

### 对附带文本提示的图像生成文字响应
<a name="w2aac13c32c33c17c19c13c13"></a>

选择与您的首选方法对应的选项卡，然后按照以下步骤操作：

------
#### [ CLI ]

以下示例针对图像以及询问图像内容的文本提示，使用 Anthropic Claude 3 Haiku 模型生成响应。打开终端，执行以下操作：

1. 将当前文件夹*image.png*中标题的图像转换为 base64 编码的字符串，然后*image.txt*通过运行以下命令将其写入标题为的文件中：

   ```
   base64 -i image.png -o image.txt
   ```

1. 创建一个名为的 JSON 文件*image-text-input.json*并粘贴*\$1\$1image-base64\$1*以下 JSON，替换为该*image.txt*文件的内容（确保字符串末尾没有新行）：

   ```
   {
       "anthropic_version": "bedrock-2023-05-31",
       "max_tokens": 1000,
       "messages": [
           {               
               "role": "user",
               "content": [
                   {
                       "type": "image",
                       "source": {
                           "type": "base64",
                           "media_type": "image/png", 
                           "data": "${image-base64}"
                       }
                   },
                   {
                       "type": "text",
                       "text": "What's in this image?"
                   }
               ]
           }
       ]
   }
   ```

1. 运行以下命令，根据图像和随附的文本提示将文本输出生成到名为的文件中*invoke-model-output.txt*：

   ```
   aws bedrock-runtime invoke-model \
       --model-id anthropic.claude-3-haiku-20240307-v1:0 \
       --body file://image-text-input.json \
       --cli-binary-format raw-in-base64-out \
       invoke-model-output.txt
   ```

1. 在当前文件夹*invoke-model-output.txt*的文件中找到输出。

------
#### [ Python ]

在以下 python 脚本中，在运行脚本之前替换*/path/to/image.png*为图像的实际路径：

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Shows how to run a multimodal prompt with Anthropic Claude (on demand) and InvokeModel.
"""

import json
import logging
import base64
import boto3

from botocore.exceptions import ClientError


logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)


def run_multi_modal_prompt(bedrock_runtime, model_id, messages, max_tokens):
    """
    Invokes a model with a multimodal prompt.
    Args:
        bedrock_runtime: The Amazon Bedrock boto3 client.
        model_id (str): The model ID to use.
        messages (JSON) : The messages to send to the model.
        max_tokens (int) : The maximum  number of tokens to generate.
    Returns:
        None.
    """



    body = json.dumps(
        {
            "anthropic_version": "bedrock-2023-05-31",
            "max_tokens": max_tokens,
            "messages": messages
        }
    )

    response = bedrock_runtime.invoke_model(
        body=body, modelId=model_id)
    response_body = json.loads(response.get('body').read())

    return response_body


def main():
    """
    Entrypoint for Anthropic Claude multimodal prompt example.
    """

    try:

        bedrock_runtime = boto3.client(service_name='bedrock-runtime')

        model_id = 'anthropic.claude-3-sonnet-20240229-v1:0'
        max_tokens = 1000
        input_text = "What's in this image?"
        input_image = "/path/to/image" # Replace with actual path to image file
 
        # Read reference image from file and encode as base64 strings.
        image_ext = input_image.split(".")[-1]
        with open(input_image, "rb") as image_file:
            content_image = base64.b64encode(image_file.read()).decode('utf8')

        message = {
            "role": "user",
            "content": [
                {
                    "type": "image", 
                    "source": {
                        "type": "base64",
                        "media_type": f"image/{image_ext}", 
                        "data": content_image
                    }
                },
                {
                    "type": "text", 
                    "text": input_text
                }
            ]
        }

    
        messages = [message]

        response = run_multi_modal_prompt(
            bedrock_runtime, model_id, messages, max_tokens)
        print(json.dumps(response, indent=4))

    except ClientError as err:
        message = err.response["Error"]["Message"]
        logger.error("A client error occurred: %s", message)
        print("A client error occurred: " +
              format(message))


if __name__ == "__main__":
    main()
```

------

### 对上传至 Amazon S3 并附带文本提示的视频生成文字响应
<a name="w2aac13c32c33c17c19c13c15"></a>

以下示例展示了针对上传至 S3 存储桶并附带文本提示的视频，如何使用 Amazon Nova Lite 模型生成响应。

**先决条件：**按照亚马逊简单存储服务用户指南中的上传[对象中的步骤将标题*video.mp4*上传到](https://docs.aws.amazon.com/AmazonS3/latest/userguide/upload-objects.html#upload-objects-procedure)您账户中的 Amazon S3 存储桶的视频。记下视频的 S3 URI。

选择与您的首选方法对应的选项卡，然后按照以下步骤操作：

------
#### [ CLI ]

打开终端并运行以下命令，*s3://amzn-s3-demo-bucket/video.mp4*替换为视频的实际 S3 位置：

```
aws bedrock-runtime invoke-model \
    --model-id amazon.nova-lite-v1:0 \
    --body '{
        "messages": [          
            {               
                "role": "user",
                "content": [      
                    {                       
                        "video": {     
                            "format": "mp4",   
                            "source": {
                                "s3Location": {
                                    "uri": "s3://amzn-s3-demo-bucket/video.mp4"
                                }
                            }
                        }                                    
                    },
                    {
                        "text": "What happens in this video?"
                    }
                ]
            }                              
        ]                  
    }' \
    --cli-binary-format raw-in-base64-out \
    invoke-model-output.txt
```

在当前文件夹*invoke-model-output.txt*的文件中找到输出。

------
#### [ Python ]

在以下 Python 脚本中，*s3://amzn-s3-demo-bucket/video.mp4*替换为视频的实际 S3 位置。然后，运行此脚本：

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Shows how to run a multimodal prompt with Nova Lite (on demand) and InvokeModel.
"""

import json
import logging
import base64
import boto3

from botocore.exceptions import ClientError


logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)


def run_multi_modal_prompt(bedrock_runtime, model_id, messages, max_tokens):
    """
    Invokes a model with a multimodal prompt.
    Args:
        bedrock_runtime: The Amazon Bedrock boto3 client.
        model_id (str): The model ID to use.
        messages (JSON) : The messages to send to the model.
        max_tokens (int) : The maximum  number of tokens to generate.
    Returns:
        None.
    """

    body = json.dumps(
        {
            "messages": messages,
            "inferenceConfig": {
                "maxTokens": max_tokens
            }
        }
    )

    response = bedrock_runtime.invoke_model(
        body=body, modelId=model_id)
    response_body = json.loads(response.get('body').read())

    return response_body


def main():
    """
    Entrypoint for Nova Lite video prompt example.
    """

    try:

        bedrock_runtime = boto3.client(service_name='bedrock-runtime')

        model_id = "amazon.nova-lite-v1:0"
        max_tokens = 1000
        input_video_s3_uri = "s3://amzn-s3-demo-bucket/video.mp4" # Replace with real S3 URI
        video_ext = input_video_s3_uri.split(".")[-1]
        input_text = "What happens in this video?"

        message = {
            "role": "user",
            "content": [
                {
                    "video": {
                        "format": video_ext,
                        "source": {
                            "s3Location": {
                                "uri": input_video_s3_uri
                            }
                        }
                    }
                },
                {
                    "text": input_text
                }
            ]
        }

    
        messages = [message]

        response = run_multi_modal_prompt(
            bedrock_runtime, model_id, messages, max_tokens)
        print(json.dumps(response, indent=4))

    except ClientError as err:
        message = err.response["Error"]["Message"]
        logger.error("A client error occurred: %s", message)
        print("A client error occured: " +
              format(message))


if __name__ == "__main__":
    main()
```

------

### 对转换为 base64 编码字符串并附带文本提示的视频生成文字响应
<a name="w2aac13c32c33c17c19c13c17"></a>

以下示例展示了针对转换为 base64 编码字符串并附带文本提示的视频，如何使用 Amazon Nova Lite 模型生成响应。选择与您的首选方法对应的选项卡，然后按照以下步骤操作：

------
#### [ CLI ]

执行以下操作：

1. 通过运行以下命令，将当前文件夹*video.mp4*中标题的视频转换为 base64：

   ```
   base64 -i video.mp4 -o video.txt
   ```

1. 创建一个名为的 JSON 文件*video-text-input.json*并粘贴*\$1\$1video-base64\$1*以下 JSON，替换为该`video.txt`文件的内容（确保最后没有新行）：

   ```
   {
       "messages": [          
           {               
               "role": "user",
               "content": [      
                   {                       
                       "video": {     
                           "format": "mp4",   
                           "source": {
                               "bytes": ${video-base64}
                           }
                       }                                    
                   },
                   {
                       "text": "What happens in this video?"
                   }
               ]
           }                              
       ]                  
   }
   ```

1. 运行以下命令，根据视频和随附的文本提示生成文本输出到名为的文件*invoke-model-output.txt*：

   ```
   aws bedrock-runtime invoke-model \
       --model-id amazon.nova-lite-v1:0 \
       --body file://video-text-input.json \
       --cli-binary-format raw-in-base64-out \
       invoke-model-output.txt
   ```

1. 在当前文件夹*invoke-model-output.txt*的文件中找到输出。

------
#### [ Python ]

在以下 Python 脚本中，*/path/to/video.mp4*替换为视频的实际路径。然后，运行此脚本：

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Shows how to run a multimodal prompt with Nova Lite (on demand) and InvokeModel.
"""

import json
import logging
import base64
import boto3

from botocore.exceptions import ClientError


logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)


def run_multi_modal_prompt(bedrock_runtime, model_id, messages, max_tokens):
    """
    Invokes a model with a multimodal prompt.
    Args:
        bedrock_runtime: The Amazon Bedrock boto3 client.
        model_id (str): The model ID to use.
        messages (JSON) : The messages to send to the model.
        max_tokens (int) : The maximum  number of tokens to generate.
    Returns:
        None.
    """

    body = json.dumps(
        {
            "messages": messages,
            "inferenceConfig": {
                "maxTokens": max_tokens
            }
        }
    )

    response = bedrock_runtime.invoke_model(
        body=body, modelId=model_id)
    response_body = json.loads(response.get('body').read())

    return response_body


def main():
    """
    Entrypoint for Nova Lite video prompt example.
    """

    try:

        bedrock_runtime = boto3.client(service_name='bedrock-runtime')

        model_id = "amazon.nova-lite-v1:0"
        max_tokens = 1000
        input_video = "/path/to/video.mp4" # Replace with real path to video
        video_ext = input_video.split(".")[-1]
        input_text = "What happens in this video?"

        # Read reference video from file and encode as base64 string.
        with open(input_video, "rb") as video_file:
            content_video = base64.b64encode(video_file.read()).decode('utf8')\

        message = {
            "role": "user",
            "content": [
                {
                    "video": {
                        "format": video_ext,
                        "source": {
                            "bytes": content_video
                        }
                    }
                },
                {
                    "text": input_text
                }
            ]
        }

    
        messages = [message]

        response = run_multi_modal_prompt(
            bedrock_runtime, model_id, messages, max_tokens)
        print(json.dumps(response, indent=4))

    except ClientError as err:
        message = err.response["Error"]["Message"]
        logger.error("A client error occurred: %s", message)
        print("A client error occured: " +
              format(message))


if __name__ == "__main__":
    main()
```

------

## 通过流式传输调用模型代码示例
<a name="inference-examples-stream"></a>

**注意**  
 AWS CLI 不支持流式传输。

以下示例说明如何使用 [InvokeModelWithResponseStream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModelWithResponseStream.html)API 使用提示符在 Python 中生成流式文本*write an essay for living on mars in 1000 words*。

```
import boto3
import json

brt = boto3.client(service_name='bedrock-runtime')

body = json.dumps({
    'prompt': '\n\nHuman: write an essay for living on mars in 1000 words\n\nAssistant:',
    'max_tokens_to_sample': 4000
})
                   
response = brt.invoke_model_with_response_stream(
    modelId='anthropic.claude-v2', 
    body=body
)
    
stream = response.get('body')
if stream:
    for event in stream:
        chunk = event.get('chunk')
        if chunk:
            print(json.loads(chunk.get('bytes').decode()))
```

# 使用 OpenAI 聊天补全 API 调用模型
<a name="inference-chat-completions"></a>

您可以将 [OpenAI 创建聊天补全 API](https://platform.openai.com/docs/api-reference/chat/create) 与 Amazon Bedrock 模型配合使用，以便运行模型推理。

您可通过以下方式调用创建聊天补全 API：
+ 通过 Amazon Bedrock 运行时端点发出 HTTP 请求。
+ 将 OpenAI SDK 请求和 Amazon Bedrock 运行时端点配合使用。

选择一个主题以了解更多信息：

**Topics**
+ [OpenAI 聊天补全 API 支持的模型和区域](#inference-chat-completions-supported)
+ [使用聊天补全 API 的先决条件](#inference-chat-completions-prereq)
+ [创建聊天补全](#inference-chat-completions-create)
+ [在聊天补全中添加护栏](#inference-chat-completions-guardrails)

## OpenAI 聊天补全 API 支持的模型和区域
<a name="inference-chat-completions-supported"></a>

您可以在 Amazon Bedrock 和支持这些OpenAI模型的 AWS 地区支持的所有型号上使用创建聊天完成 API。有关支持的模型和区域的更多信息，请参阅[Amazon Bedrock 中支持的根基模型](models-supported.md)。

## 使用聊天补全 API 的先决条件
<a name="inference-chat-completions-prereq"></a>

要查看使用聊天补全 API 的先决条件，请选择与您的首选方法对应的选项卡，然后按照以下步骤操作：

------
#### [ OpenAI SDK ]
+ **身份验证** – OpenAI SDK 仅支持使用 Amazon Bedrock API 密钥进行身份验证。生成 Amazon Bedrock API 密钥以对您的请求进行身份验证。要了解有关 Amazon Bedrock API 密钥以及如何生成密钥的信息，请参阅 “构建” 一章中的 API 密钥部分。
+ **终端节点** — 找到与要在 [Amazon Bedrock 运行时终端节点和配额中使用的 AWS 区域相对应的终端节点](https://docs.aws.amazon.com/general/latest/gr/bedrock.html#br-rt)。如果您使用 S AWS DK，则在设置客户端时可能只需要指定区域代码，而无需指定整个终端节点。
+ **安装 OpenAI SDK** – 有关更多信息，请参阅 OpenAI 文档中的[库](https://platform.openai.com/docs/libraries)。

------
#### [ HTTP request ]
+ **身份验证** — 您可以使用您的 AWS 证书或 Amazon Bedrock API 密钥进行身份验证。

  设置您的 AWS 凭证或生成 Amazon Bedrock API 密钥来验证您的请求。
  + 要了解如何设置 AWS 证书，请参阅使用[AWS 安全凭证进行编程访问](https://docs.aws.amazon.com/IAM/latest/UserGuide/security-creds-programmatic-access.html)。
  + 要了解有关 Amazon Bedrock API 密钥以及如何生成密钥的信息，请参阅 “构建” 一章中的 API 密钥部分。
+ **终端节点** — 找到与要在 [Amazon Bedrock 运行时终端节点和配额中使用的 AWS 区域相对应的终端节点](https://docs.aws.amazon.com/general/latest/gr/bedrock.html#br-rt)。如果您使用 S AWS DK，则在设置客户端时可能只需要指定区域代码，而无需指定整个终端节点。

------

## 创建聊天补全
<a name="inference-chat-completions-create"></a>

有关创建聊天补全 API 的详细信息，请参阅 OpenAI 文档中的以下资源：
+ [请求正文参数](https://platform.openai.com/docs/api-reference/chat/create)
+ [响应正文参数](https://platform.openai.com/docs/api-reference/chat/object)

**注意**  
Amazon Bedrock 目前不支持其他 OpenAI 聊天补全 API 操作。

要了解如何使用 OpenAI 创建聊天补全 API，请选择与您的首选方法对应的选项卡，然后按照以下步骤操作：

------
#### [ OpenAI SDK (Python) ]

要使用 OpenAI SDK 创建聊天补全，请执行以下操作：

1. 导入 OpenAI SDK，并使用以下字段设置客户端：
   + `base_url` – 将 Amazon Bedrock 运行时端点添加为 `/openai/v1` 的前缀，格式如下：

     ```
     https://${bedrock-runtime-endpoint}/openai/v1
     ```
   + `api_key` – 指定 Amazon Bedrock API 密钥。
   + `default_headers` – 如果需要包含任何标头，可将其作为键值对包含在此对象中。也可在进行特定 API 调用时在 `extra_headers` 中指定标头。

1. 在客户端上使用 `chat.completions.create()` 方法，并在请求正文中至少指定 `model` 和 `messages`。

以下示例会在 `us-west-2` 中调用创建聊天补全 API。*\$1AWS\$1BEARER\$1TOKEN\$1BEDROCK*替换为实际的 API 密钥。

```
from openai import OpenAI

client = OpenAI(
    base_url="https://bedrock-runtime.us-west-2.amazonaws.com/openai/v1", 
    api_key="$AWS_BEARER_TOKEN_BEDROCK" # Replace with actual API key
)

completion = client.chat.completions.create(
    model="openai.gpt-oss-20b-1:0",
    messages=[
        {
            "role": "developer",
            "content": "You are a helpful assistant."
        },
        {
            "role": "user",
            "content": "Hello!"
        }
    ]
)

print(completion.choices[0].message)
```

------
#### [ HTTP request ]

要使用直接 HTTP 请求创建聊天补全，请执行以下操作：

1. 通过将 Amazon Bedrock 运行时端点添加为 `/openai/v1/chat/completions` 的前缀来指定 URL，格式如下：

   ```
   https://${bedrock-runtime-endpoint}/openai/v1/chat/completions
   ```

1. 在`Authorization`标题中指定您的 AWS 证书或 Amazon Bedrock API 密钥。

1. 至少在请求正文中指定 `model` 和 `messages`。

以下示例会使用 curl 在 `us-west-2` 中调用创建聊天补全 API。*\$1AWS\$1BEARER\$1TOKEN\$1BEDROCK*替换为实际的 API 密钥：

```
curl -X POST https://bedrock-runtime.us-west-2.amazonaws.com/openai/v1/chat/completions \
   -H "Content-Type: application/json" \
   -H "Authorization: Bearer $AWS_BEARER_TOKEN_BEDROCK" \
   -d '{
    "model": "openai.gpt-oss-20b-1:0",
    "messages": [
        {
            "role": "developer",
            "content": "You are a helpful assistant."
        },
        {
            "role": "user",
            "content": "Hello!"
        }
    ]
}'
```

------

## 在聊天补全中添加护栏
<a name="inference-chat-completions-guardrails"></a>

要在模型输入和响应中加入保护措施，请在运行模型调用时通过在请求正文中添加以下[额外参数](https://github.com/openai/openai-python#undocumented-request-params)作为字段来应用[护栏](guardrails.md)：
+ `extra_headers` – 映射到包含以下字段的对象，这些字段在请求中指定了额外的标头：
  + `X-Amzn-Bedrock-GuardrailIdentifier`（必填）– 护栏的 ID。
  + `X-Amzn-Bedrock-GuardrailVersion`（必填）– 护栏的版本。
  + `X-Amzn-Bedrock-Trace`（可选）– 是否启用护栏跟踪。
+ `extra_body` – 映射到对象。在该对象中，您可以包含 `amazon-bedrock-guardrailConfig` 字段，该字段映射到包含以下字段的对象：
  + `tagSuffix`（可选）– 包含此字段以用于[输入标记](guardrails-tagging.md)。

有关 Amazon Bedrock 护栏中这些参数的更多信息，请参阅[测试护栏](guardrails-test.md)。

要查看在 OpenAI 聊天补全中使用护栏的示例，请选择首选方法的选项卡，然后按照以下步骤操作：

------
#### [ OpenAI SDK (Python) ]

```
import openai
from openai import OpenAIError

# Endpoint for Amazon Bedrock Runtime
bedrock_endpoint = "https://bedrock-runtime.us-west-2.amazonaws.com/openai/v1"

# Model ID
model_id = "openai.gpt-oss-20b-1:0"

# Replace with actual values
bedrock_api_key = "$AWS_BEARER_TOKEN_BEDROCK"
guardrail_id = "GR12345"
guardrail_version = "DRAFT"

client = openai.OpenAI(
    api_key=bedrock_api_key,
    base_url=bedrock_endpoint,
)

try:
    response = client.chat.completions.create(
        model=model_id,
        # Specify guardrail information in the header
        extra_headers={
            "X-Amzn-Bedrock-GuardrailIdentifier": guardrail_id,
            "X-Amzn-Bedrock-GuardrailVersion": guardrail_version,
            "X-Amzn-Bedrock-Trace": "ENABLED",
        },
        # Additional guardrail information can be specified in the body
        extra_body={
            "amazon-bedrock-guardrailConfig": {
                "tagSuffix": "xyz"  # Used for input tagging
            }
        },
        messages=[
            {
                "role": "system",
                "content": "You are a helpful assistant."
            },
            {
                "role": "assistant", 
                "content": "Hello! How can I help you today?"
            },
            {
                "role": "user",
                "content": "What is the weather like today?"
            }
        ]
    )

    request_id = response._request_id
    print(f"Request ID: {request_id}")
    print(response)
    
except OpenAIError as e:
    print(f"An error occurred: {e}")
    if hasattr(e, 'response') and e.response is not None:
        request_id = e.response.headers.get("x-request-id")
        print(f"Request ID: {request_id}")
```

------
#### [ OpenAI SDK (Java) ]

```
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.http.HttpResponseFor;
import com.openai.models.chat.completions.ChatCompletion;
import com.openai.models.chat.completions.ChatCompletionCreateParams;

// Endpoint for Amazon Bedrock Runtime
String bedrockEndpoint = "http://bedrock-runtime.us-west-2.amazonaws.com/openai/v1"

// Model ID
String modelId = "openai.gpt-oss-20b-1:0"

// Replace with actual values
String bedrockApiKey = "$AWS_BEARER_TOKEN_BEDROCK"
String guardrailId = "GR12345"
String guardrailVersion = "DRAFT"

OpenAIClient client = OpenAIOkHttpClient.builder()
        .apiKey(bedrockApiKey)
        .baseUrl(bedrockEndpoint)
        .build()

ChatCompletionCreateParams request = ChatCompletionCreateParams.builder()
        .addUserMessage("What is the temperature in Seattle?")
        .model(modelId)
        // Specify additional headers for the guardrail
        .putAdditionalHeader("X-Amzn-Bedrock-GuardrailIdentifier", guardrailId)
        .putAdditionalHeader("X-Amzn-Bedrock-GuardrailVersion", guardrailVersion)
        // Specify additional body parameters for the guardrail
        .putAdditionalBodyProperty(
                "amazon-bedrock-guardrailConfig",
                JsonValue.from(Map.of("tagSuffix", JsonValue.of("xyz"))) // Allows input tagging
        )
        .build();
        
HttpResponseFor<ChatCompletion> rawChatCompletionResponse =
        client.chat().completions().withRawResponse().create(request);

final ChatCompletion chatCompletion = rawChatCompletionResponse.parse();

System.out.println(chatCompletion);
```

------

# 使用 Converse API 操作进行对话
<a name="conversation-inference"></a>

您可以使用 Amazon Bedrock Converse API 创建对话应用程序，用于向/从 Amazon Bedrock 模型发送/接收消息。例如，您可以创建一个聊天机器人，该机器人可以在多个回合中保持对话，并使用适合您需求的角色或语气自定义，例如有用的技术支持助理。

要使用 Converse API，您可以使用 [Converse](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html) 或 [ConverseStream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ConverseStream.html)（用于流式传输响应）操作向模型发送消息。可以将现有的基础推理运算（[InvokeModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html)或 [InvokeModelWithResponseStream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModelWithResponseStream.html)）用于对话应用程序。但是，建议使用 Converse API，因为它提供一致的 API，适用于所有支持消息的 Amazon Bedrock 模型。这意味着您只需编写一次代码，即可将其用于不同的模型。如果模型具有唯一的推理参数，Converse API 还允许您在模型特定的结构中传递这些唯一参数。

您可以使用 Converse API 在应用程序中实施[工具使用](tool-use.md)和[护栏](guardrails-use-converse-api.md)。

**注意**  
借助 Mistral AI 和 Meta 模型，Converse API 会将您的输入嵌入到特定于模型的提示模板中，从而启用对话。
限制适用于以下操作：`InvokeModel`、`InvokeModelWithResponseStream``Converse`、和`ConverseStream`。有关详细信息，请参阅 [API 限制](inference-api-restrictions.md)。

有关代码示例，请参阅以下内容：
+ 本主题的 Python 示例 – [Converse API 示例](conversation-inference-examples.md)
+ 各种语言和模型 – [使用 Amazon Bedrock Runtime 的代码示例 AWS SDKs](service_code_examples_bedrock-runtime.md)
+ Java 教程 – [Bedrock 新增 Converse API 的 Java 开发人员指南](https://community.aws/content/2hUiEkO83hpoGF5nm3FWrdfYvPt/amazon-bedrock-converse-api-java-developer-guide)
+ JavaScript 教程 — [Bedrock 的新 Converse API 开发者指南](https://community.aws/content/2dtauBCeDa703x7fDS9Q30MJoBA/amazon-bedrock-converse-api-developer-guide)

**Topics**
+ [支持的模型和模型功能](conversation-inference-supported-models-features.md)
+ [使用 Converse API](conversation-inference-call.md)
+ [Converse API 示例](conversation-inference-examples.md)

# 支持的模型和模型功能
<a name="conversation-inference-supported-models-features"></a>

Converse API 支持以下 Amazon Bedrock 模型和模型功能。Converse API 不支持任何嵌入或图像生成模型。


| 模型 | Converse | ConverseStream | 系统提示 | 文档聊天 | 视觉 | 工具使用 | 使用流式传输工具 | 护栏 | 用于多媒体的 Amazon S3 链接 | 
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | 
| AI21 Jamba-Instruct | 支持 | 是 | 是 | 否 | 否 | 否 | 否 | 否 | 否 | 
| AI21 Labs Jurassic-2（文本） | 有限。不支持聊天。 | 否 | 否 | 否 | 否 | 否 | 否 | 是 | 否 | 
| AI21 Labs Jamba 1.5 Large | 是 | 是 | 是 | 是 | 否 | 是 | 是 | 是 | 否 | 
| AI21 Labs Jamba 1.5 Mini | 是 | 是 | 是 | 是 | 否 | 是 | 是 | 是 | 否 | 
| Amazon Nova Premier | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 
| Amazon Nova Pro | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 
| Amazon Nova Lite | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 
| Amazon Nova Micro | 是 | 是 | 是 | 否 | 否 | 是 | 是 | 是 | 否 | 
| Amazon Titan 模型 | 支持 | 是 | 否 | 是（Titan Text Premier 除外） | 否 | 否 | 否 | 是 | 否 | 
| Anthropic Claude 2.x 及更早的模型 | 支持 | 是 | 是 | 是 | 否 | 否 | 否 | 是 | 否 | 
| Anthropic Claude 3 模型 | 支持 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 否 | 
| Anthropic Claude 3.5 Sonnet | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 否 | 
| Anthropic Claude 3.5 Sonnet v2 | 支持 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 否 | 
| Anthropic Claude 3.7 Sonnet | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 否 | 
| Anthropic Claude 3.5 Haiku | 是 | 是 | 是 | 是 | 否 | 是 | 是 | 否 | 否 | 
| Anthropic Claude Sonnet 4 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 否 | 否 | 
| AnthropicClaude Opus4 | 支持 | 是 | 是 | 是 | 是 | 是 | 是 | 否 | 否 | 
| Anthropic Claude Sonnet 4.5 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 否 | 否 | 
| Anthropic Claude Haiku 4.5 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 否 | 否 | 
| AnthropicClaude Opus4.1 | 支持 | 是 | 是 | 是 | 是 | 是 | 是 | 否 | 否 | 
| Claude Opus4.5 | 支持 | 是 | 是 | 是 | 是 | 是 | 是 | 否 | 否 | 
| Cohere Command | 有限。不支持聊天。 | 有限。不支持聊天。 | 否 | 是 | 否 | 否 | 否 | 是 | 否 | 
| Cohere Command Light | 有限。不支持聊天。 | 有限。不支持聊天。 | 否 | 否 | 否 | 否 | 否 | 是 | 否 | 
| Cohere 和 Command RCommand R\$1 | 支持 | 是 | 是 | 是 | 否 | 是 | 是 | 否 | 否 | 
| DeepSeek-R1 | 是 | 是 | 是 | 是 | 否 | 否 | 否 | 是 | 否 | 
| Meta 和 Llama 2Llama 3 | 支持 | 是 | 是 | 是 | 否 | 否 | 否 | 是 | 否 | 
| Meta Llama 3.1 | 是 | 是 | 是 | 是 | 否 | 是 | 否 | 是 | 否 | 
| Meta Llama 3.2 1b and Llama 3.2 3b | 是 | 是 | 是 | 是 | 否 | 否 | 否 | 是 | 否 | 
| Meta Llama 3.2 11b and Llama 3.2 90b | 是 | 是 | 是 | 是 | 是 | 是 | 否 | 是 | 否 | 
| Meta Llama 4 Maverick 17B and Llama 4.0 Scout 17B | 是 | 是 | 是 | 是 | 是 | 是 | 否 | 是 | 否 | 
| Mistral AI Instruct | 是 | 是 | 否 | 是 | 否 | 否 | 否 | 是 | 否 | 
| Mistral Large | 是 | 是 | 是 | 是 | 否 | 是 | 否 | 是 | 否 | 
| Mistral Large 2 (24.07) | 是 | 是 | 是 | 是 | 否 | 是 | 否 | 是 | 否 | 
| Mistral Small | 是 | 是 | 是 | 否 | 否 | 是 | 否 | 是 | 否 | 
| Pixtral Large (25.02) | 是 | 是 | 是 | 是 | 否 | 是 | 否 | 是 | 否 | 
| Writer Palmyra X4 | 是 | 是 | 是 | 是 | 否 | 是 | 否 | 是 | 否 | 
| Writer Palmyra X5 | 是 | 是 | 是 | 是 | 否 | 是 | 否 | 是 | 否 | 

有关各种模型受支持的区域列表，请参阅[Amazon Bedroc AWS 区域 k 中的模型支持](models-regions.md)。

**注意**  
Cohere Command（文本）和 AI21 Labs Jurassic-2（文本）不支持使用 Converse API 聊天。这些模型一次只能处理一条用户消息，并且无法维护对话的历史记录。如果尝试传递多条消息，则会出错。

# 使用 Converse API
<a name="conversation-inference-call"></a>

要使用 Converse API，您需要调用 `Converse` 或 `ConverseStream` 操作向模型发送消息。要调用 `Converse`，需具有 `bedrock:InvokeModel` 操作的权限。要调用 `ConverseStream`，需具有 `bedrock:InvokeModelWithResponseStream` 操作的权限。

**Topics**
+ [请求](#conversation-inference-call-request)
+ [响应](#conversation-inference-call-response)

**注意**  
限制适用于以下操作： InvokeModel、 InvokeModelWithResponseStream、Converse 和。 ConverseStream有关详细信息，请参阅 [API 限制](inference-api-restrictions.md)。

## 请求
<a name="conversation-inference-call-request"></a>

当您对 [Amazon Bedrock 运行时端点](https://docs.aws.amazon.com/general/latest/gr/bedrock.html#br-rt)发出 [Converse](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html) 请求时，可以包含以下字段：
+ **modelId** – 标头中的必填参数，让您可以指定用于推理的资源。
+ 使用以下字段来自定义提示：
  + **messages** – 用于指定提示的内容和角色。
  + **system** – 用于指定系统提示，来定义模型的指令或上下文。
  + **inferenceConfig** – 用于指定所有模型通用的推理参数。推理参数会影响响应的生成。
  + **additionalModelRequest字段**-用于指定特定于运行推理的模型的推理参数。
  + **promptVariables** –（如果您使用提示管理器中的提示）使用此字段定义提示中要填写的变量以及填充变量的值。
+ 使用以下字段自定义响应的返回方式：
  + **guardrailConfig** – 使用此字段指定应用到整个提示的护栏。
  + **toolConfig** – 使用此字段指定用于帮助模型生成响应的工具。
  + **additionalModelResponseFieldPaths**— 使用此字段指定要作为 JSON 指针对象返回的字段。
  + **ServiceTier** — 使用此字段为特定请求指定服务层
+ **requestMetadata** – 使用此字段指定在使用调用日志时可用于进行筛选的元数据。

**注意**  
当您将提示管理器提示与 `Converse` 或 `ConverseStream` 结合使用时，以下限制适用：  
您不能包含 `additionalModelRequestFields`、`inferenceConfig`、`system` 或 `toolConfig` 字段。
如果您包含 `messages` 字段，则消息将附加到在提示中定义的消息之后。
如果包含 `guardrailConfig` 字段，则护栏将应用于整个提示。如果您在[ContentBlock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ContentBlock.html)字段中包含`guardContent`方块，则护栏将仅应用于这些方块。

展开各部分可了解有关 `Converse` 请求正文中字段的更多信息：

### 消息
<a name="converse-messages"></a>

`messages` 字段是一组 [Message](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Message.html) 对象，每个对象都定义了用户和模型之间的消息。`Message` 对象包含以下字段：
+ **role** – 定义消息是来自 `user`（发送给模型的提示）还是 `assistant`（模型响应）。
+ **content** – 定义提示中的内容。
**注意**  
Amazon Bedrock 不会存储您作为内容提供的任何文本、图像或文档。数据仅用于生成响应。

您可以在后续 `Converse` 请求中包含对话中的所有消息，并使用 `role` 字段指定消息是来自用户还是模型，以此来维护对话上下文。

该`content`字段映射到一个[ContentBlock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ContentBlock.html)对象数组。在每个字段[ContentBlock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ContentBlock.html)中，您可以指定以下字段之一（要查看哪些模型支持哪些模块，请参阅[支持的模型和模型功能](conversation-inference-supported-models-features.md)）：

------
#### [ text ]

`text` 字段会映射到指定提示的字符串。该`text`字段与同一字段中指定的其他字段一起解释[ContentBlock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ContentBlock.html)。

下面显示了一个 M [essag](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Message.html) e 对象，其`content`数组仅包含文本 [ContentBlock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ContentBlock.html)：

```
{
    "role": "user",
    "content": [
        {
            "text": "string"
        }
    ]
}
```

------
#### [ image ]

该`image`字段映射到 [ImageBlock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ImageBlock.html). 为 `bytes` 字段中的图像传递以 base64 编码的原始字节。如果您使用 AWS 软件开发工具包，则无需在 base64 中对字节进行编码。

如果排除 `text` 字段，则模型描述图像。

下面显示了一个示例 Mess [ag](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Message.html) e 对象，其`content`数组仅包含图像 [ContentBlock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ContentBlock.html)：

```
{
    "role": "user",
    "content": [
        {
            "image": {
                "format": "png",
                "source": {
                    "bytes": "image in bytes"
                }
            }
        }
    ]
}
```

您也可以指定 Amazon S3 URI，而不是直接在请求正文中传递字节。下面显示了一个示例 `Message` 对象，其内容数组包含通过 Amazon S3 URI 传递的源。

```
{
    "role": "user",
    "content": [
        {
            "image": {
                "format": "png",
                "source": {
                    "s3Location": {
                        "uri": "s3://amzn-s3-demo-bucket/myImage",
                        "bucketOwner": "111122223333"
                    }
                }
            }
        }
    ]
}
```

------
#### [ document ]

该`document`字段映射到 [DocumentBlock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_DocumentBlock.html). 如果包含 `DocumentBlock`，请检查您的请求是否符合以下限制：
+ 在 [Message](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Message.html) 对象的 `content` 字段中，还必须包括一个带有与文档相关的提示的 `text` 字段。
+ 为 `bytes` 字段中的文档传递以 base64 编码的原始字节。如果使用的是 AWS SDK，则无需使用 base64 对文档进行编码。
+ `name` 字段只能包含以下字符：
  + 字母数字字符
  + 空格字符（连续不得超过一个）
  + 连字符
  + 圆括号
  + 方括号
**注意**  
`name` 字段容易受到提示注入的影响，因为模型可能会意外将其解释为指令。因此，我们建议您指定一个中性名称。

使用文档时，您可以启用 `citations` 标签，该标签将在 API 调用的响应中提供特定于文档的引文。有关更多详细信息，请参阅 [DocumentBlock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_DocumentBlock.html)API。

下面显示了一个示例 Mess [ag](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Message.html) e 对象，其`content`数组仅包含文档[ContentBlock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ContentBlock.html)和必需的随附文本[ContentBlock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ContentBlock.html)。

```
{
    "role": "user",
    "content": [
        {
            "text": "string"
        },
        {
            "document": {
                "format": "pdf",
                "name": "MyDocument",
                "source": {
                    "bytes": "document in bytes"
                }
            }
        }
    ]
}
```

您也可以指定 Amazon S3 URI，而不是直接在请求正文中传递字节。下面显示了一个示例 `Message` 对象，其内容数组包含通过 Amazon S3 URI 传递的源。

```
{
    "role": "user",
    "content": [
        {
            "text": "string"
        },
        {
            "document": {
                "format": "pdf",
                "name": "MyDocument",
                "source": {
                    "s3Location": {
                      "uri": "s3://amzn-s3-demo-bucket/myDocument",
                      "bucketOwner": "111122223333"
                    }
                }
            }
        }
    ]
}
```

------
#### [ video ]

该`video`字段映射到一个[VideoBlock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_VideoBlock.html)对象。在 `bytes` 字段中，传递以 base64 编码的原始字节。如果您使用 AWS 软件开发工具包，则无需在 base64 中对字节进行编码。

如果未包含 `text` 字段，则模型将描述视频。

下面显示了一个示例 Mess [ag](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Message.html) e 对象，其`content`数组仅包含视频[ContentBlock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ContentBlock.html)。

```
{
    "role": "user",
    "content": [
        {
            "video": {
                "format": "mp4",
                "source": {
                    "bytes": "video in bytes"
                }
            }
        }
    ]
}
```

您也可以指定 Amazon S3 URI，而不是直接在请求正文中传递字节。下面显示了一个示例 `Message` 对象，其内容数组包含通过 Amazon S3 URI 传递的源。

```
{
    "role": "user",
    "content": [
        {
            "video": {
                "format": "mp4",
                "source": {
                    "s3Location": {
                        "uri": "s3://amzn-s3-demo-bucket/myVideo",
                        "bucketOwner": "111122223333"
                    }
                }
            }
        }
    ]
}
```

**注意**  
代入的角色必须具有该 Amazon S3 URI 的 `s3:GetObject` 权限。`bucketOwner` 字段可选，但如果发出请求的账户并非 Amazon S3 URI 所在存储桶的拥有者，则必须指定此字段。有关更多信息，请参阅 [配置对 Amazon S3 存储桶的访问权限](s3-bucket-access.md)。

------
#### [ cachePoint ]

您可以使用 `cachePoint` 字段来利用提示缓存，将缓存检查点作为单元，与随附的提示一起添加到消息中。提示缓存是一项功能，让您可以开始缓存对话上下文，从而节省成本和降低延迟。有关更多信息，请参阅 [用于加快模型推理速度的提示缓存](prompt-caching.md)。

下面显示了一个示例 Mess [ag](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Message.html) e 对象，该对象包含一个包含文档[ContentBlock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ContentBlock.html)和必需的随附文本的`content`数组 [ContentBlock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ContentBlock.html)，以及一个将文档和文本内容都添加到**缓存中的 CachePoint**。

```
{
    "role": "user",
    "content": [
        {
            "text": "string"
        },
        {
            "document": {
                "format": "pdf",
                "name": "string",
                "source": {
                    "bytes": "document in bytes"
                }
            }
        },
        {
            "cachePoint": {
                "type": "default"
            }
        }
    ]
}
```

------
#### [ guardContent ]

该`guardContent`字段映射到一个[GuardrailConverseContentBlock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_GuardrailConverseContentBlock.html)对象。您可以使用此字段来定位要由 `guardrailConfig` 字段中定义的护栏进行评估的输入。如果您未指定此字段，则护栏将评估请求正文中的所有消息。您可以在 `GuardBlock` 中传递以下内容类型：
+ **text** — 下面显示了一个示例 Mess [ag](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Message.html) e 对象，其`content`数组仅包含文本 [GuardrailConverseContentBlock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_GuardrailConverseContentBlock.html)：

  ```
  {
      "role": "user",
      "content": [
          {
              "text": "Tell me what stocks to buy.",
              "qualifiers": [
                  "guard_content"
              ]
          }
      ]
  }
  ```

  您定义要评估的文本，并提供用于[上下文一致性](guardrails-contextual-grounding-check.md)的任意限定词。
+ **image** — 下面显示了一个 M [essag](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Message.html) e 对象，其`content`数组仅包含图像 [GuardrailConverseContentBlock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_GuardrailConverseContentBlock.html)：

  ```
  {
      "role": "user",
      "content": [
          {
              "format": "png",
              "source": {
                  "bytes": "image in bytes"
              }
          }
      ]
  }
  ```

  您可以指定图像的格式并以字节为单位定义图像。

有关使用护栏的更多信息，请参阅[使用 Amazon Bedrock 护栏检测和筛选掉有害内容](guardrails.md)。

------
#### [ reasoningContent ]

该`reasoningContent`字段映射到 a [ReasoningContentBlock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ReasoningContentBlock.html). 此单元包含关于推理的内容，此推理由生成随附 `ContentBlock` 中的响应的模型执行。

下面显示了一个 `Message` 对象，其 `content` 数组仅包含 `ReasoningContentBlock` 和一个随附的文本 `ContentBlock`。

```
{
    "role": "user",
    "content": [
        {
            "text": "string"
        },
        {
            "reasoningContent": {
                "reasoningText": {
                    "text": "string",
                    "signature": "string"
                }
                "redactedContent": "base64-encoded binary data object"
            }
        }
    ]
}
```

`ReasoningContentBlock` 包含用于生成 `reasoningText` 字段中随附内容的推理，以及模型提供商出于信任和安全原因，在 `redactedContent` 字段中加密的推理中的任何内容。

在 `reasoningText` 字段中，`text` 字段描述了推理。`signature` 字段是对话中所有消息的哈希值，用于防止篡改模型使用的推理。您必须在后续 `Converse` 请求中包含签名和之前的所有消息。如果任何消息发生更改，响应就会引发错误。

------
#### [ toolUse ]

包含有关模型要使用的工具的信息。有关更多信息，请参阅 [使用工具完成 Amazon Bedrock 模型响应](tool-use.md)。

------
#### [ toolResult ]

包含有关模型使用工具得出的结果的信息。有关更多信息，请参阅 [使用工具完成 Amazon Bedrock 模型响应](tool-use.md)。

------

在以下 `messages` 示例中，用户要求提供一个包含三首流行歌曲的列表，模型生成了一个歌曲列表。

```
[
    {
        "role": "user",
        "content": [
            {
                "text": "Create a list of 3 pop songs."
            }
        ]
    },
    {
        "role": "assistant",
        "content": [
            {
                "text": "Here is a list of 3 pop songs by artists from the United Kingdom:\n\n1. \"As It Was\" by Harry Styles\n2. \"Easy On Me\" by Adele\n3. \"Unholy\" by Sam Smith and Kim Petras"
            }
        ]
    }
]
```

### 系统
<a name="converse-system"></a>

系统提示是一种提示，它向模型提供有关其应执行的任务或在对话中应采用的角色的说明或上下文。您可以在 `system` ([SystemContentBlock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_SystemContentBlock.html)) 字段中为请求指定系统提示列表，如以下示例所示。

```
[
    {
        "text": "You are an app that creates play lists for a radio station that plays rock and pop music. Only return song names and the artist. "
    }
]
```

### inferenceConfig
<a name="converse-inference"></a>

ConverseAPI 支持您在`inferenceConfig`字段 ([InferenceConfiguration](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InferenceConfiguration.html)) 中设置的一组基本推理参数。基本推理参数集包括：
+ **MaxTokens** – 允许在生成的响应中使用的最大词元数。
+ **stopSequences** – 停止序列的列表。停止序列是一个字符序列，会使模型停止生成响应。
+ **temperature** – 模型在生成响应时选择更高概率选项的可能性。
+ **topP** – 模型为下一个词元考虑的最有可能的候选项所占百分比。

有关更多信息，请参阅 [利用推理参数影响响应生成](inference-parameters.md)。

以下示例 JSON 设置了 `temperature` 推理参数。

```
{"temperature": 0.5}
```

### additionalModelRequest字段
<a name="converse-additional-model-request-fields"></a>

如果您使用的模型具有其他推理参数，则可以通过在 `additionalModelRequestFields` 字段中将其指定为 JSON 来设置这些参数。以下示例 JSON 演示了如何设置 `top_k`，该参数在 Anthropic Claude 模型中可用，但不是 messages API 中的基本推理参数。

```
{"top_k": 200}
```

### promptVariables
<a name="converse-prompt-variables"></a>

如果您在 `modelId` 中指定[提示管理器](prompt-management.md)中的提示作为对其运行推理的资源，则使用此字段将实际值填充到提示变量中。`promptVariables` 字段映射到一个 JSON 对象，其键对应于在提示中定义的变量，其值用于替换变量。

例如，假设您有一个提示 **Make me a *\$1\$1genre\$1\$1* playlist consisting of the following number of songs: *\$1\$1number\$1\$1*.**。提示的 ID 是 `PROMPT12345`，其版本是 `1`。您可以发送以下 `Converse` 请求来替换变量：

```
POST /model/arn:aws:bedrock:us-east-1:111122223333:prompt/PROMPT12345:1/converse HTTP/1.1
Content-type: application/json

{
   "promptVariables": { 
      "genre" : "pop",
      "number": 3
   }
}
```

### guardrailConfig
<a name="converse-guardrail"></a>

您可以通过包括此字段来应用您使用 [Amazon Bedrock 护栏](guardrails.md)创建的护栏。要将护栏应用于对话中的特定消息，请将该消息包含在中。[GuardrailConverseContentBlock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_GuardrailConverseContentBlock.html)如果您在请求正文中未包含任何 `GuardrailConverseContentBlock`，则会将护栏应用于 `messages` 字段中的所有消息。有关示例，请参阅[在使用 Converse API 时添加护栏](guardrails-use-converse-api.md)。

### toolConfig
<a name="converse-tool"></a>

此字段让您可以为模型定义工具，用于帮助模型生成响应。有关更多信息，请参阅 [使用工具完成 Amazon Bedrock 模型响应](tool-use.md)。

### additionalModelResponseFieldPaths
<a name="converse-additional-model-response-field-paths"></a>

您可以在 `additionalModelResponseFieldPaths` 字段中指定其他模型参数的路径，如以下示例所示。

```
[ "/stop_sequence" ]
```

API 会返回您在 `additionalModelResponseFields` 字段中请求的其他字段。

### requestMetadata
<a name="converse-request-metadata"></a>

此字段映射到 JSON 对象。您可以在该对象中指定所映射到的元数据键和值。您可以使用请求元数据来帮助您筛选模型调用日志。

### 服务等级
<a name="inference-service-tiers"></a>

此字段映射到 JSON 对象。您可以为特定请求指定服务级别。

以下示例显示了`serviceTier`结构：

```
"serviceTier": {
  "type": "reserved" | "priority" | "default" | "flex"
}
```

有关服务等级的详细信息，包括定价和性能特征，请参阅[用于优化性能和成本的服务分层](service-tiers-inference.md)。

根据所用的模型，您也可以选择向 `system` 或 `tools` 字段添加缓存检查点来使用提示缓存。有关更多信息，请参阅 [用于加快模型推理速度的提示缓存](prompt-caching.md)。

## 响应
<a name="conversation-inference-call-response"></a>

您从 Converse API 获得的响应取决于您调用的操作（`Converse` 或 `ConverseStream`）。

**Topics**
+ [Converse 响应](#conversation-inference-call-response-converse)
+ [ConverseStream 响应](#conversation-inference-call-response-converse-stream)

### Converse 响应
<a name="conversation-inference-call-response-converse"></a>

在来自的响应中`Converse`，`output`字段 ([ConverseOutput](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ConverseOutput.html)) 包含模型生成的[消息（消息](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Message.html)）。消息内容位于 `content` ([ContentBlock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ContentBlock.html)) 字段中，消息对应的角色（`user`或`assistant`）位于该`role`字段中。

如果您使用了[提示缓存](prompt-caching.md)，则在使用情况字段中，`cacheReadInputTokensCount` 和 `cacheWriteInputTokensCount` 会分别指明对缓存读取和写入的词元总数。

如果您使用了[服务层](#inference-service-tiers)，那么在响应字段中，`service tier`会告诉您请求使用了哪个服务层。

字`metrics`段 ([ConverseMetrics](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ConverseMetrics.html)) 包含呼叫的指标。要确定模型停止生成内容的原因，请检查 `stopReason` 字段。通过选中`usage`字段 ([TokenUsage](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_TokenUsage.html))，您可以获取有关在请求中传递给模型的令牌以及响应中生成的令牌的信息。如果您在请求中指定了其他响应字段，API 会在 `additionalModelResponseFields` 字段中将其作为 JSON 返回。

以下示例演示了您在传递 [请求](#conversation-inference-call-request) 中讨论的提示时 `Converse` 的响应。

```
{
    "output": {
        "message": {
            "role": "assistant",
            "content": [
                {
                    "text": "Here is a list of 3 pop songs by artists from the United Kingdom:\n\n1. \"Wannabe\" by Spice Girls\n2. \"Bitter Sweet Symphony\" by The Verve \n3. \"Don't Look Back in Anger\" by Oasis"
                }
            ]
        }
    },
    "stopReason": "end_turn",
    "usage": {
        "inputTokens": 125,
        "outputTokens": 60,
        "totalTokens": 185
    },
    "metrics": {
        "latencyMs": 1175
    }
}
```

### ConverseStream 响应
<a name="conversation-inference-call-response-converse-stream"></a>

如果您调用 `ConverseStream` 以流式传输来自模型的响应，则会在 `stream` 响应字段中返回该流。流按以下顺序发出以下事件。

1. `messageStart`([MessageStartEvent](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_MessageStartEvent.html))。 消息的开始事件。包括消息的角色。

1. `contentBlockStart`([ContentBlockStartEvent](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ContentBlockStartEvent.html))。 内容区块启动事件。仅用于实现工具使用。

1. `contentBlockDelta`([ContentBlockDeltaEvent](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ContentBlockDeltaEvent.html))。 内容区块增量事件。包含以下选项之一：
   + `text` – 模型生成的部分文本。
   + `reasoningContent` – 模型为生成响应执行的部分推理。在后续 `Converse` 请求中，除了所有之前的消息以外，您还必须提交返回的 `signature`。如果任何消息发生更改，响应就会引发错误。
   + `toolUse` – 工具使用的部分输入 JSON 对象。

1. `contentBlockStop`([ContentBlockStopEvent](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ContentBlockStopEvent.html))。 内容屏蔽停止事件。

1. `messageStop`([MessageStopEvent](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_MessageStopEvent.html))。 消息的停止事件。包括模型停止生成输出的原因。

1. `metadata`([ConverseStreamMetadataEvent](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ConverseStreamMetadataEvent.html))。 请求的元数据。元数据包括 `usage` ([TokenUsage](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_TokenUsage.html)) 中的令牌使用情况和 `metrics` ([ConverseStreamMetadataEvent](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ConverseStreamMetadataEvent.html)) 中调用的指标。

ConverseStream 将完整的内容块作为`ContentBlockStartEvent`事件、一个或多个事件和一个`ContentBlockDeltaEvent``ContentBlockStopEvent`事件进行流式传输。使用 `contentBlockIndex` 字段作为索引，关联构成内容块的事件。

以下示例是来自 `ConverseStream` 的部分响应。

```
{'messageStart': {'role': 'assistant'}}
{'contentBlockDelta': {'delta': {'text': ''}, 'contentBlockIndex': 0}}
{'contentBlockDelta': {'delta': {'text': ' Title'}, 'contentBlockIndex': 0}}
{'contentBlockDelta': {'delta': {'text': ':'}, 'contentBlockIndex': 0}}
.
.
.
{'contentBlockDelta': {'delta': {'text': ' The'}, 'contentBlockIndex': 0}}
{'messageStop': {'stopReason': 'max_tokens'}}
{'metadata': {'usage': {'inputTokens': 47, 'outputTokens': 20, 'totalTokens': 67}, 'metrics': {'latencyMs': 100.0}}}
```

# Converse API 示例
<a name="conversation-inference-examples"></a>

以下示例演示了如何使用 `Converse` 和 `ConverseStream` 操作。

------
#### [ Text ]

此示例演示了如何使用 *Anthropic Claude 3 Sonnet* 模型调用 `Converse` 操作。此示例演示了如何发送模型独有的输入文本、推理参数和其他参数。该代码通过让模型创建歌曲列表来开始对话。然后，它继续对话，要求这些歌曲是由英国艺术家创作的。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Shows how to use the <noloc>Converse</noloc> API with Anthropic Claude 3 Sonnet (on demand).
"""

import logging
import boto3

from botocore.exceptions import ClientError


logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)


def generate_conversation(bedrock_client,
                          model_id,
                          system_prompts,
                          messages):
    """
    Sends messages to a model.
    Args:
        bedrock_client: The Boto3 Bedrock runtime client.
        model_id (str): The model ID to use.
        system_prompts (JSON) : The system prompts for the model to use.
        messages (JSON) : The messages to send to the model.

    Returns:
        response (JSON): The conversation that the model generated.

    """

    logger.info("Generating message with model %s", model_id)

    # Inference parameters to use.
    temperature = 0.5
    top_k = 200

    # Base inference parameters to use.
    inference_config = {"temperature": temperature}
    # Additional inference parameters to use.
    additional_model_fields = {"top_k": top_k}

    # Send the message.
    response = bedrock_client.converse(
        modelId=model_id,
        messages=messages,
        system=system_prompts,
        inferenceConfig=inference_config,
        additionalModelRequestFields=additional_model_fields
    )

    # Log token usage.
    token_usage = response['usage']
    logger.info("Input tokens: %s", token_usage['inputTokens'])
    logger.info("Output tokens: %s", token_usage['outputTokens'])
    logger.info("Total tokens: %s", token_usage['totalTokens'])
    logger.info("Stop reason: %s", response['stopReason'])

    return response

def main():
    """
    Entrypoint for Anthropic Claude 3 Sonnet example.
    """

    logging.basicConfig(level=logging.INFO,
                        format="%(levelname)s: %(message)s")

    model_id = "anthropic.claude-3-sonnet-20240229-v1:0"

    # Setup the system prompts and messages to send to the model.
    system_prompts = [{"text": "You are an app that creates playlists for a radio station that plays rock and pop music. Only return song names and the artist."}]
    message_1 = {
        "role": "user",
        "content": [{"text": "Create a list of 3 pop songs."}]
    }
    message_2 = {
        "role": "user",
        "content": [{"text": "Make sure the songs are by artists from the United Kingdom."}]
    }
    messages = []

    try:

        bedrock_client = boto3.client(service_name='bedrock-runtime')

        # Start the conversation with the 1st message.
        messages.append(message_1)
        response = generate_conversation(
            bedrock_client, model_id, system_prompts, messages)

        # Add the response message to the conversation.
        output_message = response['output']['message']
        messages.append(output_message)

        # Continue the conversation with the 2nd message.
        messages.append(message_2)
        response = generate_conversation(
            bedrock_client, model_id, system_prompts, messages)

        output_message = response['output']['message']
        messages.append(output_message)

        # Show the complete conversation.
        for message in messages:
            print(f"Role: {message['role']}")
            for content in message['content']:
                print(f"Text: {content['text']}")
            print()

    except ClientError as err:
        message = err.response['Error']['Message']
        logger.error("A client error occurred: %s", message)
        print(f"A client error occured: {message}")

    else:
        print(
            f"Finished generating text with model {model_id}.")


if __name__ == "__main__":
    main()
```

------
#### [ Image ]

此示例演示了如何将图像作为消息的一部分发送，并要求模型对图像进行描述。此示例使用 `Converse` 操作和 *Anthropic Claude 3 Sonnet* 模型。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Shows how to send an image with the <noloc>Converse</noloc> API with an accompanying text prompt to Anthropic Claude 3 Sonnet (on demand).
"""

import logging
import boto3


from botocore.exceptions import ClientError


logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)


def generate_conversation(bedrock_client,
                          model_id,
                          input_text,
                          input_image):
    """
    Sends a message to a model.
    Args:
        bedrock_client: The Boto3 Bedrock runtime client.
        model_id (str): The model ID to use.
        input text : The text prompt accompanying the image.
        input_image : The path to the input image.

    Returns:
        response (JSON): The conversation that the model generated.

    """

    logger.info("Generating message with model %s", model_id)

    # Get image extension and read in image as bytes
    image_ext = input_image.split(".")[-1]
    with open(input_image, "rb") as f:
        image = f.read()

    message = {
        "role": "user",
        "content": [
            {
                "text": input_text
            },
            {
                "image": {
                    "format": image_ext,
                    "source": {
                        "bytes": image
                    }
                }
            }
        ]
    }

    messages = [message]

    # Send the message.
    response = bedrock_client.converse(
        modelId=model_id,
        messages=messages
    )

    return response


def main():
    """
    Entrypoint for Anthropic Claude 3 Sonnet example.
    """

    logging.basicConfig(level=logging.INFO,
                        format="%(levelname)s: %(message)s")

    model_id = "anthropic.claude-3-sonnet-20240229-v1:0"
    input_text = "What's in this image?"
    input_image = "path/to/image"

    try:

        bedrock_client = boto3.client(service_name="bedrock-runtime")

        response = generate_conversation(
            bedrock_client, model_id, input_text, input_image)

        output_message = response['output']['message']

        print(f"Role: {output_message['role']}")

        for content in output_message['content']:
            print(f"Text: {content['text']}")

        token_usage = response['usage']
        print(f"Input tokens:  {token_usage['inputTokens']}")
        print(f"Output tokens:  {token_usage['outputTokens']}")
        print(f"Total tokens:  {token_usage['totalTokens']}")
        print(f"Stop reason: {response['stopReason']}")

    except ClientError as err:
        message = err.response['Error']['Message']
        logger.error("A client error occurred: %s", message)
        print(f"A client error occured: {message}")

    else:
        print(
            f"Finished generating text with model {model_id}.")


if __name__ == "__main__":
    main()
```

------
#### [ Document ]

此示例演示了如何将文档作为消息的一部分发送，并要求模型对文档内容进行描述。此示例使用 `Converse` 操作和 *Anthropic Claude 3 Sonnet* 模型。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Shows how to send an document as part of a message to Anthropic Claude 3 Sonnet (on demand).
"""

import logging
import boto3


from botocore.exceptions import ClientError


logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)


def generate_message(bedrock_client,
                     model_id,
                     input_text,
                     input_document_path):
    """
    Sends a message to a model.
    Args:
        bedrock_client: The Boto3 Bedrock runtime client.
        model_id (str): The model ID to use.
        input text : The input message.
        input_document_path : The path to the input document.

    Returns:
        response (JSON): The conversation that the model generated.

    """

    logger.info("Generating message with model %s", model_id)

    # Get format from path and read the path
    input_document_format = input_document_path.split(".")[-1]
    with open(input_document_path, 'rb') as input_document_file:
        input_document = input_document_file.read()

    # Message to send.
    message = {
        "role": "user",
        "content": [
            {
                "text": input_text
            },
            {
                "document": {
                    "name": "MyDocument",
                    "format": input_document_format,
                    "source": {
                        "bytes": input_document
                    }
                }
            }
        ]
    }

    messages = [message]

    # Send the message.
    response = bedrock_client.converse(
        modelId=model_id,
        messages=messages
    )

    return response


def main():
    """
    Entrypoint for Anthropic Claude 3 Sonnet example.
    """

    logging.basicConfig(level=logging.INFO,
                        format="%(levelname)s: %(message)s")

    model_id = "anthropic.claude-3-sonnet-20240229-v1:0"
    input_text = "What's in this document?"
    input_document_path = "path/to/document"

    try:

        bedrock_client = boto3.client(service_name="bedrock-runtime")


        response = generate_message(
            bedrock_client, model_id, input_text, input_document_path)

        output_message = response['output']['message']

        print(f"Role: {output_message['role']}")

        for content in output_message['content']:
            print(f"Text: {content['text']}")

        token_usage = response['usage']
        print(f"Input tokens:  {token_usage['inputTokens']}")
        print(f"Output tokens:  {token_usage['outputTokens']}")
        print(f"Total tokens:  {token_usage['totalTokens']}")
        print(f"Stop reason: {response['stopReason']}")

    except ClientError as err:
        message = err.response['Error']['Message']
        logger.error("A client error occurred: %s", message)
        print(f"A client error occured: {message}")

    else:
        print(
            f"Finished generating text with model {model_id}.")


if __name__ == "__main__":
    main()
```

------
#### [ Streaming ]

此示例演示了如何使用 *Anthropic Claude 3 Sonnet* 模型调用 `ConverseStream` 操作。此示例演示了如何发送模型独有的输入文本、推理参数和其他参数。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Shows how to use the <noloc>Converse</noloc> API to stream a response from Anthropic Claude 3 Sonnet (on demand).
"""

import logging
import boto3


from botocore.exceptions import ClientError


logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)


def stream_conversation(bedrock_client,
                    model_id,
                    messages,
                    system_prompts,
                    inference_config,
                    additional_model_fields):
    """
    Sends messages to a model and streams the response.
    Args:
        bedrock_client: The Boto3 Bedrock runtime client.
        model_id (str): The model ID to use.
        messages (JSON) : The messages to send.
        system_prompts (JSON) : The system prompts to send.
        inference_config (JSON) : The inference configuration to use.
        additional_model_fields (JSON) : Additional model fields to use.

    Returns:
        Nothing.

    """

    logger.info("Streaming messages with model %s", model_id)

    response = bedrock_client.converse_stream(
        modelId=model_id,
        messages=messages,
        system=system_prompts,
        inferenceConfig=inference_config,
        additionalModelRequestFields=additional_model_fields
    )

    stream = response.get('stream')
    if stream:
        for event in stream:

            if 'messageStart' in event:
                print(f"\nRole: {event['messageStart']['role']}")

            if 'contentBlockDelta' in event:
                print(event['contentBlockDelta']['delta']['text'], end="")

            if 'messageStop' in event:
                print(f"\nStop reason: {event['messageStop']['stopReason']}")

            if 'metadata' in event:
                metadata = event['metadata']
                if 'usage' in metadata:
                    print("\nToken usage")
                    print(f"Input tokens: {metadata['usage']['inputTokens']}")
                    print(
                        f":Output tokens: {metadata['usage']['outputTokens']}")
                    print(f":Total tokens: {metadata['usage']['totalTokens']}")
                if 'metrics' in event['metadata']:
                    print(
                        f"Latency: {metadata['metrics']['latencyMs']} milliseconds")


def main():
    """
    Entrypoint for streaming message API response example.
    """

    logging.basicConfig(level=logging.INFO,
                        format="%(levelname)s: %(message)s")

    model_id = "anthropic.claude-3-sonnet-20240229-v1:0"
    system_prompt = """You are an app that creates playlists for a radio station
      that plays rock and pop music. Only return song names and the artist."""

    # Message to send to the model.
    input_text = "Create a list of 3 pop songs."

    message = {
        "role": "user",
        "content": [{"text": input_text}]
    }
    messages = [message]
    
    # System prompts.
    system_prompts = [{"text" : system_prompt}]

    # inference parameters to use.
    temperature = 0.5
    top_k = 200
    # Base inference parameters.
    inference_config = {
        "temperature": temperature
    }
    # Additional model inference parameters.
    additional_model_fields = {"top_k": top_k}

    try:
        bedrock_client = boto3.client(service_name='bedrock-runtime')

        stream_conversation(bedrock_client, model_id, messages,
                        system_prompts, inference_config, additional_model_fields)

    except ClientError as err:
        message = err.response['Error']['Message']
        logger.error("A client error occurred: %s", message)
        print("A client error occured: " +
              format(message))

    else:
        print(
            f"Finished streaming messages with model {model_id}.")


if __name__ == "__main__":
    main()
```

------
#### [ Video ]

此示例演示了如何将视频作为消息的一部分发送，并要求模型描述视频。此示例使用 `Converse` 操作和 Amazon Nova Pro 模型。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Shows how to send a video with the <noloc>Converse</noloc> API to Amazon Nova Pro (on demand).
"""

import logging
import boto3


from botocore.exceptions import ClientError


logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)


def generate_conversation(bedrock_client,
                          model_id,
                          input_text,
                          input_video):
    """
    Sends a message to a model.
    Args:
        bedrock_client: The Boto3 Bedrock runtime client.
        model_id (str): The model ID to use.
        input text : The input message.
        input_video : The input video.

    Returns:
        response (JSON): The conversation that the model generated.

    """

    logger.info("Generating message with model %s", model_id)

    # Message to send.

    with open(input_video, "rb") as f:
        video = f.read()

    message = {
        "role": "user",
        "content": [
            {
                "text": input_text
            },
            {
                    "video": {
                        "format": 'mp4',
                        "source": {
                            "bytes": video
                        }
                    }
            }
        ]
    }

    messages = [message]

    # Send the message.
    response = bedrock_client.converse(
        modelId=model_id,
        messages=messages
    )

    return response


def main():
    """
    Entrypoint for Amazon Nova Pro example.
    """

    logging.basicConfig(level=logging.INFO,
                        format="%(levelname)s: %(message)s")

    model_id = "amazon.nova-pro-v1:0"
    input_text = "What's in this video?"
    input_video = "path/to/video"

    try:

        bedrock_client = boto3.client(service_name="bedrock-runtime")

        response = generate_conversation(
            bedrock_client, model_id, input_text, input_video)

        output_message = response['output']['message']

        print(f"Role: {output_message['role']}")

        for content in output_message['content']:
            print(f"Text: {content['text']}")

        token_usage = response['usage']
        print(f"Input tokens:  {token_usage['inputTokens']}")
        print(f"Output tokens:  {token_usage['outputTokens']}")
        print(f"Total tokens:  {token_usage['totalTokens']}")
        print(f"Stop reason: {response['stopReason']}")

    except ClientError as err:
        message = err.response['Error']['Message']
        logger.error("A client error occurred: %s", message)
        print(f"A client error occured: {message}")

    else:
        print(
            f"Finished generating text with model {model_id}.")


if __name__ == "__main__":
    main()
```

------

# API 限制
<a name="inference-api-restrictions"></a>

以下限制适用于`InvokeModel`、`InvokeModelWithResponseStream``Converse`、和`ConverseStream`操作。一些限制因操作或型号而异，如下所示：
+ 使用这些操作时，如果`role`是，则只能包含图像和文档`user`。
+ **视频生成：**`InvokeModel`和不支持视频生成`InvokeModelWithResponseStream`。相反，你可以使用该[StartAsyncInvoke](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_StartAsyncInvoke.html)操作。有关示例，请参阅[使用 Amazon Nova Reel 根据文本提示生成视频](https://docs.aws.amazon.com/bedrock/latest/userguide/bedrock-runtime_example_bedrock-runtime_Scenario_AmazonNova_TextToVideo_section.html)。
+ **请求正文中的文档支持：**使用`InvokeModel`和时，不支持在请求正文中包含文档`InvokeModelWithResponseStream`。要在推理期间包含文档，请使用或中的[聊天/文本游乐场](playgrounds.md)， AWS 管理控制台 或者使用或操作。`Converse` `ConverseStream`
+ **文件数量和大小：**每次请求最多可以包含 5 份文档。每个文档的大小不能超过 4.5 MB。对于 Claude 4 及后续版本，4.5 MB 文档大小限制不适用于`PDF`格式。对于 Nova 机型，4.5 MB 文档大小限制不适用于`PDF`和`DOCX`格式。这些限制继续适用于 Bedrock 控制台。除了 Amazon Bedrock 规定的限制之外，个别模特可能还有其他内容限制。有关更多信息，请参阅**第三方模型提供商要求**。
+ **图片数量和尺寸**：Amazon Bedrock 不对图片数量和大小施加限制。但是，个别模特可能有特定的图片要求。有关更多信息，请参阅**第三方模型提供商要求**。
+ **第三方模型提供者要求：**第三方模型提供者要求适用于您使用`InvokeModel``InvokeModelWithResponseStream``Converse`、、和`ConverseStream`操作，如果不满足，可能会导致错误。如果您通过 Amazon Bedrock 使用第三方模型（例如 Anthropic Claude），请查看提供商的用户指南和 API 文档，以免出现意外错误。例如，Anthropic Messages 标准端点支持的最大请求大小为 32 MB。Claude 还有特定的内容要求，例如每个请求最多 100 `PDF` 页，最大图像大小为 8000x8000 px。[有关 Anthropic Claude Messages 请求和响应的最新信息，包括请求大小和内容要求，请参阅以下 Anthropic Claude 文档：Anthropic Claude [API 概述、Antropic Claude 消息 API](https://platform.claude.com/docs/en/api/overview)[参考、使用 Claude](https://docs.anthropic.com/claude/reference/messages_post)[构建：Vision 和 Claude 构建](https://platform.claude.com/docs/en/build-with-claude/vision)：PDF Support。](https://platform.claude.com/docs/en/build-with-claude/pdf-support)

**提示**  
Claude 要求每次请求的 PDF 文档最多 100 页。如果您有较大的 PDF 文档，我们建议将它们拆分为多个 100 页以 PDFs 下，或者将更多文本合并成更少的页面。

# 从模型中获取经过验证的 JSON 结果
<a name="structured-output"></a>

结构化输出是 Amazon Bedrock 上的一项功能，可确保模型响应符合用户定义的 JSON 架构和工具定义，从而减少生产 AI 部署中对自定义解析和验证机制的需求。

## 优势
<a name="structured-output-benefits"></a>

结构化输出解决了生产 AI 应用程序中的关键挑战：
+ **确保架构合规性** — 消除基于提示的方法中的错误率和重试循环
+ **降低开发复杂性** — 无需自定义解析和验证逻辑
+ **降低运营成本** — 减少失败的请求和重试次数
+ **生产可靠性** — 支持自信地部署需要可预测的机器可读输出的 AI 应用程序

## 工作原理
<a name="structured-output-how-it-works"></a>

结构化输出将模型响应限制为遵循特定架构，从而确保下游处理的输出有效、可解析。您可以通过两种互补机制使用结构化输出：

### JSON 架构输出格式
<a name="structured-output-json-schema"></a>

对于带有 Anthropic Claude 模型的 InvokeModel API，请使用`output_config.format`请求字段。对于开放式重量模型，请使用`response_format`请求字段。对于 Converse APIs，请使用`outputConfig.textFormat`请求字段。模型的响应将符合指定的 JSON 架构。

### 严格使用工具
<a name="structured-output-strict-tool-use"></a>

在工具定义中添加`strict: true`标志，以启用对工具名称和输入的架构验证。然后，模型的工具调用将遵循定义的工具输入架构。

这些机制可以单独使用，也可以在同一个请求中一起使用。有关更多详细信息，请参阅 [Bedrock API 文档](https://docs.aws.amazon.com/bedrock/latest/APIReference/welcome.html)。

### 请求工作流程
<a name="structured-output-request-workflow"></a>

以下内容介绍了 Amazon Bedrock 如何处理带有结构化输出的请求：

1. **初始请求** — 您可以通过`outputConfig.textFormat`、或`response_format`参数包含一个 JSON 架构`output_config.format`，或者在推理请求中加入带有`strict: true`标志的工具定义。

1. **架构验证** — Amazon Bedrock 根据支持的 2020-12 年 JSON 架构草案子集验证 JSON 架构格式。如果架构包含不支持的功能，Amazon Bedrock 会立即返回 400 错误。

1. **首次编译** — 对于新的架构，Amazon Bedrock 会编译语法，这可能需要几分钟。

1. **缓存** — 成功编译的语法将在首次访问后缓存 24 小时。缓存的语法使用 AWS 托管的密钥进行加密。

1. **后续请求** — 来自同一账户的相同架构使用缓存的语法，因此推理延迟与标准请求相当，开销最小。

1. **响应**-您会收到具有严格架构合规性的标准推理响应。

## 支持的 APIs 或功能
<a name="structured-output-supported-apis"></a>

您可以在以下 Amazon Bedrock 功能中使用结构化输出：

**Converse ConverseStream APIs** and — 使用结构化输出和 Converse ConverseStream APIs 进行对话推理。

**InvokeModel 和 InvokeModelWithResponseStream APIs** — 使用带 InvokeModel 和的结构化输出 InvokeModelWithResponseStream APIs 进行单圈推断。

**跨区域推理 — 在跨区域推理**中使用结构化输出，无需任何其他设置。

**Batch Inf** erence — 在批量推理中使用结构化输出，无需任何其他设置。

**注意**  
结构化输出与 Anthropic 模型的引文不兼容。如果您在使用结构化输出时启用引文，则模型将返回 400 错误。

## 支持的模型
<a name="structured-output-supported-models"></a>

对于精选的 Amazon Bedrock 无服务器模型，结构化输出通常适用于所有商业 AWS 区域。有关支持的型号列表，请参阅按功能划分的型号支持。

### 查看所有支持的型号
<a name="w2aac13c32c35c11b5b1"></a>

Anthropic  
+ Claude Haiku 4.5 () `anthropic.claude-haiku-4-5-20251001-v1:0`
+ Claude Sonnet 4.5 () `anthropic.claude-sonnet-4-5-20250929-v1:0`
+ Claude Opus 4.5 () `anthropic.claude-opus-4-5-20251101-v1:0`
+ Claude Opus 4.6 () `anthropic.claude-opus-4-6-v1`

Qwen  
+ Qwen3 235B A22B 2507 () `qwen.qwen3-235b-a22b-2507-v1:0`
+ Qwen3 32B（密集）() `qwen.qwen3-32b-v1:0`
+ Qwen3-Coder-30B-A3B-Instruct () `qwen.qwen3-coder-30b-a3b-v1:0`
+ Qwen3 Coder 480B A35B Instruct () `qwen.qwen3-coder-480b-a35b-v1:0`
+ Qwen3 Next 80B A3B () `qwen.qwen3-next-80b-a3b`
+ Qwen3 VL 235B A2B () `qwen.qwen3-vl-235b-a22b`

OpenAI  
+ gpt-oss-120b () `openai.gpt-oss-120b-1:0`
+ gpt-oss-20b () `openai.gpt-oss-20b-1:0`
+ GPT OSS Safegure 120B () `openai.gpt-oss-safeguard-120b`
+ GPT OSS Safeguard 20B () `openai.gpt-oss-safeguard-20b`

DeepSeek  
+ DeepSeek-V3.1 () `deepseek.v3-v1:0`

Google  
+ Gemma 3 12B IT () `google.gemma-3-12b-it`
+ Gemma 3 27B PT () `google.gemma-3-27b-it`

MiniMax  
+ MiniMax M2 (`minimax.minimax-m2`)

Mistral AI  
+ Magistral Small 2509 () `mistral.magistral-small-2509`
+ Ministral 3B () `mistral.ministral-3-3b-instruct`
+ Ministral 3 8B () `mistral.ministral-3-8b-instruct`
+ Ministral 14B 3.0 () `mistral.ministral-3-14b-instruct`
+ Mistral 大号 (3) `mistral.mistral-large-3-675b-instruct`
+ Voxtral Mini 3B 2507 () `mistral.voxtral-mini-3b-2507`
+ Voxtral Small 24B 2507 () `mistral.voxtral-small-24b-2507`

月球射击人工智能  
+ Kimi K2 Thinking () `moonshot.kimi-k2-thinking`

NVIDIA  
+ NVIDIA Nemotron Nano 12B v2 VL () BF16 `nvidia.nemotron-nano-12b-v2`
+ NVIDIA Nemotron Nano 9B v2 () `nvidia.nemotron-nano-9b-v2`

## 示例请求
<a name="structured-output-examples"></a>

### JSON 架构输出格式
<a name="structured-output-json-schema-examples"></a>

以下示例说明如何将 JSON 架构输出格式与结构化输出一起使用。

#### Converse API
<a name="json-schema-converse"></a>

##### 查看示例
<a name="w2aac13c32c35c13b3b5b3b1"></a>

```
{
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "text": "Given the following unstructured data, extract it into the provided structure."
        },
        {
          "text": "..."
        }
      ]
    }
  ],
  "outputConfig": {
    "textFormat": {
      "type": "json_schema",
      "structure": {
        "jsonSchema": {
          "schema": "{\"type\": \"object\", \"properties\": {\"title\": {\"type\": \"string\", \"description\": \"title\"}, \"summary\": {\"type\": \"string\", \"description\": \"summary\"}, \"next_steps\": {\"type\": \"string\", \"description\": \"next steps\"}}, \"required\": [\"title\", \"summary\", \"next_steps\"], \"additionalProperties\": false}",
          "name": "data_extraction",
          "description": "Extract structured data from unstructured text"
        }
      }
    }
  }
}
```

#### InvokeModel （人类 Claude）
<a name="json-schema-invokemodel-claude"></a>

##### 查看示例
<a name="w2aac13c32c35c13b3b7b3b1"></a>

```
{
  "anthropic_version": "bedrock-2023-05-31",
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "Given the following unstructured data, extract it into the provided structure."
        },
        {
          "type": "text",
          "text": "..."
        }
      ]
    }
  ],
  "max_tokens": 3000,
  "temperature": 1.0,
  "output_config": {
    "format": {
      "type": "json_schema",
      "schema": {
        "type": "object",
        "properties": {
          "title": {
            "type": "string",
            "description": "title"
          },
          "summary": {
            "type": "string",
            "description": "summary"
          },
          "next_steps": {
            "type": "string",
            "description": "next steps"
          }
        },
        "required": [
          "title",
          "summary",
          "next_steps"
        ],
        "additionalProperties": false
      }
    }
  }
}
```

#### InvokeModel （开放式重量款）
<a name="json-schema-invokemodel-openweight"></a>

##### 查看示例
<a name="w2aac13c32c35c13b3b9b3b1"></a>

```
{
  "messages": [
    {
      "role": "user",
      "content": "Given the following unstructured data, extract it into the provided structure."
    },
    {
      "role": "user",
      "content": "..."
    }
  ],
  "inferenceConfig": {
    "maxTokens": 3000,
    "temperature": 1.0
  },
  "response_format": {
    "json_schema": {
      "name": "summarizer",
      "schema": {
        "type": "object",
        "properties": {
          "title": {
            "type": "string",
            "description": "title"
          },
          "summary": {
            "type": "string",
            "description": "summary"
          },
          "next_steps": {
            "type": "string",
            "description": "next steps"
          }
        },
        "required": [
          "title",
          "summary",
          "next_steps"
        ],
        "additionalProperties": false
      }
    },
    "type": "json_schema"
  }
}
```

### 严格使用工具
<a name="structured-output-strict-tool-examples"></a>

以下示例展示了如何在使用工具时使用严格字段。

#### Converse API
<a name="strict-tool-converse"></a>

##### 查看示例
<a name="w2aac13c32c35c13b5b5b3b1"></a>

```
{
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "text": "What's the weather like in New York?"
        }
      ]
    }
  ],
  "toolConfig": {
    "tools": [
      {
        "toolSpec": {
          "name": "get_weather",
          "description": "Get the current weather for a specified location",
          "strict": true,
          "inputSchema": {
            "json": {
              "type": "object",
              "properties": {
                "location": {
                  "type": "string",
                  "description": "The city and state, e.g. San Francisco, CA"
                },
                "unit": {
                  "type": "string",
                  "enum": [
                    "fahrenheit",
                    "celsius"
                  ],
                  "description": "The temperature unit to use"
                }
              },
              "required": [
                "location",
                "unit"
              ]
            }
          }
        }
      }
    ]
  }
}
```

#### InvokeModel （人类 Claude）
<a name="strict-tool-invokemodel-claude"></a>

##### 查看示例
<a name="w2aac13c32c35c13b5b7b3b1"></a>

```
{
  "anthropic_version": "bedrock-2023-05-31",
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "What's the weather like in San Francisco?"
        }
      ]
    }
  ],
  "max_tokens": 3000,
  "temperature": 1.0,
  "tools": [
    {
      "name": "get_weather",
      "description": "Get the current weather for a specified location",
      "strict": true,
      "input_schema": {
        "type": "object",
        "properties": {
          "location": {
            "type": "string",
            "description": "The city and state, e.g. San Francisco, CA"
          },
          "unit": {
            "type": "string",
            "enum": [
              "fahrenheit",
              "celsius"
            ],
            "description": "The temperature unit to use"
          }
        },
        "required": [
          "location",
          "unit"
        ],
        "additionalProperties": false
      }
    }
  ]
}
```

#### InvokeModel （开放式重量款）
<a name="strict-tool-invokemodel-openweight"></a>

##### 查看示例
<a name="w2aac13c32c35c13b5b9b3b1"></a>

```
{
  "messages": [
    {
      "role": "user",
      "content": "What's the weather like in San Francisco?"
    }
  ],
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_weather",
        "description": "Get the current weather for a specified location",
        "strict": true,
        "parameters": {
          "type": "object",
          "properties": {
            "location": {
              "type": "string",
              "description": "The city and state, e.g. San Francisco, CA"
            },
            "unit": {
              "type": "string",
              "enum": [
                "fahrenheit",
                "celsius"
              ],
              "description": "The temperature unit to use"
            }
          },
          "required": [
            "location",
            "unit"
          ]
        }
      }
    }
  ],
  "tool_choice": "auto",
  "max_tokens": 2000,
  "temperature": 1.0
}
```

# 使用“计算机使用”工具完成 Amazon Bedrock 模型响应
<a name="computer-use"></a>

计算机使用是一项 Anthropic Claude 模型功能（测试版），仅在 Anthropic Claude 3.7 Sonnet 和 Claude 3.5 Sonnet v2 中可用。使用计算机使用时，Claude 可以帮助您通过基本的 GUI 操作自动执行任务。

**警告**  
根据服务条款的定义，计算机使用功能作为 “测试版服务” 提供给 AWS 您。它受您的协议和 AWS 服务条款 AWS 以及适用的 EULA 范本的约束。请注意，计算机使用 API 会带来与标准 API 功能或聊天界面不同的独特风险。使用计算机使用 API 与互联网进行交互时，这些风险会更加明显。为了最大限度地降低风险，请考虑采取如下预防措施：  
在具有最低权限的专用虚拟机或容器中操作计算机使用功能，以防止直接的系统攻击或事故。
避免授予计算机使用 API 访问敏感账户或数据的权限，以防止信息被盗。
将计算机使用 API 的互联网访问权限限制在必需的域内，以减少接触恶意内容。
请人工随时关注敏感任务（例如做出可能导致实际后果的决策）和任何需要肯定同意的操作（例如接受 Cookie、执行金融交易或同意服务条款），以确保进行适当的监督。
您允许 Claude 查看或访问的任何内容都可能覆盖指令或导致 Claude 犯错或执行意外操作。必须采取适当的预防措施，例如将 Claude 与敏感数据和操作隔离，包括避免与提示注入相关的风险。在启用或请求必要的权限以在您自己的产品中启用计算机使用功能之前，请告知终端用户任何相关风险，并酌情征得他们的同意。

计算机使用 API 提供了多种预定义的计算机使用工具（*computer\$120241022*、*bash\$120241022* 和 *text\$1editor\$120241022*）供您使用。然后，您可以根据您的请求创建提示，例如“向 Ben 发送一封包含我上次会议笔记的电子邮件”和屏幕截图（如果需要）。响应包含 JSON 格式的 `tool_use` 操作列表（例如，scroll\$1down、left\$1button\$1press、screenshot）。您的代码运行计算机操作并向 Claude 提供显示输出的屏幕截图（如果需要）。

Tools 参数已更新为接受多态工具类型；添加了一个新的 `tool.type` 属性来区分它们。`type` 是可选的；如果省略该属性，则假定该工具为自定义工具（以前是唯一支持的工具类型）。此外，还添加了一个新参数 `anthropic_beta`，且带有相应枚举值：`computer-use-2024-10-22`。只有使用此参数和枚举值发出的请求才能使用新的计算机使用工具。可以按如下方式指定此参数：`"anthropic_beta": ["computer-use-2024-10-22"] `。

要在 Anthropic Claude 3.5 Sonnet v2 中使用计算机，你可以使用 Converse API（C [onverse](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html) 或 [ConverseStream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ConverseStream.html)）。在 `additionalModelRequestFields` 字段中指定特定于计算机使用的字段。有关调用 Converse API 的一般信息，请参阅[使用 Converse API 操作进行对话](conversation-inference.md)。

可以将工具与基本推理运算（[InvokeModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html)或 [InvokeModelWithResponseStream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModelWithResponseStream.html)）一起使用。要查找您在请求正文中传递的推理参数，请参阅[Anthropic Claude Messages API](model-parameters-anthropic-claude-messages.md)。

有关更多信息，请参阅 Anthropic 文档中的[计算机使用（测试版）](https://docs.anthropic.com/en/docs/build-with-claude/computer-use)。

**Topics**
+ [代码示例](#computer-use-example-code)
+ [响应示例](#example-response)

## 代码示例
<a name="computer-use-example-code"></a>

以下代码演示了如何调用计算机使用 API。输入的是 AWS 控制台的图像。

```
with open('test_images/console.png', 'rb') as f:
        png = f.read()

    response = bedrock.converse(
        modelId='anthropic.claude-3-5-sonnet-20241022-v2:0',
        messages=[
            {
                'role': 'user',
                'content': [
                    {
                        'text': 'Go to the bedrock console'
                    },
                    {
                        'image': {
                            'format': 'png',
                            'source': {
                                'bytes': png
                            }
                        }
                    }
                ]
            }
        ],
        additionalModelRequestFields={
            "tools": [
                {
                    "type": "computer_20241022",
                    "name": "computer",
                    "display_height_px": 768,
                    "display_width_px": 1024,
                    "display_number": 0
                },
                {
                    "type": "bash_20241022",
                    "name": "bash",

                },
                {
                    "type": "text_editor_20241022",
                    "name": "str_replace_editor",
                }
            ],
            "anthropic_beta": ["computer-use-2024-10-22"]
        },
        toolConfig={
            'tools': [
                {
                    'toolSpec': {
                        'name': 'get_weather',
                        'inputSchema': {
                            'json': {
                                'type': 'object'
                            }
                        }
                    }
                }
            ]
        })

    print(json.dumps(response, indent=4))
```

## 响应示例
<a name="example-response"></a>

示例代码的输出如下。

```
{
   "id": "msg_bdrk_01Ch8g9MF3A9FTrmeywrwfMZ",
   "type": "message",
   "role": "assistant",
   "content": [
        {
            "type": "text",
            "text": "I can see from the screenshot that we're already in the AWS Console. To go to the Amazon Bedrock console specifically, I'll click on the Amazon Bedrock service from the \"Recently Visited\" section."
        },
        {
            "type": "tool_use",
            "id": "toolu_bdrk_013sAzs1gsda9wLrfD8bhYQ3",
            "name": "computer",
            "input": {
                "action": "screenshot"
            }
        }
   ],
   "stop_reason": "tool_use",
   "stop_sequence": null,
   "usage": {
       "input_tokens": 3710,
       "output_tokens": 97
   }
}
```

# 使用工具完成 Amazon Bedrock 模型响应
<a name="tool-use"></a>

您可以使用 Amazon Bedrock API 向模型授予访问一些工具的权限，这些工具可以帮助模型针对您发送给模型的消息生成响应。例如，您可能有一个聊天应用程序，支持用户查询某个电台播放的最受欢迎的歌曲。要回答关于最受欢迎的歌曲的请求，模型需要使用一个可以查询并返回歌曲信息的工具。

**注意**  
现在，您可以使用工具使用结构化输出。有关更多信息，请参阅[从模型中获取经过验证的 JSON 结果](structured-output.md)。

在 Amazon Bedrock 中，模型不会直接调用工具。相反，当您向模型发送消息时，您还需要提供一个或多个可能帮助模型生成响应的工具的定义。在这个示例中，您需要提供一个工具的定义，该工具可以返回指定电台上最受欢迎的歌曲。如果模型确定需要该工具来生成对消息的响应，则根据用于调用模型的 API，模型可以执行客户端调用，也可以让 Bedrock 使用服务器端工具调用该工具。让我们更详细地讨论这两个选项。

**客户端工具调用**

如果您使用响应 API、聊天完成 API、Converse API 或 InvokeModel API 来发送请求，则模型将使用客户端工具调用。这意味着在您的代码中，您可以代表模型调用该工具。在这个场景中，假设工具实现是一个 API。该工具也可以是数据库、Lambda 函数或其他软件。您可以决定如何实现工具。然后，您可以继续与模型进行对话，并提供包含工具结果的消息。最后，模型会为原始消息生成响应，其中包括您发送给模型的工具结果。

让我们定义将用于工具使用的工具。以下 Python 示例展示了如何使用在虚构的广播电台返回最受欢迎的歌曲的工具。

```
def get_most_popular_song(station_name: str) -> str:
    stations = {
        "Radio Free Mars": "Starman – David Bowie",
        "Neo Tokyo FM": "Plastic Love – Mariya Takeuchi",
        "Cloud Nine Radio": "Blinding Lights – The Weeknd",
    }
    return stations.get(station_name, "Unknown Station – No chart data available")
```

**将响应 API 用于客户端工具**

你可以使用 OpenAI 提供的[函数调用](https://platform.openai.com/docs/guides/function-calling)功能来调用这个工具。响应 API 是 OpenAI 的首选 API。以下是用于客户端工具的响应 API 的 Python 代码：

```
from openai import OpenAI
import json

client = OpenAI()

response = client.responses.create(
    model="oss-gpt-120b",
    input="What is the most popular song on Radio Free Mars?",
    tools=[
        {
            "type": "function",
            "name": "get_most_popular_song",
            "description": "Returns the most popular song on a radio station",
            "parameters": {
                "type": "object",
                "properties": {
                    "station_name": {
                        "type": "string",
                        "description": "Name of the radio station"
                    }
                },
                "required": ["station_name"]
            }
        }
    ]
)

if response.output and response.output[0].content:
    tool_call = response.output[0].content[0]
    args = json.loads(tool_call["arguments"])
    result = get_most_popular_song(args["station_name"])
    
    final_response = client.responses.create(
        model="oss-gpt-120b",
        input=[
            {
                "role": "tool",
                "tool_call_id": tool_call["id"],
                "content": result
            }
        ]
    )
    
    print(final_response.output_text)
```

**将 “聊天完成” API 用于客户端工具**

您也可以使用 “聊天完成” API。以下是使用聊天完成的 Python 代码：

```
    from openai import OpenAI
import json

client = OpenAI()

completion = client.chat.completions.create(
    model="oss-gpt-120b",
    messages=[{"role": "user", "content": "What is the most popular song on Neo Tokyo FM?"}],
    tools=[{
        "type": "function",
        "function": {
            "name": "get_most_popular_song",
            "description": "Returns the most popular song on a radio station",
            "parameters": {
                "type": "object",
                "properties": {
                   "station_name": {"type": "string", "description": "Name of the radio station"}
                },
                "required": ["station_name"]
            }
        }
    }]
)

message = completion.choices[0].message

if message.tool_calls:
    tool_call = message.tool_calls[0]
    args = json.loads(tool_call.function.arguments)
    result = get_most_popular_song(args["station_name"])

    followup = client.chat.completions.create(
        model="oss-gpt-120b",
        messages=[
            {"role": "user", "content": "What is the most popular song on Neo Tokyo FM?"},
            message,
            {"role": "tool", "tool_call_id": tool_call.id, "content": result}
        ]
    )

    print(followup.choices[0].message.content)
```

有关在响应中使用函数调用 API 和聊天完成 API 的更多详细信息，请参阅 OpenAI 中的[函数调用](https://platform.openai.com/docs/guides/function-calling)。

**将 Converse API 用于客户端工具**

您可以通过 [Converse API](https://docs.aws.amazon.com/bedrock/latest/userguide/conversation-inference.html) 让模型在对话中使用工具。以下 Python 示例展示了如何使用在虚构的广播电台返回最受欢迎的歌曲的工具。

```
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""Shows how to use tools with the Converse API and the Cohere Command R model."""

import logging
import json
import boto3
from botocore.exceptions import ClientError


class StationNotFoundError(Exception):
    """Raised when a radio station isn't found."""
    pass


logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)


def get_top_song(call_sign):
    """Returns the most popular song for the requested station.

    Args:
        call_sign (str): The call sign for the station for which you want
            the most popular song.

    Returns:
        response (json): The most popular song and artist.
    """
    song = ""
    artist = ""

    if call_sign == 'WZPZ':
        song = "Elemental Hotel"
        artist = "8 Storey Hike"
    else:
        raise StationNotFoundError(f"Station {call_sign} not found.")

    return song, artist


def generate_text(bedrock_client, model_id, tool_config, input_text):
    """Generates text using the supplied Amazon Bedrock model. If necessary,
    the function handles tool use requests and sends the result to the model.

    Args:
        bedrock_client: The Boto3 Bedrock runtime client.
        model_id (str): The Amazon Bedrock model ID.
        tool_config (dict): The tool configuration.
        input_text (str): The input text.

    Returns:
        Nothing.
    """
    logger.info("Generating text with model %s", model_id)

    # Create the initial message from the user input.
    messages = [{"role": "user",
                 "content": [{"text": input_text}]}]

    response = bedrock_client.converse(modelId=model_id,
                                       messages=messages,
                                       toolConfig=tool_config)

    output_message = response['output']['message']
    messages.append(output_message)

    stop_reason = response['stopReason']

    if stop_reason == 'tool_use':
        # Tool use requested. Call the tool and send the result to the model.
        tool_requests = response['output']['message']['content']

        for tool_request in tool_requests:
            if 'toolUse' in tool_request:
                tool = tool_request['toolUse']
                logger.info("Requesting tool %s. Request: %s",
                            tool['name'], tool['toolUseId'])

                if tool['name'] == 'top_song':
                    tool_result = {}
                    try:
                        song, artist = get_top_song(tool['input']['sign'])
                        tool_result = {"toolUseId": tool['toolUseId'],
                                       "content": [{"json": {"song": song, "artist": artist}}]}
                    except StationNotFoundError as err:
                        tool_result = {"toolUseId": tool['toolUseId'],
                                       "content": [{"text": err.args[0]}],
                                       "status": 'error'}

                    tool_result_message = {"role": "user",
                                           "content": [{"toolResult": tool_result}]}
                    messages.append(tool_result_message)

        # Send the tool result to the model.
        response = bedrock_client.converse(modelId=model_id,
                                           messages=messages,
                                           toolConfig=tool_config)

        output_message = response['output']['message']

    # print the final response from the model.
    for content in output_message['content']:
        print(json.dumps(content, indent=4))


def main():
    """Entrypoint for tool use example."""
    logging.basicConfig(level=logging.INFO,
                        format="%(levelname)s: %(message)s")

    model_id = "cohere.command-r-v1:0"
    input_text = "What is the most popular song on WZPZ?"

    tool_config = {
        "tools": [
            {
                "toolSpec": {
                    "name": "top_song",
                    "description": "Get the most popular song played on a radio station.",
                    "inputSchema": {
                        "json": {
                            "type": "object",
                            "properties": {
                                "sign": {
                                    "type": "string",
                                    "description": "The call sign for the radio station for which you want the most popular song. Example calls signs are WZPZ, and WKRP."
                                }
                            },
                            "required": ["sign"]
                        }
                    }
                }
            }
        ]
    }

    bedrock_client = boto3.client(service_name='bedrock-runtime')

    try:
        print(f"Question: {input_text}")
        generate_text(bedrock_client, model_id, tool_config, input_text)
    except ClientError as err:
        message = err.response['Error']['Message']
        logger.error("A client error occurred: %s", message)
        print(f"A client error occured: {message}")
    else:
        print(f"Finished generating text with model {model_id}.")


if __name__ == "__main__":
    main()
```

**使用 Invoke APIs 进行客户端工具使用**

可以将工具与基本推理运算（[InvokeModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html)或 [InvokeModelWithResponseStream](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModelWithResponseStream.html)）一起使用。要查找您在请求正文中传递的推理参数，请参阅您要使用的模型的[推理参数](https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters.html)。

**服务器端工具调用**

如果您使用 Responses API 来调用模型，那么除了我们之前讨论的客户端工具调用之外，它还可以使用服务器端工具调用。服务器端工具调用是一种机制，在这种机制中，工具（APIs、函数、工作流程）是在可信的后端环境中执行的，而不是在客户端上执行的。这提高了应用程序的安全性、可靠性和治理状况。在 Amazon Bedrock 执行实现工具使用的 Lambda 函数之前，它会确保 Lambda 函数与调用该函数的应用程序具有相同的 IAM 策略。由于 Amazon Bedrock 推动工具的执行，客户可以专注于实现其业务逻辑，而不是添加工具功能。Amazon Bedrock 还支持最高的治理标准，例如符合 ISO、SOC 和 HIPAA 资格。客户可以提交自己的自定义 Lambda 函数来运行该工具，也可以使用现有的预定义工具，例如备注和任务。使用 Responses API 的服务器端工具从 OpenAI 的 GPT OSS 20B/120B 型号开始，其他模型的支持即将推出。您可以使用模型 API 来发现可用于响应 API 的可用模型。有关响应 API 的更多详细信息，请参阅[使用 Open APIs AI 生成响应](https://docs.aws.amazon.com/bedrock/latest/userguide/bedrock-mantle.html)。

您可以在 Amazon Bedrock 上使用两种类型的工具：使用 Lambda 的自定义工具或 Bedrock 支持的预定义工具。在本节中，我们将介绍如何使用响应 API 创建自定义 Lambda 工具。让我们详细讨论两者。

**在响应 API 中使用 Lambda 的自定义工具**

通过在 Bedrock 中将 Lambda 函数用作自定义工具，您可以通过将自定义 AWS Lambda 函数集成为工具来扩展代理的功能。这使您能够创建无服务器、可扩展的工具，AI 助手和其他应用程序可以通过模型上下文协议 (MCP) 调用这些工具。以下是此功能的优点：
+ 扩展功能：添加自定义业务逻辑、API 集成或数据处理功能。
+ 安全运行工具：Lambda 允许工具访问 VPC 内的资源，而无需授予完整的 VPC 访问权限。
+ 无服务器架构：无需基础设施管理，Lambda 会自动处理扩展。
+ 成本效益：仅为执行时间付费，不为闲置资源付费。
+ 易于集成：Lambda 函数与内置工具无缝显示。

要让 Amazon Bedrock 中的模型使用工具完成对消息的响应，您需要将消息以及一个或多个工具的定义发送给模型。根据应用程序的提示，如果模型确定其中一个工具可以帮助生成响应，则它会返回请求 Bedrock 使用该工具并将工具结果发送回模型。然后，模型会使用这些结果生成对原始消息的响应。

以下步骤展示了如何使用带有[响应 API](https://docs.aws.amazon.com/bedrock/latest/userguide/bedrock-mantle.html) 的工具。

**工作原理**

1. **Lambda 函数**：创建实现 MCP 协议的 Lambda 函数

1. **工具发现**：Bedrock 调用你的 Lambda 函数来发现可用的工具

1. **工具注册**：您的工具已在 Bedrock 中注册

1. **工具执行**：当代理请求您的工具时，Bedrock 会调用您的 Lambda 函数

1. **响应处理**：结果通过标准接口返回给代理

**第 1 步：定义 Lambda 函数以获取最受欢迎的歌曲**

创建一个实现 MCP 协议的 Lambda 函数。下面是一个简单的 Python 示例：

```
import json

def lambda_handler(event, context):
    # Parse JSON-RPC request
    method = event.get('method')
    params = event.get('params', {})
    request_id = event.get('id')
    
    if method == 'tools/list':
        return {
            "jsonrpc": "2.0",
            "id": request_id,
            "result": {
                "tools": [
                    {
                        "name": "my_custom_tool",
                        "description": "My custom business logic tool",
                        "inputSchema": {
                            "type": "object",
                            "properties": {
                                "input": {
                                    "type": "string",
                                    "description": "Input text to process"
                                }
                            },
                            "required": ["input"]
                        }
                    }
                ]
            }
        }
    elif method == 'tools/call':
        tool_name = params.get('name')
        arguments = params.get('arguments', {})
        
        if tool_name == 'my_custom_tool':
            # Your custom logic here
            result = f"Processed: {arguments.get('input', '')}"
            return {
                "jsonrpc": "2.0",
                "id": request_id,
                "result": {
                    "content": [
                        {
                            "type": "text",
                            "text": result
                        }
                    ]
                }
            }
    
    # Error response for unsupported methods
    return {
        "jsonrpc": "2.0",
        "id": request_id,
        "error": {
            "code": -32601,
            "message": "Method not found"
        }
    }
```

**步骤 2：部署 Lambda 函数**

接下来，使用您的 IAM 角色部署此 Lambda 函数以获取 ARN。[您可以在此处阅读有关部署 Lambda 函数的更多信息。](https://docs.aws.amazon.com/lambda/latest/dg/getting-started.html)

```
# Example using AWS CLI
aws lambda create-function \
  --function-name my-custom-tool \
  --runtime python3.14 \
  --role arn:aws:iam::YOUR-ACCOUNT:role/lambda-execution-role \
  --handler lambda_function.lambda_handler \
  --zip-file fileb://function.zip
```

假设你的 ARN 是：`arn:aws:lambda:us-west-2:123456789012:function:my-custom-tool`

**第 3 步：在推理请求中定义消息和工具定义**

要发送消息和工具定义，您可以使用[响应 API](https://docs.aws.amazon.com/bedrock/latest/userguide/bedrock-mantle.html) 操作。Amazon Bedrock 使用响应 API 的[连接器和远程 MCP 服务器功能](https://platform.openai.com/docs/guides/tools-connectors-mcp)来提供工具使用功能。该工具的定义是您在 mcp 请求参数中传递给创建操作的 JSON 架构。在响应连接器 API 的`connector_id`字段中，您可以传入您在上一步中创建的 Lambda ARN。您无需提供授权证书，因为 Bedrock 使用与调用模型的应用程序相同的 IAM 角色和策略。以下是一个工具的示例架构，该工具可以获取电台播放的最受欢迎的歌曲。

```
from openai import OpenAI

client = OpenAI()

resp = client.responses.create(
    model="oss-gpt-120b",
    tools=[
        {
            "type": "mcp",
            "server_label": "xamzn_arn",
            "connector_id": "arn:aws:lambda:us-west-2:123456789012:function:my-custom-tool",
            "require_approval": "never",
        },
    ],
    input="My custom prompt.",
)

print(resp.output_text)
```

**第 4 步：Bedrock 调用该工具并将响应传回模型**

支持[响应 API](https://platform.openai.com/docs/api-reference/responses/create) 的模型中提供了使用连接器工具的功能。[在此处](https://docs.aws.amazon.com/bedrock/latest/userguide/bedrock-mantle.html)查看哪些工具支持您的模型。当您使用 Responses API 使用工具时，您只需为导入工具定义或调用工具时使用的[令牌](https://platform.openai.com/docs/pricing)付费。每次调用工具不涉及任何额外费用。

当您在`tools`参数中指定 Lambda 函数时，API 将尝试从服务器获取工具列表。如果成功检索工具列表，则模型响应`mcp_list_tools`输出中将出现一个新的输出项目。此对象的`tools`属性将显示成功导入的工具。一旦模型可以访问这些工具定义，它就可以根据模型的上下文选择调用它们。当模型决定调用 Lambda 工具时，API 将向 Lambda 函数发出请求，要求其调用该工具，并将其输出放入模型的上下文中。你可以在 [OpenAI](https://platform.openai.com/docs/guides/tools-connectors-mcp?quickstart-panels=connector) 文档中阅读更多关于列表工具和调用工具的信息。请注意，您的 Lambda 函数必须具有与在 Bedrock 中调用模型的应用程序相同的 IAM 角色和策略，否则 Lambda 函数将失败。以下是错误定义。

```
{
    "jsonrpc": "2.0",
    "id": 1,
    "error": {
        "code": -32000,
        "message": "Tool execution failed",
        "data": "Additional error details"
    }
}
```

**在响应 API 中使用 AWS 提供的工具**

Bedrock 中提供了两个 AWS 提供的工具：记笔记功能（笔记工具）和任务管理（任务工具）。让我们详细介绍一下这两个。

**备注工具概述**

该`notes`工具允许您在同一个对话会话中存储和检索键值对。这提供了一种简单的记忆机制，用于维护多个交互的上下文。密钥是区分大小写的字符串，对密钥长度或命名约定没有限制。系统会覆盖同一个密钥的先前值。值存储为字符串（JSON URLs 等），并且在工具级别没有大小限制。价值观在整个对话会话中都保持不变。记忆仅限于当前对话。

**参数**


| 参数 | Type | 必需 | 描述 | 
| --- | --- | --- | --- | 
| operation | 字符串 | 是 | 要执行的操作："store"或 "recall" | 
| key | 字符串 | 是 | 内存项目的密钥标识符 | 
| value | 字符串 | 有条件 | 要存储的值（仅在"store"操作时才需要） | 

**有效操作**
+ **`store`**: 将键值对保存到内存
+ **`recall`**: 通过键检索值

你可以使用任何一种自然语言（例如 “记住我最喜欢的颜色是蓝色”、“关于我最喜欢的颜色，我跟你说了什么？” ，“存储我更喜欢早间会议的事实”、“回想一下我所说的关于会议偏好的话”），或者你可以在提示中使用直接工具呼叫（“使用备忘工具将我的电子邮件存储为 john@example.com”，“查看备忘录中的电子邮件地址”）。

**任务工具概述**

该`tasks`工具提供了一个 Last-In-First-Out（LIFO）堆栈，用于管理对话会话中的任务。这使您可以将任务推送到堆栈上，然后以相反的顺序弹出它们，非常适合管理嵌套工作流程、临时提醒或分层任务管理。任务会持续到整个对话会话中。堆栈状态在多次交互中保持不变。记忆仅限于当前对话。


| 参数 | Type | 必需 | 描述 | 
| --- | --- | --- | --- | 
| operation | 字符串 | 是 | 要执行的操作："push"或 "pop" | 
| description | 字符串 | 有条件 | 任务项的描述（仅在"push"操作时为必填项） | 
| summary | 字符串 | 否 | 有关任务项的可选摘要（仅用于"push"操作） | 

你可以使用自然语言调用任务工具（例如 “添加任务以查看预算”、“推送提醒给客户打电话”、“我需要做的下一个任务是什么？”） ，“弹出最新的任务”、“从我的堆栈中获取最新任务”），或者你可以直接在提示中调用该工具（“使用任务工具推送'完成演示文稿'”、“从堆栈中弹出任务”、“将'安排会议'添加到我的任务列表”）。

## 服务器端工具使用与 Gateway 集成 AgentCore
<a name="tool-use-agentcore-gateway"></a>

Amazon Bedrock 现在支持 [AgentCore Gateway](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/gateway.html) 作为调用集成类型的服务器端工具。此功能允许您将模型直接连接到 AgentCore 网关端点，从而实现对通过网关基础设施管理的工具的无缝访问。

 AgentCore 网关集成遵循与 Lambda 函数集成的相同模式，但有一个关键区别。

**Lambda 集成：**
+ 使用 Lambda 函数 ARNs
+ 直接调用 AWS Lambda 函数

**AgentCore 网关集成：**
+ 使用 AgentCore 网关 ARNs
+ 通过 AgentCore 网关基础设施路由工具呼叫
+ 提供集中式工具管理和发现

### 配置
<a name="agentcore-gateway-configuration"></a>

**请求结构**

将 AgentCore Gateway 配置为工具源时，请在响应 API 请求中使用`tools`数组中的以下结构。

```
{
  "type":"mcp",
  "server_label":"agentcore_tools",
  "connector_id":"arn:aws:bedrock-agentcore:us-west-2:342789630635:gateway/agentcore-intro-gateway-v2-swvq44sovp",
  "server_description":"AgentCore Gateway providing custom tools",
  "require_approval":"never"
}
```

**参数**


| 参数 | Type | 必需 | 描述 | 
| --- | --- | --- | --- | 
| type | 字符串 | 是 | 必须设置为 mcp | 
| server\$1label | 字符串 | 是 | 您的请求中此工具连接器的唯一标识符 | 
| connector\$1id | 字符串 | 是 | 您的网关的 ARN AgentCore  | 
| server\$1description | 字符串 | 否 | 该网关提供的工具的可读描述 | 
| require\$1approval | 字符串 | 是 | 字段必须是 "never" | 

**完整请求示例**

```
{
  "model":"openai.gpt-oss-120b",
  "stream":true,
  "background":false,
  "store":false,
  "tools": [
    {
      "type":"mcp",
      "server_label":"agentcore_tools",
      "connector_id":"arn:aws:bedrock-agentcore:us-west-2:342789630635:gateway/agentcore-intro-gateway-v2-swvq44sovp",
      "server_description":"AgentCore Gateway providing custom tools",
      "require_approval":"never"
    }
  ],
  "input": [
    {
      "type":"message",
      "role":"user",
      "content": [
        {
          "type":"input_text",
          "text":"What is the weather in Seattle?"
        }
      ]
    }
  ]
}
```

### 先决条件
<a name="agentcore-gateway-prerequisites"></a>

在使用 AgentCore 网关集成之前，请确保您已具备以下条件：

1. 使用已配置@@ **的 AgentCore 目标（Lambda 函数、API 网关阶段、OpenAPI 架构或 MCP 服务器）创建**了网关

1. **已配置 IAM 权限**，允许您的 Bedrock 服务角色调用网关。请注意，Bedrock 仅支持采用 IAM 身份验证的网关。

1. 格式正确的 **Gateway ARN**

### AgentCore 网关集成的好处
<a name="agentcore-gateway-benefits"></a>
+ **集中式工具管理**：通过单个网关端点管理所有工具
+ **工具发现**：代理可以通过网关动态发现可用工具
+ **安全**：通过 IAM 和网关策略进行内置身份验证和授权
+ **可观察性**：全面监控和记录工具调用
+ **灵活性**：支持多种目标类型（Lambda、API Gateway、OpenAPI、MCP 服务器）

### IAM 权限
<a name="agentcore-gateway-iam"></a>

你的 Bedrock 执行角色需要权限才能调用 AgentCore 网关：

```
{
  "Version": "2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "bedrock-agentcore:InvokeGateway"
      ],
      "Resource": "arn:aws:bedrock-agentcore:us-west-2:342789630635:gateway/agentcore-intro-gateway-v2-swvq44sovp"
    }
  ]
}
```

### 后续步骤
<a name="agentcore-gateway-next-steps"></a>
+ 了解有关[创建 AgentCore 网关](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/gateway-create.html)的更多信息
+ 探索[网关目标类型](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/gateway-targets.html)
+ 查看[网关安全最佳实践](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/gateway-security.html)