CommunityImagemgithub.com

microsoft/azure-ai-openai-dotnet

SDK do Azure OpenAI para .NET. Biblioteca de cliente para serviços Azure OpenAI e OpenAI. Use para completações de chat, embeddings, geração de imagens, transcrição de áudio e assistentes.

O que é azure-ai-openai-dotnet?

Esta skill fornece acesso completo ao SDK do Azure OpenAI para .NET (Azure.AI.OpenAI), permitindo que agentes de IA e desenvolvedores interajam com modelos como GPT-4, GPT-4o, DALL-E e Whisper diretamente de aplicações .NET. Ela suporta operações essenciais como completações de chat, embeddings, geração de imagens, transcrição de áudio e chamada de funções. A skill também cobre cenários avançados, incluindo saídas estruturadas com JSON Schema, modelos de raciocínio (o1, o4-mini), integração RAG com Azure AI Search e autenticação via chave de API ou token Microsoft Entra. Ideal para construir chatbots, ferramentas de sumarização, assistentes multimodais e pipelines de IA generativa no ecossistema .NET, com exemplos práticos de código C# para sincronia, assíncrono e streaming.

Funciona com~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 Imagem skills: steipete/songsee, affaan-m/frontend-design, mattpocock/improve-codebase-architecture · View all 6 →

Perguntar na sua IA favorita

Abre um novo chat com esta habilidade de agente já pré-carregada.

Documentação

Azure.AI.OpenAI (.NET)

Biblioteca de cliente para o serviço Azure OpenAI que fornece acesso a modelos OpenAI, incluindo GPT-4, GPT-4o, embeddings, DALL-E e Whisper.

Instalação

dotnet add package Azure.AI.OpenAI

# Para compatibilidade com OpenAI (não Azure)
dotnet add package OpenAI

Versão Atual: 2.1.0 (estável)

Variáveis de Ambiente

AZURE_OPENAI_ENDPOINT=https://<resource-name>.openai.azure.com  # Obrigatório: endpoint do Azure OpenAI
AZURE_OPENAI_API_KEY=<api-key>  # Apenas necessário para autenticação AzureKeyCredential
AZURE_OPENAI_DEPLOYMENT_NAME=gpt-4o-mini  # Obrigatório: nome da implantação do modelo
AZURE_TOKEN_CREDENTIALS=prod  # Necessário apenas se DefaultAzureCredential for usado em produção

Hierarquia de Clientes

AzureOpenAIClient (nível superior)
├── GetChatClient(deploymentName)      → ChatClient
├── GetEmbeddingClient(deploymentName) → EmbeddingClient
├── GetImageClient(deploymentName)     → ImageClient
├── GetAudioClient(deploymentName)     → AudioClient
└── GetAssistantClient()               → AssistantClient

Autenticação

Autenticação via Chave de API

using Azure;
using Azure.AI.OpenAI;

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

Token de Credencial Microsoft Entra

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

// Desenvolvimento local: DefaultAzureCredential. Produção: defina AZURE_TOKEN_CREDENTIALS=prod ou AZURE_TOKEN_CREDENTIALS=<credential_especifica>
var credential = new DefaultAzureCredential(
    DefaultAzureCredential.DefaultEnvironmentVariableName
);
// Ou use uma credencial específica diretamente em produção:
// Consulte https://learn.microsoft.com/dotnet/api/overview/azure/identity-readme?view=azure-dotnet#credential-classes
// var credential = new ManagedIdentityCredential();
AzureOpenAIClient client = new(
    new Uri(Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")!),
    credential);

Usando o SDK OpenAI Diretamente com 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 client = new(
    model: "gpt-4o-mini",
    authenticationPolicy: tokenPolicy,
    options: new OpenAIClientOptions()
    {
        Endpoint = new Uri("https://YOUR-RESOURCE.openai.azure.com/openai/v1")
    });

Completions 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("Você é um assistente útil."),
    new UserChatMessage("O que é Azure OpenAI?")
]);

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

Chat Assíncrono

ChatCompletion completion = await chatClient.CompleteChatAsync(
[
    new SystemChatMessage("Você é um assistente útil."),
    new UserChatMessage("Explique computação em nuvem em termos simples.")
]);

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

Chat com Streaming

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

Chat com Opções

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

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

Conversa de Múltiplas Interações

List<ChatMessage> messages = new()
{
    new SystemChatMessage("Você é um assistente útil."),
    new UserChatMessage("Oi, pode me ajudar?"),
    new AssistantChatMessage("Claro! Com o que você precisa de ajuda?"),
    new UserChatMessage("Qual é a capital da França?")
};

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

Saídas Estruturadas (JSON Schema)

using System.Text.Json;

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

ChatCompletion completion = await chatClient.CompleteChatAsync(
    [new UserChatMessage("Como resolver 8x + 7 = -23?")],
    options);

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

Modelos de Raciocínio (o1, o4-mini)

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

ChatCompletion completion = await chatClient.CompleteChatAsync(
[
    new DeveloperChatMessage("Você é um assistente útil"),
    new UserChatMessage("Explique a teoria da relatividade")
], options);

Integração 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("Quais planos de saúde estão disponíveis?")],
    options);

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

Embeddings

using OpenAI.Embeddings;

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

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

Console.WriteLine($"Dimensões do embedding: {vector.Length}");

Embeddings em Lote

