CommunityImagengithub.com

Azure OpenAI SDK para .NET

Cliente de Azure OpenAI para .NET. Accede a GPT-4, embeddings, DALL-E, Whisper y más desde tus aplicaciones .NET.

¿Qué es Azure OpenAI SDK para .NET?

Esta habilidad proporciona el SDK oficial de Azure OpenAI para .NET (`Azure.AI.OpenAI`), permitiendo a desarrolladores .NET integrar modelos de lenguaje avanzados como GPT-4, GPT-4o, DALL-E, Whisper y embeddings en sus aplicaciones. Es compatible con Azure OpenAI Service y también con OpenAI directamente. Su arquitectura jerárquica parte de `AzureOpenAIClient` y ofrece subclientes especializados (`ChatClient`, `EmbeddingClient`, `ImageClient`, `AudioClient`, `AssistantClient`). La habilidad incluye ejemplos completos de finalización de chat (síncrona, asíncrona, streaming y con opciones), salidas estructuradas con esquemas JSON, modelos de razonamiento como o1, integración RAG con Azure AI Search, generación de imágenes DALL-E, transcripción y TTS con Whisper, y llamadas a funciones. Además, documenta buenas prácticas como usar Entra ID en producción, reutilizar instancias de cliente y manejar límites de tasa. Es útil para chatbots, asistentes virtuales, búsqueda semántica, generación de contenido y automatización empresarial.

Compatible con~Claude Code✓Codex CLI~Cursor
npx skills add https://github.com/microsoft/agent-skills/tree/main/.github/plugins/azure-sdk-dotnet/skills/azure-ai-openai-dotnet

Installed? Explore more Imagen skills: steipete/songsee, affaan-m/frontend-design, mattpocock/improve-codebase-architecture · View all 6 →

Preguntar en tu IA favorita

Abre un nuevo chat con esta habilidad de agente ya precargada.

Documentación

Azure.AI.OpenAI (.NET)

Biblioteca cliente para el servicio Azure OpenAI que proporciona acceso a modelos de OpenAI, incluyendo GPT-4, GPT-4o, embeddings, DALL-E y Whisper.

Instalación

dotnet add package Azure.AI.OpenAI

# Para compatibilidad con OpenAI (no Azure)
dotnet add package OpenAI

Versión actual: 2.1.0 (estable)

Variables de entorno

AZURE_OPENAI_ENDPOINT=https://<recurso>.openai.azure.com  # Obligatorio: endpoint de Azure OpenAI
AZURE_OPENAI_API_KEY=<clave-api>  # Solo necesario para autenticación AzureKeyCredential
AZURE_OPENAI_DEPLOYMENT_NAME=gpt-4o-mini  # Obligatorio: nombre del despliegue del modelo
AZURE_TOKEN_CREDENTIALS=prod  # Solo necesario si se usa DefaultAzureCredential en producción

Jerarquía de clientes

AzureOpenAIClient (nivel superior)
├── GetChatClient(nombreDespliegue)      → ChatClient
├── GetEmbeddingClient(nombreDespliegue) → EmbeddingClient
├── GetImageClient(nombreDespliegue)     → ImageClient
├── GetAudioClient(nombreDespliegue)     → AudioClient
└── GetAssistantClient()                 → AssistantClient

Autenticación

Autenticación con clave de API

using Azure;
using Azure.AI.OpenAI;

