

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

# 从知识库检索文档的内容
<a name="kb-test-get-document-content"></a>

该 `GetDocumentContent` API 允许您检索已导入亚马逊 Bedrock 知识库的文档内容。此 API 返回一个预签名的 URL，该网址为下载或查看文档的原始内容或提取的内容提供临时、安全的访问权限。

这在你想做时很有用：
+ 访问 `Retrieve` API 响应中引用的源文档
+ 从知识库下载原始文件（PDF、Word、HTML 等）
+ 检索 JSON 格式的文档的 extracted/parsed 文本内容
+ 构建允许用户查看或下载 `Retrieve` API 响应背后的源文档的应用程序

## 工作原理
<a name="kb-get-doc-content-how-it-works"></a>

1. 您`GetDocumentContent`使用知识库 ID、数据源 ID 和文档 ID 进行通话。

1. 该服务会验证您的访问权限（包括知识库中配置的任何 ACL-based 访问控制）。

1. API 返回预签名的网址和文档的 MIME 类型。

1. 您可以使用预签名 URL 下载文档内容。该 URL 将在 ** 5 分钟后过期**。

## IAM 权限
<a name="kb-get-doc-content-iam"></a>

调用既`GetDocumentContent``bedrock:Retrieve`需要对知识库资源进行 `bedrock:GetDocumentContent` IAM 操作。这是因为在返回文档内容之前，API 会在内部验证检索级别的访问权限。确保您的 IAM 政策包括这两项操作：

```
{
    "Effect": "Allow",
    "Action": [
        "bedrock:Retrieve",
        "bedrock:GetDocumentContent"
    ],
    "Resource": "arn:aws:bedrock:{{region}}:{{account-id}}:knowledge-base/{{kb-id}}"
}
```

## 用法示例
<a name="kb-get-doc-content-examples"></a>

### 启用 ACL 的同一个账户
<a name="kb-get-doc-content-same-account-acl"></a>

当您的知识库启用 ACL-based 访问控制后，请传递用户`userContext`的身份以确保进行文档级权限检查：

```
import boto3
import requests

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

# Step 1: Retrieve relevant documents
retrieve_response = client.retrieve(
    knowledgeBaseId='{{KBID1234567}}',
    retrievalQuery={'text': 'What is the refund policy?'}
)

# Step 2: Get the full document content for the top result
result = retrieve_response['retrievalResults'][0]

doc_response = client.get_document_content(
    knowledgeBaseId='{{KBID1234567}}',
    dataSourceId=result['metadata']['_data_source_id'],
    documentId=result['documentId'],
    outputFormat='RAW',
    userContext={
        'userId': '{{user-email}}',
        'groups': [
            {'id': '{{group-engineering}}'},
            {'id': '{{group-project-alpha}}'}
        ]
    }
)

# Step 3: Download the document
download = requests.get(doc_response['presignedUrl'])
with open('document.pdf', 'wb') as f:
    f.write(download.content)
```

### 未启用 ACL 的同一个账户
<a name="kb-get-doc-content-same-account-no-acl"></a>

如果未配置 ACL，请省略`userContext`：

```
import boto3
import requests

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

# Step 1: Retrieve relevant documents
retrieve_response = client.retrieve(
    knowledgeBaseId='{{KBID1234567}}',
    retrievalQuery={'text': 'What is the refund policy?'}
)

# Step 2: Get the full document content
result = retrieve_response['retrievalResults'][0]

doc_response = client.get_document_content(
    knowledgeBaseId='{{KBID1234567}}',
    dataSourceId=result['metadata']['_data_source_id'],
    documentId=result['documentId'],
    outputFormat='RAW'
)

# Step 3: Download the document
download = requests.get(doc_response['presignedUrl'])
with open('document.pdf', 'wb') as f:
    f.write(download.content)
```

### Cross-account 未启用 ACL
<a name="kb-get-doc-content-cross-account"></a>

要进行跨账户访问，知识库所有者必须将**资源策略附加**到其知识库中，以授予调用者的账户权限。然后，呼叫者使用完整的知识库 ARN。

**第 1 步：知识库所有者将资源策略附加到知识库 **

拥有知识库（例如`999999999999`）的账户必须附加资源策略，授予呼叫者账户（例如`111111111111`）访问权限：

```
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "111111111111"
            },
            "Action": [
                "bedrock:Retrieve",
                "bedrock:GetDocumentContent"
            ],
            "Resource": "arn:aws:bedrock:us-east-1:999999999999:knowledge-base/{{KBID1234567}}"
        }
    ]
}
```

