Azure.AI.Projects (.NET)
Hochrangiges SDK für Azure AI Foundry-Projektvorgänge einschließlich Agents, Verbindungen, Datasets, Deployments, Evaluierungen und Indizes.
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
Aktuelle Versionen: GA v1.1.0, Preview v1.2.0-beta.5
Umgebungsvariablen
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>
AZURE_TOKEN_CREDENTIALS=prod
Authentifizierung
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);
Client-Hierarchie
AIProjectClient
├── Agents → AIProjectAgentsOperations (versionierte Agents)
├── Connections → ConnectionsClient
├── Datasets → DatasetsClient
├── Deployments → DeploymentsClient
├── Evaluations → EvaluationsClient
├── Evaluators → EvaluatorsClient
├── Indexes → IndexesClient
├── Telemetry → AIProjectTelemetry
├── OpenAI → ProjectOpenAIClient (Preview)
└── GetPersistentAgentsClient() → PersistentAgentsClient
Kernworkflows
1. Persistent Agents Client abrufen
PersistentAgentsClient agentsClient = projectClient.GetPersistentAgentsClient();
PersistentAgent agent = await agentsClient.Administration.CreateAgentAsync(
model: "gpt-4o-mini",
name: "Mathe-Tutor",
instructions: "Du bist ein persönlicher Mathe-Tutor.");
PersistentAgentThread thread = await agentsClient.Threads.CreateThreadAsync();
await agentsClient.Messages.CreateMessageAsync(thread.Id, MessageRole.User, "Löse 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. Versionierte Agents mit Tools (Preview)
using Azure.AI.Projects.OpenAI;
PromptAgentDefinition agentDefinition = new(model: "gpt-4o-mini")
{
Instructions = "Du bist ein hilfreicher Assistent, der das Web durchsuchen kann",
Tools = {
ResponseTool.CreateWebSearchTool(
userLocation: WebSearchToolLocation.CreateApproximateLocation(
country: "US",
city: "Seattle",
region: "Washington"
)
),
}
};
AgentVersion agentVersion = await projectClient.Agents.CreateAgentVersionAsync(
agentName: "myAgent",
options: new(agentDefinition));
ProjectResponsesClient responseClient = projectClient.OpenAI.GetProjectResponsesClientForAgent(agentVersion.Name);
ResponseResult response = responseClient.CreateResponse("Wie ist das Wetter in Seattle?");
Console.WriteLine(response.GetOutputText());
projectClient.Agents.DeleteAgentVersion(agentName: agentVersion.Name, agentVersion: agentVersion.Version);
3. Verbindungen
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. Deployments
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. Datasets
FileDataset fileDataset = projectClient.Datasets.UploadFile(
name: "mein-dataset",
version: "1.0",
filePath: "data/training.txt",
connectionName: connectionName);
FolderDataset folderDataset = projectClient.Datasets.UploadFolder(
name: "mein-dataset",
version: "2.0",
folderPath: "data/training",
connectionName: connectionName,
filePattern: new Regex(".*\\.txt"));
AIProjectDataset dataset = projectClient.Datasets.GetDataset("mein-dataset", "1.0");
projectClient.Datasets.Delete("mein-dataset", "1.0");
6. Indizes
AzureAISearchIndex searchIndex = new(aiSearchConnectionName, aiSearchIndexName)
{
Description = "Beispielindex"
};
searchIndex = (AzureAISearchIndex)projectClient.Indexes.CreateOrUpdate(
name: "mein-index",
version: "1.0",
index: searchIndex);
foreach (AIProjectIndex index in projectClient.Indexes.GetIndexes())
{
Console.WriteLine(index.Name);
}
projectClient.Indexes.Delete(name: "mein-index", version: "1.0");
7. Evaluierungen
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 = "Beispiel-Evaluierung"
};
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. Azure OpenAI Chat-Client abrufen
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("Ungültige 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("Liste alle Regenbogenfarben auf");
Console.WriteLine(result.Content[0].Text);
Verfügbare Agent-Tools
| Tool | Klasse | Zweck |
|---|
| Code Interpreter | CodeInterpreterToolDefinition | Python-Code ausführen |
| File Search | FileSearchToolDefinition | Hochgeladene Dateien durchsuchen |
| Function Calling | FunctionToolDefinition | Benutzerdefinierte Funktionen aufrufen |
| Bing Grounding | BingGroundingToolDefinition | Websuche über Bing |
| Azure AI Search | AzureAISearchToolDefinition | Azure AI-Indizes durchsuchen |
| OpenAPI | OpenApiToolDefinition | Externe APIs aufrufen |
| Azure Functions | AzureFunctionToolDefinition | Azure Functions aufrufen |
| MCP | MCPToolDefinition | Model Context Protocol-Tools |
Referenz der wichtigsten Typen
| Typ | Zweck |
|---|
AIProjectClient | Haupteinstiegspunkt |
PersistentAgentsClient | Low-Level-Agent-Operationen |
PromptAgentDefinition | Definition versionierter Agenten |
AgentVersion | Instanz eines versionierten Agenten |
AIProjectConnection | Verbindung zu einer Azure-Ressource |
AIProjectDeployment | Modell-Deployment-Informationen |
AIProjectDataset | Dataset-Metadaten |
AIProjectIndex | Suchindex-Metadaten |
Evaluation | Evaluierungskonfiguration und -ergebnisse |
Best Practices
- Verwende
DefaultAzureCredential für die Authentifizierung in der Produktion
- Verwende asynchrone Methoden (
*Async) für alle I/O-Operationen
- Führe Polling mit angemessenen Verzögerungen (500ms empfohlen) beim Warten auf Runs durch
- Räume Ressourcen auf — lösche Threads, Agents und Dateien nach der Nutzung
- Verwende versionierte Agents (über
Azure.AI.Projects.OpenAI) für Produktionsszenarien
- Speichere Verbindungs-IDs anstelle von Namen für Tool-Konfigurationen
- Verwende
includeCredentials: true nur, wenn Anmeldeinformationen benötigt werden
- Behandle Paginierung — verwende
AsyncPageable<T> für Auflistungsoperationen
Fehlerbehandlung
using Azure;
try
{
var result = await projectClient.Evaluations.CreateAsync(evaluation);
}
catch (RequestFailedException ex)
{
Console.WriteLine($"Fehler: {ex.Status} - {ex.ErrorCode}: {ex.Message}");
}
Verwandte SDKs
| SDK | Zweck | Installation |
|---|
Azure.AI.Projects | Hochrangiger Projekt-Client (dieses SDK) | dotnet add package Azure.AI.Projects |
Azure.AI.Agents.Persistent | Low-Level-Agent-Operationen | dotnet add package Azure.AI.Agents.Persistent |
Azure.AI.Projects.OpenAI | Versionierte Agents mit OpenAI | dotnet add package Azure.AI.Projects.OpenAI |
Referenzlinks