

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

# 通过适用于 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)
```

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