这是通过 `PutKnowledgeBaseResourcePolicy` API 或通过亚马逊 Bedrock 控制台完成的。

**第 2 步：来电者账户拥有调用 API 的 IAM 权限 **

调用者的 IAM role/user （账户内`111111111111`）需要一个 IAM 策略，允许对跨账户 KB ARN 进行操作：

```
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "bedrock:Retrieve",
                "bedrock:GetDocumentContent"
            ],
            "Resource": "arn:aws:bedrock:us-east-1:999999999999:knowledge-base/{{KBID1234567}}"
        }
    ]
}
```

**第 3 步：使用完整的 KB ARN 调用 API **

```
import boto3
import requests

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

CROSS_ACCOUNT_KB_ARN = 'arn:aws:bedrock:us-east-1:999999999999:knowledge-base/{{KBID1234567}}'

# Step 1: Retrieve relevant documents using the KB ARN
retrieve_response = client.retrieve(
    knowledgeBaseId=CROSS_ACCOUNT_KB_ARN,
    retrievalQuery={'text': 'What is the refund policy?'}
)

# Step 2: Get the full document content using the same ARN
result = retrieve_response['retrievalResults'][0]

doc_response = client.get_document_content(
    knowledgeBaseId=CROSS_ACCOUNT_KB_ARN,
    dataSourceId=result['metadata']['_data_source_id'],
    documentId=result['documentId'],
    outputFormat='RAW'
)

# Step 3: Download the document
download = requests.get(doc_response['presignedUrl'])
with open('document.pdf', 'wb') as f:
    f.write(download.content)
```

资源策略（知识库所有者方面）和 IAM 政策（调用方方面）都必须到位。如果缺少任一项，则拒绝访问。

## 检索原生多模态知识库的响应
<a name="kb-get-doc-content-native-multimodal"></a>

当您的知识库使用原生多模态嵌入模型时，[Retrieve](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_Retrieve.html)响应会返回元数据，您可以使用这些元数据来定位匹配的图像或音频或视频文件的特定片段。有关原生多模态处理的更多信息，请参阅[原生多模态处理](kb-managed-native-multimodal.md)。

**注意**  
我们建议您使用`Retrieve`响应中`documentId`返回的调`GetDocumentContent`用来获取多模态内容，如前面的示例所示。`Retrieve`响应中的`content`字段为访问图像、音频或视频信息提供了另一种方式。

### 多模态元数据字段
<a name="kb-get-doc-content-native-multimodal-metadata"></a>

来自原生多模态知识库的结果包括以下元数据字段：
+ `_file_type`— 生成区块的源内容的模式。值为 `AUDIO`、`VIDEO` 或 `IMAGE`。您可以在此字段上进行筛选，仅返回特定模态的结果。有关筛选的更多信息，请参阅 [手动元数据筛选](kb-managed-test-config.md#kb-managed-test-config-filters)。
+ `_media_start_time_ms`和 `_media_end_time_ms` — 对于音频和视频块，该区块所代表的文件段的开始和结束时间，以毫秒为单位。

### 图像结果
<a name="kb-get-doc-content-native-multimodal-images"></a>

对于图像结果，[Retrieve](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_Retrieve.html)响应将`byteContent`字段中的图像作为 base64 编码的数据 URI 返回，其值为`type`：`IMAGE`

```
"retrievalResults": [
    {
        "content": {
            "byteContent": "data:image/png;base64,{{<base64-encoded-bytes>}}",
            "type": "IMAGE"
        }
    }
]
```

### 音频和视频结果
<a name="kb-get-doc-content-native-multimodal-av"></a>

对于音频和视频结果，[Retrieve](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_agent-runtime_Retrieve.html)响应会返回一个 Amazon S3 URI，您可以使用它来提取文件。`type`是`AUDIO`或`VIDEO`，URI 位于相应的`audio`或`video`对象中。

以下示例显示了音频结果：

```
"retrievalResults": [
    {
        "content": {
            "audio": {
                "s3Uri": "s3://{{amzn-s3-demo-bucket}}/{{path/to/audio.mp3}}"
            },
            "type": "AUDIO"
        }
    }
]
```

以下示例显示了视频结果：

```
"retrievalResults": [
    {
        "content": {
            "type": "VIDEO",
            "video": {
                "s3Uri": "s3://{{amzn-s3-demo-bucket}}/{{path/to/video.mp4}}"
            }
        }
    }
]
```