

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

# 开始使用 API
<a name="getting-started-api"></a>

本节介绍如何设置您的环境以通过 AWS API 发出 Amazon Bedrock 请求。 AWS 提供以下工具来简化您的体验：
+ AWS Command Line Interface (AWS CLI)
+ AWS SDKs
+ 亚马逊 SageMaker AI 笔记本电脑

要开始使用 API，您需要获取凭证来授予编程访问权限。如果以下部分与您有关，请展开并按照说明操作。否则，请继续完成剩余部分。

## 我是新手 AWS
<a name="gs-api-new-to-aws"></a>

如果您没有 AWS 账户，请完成以下步骤来创建一个。

**报名参加 AWS 账户**

1. 打开[https://portal.aws.amazon.com/billing/注册。](https://portal.aws.amazon.com/billing/signup)

1. 按照屏幕上的说明操作。

   在注册时，将接到电话或收到短信，要求使用电话键盘输入一个验证码。

   当您注册时 AWS 账户，就会创建*AWS 账户根用户*一个。根用户有权访问该账户中的所有 AWS 服务 和资源。作为最佳安全实践，请为用户分配管理访问权限，并且只使用根用户来执行[需要根用户访问权限的任务](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html#root-user-tasks)。

AWS 注册过程完成后会向您发送一封确认电子邮件。您可以随时前往 [https://aws.amazon.com/](https://aws.amazon.com/)并选择 “**我的账户”，查看您当前的账户活动并管理您的账户**。

**保护你的 AWS 账户根用户**

1.  选择 **Root 用户**并输入您的 AWS 账户 电子邮件地址，以账户所有者的身份登录。[AWS 管理控制台](https://console.aws.amazon.com/)在下一页上，输入您的密码。

   要获取使用根用户登录方面的帮助，请参阅《AWS 登录 用户指南》**中的 [Signing in as the root user](https://docs.aws.amazon.com/signin/latest/userguide/console-sign-in-tutorials.html#introduction-to-root-user-sign-in-tutorial)。

1. 为您的根用户启用多重身份验证（MFA）。

   有关说明，请参阅 I [A *M* 用户指南中的为 AWS 账户 根用户启用虚拟 MFA 设备（控制台）](https://docs.aws.amazon.com/IAM/latest/UserGuide/enable-virt-mfa-for-root.html)。

## 我需要安装 AWS CLI 或 S AWS DK
<a name="gs-api-cli-sdk-install"></a>

要安装 AWS CLI，请按照[安装或更新到最新版本中的步骤进行](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)操作 AWS CLI。

要安装 S AWS DK，请在 “[构建工具” 中选择与您要使用的编程语言相对应的](https://aws.amazon.com/developer/tools/)选项卡 AWS。 AWS 软件开发套件 (SDKs) 可用于许多流行的编程语言。每个 SDK 都提供一个 API、代码示例和文档，便于开发人员使用自己的首选语言构建应用程序。 SDKs 自动为您执行有用的任务，例如：
+ 对服务请求进行加密签名
+ 重试请求
+ 处理错误响应

## 获取凭证来授予编程访问权限
<a name="gs-grant-program-access"></a>

如果用户想在 AWS 外部进行交互，则需要编程访问权限 AWS 管理控制台。 AWS 根据您的安全考虑，提供了多种选项。

**注意**  
有关生成可用于快速访问 Amazon Bedrock API 的 API 密钥的 step-by-step指南，请参阅[开始使用 Amazon Bedrock API 密钥：生成 30 天密钥并发出第一个 API 调用](getting-started-api-keys.md)。  
如有更高的安全性要求，请继续阅读本部分。

授予编程访问权限的方式取决于正在访问的用户类型 AWS。

要向用户授予编程式访问权限，请选择以下选项之一。


****  

| 哪个主体需要编程访问权限？ | 目标 | 方式 | 
| --- | --- | --- | 
| IAM 用户 | 限制签署 AWS CLI、 AWS SDKs或编程请求的长期证书的持续时间 AWS APIs。 |  按照您希望使用的界面的说明进行操作。 [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/bedrock/latest/userguide/getting-started-api.html)  | 
| IAM 角色 | 使用临时证书签署向 AWS CLI AWS SDKs、或发出的编程请求 AWS APIs。 | 按照 IAM 用户指南中的将[临时证书与 AWS 资源配合使用](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html)中的说明进行操作。 | 
|  人力身份 （在 IAM Identity Center 中管理的用户）  | 使用临时证书签署向 AWS CLI AWS SDKs、或发出的编程请求 AWS APIs。 |  按照您希望使用的界面的说明进行操作。 [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/bedrock/latest/userguide/getting-started-api.html)  | 

## 如何为 IAM 用户创建访问密钥
<a name="create-user-time-bound"></a>

如果您决定对 IAM 用户使用访问密钥， AWS 建议您通过包含限制性内联策略来为 IAM 用户设置过期时间。

**重要**  
请注意以下警告：  
**请勿**使用您账户的根凭证访问 AWS 资源。这些凭证可提供不受限的账户访问且难以撤销。
**不得**在应用程序文件中按字面输入访问密钥或凭证信息。如果您这样做，则在将项目上传到公共存储库或在其他情况下，会有意外暴露凭证的风险。
**不得**在项目区域中放入包含凭证的文件。
安全管理您的访问密钥。请不要向未经授权方提供访问密钥，即便是为了帮助[找到您的账户标识符](https://docs.aws.amazon.com/general/latest/gr/acct-identifiers.html)也不行。通过这样做，您可以授予他人永久访问您的帐户的权限。
请注意，存储在共享凭证文件中的所有 AWS 凭据都以纯文本形式存储。

有关更多详细信息，请参阅中的[管理 AWS 访问密钥的最佳实践](https://docs.aws.amazon.com/general/latest/gr/aws-access-keys-best-practices.html) AWS 一般参考。

**创建 IAM 用户**

1. 在 AWS 管理控制台 主页上，选择 IAM 服务或导航到 IAM 控制台，网址为[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/)。

1. 在导航窗格中，选择**用户**，然后选择**创建用户**。

1. 按照 IAM 控制台中的指导设置无权限的编程用户（无权访问 AWS 管理控制台）。

**将用户访问权限限制在有限的时间段内**

您创建的任何 IAM 用户访问密钥都属于长期凭证。为了确保这些凭证在处理不当的情况下会过期，您可以创建内联策略来指定密钥失效的日期，从而限制这些凭证的使用时间。

1. 打开刚创建的 IAM 用户。在**权限**选项卡中，选择**添加权限**，然后选择**创建内联策略**。

1. 在 JSON 编辑器中，指定以下权限。要使用此策略，请将示例策略中的 `aws:CurrentTime` 时间戳值替换为自己的结束日期。
**注意**  
IAM 建议将访问密钥限制在 12 小时以内。

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

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement": [
       {
         "Effect": "Deny",
         "Action": "*",
         "Resource": "*",
         "Condition": {
           "DateGreaterThan": {
             "aws:CurrentTime": "2024-01-01T00:00:000"
           }
         }
       }
     ]
   }
   ```

------

**创建访问密钥**

1. 在**用户详细信息**页面上，选择**安全凭证**选项卡。在**访问密钥**部分，选择**创建访问密钥**。

1. 表明您计划将这些访问密钥用作**其他**，然后选择**创建访问密钥**。

1. 在 **Retrieve access keys**（检索访问密钥）页面上，选择 **Show**（显示）来显示用户的秘密访问密钥的值。您可以复制凭证或下载 .csv 文件。

**重要**  
当您不再需要此 IAM 用户时，我们建议您将其移除并遵循[AWS 安全最佳实践](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#lock-away-credentials)，我们建议您要求您的人类用户在访问时通过 [AWS IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/getting-started.html) 使用临时证书 AWS。

## 将 Amazon Bedrock 权限附加到用户或角色
<a name="gs-api-br-permissions"></a>

在设置好编程访问凭证后，您需要为用户或 IAM 角色配置权限，以便其访问一组与 Amazon Bedrock 相关的操作。要设置这些权限，请执行以下操作：

1. 在 AWS 管理控制台 主页上，选择 IAM 服务或导航到 IAM 控制台，网址为[https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/)。

1. 选择**用户**或**角色**，然后选择您的用户或角色。

1. 在 “**权限**” 选项卡中，选择 “**添加权限**”，然后选择 “**添加 AWS 托管策略**”。选择名为 [AmazonBedrockFullAccess]() AWS 的托管式策略。

1. 要允许用户或角色订阅模型，请选择**创建内联策略**，然后在 JSON 编辑器中指定以下权限：

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

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement": [
         {
             "Sid": "MarketplaceBedrock",
             "Effect": "Allow",
             "Action": [
                 "aws-marketplace:ViewSubscriptions",
                 "aws-marketplace:Unsubscribe",
                 "aws-marketplace:Subscribe"
             ],
             "Resource": "*"
         }
     ]
   }
   ```

------

## 尝试对 Amazon Bedrock 进行 API 调用
<a name="gs-try-bedrock"></a>

在完成所有前提条件后，选择以下主题之一来测试使用 Amazon Bedrock 模型发出模型调用请求：

**Topics**
+ [获取凭证来授予编程访问权限](#gs-grant-program-access)
+ [将 Amazon Bedrock 权限附加到用户或角色](#gs-api-br-permissions)
+ [尝试对 Amazon Bedrock 进行 API 调用](#gs-try-bedrock)
+ [开始使用 Amazon Bedrock API 密钥：生成 30 天密钥并发出第一个 API 调用](getting-started-api-keys.md)
+ [使用以下命令运行 Amazon Bedrock API 请求示例 AWS Command Line Interface](getting-started-api-ex-cli.md)
+ [通过适用于 Python 的 AWS 软件开发工具包 (Boto3) 运行示例 Amazon Bedrock API 请求](getting-started-api-ex-python.md)
+ [使用亚马逊 AI 笔记本运行 Ama SageMaker zon Bedrock API 请求示例](getting-started-api-ex-sm.md)

# 开始使用 Amazon Bedrock API 密钥：生成 30 天密钥并发出第一个 API 调用
<a name="getting-started-api-keys"></a>

本教程将引导您创建一个有效期为 30 天的长期 Amazon Bedrock API 密钥，并使用它通过 Python 发出简单的 [Converse](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html) API 调用。这是无需设置复杂 AWS 凭证即可开始试用 Amazon Bedrock 的最快方法。

**警告**  
建议仅在 Amazon Bedrock 的探索和开发阶段使用长期 API 密钥。对于生产应用程序，请使用[长期访问密钥的替代方案](https://docs.aws.amazon.com/IAM/latest/UserGuide/security-creds-programmatic-access.html#security-creds-alternatives-to-long-term-access-keys)，例如 IAM 角色或临时凭证。

按照以下步骤创建长期 Amazon Bedrock API 密钥，该密钥将在 30 天后过期：

1. 使用有权使用 Amazon Bedrock 控制台的 IAM 身份登录。 AWS 管理控制台 然后，在 [https://console.aws.amazon.com/](https://console.aws.amazon.com/bedrock)bedrock 上打开 Amazon Bedrock 控制台。

1. 在左侧导航窗格中，选择 **API 密钥**。

1. 在**长期 API 密钥**选项卡中，选择**生成长期 API 密钥**。

1. 在 **API 密钥到期**部分中，选择 **30 天**。

1. 选择**生成**。您生成的密钥提供执行核心 Amazon Bedrock 操作的权限，如所附[AmazonBedrockLimitedAccess](security-iam-awsmanpol.md#security-iam-awsmanpol-AmazonBedrockLimitedAccess)策略所定义。

1. 复制生成的 API 密钥并妥善存储。在下一个步骤中，您需要用到该密钥。
**重要**  
API 密钥仅显示一次。在关闭对话框之前，请务必复制并保存密钥。请记住，您的 API 密钥将在 30 天后过期。您可以按照相同的步骤生成一个新的密钥，或者考虑在持续使用中改为采用更安全的身份验证方法。

1. 将 API 密钥设置为环境变量，方法是将其*\$1\$1api-key\$1*替换为生成的 API 密钥值，然后使用它以您选择的方法生成响应：

------
#### [ Python ]

   ```
   import boto3
   import os
   
   # Set the API key as an environment variable
   os.environ['AWS_BEARER_TOKEN_BEDROCK'] = "${api-key}"
   
   # Create the Bedrock client
   client = boto3.client(
       service_name="bedrock-runtime",
       region_name="us-east-1"
   )
   
   # Define the model and message
   model_id = "us.anthropic.claude-3-5-haiku-20241022-v1:0"
   messages = [{"role": "user", "content": [{"text": "Hello! Can you tell me about Amazon Bedrock?"}]}]
   
   # Make the API call
   response = client.converse(
       modelId=model_id,
       messages=messages,
   )
   
   # Print the response
   print(response['output']['message']['content'][0]['text'])
   ```

------
#### [ HTTP client using Python ]

   ```
   import requests
   
   url = "https://bedrock-runtime.us-east-1.amazonaws.com/model/us.anthropic.claude-3-5-haiku-20241022-v1:0/converse"
   
   payload = {
       "messages": [
           {
               "role": "user",
               "content": [{"text": "Hello"}]
           }
       ]
   }
   
   headers = {
       "Content-Type": "application/json",
       "Authorization": "Bearer ${api-key}"
   }
   
   response = requests.request("POST", url, json=payload, headers=headers)
   
   print(response.text)
   ```

------
#### [ HTTP request using cURL ]

   ```
   curl -X POST "https://bedrock-runtime.us-east-1.amazonaws.com/model/us.anthropic.claude-3-5-haiku-20241022-v1:0/converse" \
     -H "Content-Type: application/json" \
     -H "Authorization: Bearer ${api-key}" \
     -d '{
       "messages": [
           {
               "role": "user",
               "content": [{"text": "Hello"}]
           }
       ]
     }'
   ```

------

恭喜您！您已成功生成了 Amazon Bedrock API 密钥，并首次对 Amazon Bedrock 服务发出了 API 调用。在探索了更多的 Amazon Bedrock 操作之后，您应该过渡到更安全的身份验证方法，例如短期 Amazon Bedrock API 密钥或 AWS全局临时证书。要了解更多信息，请参阅以下资源：
+ **探索其他模型**：在[Amazon Bedrock 基础模型信息](foundation-models-reference.md)中了解 Amazon Bedrock 提供的其他基础模型，并在您的代码中更改 `model_id` 以进行试用。
+ **了解模型推理**：通过在[使用模型推理提交提示并生成响应](inference.md)中阅读有关概念和 Amazon Bedrock 提供的选项的信息，了解如何通过模型推理生成响应。
+ **使用更安全的身份验证方法进行生产规划** — 在 “构建” 章节中详细了解 Amazon Bedrock API 密钥以及如何创建更安全的短期 Amazon Bedrock API 密钥。准备好构建生产应用程序时，还应查看[长期访问密钥的替代方案，以](https://docs.aws.amazon.com/IAM/latest/UserGuide/security-creds-programmatic-access.html#security-creds-alternatives-to-long-term-access-keys)获得更安全的选项，这些选项还允许访问其他 AWS 服务。

# 使用以下命令运行 Amazon Bedrock API 请求示例 AWS Command Line Interface
<a name="getting-started-api-ex-cli"></a>

本节将指导您使用在 Amazon Bedrock 中尝试一些常见的操作， AWS Command Line Interface 以测试您的权限和身份验证设置是否正确。在运行以下示例之前，应检查您是否满足了以下先决条件：

**先决条件**
+ 您的用户或角色已设置身份验证 AWS 账户 并拥有 Amazon Bedrock 的必要权限。否则，请按照[开始使用 API](getting-started-api.md)中的步骤操作。
+ 您已安装 AWS CLI并设置了身份验证。要安装 AWS CLI，请按照[安装或更新到最新版本中的步骤进行](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)操作 AWS CLI。按照[获取凭证来授予编程访问权限](getting-started-api.md#gs-grant-program-access)中的步骤，验证是否已设置凭证来使用 CLI。

使用您已设置适当权限的用户或角色，测试是否已针对 Amazon Bedrock 设置了正确的权限。

**Topics**
+ [列出 Amazon Bedrock 必须提供的基础模型](#getting-started-api-ex-cli-listfm)
+ [向模型提交文本提示并使用以下命令生成文本回复 InvokeModel](#getting-started-api-ex-cli-invoke-text)
+ [向模型提交文本提示并使用 Converse 生成文本响应](#getting-started-api-ex-cli-converse)

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

以下示例使用[ListFoundationModels](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_ListFoundationModels.html)运行操作 AWS CLI。 `ListFoundationModels`列出了您所在地区的 Amazon Bedrock 中可用的基础模型 (FMs)。在终端，运行以下命令：

```
aws bedrock list-foundation-models
```

如果此命令成功，响应会返回一个包含 Amazon Bedrock 中可用基础模型的列表。

## 向模型提交文本提示并使用以下命令生成文本回复 InvokeModel
<a name="getting-started-api-ex-cli-invoke-text"></a>

以下示例使用[InvokeModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html)运行操作 AWS CLI。 `InvokeModel`允许您提交提示以生成模型响应。在终端，运行以下命令：

```
aws bedrock-runtime invoke-model \
--model-id amazon.titan-text-express-v1 \
--body '{"inputText": "Describe the purpose of a \"hello world\" program in one line.", "textGenerationConfig" : {"maxTokenCount": 512, "temperature": 0.5, "topP": 0.9}}' \
--cli-binary-format raw-in-base64-out \
invoke-model-output-text.txt
```

如果此命令成功，模型生成的响应会写入 `invoke-model-output-text.txt` 文件。`outputText` 字段会返回文本响应和随附信息。

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

以下示例使用运行[匡威](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html)操作。 AWS CLI`Converse`允许您提交提示以生成模型响应。我们建议在支持时用 `Converse` 来代替 `InvokeModel` 操作，因为前者可以统一各个 Amazon Bedrock 模型的推理请求并简化多轮对话的管理。在终端，运行以下命令：

```
aws bedrock-runtime converse \
--model-id amazon.titan-text-express-v1 \
--messages '[{"role": "user", "content": [{"text": "Describe the purpose of a \"hello world\" program in one line."}]}]' \
--inference-config '{"maxTokens": 512, "temperature": 0.5, "topP": 0.9}'
```

如果此命令成功，则 `text` 字段会返回模型生成的响应和随附信息。

# 通过适用于 Python 的 AWS 软件开发工具包 (Boto3) 运行示例 Amazon Bedrock API 请求
<a name="getting-started-api-ex-python"></a>

本节将指导您在 Amazon Bedrock 中尝试一些常见的操作， AWS Python以测试您的权限和身份验证设置是否正确。在运行以下示例之前，应检查您是否满足了以下先决条件：

**先决条件**
+ 您的用户或角色已设置身份验证 AWS 账户 并拥有 Amazon Bedrock 的必要权限。否则，请按照[开始使用 API](getting-started-api.md)中的步骤操作。
+ 你已经为适用于 Python 的 AWS SDK (Boto3) 安装并设置了身份验证。要安装 Boto3，请按照 Boto3 文档中 [Quickstart](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html) 中的步骤操作。按照[获取凭证来授予编程访问权限](getting-started-api.md#gs-grant-program-access)中的步骤，验证是否已设置凭证来使用 Boto3。

使用您已设置适当权限的用户或角色，测试是否已针对 Amazon Bedrock 设置了正确的权限。

Amazon Bedrock 文档还包括其他编程语言的代码示例。有关更多信息，请参阅 [使用 Amazon Bedrock 的代码示例 AWS SDKs](service_code_examples.md)。

**Topics**
+ [列出 Amazon Bedrock 必须提供的基础模型](#getting-started-api-ex-python-listfm)
+ [向模型提交文本提示并使用以下命令生成文本回复 InvokeModel](#getting-started-api-ex-python-invoke-text)
+ [向模型提交文本提示并使用 Converse 生成文本响应](#getting-started-api-ex-python-converse)

## 列出 Amazon Bedrock 必须提供的基础模型
<a name="getting-started-api-ex-python-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 中可用基础模型的列表。

## 向模型提交文本提示并使用以下命令生成文本回复 InvokeModel
<a name="getting-started-api-ex-python-invoke-text"></a>

以下示例使用 Amazon Bedrock 客户端运行该[InvokeModel](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_InvokeModel.html)操作。 `InvokeModel`允许您提交提示以生成模型响应。运行以下适用于 Python 的 SDK 脚本来创建 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 生成文本响应
<a name="getting-started-api-ex-python-converse"></a>

以下示例使用 Amazon Bedrock 客户端运行 [Converse](https://docs.aws.amazon.com/bedrock/latest/APIReference/API_runtime_Converse.html) 操作。我们建议在支持时用 `Converse` 来代替 `InvokeModel` 操作，因为前者可以统一各个 Amazon Bedrock 模型的推理请求并简化多轮对话的管理。运行以下适用于 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)
```

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

# 使用亚马逊 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 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)
```

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