Invocar modelos Amazon Titan Text no Amazon Bedrock usando a API InvokeModel - Amazon Bedrock

Invocar modelos Amazon Titan Text no Amazon Bedrock usando a API InvokeModel

O exemplo de código a seguir mostra como enviar uma mensagem de texto ao Amazon Titan Text usando a API InvokeModel.

Python
SDK para Python (Boto3).
nota

Há mais no GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWSCode Examples Repository.

Use a API InvokeModel para enviar uma mensagem de texto.

# 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)
  • Para obter detalhes da API, consulte InvokeModel na Referência de API do AWS SDK para Python (Boto3).

Para ver uma lista completa dos guias de desenvolvedor e exemplos de código do SDK da AWS, consulte Usar o Amazon Bedrock com um SDK da AWS. Este tópico também inclui informações sobre como começar e detalhes sobre versões anteriores do SDK.