通過 Python(博托 3)運行示例 Amazon 基岩API請求 AWS SDK - Amazon Bedrock

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

通過 Python(博托 3)運行示例 Amazon 基岩API請求 AWS SDK

本節將引導您嘗試 Amazon Bdrock 中的一些常見操作,以測試您的許可和身份驗證是否已正確設置。在執行下列範例之前,請先檢查您是否符合下列先決條件:

先決條件

使用您建立的 Amazon 基岩角色測試您的許可和存取金鑰是否已正確設定 Amazon 基岩。這些範例假設您已使用存取金鑰設定環境。注意下列事項:

  • 最低限度,您必須指定 AWS 存取金鑰 ID 和 AWS 秘密存取金鑰。

  • 如果您使用臨時憑據,則還必須包含會 AWS 話令牌。

如果您未在環境中指定登入資料,則可以在為 Amazon Bdrock 操作建立用戶端時指定登入資料。若要這麼做,請在aws_access_key_id建立用戶端時加入aws_secret_access_key、和 (如果您使用短期憑證) aws_session_token 引數。

列出 Amazon 基岩必須提供的基礎模型

下列範例會使用 Amazon 基岩用戶端執行ListFoundationModels作業。 ListFoundationModels列出您所在地區的 Amazon 基岩中可用的基礎模型 (FMs)。SDK對 Python 腳本運行以下命令以創建 Amazon 基岩客戶端並測試操作 ListFoundationModels

# Use the ListFoundationModels API to show the models that are available in your region. import boto3 # Create an &BR; client in the &region-us-east-1; Region. bedrock = boto3.client( service_name="bedrock" ) bedrock.list_foundation_models()

如果指令碼成功,回應會傳回 Amazon 基岩中可用的基礎模型清單。

向模型提交文本提示並生成文本響應 InvokeModel

下列範例會使用 Amazon 基岩用戶端執行InvokeModel作業。 InvokeModel可讓您提交產生模型回應的提示。SDK針對 Python 指令碼執行下列指令,以建立 Amazon 基岩執行階段用戶端,並透過該作業產生文字回應:

# 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 基岩用戶端執行匡威作業。我們建議在受支援的情況下使用Converse操作,因為它可以統一跨 Amazon Bedrock 模型的推論請求,並簡化多InvokeModel回合對話的管理。SDK針對 Python 指令碼執行下列指令,以建立 Amazon 基岩執行階段用戶端,並透過該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)

如果指令成功,則回應會傳回模型為回應提示而產生的文字。