CommunityRédaction et éditiongithub.com

microsoft/azure-ai-projects-dotnet

SDK Azure AI Projects pour .NET. Client haut niveau pour les projets Azure AI Foundry, incluant les agents, connexions, jeux de données, déploiements, évaluations et index. Utilisé pour la gestion de projets Foundry, les agents versionnés et l'orchestration. Déclencheurs : "AI Projects", "AIProjectClient", "Foundry project", "versioned agents", "evaluations", "datasets", "connections", "deployments .NET".

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

Ce SDK .NET de haut niveau permet d'interagir avec les projets Azure AI Foundry. Il offre une interface unifiée pour gérer les agents (versionnés ou persistants), les connexions aux ressources Azure, les jeux de données, les déploiements de modèles, les évaluations et les index de recherche. Le client principal `AIProjectClient` expose des sous-clients spécialisés (`Agents`, `Connections`, `Datasets`, `Deployments`, `Evaluations`, `Indexes`) ainsi qu'un accès aux fonctionnalités OpenAI en prévisualisation et aux agents persistants de bas niveau. Les workflows typiques incluent la création et l'exécution d'agents avec outils (recherche web, interpréteur de code, appels de fonction), la gestion des connexions et déploiements, le téléchargement de jeux de données, la création d'index de recherche Azure AI et le lancement d'évaluations. Le SDK prend en charge l'authentification via `DefaultAzureCredential` et les méthodes asynchrones pour toutes les opérations I/O. Il est disponible sur NuGet sous les packages `Azure.AI.Projects`, `Azure.AI.Agents.Persistent` et `Azure.AI.Projects.OpenAI`.

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-projects-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.Projects (.NET)

SDK haut niveau pour les opérations sur les projets Azure AI Foundry, incluant les agents, connexions, jeux de données, déploiements, évaluations et index.

Installation

dotnet add package Azure.AI.Projects
dotnet add package Azure.Identity

# Facultatif : pour les agents versionnés avec les extensions OpenAI
dotnet add package Azure.AI.Projects.OpenAI --prerelease

# Facultatif : pour les opérations agents de bas niveau
dotnet add package Azure.AI.Agents.Persistent --prerelease

Versions actuelles : GA v1.1.0, Preview v1.2.0-beta.5

Variables d'environnement

PROJECT_ENDPOINT=https://<resource>.services.ai.azure.com/api/projects/<project>  # Obligatoire : point de terminaison du projet Azure AI
MODEL_DEPLOYMENT_NAME=gpt-4o-mini  # Obligatoire : nom du déploiement du modèle
CONNECTION_NAME=<votre-nom-connexion>  # Facultatif : nom de connexion du projet
AI_SEARCH_CONNECTION_NAME=<connexion-ai-search>  # Facultatif : nom de connexion Azure AI Search
AZURE_TOKEN_CREDENTIALS=prod  # Obligatoire uniquement si DefaultAzureCredential est utilisé en production

Authentification

using Azure.Identity;
using Azure.AI.Projects;

var endpoint = 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();
AIProjectClient projectClient = new AIProjectClient(
    new Uri(endpoint), 
    credential);

Hiérarchie du client

AIProjectClient
├── Agents          → AIProjectAgentsOperations (agents versionnés)
├── Connections     → ConnectionsClient
├── Datasets        → DatasetsClient
├── Deployments     → DeploymentsClient
├── Evaluations     → EvaluationsClient
├── Evaluators      → EvaluatorsClient
├── Indexes         → IndexesClient
├── Telemetry       → AIProjectTelemetry
├── OpenAI          → ProjectOpenAIClient (preview)
└── GetPersistentAgentsClient() → PersistentAgentsClient

Workflows principaux

1. Obtenir le client d'agents persistants

// Obtenir le client agents de bas niveau à partir du client de projet
PersistentAgentsClient agentsClient = projectClient.GetPersistentAgentsClient();

// Créer un agent
PersistentAgent agent = await agentsClient.Administration.CreateAgentAsync(
    model: "gpt-4o-mini",
    name: "Professeur de maths",
    instructions: "Vous êtes un professeur de maths personnel.");

// Créer un thread et exécuter
PersistentAgentThread thread = await agentsClient.Threads.CreateThreadAsync();
await agentsClient.Messages.CreateMessageAsync(thread.Id, MessageRole.User, "Résoudre 3x + 11 = 14");
ThreadRun run = await agentsClient.Runs.CreateRunAsync(thread.Id, agent.Id);

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

