CommunityBildgithub.com

microsoft/azure-ai-openai-dotnet

Azure OpenAI SDK für .NET. Clientbibliothek für Azure OpenAI- und OpenAI-Dienste. Verwendung für Chat-Vervollständigungen, Einbettungen, Bildgenerierung, Audiotranskription und Assistenten. Auslöser: "Azure OpenAI", "AzureOpenAIClient", "ChatClient", "Chat-Vervollständigungen .NET", "GPT-4", "Einbettungen", "DALL-E", "Whisper", "OpenAI .NET".

Was ist azure-ai-openai-dotnet?

Diese Skill bietet eine umfassende Clientbibliothek für den Zugriff auf Azure OpenAI- und OpenAI-Dienste in .NET-Anwendungen. Sie ermöglicht die Nutzung modernster KI-Modelle wie GPT-4 und GPT-4o für Chat-Vervollständigungen, DALL-E für die Bildgenerierung, Whisper für die Audiotranskription und Text-to-Speech, sowie Einbettungen für semantische Suche. Der Skill unterstützt verschiedene Authentifizierungsmethoden (API-Schlüssel, Microsoft Entra ID) und bietet eine hierarchische Client-Struktur mit spezialisierten Clients für jeden Dienst (ChatClient, EmbeddingClient, ImageClient, AudioClient, AssistantClient). Entwickler können strukturierte Ausgaben mittels JSON-Schema definieren, Reasoning-Modelle (o1, o4-mini) einsetzen und Azure KI Search als Datenquelle für RAG (Retrieval-Augmented Generation) integrieren. Der Skill wird auf Plattformen wie Claude Code, Cursor und Codex verwendet und enthält vollständige Codebeispiele in C#, Best Practices für Produktion (Entra ID, Wiederverwendung von Client-Instanzen, Ratenbegrenzungs-Handling, Streaming) und Referenzen zu verwandten SDKs wie Azure.Identity und Azure.Search.Documents.

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

In Ihrer bevorzugten KI fragen

Öffnet einen neuen Chat, in dem dieser Agent-Skill bereits geladen ist.

Dokumentation

Azure.AI.OpenAI (.NET)

Clientbibliothek für den Azure OpenAI-Dienst, die Zugriff auf OpenAI-Modelle einschließlich GPT-4, GPT-4o, Einbettungen, DALL-E und Whisper bietet.

Installation

dotnet add package Azure.AI.OpenAI

# Für OpenAI (nicht Azure) Kompatibilität
dotnet add package OpenAI

Aktuelle Version: 2.1.0 (stabil)

Umgebungsvariablen

AZURE_OPENAI_ENDPOINT=https://<resource-name>.openai.azure.com  # Erforderlich: Azure OpenAI-Endpunkt
AZURE_OPENAI_API_KEY=<api-key>  # Nur für AzureKeyCredential-Authentifizierung erforderlich
AZURE_OPENAI_DEPLOYMENT_NAME=gpt-4o-mini  # Erforderlich: Name des Modell-Deployments
AZURE_TOKEN_CREDENTIALS=prod  # Nur erforderlich, wenn DefaultAzureCredential in Produktion verwendet wird

Client-Hierarchie

AzureOpenAIClient (Top-Level)
├── GetChatClient(deploymentName)      → ChatClient
├── GetEmbeddingClient(deploymentName) → EmbeddingClient
├── GetImageClient(deploymentName)     → ImageClient
├── GetAudioClient(deploymentName)     → AudioClient
└── GetAssistantClient()               → AssistantClient

Authentifizierung

API-Schlüssel-Authentifizierung

using Azure;
using Azure.AI.OpenAI;

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

Microsoft Entra Token-Anmeldeinformation

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

// Lokale Entwicklung: DefaultAzureCredential. Produktion: setze AZURE_TOKEN_CREDENTIALS=prod oder AZURE_TOKEN_CREDENTIALS=<spezifische_anmeldeinformation>
var credential = new DefaultAzureCredential(
    DefaultAzureCredential.DefaultEnvironmentVariableName
);
// Oder verwende direkt eine spezifische Anmeldeinformation in der Produktion:
// Siehe 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);

Direkte Verwendung des OpenAI SDK mit 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")
    });

Chat-Vervollständigungen

Basis-Chat

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("Du bist ein hilfreicher Assistent."),
    new UserChatMessage("Was ist Azure OpenAI?")
]);

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

Asynchroner Chat

ChatCompletion completion = await chatClient.CompleteChatAsync(
[
    new SystemChatMessage("Du bist ein hilfreicher Assistent."),
    new UserChatMessage("Erkläre Cloud Computing in einfachen Worten.")
]);

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

Streaming-Chat

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

Chat mit Optionen

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

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

Mehrrunden-Konversation

List<ChatMessage> messages = new()
{
    new SystemChatMessage("Du bist ein hilfreicher Assistent."),
    new UserChatMessage("Hallo, kannst du mir helfen?"),
    new AssistantChatMessage("Natürlich! Wobei brauchst du Hilfe?"),
    new UserChatMessage("Was ist die Hauptstadt von Frankreich?")
};

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

Strukturierte Ausgaben (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("Wie löse ich 8x + 7 = -23?")],
    options);

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

Reasoning-Modelle (o1, o4-mini)

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

ChatCompletion completion = await chatClient.CompleteChatAsync(
[
    new DeveloperChatMessage("Du bist ein hilfreicher Assistent"),
    new UserChatMessage("Erkläre die Relativitätstheorie")
], options);

