

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

# 建置
<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/responses) [或聊天完成 API](https://platform.openai.com/docs/api-reference/chat) | 
| 使用與 OpenAI 相容端點不相容的模型 | 使用原生 Amazon Bedrock APIs：[Converse](conversation-inference.md) 和 [Invoke](inference-invoke.md)。進一步了解如何為您的使用案例選擇正確的 APIs。 | 

**選擇 Amazon Bedrock 的端點**

識別要使用的 API 之後，您就可以識別要用來以程式設計方式與 Amazon Bedrock 互動的端點。進一步了解支援的 APIs。


| **端點** | **支援的 APIs** | 
| --- | --- | 
| bedrock-mantle.\$1 | [回應 API](bedrock-mantle.md)、[聊天完成 API](bedrock-mantle.md) | 
| bedrock-runtime.\$1 | [叫用 API](inference-invoke.md)、[Converse API](conversation-inference.md)、[聊天完成 API](inference-chat-completions.md) | 

**選擇模型**

您可以根據您使用的端點，查看 Amazon Bedrock 支援的模型清單。


| **端點** | **API** | **Description** | 
| --- | --- | --- | 
| bedrock-runtime.\$1 | ListFoundationModels | 傳回 Bedrock 中所有可用基礎模型的清單。提供有關多個模型的摘要資訊，包括其模型 IDs、提供者名稱、支援的模態 （文字、影像、內嵌）、輸入/輸出格式，以及它們是否支援串流或自訂。使用 GetFoundationModel API，使用其模型 ID 擷取特定基礎模型的詳細資訊。 | 
| bedrock-mantle.\$1 | client.models.list | 可探索可用模型的 OpenAI 相容 API。擷取可與回應 API 和聊天完成 API 搭配使用的模型清單。 | 

# Amazon Bedrock 支援的 APIs
<a name="apis"></a>

**支援的推論 APIs **

Amazon Bedrock 提供四種主要 API 模式，可在 Amazon Bedrock 中執行[推論](inference.md)。


| **API 方法** | **服務端點** | **最適合 的使用案例** | **金鑰功能** | 
| --- | --- | --- | --- | 
| [回應 API](bedrock-mantle.md) （建議） | bedrock-mantle.<suffix> | 狀態對話 | 將 Responses API 用於需要內建工具 （搜尋、程式碼解譯器）、多模式輸入和具狀態對話的現代客服人員應用程式 | 
| [聊天完成](bedrock-mantle.md) | bedrock-mantle.<suffix> （建議） 和 bedrock-runtime.<suffix> | 無狀態多轉聊天 | 將[聊天完成 API](inference-chat-completions.md) 用於輕量、無狀態、以文字為中心的任務，其中您需要完全控制聊天歷史記錄管理和更低延遲。 | 
| [Converse 方法](conversation-inference.md) | bedrock-runtime.<suffix> | 多轉聊天/標準化 | [Converse API](conversation-inference.md) 提供與 Amazon Bedrock 中所有模型互動的統一界面。 | 
| [叫用 方法](inference-invoke.md) | bedrock-runtime.<suffix> | 單一交易/大型承載 | 調用 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) [或聊天完成 API](inference-chat-completions.md)。根據 OpenAI，[建議的](https://platform.openai.com/docs/guides/migrate-to-responses) API 長期為 Responses API。 | 
| 使用與 OpenAI 相容端點不相容的模型 | 使用原生 Amazon Bedrock APIs：[Converse ](conversation-inference.md)和 [Invoke](inference-invoke.md)。如需詳細資訊，請參閱[使用 API 提交提示並產生回應](inference-api.md)。 | 
| 所有模型的一致界面 | [Converse API](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html) - 適用於所有支援訊息的模型。編寫程式碼一次，並搭配不同的模型使用。如需範例程式碼，請參閱 [Converse 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)。[在這裡](https://docs.aws.amazon.com/general/latest/gr/bedrock.html)閱讀有關控制平面 API 的詳細資訊。

**推論操作**

Amazon Bedrock 支援下列主要兩個端點，以程式設計方式執行推論：


| **端點** | **支援的 APIs** | **Description** | 
| --- | --- | --- | 
| 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) | 區域特定的端點，用於使用 InvokeModel/Converse/Chat Completions APIs，對 Amazon Bedrock 中託管的模型進行推論請求。[在此處](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Amazon_Bedrock_Runtime.html)閱讀有關 Amazon Bedrock 執行期 APIs的詳細資訊。 | 

**您應該使用哪個服務端點進行推論？**

您使用的端點取決於您的使用案例。


| **端點** | **功能和使用案例** | 
| --- | --- | 
| bedrock-mantle |  支援 OpenAI 相容 APIs [（回應 API](bedrock-mantle.md)、[聊天完成 API](bedrock-mantle.md))。 **用於：**從使用 OpenAI 相容 APIs 的其他模型輕鬆遷移。 **功能：**支援搭配 Lambda 函數使用的用戶端和伺服器端工具，並在您的應用程式中設定ready-to-use工具。 **建議用於：**Amazon Bedrock 的新使用者。  | 
| bedrock-runtime |  支援 Amazon Bedrock 原生 APIs([呼叫 API](inference-invoke.md)、[Converse API](conversation-inference.md))。也支援 OpenAI 相容[聊天完成 API](inference-chat-completions.md)。 **用於：**執行 Amazon Bedrock 支援的任何模型。[Converse API](conversation-inference.md) 提供與 Amazon Bedrock 中所有模型互動的統一界面，而[調用 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 工作負載提供應用程式層級隔離。專案可讓您透過改善的存取控制、成本追蹤和整個組織的可觀測性來組織和管理 AI 應用程式。

**注意**  
專案只能與針對 [bedrock-mantle 端點](bedrock-mantle.md)使用 OpenAI 相容 APIs的模型搭配使用。如果您使用的是底ock-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 標籤](https://docs.aws.amazon.com/whitepapers/latest/tagging-best-practices/what-are-tags.html)和 [AWS 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 用量，例如業務單位、團隊、應用程式或成本中心
+ **隔離敏感資料**：確保其他應用程式無法存取來自某個應用程式的提示、回應和內容資料
+ **準確追蹤成本**：監控並配置 AI 支出給特定團隊、專案或環境
+ **強制執行存取政策**：套用精細的 IAM 許可，以控制誰可以存取特定 AI 工作負載
+ **擴展生產工作負載**：執行多個具有明確操作界限和監控的生產應用程式

## 專案與推論設定檔
<a name="projects-vs-inference-profiles"></a>

專案 API [和推論設定檔](inference-profiles-create.md)在 Amazon Bedrock 中提供隔離、標記和存取控制功能，但它們會根據您使用的 API 而有所不同。如果您將 OpenAI 相容 APIs與使用 Mantle 推論引擎的 [bedrock-mantle](endpoints.md) 端點搭配使用，請使用 Projects API。如果您使用 Invoke 或 Converse APIs搭配 [bedrock-runtime](endpoints.md) 端點，請使用推論設定檔。雖然您可以將聊天完成 API 與 bedrock-mantle 或 bedrock-runtime 端點搭配使用，但我們建議您使用 Mantle 端點。


| 功能 | 專案 API | 推論設定檔 | 
| --- | --- | --- | 
| 支援的 API | OpenAI 相容 APIs （回應、聊天完成） | 原生 Bedrock APIs（調用、Converse)、OpenAI 相容 API （聊天完成） | 
| Endpoint | bedrock-mantle.\$1region\$1.api.aws | bedrock-runtime.\$1region\$1.amazonaws.com | 
| 使用案例 | 使用 OpenAI 相容端點的應用程式 | 使用原生 Bedrock APIs的應用程式 | 
| 存取控制 | 在 IAM 政策中將 投影為資源 | 推論設定檔 ARN 的 IAM 政策 | 
| 成本追蹤 | 專案上的 AWS 標籤 | 推論設定檔上的 AWS 標籤 | 

