

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# 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 の 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 AI ノートブックインスタンスを作成する](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) を一覧表示します。次の SDK for Python スクリプトを実行して 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` では、プロンプトを送信してモデルレスポンスを生成できます。次の SDK for Python スクリプトを実行して 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)
```

コマンドが成功すると、レスポンスは、プロンプトに応答してモデルによって生成されたテキストを返します。