を使用した Amazon Bedrock ランタイムの例 AWS SDK for .NET - AWS SDK for .NET

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

を使用した Amazon Bedrock ランタイムの例 AWS SDK for .NET

次のコード例は、Amazon Bedrock ランタイム AWS SDK for .NET で を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

アクションはより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、関連するシナリオやサービス間の例ではアクションのコンテキストが確認できます。

「シナリオ」は、同じサービス内で複数の関数を呼び出して、特定のタスクを実行する方法を示すコード例です。

各例には、 へのリンクが含まれています。ここでは GitHub、コンテキスト内でコードを設定および実行する方法の手順を確認できます。

AI21 ラボ Jurassic-2

次のコード例は、Bedrock の Converse API を使用して、AI21 Labs Jurassic-2 にテキストメッセージを送信する方法を示しています。

AWS SDK for .NET
注記

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

Bedrock の Converse API を使用して、AI21 Labs Jurassic-2 にテキストメッセージを送信します。

// Use the Converse API to send a text message to AI21 Labs Jurassic-2. using System; using System.Collections.Generic; 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., Jurassic-2 Mid. var modelId = "ai21.j2-mid-v1"; // Define the user message. var userMessage = "Describe the purpose of a 'hello world' program in one line."; // Create a request with the model ID, the user message, and an inference configuration. var request = new ConverseRequest { ModelId = modelId, Messages = new List<Message> { new Message { Role = ConversationRole.User, Content = new List<ContentBlock> { new ContentBlock { Text = userMessage } } } }, InferenceConfig = new InferenceConfiguration() { MaxTokens = 512, Temperature = 0.5F, TopP = 0.9F } }; try { // Send the request to the Bedrock Runtime and wait for the result. var response = await client.ConverseAsync(request); // Extract and print the response text. string responseText = response?.Output?.Message?.Content?[0]?.Text ?? ""; Console.WriteLine(responseText); } catch (AmazonBedrockRuntimeException e) { Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}"); throw; }
  • API の詳細については、「 API リファレンス」のAWS SDK for .NET 「会話」を参照してください。

次のコード例は、Invoke Model API を使用して AI21 Labs Jurassic-2 にテキストメッセージを送信する方法を示しています。

AWS SDK for .NET
注記

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

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

// Use the native inference API to send a text message to AI21 Labs Jurassic-2. 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., Jurassic-2 Mid. var modelId = "ai21.j2-mid-v1"; // 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 { prompt = userMessage, maxTokens = 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["completions"]?[0]?["data"]?["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

Amazon Titan Text

次のコード例は、Bedrock の Converse API を使用して Amazon Titan Text にテキストメッセージを送信する方法を示しています。

AWS SDK for .NET
注記

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

Bedrock の Converse API を使用して、Amazon Titan Text にテキストメッセージを送信します。

// Use the Converse API to send a text message to Amazon Titan Text. using System; using System.Collections.Generic; 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., Titan Text Premier. var modelId = "amazon.titan-text-premier-v1:0"; // Define the user message. var userMessage = "Describe the purpose of a 'hello world' program in one line."; // Create a request with the model ID, the user message, and an inference configuration. var request = new ConverseRequest { ModelId = modelId, Messages = new List<Message> { new Message { Role = ConversationRole.User, Content = new List<ContentBlock> { new ContentBlock { Text = userMessage } } } }, InferenceConfig = new InferenceConfiguration() { MaxTokens = 512, Temperature = 0.5F, TopP = 0.9F } }; try { // Send the request to the Bedrock Runtime and wait for the result. var response = await client.ConverseAsync(request); // Extract and print the response text. string responseText = response?.Output?.Message?.Content?[0]?.Text ?? ""; Console.WriteLine(responseText); } catch (AmazonBedrockRuntimeException e) { Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}"); throw; }
  • API の詳細については、「 API リファレンス」のAWS SDK for .NET 「会話」を参照してください。

次のコード例は、Bedrock の Converse API を使用して Amazon Titan Text にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理する方法を示しています。

AWS SDK for .NET
注記

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

Bedrock の Converse API を使用して Amazon Titan Text にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。