List<string> inputs = new()
{
    "Texto do primeiro documento",
    "Texto do segundo documento",
    "Texto do terceiro documento"
};

OpenAIEmbeddingCollection embeddings = await embeddingClient.GenerateEmbeddingsAsync(inputs);

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

Geração de Imagens (DALL-E)

using OpenAI.Images;

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

GeneratedImage image = await imageClient.GenerateImageAsync(
    "Um horizonte de cidade futurista ao pôr do sol",
    new ImageGenerationOptions
    {
        Size = GeneratedImageSize.W1024xH1024,
        Quality = GeneratedImageQuality.High,
        Style = GeneratedImageStyle.Vivid
    });

Console.WriteLine($"URL da imagem: {image.ImageUri}");

Áudio (Whisper)

Transcrição

using OpenAI.Audio;

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

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

Console.WriteLine(transcription.Text);

Texto-para-Fala

BinaryData speech = await audioClient.GenerateSpeechAsync(
    "Olá, bem-vindo ao Azure OpenAI!",
    GeneratedSpeechVoice.Alloy,
    new SpeechGenerationOptions
    {
        SpeedRatio = 1.0f,
        ResponseFormat = GeneratedSpeechFormat.Mp3
    });

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

Chamada de Função (Ferramentas)

ChatTool getCurrentWeatherTool = ChatTool.CreateFunctionTool(
    functionName: "obter_clima_atual",
    functionDescription: "Obter o clima atual em uma determinada localização",
    functionParameters: BinaryData.FromString("""
        {
            "type": "object",
            "properties": {
                "localizacao": {
                    "type": "string",
                    "description": "A cidade e estado, ex. São Paulo, SP"
                },
                "unidade": {
                    "type": "string",
                    "enum": ["celsius", "fahrenheit"]
                }
            },
            "required": ["localizacao"]
        }
        """));

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

ChatCompletion completion = await chatClient.CompleteChatAsync(
    [new UserChatMessage("Como está o clima em Seattle?")],
    options);

if (completion.FinishReason == ChatFinishReason.ToolCalls)
{
    foreach (ChatToolCall toolCall in completion.ToolCalls)
    {
        Console.WriteLine($"Função: {toolCall.FunctionName}");
        Console.WriteLine($"Argumentos: {toolCall.FunctionArguments}");
    }
}

Referência de Tipos Principais

TipoPropósito
AzureOpenAIClientCliente de nível superior para Azure OpenAI
ChatClientCompletions de chat
EmbeddingClientEmbeddings de texto
ImageClientGeração de imagens (DALL-E)
AudioClientTranscrição de áudio/TTS
ChatCompletionResposta do chat
ChatCompletionOptionsConfiguração da requisição
StreamingChatCompletionUpdateFragmento da resposta em streaming
ChatMessageTipo base de mensagem
SystemChatMessagePrompt do sistema
UserChatMessageEntrada do usuário
AssistantChatMessageResposta do assistente
DeveloperChatMessageMensagem do desenvolvedor (modelos de raciocínio)
ChatToolDefinição de função/ferramenta
ChatToolCallSolicitação de invocação de ferramenta

Melhores Práticas

  1. Use Entra ID em produção — Evite chaves de API; use DefaultAzureCredential
  2. Reutilize instâncias de cliente — Crie uma vez, compartilhe entre requisições
  3. Lide com limites de taxa — Implemente backoff exponencial para erros 429
  4. Faça streaming para respostas longas — Use CompleteChatStreamingAsync para melhor experiência do usuário
  5. Defina timeouts adequados — Completions longas podem precisar de timeouts estendidos
  6. Use saídas estruturadas — O esquema JSON garante um formato de resposta consistente
  7. Monitore o uso de tokens — Acompanhe completion.Usage para gerenciamento de custos
  8. Valide chamadas de ferramenta — Sempre valide os argumentos da função antes da execução

Tratamento de Erros

using Azure;

try
{
    ChatCompletion completion = await chatClient.CompleteChatAsync(messages);
}
catch (RequestFailedException ex) when (ex.Status == 429)
{
    Console.WriteLine("Limite de taxa excedido. Repetir após atraso.");
    await Task.Delay(TimeSpan.FromSeconds(10));
}
catch (RequestFailedException ex) when (ex.Status == 400)
{
    Console.WriteLine($"Requisição inválida: {ex.Message}");
}
catch (RequestFailedException ex)
{
    Console.WriteLine($"Erro do Azure OpenAI: {ex.Status} - {ex.Message}");
}

SDKs Relacionados

SDKPropósitoInstalação
Azure.AI.OpenAICliente Azure OpenAI (este SDK)dotnet add package Azure.AI.OpenAI
OpenAICompatibilidade OpenAIdotnet add package OpenAI
Azure.IdentityAutenticaçãodotnet add package Azure.Identity
Azure.Search.DocumentsAI Search para RAGdotnet add package Azure.Search.Documents

Links de Referência

RecursoURL
Pacote NuGethttps://www.nuget.org/packages/Azure.AI.OpenAI
Referência da APIhttps://learn.microsoft.com/dotnet/api/azure.ai.openai
Guia de Migração (1.0→2.0)https://learn.microsoft.com/azure/ai-services/openai/how-to/dotnet-migration
Guia de Início Rápidohttps://learn.microsoft.com/azure/ai-services/openai/quickstart
Código Fonte no 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.

Habilidades Relacionadas