CommunityRédaction et éditiongithub.com

microsoft/azure-ai-agents-persistent-dotnet

SDK bas niveau .NET pour créer et gérer des agents d'IA persistants avec threads, messages, exécutions et outils. Idéal pour le CRUD d'agents, les threads de conversation, les réponses en streaming, l'appel de fonctions, la recherche de fichiers et l'interpréteur de code.

Qu'est-ce que azure-ai-agents-persistent-dotnet ?

Azure.AI.Agents.Persistent pour .NET est un SDK bas niveau permettant de créer et gérer des agents d'IA persistants avec des threads de conversation, des messages, des exécutions et divers outils. Il est idéal pour les développeurs .NET qui souhaitent implémenter des flux d'IA conversationnelle complexes, avec prise en charge du polling et du streaming pour les réponses en temps réel. Le SDK prend en charge l'appel de fonctions (function calling) pour intégrer des logiques métier, la recherche de fichiers avec des vector stores, l'interpréteur de code pour exécuter du code Python, la recherche Bing (grounding) et Azure AI Search. Il fonctionne avec les agents d'IA Azure et peut être utilisé avec différents types de credentials Azure (DefaultAzureCredential, ManagedIdentityCredential, etc.). Les points d'entrée principaux sont les clients `PersistentAgentsClient`, les threads `PersistentAgentThread`, les messages `PersistentThreadMessage`, les exécutions `ThreadRun` et les outils comme `CodeInterpreterToolDefinition`, `FileSearchToolDefinition`, `FunctionToolDefinition`, `BingGroundingToolDefinition` et `AzureAISearchToolDefinition.`

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

Installed? Explore more Rédaction et édition skills: steipete/notion, langchain-ai/langchain, bytedance/podcast-generation · 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.Agents.Persistent (.NET)

SDK bas niveau pour créer et gérer des agents d'IA persistants avec threads, messages, exécutions et outils.

Installation

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

Versions actuelles : Stable v1.1.0, Preview v1.2.0-beta.8

Variables d'environnement

PROJECT_ENDPOINT=https://<resource>.services.ai.azure.com/api/projects/<project>  # Requis : point de terminaison du projet Azure AI
MODEL_DEPLOYMENT_NAME=gpt-4o-mini  # Requis : nom du déploiement du modèle
AZURE_BING_CONNECTION_ID=<bing-connection-resource-id>  # Requis : ID de ressource de connexion Bing
AZURE_AI_SEARCH_CONNECTION_ID=<search-connection-resource-id>  # Requis : ID de ressource de connexion Azure AI Search
AZURE_TOKEN_CREDENTIALS=prod  # Requis uniquement si DefaultAzureCredential est utilisé en production

Authentification

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

var projectEndpoint = Environment.GetEnvironmentVariable("PROJECT_ENDPOINT");
// 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 un credential spécifique directement en production :
// Voir https://learn.microsoft.com/dotnet/api/overview/azure/identity-readme?view=azure-dotnet#credential-classes
// var credential = new ManagedIdentityCredential();
PersistentAgentsClient client = new(projectEndpoint, credential);

Hiérarchie du client

PersistentAgentsClient
├── Administration  → Opérations CRUD sur les agents
├── Threads         → Gestion des threads
├── Messages        → Opérations sur les messages
├── Runs            → Exécution des runs et streaming
├── Files           → Upload/téléchargement de fichiers
└── VectorStores    → Gestion des vector stores

Flux de travail principal

1. Créer un agent

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

PersistentAgent agent = await client.Administration.CreateAgentAsync(
    model: modelDeploymentName,
    name: "Tuteur de maths",
    instructions: "Tu es un tuteur personnel de mathématiques. Écris et exécute du code pour répondre aux questions de maths.",
    tools: [new CodeInterpreterToolDefinition()]
);

2. Créer un thread et un message

// Créer un thread
PersistentAgentThread thread = await client.Threads.CreateThreadAsync();

// Créer un message
await client.Messages.CreateMessageAsync(
    thread.Id,
    MessageRole.User,
    "J'ai besoin de résoudre l'équation `3x + 11 = 14`. Peux-tu m'aider ?"
);

3. Exécuter l'agent (par polling)

// Créer une exécution
ThreadRun run = await client.Runs.CreateRunAsync(
    thread.Id,
    agent.Id,
    additionalInstructions: "Veuillez vous adresser à l'utilisateur en tant que Jane Doe."
);

// Interroger jusqu'à la fin
while (run.Status == RunStatus.Queued || run.Status == RunStatus.InProgress)
{
    await Task.Delay(TimeSpan.FromMilliseconds(500));
    run = await client.Runs.GetRunAsync(thread.Id, run.Id);
}

// Récupérer les messages
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. Réponse en streaming

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

await foreach (StreamingUpdate update in stream)
{
    if (update.UpdateKind == StreamingUpdateReason.RunCreated)
    {
        Console.WriteLine("--- Exécution démarrée ! ---");
    }
    else if (update is MessageContentUpdate contentUpdate)
    {
        Console.Write(contentUpdate.Text);
    }
    else if (update.UpdateKind == StreamingUpdateReason.RunCompleted)
    {
        Console.WriteLine("\n--- Exécution terminée ! ---");
    }
}

5. Appel de fonctions (Function Calling)

// Définir un outil de fonction
FunctionToolDefinition weatherTool = new(
    name: "getCurrentWeather",
    description: "Obtient la météo actuelle à un endroit donné.",
    parameters: BinaryData.FromObjectAsJson(new
    {
        Type = "object",
        Properties = new
        {
            Location = new { Type = "string", Description = "Ville et état, ex. San Francisco, CA" },
            Unit = new { Type = "string", Enum = new[] { "c", "f" } }
        },
        Required = new[] { "location" }
    }, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase })
);