AzureOpenAIClient cliente = new(
    new Uri(Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")!),
    new AzureKeyCredential(Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")!));

Credencial de token Microsoft Entra

using Azure.Identity;
using Azure.AI.OpenAI;

// Desarrollo local: DefaultAzureCredential. Producción: establecer AZURE_TOKEN_CREDENTIALS=prod o AZURE_TOKEN_CREDENTIALS=<credencial_específica>
var credential = new DefaultAzureCredential(
    DefaultAzureCredential.DefaultEnvironmentVariableName
);
// O usar una credencial específica directamente en producción:
// Véase https://learn.microsoft.com/dotnet/api/overview/azure/identity-readme?view=azure-dotnet#credential-classes
// var credential = new ManagedIdentityCredential();
AzureOpenAIClient cliente = new(
    new Uri(Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")!),
    credential);

Usar el SDK de OpenAI directamente con Azure

using Azure.Identity;
using OpenAI;
using OpenAI.Chat;
using System.ClientModel.Primitives;

#pragma warning disable OPENAI001

BearerTokenPolicy tokenPolicy = new(
    new DefaultAzureCredential(),
    "https://cognitiveservices.azure.com/.default");

ChatClient cliente = new(
    model: "gpt-4o-mini",
    authenticationPolicy: tokenPolicy,
    options: new OpenAIClientOptions()
    {
        Endpoint = new Uri("https://TU-RECURSO.openai.azure.com/openai/v1")
    });

Finalizaciones de chat

Chat básico

using Azure.AI.OpenAI;
using OpenAI.Chat;

AzureOpenAIClient azureClient = new(
    new Uri(endpoint),
    new DefaultAzureCredential());

ChatClient chatClient = azureClient.GetChatClient("gpt-4o-mini");

ChatCompletion completion = chatClient.CompleteChat(
[
    new SystemChatMessage("Eres un asistente útil."),
    new UserChatMessage("¿Qué es Azure OpenAI?")
]);

Console.WriteLine(completion.Content[0].Text);

Chat asíncrono

ChatCompletion completion = await chatClient.CompleteChatAsync(
[
    new SystemChatMessage("Eres un asistente útil."),
    new UserChatMessage("Explica la computación en la nube en términos simples.")
]);

Console.WriteLine($"Respuesta: {completion.Content[0].Text}");
Console.WriteLine($"Tokens usados: {completion.Usage.TotalTokenCount}");

Chat en streaming

await foreach (StreamingChatCompletionUpdate update 
    in chatClient.CompleteChatStreamingAsync(messages))
{
    if (update.ContentUpdate.Count > 0)
    {
        Console.Write(update.ContentUpdate[0].Text);
    }
}

Chat con opciones

ChatCompletionOptions options = new()
{
    MaxOutputTokenCount = 1000,
    Temperature = 0.7f,
    TopP = 0.95f,
    FrequencyPenalty = 0,
    PresencePenalty = 0
};

ChatCompletion completion = await chatClient.CompleteChatAsync(messages, options);

Conversación multi-turno

List<ChatMessage> messages = new()
{
    new SystemChatMessage("Eres un asistente útil."),
    new UserChatMessage("Hola, ¿puedes ayudarme?"),
    new AssistantChatMessage("¡Por supuesto! ¿Con qué necesitas ayuda?"),
    new UserChatMessage("¿Cuál es la capital de Francia?")
};

ChatCompletion completion = await chatClient.CompleteChatAsync(messages);
messages.Add(new AssistantChatMessage(completion.Content[0].Text));

Salidas estructuradas (esquema JSON)

using System.Text.Json;

ChatCompletionOptions options = new()
{
    ResponseFormat = ChatResponseFormat.CreateJsonSchemaFormat(
        jsonSchemaFormatName: "razonamiento_matematico",
        jsonSchema: BinaryData.FromBytes("""
            {
                "type": "object",
                "properties": {
                    "pasos": {
                        "type": "array",
                        "items": {
                            "type": "object",
                            "properties": {
                                "explicacion": { "type": "string" },
                                "resultado": { "type": "string" }
                            },
                            "required": ["explicacion", "resultado"],
                            "additionalProperties": false
                        }
                    },
                    "respuesta_final": { "type": "string" }
                },
                "required": ["pasos", "respuesta_final"],
                "additionalProperties": false
            }
            """u8.ToArray()),
        jsonSchemaIsStrict: true)
};

ChatCompletion completion = await chatClient.CompleteChatAsync(
    [new UserChatMessage("¿Cómo resuelvo 8x + 7 = -23?")],
    options);

using JsonDocument json = JsonDocument.Parse(completion.Content[0].Text);
Console.WriteLine($"Respuesta: {json.RootElement.GetProperty("respuesta_final")}");

Modelos de razonamiento (o1, o4-mini)

ChatCompletionOptions options = new()
{
    ReasoningEffortLevel = ChatReasoningEffortLevel.Low,
    MaxOutputTokenCount = 100000
};

ChatCompletion completion = await chatClient.CompleteChatAsync(
[
    new DeveloperChatMessage("Eres un asistente útil"),
    new UserChatMessage("Explica la teoría de la relatividad")
], options);

Integración con Azure AI Search (RAG)

using Azure.AI.OpenAI.Chat;

#pragma warning disable AOAI001

ChatCompletionOptions options = new();
options.AddDataSource(new AzureSearchChatDataSource()
{
    Endpoint = new Uri(searchEndpoint),
    IndexName = searchIndex,
    Authentication = DataSourceAuthentication.FromApiKey(searchKey)
});

ChatCompletion completion = await chatClient.CompleteChatAsync(
    [new UserChatMessage("¿Qué planes de salud están disponibles?")],
    options);

ChatMessageContext context = completion.GetMessageContext();
if (context?.Intent is not null)
{
    Console.WriteLine($"Intención: {context.Intent}");
}
foreach (ChatCitation citation in context?.Citations ?? [])
{
    Console.WriteLine($"Cita: {citation.Content}");
}

Embeddings

using OpenAI.Embeddings;

EmbeddingClient embeddingClient = azureClient.GetEmbeddingClient("text-embedding-ada-002");

OpenAIEmbedding embedding = await embeddingClient.GenerateEmbeddingAsync("¡Hola, mundo!");
ReadOnlyMemory<float> vector = embedding.ToFloats();

Console.WriteLine($"Dimensiones del embedding: {vector.Length}");

Embeddings por lotes

List<string> inputs = new()
{
    "Texto del primer documento",
    "Texto del segundo documento",
    "Texto del tercer documento"
};

OpenAIEmbeddingCollection embeddings = await embeddingClient.GenerateEmbeddingsAsync(inputs);

foreach (OpenAIEmbedding emb in embeddings)
{
    Console.WriteLine($"Índice {emb.Index}: {emb.ToFloats().Length} dimensiones");
}

Generación de imágenes (DALL-E)

using OpenAI.Images;

ImageClient imageClient = azureClient.GetImageClient("dall-e-3");

GeneratedImage image = await imageClient.GenerateImageAsync(
    "Un horizonte urbano futurista al atardecer",
    new ImageGenerationOptions
    {
        Size = GeneratedImageSize.W1024xH1024,
        Quality = GeneratedImageQuality.High,
        Style = GeneratedImageStyle.Vivid
    });

Console.WriteLine($"URL de la imagen: {image.ImageUri}");

Audio (Whisper)

Transcripción

using OpenAI.Audio;

AudioClient audioClient = azureClient.GetAudioClient("whisper");

AudioTranscription transcription = await audioClient.TranscribeAudioAsync(
    "audio.mp3",
    new AudioTranscriptionOptions
    {
        ResponseFormat = AudioTranscriptionFormat.Verbose,
        Language = "es"
    });

Console.WriteLine(transcription.Text);

Texto a voz

BinaryData speech = await audioClient.GenerateSpeechAsync(
    "Hola, ¡bienvenido a Azure OpenAI!",
    GeneratedSpeechVoice.Alloy,
    new SpeechGenerationOptions
    {
        SpeedRatio = 1.0f,
        ResponseFormat = GeneratedSpeechFormat.Mp3
    });

await File.WriteAllBytesAsync("output.mp3", speech.ToArray());

Llamada a funciones (Tools)

ChatTool getCurrentWeatherTool = ChatTool.CreateFunctionTool(
    functionName: "obtener_clima_actual",
    functionDescription: "Obtiene el clima actual en una ubicación dada",
    functionParameters: BinaryData.FromString("""
        {
            "type": "object",
            "properties": {
                "ubicacion": {
                    "type": "string",
                    "description": "La ciudad y estado, ej. Ciudad de México, CDMX"
                },
                "unidad": {
                    "type": "string",
                    "enum": ["celsius", "fahrenheit"]
                }
            },
            "required": ["ubicacion"]
        }
        """));

ChatCompletionOptions options = new()
{
    Tools = { getCurrentWeatherTool }
};

ChatCompletion completion = await chatClient.CompleteChatAsync(
    [new UserChatMessage("¿Qué clima hace en Seattle?")],
    options);

if (completion.FinishReason == ChatFinishReason.ToolCalls)
{
    foreach (ChatToolCall toolCall in completion.ToolCalls)
    {
        Console.WriteLine($"Función: {toolCall.FunctionName}");
        Console.WriteLine($"Argumentos: {toolCall.FunctionArguments}");
    }
}

Referencia de tipos clave

TipoPropósito
AzureOpenAIClientCliente de nivel superior para Azure OpenAI
ChatClientFinalizaciones de chat
EmbeddingClientEmbeddings de texto
ImageClientGeneración de imágenes (DALL-E)
AudioClientTranscripción de audio/TTS
ChatCompletionRespuesta de chat
ChatCompletionOptionsConfiguración de solicitudes
StreamingChatCompletionUpdateFragmento de respuesta en streaming
ChatMessageTipo base de mensaje
SystemChatMessagePrompt del sistema
UserChatMessageEntrada del usuario
AssistantChatMessageRespuesta del asistente
DeveloperChatMessageMensaje de desarrollador (modelos de razonamiento)
ChatToolDefinición de función/herramienta
ChatToolCallSolicitud de invocación de herramienta

Buenas prácticas

  1. Usar Entra ID en producción — Evitar claves de API; usar DefaultAzureCredential
  2. Reutilizar instancias de cliente — Crear una vez, compartir entre solicitudes
  3. Manejar límites de tasa — Implementar retroceso exponencial para errores 429
  4. Transmitir respuestas largas — Usar CompleteChatStreamingAsync para mejor experiencia de usuario
  5. Establecer tiempos de espera adecuados — Finalizaciones largas pueden necesitar tiempos de espera extendidos
  6. Usar salidas estructuradas — El esquema JSON garantiza un formato de respuesta consistente
  7. Monitorear uso de tokens — Seguir completion.Usage para la gestión de costos
  8. Validar llamadas a herramientas — Siempre validar los argumentos de las funciones antes de ejecutarlas

Manejo de errores

using Azure;

try
{
    ChatCompletion completion = await chatClient.CompleteChatAsync(messages);
}
catch (RequestFailedException ex) when (ex.Status == 429)
{
    Console.WriteLine("Límite de tasa alcanzado. Reintentar tras una pausa.");
    await Task.Delay(TimeSpan.FromSeconds(10));
}
catch (RequestFailedException ex) when (ex.Status == 400)
{
    Console.WriteLine($"Solicitud incorrecta: {ex.Message}");
}
catch (RequestFailedException ex)
{
    Console.WriteLine($"Error de Azure OpenAI: {ex.Status} - {ex.Message}");
}

SDKs relacionados

SDKPropósitoInstalación
Azure.AI.OpenAICliente de Azure OpenAI (este SDK)dotnet add package Azure.AI.OpenAI
OpenAICompatibilidad con OpenAIdotnet add package OpenAI
Azure.IdentityAutenticacióndotnet add package Azure.Identity
Azure.Search.DocumentsAI Search para RAGdotnet add package Azure.Search.Documents

Enlaces de referencia

RecursoURL
Paquete NuGethttps://www.nuget.org/packages/Azure.AI.OpenAI
Referencia de APIhttps://learn.microsoft.com/dotnet/api/azure.ai.openai
Guía de migración (1.0→2.0)https://learn.microsoft.com/azure/ai-services/openai/how-to/dotnet-migration
Inicio rápidohttps://learn.microsoft.com/azure/ai-services/openai/quickstart
Código fuente en GitHubhttps://github.com/Azure/azure-sdk-for-net/tree/main/sdk/openai/Azure.AI.OpenAI

Individual skills in this repo

This repo contains 12 individual skills — each has its own dedicated page.

microsoft/azure-ai-agents-persistent-dotnet

Azure AI Agents Persistent SDK for .NET. Low-level SDK for creating and managing AI agents with threads, messages, runs, and tools. Use for agent CRUD, conversation threads, streaming responses, function calling, file search, and code interpreter. Triggers: "PersistentAgentsClient", "persistent agents", "agent threads", "agent runs", "streaming agents", "function calling agents .NET".

microsoft/azure-ai-document-intelligence-dotnet

Azure AI Document Intelligence SDK for .NET. Extract text, tables, and structured data from documents using prebuilt and custom models. Use for invoice processing, receipt extraction, ID document analysis, and custom document models. Triggers: "Document Intelligence", "DocumentIntelligenceClient", "form recognizer", "invoice extraction", "receipt OCR", "document analysis .NET".

microsoft/azure-ai-projects-dotnet

Azure AI Projects SDK for .NET. High-level client for Azure AI Foundry projects including agents, connections, datasets, deployments, evaluations, and indexes. Use for AI Foundry project management, versioned agents, and orchestration. Triggers: "AI Projects", "AIProjectClient", "Foundry project", "versioned agents", "evaluations", "datasets", "connections", "deployments .NET".

microsoft/azure-ai-voicelive-dotnet

Azure AI Voice Live SDK for .NET. Build real-time voice AI applications with bidirectional WebSocket communication. Use for voice assistants, conversational AI, real-time speech-to-speech, and voice-enabled chatbots. Triggers: "voice live", "real-time voice", "VoiceLiveClient", "VoiceLiveSession", "voice assistant .NET", "bidirectional audio", "speech-to-speech".

microsoft/azure-eventgrid-dotnet

Azure Event Grid SDK for .NET. Client library for publishing and consuming events with Azure Event Grid. Use for event-driven architectures, pub/sub messaging, CloudEvents, and EventGridEvents. Triggers: "Event Grid", "EventGridPublisherClient", "CloudEvent", "EventGridEvent", "publish events .NET", "event-driven", "pub/sub".

microsoft/azure-eventhub-dotnet

Azure Event Hubs SDK for .NET. Use for high-throughput event streaming: sending events (EventHubProducerClient, EventHubBufferedProducerClient), receiving events (EventProcessorClient with checkpointing), partition management, and real-time data ingestion. Triggers: "Event Hubs", "event streaming", "EventHubProducerClient", "EventProcessorClient", "send events", "receive events", "checkpointing", "partition".

microsoft/azure-identity-dotnet

Azure Identity library for .NET. Authentication library for Azure SDK clients using Microsoft Entra ID. Use for DefaultAzureCredential, managed identity, service principals, and developer credentials. Triggers: "Azure Identity", "DefaultAzureCredential", "ManagedIdentityCredential", "ClientSecretCredential", "authentication .NET", "Azure auth", "credential chain".

microsoft/azure-kusto-graph

Build and query Kusto graphs from natural language. Covers transient graphs (make-graph), persistent graph models/snapshots, pattern matching (graph-match), shortest paths, connected components, and graph-to-table export. Generates the edges-first thinking: define edges, define node lookups, union, make-graph. WHEN: make-graph, graph-match, graph-shortest-paths, graph-to-table, graph-mark-components, persistent graph, graph model, graph snapshot, build a graph from data, find paths between nodes, pattern matching in graph, connected components, transient graph, Kusto graph, KQL graph.

microsoft/azure-kusto-irql

Compose IRQL (Incident Response Query Language) queries for Kusto cybersecurity investigations. Translates natural language hunting questions into composable IRQL pipelines using Get_*, Extract_*, and Enrich_* functions. WHEN: IRQL query, security hunt, threat hunting KQL, incident response query, compose hunting pipeline, failed logins, phishing investigation, lateral movement, process execution, file creation events.

microsoft/azure-kusto-irql-graph

Apply IRQL graph functions to KQL or IRQL query results for Kusto Explorer visualization. Generates Lift_To_Graph mappings and composes Graph_Render_View, Graph_Fold_By_Property, Extract_Node_*, Enrich_Node_*, and Enrich_Graph_* calls. Accepts a supplied query or limited basic natural-language source request; it is not a general natural-language-to-KQL/IRQL skill. WHEN: Lift_To_Graph, Graph_Render_View, Graph_Fold_By_Property, IRQL graph enrichment, graph mapping for existing query results, icon-decorated graph, fold graph nodes. Use azure-kusto-graph for native make-graph analysis, graph-match, shortest paths, components, or persistent graphs.

microsoft/azure-local

Plan, deploy, operate, and troubleshoot Azure Local (formerly Azure Stack HCI): sizing and prerequisites, Arc registration, lifecycle updates, workloads (Azure Local VMs, AKS on Azure Local, images, disks, logical networks), SDN and network security, and failure triage — starting read-only and confirming before risky changes. WHEN: Azure Local, Azure Stack HCI, Arc resource bridge, custom location, Azure Local VM, Arc VM, AKS on Azure Local, AKS hybrid, SDN, Lifecycle Manager, Azure Local update, disconnected site.

microsoft/azure-local-multi-rack

Plan, deploy, operate, and troubleshoot multi-rack (rack scale) deployments of Azure Local — preintegrated racks scaling to hundreds of machines, built on Network Fabric Controller, Cluster Manager, SAN storage, and managed network fabric. Use for the Microsoft.NetworkCloud and Microsoft.ManagedNetworkFabric control plane. NOT for standard 1-16 node Azure Local, and NOT for rack-aware clusters (two racks as availability zones, up to 8 nodes, synchronous replication) — those are standard scale. WHEN: multi-rack, rack scale Azure Local, aggregation rack, compute rack, Network Fabric Controller, NFC, Cluster Manager, network fabric, isolation domain, az networkcloud, az networkfabric, multi-rack logical network, multi-rack Arc VM.

Skills relacionados