## 專案與 AWS 帳戶
<a name="projects-vs-aws-accounts"></a>

[AWS 帳戶](https://docs.aws.amazon.com/accounts/latest/reference/accounts-welcome.html)和 [AWS Organizations](https://docs.aws.amazon.com/controltower/latest/userguide/organizations.html) 代表基礎設施層級的帳單和擁有權界限。專案代表單一帳戶中的工作負載和應用程式邊界。

使用專案而非單獨的 AWS 帳戶提供：
+ **更快速的設定**：透過 API 呼叫在幾秒鐘內建立專案
+ **降低複雜性**：無需擴展帳戶即可管理多個工作負載
+ **簡化操作**：單一帳戶中的集中式管理
+ **較低的額外**負荷：不需要跨帳戶 IAM 角色或資源共用

## 專案入門
<a name="projects-getting-started"></a>

此頁面會逐步引導您建立第一個專案、將其與推論請求建立關聯，以及管理專案資源。

### 先決條件
<a name="projects-prerequisites"></a>

開始前，請確保您具備以下條件：
+ 具有 Amazon 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，但我們建議具有較高安全需求的應用程式使用短期金鑰。如果您將長期金鑰與專案搭配使用，請注意，連接至長期金鑰的預設政策僅允許您取得和列出專案，但無法create/update/archive專案。如果您想要長期金鑰來管理專案，則必須將其他 IAM 政策指派給金鑰，才能啟用這些操作。

### 步驟 2：探索可用的模型
<a name="projects-discover-models"></a>

使用 `list()` API 擷取與專案 API 相容的模型清單：

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

### 步驟 3：建立您的第一個專案
<a name="projects-create-first"></a>

使用具有成本監控和可觀測性標籤的建立專案 API 來建立專案。請注意，目前 SDK 僅支援 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、InternalSearch-Dev
+ **依團隊**：TeamAlpha-Production、DataScience-Experiments
+ **依環境**：Production-WebApp、Staging-MobileApp
+ **依成本中心**：CostCenter-2152-Production

### 列出專案
<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 的 Data Automation](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Data_Automation_for_Amazon_Bedrock.html) 或 [Amazon Bedrock Data Automation 的執行時期](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 小時)。您應該已設定具有使用 Amazon Bedrock 之適當許可的 [IAM 主體](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction_identity-management.html#intro-structure-terms)。對於需要定期變更憑證以提高安全性的生產環境，此選項優於長期金鑰。

  短期金鑰具有下列屬性：
  + 有效期限為下列值中較短者：
    + 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)
+ [Amazon 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_tw/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)。

# Amazon Bedrock API 金鑰支援的區域和 AWS 軟體開發套件 (SDKs)
<a name="api-keys-supported"></a>

