

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

# 開始使用 API
<a name="getting-started-api"></a>

本節說明如何設定您的環境，透過 AWS API 提出 Amazon Bedrock 請求。 AWS 提供下列工具來簡化您的體驗：
+ AWS Command Line Interface (AWS CLI)
+ AWS SDKs
+ 使用 Amazon SageMaker AI 筆記本

若要開始使用 API，您需要憑證才能授予程式設計存取權。如果下列各節與您相關，請展開它們並遵循指示。否則，請繼續完成其餘區段。

## 我第一次使用 AWS
<a name="gs-api-new-to-aws"></a>

如果您沒有 AWS 帳戶，請完成下列步驟來建立一個。

**註冊 AWS 帳戶**

1. 開啟 [https://portal.aws.amazon.com/billing/signup](https://portal.aws.amazon.com/billing/signup)。

1. 請遵循線上指示進行。

   部分註冊程序需接收來電或簡訊，並在電話鍵盤輸入驗證碼。

   當您註冊 時 AWS 帳戶，*AWS 帳戶根使用者*會建立 。根使用者有權存取該帳戶中的所有 AWS 服務 和資源。作為安全最佳實務，請將管理存取權指派給使用者，並且僅使用根使用者來執行[需要根使用者存取權的任務](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html#root-user-tasks)。

AWS 會在註冊程序完成後傳送確認電子郵件給您。您可以隨時登錄 [https://aws.amazon.com/](https://aws.amazon.com/) 並選擇**我的帳戶**，以檢視您目前的帳戶活動並管理帳戶。

**保護您的 AWS 帳戶根使用者**

1.  選擇**根使用者**並輸入 AWS 帳戶 您的電子郵件地址，以帳戶擁有者[AWS 管理主控台](https://console.aws.amazon.com/)身分登入 。在下一頁中，輸入您的密碼。

   如需使用根使用者登入的說明，請參閱 *AWS 登入 使用者指南*中的[以根使用者身分登入](https://docs.aws.amazon.com/signin/latest/userguide/console-sign-in-tutorials.html#introduction-to-root-user-sign-in-tutorial)。

1. 若要在您的根使用者帳戶上啟用多重要素驗證 (MFA)。

   如需說明，請參閱《*IAM 使用者指南*》中的[為您的 AWS 帳戶 根使用者 （主控台） 啟用虛擬 MFA 裝置](https://docs.aws.amazon.com/IAM/latest/UserGuide/enable-virt-mfa-for-root.html)。

## 我需要安裝 AWS CLI 或 AWS 開發套件
<a name="gs-api-cli-sdk-install"></a>

若要安裝 AWS CLI，請遵循[安裝或更新至最新版本 AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)中的步驟。

若要安裝 AWS SDK，請選取與您想要在 [Tools to Build on AWS](https://aws.amazon.com/developer/tools/). AWS software 開發套件 (SDKs) 中使用的程式設計語言對應的索引標籤，適用於許多熱門的程式設計語言。每個 SDK 都提供 API、程式碼範例和說明文件，讓開發人員能夠更輕鬆地以偏好的語言建置應用程式。SDK 會自動為您執行有用的任務，例如：
+ 加密簽署服務請求
+ 重試請求
+ 處理錯誤回應

## 取得憑證以授予程式設計存取權
<a name="gs-grant-program-access"></a>

如果使用者想要與 AWS 外部互動，則需要程式設計存取 AWS 管理主控台。 會根據您的安全性考量 AWS 提供多個選項。

**注意**  
如需逐步指南，以產生可用來快速存取 Amazon Bedrock API 的 API 金鑰，請參閱 [開始使用 Amazon Bedrock API 金鑰：產生 30 天金鑰並發出您的第一次 API 呼叫](getting-started-api-keys.md)。  
如需更高的安全需求，請繼續完成本節。

授予程式設計存取權的方式取決於正在存取的使用者類型 AWS。

若要授與使用者程式化存取權，請選擇下列其中一個選項。


****  

| 哪個主體需要程式設計存取權？ | 到 | 根據 | 
| --- | --- | --- | 
| IAM 使用者 | 限制長期憑證的持續時間，以簽署對 AWS CLI、 AWS SDKs程式設計請求。 AWS APIs |  請依照您要使用的介面所提供的指示操作。 [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/bedrock/latest/userguide/getting-started-api.html)  | 
| IAM 角色 | 使用暫時登入資料簽署對 AWS CLI、 AWS SDKs程式設計請求。 AWS APIs | 遵循《IAM 使用者指南》中[將臨時登入資料與 AWS 資源](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html)搭配使用的指示。 | 
|  人力資源身分 (IAM Identity Center 中管理的使用者)  | 使用暫時登入資料簽署對 AWS CLI、 AWS SDKs程式設計請求。 AWS APIs |  請依照您要使用的介面所提供的指示操作。 [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/bedrock/latest/userguide/getting-started-api.html)  | 

## 如何設定 IAM 使用者的存取金鑰
<a name="create-user-time-bound"></a>

如果您決定使用 IAM 使用者的存取金鑰， AWS 建議您透過包含限制性內嵌政策來設定 IAM 使用者的過期。

**重要**  
請注意下列警告：  
**請勿使用**您帳戶的根登入資料來存取 AWS 資源。這些登入資料可讓未管制的帳戶存取和很難撤銷這些帳戶。
**請勿**在應用程式檔案中放置常值存取金鑰或憑證資訊。如果您不小心這麼做了，則會有暴露您登入資料的風險，例如，當您上傳專案到公有儲存庫時。
**請勿在**您的專案區域中放入包含憑證的檔案。
安全地管理存取金鑰。請勿將您的存取金鑰提供給未經授權的當事方，即便是協助[尋找您的帳戶識別符](https://docs.aws.amazon.com/general/latest/gr/acct-identifiers.html)也不妥。如果這麼做，就可能會讓他人能夠永久存取您的帳戶。
請注意，存放在共用登入資料檔案中的任何 AWS 登入資料都會以純文字儲存。

如需詳細資訊，請參閱 中[管理 AWS 存取金鑰的最佳實務](https://docs.aws.amazon.com/general/latest/gr/aws-access-keys-best-practices.html) AWS 一般參考。

**建立 IAM 使用者**

1. 在 AWS 管理主控台 首頁上，選取 IAM 服務或導覽至 IAM 主控台，網址為 https：//[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/)。

1. 在導覽窗格中選取**使用者**，然後選取**建立使用者**。

1. 遵循 IAM 主控台中的指引，設定程式設計使用者 （無法存取 AWS 管理主控台) 且沒有許可。

**限制使用者對有限時段的存取**

您建立的任何 IAM 使用者存取金鑰都是長期憑證。為了確保這些憑證在處理不當時過期，您可以建立內嵌政策，指定金鑰不再有效的日期，讓這些憑證有時間限制。

1. 開啟您剛才建立的 IAM 使用者。在**許可**標籤中，選擇**新增許可**，然後選擇**建立內嵌政策**。

1. 在 JSON 編輯器中，指定下列許可。若要使用此政策，請將範例政策中 `aws:CurrentTime` 時間戳記值的值取代為您自己的結束日期。
**注意**  
IAM 建議您將存取金鑰限制為 12 小時。

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

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement": [
       {
         "Effect": "Deny",
         "Action": "*",
         "Resource": "*",
         "Condition": {
           "DateGreaterThan": {
             "aws:CurrentTime": "2024-01-01T00:00:000"
           }
         }
       }
     ]
   }
   ```

------

**建立存取金鑰**

1. 在**使用者詳細資訊**頁面上，選取**安全憑證**頁面。在**存取金鑰**區段中，選擇**建立存取金鑰**。

1. 表示您計劃使用這些存取金鑰做為**其他**，然後選擇**建立存取金鑰**。

1. 在**擷取存取金鑰**頁面上，選擇**顯示**以顯示您的使用者的私密存取金鑰的值。您可以複製憑證或下載 .csv 檔案。

**重要**  
當您不再需要此 IAM 使用者時，我們建議您將其移除並符合[AWS 安全最佳實務](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#lock-away-credentials)，我們建議您要求人類使用者在存取時透過 [AWS IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/getting-started.html) 使用臨時憑證 AWS。

## 將 Amazon Bedrock 許可連接至使用者或角色
<a name="gs-api-br-permissions"></a>

設定程式設計存取的憑證後，您需要設定使用者或 IAM 角色的許可，才能存取一組 Amazon Bedrock 相關動作。若要設定這些許可，請執行下列動作：

1. 在 AWS 管理主控台 首頁上，選取 IAM 服務或導覽至 IAM 主控台，網址為 https：//[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/)。

1. 選取**使用者**或**角色**，然後選取您的使用者或角色。

1. 在**許可**索引標籤中，選擇**新增許可**，然後選擇**新增 AWS 受管政策**。選擇 [AmazonBedrockFullAccess]() AWS 受管政策。

1. 若要允許使用者或角色訂閱模型，請選擇**建立內嵌政策**，然後在 JSON 編輯器中指定下列許可：

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

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement": [
         {
             "Sid": "MarketplaceBedrock",
             "Effect": "Allow",
             "Action": [
                 "aws-marketplace:ViewSubscriptions",
                 "aws-marketplace:Unsubscribe",
                 "aws-marketplace:Subscribe"
             ],
             "Resource": "*"
         }
     ]
   }
   ```

------

## 嘗試對 Amazon Bedrock 進行 API 呼叫
<a name="gs-try-bedrock"></a>

在您滿足所有先決條件之後，請選取下列其中一個主題，以測試使用 Amazon Bedrock 模型提出模型調用請求：

**Topics**
+ [取得憑證以授予程式設計存取權](#gs-grant-program-access)
+ [將 Amazon Bedrock 許可連接至使用者或角色](#gs-api-br-permissions)
+ [嘗試對 Amazon Bedrock 進行 API 呼叫](#gs-try-bedrock)
+ [開始使用 Amazon Bedrock API 金鑰：產生 30 天金鑰並發出您的第一次 API 呼叫](getting-started-api-keys.md)
+ [使用 執行範例 Amazon Bedrock API 請求 AWS Command Line Interface](getting-started-api-ex-cli.md)
+ [透過適用於 Python 的 AWS SDK (Boto3) 執行範例 Amazon Bedrock API 請求](getting-started-api-ex-python.md)
+ [使用 Amazon SageMaker AI 筆記本執行範例 Amazon Bedrock API 請求](getting-started-api-ex-sm.md)

# 開始使用 Amazon Bedrock API 金鑰：產生 30 天金鑰並發出您的第一次 API 呼叫
<a name="getting-started-api-keys"></a>

本教學課程會逐步引導您建立在 30 天內過期的長期 Amazon Bedrock API 金鑰，並使用它透過 Python 進行簡單的 [Converse](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html) API 呼叫。這是開始試驗 Amazon Bedrock 而不設定複雜 AWS 登入資料最快的方式。

**警告**  
建議僅用於探索和開發 Amazon Bedrock 的長期 API 金鑰。對於生產應用程式，請使用[長期存取金鑰的替代方案](https://docs.aws.amazon.com/IAM/latest/UserGuide/security-creds-programmatic-access.html#security-creds-alternatives-to-long-term-access-keys)，例如 IAM 角色或暫時憑證。

請依照下列步驟，建立在 30 天後過期的長期 Amazon Bedrock API 金鑰：

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

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

1. 在**長期 API 金鑰**索引標籤中，選擇**產生長期 API 金鑰**。

1. 在 **API 金鑰過期**區段中，選取 **30 天**。

1. 選擇 **Generate (產生)**。您產生的金鑰提供執行核心 Amazon Bedrock 動作的許可，如連接的 [AmazonBedrockLimitedAccess](security-iam-awsmanpol.md#security-iam-awsmanpol-AmazonBedrockLimitedAccess) 政策所定義。

1. 複製產生的 API 金鑰並將其安全地存放。在下一個步驟中，您將需要用到此金鑰。
**重要**  
API 金鑰只會顯示一次。請務必先複製並儲存後，再關閉對話方塊。請記住，您的 API 金鑰將在 30 天後過期。您可以依照相同的步驟產生新的身分驗證方法，或考慮轉換為更安全的身分驗證方法以持續使用。

1. 將 API 金鑰設定為環境變數，方法是將 *\$1\$1api-key\$1* 取代為您產生的 API 金鑰值，並使用它在您選擇的方法中產生回應：

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

   ```
   import boto3
   import os
   
   # Set the API key as an environment variable
   os.environ['AWS_BEARER_TOKEN_BEDROCK'] = "${api-key}"
   
   # Create the Bedrock client
   client = boto3.client(
       service_name="bedrock-runtime",
       region_name="us-east-1"
   )
   
   # Define the model and message
   model_id = "us.anthropic.claude-3-5-haiku-20241022-v1:0"
   messages = [{"role": "user", "content": [{"text": "Hello! Can you tell me about Amazon Bedrock?"}]}]
   
   # Make the API call
   response = client.converse(
       modelId=model_id,
       messages=messages,
   )
   
   # Print the response
   print(response['output']['message']['content'][0]['text'])
   ```

------
#### [ HTTP client using Python ]

   ```
   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 -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 ${api-key}" \
     -d '{
       "messages": [
           {
               "role": "user",
               "content": [{"text": "Hello"}]
           }
       ]
     }'
   ```

------

恭喜您！您已成功產生 Amazon Bedrock API 金鑰，並對 Amazon Bedrock 服務進行第一次 API 呼叫。探索更多 Amazon Bedrock 動作之後，您應該轉換到更安全的身分驗證方法，例如短期 Amazon Bedrock API 金鑰或 AWS整體臨時憑證。請參閱下列資源以進一步了解：
+ **探索不同的模型** – 了解 Amazon Bedrock 在 [Amazon Bedrock 基礎模型資訊](foundation-models-reference.md) 提供的其他基礎模型，並變更程式碼中的 `model_id` 來試用這些模型。
+ **了解模型推論** – 閱讀 Amazon Bedrock 在 [提交提示並使用模型推論產生回應](inference.md) 提供的概念和選項，了解如何透過模型推論產生回應。
+ **使用更安全的身分驗證方法規劃生產** – 進一步了解建置章節中的 Amazon Bedrock API 金鑰，以及如何建立更安全、短期的 Amazon Bedrock API 金鑰。當您準備好建置生產應用程式時，您也應該檢閱[長期存取金鑰的替代方案](https://docs.aws.amazon.com/IAM/latest/UserGuide/security-creds-programmatic-access.html#security-creds-alternatives-to-long-term-access-keys)，以取得更安全的選項，以允許存取其他 AWS 服務。

# 使用 執行範例 Amazon Bedrock API 請求 AWS Command Line Interface
<a name="getting-started-api-ex-cli"></a>

本節會引導您使用 在 Amazon Bedrock 中嘗試一些常見操作 AWS Command Line Interface ，以測試您的許可和身分驗證是否已正確設定。在執行下列範例之前，您應該檢查是否符合下列必要條件：

**先決條件**
+ 您有 AWS 帳戶 和已設定身分驗證的使用者或角色，以及 Amazon Bedrock 的必要許可。否則，請依照 [開始使用 API](getting-started-api.md) 中的步驟進行。
+ 您已安裝並設定 AWS CLI的身分驗證。若要安裝 AWS CLI，請遵循[安裝或更新至最新版本 AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)中的步驟。遵循 [取得憑證以授予程式設計存取權](getting-started-api.md#gs-grant-program-access) 中的步驟，確認您已設定憑證來使用 CLI。

使用您以適當許可設定的使用者或角色，測試您的 Amazon Bedrock 許可是否已正確設定。

**Topics**
+ [列出 Amazon Bedrock 必須提供的基礎模型](#getting-started-api-ex-cli-listfm)
+ [向模型提交文字提示，並使用 InvokeModel 產生文字回應](#getting-started-api-ex-cli-invoke-text)
+ [向模型提交文字提示，並使用 Converse 產生文字回應](#getting-started-api-ex-cli-converse)

## 列出 Amazon Bedrock 必須提供的基礎模型
<a name="getting-started-api-ex-cli-listfm"></a>

下列範例使用 執行 [ListFoundationModels](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_ListFoundationModels.html) 操作 AWS CLI。 `ListFoundationModels`列出您區域中 Amazon Bedrock 中可用的基礎模型 (FMs)。在終端機中，執行下列命令：

```
aws bedrock list-foundation-models
```

如果命令成功，回應會傳回 Amazon Bedrock 中可用的基礎模型清單。

## 向模型提交文字提示，並使用 InvokeModel 產生文字回應
<a name="getting-started-api-ex-cli-invoke-text"></a>

下列範例使用 執行 [InvokeModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html) 操作 AWS CLI。 `InvokeModel`可讓您提交提示以產生模型回應。在終端機中，執行下列命令：

```
aws bedrock-runtime invoke-model \
--model-id amazon.titan-text-express-v1 \
--body '{"inputText": "Describe the purpose of a \"hello world\" program in one line.", "textGenerationConfig" : {"maxTokenCount": 512, "temperature": 0.5, "topP": 0.9}}' \
--cli-binary-format raw-in-base64-out \
invoke-model-output-text.txt
```

如果命令成功，則模型產生的回應會寫入 `invoke-model-output-text.txt` 檔案。文字回應以及隨附的資訊會在 `outputText` 欄位中傳回。

## 向模型提交文字提示，並使用 Converse 產生文字回應
<a name="getting-started-api-ex-cli-converse"></a>

下列範例使用 執行 [Converse](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html) 操作 AWS CLI。 `Converse`可讓您提交提示以產生模型回應。建議在支援時對 `InvokeModel` 使用 `Converse` 操作，因為它會統一跨 Amazon Bedrock 模型的推論請求，並簡化多回合對話的管理。在終端機中，執行下列命令：

```
aws bedrock-runtime converse \
--model-id amazon.titan-text-express-v1 \
--messages '[{"role": "user", "content": [{"text": "Describe the purpose of a \"hello world\" program in one line."}]}]' \
--inference-config '{"maxTokens": 512, "temperature": 0.5, "topP": 0.9}'
```

如果命令成功，則 `text` 欄位中會傳回模型產生的回應，以及隨附的資訊。

# 透過適用於 Python 的 AWS SDK (Boto3) 執行範例 Amazon Bedrock API 請求
<a name="getting-started-api-ex-python"></a>

本節會引導您使用 嘗試 Amazon Bedrock 中的一些常見操作Python， AWS 以測試您的許可和身分驗證是否已正確設定。在執行下列範例之前，您應該檢查是否符合下列必要條件：

**先決條件**
+ 您有 AWS 帳戶 和已設定身分驗證的使用者或角色，以及 Amazon Bedrock 的必要許可。否則，請依照 [開始使用 API](getting-started-api.md) 中的步驟進行。
+ 您已安裝並設定適用於 Python (Boto3) 的 AWS SDK 的身分驗證。若要安裝 Boto3，請遵循 Boto3 文件中的 [Quickstart](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html) 步驟。遵循 [取得憑證以授予程式設計存取權](getting-started-api.md#gs-grant-program-access) 中的步驟，確認您已設定憑證來使用 Boto3。

使用您以適當許可設定的使用者或角色，測試您的 Amazon Bedrock 許可是否已正確設定。

Amazon Bedrock 文件也包含其他程式設計語言的程式碼範例。如需詳細資訊，請參閱[使用 AWS SDKs Amazon Bedrock 程式碼範例](service_code_examples.md)。

**Topics**
+ [列出 Amazon Bedrock 必須提供的基礎模型](#getting-started-api-ex-python-listfm)
+ [向模型提交文字提示，並使用 InvokeModel 產生文字回應](#getting-started-api-ex-python-invoke-text)
+ [向模型提交文字提示，並使用 Converse 產生文字回應](#getting-started-api-ex-python-converse)

## 列出 Amazon Bedrock 必須提供的基礎模型
<a name="getting-started-api-ex-python-listfm"></a>

下列範例使用 Amazon Bedrock 用戶端執行 [ListFoundationModels](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_ListFoundationModels.html) 操作。`ListFoundationModels` 列出您所在區域的 Amazon Bedrock 中可用的基礎模型 (FM)。執行下列適用於 Python 的 SDK 指令碼來建立 Amazon Bedrock 用戶端，並測試 [ListFoundationModels](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_ListFoundationModels.html) 操作：

```
"""
Lists the available Amazon Bedrock models in an &AWS-Region;.
"""
import logging
import json
import boto3


from botocore.exceptions import ClientError


logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


def list_foundation_models(bedrock_client):
    """
    Gets a list of available Amazon Bedrock foundation models.

    :return: The list of available bedrock foundation models.
    """

    try:
        response = bedrock_client.list_foundation_models()
        models = response["modelSummaries"]
        logger.info("Got %s foundation models.", len(models))
        return models

    except ClientError:
        logger.error("Couldn't list foundation models.")
        raise


def main():
    """Entry point for the example. Change aws_region to the &AWS-Region;
    that you want to use."""
   
    aws_region = "us-east-1"

    bedrock_client = boto3.client(service_name="bedrock", region_name=aws_region)
    
    fm_models = list_foundation_models(bedrock_client)
    for model in fm_models:
        print(f"Model: {model["modelName"]}")
        print(json.dumps(model, indent=2))
        print("---------------------------\n")
    
    logger.info("Done.")

if __name__ == "__main__":
    main()
```

如果指令碼成功，回應會傳回 Amazon Bedrock 中可用的基礎模型清單。

## 向模型提交文字提示，並使用 InvokeModel 產生文字回應
<a name="getting-started-api-ex-python-invoke-text"></a>

下列範例使用 Amazon Bedrock 用戶端執行 [InvokeModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html) 操作。`InvokeModel` 可讓您提交提示以產生模型回應。執行下列適用於 Python 的 SDK 指令碼來建立 Amazon Bedrock 執行時期用戶端，並使用 `` 操作產生文字回應：

```
# Use the native inference API to send a text message to Amazon Titan Text G1 - Express.

import boto3
import json

from botocore.exceptions import ClientError

# Create an Amazon Bedrock Runtime client.
brt = boto3.client("bedrock-runtime")

# Set the model ID, e.g., Amazon Titan Text G1 - Express.
model_id = "amazon.titan-text-express-v1"

# 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,
        "topP": 0.9
    },
}

# Convert the native request to JSON.
request = json.dumps(native_request)

try:
    # Invoke the model with the request.
    response = brt.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)
```

如果命令成功，回應會傳回模型所產生的文字，以回應提示。

## 向模型提交文字提示，並使用 Converse 產生文字回應
<a name="getting-started-api-ex-python-converse"></a>

下列範例使用 Amazon Bedrock 用戶端執行 [Converse](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html) 操作。建議在支援時對 `InvokeModel` 使用 `Converse` 操作，因為它會統一跨 Amazon Bedrock 模型的推論請求，並簡化多回合對話的管理。執行下列適用於 Python 的 SDK 指令碼來建立 Amazon Bedrock 執行時期用戶端，並使用 `Converse` 操作產生文字回應：

```
# Use the Conversation API to send a text message to Amazon Titan Text G1 - Express.

import boto3
from botocore.exceptions import ClientError

# Create an Amazon Bedrock Runtime client.
brt = boto3.client("bedrock-runtime")

# Set the model ID, e.g., Amazon Titan Text G1 - Express.
model_id = "amazon.titan-text-express-v1"

# Start a conversation with the user message.
user_message = "Describe the purpose of a 'hello world' program in one line."
conversation = [
    {
        "role": "user",
        "content": [{"text": user_message}],
    }
]

try:
    # Send the message to the model, using a basic inference configuration.
    response = brt.converse(
        modelId=model_id,
        messages=conversation,
        inferenceConfig={"maxTokens": 512, "temperature": 0.5, "topP": 0.9},
    )

    # Extract and print the response text.
    response_text = response["output"]["message"]["content"][0]["text"]
    print(response_text)

except (ClientError, Exception) as e:
    print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}")
    exit(1)
```

如果命令成功，回應會傳回模型所產生的文字，以回應提示。

# 使用 Amazon SageMaker AI 筆記本執行範例 Amazon Bedrock API 請求
<a name="getting-started-api-ex-sm"></a>

本節引導您使用 Amazon SageMaker AI 筆記本在 Amazon Bedrock 中嘗試一些常見操作，以測試您的 Amazon Bedrock 角色許可是否已正確設定。在執行下列範例之前，您應該檢查是否符合下列必要條件：

**先決條件**
+ 您擁有 AWS 帳戶 和 許可，可存取具有 Amazon Bedrock 必要許可的角色。否則，請依照 [快速指南](getting-started.md) 中的步驟進行。
+ 執行下列步驟來設定 SageMaker AI 的 IAM 許可並建立筆記本：

  1. 透過[主控台](https://docs.aws.amazon.com/IAM/latest/UserGuide/roles-managingrole-editing-console.html#roles-managingrole_edit-trust-policy)、[CLI](https://docs.aws.amazon.com/IAM/latest/UserGuide/roles-managingrole-editing-cli.html#roles-managingrole_edit-trust-policy-cli) 或 [API](https://docs.aws.amazon.com/IAM/latest/UserGuide/roles-managingrole-editing-api.html#roles-managingrole_edit-trust-policy-api) 修改您在 [快速指南](getting-started.md) 中設定的 Amazon Bedrock 角色的[信任政策](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts.html#term_trust-policy)。將下列信任政策連接至角色，以允許 Amazon Bedrock 和 SageMaker AI 服務擔任 Amazon Bedrock 角色：

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

****  

     ```
     {
         "Version":"2012-10-17",		 	 	 
         "Statement": [
             {
                 "Sid": "BedrockTrust",
                 "Effect": "Allow",
                 "Principal": {
                     "Service": "bedrock.amazonaws.com"
                 },
                 "Action": "sts:AssumeRole"
             },
             {
                 "Sid": "SagemakerTrust",
                 "Effect": "Allow",
                 "Principal": {
                     "Service": "sagemaker.amazonaws.com"
                 },
                 "Action": "sts:AssumeRole"
             }
         ]
     }
     ```

------

  1. 登入您剛修改其信任政策的 Amazon Bedrock 角色。

  1. 請遵循[建立教學課程的 Amazon SageMaker 筆記本執行個體](https://docs.aws.amazon.com/sagemaker/latest/dg/gs-setup-working-env.html)中的步驟，並指定您建立以建立 SageMaker AI 筆記本執行個體之 Amazon Bedrock 角色的 ARN。

  1. 當筆記本執行個體的**狀態**為 **InService** 時，請選擇執行個體，然後選擇**開啟 JupyterLab**。

開啟 SageMaker AI 筆記本後，您可以嘗試下列範例：

**Topics**
+ [列出 Amazon Bedrock 必須提供的基礎模型](#getting-started-api-ex-sm-listfm)
+ [向模型提交文字提示，並產生文字回應](#getting-started-api-ex-sm-converse)

## 列出 Amazon Bedrock 必須提供的基礎模型
<a name="getting-started-api-ex-sm-listfm"></a>

下列範例使用 Amazon Bedrock 用戶端執行 [ListFoundationModels](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_ListFoundationModels.html) 操作。`ListFoundationModels` 列出您所在區域的 Amazon Bedrock 中可用的基礎模型 (FM)。執行下列適用於 Python 的 SDK 指令碼來建立 Amazon Bedrock 用戶端，並測試 [ListFoundationModels](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_ListFoundationModels.html) 操作：

```
"""
Lists the available Amazon Bedrock models in an &AWS-Region;.
"""
import logging
import json
import boto3


from botocore.exceptions import ClientError


logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


def list_foundation_models(bedrock_client):
    """
    Gets a list of available Amazon Bedrock foundation models.

    :return: The list of available bedrock foundation models.
    """

    try:
        response = bedrock_client.list_foundation_models()
        models = response["modelSummaries"]
        logger.info("Got %s foundation models.", len(models))
        return models

    except ClientError:
        logger.error("Couldn't list foundation models.")
        raise


def main():
    """Entry point for the example. Change aws_region to the &AWS-Region;
    that you want to use."""
   
    aws_region = "us-east-1"

    bedrock_client = boto3.client(service_name="bedrock", region_name=aws_region)
    
    fm_models = list_foundation_models(bedrock_client)
    for model in fm_models:
        print(f"Model: {model["modelName"]}")
        print(json.dumps(model, indent=2))
        print("---------------------------\n")
    
    logger.info("Done.")

if __name__ == "__main__":
    main()
```

如果指令碼成功，回應會傳回 Amazon Bedrock 中可用的基礎模型清單。

## 向模型提交文字提示，並產生文字回應
<a name="getting-started-api-ex-sm-converse"></a>

下列範例使用 Amazon Bedrock 用戶端執行 [Converse](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html) 操作。`Converse` 可讓您提交提示以產生模型回應。執行下列適用於 Python 的 SDK 指令碼來建立 Amazon Bedrock 執行時期用戶端，並測試 [Converse](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html) 操作：

```
# Use the Conversation API to send a text message to Amazon Titan Text G1 - Express.

import boto3
from botocore.exceptions import ClientError

# Create an Amazon Bedrock Runtime client.
brt = boto3.client("bedrock-runtime")

# Set the model ID, e.g., Amazon Titan Text G1 - Express.
model_id = "amazon.titan-text-express-v1"

# Start a conversation with the user message.
user_message = "Describe the purpose of a 'hello world' program in one line."
conversation = [
    {
        "role": "user",
        "content": [{"text": user_message}],
    }
]

try:
    # Send the message to the model, using a basic inference configuration.
    response = brt.converse(
        modelId=model_id,
        messages=conversation,
        inferenceConfig={"maxTokens": 512, "temperature": 0.5, "topP": 0.9},
    )

    # Extract and print the response text.
    response_text = response["output"]["message"]["content"][0]["text"]
    print(response_text)

except (ClientError, Exception) as e:
    print(f"ERROR: Can't invoke '{model_id}'. Reason: {e}")
    exit(1)
```

如果命令成功，回應會傳回模型所產生的文字，以回應提示。