

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

# AWS SDK for Python (Boto3) を使用して Amazon Bedrock API リクエストの例を実行する
<a name="getting-started-api-ex-python"></a>

このセクションでは、 を使用して AWS Amazon Bedrock の一般的なオペレーションを試Pythonして、アクセス許可と認証が適切に設定されていることをテストする方法について説明します。次の例を実行する前に、次の前提条件が満たされていることを確認してください。

**前提条件**
+  AWS アカウント 認証が設定され、Amazon Bedrock に必要なアクセス許可を持つ とユーザーまたはロールがあります。そうでない場合は、「[API の使用を開始する](getting-started-api.md)」の手順を実行します。
+  AWS SDK for Python (Boto3) の認証をインストールしてセットアップしました。Boto3 をインストールするには、Boto3 ドキュメントの「[クイックスタート](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コード例](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) を一覧表示します。次の 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 で使用できる基盤モデルのリストを返します。

## 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` では、プロンプトを送信してモデルレスポンスを生成できます。次の SDK for Python スクリプトを実行して 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 モデル間で推論リクエストを統合し、マルチターン対話の管理を簡素化できます。次の SDK for Python スクリプトを実行して 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)
```

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