

文档 AWS SDK 示例 GitHub 存储库中还有更多 [S AWS DK 示例](https://github.com/awsdocs/aws-doc-sdk-examples)。

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

# 适用于 Amazon Bedrock 运行时的 Amazon Titan Text
<a name="bedrock-runtime_code_examples_amazon_titan_text"></a>

以下代码示例展示了如何将 Amazon Bedrock 运行时与一起 AWS SDKs使用。

**Topics**
+ [InvokeModel](bedrock-runtime_example_bedrock-runtime_InvokeModel_TitanText_section.md)

# 使用调用模型 API 在 Amazon Bedrock 上调用 Amazon Titan Text 模型
<a name="bedrock-runtime_example_bedrock-runtime_InvokeModel_TitanText_section"></a>

以下代码示例演示如何使用调用模型 API 向 Amazon Titan Text 发送文本消息。

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

**适用于 Python 的 SDK（Boto3）**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/python/example_code/bedrock-runtime#code-examples)中查找完整示例，了解如何进行设置和运行。
使用调用模型 API 发送文本消息。  

```
# Use the native inference API to send a text message to Amazon Titan Text.

import boto3
import json

from botocore.exceptions import ClientError

# Create a Bedrock Runtime client in the AWS Region of your choice.
client = boto3.client("bedrock-runtime", region_name="us-east-1")

# Set the model ID, e.g., Titan Text Premier.
model_id = "amazon.titan-text-premier-v1:0"

# 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,
    },
}

# Convert the native request to JSON.
request = json.dumps(native_request)

try:
    # Invoke the model with the request.
    response = client.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)
```
+  有关 API 的详细信息，请参阅适用[InvokeModel](https://docs.aws.amazon.com/goto/boto3/bedrock-runtime-2023-09-30/InvokeModel)于 *Python 的AWS SDK (Boto3) API 参考*。

------