

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

# 使用 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 Nova Micro.

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 Nova Micro.
model_id = "amazon.nova-micro-v1:0"

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

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