CommunitySchreiben & Editierengithub.com

microsoft/azure-ai-agents-persistent-dotnet

Low-Level-SDK für .NET zur Erstellung und Verwaltung persistenter KI-Agenten mit Threads, Nachrichten, Ausführungen und Tools. Für Agent-CRUD, Konversationsthreads, Streaming, Funktionsaufrufe, Dateisuche und Code-Interpreter.

Was ist azure-ai-agents-persistent-dotnet?

Dieses .NET SDK bietet eine programmatische Low-Level-Schnittstelle zur Erstellung und Verwaltung persistenter KI-Agenten in Azure AI. Es ermöglicht CRUD-Operationen für Agenten, die Verwaltung von Unterhaltungsthreads und -nachrichten, die Ausführung von Agentenläufen (sowohl polling-basiert als auch per Streaming) sowie die Integration verschiedener Tools wie Code-Interpreter, Dateisuche mit Vektor-Store, Funktionsaufrufe, Bing Grounding und Azure AI Search. Ein zentraler Vorteil ist die persistente Speicherung von Agenten und Threads, die sich besonders für langlebige, interaktive Anwendungen eignet. Entwickler können mit diesem SDK robuste und asynchrone .NET-Anwendungen erstellen, die KI-Agenten in Produktionsumgebungen einsetzen.

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-agents-persistent-dotnet

Installed? Explore more Schreiben & Editieren skills: steipete/notion, langchain-ai/langchain, bytedance/podcast-generation · View all 6 →

In Ihrer bevorzugten KI fragen

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

Dokumentation

Azure.AI.Agents.Persistent (.NET)

Low-Level-SDK für die Erstellung und Verwaltung persistenter KI-Agenten mit Threads, Nachrichten, Ausführungen und Tools.

Installation

dotnet add package Azure.AI.Agents.Persistent --prerelease
dotnet add package Azure.Identity

Aktuelle Versionen: Stabil v1.1.0, Vorschau v1.2.0-beta.8

Umgebungsvariablen

PROJECT_ENDPOINT=https://<resource>.services.ai.azure.com/api/projects/<project>  # Erforderlich: Azure AI Projektendpunkt
MODEL_DEPLOYMENT_NAME=gpt-4o-mini  # Erforderlich: Modellbereitstellungsname
AZURE_BING_CONNECTION_ID=<bing-connection-resource-id>  # Erforderlich: Bing Verbindungsressourcen-ID
AZURE_AI_SEARCH_CONNECTION_ID=<search-connection-resource-id>  # Erforderlich: Azure AI Search Verbindungsressourcen-ID
AZURE_TOKEN_CREDENTIALS=prod  # Nur erforderlich, wenn DefaultAzureCredential in der Produktion verwendet wird

Authentifizierung

using Azure.AI.Agents.Persistent;
using Azure.Identity;

var projectEndpoint = Environment.GetEnvironmentVariable("PROJECT_ENDPOINT");
// Lokale Entwicklung: DefaultAzureCredential. Produktion: Setze AZURE_TOKEN_CREDENTIALS=prod oder AZURE_TOKEN_CREDENTIALS=<spezifische_anmeldeinformationen>
var credential = new DefaultAzureCredential(
    DefaultAzureCredential.DefaultEnvironmentVariableName
);
// Oder verwende in der Produktion direkt eine spezifische Anmeldeinformation:
// Siehe https://learn.microsoft.com/dotnet/api/overview/azure/identity-readme?view=azure-dotnet#credential-classes
// var credential = new ManagedIdentityCredential();
PersistentAgentsClient client = new(projectEndpoint, credential);

Client-Hierarchie

PersistentAgentsClient
├── Administration  → Agent-CRUD-Operationen
├── Threads         → Thread-Verwaltung
├── Messages        → Nachrichtenoperationen
├── Runs            → Ausführung und Streaming
├── Files           → Datei-Upload/Download
└── VectorStores    → Vektor-Store-Verwaltung

Kernablauf

1. Agent erstellen

var modelDeploymentName = Environment.GetEnvironmentVariable("MODEL_DEPLOYMENT_NAME");

PersistentAgent agent = await client.Administration.CreateAgentAsync(
    model: modelDeploymentName,
    name: "Mathe-Tutor",
    instructions: "Du bist ein persönlicher Mathe-Tutor. Schreibe und führe Code aus, um Mathefragen zu beantworten.",
    tools: [new CodeInterpreterToolDefinition()]
);

2. Thread und Nachricht erstellen

// Thread erstellen
PersistentAgentThread thread = await client.Threads.CreateThreadAsync();

// Nachricht erstellen
await client.Messages.CreateMessageAsync(
    thread.Id,
    MessageRole.User,
    "Ich muss die Gleichung `3x + 11 = 14` lösen. Kannst du mir helfen?"
);

3. Agent ausführen (Polling)

// Ausführung erstellen
ThreadRun run = await client.Runs.CreateRunAsync(
    thread.Id,
    agent.Id,
    additionalInstructions: "Bitte spreche den Benutzer als Max Mustermann an."
);

