Cookie の設定を選択する

当社は、当社のサイトおよびサービスを提供するために必要な必須 Cookie および類似のツールを使用しています。当社は、パフォーマンス Cookie を使用して匿名の統計情報を収集することで、お客様が当社のサイトをどのように利用しているかを把握し、改善に役立てています。必須 Cookie は無効化できませんが、[カスタマイズ] または [拒否] をクリックしてパフォーマンス Cookie を拒否することはできます。

お客様が同意した場合、AWS および承認された第三者は、Cookie を使用して便利なサイト機能を提供したり、お客様の選択を記憶したり、関連する広告を含む関連コンテンツを表示したりします。すべての必須ではない Cookie を受け入れるか拒否するには、[受け入れる] または [拒否] をクリックしてください。より詳細な選択を行うには、[カスタマイズ] をクリックしてください。

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

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

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

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

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

前提条件

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

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

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

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

""" Lists the available Amazon Bedrock models. """ 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. Uses the AWS SDK for Python (Boto3) to create an Amazon Bedrock client. Then lists the available Bedrock models in the region set in the callers profile and credentials. """ bedrock_client = boto3.client(service_name="bedrock") 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)

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

プライバシーサイト規約Cookie の設定
© 2025, Amazon Web Services, Inc. or its affiliates.All rights reserved.