使用調用模型 API,在 Amazon Bedrock 上調用 Amazon Titan Text 模型
下列程式碼範例示範如何使用調用模型 API,將文字訊息傳送至 Amazon Titan Text。
- Python
-
- 適用於 Python (Boto3) 的 SDK
-
注意
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 的詳細資訊。
Amazon Titan Text
Amazon Titan 文本嵌入