// Auf Abschluss warten
await Task.Delay(TimeSpan.FromMilliseconds(500));
run = await client.Runs.GetRunAsync(thread.Id, run.Id);
while (run.Status == RunStatus.Queued || run.Status == RunStatus.InProgress)
{
    await Task.Delay(TimeSpan.FromMilliseconds(500));
    run = await client.Runs.GetRunAsync(thread.Id, run.Id);
}

// Nachrichten abrufen
await foreach (PersistentThreadMessage message in client.Messages.GetMessagesAsync(
    threadId: thread.Id, 
    order: ListSortOrder.Ascending))
{
    Console.Write($"{message.Role}: ");
    foreach (MessageContent content in message.ContentItems)
    {
        if (content is MessageTextContent textContent)
            Console.WriteLine(textContent.Text);
    }
}

4. Streaming-Antwort

AsyncCollectionResult<StreamingUpdate> stream = client.Runs.CreateRunStreamingAsync(
    thread.Id, 
    agent.Id
);

await foreach (StreamingUpdate update in stream)
{
    if (update.UpdateKind == StreamingUpdateReason.RunCreated)
    {
        Console.WriteLine("--- Ausführung gestartet! ---");
    }
    else if (update is MessageContentUpdate contentUpdate)
    {
        Console.Write(contentUpdate.Text);
    }
    else if (update.UpdateKind == StreamingUpdateReason.RunCompleted)
    {
        Console.WriteLine("\n--- Ausführung abgeschlossen! ---");
    }
}

5. Funktionsaufrufe

// Funktionswerkzeug definieren
FunctionToolDefinition weatherTool = new(
    name: "getCurrentWeather",
    description: "Ermittelt das aktuelle Wetter an einem Ort.",
    parameters: BinaryData.FromObjectAsJson(new
    {
        Type = "object",
        Properties = new
        {
            Location = new { Type = "string", Description = "Stadt und Bundesland, z.B. Berlin, Deutschland" },
            Unit = new { Type = "string", Enum = new[] { "c", "f" } }
        },
        Required = new[] { "location" }
    }, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase })
);

// Agent mit Funktion erstellen
PersistentAgent agent = await client.Administration.CreateAgentAsync(
    model: modelDeploymentName,
    name: "Wetter-Bot",
    instructions: "Du bist ein Wetter-Bot.",
    tools: [weatherTool]
);

// Funktionsaufrufe während des Pollings behandeln
do
{
    await Task.Delay(500);
    run = await client.Runs.GetRunAsync(thread.Id, run.Id);

    if (run.Status == RunStatus.RequiresAction 
        && run.RequiredAction is SubmitToolOutputsAction submitAction)
    {
        List<ToolOutput> outputs = [];
        foreach (RequiredToolCall toolCall in submitAction.ToolCalls)
        {
            if (toolCall is RequiredFunctionToolCall funcCall)
            {
                // Funktion ausführen und Ergebnis abrufen
                string result = ExecuteFunction(funcCall.Name, funcCall.Arguments);
                outputs.Add(new ToolOutput(toolCall, result));
            }
        }
        run = await client.Runs.SubmitToolOutputsToRunAsync(run, outputs, toolApprovals: null);
    }
}
while (run.Status == RunStatus.Queued || run.Status == RunStatus.InProgress);

6. Dateisuche mit Vektor-Store

// Datei hochladen
PersistentAgentFileInfo file = await client.Files.UploadFileAsync(
    filePath: "document.txt",
    purpose: PersistentAgentFilePurpose.Agents
);

// Vektor-Store erstellen
PersistentAgentsVectorStore vectorStore = await client.VectorStores.CreateVectorStoreAsync(
    fileIds: [file.Id],
    name: "mein_vektor_store"
);

// Dateisuchressource erstellen
FileSearchToolResource fileSearchResource = new();
fileSearchResource.VectorStoreIds.Add(vectorStore.Id);

// Agent mit Dateisuche erstellen
PersistentAgent agent = await client.Administration.CreateAgentAsync(
    model: modelDeploymentName,
    name: "Dokumenten-Assistent",
    instructions: "Du hilfst Benutzern, Informationen in Dokumenten zu finden.",
    tools: [new FileSearchToolDefinition()],
    toolResources: new ToolResources { FileSearch = fileSearchResource }
);

7. Bing Grounding

var bingConnectionId = Environment.GetEnvironmentVariable("AZURE_BING_CONNECTION_ID");

BingGroundingToolDefinition bingTool = new(
    new BingGroundingSearchToolParameters(
        [new BingGroundingSearchConfiguration(bingConnectionId)]
    )
);

PersistentAgent agent = await client.Administration.CreateAgentAsync(
    model: modelDeploymentName,
    name: "Such-Agent",
    instructions: "Verwende Bing, um Fragen zu aktuellen Ereignissen zu beantworten.",
    tools: [bingTool]
);

8. Azure AI Search

AzureAISearchToolResource searchResource = new(
    connectionId: searchConnectionId,
    indexName: "mein_index",
    topK: 5,
    filter: "category eq 'documentation'",
    queryType: AzureAISearchQueryType.Simple
);

