CommunityImagegithub.com

microsoft/azure-ai-openai-dotnet

SDK Azure OpenAI pour .NET. Bibliothèque cliente pour les services Azure OpenAI et OpenAI. Utilisé pour les complétions de chat, les embeddings, la génération d'images, la transcription audio et les assistants. Déclencheurs : "Azure OpenAI", "AzureOpenAIClient", "ChatClient", "chat completions .NET", "GPT-4", "embeddings", "DALL-E", "Whisper", "OpenAI .NET".

Qu'est-ce que azure-ai-openai-dotnet ?

Ce skill fournit une bibliothèque cliente .NET complète pour interagir avec le service Azure OpenAI, donnant accès aux modèles GPT-4, GPT-4o, aux embeddings, à DALL-E et à Whisper. Il est conçu pour les développeurs utilisant des environnements comme Claude Code, Cursor ou Codex, et prend en charge les applications console, les API web et les services backend. La bibliothèque simplifie l'intégration en gérant l'authentification via des clés API ou des identifiants Microsoft Entra, et expose une hiérarchie de clients pour différents services : ChatClient pour les complétions de chat, EmbeddingClient pour les embeddings, ImageClient pour la génération d'images, AudioClient pour la transcription audio et la synthèse vocale, et AssistantClient pour les assistants. Les fonctionnalités clés incluent le chat de base et en streaming, les sorties structurées via JSON Schema, l'appel de fonctions, l'intégration de la recherche Azure AI pour le RAG, et la gestion des modèles de raisonnement comme o1 et o4-mini. L'accent est mis sur les meilleures pratiques de production, telles que la réutilisation des instances clientes, la gestion des limites de débit, l'utilisation de sorties structurées et le suivi de la consommation de tokens. Le skill fournit également des modèles de gestion des erreurs et des liens vers la documentation de référence complète.

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

Demander à votre IA préférée

Ouvre une nouvelle conversation avec cette compétence d'agent déjà préchargée.

Documentation

Azure.AI.OpenAI (.NET)

Bibliothèque cliente pour le service Azure OpenAI donnant accès aux modèles OpenAI, y compris GPT-4, GPT-4o, embeddings, DALL-E et Whisper.

Installation

dotnet add package Azure.AI.OpenAI

# Pour la compatibilité OpenAI (non-Azure)
dotnet add package OpenAI

Version actuelle : 2.1.0 (stable)

Variables d'environnement

AZURE_OPENAI_ENDPOINT=https://<resource-name>.openai.azure.com  # Obligatoire : point de terminaison Azure OpenAI
AZURE_OPENAI_API_KEY=<api-key>  # Uniquement requis pour l'authentification AzureKeyCredential
AZURE_OPENAI_DEPLOYMENT_NAME=gpt-4o-mini  # Obligatoire : nom du déploiement du modèle
AZURE_TOKEN_CREDENTIALS=prod  # Obligatoire uniquement si DefaultAzureCredential est utilisé en production

Hiérarchie des clients

AzureOpenAIClient (niveau supérieur)
├── GetChatClient(deploymentName)      → ChatClient
├── GetEmbeddingClient(deploymentName) → EmbeddingClient
├── GetImageClient(deploymentName)     → ImageClient
├── GetAudioClient(deploymentName)     → AudioClient
└── GetAssistantClient()               → AssistantClient

Authentification

Authentification par clé 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")!));

Jeton d'accès Microsoft Entra

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

// Développement local : DefaultAzureCredential. Production : définir AZURE_TOKEN_CREDENTIALS=prod ou AZURE_TOKEN_CREDENTIALS=<credential_spécifique>
var credential = new DefaultAzureCredential(
    DefaultAzureCredential.DefaultEnvironmentVariableName
);
// Ou utiliser directement un identifiant spécifique en production :
// Voir 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);

Utilisation directe du SDK OpenAI avec 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")
    });

Complétions de chat