Azure KI Search-Integration (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("Welche Krankenversicherungspläne sind verfügbar?")],
    options);

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

Einbettungen

using OpenAI.Embeddings;

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

OpenAIEmbedding embedding = await embeddingClient.GenerateEmbeddingAsync("Hallo, Welt!");
ReadOnlyMemory<float> vector = embedding.ToFloats();

Console.WriteLine($"Einbettungsdimensionen: {vector.Length}");

Batch-Einbettungen

List<string> inputs = new()
{
    "Erster Dokumenttext",
    "Zweiter Dokumenttext",
    "Dritter Dokumenttext"
};

OpenAIEmbeddingCollection embeddings = await embeddingClient.GenerateEmbeddingsAsync(inputs);

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

Bildgenerierung (DALL-E)

using OpenAI.Images;

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

GeneratedImage image = await imageClient.GenerateImageAsync(
    "Eine futuristische Stadtsilhouette bei Sonnenuntergang",
    new ImageGenerationOptions
    {
        Size = GeneratedImageSize.W1024xH1024,
        Quality = GeneratedImageQuality.High,
        Style = GeneratedImageStyle.Vivid
    });

Console.WriteLine($"Bild-URL: {image.ImageUri}");

Audio (Whisper)

Transkription

using OpenAI.Audio;

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

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

Console.WriteLine(transcription.Text);

Text-zu-Sprache

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

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

Funktionsaufruf (Tools)

ChatTool getCurrentWeatherTool = ChatTool.CreateFunctionTool(
    functionName: "get_current_weather",
    functionDescription: "Ruft das aktuelle Wetter an einem bestimmten Ort ab",
    functionParameters: BinaryData.FromString("""
        {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "Stadt und Bundesland, z.B. Berlin, Deutschland"
                },
                "unit": {
                    "type": "string",
                    "enum": ["celsius", "fahrenheit"]
                }
            },
            "required": ["location"]
        }
        """));

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

ChatCompletion completion = await chatClient.CompleteChatAsync(
    [new UserChatMessage("Wie ist das Wetter in Seattle?")],
    options);

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

Referenz der wichtigsten Typen

TypZweck
AzureOpenAIClientTop-Level-Client für Azure OpenAI
ChatClientChat-Vervollständigungen
EmbeddingClientText-Einbettungen
ImageClientBildgenerierung (DALL-E)
AudioClientAudiotranskription/TTS
ChatCompletionChat-Antwort
ChatCompletionOptionsAnforderungskonfiguration
StreamingChatCompletionUpdateStreaming-Antwortfragment
ChatMessageBasismessagetyp
SystemChatMessageSystem-Prompt
UserChatMessageBenutzereingabe
AssistantChatMessageAssistentenantwort
DeveloperChatMessageEntwicklernachricht (Reasoning-Modelle)
ChatToolFunktions-/Tooldefinition
ChatToolCallTool-Aufrufanforderung

Best Practices

  1. Entra ID in der Produktion verwenden — Vermeide API-Schlüssel; verwende DefaultAzureCredential
  2. Client-Instanzen wiederverwenden — Einmal erstellen, über mehrere Anfragen teilen
  3. Ratenbegrenzungen behandeln — Exponentielles Backoff für 429-Fehler implementieren
  4. Streamen für lange Antworten — Verwende CompleteChatStreamingAsync für bessere Benutzererfahrung
  5. Angemessene Timeouts setzen — Lange Vervollständigungen benötigen möglicherweise verlängerte Timeouts
  6. Strukturierte Ausgaben verwenden — JSON-Schema gewährleistet einheitliches Antwortformat
  7. Tokenverbrauch überwachen — Verfolge completion.Usage für Kostenmanagement
  8. Tool-Aufrufe validieren — Funktionsargumente vor der Ausführung immer validieren

Fehlerbehandlung

using Azure;

try
{
    ChatCompletion completion = await chatClient.CompleteChatAsync(messages);
}
catch (RequestFailedException ex) when (ex.Status == 429)
{
    Console.WriteLine("Ratenbegrenzung erreicht. Wiederholung nach Verzögerung.");
    await Task.Delay(TimeSpan.FromSeconds(10));
}
catch (RequestFailedException ex) when (ex.Status == 400)
{
    Console.WriteLine($"Fehlerhafte Anfrage: {ex.Message}");
}
catch (RequestFailedException ex)
{
    Console.WriteLine($"Azure OpenAI-Fehler: {ex.Status} - {ex.Message}");
}

Verwandte SDKs

SDKZweckInstallation
Azure.AI.OpenAIAzure OpenAI-Client (dieses SDK)dotnet add package Azure.AI.OpenAI
OpenAIOpenAI-Kompatibilitätdotnet add package OpenAI
Azure.IdentityAuthentifizierungdotnet add package Azure.Identity
Azure.Search.DocumentsKI-Suche für RAGdotnet add package Azure.Search.Documents

Referenzlinks

RessourceURL
NuGet-Pakethttps://www.nuget.org/packages/Azure.AI.OpenAI
API-Referenzhttps://learn.microsoft.com/dotnet/api/azure.ai.openai
Migrationsleitfaden (1.0→2.0)https://learn.microsoft.com/azure/ai-services/openai/how-to/dotnet-migration
Schnellstarthttps://learn.microsoft.com/azure/ai-services/openai/quickstart
GitHub-Quellehttps://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.

Verwandte Skills