// Use the Converse API to send a text message to Amazon Titan Text // and print the response stream. using System; using System.Collections.Generic; using System.Linq; 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., Titan Text Premier. var modelId = "amazon.titan-text-premier-v1:0"; // Define the user message. var userMessage = "Describe the purpose of a 'hello world' program in one line."; // Create a request with the model ID, the user message, and an inference configuration. var request = new ConverseStreamRequest { ModelId = modelId, Messages = new List<Message> { new Message { Role = ConversationRole.User, Content = new List<ContentBlock> { new ContentBlock { Text = userMessage } } } }, InferenceConfig = new InferenceConfiguration() { MaxTokens = 512, Temperature = 0.5F, TopP = 0.9F } }; try { // Send the request to the Bedrock Runtime and wait for the result. var response = await client.ConverseStreamAsync(request); // Extract and print the streamed response text in real-time. foreach (var chunk in response.Stream.AsEnumerable()) { if (chunk is ContentBlockDeltaEvent) { Console.Write((chunk as ContentBlockDeltaEvent).Delta.Text); } } } catch (AmazonBedrockRuntimeException e) { Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}"); throw; }
  • API の詳細については、「 API リファレンスConverseStream」の「」を参照してください。 AWS SDK for .NET

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

AWS SDK for .NET
注記

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

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

// Use the native inference API to send a text message to Amazon Titan Text. 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., Titan Text Premier. var modelId = "amazon.titan-text-premier-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 { inputText = userMessage, textGenerationConfig = new { maxTokenCount = 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["results"]?[0]?["outputText"] ?? ""; Console.WriteLine(responseText); } catch (AmazonBedrockRuntimeException e) { Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}"); throw; }
  • API の詳細については、「 API リファレンスInvokeModel」の「」を参照してください。 AWS SDK for .NET

次のコード例は、Invoke Model API を使用して Amazon Titan Text モデルにテキストメッセージを送信し、レスポンスストリームを出力する方法を示しています。

AWS SDK for .NET
注記

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

モデル呼び出し API を使用してテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。

// Use the native inference API to send a text message to Amazon Titan Text // and print the response stream. 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., Titan Text Premier. var modelId = "amazon.titan-text-premier-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 { inputText = userMessage, textGenerationConfig = new { maxTokenCount = 512, temperature = 0.5 } }); // Create a request with the model ID and the model's native request payload. var request = new InvokeModelWithResponseStreamRequest() { 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 streamingResponse = await client.InvokeModelWithResponseStreamAsync(request); // Extract and print the streamed response text in real-time. foreach (var item in streamingResponse.Body) { var chunk = JsonSerializer.Deserialize<JsonObject>((item as PayloadPart).Bytes); var text = chunk["outputText"] ?? ""; Console.Write(text); } } catch (AmazonBedrockRuntimeException e) { Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}"); throw; }
  • API の詳細については、「 API リファレンスInvokeModelWithResponseStream」の「」を参照してください。 AWS SDK for .NET

Anthropic Claude

次のコード例は、Bedrock の Converse API を使用して Anthropic Claude にテキストメッセージを送信する方法を示しています。

AWS SDK for .NET
注記

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

Bedrock の Converse API を使用して、Anthropic Claude にテキストメッセージを送信します。

// Use the Converse API to send a text message to Anthropic Claude. using System; using System.Collections.Generic; 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., Claude 3 Haiku. var modelId = "anthropic.claude-3-haiku-20240307-v1:0"; // Define the user message. var userMessage = "Describe the purpose of a 'hello world' program in one line."; // Create a request with the model ID, the user message, and an inference configuration. var request = new ConverseRequest { ModelId = modelId, Messages = new List<Message> { new Message { Role = ConversationRole.User, Content = new List<ContentBlock> { new ContentBlock { Text = userMessage } } } }, InferenceConfig = new InferenceConfiguration() { MaxTokens = 512, Temperature = 0.5F, TopP = 0.9F } }; try { // Send the request to the Bedrock Runtime and wait for the result. var response = await client.ConverseAsync(request); // Extract and print the response text. string responseText = response?.Output?.Message?.Content?[0]?.Text ?? ""; Console.WriteLine(responseText); } catch (AmazonBedrockRuntimeException e) { Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}"); throw; }
  • API の詳細については、「 API リファレンス」のAWS SDK for .NET 「会話」を参照してください。

次のコード例は、Bedrock の Converse API を使用して Anthropic Claude にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理する方法を示しています。

AWS SDK for .NET
注記

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

Bedrock の Converse API を使用して Anthropic Claude にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。

