View a markdown version of this page

Exemplos do Amazon Bedrock Runtime usando SDK for .NET (v4) - AWS SDK for .NET (V4)

A versão 4 (V4) do AWS SDK for .NET foi lançada!

Para obter informações sobre mudanças significativas e migrar seus aplicativos, consulte o tópico de migração.

Orange button with text "Click here for details".

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á.

Exemplos do Amazon Bedrock Runtime usando SDK for .NET (v4)

Os exemplos de código a seguir mostram como realizar ações e implementar cenários comuns usando o AWS SDK for .NET (v4) com o Amazon Bedrock Runtime.

Cada exemplo inclui um link para o código-fonte completo, em que você pode encontrar instruções sobre como configurar e executar o código.

Conceitos básicos

O exemplo de código a seguir mostra como começar a usar o Amazon Bedrock Runtime.

SDK for .NET (v4)
nota

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

using Amazon; using Amazon.BedrockRuntime; using Amazon.BedrockRuntime.Model; namespace BedrockRuntimeActions; /// <summary> /// This example shows how to use the Converse API to send a text message /// to Amazon Bedrock. /// </summary> internal class HelloBedrockRuntime { static async Task Main(string[] args) { // Create a Bedrock Runtime client in the AWS Region you want to use. // You can change the region to match your setup. var client = new AmazonBedrockRuntimeClient(RegionEndpoint.USWest2); // Set the model ID, e.g., Claude Haiku. // The "global." prefix enables cross-region inference, allowing the request // to be routed to the nearest available region for the specified model. var modelId = "global.anthropic.claude-haiku-4-5-20251001-v1:0"; // Define the user message. var userMessage = "Hi. In a short paragraph, explain what you can do."; // 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 } } } } }; try { // Send the request to the Bedrock Runtime and wait for the response. 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; } } }
  • Consulte detalhes da API em Converse na Referência de API do AWS SDK for .NET .

Claude da Anthropic

O exemplo de código a seguir mostra como enviar uma mensagem de texto ao Claude da Anthropic usando a API Converse do Bedrock.

SDK for .NET (v4)
nota

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

Envie uma mensagem de texto ao Claude da Anthropic usando a API Converse do Bedrock.

// 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; }
  • Consulte detalhes da API em Converse na Referência de API do AWS SDK for .NET .

O exemplo de código a seguir mostra como enviar uma mensagem de texto ao Claude da Anthropic usando a API Converse do Bedrock e processar o fluxo de resposta em tempo real.

SDK for .NET (v4)
nota

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

Envie uma mensagem de texto ao Claude da Anthropic usando a API Converse do Bedrock e processe o fluxo de resposta em tempo real.

// 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; }
  • Para obter detalhes da API, consulte ConverseStreama Referência AWS SDK for .NET da API.

Command da Cohere

O exemplo de código a seguir mostra como enviar uma mensagem de texto ao Command da Cohere usando a API Converse do Bedrock.

SDK for .NET (v4)
nota

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

Envie uma mensagem de texto ao Cohere Command usando a API Converse do Bedrock.

// 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; }
  • Consulte detalhes da API em Converse na Referência de API do AWS SDK for .NET .

O exemplo de código a seguir mostra como enviar uma mensagem de texto ao Command da Cohere usando a API Converse do Bedrock e processar o fluxo de resposta em tempo real.

SDK for .NET (v4)
nota

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

Envie uma mensagem de texto ao Command da Cohere usando a API Converse do Bedrock e processe o fluxo de resposta em tempo real.

// 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; }
  • Para obter detalhes da API, consulte ConverseStreama Referência AWS SDK for .NET da API.

Llama da Meta

O exemplo de código a seguir mostra como enviar uma mensagem de texto ao Llama da Meta usando a API Converse do Bedrock.

SDK for .NET (v4)
nota

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

Envie uma mensagem de texto ao Llama da Meta usando a API Converse do Bedrock.

// 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; }
  • Consulte detalhes da API em Converse na Referência de API do AWS SDK for .NET .

O exemplo de código a seguir mostra como enviar uma mensagem de texto ao Llama da Meta usando a API Converse do Bedrock e processar o fluxo de resposta em tempo real.

SDK for .NET (v4)
nota

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

Envie uma mensagem de texto ao Llama da Meta usando a API Converse do Bedrock e processe o fluxo de resposta em tempo real.

// 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; }
  • Para obter detalhes da API, consulte ConverseStreama Referência AWS SDK for .NET da API.

Mistral AI

O exemplo de código a seguir mostra como enviar uma mensagem de texto à Mistral usando a API Converse do Bedrock.

SDK for .NET (v4)
nota

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

Envie uma mensagem de texto à Mistral usando a API Converse do Bedrock.

// 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; }
  • Para obter detalhes da API, consulte Converse na Referência da API do AWS SDK for .NET .

O exemplo de código a seguir mostra como enviar uma mensagem de texto à Mistral usando a API Converse do Bedrock e processar o fluxo de resposta em tempo real.

SDK for .NET (v4)
nota

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

Envie uma mensagem de texto para a Mistral usando a API Converse do Bedrock e processe o fluxo de resposta em tempo real.

// 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; }
  • Para obter detalhes da API, consulte ConverseStreama Referência AWS SDK for .NET da API.

Stable Image Core

O exemplo de código a seguir mostra como invocar o Stability.ai Stable Image Core no Amazon Bedrock para gerar uma imagem.

SDK for .NET (v4)
nota

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

Crie uma imagem com o Stable Image Core.

/// <summary> /// Asynchronously invokes the Stability.ai Stable Image Core model to run an inference based on the provided input. /// </summary> /// <param name="prompt">The prompt that describes the image Stability.ai Stable Image Core has to generate.</param> /// <returns>A base-64 encoded image generated by model</returns> /// <remarks> /// The different model providers have individual request and response formats. /// For the format, ranges, and default values for Stability.ai Stable Image Core, refer to: /// https://docs.aws.amazon.com/bedrock/latest/userguide/model-parameters-diffusion-stable-image-core-text-image-request-response.html /// </remarks> public static async Task<string?> InvokeStableImageCoreAsync(string prompt, int seed) { string stableImageCoreModelId = "stability.stable-image-core-v1:1"; AmazonBedrockRuntimeClient client = new(RegionEndpoint.USWest2); string payload = new JsonObject() { { "prompt", prompt }, { "aspect_ratio", "1:1" }, { "seed", seed }, { "output_format", "png" } }.ToJsonString(); try { InvokeModelResponse response = await client.InvokeModelAsync(new InvokeModelRequest() { ModelId = stableImageCoreModelId, Body = AWSSDKUtils.GenerateMemoryStreamFromString(payload), ContentType = "application/json", Accept = "application/json" }); if (response.HttpStatusCode == System.Net.HttpStatusCode.OK) { var results = JsonNode.ParseAsync(response.Body).Result?["images"]?.AsArray(); return results?[0]?.GetValue<string>(); } else { Console.WriteLine("InvokeModelAsync failed with status code " + response.HttpStatusCode); } } catch (AmazonBedrockRuntimeException e) { Console.WriteLine(e.Message); } return null; }
  • Para obter detalhes da API, consulte InvokeModela Referência AWS SDK for .NET da API.