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
dotnet add package Azure.AI.Projects.OpenAI --prerelease
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>
MODEL_DEPLOYMENT_NAME=gpt-4o-mini
CONNECTION_NAME=<votre-nom-connexion>
AI_SEARCH_CONNECTION_NAME=<connexion-ai-search>
AZURE_TOKEN_CREDENTIALS=prod
Authentification
using Azure.Identity;
using Azure.AI.Projects;
var endpoint = Environment.GetEnvironmentVariable("PROJECT_ENDPOINT");
var credential = new DefaultAzureCredential(
DefaultAzureCredential.DefaultEnvironmentVariableName
);
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
PersistentAgentsClient agentsClient = projectClient.GetPersistentAgentsClient();
PersistentAgent agent = await agentsClient.Administration.CreateAgentAsync(
model: "gpt-4o-mini",
name: "Professeur de maths",
instructions: "Vous êtes un professeur de maths personnel.");
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);
do
{
await Task.Delay(500);
run = await agentsClient.Runs.GetRunAsync(thread.Id, run.Id);
}
while (run.Status == RunStatus.Queued || run.Status == RunStatus.InProgress);
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);
}
}
await agentsClient.Threads.DeleteThreadAsync(thread.Id);
await agentsClient.Administration.DeleteAgentAsync(agent.Id);
2. Agents versionnés avec outils (Preview)
using Azure.AI.Projects.OpenAI;
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));
ProjectResponsesClient responseClient = projectClient.OpenAI.GetProjectResponsesClientForAgent(agentVersion.Name);
ResponseResult response = responseClient.CreateResponse("Quel temps fait-il à Seattle ?");
Console.WriteLine(response.GetOutputText());
projectClient.Agents.DeleteAgentVersion(agentName: agentVersion.Name, agentVersion: agentVersion.Version);
3. Connexions
foreach (AIProjectConnection connection in projectClient.Connections.GetConnections())
{
Console.WriteLine($"{connection.Name}: {connection.ConnectionType}");
}
AIProjectConnection conn = projectClient.Connections.GetConnection(
connectionName,
includeCredentials: true);
AIProjectConnection defaultConn = projectClient.Connections.GetDefaultConnection(
includeCredentials: false);
4. Déploiements
foreach (AIProjectDeployment deployment in projectClient.Deployments.GetDeployments())
{
Console.WriteLine($"{deployment.Name}: {deployment.ModelName}");
}
foreach (var deployment in projectClient.Deployments.GetDeployments(modelPublisher: "Microsoft"))
{
Console.WriteLine(deployment.Name);
}
ModelDeployment details = (ModelDeployment)projectClient.Deployments.GetDeployment("gpt-4o-mini");
5. Jeux de données
FileDataset fileDataset = projectClient.Datasets.UploadFile(
name: "mon-dataset",
version: "1.0",
filePath: "data/training.txt",
connectionName: connectionName);
FolderDataset folderDataset = projectClient.Datasets.UploadFolder(
name: "mon-dataset",
version: "2.0",
folderPath: "data/training",
connectionName: connectionName,
filePattern: new Regex(".*\\.txt"));
AIProjectDataset dataset = projectClient.Datasets.GetDataset("mon-dataset", "1.0");
projectClient.Datasets.Delete("mon-dataset", "1.0");
6. Index
AzureAISearchIndex searchIndex = new(aiSearchConnectionName, aiSearchIndexName)
{
Description = "Exemple d'index"
};
searchIndex = (AzureAISearchIndex)projectClient.Indexes.CreateOrUpdate(
name: "mon-index",
version: "1.0",
index: searchIndex);
foreach (AIProjectIndex index in projectClient.Indexes.GetIndexes())
{
Console.WriteLine(index.Name);
}
projectClient.Indexes.Delete(name: "mon-index", version: "1.0");
7. Évaluations
var evaluatorConfig = new EvaluatorConfiguration(id: EvaluatorIDs.Relevance);
evaluatorConfig.InitParams.Add("deployment_name", BinaryData.FromObjectAsJson("gpt-4o"));
Evaluation evaluation = new Evaluation(
data: new InputDataset("<dataset_id>"),
evaluators: new Dictionary<string, EvaluatorConfiguration>
{
{ "relevance", evaluatorConfig }
}
)
{
DisplayName = "Évaluation exemple"
};
Evaluation result = projectClient.Evaluations.Create(evaluation: evaluation);
Evaluation getResult = projectClient.Evaluations.Get(result.Name);
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
| Outil | Classe | Objectif |
|---|
| Interpréteur de code | CodeInterpreterToolDefinition | Exécuter du code Python |
| Recherche de fichiers | FileSearchToolDefinition | Rechercher dans les fichiers téléchargés |
| Appel de fonction | FunctionToolDefinition | Appeler des fonctions personnalisées |
| Ancrage Bing | BingGroundingToolDefinition | Recherche web via Bing |
| Recherche Azure AI | AzureAISearchToolDefinition | Rechercher dans les index Azure AI |
| OpenAPI | OpenApiToolDefinition | Appeler des API externes |
| Fonctions Azure | AzureFunctionToolDefinition | Invoquer des fonctions Azure |
| MCP | MCPToolDefinition | Outils du protocole de contexte de modèle |
Référence des types clés
| Type | Objectif |
|---|
AIProjectClient | Point d'entrée principal |
PersistentAgentsClient | Opérations agents de bas niveau |
PromptAgentDefinition | Définition d'agent versionné |
AgentVersion | Instance d'agent versionné |
AIProjectConnection | Connexion à une ressource Azure |
AIProjectDeployment | Informations de déploiement de modèle |
AIProjectDataset | Métadonnées de jeu de données |
AIProjectIndex | Métadonnées d'index de recherche |
Evaluation | Configuration et résultats d'évaluation |
Bonnes pratiques
- Utiliser
DefaultAzureCredential pour l'authentification en production
- Utiliser les méthodes asynchrones (
*Async) pour toutes les opérations I/O
- Interroger avec des délais appropriés (500ms recommandé) lors de l'attente d'exécutions
- Nettoyer les ressources — supprimer les threads, agents et fichiers une fois terminé
- Utiliser les agents versionnés (via
Azure.AI.Projects.OpenAI) pour les scénarios de production
- Stocker les IDs de connexion plutôt que les noms pour les configurations d'outils
- Utiliser
includeCredentials: true uniquement lorsque les informations d'identification sont nécessaires
- 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
| SDK | Objectif | Installation |
|---|
Azure.AI.Projects | Client de projet haut niveau (ce SDK) | dotnet add package Azure.AI.Projects |
Azure.AI.Agents.Persistent | Opérations agents de bas niveau | dotnet add package Azure.AI.Agents.Persistent |
Azure.AI.Projects.OpenAI | Agents versionnés avec OpenAI | dotnet add package Azure.AI.Projects.OpenAI |
Liens de référence