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
dotnet add package OpenAI
Version actuelle : 2.1.0 (stable)
Variables d'environnement
AZURE_OPENAI_ENDPOINT=https://<resource-name>.openai.azure.com
AZURE_OPENAI_API_KEY=<api-key>
AZURE_OPENAI_DEPLOYMENT_NAME=gpt-4o-mini
AZURE_TOKEN_CREDENTIALS=prod
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;
var credential = new DefaultAzureCredential(
DefaultAzureCredential.DefaultEnvironmentVariableName
);
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
| Type | Objectif |
|---|
AzureOpenAIClient | Client de niveau supérieur pour Azure OpenAI |
ChatClient | Complétions de chat |
EmbeddingClient | Embeddings de texte |
ImageClient | Génération d'images (DALL-E) |
AudioClient | Transcription audio/TTS |
ChatCompletion | Réponse de chat |
ChatCompletionOptions | Configuration de la requête |
StreamingChatCompletionUpdate | Fragment de réponse en streaming |
ChatMessage | Type de message de base |
SystemChatMessage | Prompt système |
UserChatMessage | Saisie utilisateur |
AssistantChatMessage | Réponse de l'assistant |
DeveloperChatMessage | Message développeur (modèles de raisonnement) |
ChatTool | Définition de fonction/outil |
ChatToolCall | Demande d'invocation d'outil |
Bonnes pratiques
- Utiliser Entra ID en production — Éviter les clés API ; utiliser
DefaultAzureCredential
- Réutiliser les instances clientes — Créer une fois, partager entre les requêtes
- Gérer les limites de débit — Implémenter un backoff exponentiel pour les erreurs 429
- Streamer pour les longues réponses — Utiliser
CompleteChatStreamingAsync pour une meilleure expérience utilisateur
- Définir des délais d'attente appropriés — Les longues complétions peuvent nécessiter des délais étendus
- Utiliser des sorties structurées — Le schéma JSON garantit un format de réponse cohérent
- Surveiller l'utilisation des tokens — Suivre
completion.Usage pour la gestion des coûts
- 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
| SDK | Objectif | Installation |
|---|
Azure.AI.OpenAI | Client Azure OpenAI (ce SDK) | dotnet add package Azure.AI.OpenAI |
OpenAI | Compatibilité OpenAI | dotnet add package OpenAI |
Azure.Identity | Authentification | dotnet add package Azure.Identity |
Azure.Search.Documents | Recherche AI pour RAG | dotnet add package Azure.Search.Documents |
Liens de référence