// Use the Converse API to send a text message to Anthropic Claude // and print the response stream. using System; using System.Collections.Generic; using System.Linq; 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., Claude 3 Haiku. var modelId = "anthropic.claude-3-haiku-20240307-v1:0"; // Define the user message. var userMessage = "Describe the purpose of a 'hello world' program in one line."; // Create a request with the model ID, the user message, and an inference configuration. var request = new ConverseStreamRequest { ModelId = modelId, Messages = new List<Message> { new Message { Role = ConversationRole.User, Content = new List<ContentBlock> { new ContentBlock { Text = userMessage } } } }, InferenceConfig = new InferenceConfiguration() { MaxTokens = 512, Temperature = 0.5F, TopP = 0.9F } }; try { // Send the request to the Bedrock Runtime and wait for the result. var response = await client.ConverseStreamAsync(request); // Extract and print the streamed response text in real-time. foreach (var chunk in response.Stream.AsEnumerable()) { if (chunk is ContentBlockDeltaEvent) { Console.Write((chunk as ContentBlockDeltaEvent).Delta.Text); } } } catch (AmazonBedrockRuntimeException e) { Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}"); throw; }
  • API の詳細については、「 API リファレンスConverseStream」の「」を参照してください。 AWS SDK for .NET

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

AWS SDK for .NET
注記

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

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

// Use the native inference API to send a text message to Anthropic Claude. 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., Claude 3 Haiku. var modelId = "anthropic.claude-3-haiku-20240307-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 { anthropic_version = "bedrock-2023-05-31", max_tokens = 512, temperature = 0.5, messages = new[] { new { role = "user", content = userMessage } } }); // 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["content"]?[0]?["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

次のコード例は、Invoke Model API を使用して Anthropic Claude モデルにテキストメッセージを送信し、レスポンスストリームを出力する方法を示しています。

AWS SDK for .NET
注記

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

モデル呼び出し API を使用してテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。

// Use the native inference API to send a text message to Anthropic Claude // and print the response stream. 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., Claude 3 Haiku. var modelId = "anthropic.claude-3-haiku-20240307-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 { anthropic_version = "bedrock-2023-05-31", max_tokens = 512, temperature = 0.5, messages = new[] { new { role = "user", content = userMessage } } }); // Create a request with the model ID, the user message, and an inference configuration. var request = new InvokeModelWithResponseStreamRequest() { 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 streamingResponse = await client.InvokeModelWithResponseStreamAsync(request); // Extract and print the streamed response text in real-time. foreach (var item in streamingResponse.Body) { var chunk = JsonSerializer.Deserialize<JsonObject>((item as PayloadPart).Bytes); var text = chunk["delta"]?["text"] ?? ""; Console.Write(text); } } catch (AmazonBedrockRuntimeException e) { Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}"); throw; }
  • API の詳細については、「 API リファレンスInvokeModelWithResponseStream」の「」を参照してください。 AWS SDK for .NET

Cohere Command

次のコード例は、Bedrock の Converse API を使用して Cohere コマンドにテキストメッセージを送信する方法を示しています。

AWS SDK for .NET
注記

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

Bedrock の Converse API を使用して、Cohere コマンドにテキストメッセージを送信します。

// Use the Converse API to send a text message to Cohere Command. using System; using System.Collections.Generic; 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."; // Create a request with the model ID, the user message, and an inference configuration. var request = new ConverseRequest { ModelId = modelId, Messages = new List<Message> { new Message { Role = ConversationRole.User, Content = new List<ContentBlock> { new ContentBlock { Text = userMessage } } } }, InferenceConfig = new InferenceConfiguration() { MaxTokens = 512, Temperature = 0.5F, TopP = 0.9F } }; try { // Send the request to the Bedrock Runtime and wait for the result. var response = await client.ConverseAsync(request); // Extract and print the response text. string responseText = response?.Output?.Message?.Content?[0]?.Text ?? ""; Console.WriteLine(responseText); } catch (AmazonBedrockRuntimeException e) { Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}"); throw; }
  • API の詳細については、「 API リファレンス」のAWS SDK for .NET 「会話」を参照してください。

次のコード例は、Bedrock の Converse API を使用して Cohere Command にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理する方法を示しています。

AWS SDK for .NET
注記

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

Bedrock の Converse API を使用して Cohere Command にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。