Chat de base

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("Vous êtes un assistant serviable."),
    new UserChatMessage("Qu'est-ce qu'Azure OpenAI ?")
]);

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

Chat asynchrone

ChatCompletion completion = await chatClient.CompleteChatAsync(
[
    new SystemChatMessage("Vous êtes un assistant serviable."),
    new UserChatMessage("Expliquez le cloud computing en termes simples.")
]);

Console.WriteLine($"Réponse : {completion.Content[0].Text}");
Console.WriteLine($"Tokens utilisés : {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 avec options

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

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

Conversation à plusieurs tours

List<ChatMessage> messages = new()
{
    new SystemChatMessage("Vous êtes un assistant serviable."),
    new UserChatMessage("Bonjour, pouvez-vous m'aider ?"),
    new AssistantChatMessage("Bien sûr ! Avec quoi avez-vous besoin d'aide ?"),
    new UserChatMessage("Quelle est la capitale de la France ?")
};

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

Sorties structurées (JSON Schema)

using System.Text.Json;

ChatCompletionOptions options = new()
{
    ResponseFormat = ChatResponseFormat.CreateJsonSchemaFormat(
        jsonSchemaFormatName: "math_reasoning",
        jsonSchema: BinaryData.FromBytes("""
            {
                "type": "object",
                "properties": {
                    "steps": {
                        "type": "array",
                        "items": {
                            "type": "object",
                            "properties": {
                                "explanation": { "type": "string" },
                                "output": { "type": "string" }
                            },
                            "required": ["explanation", "output"],
                            "additionalProperties": false
                        }
                    },
                    "final_answer": { "type": "string" }
                },
                "required": ["steps", "final_answer"],
                "additionalProperties": false
            }
            """u8.ToArray()),
        jsonSchemaIsStrict: true)
};

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

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

Modèles de raisonnement (o1, o4-mini)

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

ChatCompletion completion = await chatClient.CompleteChatAsync(
[
    new DeveloperChatMessage("Vous êtes un assistant serviable"),
    new UserChatMessage("Expliquez la théorie de la relativité")
], options);

Intégration 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("Quels sont les plans de santé disponibles ?")],
    options);

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

Embeddings

using OpenAI.Embeddings;

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

OpenAIEmbedding embedding = await embeddingClient.GenerateEmbeddingAsync("Bonjour le monde !");
ReadOnlyMemory<float> vector = embedding.ToFloats();

Console.WriteLine($"Dimensions de l'embedding : {vector.Length}");

Embeddings par lots

List<string> inputs = new()
{
    "Texte du premier document",
    "Texte du deuxième document",
    "Texte du troisième document"
};

OpenAIEmbeddingCollection embeddings = await embeddingClient.GenerateEmbeddingsAsync(inputs);

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

Génération d'images (DALL-E)

using OpenAI.Images;

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

GeneratedImage image = await imageClient.GenerateImageAsync(
    "Un paysage urbain futuriste au coucher du soleil",
    new ImageGenerationOptions
    {
        Size = GeneratedImageSize.W1024xH1024,
        Quality = GeneratedImageQuality.High,
        Style = GeneratedImageStyle.Vivid
    });

Console.WriteLine($"URL de l'image : {image.ImageUri}");

Audio (Whisper)

Transcription

using OpenAI.Audio;

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

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

Console.WriteLine(transcription.Text);

Synthèse vocale (Text-to-Speech)

BinaryData speech = await audioClient.GenerateSpeechAsync(
    "Bonjour, bienvenue sur Azure OpenAI !",
    GeneratedSpeechVoice.Alloy,
    new SpeechGenerationOptions
    {
        SpeedRatio = 1.0f,
        ResponseFormat = GeneratedSpeechFormat.Mp3
    });

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

Appel de fonctions (Outils)

