

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 從知識庫擷取文件的內容
<a name="kb-test-get-document-content"></a>

`GetDocumentContent` API 可讓您擷取已擷取至 Amazon Bedrock 知識庫的文件內容。此 API 會傳回預先簽章的 URL，提供暫時、安全存取，以下載或檢視文件的原始或擷取內容。

當您想要：
+ 存取 `Retrieve` API 回應中參考的來源文件
+ 從知識庫下載原始檔案 (PDF、Word、HTML 等）
+ 擷取 JSON 格式的文件擷取/剖析的文字內容
+ 建置應用程式，讓使用者在 `Retrieve` API 回應後檢視或下載來源文件

## 運作方式
<a name="kb-get-doc-content-how-it-works"></a>

1. 您可以使用`GetDocumentContent`知識庫 ID、資料來源 ID 和文件 ID 來呼叫 。

1. 服務會驗證您的存取許可 （包括知識庫上設定的任何 ACL 型存取控制）。

1. API 會傳回預先簽章的 URL 和文件的 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 型存取控制時，請`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>

未設定 ACLs 時，省略 `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)
```

### 未啟用 ACL 的跨帳戶
<a name="kb-get-doc-content-cross-account"></a>

對於跨帳戶存取，知識庫擁有者必須將**資源政策**連接至其知識庫，以授予發起人的帳戶許可。然後，發起人會使用完整的知識庫 ARN。

**步驟 1：KB 擁有者將資源政策連接至知識庫**

擁有知識庫的帳戶 （例如 `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 或 Amazon Bedrock 主控台來完成。

**步驟 2：來電者帳戶具有叫用 API 的 IAM 許可**

發起人的 IAM 角色/使用者 （在帳戶 中`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)
```

資源政策 （在 KB 擁有者端） 和 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)回應會以 base64 編碼的資料 URI 傳回 `byteContent` 欄位中的影像，其中 `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}}"
            }
        }
    }
]
```