// Use the Converse API to send a text message to Cohere Command // and print the response stream. using System; using System.Collections.Generic; using System.Linq; 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."; // Create a request with the model ID, the user message, and an inference configuration. var request = new ConverseStreamRequest { ModelId = modelId, Messages = new List<Message> { new Message { Role = ConversationRole.User, Content = new List<ContentBlock> { new ContentBlock { Text = userMessage } } } }, InferenceConfig = new InferenceConfiguration() { MaxTokens = 512, Temperature = 0.5F, TopP = 0.9F } }; try { // Send the request to the Bedrock Runtime and wait for the result. var response = await client.ConverseStreamAsync(request); // Extract and print the streamed response text in real-time. foreach (var chunk in response.Stream.AsEnumerable()) { if (chunk is ContentBlockDeltaEvent) { Console.Write((chunk as ContentBlockDeltaEvent).Delta.Text); } } } catch (AmazonBedrockRuntimeException e) { Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}"); throw; }
  • API の詳細については、「 API リファレンスConverseStream」の「」を参照してください。 AWS SDK for .NET

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

AWS SDK for .NET
注記

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

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

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

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

AWS SDK for .NET
注記

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

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

// Use the native inference API to send a text message to Cohere Command. 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 Light. var modelId = "cohere.command-light-text-v14"; // 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 { prompt = 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["generations"]?[0]?["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

次のコード例は、レスポンスストリームでモデル呼び出し API を使用して、Cohere コマンドにテキストメッセージを送信する方法を示しています。

AWS SDK for .NET
注記

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

モデル呼び出し API を使用してテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。

// Use the native inference API to send a text message to Cohere Command R // and print the response stream. 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 InvokeModelWithResponseStreamRequest() { 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 streamingResponse = await client.InvokeModelWithResponseStreamAsync(request); // Extract and print the streamed response text in real-time. foreach (var item in streamingResponse.Body) { var chunk = JsonSerializer.Deserialize<JsonObject>((item as PayloadPart).Bytes); var text = chunk["text"] ?? ""; Console.Write(text); } } catch (AmazonBedrockRuntimeException e) { Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}"); throw; }
  • API の詳細については、「 API リファレンスInvokeModel」の「」を参照してください。 AWS SDK for .NET

次のコード例は、レスポンスストリームでモデル呼び出し API を使用して、Cohere コマンドにテキストメッセージを送信する方法を示しています。

AWS SDK for .NET
注記

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

モデル呼び出し API を使用してテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。

// Use the native inference API to send a text message to Cohere Command // and print the response stream. 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 Light. var modelId = "cohere.command-light-text-v14"; // 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 { prompt = userMessage, max_tokens = 512, temperature = 0.5 }); // Create a request with the model ID and the model's native request payload. var request = new InvokeModelWithResponseStreamRequest() { 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 streamingResponse = await client.InvokeModelWithResponseStreamAsync(request); // Extract and print the streamed response text in real-time. foreach (var item in streamingResponse.Body) { var chunk = JsonSerializer.Deserialize<JsonObject>((item as PayloadPart).Bytes); var text = chunk["generations"]?[0]?["text"] ?? ""; Console.Write(text); } } catch (AmazonBedrockRuntimeException e) { Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}"); throw; }
  • API の詳細については、「 API リファレンスInvokeModel」の「」を参照してください。 AWS SDK for .NET

メタラマ

次のコード例は、Bedrock の Converse API を使用して Meta Llama にテキストメッセージを送信する方法を示しています。

AWS SDK for .NET
注記

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

Bedrock の Converse API を使用して、Meta Llama にテキストメッセージを送信します。

// Use the Converse API to send a text message to Meta Llama. using System; using System.Collections.Generic; 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., Llama 3 8b Instruct. var modelId = "meta.llama3-8b-instruct-v1:0"; // Define the user message. var userMessage = "Describe the purpose of a 'hello world' program in one line."; // Create a request with the model ID, the user message, and an inference configuration. var request = new ConverseRequest { ModelId = modelId, Messages = new List<Message> { new Message { Role = ConversationRole.User, Content = new List<ContentBlock> { new ContentBlock { Text = userMessage } } } }, InferenceConfig = new InferenceConfiguration() { MaxTokens = 512, Temperature = 0.5F, TopP = 0.9F } }; try { // Send the request to the Bedrock Runtime and wait for the result. var response = await client.ConverseAsync(request); // Extract and print the response text. string responseText = response?.Output?.Message?.Content?[0]?.Text ?? ""; Console.WriteLine(responseText); } catch (AmazonBedrockRuntimeException e) { Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}"); throw; }
  • API の詳細については、「 API リファレンス」のAWS SDK for .NET 「会話」を参照してください。