ChatTool getCurrentWeatherTool = ChatTool.CreateFunctionTool(
    functionName: "get_current_weather",
    functionDescription: "Obtenir la météo actuelle pour un lieu donné",
    functionParameters: BinaryData.FromString("""
        {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "La ville et l'état, ex. Paris, France"
                },
                "unit": {
                    "type": "string",
                    "enum": ["celsius", "fahrenheit"]
                }
            },
            "required": ["location"]
        }
        """));

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

ChatCompletion completion = await chatClient.CompleteChatAsync(
    [new UserChatMessage("Quel temps fait-il à Seattle ?")],
    options);

if (completion.FinishReason == ChatFinishReason.ToolCalls)
{
    foreach (ChatToolCall toolCall in completion.ToolCalls)
    {
        Console.WriteLine($"Fonction : {toolCall.FunctionName}");
        Console.WriteLine($"Arguments : {toolCall.FunctionArguments}");
    }
}

Référence des types clés

TypeObjectif
AzureOpenAIClientClient de niveau supérieur pour Azure OpenAI
ChatClientComplétions de chat
EmbeddingClientEmbeddings de texte
ImageClientGénération d'images (DALL-E)
AudioClientTranscription audio/TTS
ChatCompletionRéponse de chat
ChatCompletionOptionsConfiguration de la requête
StreamingChatCompletionUpdateFragment de réponse en streaming
ChatMessageType de message de base
SystemChatMessagePrompt système
UserChatMessageSaisie utilisateur
AssistantChatMessageRéponse de l'assistant
DeveloperChatMessageMessage développeur (modèles de raisonnement)
ChatToolDéfinition de fonction/outil
ChatToolCallDemande d'invocation d'outil

Bonnes pratiques

  1. Utiliser Entra ID en production — Éviter les clés API ; utiliser DefaultAzureCredential
  2. Réutiliser les instances clientes — Créer une fois, partager entre les requêtes
  3. Gérer les limites de débit — Implémenter un backoff exponentiel pour les erreurs 429
  4. Streamer pour les longues réponses — Utiliser CompleteChatStreamingAsync pour une meilleure expérience utilisateur
  5. Définir des délais d'attente appropriés — Les longues complétions peuvent nécessiter des délais étendus
  6. Utiliser des sorties structurées — Le schéma JSON garantit un format de réponse cohérent
  7. Surveiller l'utilisation des tokens — Suivre completion.Usage pour la gestion des coûts
  8. Valider les appels d'outils — Toujours valider les arguments des fonctions avant exécution

Gestion des erreurs

using Azure;

try
{
    ChatCompletion completion = await chatClient.CompleteChatAsync(messages);
}
catch (RequestFailedException ex) when (ex.Status == 429)
{
    Console.WriteLine("Limite de débit atteinte. Nouvelle tentative après délai.");
    await Task.Delay(TimeSpan.FromSeconds(10));
}
catch (RequestFailedException ex) when (ex.Status == 400)
{
    Console.WriteLine($"Requête incorrecte : {ex.Message}");
}
catch (RequestFailedException ex)
{
    Console.WriteLine($"Erreur Azure OpenAI : {ex.Status} - {ex.Message}");
}

SDK associés

SDKObjectifInstallation
Azure.AI.OpenAIClient Azure OpenAI (ce SDK)dotnet add package Azure.AI.OpenAI
OpenAICompatibilité OpenAIdotnet add package OpenAI
Azure.IdentityAuthentificationdotnet add package Azure.Identity
Azure.Search.DocumentsRecherche AI pour RAGdotnet add package Azure.Search.Documents

Liens de référence

RessourceURL
Package NuGethttps://www.nuget.org/packages/Azure.AI.OpenAI
Référence APIhttps://learn.microsoft.com/dotnet/api/azure.ai.openai
Guide de migration (1.0→2.0)https://learn.microsoft.com/azure/ai-services/openai/how-to/dotnet-migration
Guide de démarrage rapidehttps://learn.microsoft.com/azure/ai-services/openai/quickstart
Source 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 associés