

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 使用亚马逊 AI 笔记本运行 Ama SageMaker zon Bedrock API 请求示例
<a name="getting-started-api-ex-sm"></a>

本节将指导你使用亚马逊 A SageMaker I 笔记本在 Amazon Bedrock 中尝试一些常见的操作，以测试你的 Amazon Bedrock 角色权限设置是否正确。在运行以下示例之前，应检查您是否满足了以下先决条件：

**先决条件**
+ 您拥有 AWS 账户 并有权访问具有 Amazon Bedrock 必要权限的角色。否则，请按照[快速入门](getting-started.md)中的步骤操作。
+ 执行以下步骤为 A SageMaker I 设置 IAM 权限并创建笔记本：

  1. 修改您在[快速入门](getting-started.md)中通过[控制台](https://docs.aws.amazon.com/IAM/latest/UserGuide/roles-managingrole-editing-console.html#roles-managingrole_edit-trust-policy)、[CLI](https://docs.aws.amazon.com/IAM/latest/UserGuide/roles-managingrole-editing-cli.html#roles-managingrole_edit-trust-policy-cli) 或 [API](https://docs.aws.amazon.com/IAM/latest/UserGuide/roles-managingrole-editing-api.html#roles-managingrole_edit-trust-policy-api) 设置的 Amazon Bedrock 角色的[信任策略](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts.html#term_trust-policy)。将以下信任策略附加到该角色，以允许 Amazon Bedrock 和 A SageMaker I 服务同时担任 Amazon Bedrock 角色：

------
#### [ JSON ]

****  

     ```
     {
         "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"
             }
         ]
     }
     ```

------

  1. 登录您刚刚修改了其信任策略的 Amazon Bedrock 角色。

  1. 按照[本教程的创建 Amazon SageMaker AI 笔记本实例中的步骤进行操作，并指定您为](https://docs.aws.amazon.com/sagemaker/latest/dg/gs-setup-working-env.html)创建 A SageMaker I 笔记本实例而创建的 Amazon Bedrock 角色的 ARN。

  1. 当笔记本实例的**状态**为时 **InService**，选择该实例，然后选择**打开 JupyterLab**。

打开 SageMaker AI 笔记本后，您可以尝试以下示例：

**Topics**
+ [列出 Amazon Bedrock 必须提供的基础模型](#getting-started-api-ex-sm-listfm)
+ [向模型提交文本提示并生成响应](#getting-started-api-ex-sm-converse)

## 列出 Amazon Bedrock 必须提供的基础模型
<a name="getting-started-api-ex-sm-listfm"></a>

以下示例使用 Amazon Bedrock 客户端运行该[ListFoundationModels](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_ListFoundationModels.html)操作。 `ListFoundationModels`列出了您所在地区的 Amazon Bedrock 中可用的基础模型 (FMs)。运行以下适用于 Python 的 SDK 脚本来创建 Amazon Bedrock 客户端并测试[ListFoundationModels](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_ListFoundationModels.html)操作：

```
"""
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 中可用基础模型的列表。

## 向模型提交文本提示并生成响应
<a name="getting-started-api-ex-sm-converse"></a>

以下示例使用 Amazon Bedrock 客户端运行 [Converse](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html) 操作。`Converse` 允许您提交提示以生成模型响应。运行以下适用于 Python 的 SDK 脚本来创建 Amazon Bedrock 运行时客户端并测试 [Converse](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html) 操作：

```
# Use the Conversation API to send a text message to Amazon Nova Micro.

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 Nova Micro.
model_id = "amazon.nova-micro-v1:0"

# 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)
```

如果此命令成功，响应会返回模型为响应提示而生成的文本。