次のコード例は、Bedrock の Converse API を使用してテキストメッセージを Meta Llama に送信し、レスポンスストリームをリアルタイムで処理する方法を示しています。

AWS SDK for .NET
注記

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

Bedrock の Converse API を使用して Meta Llama にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。

// Use the Converse API to send a text message to Meta Llama // and print the response stream. using System; using System.Collections.Generic; using System.Linq; 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., Llama 3 8b Instruct. var modelId = "meta.llama3-8b-instruct-v1:0"; // Define the user message. var userMessage = "Describe the purpose of a 'hello world' program in one line."; // Create a request with the model ID, the user message, and an inference configuration. var request = new ConverseStreamRequest { ModelId = modelId, Messages = new List<Message> { new Message { Role = ConversationRole.User, Content = new List<ContentBlock> { new ContentBlock { Text = userMessage } } } }, InferenceConfig = new InferenceConfiguration() { MaxTokens = 512, Temperature = 0.5F, TopP = 0.9F } }; try { // Send the request to the Bedrock Runtime and wait for the result. var response = await client.ConverseStreamAsync(request); // Extract and print the streamed response text in real-time. foreach (var chunk in response.Stream.AsEnumerable()) { if (chunk is ContentBlockDeltaEvent) { Console.Write((chunk as ContentBlockDeltaEvent).Delta.Text); } } } catch (AmazonBedrockRuntimeException e) { Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}"); throw; }
  • API の詳細については、「 API リファレンスConverseStream」の「」を参照してください。 AWS SDK for .NET

次のコード例は、モデル呼び出し API を使用して Meta Llama 2 にテキストメッセージを送信する方法を示しています。

AWS SDK for .NET
注記

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

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

// Use the native inference API to send a text message to Meta Llama 2. 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., Llama 2 Chat 13B. var modelId = "meta.llama2-13b-chat-v1"; // Define the prompt for the model. var prompt = "Describe the purpose of a 'hello world' program in one line."; // Embed the prompt in Llama 2's instruction format. var formattedPrompt = $"<s>[INST] {prompt} [/INST]"; //Format the request payload using the model's native structure. var nativeRequest = JsonSerializer.Serialize(new { prompt = formattedPrompt, max_gen_len = 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["generation"] ?? ""; Console.WriteLine(responseText); } catch (AmazonBedrockRuntimeException e) { Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}"); throw; }
  • API の詳細については、「 API リファレンスInvokeModel」の「」を参照してください。 AWS SDK for .NET

次のコード例は、モデル呼び出し API を使用して Meta Llama 3 にテキストメッセージを送信する方法を示しています。

AWS SDK for .NET
注記

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

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

// Use the native inference API to send a text message to Meta Llama 3. 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., Llama 3 8b Instruct. var modelId = "meta.llama3-8b-instruct-v1:0"; // Define the prompt for the model. var prompt = "Describe the purpose of a 'hello world' program in one line."; // Embed the prompt in Llama 2's instruction format. var formattedPrompt = $@" <|begin_of_text|> <|start_header_id|>user<|end_header_id|> {prompt} <|eot_id|> <|start_header_id|>assistant<|end_header_id|> "; //Format the request payload using the model's native structure. var nativeRequest = JsonSerializer.Serialize(new { prompt = formattedPrompt, max_gen_len = 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["generation"] ?? ""; Console.WriteLine(responseText); } catch (AmazonBedrockRuntimeException e) { Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}"); throw; }
  • API の詳細については、「 API リファレンスInvokeModel」の「」を参照してください。 AWS SDK for .NET

次のコード例は、モデル呼び出し API を使用して Meta Llama 2 にテキストメッセージを送信し、レスポンスストリームを出力する方法を示しています。

AWS SDK for .NET
注記

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

モデル呼び出し API を使用してテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。