PersistentAgent agent = await client.Administration.CreateAgentAsync(
    model: modelDeploymentName,
    name: "Such-Agent",
    instructions: "Durchsuche den Dokumentationsindex, um Fragen zu beantworten.",
    tools: [new AzureAISearchToolDefinition()],
    toolResources: new ToolResources { AzureAISearch = searchResource }
);

9. Bereinigung

await client.Threads.DeleteThreadAsync(thread.Id);
await client.Administration.DeleteAgentAsync(agent.Id);
await client.VectorStores.DeleteVectorStoreAsync(vectorStore.Id);
await client.Files.DeleteFileAsync(file.Id);

Verfügbare Werkzeuge

WerkzeugKlasseZweck
Code-InterpreterCodeInterpreterToolDefinitionPython-Code ausführen, Visualisierungen erstellen
DateisucheFileSearchToolDefinitionHochgeladene Dateien über Vektor-Stores durchsuchen
FunktionsaufrufeFunctionToolDefinitionBenutzerdefinierte Funktionen aufrufen
Bing GroundingBingGroundingToolDefinitionWebsuche über Bing
Azure AI SearchAzureAISearchToolDefinitionAzure AI Search-Indizes durchsuchen
OpenAPIOpenApiToolDefinitionExterne APIs über OpenAPI-Spezifikation aufrufen
Azure FunctionsAzureFunctionToolDefinitionAzure Functions aufrufen
MCPMCPToolDefinitionModel Context Protocol-Werkzeuge
SharePointSharepointToolDefinitionAuf SharePoint-Inhalte zugreifen
Microsoft FabricMicrosoftFabricToolDefinitionAuf Fabric-Daten zugreifen

Arten von Streaming-Updates

Update-TypBeschreibung
StreamingUpdateReason.RunCreatedAusführung gestartet
StreamingUpdateReason.RunInProgressAusführung läuft
StreamingUpdateReason.RunCompletedAusführung abgeschlossen
StreamingUpdateReason.RunFailedAusführung fehlgeschlagen
MessageContentUpdateTextinhalt-Abschnitt
RunStepUpdateStatusänderung des Schritts

Referenz wichtiger Typen

TypZweck
PersistentAgentsClientHaupteinstiegspunkt
PersistentAgentAgent mit Modell, Anweisungen, Werkzeugen
PersistentAgentThreadUnterhaltungsthread
PersistentThreadMessageNachricht in einem Thread
ThreadRunAusführung eines Agenten gegen einen Thread
RunStatusInWarteschlange, InBearbeitung, ErfordertAktion, Abgeschlossen, Fehlgeschlagen
ToolResourcesKombinierte Werkzeugressourcen
ToolOutputAntwort eines Funktionsaufrufs

Best Practices

  1. Clients immer entsorgen — using-Anweisungen oder explizite Entsorgung verwenden
  2. Mit angemessenen Verzögerungen abfragen — 500ms zwischen Statusabfragen empfohlen
  3. Ressourcen bereinigen — Threads und Agenten nach der Verwendung löschen
  4. Alle Ausführungsstatus behandeln — Auf RequiresAction, Failed, Cancelled prüfen
  5. Streaming für Echtzeit-Benutzererlebnis verwenden — Bessere Benutzererfahrung als Polling
  6. IDs, nicht Objekte speichern — Agenten/Threads über ID referenzieren
  7. Asynchrone Methoden verwenden — Alle Operationen sollten asynchron sein

Fehlerbehandlung

using Azure;

try
{
    var agent = await client.Administration.CreateAgentAsync(...);
}
catch (RequestFailedException ex) when (ex.Status == 404)
{
    Console.WriteLine("Ressource nicht gefunden");
}
catch (RequestFailedException ex)
{
    Console.WriteLine($"Fehler: {ex.Status} - {ex.ErrorCode}: {ex.Message}");
}

Verwandte SDKs

SDKZweckInstallationsbefehl
Azure.AI.Agents.PersistentLow-Level-Agenten (dieses SDK)dotnet add package Azure.AI.Agents.Persistent
Azure.AI.ProjectsHigh-Level-Projektclientdotnet add package Azure.AI.Projects

Referenzlinks

RessourceURL
NuGet-Pakethttps://www.nuget.org/packages/Azure.AI.Agents.Persistent
API-Referenzhttps://learn.microsoft.com/dotnet/api/azure.ai.agents.persistent
GitHub-Quellehttps://github.com/Azure/azure-sdk-for-net/tree/main/sdk/ai/Azure.AI.Agents.Persistent
Beispielehttps://github.com/Azure/azure-sdk-for-net/tree/main/sdk/ai/Azure.AI.Agents.Persistent/samples

Individual skills in this repo

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

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-openai-dotnet

Azure OpenAI SDK for .NET. Client library for Azure OpenAI and OpenAI services. Use for chat completions, embeddings, image generation, audio transcription, and assistants. Triggers: "Azure OpenAI", "AzureOpenAIClient", "ChatClient", "chat completions .NET", "GPT-4", "embeddings", "DALL-E", "Whisper", "OpenAI .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