使用调用模型 API 在 Amazon Bedrock 上调用 Amazon Titan Text 模型 - Amazon Bedrock

使用调用模型 API 在 Amazon Bedrock 上调用 Amazon Titan Text 模型

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

Python
适用于 Python 的 SDK (Boto3)
注意

查看 GitHub,了解更多信息。在 AWS 代码示例存储库中查找完整示例,了解如何进行设置和运行。

使用调用模型 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 详细信息,请参阅《AWS SDK for Python (Boto3) API 参考》中的 InvokeModel

有关 AWS SDK 开发人员指南和代码示例的完整列表,请参阅 将 Amazon Bedrock 与 AWS SDK 结合使用。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。