Invoque os comandos Cohere R e R+ no Amazon Bedrock usando a API Invoke Model - AWS Exemplos de código do SDK

Há mais exemplos de AWS SDK disponíveis no repositório AWS Doc SDK Examples GitHub .

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

Invoque os comandos Cohere R e R+ no Amazon Bedrock usando a API Invoke Model

Os exemplos de código a seguir mostram como enviar uma mensagem de texto para o Cohere Command R e R+, usando a API Invoke Model.

.NET
AWS SDK for .NET
nota

Tem mais sobre GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository.

Use a API Invoke Model para enviar uma mensagem de texto.

// Use the native inference API to send a text message to Cohere Command R. using System; using System.IO; using System.Text.Json; using System.Text.Json.Nodes; using Amazon; using Amazon.BedrockRuntime; using Amazon.BedrockRuntime.Model; // Create a Bedrock Runtime client in the AWS Region you want to use. var client = new AmazonBedrockRuntimeClient(RegionEndpoint.USEast1); // Set the model ID, e.g., Command R. var modelId = "cohere.command-r-v1:0"; // Define the user message. var userMessage = "Describe the purpose of a 'hello world' program in one line."; //Format the request payload using the model's native structure. var nativeRequest = JsonSerializer.Serialize(new { message = userMessage, max_tokens = 512, temperature = 0.5 }); // Create a request with the model ID and the model's native request payload. var request = new InvokeModelRequest() { ModelId = modelId, Body = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(nativeRequest)), ContentType = "application/json" }; try { // Send the request to the Bedrock Runtime and wait for the response. var response = await client.InvokeModelAsync(request); // Decode the response body. var modelResponse = await JsonNode.ParseAsync(response.Body); // Extract and print the response text. var responseText = modelResponse["text"] ?? ""; Console.WriteLine(responseText); } catch (AmazonBedrockRuntimeException e) { Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}"); throw; }
  • Para obter detalhes da API, consulte InvokeModela Referência AWS SDK for .NET da API.

Java
SDK para Java 2.x
nota

Tem mais sobre GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository.

Use a API Invoke Model para enviar uma mensagem de texto.

// Use the native inference API to send a text message to Cohere Command R. import org.json.JSONObject; import org.json.JSONPointer; import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider; import software.amazon.awssdk.core.SdkBytes; import software.amazon.awssdk.core.exception.SdkClientException; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.bedrockruntime.BedrockRuntimeClient; public class Command_R_InvokeModel { public static String invokeModel() { // Create a Bedrock Runtime client in the AWS Region you want to use. // Replace the DefaultCredentialsProvider with your preferred credentials provider. var client = BedrockRuntimeClient.builder() .credentialsProvider(DefaultCredentialsProvider.create()) .region(Region.US_EAST_1) .build(); // Set the model ID, e.g., Command R. var modelId = "cohere.command-r-v1:0"; // The InvokeModel API uses the model's native payload. // Learn more about the available inference parameters and response fields at: // https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-cohere-command-r-plus.html var nativeRequestTemplate = "{ \"message\": \"{{prompt}}\" }"; // Define the prompt for the model. var prompt = "Describe the purpose of a 'hello world' program in one line."; // Embed the prompt in the model's native request payload. String nativeRequest = nativeRequestTemplate.replace("{{prompt}}", prompt); try { // Encode and send the request to the Bedrock Runtime. var response = client.invokeModel(request -> request .body(SdkBytes.fromUtf8String(nativeRequest)) .modelId(modelId) ); // Decode the response body. var responseBody = new JSONObject(response.body().asUtf8String()); // Retrieve the generated text from the model's response. var text = new JSONPointer("/text").queryFrom(responseBody).toString(); System.out.println(text); return text; } catch (SdkClientException e) { System.err.printf("ERROR: Can't invoke '%s'. Reason: %s", modelId, e.getMessage()); throw new RuntimeException(e); } } public static void main(String[] args) { invokeModel(); } }
  • Para obter detalhes da API, consulte InvokeModela Referência AWS SDK for Java 2.x da API.

Python
SDK para Python (Boto3)
nota

Tem mais sobre GitHub. Encontre o exemplo completo e veja como configurar e executar no AWS Code Examples Repository.

Use a API Invoke Model para enviar uma mensagem de texto.

# Use the native inference API to send a text message to Cohere Command R and R+. 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., Command R. model_id = "cohere.command-r-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 = { "message": prompt, "max_tokens": 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["text"] print(response_text)
  • Para obter detalhes da API, consulte a InvokeModelReferência da API AWS SDK for Python (Boto3).