本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
使用 Amazon SageMaker AI 筆記本執行範例 Amazon Bedrock API 請求
本節將引導您嘗試使用 Amazon SageMaker AI 筆記本在 Amazon Bedrock 中執行一些常見操作,以測試您的 Amazon Bedrock 角色許可是否已正確設定。執行下列範例之前,您應該檢查您是否符合下列先決條件:
先決條件
-
您擁有 AWS 帳戶 和 許可,可存取具有 Amazon Bedrock 必要許可的角色。否則,請遵循 中的步驟我已經有一個 AWS 帳戶。
-
您已請求存取Amazon Titan Text G1 - Express模型。否則,請遵循 中的步驟請求存取 Amazon Bedrock 基礎模型。
-
執行下列步驟來設定 SageMaker AI 的 IAM 許可並建立筆記本:
-
透過主控台、CLI 或 API 修改您在 中設定的 Amazon Bedrock 角色我已經有一個 AWS 帳戶的信任政策。將下列信任政策連接至角色,以允許 Amazon Bedrock 和 SageMaker AI 服務擔任 Amazon Bedrock 角色:
{ "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" } ] }
-
登入您剛修改其信任政策的 Amazon Bedrock 角色。
-
請遵循建立 Amazon SageMaker AI 筆記本執行個體中的教學課程步驟,並指定您為建立 SageMaker AI 筆記本執行個體而建立之 Amazon Bedrock 角色的 ARN。
-
當筆記本執行個體的狀態為 InService 時,請選擇執行個體,然後選擇開啟 JupyterLab。
-
開啟 SageMaker AI 筆記本之後,您可以嘗試下列範例:
列出 Amazon Bedrock 必須提供的基礎模型
下列範例使用 Amazon Bedrock 用戶端執行 ListFoundationModels 操作。 ListFoundationModels
列出您區域中 Amazon Bedrock 中可用的基礎模型 (FMs)。執行下列適用於 Python 的 SDK 指令碼來建立 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 中可用的基礎模型清單。
提交文字提示給模型並產生回應
下列範例使用 Amazon Bedrock 用戶端執行 Converse 操作。 Converse
可讓您提交提示以產生模型回應。執行下列適用於 Python 的 SDK 指令碼,以建立 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)
如果命令成功,回應會傳回模型所產生的文字,以回應提示。