モデル呼び出し API を使用して Amazon Bedrock で Cohere コマンド R と R+ を呼び出す - AWS SDK コードの例

Doc AWS SDK Examples リポジトリには、他にも SDK の例があります。 AWS GitHub

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

モデル呼び出し API を使用して Amazon Bedrock で Cohere コマンド R と R+ を呼び出す

次のコード例は、Invoke Model API を使用して Cohere Command R と R+ にテキストメッセージを送信する方法を示しています。

.NET
AWS SDK for .NET
注記

については、「」を参照してください GitHub。AWS コード例リポジトリ で全く同じ例を見つけて、設定と実行の方法を確認してください。

モデル呼び出し API を使用してテキストメッセージを送信します。

// Use the native inference API to send a text message to Cohere Command R. using Amazon; using Amazon.BedrockRuntime; using Amazon.BedrockRuntime.Model; using System; using System.IO; using System.Text.Json; using System.Text.Json.Nodes; // 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; }
  • API の詳細については、「 API リファレンスInvokeModel」の「」を参照してください。 AWS SDK for .NET

Java
SDK for Java 2.x
注記

については、「」を参照してください GitHub。AWS コード例リポジトリ で全く同じ例を見つけて、設定と実行の方法を確認してください。

モデル呼び出し API を使用してテキストメッセージを送信します。

// 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(); } }
  • API の詳細については、「 API リファレンスInvokeModel」の「」を参照してください。 AWS SDK for Java 2.x

Python
SDK for Python (Boto3)
注記

については、「」を参照してください GitHub。AWS コード例リポジトリ で全く同じ例を見つけて、設定と実行の方法を確認してください。

モデル呼び出し API を使用してテキストメッセージを送信します。

# 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)
  • API の詳細については、InvokeModelAWS 「 SDK for Python (Boto3) API リファレンス」の「」を参照してください。