下列清單顯示支援 API 金鑰 AWS 區域 的 ：
+ 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 的 Data Automation](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Data_Automation_for_Amazon_Bedrock.html) 或 [Amazon Bedrock Data Automation 的執行時期](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 管理主控台。接著，開啟位於 [https://console.aws.amazon.com/bedrock](https://console.aws.amazon.com/bedrock) 的 Amazon Bedrock 主控台。

1. 在左側導覽窗格中，選取**API 金鑰**。

1. 產生下列其中一種類型的金鑰：
   + **短期 API 金鑰** – 在**短期 API 金鑰**索引標籤中，選擇**產生短期 API 金鑰**。金鑰會在主控台工作階段過期 (且不超過 12 小時) 時過期，並可讓您呼叫產生該金鑰的 AWS 區域。您可以直接在產生的金鑰中修改區域。
   + **長期 API 金鑰** – 在**長期 API 金鑰**索引標籤中，選擇**產生長期 API 金鑰**。

     1. 在 **API 金鑰過期**區段中，選擇金鑰過期的時間。

     1. (選用) 根據預設，授予核心 Amazon Bedrock API 操作存取權的 [AmazonBedrockLimitedAccess](security-iam-awsmanpol.md#security-iam-awsmanpol-AmazonBedrockLimitedAccess) AWS 受管政策會連接到與金鑰相關聯的 IAM 使用者。若要選取更多政策以連接到使用者，請展開**進階許可**區段，然後選取您要新增的政策。

     1. 選擇 **Generate (產生)**。
**警告**  
我們強烈建議限縮將 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)中查看特定 SDK 或工具的階層。
+ 安裝 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 的 Data Automation](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_Operations_Data_Automation_for_Amazon_Bedrock.html) 或 [Amazon Bedrock Data Automation 的執行時期](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.  AWS 管理主控台 使用具有使用 Amazon Bedrock 主控台之許可的 IAM 身分登入 。接著，開啟位於 [https://console.aws.amazon.com/bedrock](https://console.aws.amazon.com/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](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateServiceSpecificCredential.html.html)、[ResetServiceSpecificCredential](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ResetServiceSpecificCredential.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.  AWS 管理主控台 使用具有使用 Amazon Bedrock 主控台之許可的 IAM 身分登入 。接著，開啟位於 [https://console.aws.amazon.com/bedrock](https://console.aws.amazon.com/bedrock) 的 Amazon Bedrock 主控台。

1. 在左側導覽窗格中，選取**API 金鑰**。

1. 在**長期 API 金鑰**區段中，選擇**狀態**為**非作用中**的金鑰。

1. 選擇**動作**。

1. 選取 **Deactivate** (停用)。

1. 確認後，請選取**停用 API 金鑰**。金鑰的**狀態**會變成**非作用中**。

**重新啟用金鑰**

1.  AWS 管理主控台 使用具有使用 Amazon Bedrock 主控台之許可的 IAM 身分登入 。接著，開啟位於 [https://console.aws.amazon.com/bedrock](https://console.aws.amazon.com/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.  AWS 管理主控台 使用具有使用 Amazon Bedrock 主控台之許可的 IAM 身分登入 。接著，開啟位於 [https://console.aws.amazon.com/bedrock](https://console.aws.amazon.com/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.  AWS 管理主控台 使用具有使用 Amazon Bedrock 主控台之許可的 IAM 身分登入 。接著，開啟位於 [https://console.aws.amazon.com/bedrock](https://console.aws.amazon.com/bedrock) 的 Amazon Bedrock 主控台。

1. 在左側導覽窗格中，選取**API 金鑰**。

1. 在**長期 API 金鑰**區段中，選擇金鑰。

1. 選擇**動作**。

1. 選取**刪除**。

1. 確認刪除。

**API 金鑰與 IAM 使用者連結**  
刪除此 API 金鑰不會刪除使用此金鑰建立的 IAM 使用者做為擁有者。您可以在下一個步驟中從 IAM 主控台刪除 IAM 使用者。

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

若要使用 API 刪除金鑰，請傳送 [DeleteServiceSpecificCredential](https://docs.aws.amazon.com/IAM/latest/APIReference/API_DeleteServiceSpecificCredential.html.html) 請求與 [IAM 端點](https://docs.aws.amazon.com/general/latest/gr/iam-service.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 金鑰的產生**  
[iam:CreateServiceSpecificCredential](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsidentityandaccessmanagementiam.html#awsidentityandaccessmanagementiam-actions-as-permissions) 動作會控制產生服務特定金鑰 (例如長期 Amazon 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 金鑰。

**控制 Amazon Bedrock API 金鑰的使用**  
[bedrock:CallWithBearerToken](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonbedrock.html#amazonbedrock-actions-as-permissions) 動作控制短期或長期 Amazon Bedrock API 金鑰的使用。

您可以使用 `bedrock:bearerTokenType` 條件索引鍵搭配[字串條件運算子](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String)來指定要套用 `bedrock:CallWithBearerToken` 許可的承載字符類型。您可以指定下列其中一個值：
+ `SHORT_TERM` – 在條件中指定短期 Amazon Bedrock API 金鑰。
+ `LONG_TERM` – 在條件中指定長期 Amazon Bedrock API 金鑰。

下表摘要說明如何防止身分產生或使用 Amazon Bedrock API 金鑰：


****  

| 用途 | 長期金鑰 | 短期金鑰 | 
| --- | --- | --- | 
| 防止產生金鑰 | 將拒絕 iam:CreateServiceSpecificCredential 動作的政策連接至 IAM 身分。 | N/A | 
| 防止使用金鑰 | 將拒絕 bedrock:CallWithBearerToken 動作的政策連接到與金鑰相關聯的 IAM 使用者。 | 將拒絕 bedrock:CallWithBearerToken 動作的政策連接到您不想使用金鑰的 IAM 身分。 | 

**警告**  
由於短期 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)
+ [僅允許建立有效期在 90 天內的 Amazon Bedrock 金鑰](#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": "*"
        }
    ]
}
```

------

### 僅允許建立有效期在 90 天內的 Amazon Bedrock 金鑰
<a name="api-keys-permissions-examples-allow-bedrock-keys-expire-within-90-days"></a>

若要允許 IAM 身分僅在適用於 Amazon Bedrock 且過期時間為 90 天或更短時才允許其建立長期 API 金鑰，請將下列政策連接至身分：

------
#### [ 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)。


****  

| 輸出模態 | Description | 範例使用案例 | 
| --- | --- | --- | 
| 文字 | 提供文字輸入並產生各種類型的文字 | 聊天、問答、腦力激盪、摘要、產生程式碼、資料表建立、資料格式、重寫 | 
| 影像 | 提供文字或輸入影像，並產生或修改影像 | 影像產生、影像編輯、影像變化 | 
| 影片 | 提供文字或參考影像並產生影片 | 影片產生、影像轉換為影片 | 
| 嵌入項目 | 提供文字、影像或文字和影像，並產生代表輸入的數值向量。輸出向量可以與其他內嵌向量進行比較，以判斷語意相似性 (適用於文字) 或視覺相似性 (適用於影像)。 | 文字和影像搜尋、查詢、分類、建議、個人化、[知識庫建立](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>

您可採用下列方式，直接執行模型推論：


****  

| Method | 使用案例 | 
| --- | --- | 
| [Amazon Bedrock 主控台遊樂場](playgrounds.md) | 在易於使用的圖形界面中執行推論。方便探索。 | 
| [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) | 使用統一 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) | 將聊天完成 API 用於輕量、無狀態、以文字為主的任務，其中您需要完全控制聊天歷史記錄管理和更低延遲。 | 

下列 Amazon Bedrock 功能也會使用模型推論作為較大工作流程中的步驟：
+ 在您提交 [CreateEvaluationJob](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_CreateEvaluationJob.html) 請求後，[模型評估](evaluation.md)會使用模型調用程序來評估不同模型的效能。
+ [知識庫](knowledge-base.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 以根據從知識庫擷取到的結果產生回應時，會使用模型調用。
+ [代理程式](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 資源，例如提示、知識庫和代理程式。

使用不同的提示和推論參數測試不同的基礎模型之後，您可以設定應用程式，以使用所需的規格來呼叫這些 API。

# 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 方法而有所不同。如需詳細資訊，請參閱《[基礎模型參考](foundation-models-reference.md)》中的 [Amazon Bedrock 中支援的基礎模型](models-supported.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 Service Quotas](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 Service Quotas](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 帳戶 或 Organization 層級明確啟用的區域。若要進一步了解，請參閱《[在您的帳戶中啟用或停用 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/)Enabling Amazon Bedrock cross-Region inference in multi-account environments》。

# 使用推論參數影響回應生成
<a name="inference-parameters"></a>

執行模型推論時，您可以調整推論參數來影響模型回應。推論參數可以變更模型在生成期間考慮的可能輸出集區，也可以限制最終回應。

推論參數預設值和範圍取決於模型。若要了解不同模型的推論參數，請參閱 [基礎模型的推論請求參數和回應欄位](model-parameters.md)。

以下的參數類別通常可在不同的模型中找到。

**Topics**
+ [隨機性和多樣性](#inference-randomness)
+ [Length](#inference-length)

## 隨機性和多樣性
<a name="inference-randomness"></a>

對於任何指定的序列，模型可決定序列中下一個字符選項的機率分佈。為了在輸出中產生每個字符，模型會從此分佈中進行取樣。隨機性和多樣性是指模型回應中的變體數量。您可以透過限制或調整分佈來控制這些係數。基礎模型通常支援以下參數來控制回應中的隨機性和多樣性。
+ **溫度** — 影響預測輸出的機率分佈形狀，並影響模型選擇較低機率輸出的可能性。
  + 選擇較低的值來影響模型，以選擇較高機率的輸出。
  + 選擇較高的值來影響模型，以選取較低機率的輸出。

  用技術性名詞來說，溫度會調節下一個字符的機率質量函數。較低的溫度會使函數變得陡峭，並導致更具確定性的回應，而較高的溫度會使函數變得平坦，並導致更隨機的回應。
+ **Top K** - 模型考慮下一個字符時，最有可能的候選項數量。
  + 選擇較低的值以縮減集區的大小，並將選項限制為更可能的輸出。
  + 選擇較高的值以增加集區的大小，並允許模型考慮較不可能的輸出。

  例如，若為 Top K 選擇值 50，則模型會從 50 個最有可能成為序列中下一個的字符中做選擇。
+ **Top P** - 模型考慮下一個字符時，最可能的候選項目百分比。
  + 選擇較低的值以縮減集區的大小，並將選項限制為更可能的輸出。
  + 選擇較高的值以增加集區的大小，並允許模型考慮較不可能的輸出。

  用技術性名詞來說，該模型會運算回應集的累積機率分佈，並僅考慮分佈的前 P%。

  例如，若您為 Top P 選擇值 0.8，則模型會從可能是序列中下一個字符的機率分佈的前 80% 中做選擇。

下表摘要說明這些參數的功用。


****  

| 參數 | 較低值的影響 | 較高值的影響 | 
| --- | --- | --- | 
| 溫度 | 增加高機率字符的可能性 減少低機率字符的可能性 | 增加低機率字符的可能性減少高機率字符的可能性 | 
| Top K | 移除低機率的字符 | 允許低機率的字符 | 
| Top P | 移除低機率的字符 | 允許低機率的字符 | 

做為用於了解這些參數的範例，請考慮範例提示 **I hear the hoof beats of "**。假設模型確定以下三個單字當做下一個字符的候選項。該模型也會為每個單字指派機率。

```
{
    "horses": 0.7,
    "zebras": 0.2,
    "unicorns": 0.1
}
```
+ 如果設定較高的**溫度**，則機率分佈較平坦，機率差異會減小，這會增加選擇「獨角獸」的機率，並降低選擇「馬」的機率。
+ 如果將 **Top K** 設為 2，則模型僅考慮前 2 名最有可能的候選項：「馬」和「斑馬」。
+ 如果將 **Top P** 設定為 0.7，則模型只會考慮「馬」，因為它是唯一位於機率分佈前 70% 的候選項。如果您將 **Top P** 設定為 0.9，則模型會將「馬」和「斑馬」視為機率分佈的前 90%。

## Length
<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 受管政策，您可以略過本節。否則，請將下列許可連接到角色，以允許其使用 [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 中所有支援的資源：

------
#### [ 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) 和 [Converse](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) 和 [Converse](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 遊樂場是 中的一種工具 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 提供下列遊樂場供您試驗：
+ **聊天/文字** – 提交文字提示並產生回應，或使用語音互動。您可以選取下列其中一個模式：
  + **聊天** – 提交文字提示或使用語音互動。對於文字提示，您也可以包含影像或文件來補充提示。您提交的後續提示將包含您先前的提示做為內容，讓提示和回應的順序與對話類似。
  + **單一提示** – 提交單一文字提示並產生提示的回應。
**注意**  
如 Amazon Nova Sonic 等語音轉語音模型適用於聊天模式。語音轉語音模型不支援比較模式。
+ **影像** – 提交文字提示以產生影像。您也可以提交影像提示，並指定要編輯提示還是產生其變化。
+ **多模態 （預覽）** – 提交文字提示並產生多模態內容。它也支援聊天和單一提示模式。

下列程序說明如何在遊樂場中提交提示、您可以調整的選項，以及在模型產生回應後您可以採取的動作。

**使用遊樂場**

1. 如果您尚未行動，可請求存取您要使用的模型。如需詳細資訊，請參閱[存取 Amazon Bedrock 基礎模型](model-access.md)。

1.  AWS 管理主控台 使用具有使用 Amazon Bedrock 主控台之許可的 IAM 身分登入 。接著，開啟位於 [https://console.aws.amazon.com/bedrock](https://console.aws.amazon.com/bedrock) 的 Amazon Bedrock 主控台。

1. 在導覽窗格的測試下，選擇**遊樂場**。

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**」。您可以包含下列類型的檔案：
     + **文件** – 新增文件以補充提示。如需支援的檔案類型清單，請參閱 [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) 中的 `format` 欄位。
**注意**  
內容限制會因基礎 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_tw/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_tw/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_tw/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_tw/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 | 此模型會有 32,768 個字符，其中包括輸出和推理字符。 | 您可以使用可設定的字符預算來啟用或停用此模型的推理。預設會停用推理。 | 
| Anthropic Claude Sonnet 4 | anthropic.claude-sonnet-4-20250514-v1:0 | 此模型會有 65,536 個字符，其中包括輸出和推理字符。 | 您可以使用可設定的字符預算來啟用或停用此模型的推理。預設會停用推理。 | 
| Anthropic Claude 3.7 Sonnet | anthropic.claude-3-7-sonnet-20250219-v1:0 | 此模型會有 65,536 個字符，其中包括輸出和推理字符。 | 您可以使用可設定的字符預算來啟用或停用此模型的推理。預設會停用推理。 | 
| DeepSeek DeepSeek-R1 | deepseek.r1-v1:0 | 此模型會有 8192 個字符，其中包括輸出和推理字符。無法設定思維字符的數量，且輸出字符的數量上限不得大於 8192。 | 此模型一律會啟用推理。此模型不支援開啟和關閉推理功能。 | 

# 針對延遲最佳化模型推論
<a name="latency-optimized-inference"></a>

**注意**  
延遲最佳化推論功能為 的預覽版本 Amazon Bedrock ，可能會有所變更。

中基礎模型的延遲最佳化推論，可為 AI 應用程式 Amazon Bedrock 提供更快的回應時間並改善回應能力。最佳化版本的 [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 日誌中。您也可以在「model-id\$1latency-optimized」下的 Amazon CloudWatch 日誌中檢視延遲最佳化請求的指標。

延遲最佳化推論適用於 Meta 的 Llama 3.1 70B 和 405B，以及透過[跨區域推論](https://docs.aws.amazon.com/bedrock/latest/userguide/cross-region-inference.html)美國東部 (俄亥俄) 和美國西部 (奧勒岡) 區域中 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 的請求。對於較大的字符計數請求，我們將返回標準模式。

下表顯示支援延遲最佳化的推論設定檔：


| 供應商 | 模型 | 模型 ID | 跨區域推論設定檔支援 | 
| --- | --- | --- | --- | 
| Amazon | Nova Pro | amazon.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-405b-instruct-v1:0 |  us-east-2  | 
| Meta | Llama 3.1 70B Instruct | meta.llama3-1-70b-instruct-v1:0 |  us-east-2 us-west-2  | 

如需推論設定檔的詳細資訊，請參閱 [推論設定檔支援的區域和模型](inference-profiles-support.md)。

# 使用 OpenAI APIs產生回應
<a name="bedrock-mantle"></a>

Amazon Bedrock 為模型推論提供OpenAI相容的 API 端點，採用適用於大規模機器學習模型服務的分散式推論引擎 Mantle。這些端點可讓您使用熟悉的 OpenAI SDK 和工具搭配 Amazon Bedrock 模型，讓您以最少的程式碼變更遷移現有的應用程式，只需更新您的基本 URL 和 API 金鑰即可。 SDKs 

主要優點包括：
+ **非同步推論** – 透過 Responses API 支援長時間執行的推論工作負載
+ **具狀態對話管理** – 自動重建內容，無需在每個請求中手動傳遞對話歷史記錄
+ **簡化工具使用** – 簡化客服人員工作流程的整合
+ **彈性回應模式** – 支援串流和非串流回應
+ **輕鬆遷移** – 與現有的 OpenAI SDK 程式碼庫相容

## 支援的區域和端點
<a name="bedrock-mantle-supported"></a>

Amazon Bedrock 可在下列 AWS 區域使用：


| 區域名稱 | 區域 | Endpoint | 
| --- | --- | --- | 
| 美國東部 (俄亥俄) | 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 | 
| Europe (Stockholm) | 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之前，請確定您擁有下列項目：
+ **身分驗證** – 您可以使用下列方法進行身分驗證：
  + Amazon Bedrock API 金鑰 ( OpenAI SDK 需要）
  + AWS 登入資料 (HTTP 請求支援）
+ **OpenAI SDK** （選用） – 如果使用以 SDK 為基礎的請求，請安裝 OpenAI Python SDK。
+ **環境變數** – 設定下列環境變數：
  + `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 提供 followingAPI 操作來執行模型推論：
+ [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/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 – 使用 [OpenAI 聊天完成 API](https://platform.openai.com/docs/api-reference/chat/create) 搭配 Amazon Bedrock 支援的模型來產生回應。

**注意**  
限制適用於下列操作：`InvokeModel`、`Converse`、 `InvokeModelWithResponseStream`和 `ConverseStream`。如需詳細資訊，請參閱 [API 限制](inference-api-restrictions.md)。

針對模型推論，您需要判斷下列參數：
+ 模型 ID – 要在 `modelId` 欄位中用於推論的模型或推論設定檔 ID 或 Amazon Resource Name (ARN)。下表說明如何尋找不同類型的資源 ID：  
****    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/bedrock/latest/userguide/inference-api.html)
+ 請求內文 – 包含模型和其他組態的推論參數。每個基本模型都有各自的推論參數。自訂或佈建的模型的推論參數為何，取決於建立該參數的基本模型。如需詳細資訊，請參閱[基礎模型的推論請求參數和回應欄位](model-parameters.md)。

選取主題以了解如何使用模型調用 API。

**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 執行時期端點](https://docs.aws.amazon.com/general/latest/gr/bedrock.html#br-rt)傳送 [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) 請求，在提示上執行模型推論。

**注意**  
限制適用於下列操作：`InvokeModel`、`Converse`、 `InvokeModelWithResponseStream`和 `ConverseStream`。如需詳細資訊，請參閱 [API 限制](inference-api-restrictions.md)。

下列是必要欄位：


****  

| 欄位 | 使用案例 | 
| --- | --- | 
| modelId | 從提示管理指定要使用的模型、推論設定檔或提示。若要了解如何尋找此值，請參閱 [使用 API 提交提示並產生回應](inference-api.md)。 | 
| 本文 | 指定模型的推論參數。若要查看不同模型的推論參數，請參閱 [基礎模型的推論請求參數和回應欄位](model-parameters.md)。如果您在 modelId 欄位中從提示管理指定提示，請省略此欄位 (如果您包含它，則會予以忽略)。 | 

以下是選填欄位：


****  

| 欄位 | 使用案例 | 
| --- | --- | 
| 接受 | 指定請求內文的媒體類型。如需詳細資訊，請參閱 [Swagger 網站](https://swagger.io/specification/)上的媒體類型。 | 
| ContentType | 指定回應內文的媒體類型。如需詳細資訊，請參閱 [Swagger 網站](https://swagger.io/specification/)上的媒體類型。 | 
| performanceConfigLatency | 指定是否針對延遲最佳化模型。如需詳細資訊，請參閱[針對延遲最佳化模型推論](latency-optimized-inference.md)。 | 
| guardrailIdentifier | 指定要套用至提示和回應的防護機制。如需詳細資訊，請參閱[測試您的防護機制](guardrails-test.md)。 | 
| guardrailVersion | 指定要套用至提示和回應的防護機制。如需詳細資訊，請參閱[測試您的防護機制](guardrails-test.md)。 | 
| 追蹤 | 指定是否要傳回您指定之防護機制的追蹤。如需詳細資訊，請參閱[測試您的防護機制](guardrails-test.md)。 | 
| serviceTier | 指定請求的服務層。如需詳細資訊，請參閱[最佳化效能和成本的服務層](service-tiers-inference.md)。 | 

## 調用模型程式碼範例
<a name="inference-example-invoke"></a>

本主題提供一些搭配 [InvokeModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html) API 使用單一提示執行推論的基本範例。如需不同模型的更多範例，請造訪下列資源：
+ 在 [使用 AWS SDKs的 Amazon Bedrock 執行期程式碼範例](service_code_examples_bedrock-runtime.md) 主題下選擇一個範例。
+ 請造訪 [基礎模型的推論請求參數和回應欄位](model-parameters.md) 中所需模型的推論參數參考。

下列範例假設您已設定程式設計存取，以便在執行這些範例 AWS 區域 時，自動驗證預設值中的 AWS CLI 和 SDK for Python (Boto3)。如需設定程式設計存取權的資訊，請參閱 [開始使用 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* 影像檔案。

```
# 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. 建立名為 *image-input-embeddings-output.json* 的 JSON 檔案，並貼上下列 JSON，將 *\$1\$1image-base64\$1* 取代為 *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. 建立名為 *image-text-input.json* 的 JSON 檔案，並貼上下列 JSON，將 *\$1\$1image-base64\$1* 取代為 *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 模型產生回應。

**先決條件：**遵循《Amazon Simple Storage Service 使用者指南》中[上傳物件](https://docs.aws.amazon.com/AmazonS3/latest/userguide/upload-objects.html#upload-objects-procedure)的步驟，將標題為 *video.mp4* 的影片上傳至您帳戶中的 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. 建立名為 *video-text-input.json* 的 JSON 檔案，然後貼上下列 JSON，將 *\$1\$1video-base64\$1* 取代為 `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 使用提示詞*寫一篇 1000 字以內關於在火星生活*的文章。

```
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 請求。
+ 搭配 Amazon Bedrock 執行時期端點使用 OpenAI SDK 請求。

選取主題以進一步了解：

**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>

您可以使用建立聊天完成 API 搭配 Amazon Bedrock 和支援這些OpenAI模型的 AWS 區域中支援的所有模型。如需支援模型和區域的詳細資訊，請參閱 [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](https://docs.aws.amazon.com/general/latest/gr/bedrock.html#br-rt)如果您使用 AWS SDK，您可能只需要在設定用戶端時指定區域碼，而不是整個端點。
+ **安裝 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](https://docs.aws.amazon.com/general/latest/gr/bedrock.html#br-rt)如果您使用 AWS SDK，您可能只需要在設定用戶端時指定區域碼，而不是整個端點。

------

## 建立聊天完成
<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。使用實際 API 金鑰取代 *\$1AWS\$1BEARER\$1TOKEN\$1BEDROCK*。

```
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。使用實際 API 金鑰取代 *\$1AWS\$1BEARER\$1TOKEN\$1BEDROCK*：

```
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>

若要在模型輸入和回應中包含保護措施，請在執行模型調用時套用[防護機制](guardrails.md)，方法是在請求內文中包含下列[額外參數](https://github.com/openai/openai-python#undocumented-request-params)做為欄位：
+ `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 模型和接收來自 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`、`Converse`、 `InvokeModelWithResponseStream`和 `ConverseStream`。如需詳細資訊，請參閱 [API 限制](inference-api-restrictions.md)。

如需程式碼範例，請參閱下方：
+ 本主題的 Python 範例：[Converse API 範例](conversation-inference-examples.md)
+ 各種語言和模型：[使用 AWS SDKs的 Amazon Bedrock 執行期程式碼範例](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 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 否 | 否 | 
| Anthropic Claude Opus 4 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 否 | 否 | 
| Anthropic Claude Sonnet 4.5 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 否 | 否 | 
| Anthropic Claude Haiku 4.5 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 否 | 否 | 
| Anthropic Claude Opus 4.1 | 是 | 是 | 是 | 是 | 是 | 是 | 是 | 否 | 否 | 
| Claude Opus 4.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 Bedrock AWS 區域 中的 模型支援](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**：標頭中的必要參數，可讓您指定用於推論的資源。
+ 下列欄位可讓您自訂提示：
  + **訊息**：用來指定提示的內容和角色。
  + **系統**：用來指定系統提示，以定義模型的指示或內容。
  + **inferenceConfig**：用來指定所有模型通用的推論參數。影響回應產生的推論參數。
  + **additionalModelRequestFields**：用來指定與您執行推論所用之模型所特有的推論參數。
  + **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` 請求內文中的欄位：

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

`messages` 欄位是 [Message](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Message.html) 物件的陣列，每個項目都會定義使用者與模型之間的訊息。`Message` 物件包含下列欄位：
+ **角色**：定義訊息是來自 `user` (傳送至模型的提示) 還是 `assistant` (模型回應)。
+ **內容**：在提示中定義內容。
**注意**  
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) 中指定的欄位一起解譯。

以下顯示 [Message](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)：

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

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

`image` 欄位會對應至 [ImageBlock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_ImageBlock.html)。傳遞 `bytes` 欄位中影像的原始位元組 (以 base64 編碼)。如果您使用 AWS SDK，則不需要對 base64 中的位元組進行編碼。

如果您排除 `text` 欄位，則模型會描述影像。

以下顯示範例 [Message](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)：

```
{
    "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。

以下顯示範例 [Message](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) 和必要的隨附文字 [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 SDK，則不需要對 base64 中的位元組進行編碼。

如果您未包含 `text` 欄位，模型會描述影片。

以下顯示範例 [Message](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)。

```
{
    "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)。

以下顯示範例 [Message](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) 和必要的隨附文字 [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` 中傳遞下列類型的內容：
+ **文字**：以下顯示範例 [Message](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Message.html) 物件，其 `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)的任何限定詞。
+ **影像**：以下顯示具有僅包含影像 [GuardrailConverseContentBlock](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_GuardrailConverseContentBlock.html) `content` 陣列的 [Message](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Message.html) 物件：

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

  您可以指定影像的格式，並以位元組為單位定義影像。

如需防護機制的使用詳細資訊，請參閱[使用 Amazon Bedrock 防護機制偵測和篩選有害內容](guardrails.md)。

------
#### [ reasoningContent ]

`reasoningContent` 欄位會對應至 [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"
            }
        ]
    }
]
```

### system
<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>

Converse API 支援一組您在 `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}
```

### additionalModelRequestFields
<a name="converse-additional-model-request-fields"></a>

如果您使用的模型有其他推論參數，您可以在 `additionalModelRequestFields` 欄位中將那些參數指定為 JSON，以設定參數。下列範例 JSON 說明如何設定可在 Anthropic Claude 模型中使用的 `top_k` (但其不是訊息 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 物件。您可以指定中繼資料金鑰和其在此物件中所對應的值。您可以使用請求中繼資料來協助您篩選模型調用日誌。

### serviceTier
<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`、`Converse`、 和 `ConverseStream`操作時`InvokeModelWithResponseStream`，會套用第三方模型提供者要求，如果不符合，可能會導致錯誤。如果您透過 Amazon Bedrock 使用第三方模型 （例如 Anthropic Claude)，請檢閱供應商的使用者指南和 API 文件，以避免非預期的錯誤。例如，Anthropic Messages 標準端點支援 32 MB 的最大請求大小。Claude 也有特定的內容需求，例如每個請求最多 100 `PDF` 頁，以及影像大小上限為 8000x8000 px。如需 Anthropic Claude Messages 請求和回應的最新資訊，包括請求大小和內容需求，請參閱下列 Anthropic Claude 文件：[Anthropic Claude API Overview](https://platform.claude.com/docs/en/api/overview)、[Anthropic Claude Messages API Reference](https://docs.anthropic.com/claude/reference/messages_post)、[Build with Claude： Vision](https://platform.claude.com/docs/en/build-with-claude/vision) and [Build with Claude： PDF Support](https://platform.claude.com/docs/en/build-with-claude/pdf-support)。

**提示**  
Claude 要求每個請求最多 100 頁的 PDF 文件。如果您有較大的 PDF 文件，建議您將其分割成多個 PDFs，各不到 100 頁，或將更多文字合併成較少的頁面。

# 從模型取得經過驗證的 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 會根據支援的 JSON 結構描述草稿 2020 年 12 月子集來驗證 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** – 使用結構化輸出搭配 Converse 和 ConverseStream APIs 進行對話推論。

**InvokeModel 和 InvokeModelWithResponseStream APIs** – 將結構化輸出與 InvokeModel 和 InvokeModelWithResponseStream APIs搭配使用，以進行一次性推論。

**跨區域推論** – 在跨區域推論中使用結構化輸出，無需任何額外設定。

**批次推論** – 在批次推論中使用結構化輸出，無需任何額外設定。

**注意**  
結構化輸出與 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 指示 (`qwen.qwen3-coder-480b-a35b-v1:0`)
+ Qwen3 Next 80B A3B (`qwen.qwen3-next-80b-a3b`)
+ Qwen3 VL 235B A22B (`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 保護 120B (`openai.gpt-oss-safeguard-120b`)
+ GPT OSS 保護 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`)
+ 最小 3B (`mistral.ministral-3-3b-instruct`)
+ Ministral 3 8B (`mistral.ministral-3-8b-instruct`)
+ 最小 14B 3.0 (`mistral.ministral-3-14b-instruct`)
+ Mistral Large 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`)

月亮 AI  
+ Kimi K2 思維 (`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 (Anthropic 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 (Open-weight 模型）
<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 (Anthropic 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 (Open-weight 模型）
<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 動作自動化任務。

**警告**  
電腦使用功能會以「Beta Service」的形式提供給您，如 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、螢幕擷取畫面)。程式碼會執行電腦動作，並向 Claude 提供顯示輸出的螢幕擷取畫面 (當要求時)。

工具參數已更新為接受多型工具類型；正在新增 `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 ([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))。您可以在 `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 訊息 API](model-parameters-anthropic-claude-messages.md)。

如需詳細資訊，請參閱 Anthropic 文件中的[電腦使用 (beta 版)](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。以下是用戶端工具的 Python 回應 API 程式碼：

```
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()
```

**將調用 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)。

**伺服器端工具呼叫**

如果您使用回應 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 的詳細資訊，請參閱[使用 OpenAI APIs產生回應](https://docs.aws.amazon.com/bedrock/latest/userguide/bedrock-mantle.html)。

您可以搭配 Amazon Bedrock 使用兩種類型的工具：使用 Lambda 的自訂工具，或 Bedrock 支援的預先定義工具。在本節中，我們將檢閱如何使用 Responses API 建立自訂 Lambda 工具。讓我們詳細討論兩者。

**在回應 API 中使用 Lambda 的自訂工具**

透過使用 Lambda 函數作為 Bedrock 中的自訂工具，您可以透過將自訂 AWS Lambda 函數整合為工具來擴展代理程式的功能。這可讓您建立無伺服器、可擴展的工具，AI 助理和其他應用程式可透過模型內容通訊協定 (MCP) 呼叫這些工具。以下是此功能的優點：
+ 擴展功能：新增自訂商業邏輯、API 整合或資料處理功能。
+ 安全地執行工具：Lambda 允許工具存取 VPC 內的資源，而不必授予完整的 VPC 存取權。
+ 無伺服器架構：沒有基礎設施管理，Lambda 會自動處理擴展。
+ 成本效益：僅支付執行時間，而非閒置資源。
+ 輕鬆整合：Lambda 函數與內建工具一起無縫顯示。

若要讓 Amazon Bedrock 中的模型使用工具來完成訊息的回應，您可以將訊息和一或多個工具的定義傳送到模型。根據您應用程式的提示，如果模型判斷其中一個工具可協助產生回應，則會傳回 Bedrock 使用該工具的請求，並將工具結果傳回模型。模型接著會使用結果來產生對原始訊息的回應。

下列步驟說明如何搭配 [Responses 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。您可以在[此處](https://docs.aws.amazon.com/lambda/latest/dg/getting-started.html)閱讀更多有關部署 Lambda 函數的資訊。

```
# 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：在推論請求中定義訊息和工具定義**

若要傳送訊息和工具定義，您可以使用 [Responses API](https://docs.aws.amazon.com/bedrock/latest/userguide/bedrock-mantle.html) 操作。Amazon Bedrock 使用 Responses 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 呼叫工具並將回應傳遞回模型**

支援 [Responses API](https://platform.openai.com/docs/api-reference/responses/create) 的模型提供使用連接器工具的功能。[在此處](https://docs.aws.amazon.com/bedrock/latest/userguide/bedrock-mantle.html)檢查哪些工具支援您的模型。當您使用 回應 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 工具概觀**

此`notes`工具可讓您在相同的對話工作階段中存放和擷取鍵/值對。這提供了簡單的記憶體機制，用於維護多個互動之間的內容。金鑰是區分大小寫的字串，金鑰長度或命名慣例沒有限制。系統會覆寫相同金鑰的先前值。值會儲存為字串 (JSON、URLs等），且在工具層級不會強制執行大小限制。值會在整個對話工作階段中保留。記憶體範圍僅限於目前的對話。

**參數**


| 參數 | Type | 必要 | 描述 | 
| --- | --- | --- | --- | 
| operation | string | 是 | 要執行的操作： "store" 或 "recall" | 
| key | string | 是 | 記憶體項目的金鑰識別符 | 
| value | string | 有條件 | 要存放的值 （僅"store"操作需要） | 

**有效操作**
+ **`store`**：將鍵/值對儲存至記憶體
+ **`recall`**：依索引鍵擷取值

您可以使用自然語言 （例如，「記住我最愛的顏色是藍色」、「我告訴過您我最愛的顏色是什麼？」、「儲存我偏好早會的事實」、「回想我說過的會議偏好設定」) 或您可以在提示中使用直接工具呼叫 (「使用筆記工具將我的電子郵件儲存為 john@example.com」、「查看我電子郵件地址的筆記」)。

**任務工具概觀**

該`tasks`工具提供Last-In-First-Out(LIFO) 堆疊，用於管理對話工作階段中的任務。這可讓您將任務推送至堆疊，並以相反順序將其彈出，因此非常適合管理巢狀工作流程、暫時提醒或階層式任務管理。任務會在整個對話工作階段中保留。堆疊狀態會在多個互動之間維持。記憶體範圍僅限於目前的對話。


| 參數 | Type | 必要 | 描述 | 
| --- | --- | --- | --- | 
| operation | string | 是 | 要執行的操作： "push" 或 "pop" | 
| description | string | 有條件 | 任務項目的描述 （僅"push"操作需要） | 
| summary | string | 否 | 有關任務項目的選用摘要 （僅適用於 "push"操作） | 

您可以使用自然語言 （例如「新增任務以檢閱預算」、「推送提醒以呼叫用戶端」、「我需要執行的下一個任務是什麼？」、「退出最新任務」、「從我的堆疊取得最新任務」) 或直接在提示中呼叫工具 (「使用任務工具來推送「完成簡報」、「從堆疊中提取任務」、「新增「排程會議」到我的任務清單」)。

## 伺服器端工具使用與 AgentCore Gateway 整合
<a name="tool-use-agentcore-gateway"></a>

Amazon Bedrock 現在支援 [AgentCore Gateway](https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/gateway.html) 做為呼叫整合類型的伺服器端工具。此功能可讓您將模型直接連線至 AgentCore Gateway 端點，以便無縫存取透過閘道基礎設施管理的工具。

AgentCore Gateway 整合遵循與 Lambda 函數整合相同的模式，具有一個關鍵差異。

**Lambda 整合：**
+ 使用 Lambda ARNs
+ 直接叫用 AWS Lambda 函數

**AgentCore Gateway 整合：**
+ 使用 AgentCore Gateway ARNs
+ 透過 AgentCore Gateway 基礎設施路由工具呼叫
+ 提供集中式工具管理和探索

### Configuration
<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 | string | 是 | 必須設定為 mcp | 
| server\$1label | string | 是 | 請求中此工具連接器的唯一識別符 | 
| connector\$1id | string | 是 | AgentCore Gateway 的 ARN | 
| server\$1description | string | 否 | 此閘道所提供工具的人類可讀描述 | 
| require\$1approval | string | 是 | 欄位必須是 "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 Gateway 整合之前，請確定您有：

1. 建立具有設定目標的** AgentCore Gateway** (Lambda 函數、API Gateway 階段、OpenAPI 結構描述或 MCP 伺服器）

1. **已設定的 IAM 許可**，允許 Bedrock 服務角色叫用閘道。請注意，Bedrock 僅支援具有 IAM 身分驗證的閘道。

1. 正確格式的**閘道 ARN** 

### AgentCore Gateway 整合的優點
<a name="agentcore-gateway-benefits"></a>
+ **集中工具管理**：透過單一閘道端點管理所有工具
+ **工具探索**：客服人員可以透過閘道動態探索可用的工具
+ **安全性**：透過 IAM 和閘道政策的內建身分驗證和授權
+ 可**觀測性**：全面監控和記錄工具叫用
+ **彈性**：支援多種目標類型 (Lambda、API Gateway、OpenAPI、MCP 伺服器）

### IAM 許可
<a name="agentcore-gateway-iam"></a>

您的 Bedrock 執行角色需要許可才能叫用 AgentCore Gateway：

```
{
  "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 Gateway](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)