// Créer un agent avec la fonction
PersistentAgent agent = await client.Administration.CreateAgentAsync(
    model: modelDeploymentName,
    name: "Bot météo",
    instructions: "Tu es un bot météo.",
    tools: [weatherTool]
);

// Gérer les appels de fonction pendant le polling
while (run.Status == RunStatus.Queued || run.Status == RunStatus.InProgress)
{
    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)
            {
                // Exécuter la fonction et obtenir le résultat
                string result = ExecuteFunction(funcCall.Name, funcCall.Arguments);
                outputs.Add(new ToolOutput(toolCall, result));
            }
        }
        run = await client.Runs.SubmitToolOutputsToRunAsync(run, outputs, toolApprovals: null);
    }
}

6. Recherche de fichiers avec Vector Store

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

// Créer un vector store
PersistentAgentsVectorStore vectorStore = await client.VectorStores.CreateVectorStoreAsync(
    fileIds: [file.Id],
    name: "mon_vector_store"
);

// Créer une ressource de recherche de fichiers
FileSearchToolResource fileSearchResource = new();
fileSearchResource.VectorStoreIds.Add(vectorStore.Id);

// Créer un agent avec recherche de fichiers
PersistentAgent agent = await client.Administration.CreateAgentAsync(
    model: modelDeploymentName,
    name: "Assistant documentaire",
    instructions: "Tu aides les utilisateurs à trouver des informations dans les documents.",
    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: "Agent de recherche",
    instructions: "Utilise Bing pour répondre aux questions sur l'actualité.",
    tools: [bingTool]
);

8. Azure AI Search

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

PersistentAgent agent = await client.Administration.CreateAgentAsync(
    model: modelDeploymentName,
    name: "Agent de recherche",
    instructions: "Cherche dans l'index de documentation pour répondre aux questions.",
    tools: [new AzureAISearchToolDefinition()],
    toolResources: new ToolResources { AzureAISearch = searchResource }
);

9. Nettoyage

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

Outils disponibles

OutilClasseObjectif
Interpréteur de codeCodeInterpreterToolDefinitionExécuter du code Python, générer des visualisations
Recherche de fichiersFileSearchToolDefinitionRechercher dans les fichiers uploadés via des vector stores
Appel de fonctionsFunctionToolDefinitionAppeler des fonctions personnalisées
Bing GroundingBingGroundingToolDefinitionRecherche web via Bing
Azure AI SearchAzureAISearchToolDefinitionRechercher dans les index Azure AI Search
OpenAPIOpenApiToolDefinitionAppeler des API externes via une spécification OpenAPI
Azure FunctionsAzureFunctionToolDefinitionInvoquer des Azure Functions
MCPMCPToolDefinitionOutils du protocole de contexte de modèle (Model Context Protocol)
SharePointSharepointToolDefinitionAccéder au contenu SharePoint
Microsoft FabricMicrosoftFabricToolDefinitionAccéder aux données Fabric

Types de mises à jour en streaming

Type de mise à jourDescription
StreamingUpdateReason.RunCreatedExécution démarrée
StreamingUpdateReason.RunInProgressExécution en cours
StreamingUpdateReason.RunCompletedExécution terminée
StreamingUpdateReason.RunFailedExécution en erreur
MessageContentUpdateMorceau de contenu texte
RunStepUpdateChangement d'état d'une étape

Référence des types clés

TypeObjectif
PersistentAgentsClientPoint d'entrée principal
PersistentAgentAgent avec modèle, instructions, outils
PersistentAgentThreadThread de conversation
PersistentThreadMessageMessage dans un thread
ThreadRunExécution d'un agent sur un thread
RunStatusEn file d'attente, En cours, Action requise, Terminé, Échoué
ToolResourcesRessources d'outils combinées
ToolOutputRéponse d'appel de fonction

Bonnes pratiques

  1. Toujours libérer les clients — Utiliser des instructions using ou un libéré explicite
  2. Interroger avec des délais appropriés — 500ms recommandé entre les vérifications d'état
  3. Nettoyer les ressources — Supprimer les threads et les agents après utilisation
  4. Gérer tous les statuts d'exécution — Vérifier RequiresAction, Failed, Cancelled
  5. Utiliser le streaming pour une UX en temps réel — Meilleure expérience utilisateur que le polling
  6. Stocker les ID, pas les objets — Référencer les agents/threads par leur ID
  7. Utiliser les méthodes asynchrones — Toutes les opérations doivent être async

Gestion des erreurs

using Azure;

try
{
    var agent = await client.Administration.CreateAgentAsync(...);
}
catch (RequestFailedException ex) when (ex.Status == 404)
{
    Console.WriteLine("Ressource non trouvée");
}
catch (RequestFailedException ex)
{
    Console.WriteLine($"Erreur : {ex.Status} - {ex.ErrorCode}: {ex.Message}");
}

SDK associés

SDKObjectifInstallation
Azure.AI.Agents.PersistentAgents bas niveau (ce SDK)dotnet add package Azure.AI.Agents.Persistent
Azure.AI.ProjectsClient projet haut niveaudotnet add package Azure.AI.Projects

Liens de référence

RessourceURL
Package NuGethttps://www.nuget.org/packages/Azure.AI.Agents.Persistent
Référence APIhttps://learn.microsoft.com/dotnet/api/azure.ai.agents.persistent
Source GitHubhttps://github.com/Azure/azure-sdk-for-net/tree/main/sdk/ai/Azure.AI.Agents.Persistent
Exempleshttps://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.

Skills associés