AWS SDK for Python (Boto3) を使用して Amazon Bedrock API リクエストの例を実行する - Amazon Bedrock

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

AWS SDK for Python (Boto3) を使用して Amazon Bedrock API リクエストの例を実行する

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

前提条件

適切なアクセス許可を指定して設定したユーザーまたはロールを使用して、Amazon Bedrock のアクセス許可が正しく設定されていることをテストします。

Amazon Bedrock ドキュメントには、その他のプログラミング言語のコードサンプルも記載されています。詳細については、「AWSSDKsコード例」を参照してください。

Amazon Bedrock が提供する基盤モデルを一覧表示する

次の例では、Amazon Bedrock クライアントを使用して、ListFoundationModels オペレーションを実行します。ListFoundationModels は、該当リージョンの Amazon Bedrock で利用可能な基盤モデル (FM) を一覧表示します。次の SDK for Python スクリプトを実行して Amazon Bedrock クライアントを作成し、ListFoundationModels オペレーションをテストします。

""" 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 を使用してテキストプロンプトをモデルに送信し、テキストレスポンスを生成する

次の例では、Amazon Bedrock クライアントを使用して InvokeModel オペレーションを実行します。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 を使用してテキストプロンプトをモデルに送信し、テキストレスポンスを生成する

次の例では、Amazon Bedrock クライアントを使用して Converse オペレーションを実行します。サポートされている場合、InvokeModelConverse オペレーションを使用することをお勧めします。これにより、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)

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