View a markdown version of this page

Ejemplos de Amazon Bedrock Runtime utilizando SDK for .NET (v4) - AWS SDK for .NET (V4)

¡Se AWS SDK for .NET ha publicado la versión 4 (V4) del!

Para obtener información sobre los cambios más importantes y la migración de sus aplicaciones, consulte el tema sobre migración.

Orange button with text "Click here for details".

Las traducciones son generadas a través de traducción automática. En caso de conflicto entre la traducción y la version original de inglés, prevalecerá la version en inglés.

Ejemplos de Amazon Bedrock Runtime utilizando SDK for .NET (v4)

Los siguientes ejemplos de código muestran cómo realizar acciones e implementar escenarios comunes mediante el uso de AWS SDK for .NET (v4) con Amazon Bedrock Runtime.

En cada ejemplo se incluye un enlace al código de origen completo, con instrucciones de configuración y ejecución del código en el contexto.

Introducción

El siguiente ejemplo de código muestra cómo empezar a utilizar Amazon Bedrock Runtime.

SDK for .NET (v4)
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

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; } } }
  • Para obtener información sobre la API, consulte Converse en la Referencia de la API de AWS SDK for .NET .

Anthropic Claude

El siguiente ejemplo de código muestra cómo enviar un mensaje de texto a Anthropic Claude con la API de Converse de Bedrock.

SDK for .NET (v4)
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

Envíe un mensaje de texto a Anthropic Claude mediante la API de Converse de 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; }
  • Para obtener información sobre la API, consulte Converse en la Referencia de la API de AWS SDK for .NET .

El siguiente ejemplos de código muestra cómo enviar un mensaje de texto a Anthropic Claude con la API de Converse de Bedrock y procesar el flujo de respuesta en tiempo real.

SDK for .NET (v4)
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

Envíe un mensaje de texto a Anthropic Claude con la API de Converse de Bedrock y procese el flujo de respuesta en tiempo 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 obtener más información sobre la API, consulta ConverseStreamla Referencia AWS SDK for .NET de la API.

Cohere Command

El siguiente ejemplo de código muestra cómo enviar un mensaje de texto a Cohere Command con la API de Converse de Bedrock.

SDK for .NET (v4)
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

Envíe un mensaje de texto a Cohere Command mediante la API de Converse de 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; }
  • Para obtener información sobre la API, consulte Converse en la Referencia de la API de AWS SDK for .NET .

El siguiente ejemplo de código muestra cómo enviar un mensaje de texto a Cohere Command con la API de Converse de Bedrock y procesar el flujo de respuesta en tiempo real.

SDK for .NET (v4)
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

Envíe un mensaje de texto a Cohere Command con la API de Converse de Bedrock y procese el flujo de respuesta en tiempo 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 obtener más información sobre la API, consulta ConverseStreamla Referencia AWS SDK for .NET de la API.

Meta Llama

El siguiente ejemplo de código muestra cómo enviar un mensaje de texto a Meta Llama con la API de Converse de Bedrock.

SDK for .NET (v4)
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

Envíe un mensaje de texto a Meta Llama mediante la API de Converse de 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; }
  • Para obtener información sobre la API, consulte Converse en la Referencia de la API de AWS SDK for .NET .

El siguiente ejemplo de código muestra cómo enviar un mensaje de texto a Meta Llama con la API de Converse de Bedrock y procesar el flujo de respuesta en tiempo real.

SDK for .NET (v4)
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

Envíe un mensaje de texto a Meta Llama con la API de Converse de Bedrock y procese el flujo de respuesta en tiempo 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 obtener más información sobre la API, consulta ConverseStreamla Referencia AWS SDK for .NET de la API.

Mistral AI

El siguiente ejemplo de código muestra cómo enviar un mensaje de texto a Mistral con la API de Converse de Bedrock.

SDK for .NET (v4)
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

Envíe un mensaje de texto a Mistral mediante la API de Converse de 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 obtener información sobre la API, consulte Converse en la Referencia de la API de AWS SDK for .NET .

El siguiente ejemplo de código muestra cómo enviar un mensaje de texto a Mistral con la API de Converse de Bedrock y procesar el flujo de respuesta en tiempo real.

SDK for .NET (v4)
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

Envíe un mensaje de texto a Mistral mediante la API de Converse de Bedrock y procese el flujo de respuesta en tiempo 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 obtener más información sobre la API, consulta ConverseStreamla Referencia AWS SDK for .NET de la API.

Stable Image Core

El siguiente ejemplo de código muestra cómo invocar Stability.ai Stable Image Core en Amazon Bedrock para generar una imagen.

SDK for .NET (v4)
nota

Hay más información GitHub. Busque el ejemplo completo y aprenda a configurar y ejecutar en el Repositorio de ejemplos de código de AWS.

Crea una imagen con 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 obtener más información sobre la API, consulte InvokeModella referencia AWS SDK for .NET de la API.