

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

# 使用匡威 API 进行推理
<a name="conversation-inference"></a>

Converse API 仅在`bedrock-runtime`终端节点上可用。

您可以使用 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 示例匡威 API 示例（已移动）](conversation-inference-examples.md)
+ 各种语言和模型 – [使用 Amazon Bedrock Runtime 的代码示例 AWS 软件开发工具包](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)

## 使用 Converse API
<a name="converse-api-usage"></a>

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

### 请求
<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** – 用于指定所有模型通用的推理参数。推理参数会影响响应的生成。
  + 其@@ **他 ModelRequestFields**-用于指定特定于运行推理的模型的推理参数。
  + **promptVariables** –（如果您使用提示管理器中的提示）使用此字段定义提示中要填写的变量以及填充变量的值。
+ 使用以下字段自定义响应的返回方式：
  + **guardrailConfig** – 使用此字段指定应用到整个提示的护栏。
  + **toolConfig** – 使用此字段指定用于帮助模型生成响应的工具。
  + 其@@ **他 ModelResponseFieldPaths**-使用此字段指定要作为 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)中，您可以指定以下字段之一（要查看哪些模型支持哪些模块，请查看[模型一览](model-cards.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}
```

#### 额外的 ModelRequestFields
<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 {{{{genre}}}} playlist consisting of the following number of songs: {{{{number}}}}.**。提示的 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": {
         "text": "pop"
      },
      "number": {
         "text": "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)。

#### 额外的 ModelResponseFieldPaths
<a name="converse-additional-model-response-field-paths"></a>

您可以在 `additionalModelResponseFieldPaths` 字段中指定其他模型参数的路径，如以下示例所示。

```
[ "/stop_sequence" ]
```

API 会返回您在 `additionalModelResponseFields` 字段中请求的其他字段。

#### requestMetadata
<a name="converse-request-metadata"></a>

该`requestMetadata`字段映射到一个包含键值标签的 JSON 对象，这些标签与请求一起记录在模型调用日志中。您可以使用请求元数据按团队、应用程序、环境或每次调用不同的任何其他维度筛选和聚合日志。

同样的功能在 HTTP 标头上[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)通过 `X-Amzn-Bedrock-Request-Metadata` HTTP 标头可用。有关支持的 API、限制以及请求元数据在调用日志中的显示方式的详细信息，请参阅[Per-request 元数据标记](cost-mgmt-request-metadata.md)。

#### 服务等级
<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`）。

#### 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)，则在使用情况字段中，`cacheReadInputTokens` 和 `cacheWriteInputTokens` 会分别指明对缓存读取和写入的词元总数。

如果您使用了[服务层](#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="converse-api-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()
```

------