

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

# 在 Amazon Bedrock 中使用重排器模型
<a name="rerank-use"></a>

您可以直接使用重排器模型，也可以在知识库查询期间检索结果时使用该模型。选择与您的首选方法对应的选项卡，然后按照以下步骤操作：

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

您不能直接在中使用重新排名模型 AWS 管理控制台，但您可以通过执行以下操作在查询知识库时使用重新排名模型：

1. 在查询知识库时，请选择 ![Icon showing three horizontal sliders at different positions for adjusting settings.](http://docs.aws.amazon.com/zh_cn/bedrock/latest/userguide/images/icons/configurations.png) 图标打开**配置**窗格。

1. 展开**重排**部分。

1. 选择**选择模型**并选择一个重排器模型。

1. 如果 Amazon Bedrock 知识库服务角色缺少[使用重排器模型的权限](rerank-prereq.md)，请选择**更新服务角色**以使用合适的权限修改该角色。

1. （可选）在**其他重排选项**部分，根据需要修改所有选项。

1. 输入新提示并选择**运行**。响应是应用重排器模型后的结果。

有关执行知识库查询的更多详细说明，请参阅[查询知识库并检索数据](kb-test-retrieve.md)和[根据检索到的数据查询知识库并生成响应](kb-test-retrieve-generate.md)。

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

有关在知识库查询期间使用重排器模型的说明，请参阅[查询知识库并检索数据](kb-test-retrieve.md)和[根据检索到的数据查询知识库并生成响应](kb-test-retrieve-generate.md)。

要直接将重排器模型与 Amazon Bedrock API 结合使用，请使用 [Amazon Bedrock 代理运行时端点](https://docs.aws.amazon.com/general/latest/gr/bedrock.html#bra-rt)发送[重排](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_Rerank.html)请求。

以下字段是必填字段：


****  

| 字段 | Basic description | 
| --- | --- | 
| 查询 | 一个[RerankQuery](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_RerankQuery.html)对象的数组。请将 TEXT 指定为 type，并在 textQuery 字段中提供查询。 | 
| sources | 要提交给重新排序模型的[RerankSource](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_RerankSource.html)对象数组。对于每个RerankSource，请指定INLINE为，type并在inlineDocumentSource字段中包含一个[RerankDocument](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_RerankDocument.html)对象。有关 RerankDocument 的详细信息，请参阅下文。 | 
| rerankingConfiguration | 添加要使用的重排模型的 Amazon 资源名称（ARN）、重排后要返回的结果数量以及模型的推理配置（可选）。您需要以键值对的格式指定额外的模型配置。有关更多信息，请参阅 Cohere 文档网站上的[重排](https://docs.cohere.com/reference/rerank)。 | 

以下字段是可选字段：


****  

| 字段 | 使用案例 | 
| --- | --- | 
| nextToken | 上一个响应中返回的一个词元，您可以添加该词元以提供下一批结果。 | 

添加的 `RerankSource` 对象的格式取决于文档的格式。要查看其他 `RerankSource` 类型的格式，请选择与文档的格式对应的选项卡：

------
#### [ String ]

如果文档是字符串，则将[RerankDocument](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_RerankDocument.html)对象`type`字段的值指定为，`TEXT`并将文档包含在`text`字段中。例如：

```
{
    "inlineDocumentSource": {
        "textDocument": {
            "text": "string"
        },
        "type": "TEXT"
    },
    "type": "INLINE"
}
```

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

如果文档是 JSON 对象，则将该[RerankDocument](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_RerankDocument.html)对象中该`type`字段的值指定为，`JSON`并将该文档包含在`jsonDocument`字段中。例如：

```
{
    "inlineDocumentSource": {
        "jsonDocument": JSON value,
        "type": "JSON"
    },
    "type": "INLINE"
}
```

------

对您的`Rerank`请求的响应会返回该`results`字段中的[RerankResult](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_RerankResult.html)对象列表。每个对象都包含以下字段：
+ `document`：包含您提交的文档的相关信息。
+ `relevanceScore`：文档的相关性分数，由重排模型分配。
+ `index`：表示文档相对于列表中其他文档的排名。分数越低，排序位置越靠前。

如果要显示的结果过多，则响应会在 `nextToken` 字段中返回一个值。在这种情况下，为了查看下一批结果，请在后续请求中添加该词元。

**代码示例**

以下示例展示了如何使用 AWS 软件开发工具包调用 Rerank API。

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

```
import boto3

client = boto3.client('bedrock-agent-runtime', region_name='us-east-1')
response = client.rerank(
    queries=[{
        'type': 'TEXT',
        'textQuery': {'text': 'What is Amazon Bedrock?'}
    }],
    sources=[
        {
            'type': 'INLINE',
            'inlineDocumentSource': {
                'type': 'TEXT',
                'textDocument': {'text': 'Amazon Bedrock is a fully managed service for foundation models.'}
            }
        },
        {
            'type': 'INLINE',
            'inlineDocumentSource': {
                'type': 'TEXT',
                'textDocument': {'text': 'Amazon S3 is an object storage service.'}
            }
        }
    ],
    rerankingConfiguration={
        'type': 'BEDROCK_RERANKING_MODEL',
        'bedrockRerankingConfiguration': {
            'modelConfiguration': {
                'modelArn': 'arn:aws:bedrock:us-east-1::foundation-model/cohere.rerank-v3-5:0'
            },
            'numberOfResults': 2
        }
    }
)
for result in response['results']:
    print(f'Index: {result["index"]}, Score: {result["relevanceScore"]}')
```

------
#### [ Node.js ]

```
import { BedrockAgentRuntimeClient, RerankCommand } from "@aws-sdk/client-bedrock-agent-runtime";

const client = new BedrockAgentRuntimeClient({ region: "us-east-1" });
const response = await client.send(new RerankCommand({
    queries: [{
        type: "TEXT",
        textQuery: { text: "What is Amazon Bedrock?" }
    }],
    sources: [
        {
            type: "INLINE",
            inlineDocumentSource: {
                type: "TEXT",
                textDocument: { text: "Amazon Bedrock is a fully managed service for foundation models." }
            }
        },
        {
            type: "INLINE",
            inlineDocumentSource: {
                type: "TEXT",
                textDocument: { text: "Amazon S3 is an object storage service." }
            }
        }
    ],
    rerankingConfiguration: {
        type: "BEDROCK_RERANKING_MODEL",
        bedrockRerankingConfiguration: {
            modelConfiguration: {
                modelArn: "arn:aws:bedrock:us-east-1::foundation-model/cohere.rerank-v3-5:0"
            },
            numberOfResults: 2
        }
    }
}));
for (const result of response.results) {
    console.log(`Index: ${result.index}, Score: ${result.relevanceScore}`);
}
```

------

------