選取您的 Cookie 偏好設定

我們使用提供自身網站和服務所需的基本 Cookie 和類似工具。我們使用效能 Cookie 收集匿名統計資料,以便了解客戶如何使用我們的網站並進行改進。基本 Cookie 無法停用,但可以按一下「自訂」或「拒絕」以拒絕效能 Cookie。

如果您同意,AWS 與經核准的第三方也會使用 Cookie 提供實用的網站功能、記住您的偏好設定,並顯示相關內容,包括相關廣告。若要接受或拒絕所有非必要 Cookie,請按一下「接受」或「拒絕」。若要進行更詳細的選擇,請按一下「自訂」。

使用 Amazon SageMaker AI 筆記本執行範例 Amazon Bedrock API 請求

焦點模式
使用 Amazon SageMaker AI 筆記本執行範例 Amazon Bedrock API 請求 - Amazon Bedrock

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

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

本節會引導您使用 Amazon SageMaker AI 筆記本嘗試 Amazon Bedrock 中的一些常見操作,以測試您的 Amazon Bedrock 角色許可是否已正確設定。在執行下列範例之前,您應該檢查您是否符合下列先決條件:

先決條件

  • 您擁有 AWS 帳戶 和 許可,可存取具有 Amazon Bedrock 必要許可的角色。否則,請遵循 中的步驟我已經有 AWS 帳戶

  • 您已請求存取Amazon Titan Text G1 - Express模型。否則,請遵循 中的步驟請求存取 Amazon Bedrock 基礎模型

  • 執行下列步驟來設定 SageMaker AI 的 IAM 許可並建立筆記本:

    1. 我已經有 AWS 帳戶 透過主控台CLIAPI 修改您在 中設定的 Amazon Bedrock 角色的信任政策。將下列信任政策連接至角色,以允許 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" } ] }
    2. 登入您剛修改其信任政策的 Amazon Bedrock 角色。

    3. 請遵循建立 Amazon SageMaker AI 筆記本執行個體中的教學課程步驟,並指定您建立以建立 SageMaker AI 筆記本執行個體之 Amazon Bedrock 角色的 ARN。

    4. 當筆記本執行個體的狀態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)

如果命令成功,回應會傳回模型所產生的文字,以回應提示。

隱私權網站條款Cookie 偏好設定
© 2025, Amazon Web Services, Inc.或其附屬公司。保留所有權利。