// Use the native inference API to send a text message to Meta Llama 2 // and print the response stream. 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., Llama 2 Chat 13B. var modelId = "meta.llama2-13b-chat-v1"; // Define the prompt for the model. var prompt = "Describe the purpose of a 'hello world' program in one line."; // Embed the prompt in Llama 2's instruction format. var formattedPrompt = $"<s>[INST] {prompt} [/INST]"; //Format the request payload using the model's native structure. var nativeRequest = JsonSerializer.Serialize(new { prompt = formattedPrompt, max_gen_len = 512, temperature = 0.5 }); // Create a request with the model ID and the model's native request payload. var request = new InvokeModelWithResponseStreamRequest() { 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 streamingResponse = await client.InvokeModelWithResponseStreamAsync(request); // Extract and print the streamed response text in real-time. foreach (var item in streamingResponse.Body) { var chunk = JsonSerializer.Deserialize<JsonObject>((item as PayloadPart).Bytes); var text = chunk["generation"] ?? ""; Console.Write(text); } } catch (AmazonBedrockRuntimeException e) { Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}"); throw; }
  • API の詳細については、「 API リファレンスInvokeModelWithResponseStream」の「」を参照してください。 AWS SDK for .NET

次のコード例は、モデル呼び出し API を使用して Meta Llama 3 にテキストメッセージを送信し、レスポンスストリームを出力する方法を示しています。

AWS SDK for .NET
注記

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

モデル呼び出し API を使用してテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。

// Use the native inference API to send a text message to Meta Llama 3 // and print the response stream. 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., Llama 3 8b Instruct. var modelId = "meta.llama3-8b-instruct-v1:0"; // Define the prompt for the model. var prompt = "Describe the purpose of a 'hello world' program in one line."; // Embed the prompt in Llama 2's instruction format. var formattedPrompt = $@" <|begin_of_text|> <|start_header_id|>user<|end_header_id|> {prompt} <|eot_id|> <|start_header_id|>assistant<|end_header_id|> "; //Format the request payload using the model's native structure. var nativeRequest = JsonSerializer.Serialize(new { prompt = formattedPrompt, max_gen_len = 512, temperature = 0.5 }); // Create a request with the model ID and the model's native request payload. var request = new InvokeModelWithResponseStreamRequest() { 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 streamingResponse = await client.InvokeModelWithResponseStreamAsync(request); // Extract and print the streamed response text in real-time. foreach (var item in streamingResponse.Body) { var chunk = JsonSerializer.Deserialize<JsonObject>((item as PayloadPart).Bytes); var text = chunk["generation"] ?? ""; Console.Write(text); } } catch (AmazonBedrockRuntimeException e) { Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}"); throw; }
  • API の詳細については、「 API リファレンスInvokeModelWithResponseStream」の「」を参照してください。 AWS SDK for .NET

ミスタル AI

次のコード例は、Bedrock の Converse API を使用して Mistral にテキストメッセージを送信する方法を示しています。

AWS SDK for .NET
注記

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

Bedrock の Converse API を使用して、Mistral にテキストメッセージを送信します。

// Use the Converse API to send a text message to Mistral. using System; using System.Collections.Generic; 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., Mistral Large. var modelId = "mistral.mistral-large-2402-v1:0"; // Define the user message. var userMessage = "Describe the purpose of a 'hello world' program in one line."; // Create a request with the model ID, the user message, and an inference configuration. var request = new ConverseRequest { ModelId = modelId, Messages = new List<Message> { new Message { Role = ConversationRole.User, Content = new List<ContentBlock> { new ContentBlock { Text = userMessage } } } }, InferenceConfig = new InferenceConfiguration() { MaxTokens = 512, Temperature = 0.5F, TopP = 0.9F } }; try { // Send the request to the Bedrock Runtime and wait for the result. var response = await client.ConverseAsync(request); // Extract and print the response text. string responseText = response?.Output?.Message?.Content?[0]?.Text ?? ""; Console.WriteLine(responseText); } catch (AmazonBedrockRuntimeException e) { Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}"); throw; }
  • API の詳細については、「 API リファレンス」のAWS SDK for .NET 「会話」を参照してください。

次のコード例は、Bedrock の Converse API を使用して Mistral にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理する方法を示しています。

AWS SDK for .NET
注記

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

Bedrock の Converse API を使用して Mistral にテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。

