

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

# 透過適用於 Python 的 AWS SDK (Boto3) 執行範例 Amazon Bedrock API 請求
<a name="getting-started-api-ex-python"></a>

本節會引導您使用 嘗試 Amazon Bedrock 中的一些常見操作Python， AWS 以測試您的許可和身分驗證是否已正確設定。在執行下列範例之前，您應該檢查是否符合下列必要條件：

**先決條件**
+ 您有 AWS 帳戶 和已設定身分驗證的使用者或角色，以及 Amazon Bedrock 的必要許可。否則，請依照 [開始使用 API](getting-started-api.md) 中的步驟進行。
+ 您已安裝並設定適用於 Python (Boto3) 的 AWS SDK 的身分驗證。若要安裝 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 文件也包含其他程式設計語言的程式碼範例。如需詳細資訊，請參閱[使用 AWS SDKs Amazon Bedrock 程式碼範例](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 中可用的基礎模型 (FM)。執行下列適用於 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) 操作。建議在支援時對 `InvokeModel` 使用 `Converse` 操作，因為它會統一跨 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)
```

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