// Obtenir les messages
await foreach (var msg in agentsClient.Messages.GetMessagesAsync(thread.Id))
{
    foreach (var content in msg.ContentItems)
    {
        if (content is MessageTextContent textContent)
            Console.WriteLine(textContent.Text);
    }
}

// Nettoyage
await agentsClient.Threads.DeleteThreadAsync(thread.Id);
await agentsClient.Administration.DeleteAgentAsync(agent.Id);

2. Agents versionnés avec outils (Preview)

using Azure.AI.Projects.OpenAI;

// Créer un agent avec un outil de recherche web
PromptAgentDefinition agentDefinition = new(model: "gpt-4o-mini")
{
    Instructions = "Vous êtes un assistant utile capable de rechercher sur le web",
    Tools = {
        ResponseTool.CreateWebSearchTool(
            userLocation: WebSearchToolLocation.CreateApproximateLocation(
                country: "US",
                city: "Seattle",
                region: "Washington"
            )
        ),
    }
};

AgentVersion agentVersion = await projectClient.Agents.CreateAgentVersionAsync(
    agentName: "monAgent",
    options: new(agentDefinition));

// Obtenir le client de réponse
ProjectResponsesClient responseClient = projectClient.OpenAI.GetProjectResponsesClientForAgent(agentVersion.Name);

// Créer une réponse
ResponseResult response = responseClient.CreateResponse("Quel temps fait-il à Seattle ?");
Console.WriteLine(response.GetOutputText());

// Nettoyage
projectClient.Agents.DeleteAgentVersion(agentName: agentVersion.Name, agentVersion: agentVersion.Version);

3. Connexions

// Lister toutes les connexions
foreach (AIProjectConnection connection in projectClient.Connections.GetConnections())
{
    Console.WriteLine($"{connection.Name}: {connection.ConnectionType}");
}

// Obtenir une connexion spécifique
AIProjectConnection conn = projectClient.Connections.GetConnection(
    connectionName, 
    includeCredentials: true);

// Obtenir la connexion par défaut
AIProjectConnection defaultConn = projectClient.Connections.GetDefaultConnection(
    includeCredentials: false);

4. Déploiements

// Lister tous les déploiements
foreach (AIProjectDeployment deployment in projectClient.Deployments.GetDeployments())
{
    Console.WriteLine($"{deployment.Name}: {deployment.ModelName}");
}

// Filtrer par éditeur
foreach (var deployment in projectClient.Deployments.GetDeployments(modelPublisher: "Microsoft"))
{
    Console.WriteLine(deployment.Name);
}

// Obtenir un déploiement spécifique
ModelDeployment details = (ModelDeployment)projectClient.Deployments.GetDeployment("gpt-4o-mini");

5. Jeux de données

// Télécharger un fichier unique
FileDataset fileDataset = projectClient.Datasets.UploadFile(
    name: "mon-dataset",
    version: "1.0",
    filePath: "data/training.txt",
    connectionName: connectionName);

// Télécharger un dossier
FolderDataset folderDataset = projectClient.Datasets.UploadFolder(
    name: "mon-dataset",
    version: "2.0",
    folderPath: "data/training",
    connectionName: connectionName,
    filePattern: new Regex(".*\\.txt"));

// Obtenir un jeu de données
AIProjectDataset dataset = projectClient.Datasets.GetDataset("mon-dataset", "1.0");

// Supprimer un jeu de données
projectClient.Datasets.Delete("mon-dataset", "1.0");

6. Index

// Créer un index Azure AI Search
AzureAISearchIndex searchIndex = new(aiSearchConnectionName, aiSearchIndexName)
{
    Description = "Exemple d'index"
};

searchIndex = (AzureAISearchIndex)projectClient.Indexes.CreateOrUpdate(
    name: "mon-index",
    version: "1.0",
    index: searchIndex);

// Lister les index
foreach (AIProjectIndex index in projectClient.Indexes.GetIndexes())
{
    Console.WriteLine(index.Name);
}

// Supprimer un index
projectClient.Indexes.Delete(name: "mon-index", version: "1.0");

7. Évaluations

// Créer une configuration d'évaluation
var evaluatorConfig = new EvaluatorConfiguration(id: EvaluatorIDs.Relevance);
evaluatorConfig.InitParams.Add("deployment_name", BinaryData.FromObjectAsJson("gpt-4o"));

// Créer une évaluation
Evaluation evaluation = new Evaluation(
    data: new InputDataset("<dataset_id>"),
    evaluators: new Dictionary<string, EvaluatorConfiguration> 
    { 
        { "relevance", evaluatorConfig } 
    }
)
{
    DisplayName = "Évaluation exemple"
};