// Use the Converse API to send a text message to Mistral // and print the response stream. using System; using System.Collections.Generic; using System.Linq; 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., Mistral Large. var modelId = "mistral.mistral-large-2402-v1:0"; // Define the user message. var userMessage = "Describe the purpose of a 'hello world' program in one line."; // Create a request with the model ID, the user message, and an inference configuration. var request = new ConverseStreamRequest { ModelId = modelId, Messages = new List<Message> { new Message { Role = ConversationRole.User, Content = new List<ContentBlock> { new ContentBlock { Text = userMessage } } } }, InferenceConfig = new InferenceConfiguration() { MaxTokens = 512, Temperature = 0.5F, TopP = 0.9F } }; try { // Send the request to the Bedrock Runtime and wait for the result. var response = await client.ConverseStreamAsync(request); // Extract and print the streamed response text in real-time. foreach (var chunk in response.Stream.AsEnumerable()) { if (chunk is ContentBlockDeltaEvent) { Console.Write((chunk as ContentBlockDeltaEvent).Delta.Text); } } } catch (AmazonBedrockRuntimeException e) { Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}"); throw; }
  • API の詳細については、「 API リファレンスConverseStream」の「」を参照してください。 AWS SDK for .NET

次のコード例は、Invoke Model API を使用して Mistral モデルにテキストメッセージを送信する方法を示しています。

AWS SDK for .NET
注記

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

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

// Use the native inference API to send a text message to Mistral. 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., Mistral Large. var modelId = "mistral.mistral-large-2402-v1:0"; // Define the prompt for the model. var prompt = "Describe the purpose of a 'hello world' program in one line."; // Embed the prompt in Mistral's instruction format. var formattedPrompt = $"<s>[INST] {prompt} [/INST]"; //Format the request payload using the model's native structure. var nativeRequest = JsonSerializer.Serialize(new { prompt = formattedPrompt, 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["outputs"]?[0]?["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

次のコード例は、Invoke Model API を使用して Mistral AI モデルにテキストメッセージを送信し、レスポンスストリームを出力する方法を示しています。

AWS SDK for .NET
注記

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

モデル呼び出し API を使用してテキストメッセージを送信し、レスポンスストリームをリアルタイムで処理します。

// Use the native inference API to send a text message to Mistral // and print the response stream. 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., Mistral Large. var modelId = "mistral.mistral-large-2402-v1:0"; // Define the prompt for the model. var prompt = "Describe the purpose of a 'hello world' program in one line."; // Embed the prompt in Mistral's instruction format. var formattedPrompt = $"<s>[INST] {prompt} [/INST]"; //Format the request payload using the model's native structure. var nativeRequest = JsonSerializer.Serialize(new { prompt = formattedPrompt, max_tokens = 512, temperature = 0.5 }); // Create a request with the model ID and the model's native request payload. var request = new InvokeModelWithResponseStreamRequest() { 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 streamingResponse = await client.InvokeModelWithResponseStreamAsync(request); // Extract and print the streamed response text in real-time. foreach (var item in streamingResponse.Body) { var chunk = JsonSerializer.Deserialize<JsonObject>((item as PayloadPart).Bytes); var text = chunk["outputs"]?[0]?["text"] ?? ""; Console.Write(text); } } catch (AmazonBedrockRuntimeException e) { Console.WriteLine($"ERROR: Can't invoke '{modelId}'. Reason: {e.Message}"); throw; }
  • API の詳細については、「 API リファレンスInvokeModelWithResponseStream」の「」を参照してください。 AWS SDK for .NET

シナリオ

次のコード例は、さまざまな方法で Amazon Bedrock 基盤モデルと相互作用するプレイグラウンドを作成する方法を示しています。

AWS SDK for .NET

.NET 基盤モデル (FM) プレイグラウンドは、C# コードから Amazon Bedrock を使用する方法を紹介する.NET MAUI Blazor サンプルアプリケーションです。この例は、.NET 開発者と C# 開発者が Amazon Bedrock を使用してジェネレーティブな AI 対応アプリケーションを構築する方法を示しています。次の 4 つのプレイグラウンドを使用して Amazon Bedrock 基盤モデルをテストしたり操作したりできます。

  • テキストプレイグラウンド。

  • チャットプレイグラウンド。

  • ボイスチャットプレイグラウンド。

  • イメージプレイグラウンド。

この例には、アクセスできる基盤モデルとその特性も一覧表示されています。ソースコードとデプロイ手順については、「」の「 プロジェクト」を参照してくださいGitHub

この例で使用されているサービス
  • Amazon Bedrock ランタイム