Azure.AI.Projects (.NET)
SDK haut niveau pour les opérations de projet Azure AI Foundry, incluant les agents, connexions, ensembles de données, déploiements, évaluations et index.
Installation
dotnet add package Azure.AI.Projects
dotnet add package Azure.Identity
# Optionnel : Pour les agents versionnés avec extensions OpenAI
dotnet add package Azure.AI.Projects.OpenAI --prerelease
# Optionnel : Pour les opérations bas niveau d'agents
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=<your-connection-name>
AI_SEARCH_CONNECTION_NAME=<ai-search-connection>
Authentification
using Azure.Identity;
using Azure.AI.Projects;
var endpoint = Environment.GetEnvironmentVariable("PROJECT_ENDPOINT");
AIProjectClient projectClient = new AIProjectClient(
new Uri(endpoint),
new DefaultAzureCredential());
Hiérarchie des clients
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
Flux de travail principaux
1. Obtenir le client Agents persistants
// Obtenir le client agents bas niveau depuis le client de projet
PersistentAgentsClient agentsClient = projectClient.GetPersistentAgentsClient();
// Créer un agent
PersistentAgent agent = await agentsClient.Administration.CreateAgentAsync(
model: "gpt-4o-mini",
name: "Math Tutor",
instructions: "You are a personal math tutor.");
// Créer un fil et une exécution
PersistentAgentThread thread = await agentsClient.Threads.CreateThreadAsync();
await agentsClient.Messages.CreateMessageAsync(thread.Id, MessageRole.User, "Solve 3x + 11 = 14");
ThreadRun run = await agentsClient.Runs.CreateRunAsync(thread.Id, agent.Id);
// Interroger l'achèvement
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 outil de recherche web
PromptAgentDefinition agentDefinition = new(model: "gpt-4o-mini")
{
Instructions = "You are a helpful assistant that can search the web",
Tools = {
ResponseTool.CreateWebSearchTool(
userLocation: WebSearchToolLocation.CreateApproximateLocation(
country: "US",
city: "Seattle",
region: "Washington"
)
),
}
};
AgentVersion agentVersion = await projectClient.Agents.CreateAgentVersionAsync(
agentName: "myAgent",
options: new(agentDefinition));
// Obtenir le client de réponses
ProjectResponsesClient responseClient = projectClient.OpenAI.GetProjectResponsesClientForAgent(agentVersion.Name);
// Créer une réponse
ResponseResult response = responseClient.CreateResponse("What's the weather in 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. Ensembles de données
// Télécharger un fichier unique
FileDataset fileDataset = projectClient.Datasets.UploadFile(
name: "my-dataset",
version: "1.0",
filePath: "data/training.txt",
connectionName: connectionName);
// Télécharger un dossier
FolderDataset folderDataset = projectClient.Datasets.UploadFolder(
name: "my-dataset",
version: "2.0",
folderPath: "data/training",
connectionName: connectionName,
filePattern: new Regex(".*\\.txt"));
// Obtenir un ensemble de données
AIProjectDataset dataset = projectClient.Datasets.GetDataset("my-dataset", "1.0");
// Supprimer un ensemble de données
projectClient.Datasets.Delete("my-dataset", "1.0");
6. Index
// Créer un index Azure AI Search
AzureAISearchIndex searchIndex = new(aiSearchConnectionName, aiSearchIndexName)
{
Description = "Sample Index"
};
searchIndex = (AzureAISearchIndex)projectClient.Indexes.CreateOrUpdate(
name: "my-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: "my-index", version: "1.0");
7. Évaluations
// Créer une configuration d'évaluateur
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 = "Sample Evaluation"
};
// 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 Azure OpenAI Chat
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("Invalid URI.");
uri = new Uri($"https://{uri.Host}");
AzureOpenAIClient azureOpenAIClient = new AzureOpenAIClient(uri, new DefaultAzureCredential());
ChatClient chatClient = azureOpenAIClient.GetChatClient("gpt-4o-mini");
ChatCompletion result = chatClient.CompleteChat("List all rainbow colors");
Console.WriteLine(result.Content[0].Text);
Outils d'agent disponibles
| Outil |
Classe |
Objectif |
| Code Interpreter |
CodeInterpreterToolDefinition |
Exécuter du code Python |
| File Search |
FileSearchToolDefinition |
Rechercher dans les fichiers téléchargés |
| Function Calling |
FunctionToolDefinition |
Appeler des fonctions personnalisées |
| Bing Grounding |
BingGroundingToolDefinition |
Recherche web via Bing |
| Azure AI Search |
AzureAISearchToolDefinition |
Rechercher dans les index Azure AI |
| OpenAPI |
OpenApiToolDefinition |
Appeler des API externes |
| Azure Functions |
AzureFunctionToolDefinition |
Invoquer Azure Functions |
| MCP |
MCPToolDefinition |
Outils Model Context Protocol |
Référence des types clés
| Type |
Objectif |
AIProjectClient |
Point d'entrée principal |
PersistentAgentsClient |
Opérations agents 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 d'ensemble 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 d'E/S
- Interroger avec des délais appropriés (500 ms recommandé) lors de l'attente d'exécutions
- Nettoyer les ressources — supprimer les fils, agents et fichiers après utilisation
- Utiliser les agents versionnés (via
Azure.AI.Projects.OpenAI) pour les scénarios de production
- Stocker les ID de connexion plutôt que les noms pour les configurations d'outils
- Utiliser
includeCredentials: true uniquement quand les credentials sont nécessaires
- Gérer la pagination — utiliser
AsyncPageable<T> pour les opérations de listing
Gestion des erreurs
using Azure;
try
{
var result = await projectClient.Evaluations.CreateAsync(evaluation);
}
catch (RequestFailedException ex)
{
Console.WriteLine($"Error: {ex.Status} - {ex.ErrorCode}: {ex.Message}");
}
SDK connexes
| 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 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