// Exécuter l'évaluation
Evaluation result = projectClient.Evaluations.Create(evaluation: evaluation);

// Obtenir l'évaluation
Evaluation getResult = projectClient.Evaluations.Get(result.Name);

// Lister les évaluations
foreach (var eval in projectClient.Evaluations.GetAll())
{
    Console.WriteLine($"{eval.DisplayName}: {eval.Status}");
}

8. Obtenir le client de chat Azure OpenAI

using Azure.AI.OpenAI;
using OpenAI.Chat;

ClientConnection connection = projectClient.GetConnection(typeof(AzureOpenAIClient).FullName!);

if (!connection.TryGetLocatorAsUri(out Uri uri) || uri is null)
    throw new InvalidOperationException("URI invalide.");

uri = new Uri($"https://{uri.Host}");

AzureOpenAIClient azureOpenAIClient = new AzureOpenAIClient(uri, new DefaultAzureCredential());
ChatClient chatClient = azureOpenAIClient.GetChatClient("gpt-4o-mini");

ChatCompletion result = chatClient.CompleteChat("Lister toutes les couleurs de l'arc-en-ciel");
Console.WriteLine(result.Content[0].Text);

Outils d'agent disponibles

OutilClasseObjectif
Interpréteur de codeCodeInterpreterToolDefinitionExécuter du code Python
Recherche de fichiersFileSearchToolDefinitionRechercher dans les fichiers téléchargés
Appel de fonctionFunctionToolDefinitionAppeler des fonctions personnalisées
Ancrage BingBingGroundingToolDefinitionRecherche web via Bing
Recherche Azure AIAzureAISearchToolDefinitionRechercher dans les index Azure AI
OpenAPIOpenApiToolDefinitionAppeler des API externes
Fonctions AzureAzureFunctionToolDefinitionInvoquer des fonctions Azure
MCPMCPToolDefinitionOutils du protocole de contexte de modèle

Référence des types clés

TypeObjectif
AIProjectClientPoint d'entrée principal
PersistentAgentsClientOpérations agents de bas niveau
PromptAgentDefinitionDéfinition d'agent versionné
AgentVersionInstance d'agent versionné
AIProjectConnectionConnexion à une ressource Azure
AIProjectDeploymentInformations de déploiement de modèle
AIProjectDatasetMétadonnées de jeu de données
AIProjectIndexMétadonnées d'index de recherche
EvaluationConfiguration et résultats d'évaluation

Bonnes pratiques

  1. Utiliser DefaultAzureCredential pour l'authentification en production
  2. Utiliser les méthodes asynchrones (*Async) pour toutes les opérations I/O
  3. Interroger avec des délais appropriés (500ms recommandé) lors de l'attente d'exécutions
  4. Nettoyer les ressources — supprimer les threads, agents et fichiers une fois terminé
  5. Utiliser les agents versionnés (via Azure.AI.Projects.OpenAI) pour les scénarios de production
  6. Stocker les IDs de connexion plutôt que les noms pour les configurations d'outils
  7. Utiliser includeCredentials: true uniquement lorsque les informations d'identification sont nécessaires
  8. Gérer la pagination — utiliser AsyncPageable<T> pour les opérations de listage

Gestion des erreurs

using Azure;

try
{
    var result = await projectClient.Evaluations.CreateAsync(evaluation);
}
catch (RequestFailedException ex)
{
    Console.WriteLine($"Erreur : {ex.Status} - {ex.ErrorCode}: {ex.Message}");
}

SDK associés

SDKObjectifInstallation
Azure.AI.ProjectsClient de projet haut niveau (ce SDK)dotnet add package Azure.AI.Projects
Azure.AI.Agents.PersistentOpérations agents de bas niveaudotnet add package Azure.AI.Agents.Persistent
Azure.AI.Projects.OpenAIAgents versionnés avec OpenAIdotnet add package Azure.AI.Projects.OpenAI

Liens de référence

RessourceURL
Package NuGethttps://www.nuget.org/packages/Azure.AI.Projects
Référence APIhttps://learn.microsoft.com/dotnet/api/azure.ai.projects
Source GitHubhttps://github.com/Azure/azure-sdk-for-net/tree/main/sdk/ai/Azure.AI.Projects
Exempleshttps://github.com/Azure/azure-sdk-for-net/tree/main/sdk/ai/Azure.AI.Projects/samples

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