azure-ai-projects-dotnet

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Azure.AI.Projects (.NET)

Azure.AI.Projects(.NET)

High-level SDK for Azure AI Foundry project operations including agents, connections, datasets, deployments, evaluations, and indexes.
用于Azure AI Foundry项目操作的高级SDK,涵盖agents、connections、datasets、deployments、evaluations和indexes。

Installation

安装

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

Optional: For versioned agents with OpenAI extensions

可选:用于带OpenAI扩展的版本化agents

dotnet add package Azure.AI.Projects.OpenAI --prerelease
dotnet add package Azure.AI.Projects.OpenAI --prerelease

Optional: For low-level agent operations

可选:用于低级别agent操作

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

**Current Versions**: GA v1.1.0, Preview v1.2.0-beta.5
dotnet add package Azure.AI.Agents.Persistent --prerelease

**当前版本**:正式版(GA)v1.1.0,预览版v1.2.0-beta.5

Environment Variables

环境变量

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

Authentication

认证

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

var endpoint = Environment.GetEnvironmentVariable("PROJECT_ENDPOINT");
AIProjectClient projectClient = new AIProjectClient(
    new Uri(endpoint), 
    new DefaultAzureCredential());
csharp
using Azure.Identity;
using Azure.AI.Projects;

var endpoint = Environment.GetEnvironmentVariable("PROJECT_ENDPOINT");
AIProjectClient projectClient = new AIProjectClient(
    new Uri(endpoint), 
    new DefaultAzureCredential());

Client Hierarchy

客户端层级

AIProjectClient
├── Agents          → AIProjectAgentsOperations (versioned agents)
├── Connections     → ConnectionsClient
├── Datasets        → DatasetsClient
├── Deployments     → DeploymentsClient
├── Evaluations     → EvaluationsClient
├── Evaluators      → EvaluatorsClient
├── Indexes         → IndexesClient
├── Telemetry       → AIProjectTelemetry
├── OpenAI          → ProjectOpenAIClient (preview)
└── GetPersistentAgentsClient() → PersistentAgentsClient
AIProjectClient
├── Agents          → AIProjectAgentsOperations(版本化agents)
├── Connections     → ConnectionsClient
├── Datasets        → DatasetsClient
├── Deployments     → DeploymentsClient
├── Evaluations     → EvaluationsClient
├── Evaluators      → EvaluatorsClient
├── Indexes         → IndexesClient
├── Telemetry       → AIProjectTelemetry
├── OpenAI          → ProjectOpenAIClient(预览版)
└── GetPersistentAgentsClient() → PersistentAgentsClient

Core Workflows

核心工作流

1. Get Persistent Agents Client

1. 获取Persistent Agents客户端

csharp
// Get low-level agents client from project client
PersistentAgentsClient agentsClient = projectClient.GetPersistentAgentsClient();

// Create agent
PersistentAgent agent = await agentsClient.Administration.CreateAgentAsync(
    model: "gpt-4o-mini",
    name: "Math Tutor",
    instructions: "You are a personal math tutor.");

// Create thread and run
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);

// Poll for completion
do
{
    await Task.Delay(500);
    run = await agentsClient.Runs.GetRunAsync(thread.Id, run.Id);
}
while (run.Status == RunStatus.Queued || run.Status == RunStatus.InProgress);

// Get 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);
    }
}

// Cleanup
await agentsClient.Threads.DeleteThreadAsync(thread.Id);
await agentsClient.Administration.DeleteAgentAsync(agent.Id);
csharp
// 从项目客户端获取低级别agents客户端
PersistentAgentsClient agentsClient = projectClient.GetPersistentAgentsClient();

// 创建agent
PersistentAgent agent = await agentsClient.Administration.CreateAgentAsync(
    model: "gpt-4o-mini",
    name: "Math Tutor",
    instructions: "You are a personal math tutor.");

// 创建线程并运行
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);

// 轮询等待完成
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. Versioned Agents with Tools (Preview)

2. 带工具的版本化Agents(预览版)

csharp
using Azure.AI.Projects.OpenAI;

// Create agent with web search tool
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));

// Get response client
ProjectResponsesClient responseClient = projectClient.OpenAI.GetProjectResponsesClientForAgent(agentVersion.Name);

// Create response
ResponseResult response = responseClient.CreateResponse("What's the weather in Seattle?");
Console.WriteLine(response.GetOutputText());

// Cleanup
projectClient.Agents.DeleteAgentVersion(agentName: agentVersion.Name, agentVersion: agentVersion.Version);
csharp
using Azure.AI.Projects.OpenAI;

// 创建带网页搜索工具的agent
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));

// 获取响应客户端
ProjectResponsesClient responseClient = projectClient.OpenAI.GetProjectResponsesClientForAgent(agentVersion.Name);

// 创建响应
ResponseResult response = responseClient.CreateResponse("What's the weather in Seattle?");
Console.WriteLine(response.GetOutputText());

// 清理资源
projectClient.Agents.DeleteAgentVersion(agentName: agentVersion.Name, agentVersion: agentVersion.Version);

3. Connections

3. 连接管理

csharp
// List all connections
foreach (AIProjectConnection connection in projectClient.Connections.GetConnections())
{
    Console.WriteLine($"{connection.Name}: {connection.ConnectionType}");
}

// Get specific connection
AIProjectConnection conn = projectClient.Connections.GetConnection(
    connectionName, 
    includeCredentials: true);

// Get default connection
AIProjectConnection defaultConn = projectClient.Connections.GetDefaultConnection(
    includeCredentials: false);
csharp
// 列出所有连接
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

4. 部署管理

csharp
// List all deployments
foreach (AIProjectDeployment deployment in projectClient.Deployments.GetDeployments())
{
    Console.WriteLine($"{deployment.Name}: {deployment.ModelName}");
}

// Filter by publisher
foreach (var deployment in projectClient.Deployments.GetDeployments(modelPublisher: "Microsoft"))
{
    Console.WriteLine(deployment.Name);
}

// Get specific deployment
ModelDeployment details = (ModelDeployment)projectClient.Deployments.GetDeployment("gpt-4o-mini");
csharp
// 列出所有部署
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

5. 数据集管理

csharp
// Upload single file
FileDataset fileDataset = projectClient.Datasets.UploadFile(
    name: "my-dataset",
    version: "1.0",
    filePath: "data/training.txt",
    connectionName: connectionName);

// Upload folder
FolderDataset folderDataset = projectClient.Datasets.UploadFolder(
    name: "my-dataset",
    version: "2.0",
    folderPath: "data/training",
    connectionName: connectionName,
    filePattern: new Regex(".*\\.txt"));

// Get dataset
AIProjectDataset dataset = projectClient.Datasets.GetDataset("my-dataset", "1.0");

// Delete dataset
projectClient.Datasets.Delete("my-dataset", "1.0");
csharp
// 上传单个文件
FileDataset fileDataset = projectClient.Datasets.UploadFile(
    name: "my-dataset",
    version: "1.0",
    filePath: "data/training.txt",
    connectionName: connectionName);

// 上传文件夹
FolderDataset folderDataset = projectClient.Datasets.UploadFolder(
    name: "my-dataset",
    version: "2.0",
    folderPath: "data/training",
    connectionName: connectionName,
    filePattern: new Regex(".*\\.txt"));

// 获取数据集
AIProjectDataset dataset = projectClient.Datasets.GetDataset("my-dataset", "1.0");

// 删除数据集
projectClient.Datasets.Delete("my-dataset", "1.0");

6. Indexes

6. 索引管理

csharp
// Create Azure AI Search index
AzureAISearchIndex searchIndex = new(aiSearchConnectionName, aiSearchIndexName)
{
    Description = "Sample Index"
};

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

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

// Delete index
projectClient.Indexes.Delete(name: "my-index", version: "1.0");
csharp
// 创建Azure AI Search索引
AzureAISearchIndex searchIndex = new(aiSearchConnectionName, aiSearchIndexName)
{
    Description = "Sample Index"
};

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

// 列出索引
foreach (AIProjectIndex index in projectClient.Indexes.GetIndexes())
{
    Console.WriteLine(index.Name);
}

// 删除索引
projectClient.Indexes.Delete(name: "my-index", version: "1.0");

7. Evaluations

7. 评估管理

csharp
// Create evaluation configuration
var evaluatorConfig = new EvaluatorConfiguration(id: EvaluatorIDs.Relevance);
evaluatorConfig.InitParams.Add("deployment_name", BinaryData.FromObjectAsJson("gpt-4o"));

// Create evaluation
Evaluation evaluation = new Evaluation(
    data: new InputDataset("<dataset_id>"),
    evaluators: new Dictionary<string, EvaluatorConfiguration> 
    { 
        { "relevance", evaluatorConfig } 
    }
)
{
    DisplayName = "Sample Evaluation"
};

// Run evaluation
Evaluation result = projectClient.Evaluations.Create(evaluation: evaluation);

// Get evaluation
Evaluation getResult = projectClient.Evaluations.Get(result.Name);

// List evaluations
foreach (var eval in projectClient.Evaluations.GetAll())
{
    Console.WriteLine($"{eval.DisplayName}: {eval.Status}");
}
csharp
// 创建评估配置
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 = "Sample Evaluation"
};

// 运行评估
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. Get Azure OpenAI Chat Client

8. 获取Azure OpenAI聊天客户端

csharp
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);
csharp
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);

Available Agent Tools

可用Agent工具

ToolClassPurpose
Code Interpreter
CodeInterpreterToolDefinition
Execute Python code
File Search
FileSearchToolDefinition
Search uploaded files
Function Calling
FunctionToolDefinition
Call custom functions
Bing Grounding
BingGroundingToolDefinition
Web search via Bing
Azure AI Search
AzureAISearchToolDefinition
Search Azure AI indexes
OpenAPI
OpenApiToolDefinition
Call external APIs
Azure Functions
AzureFunctionToolDefinition
Invoke Azure Functions
MCP
MCPToolDefinition
Model Context Protocol tools
工具用途
代码解释器
CodeInterpreterToolDefinition
执行Python代码
文件搜索
FileSearchToolDefinition
搜索已上传文件
函数调用
FunctionToolDefinition
调用自定义函数
Bing grounding
BingGroundingToolDefinition
通过Bing进行网页搜索
Azure AI Search
AzureAISearchToolDefinition
搜索Azure AI索引
OpenAPI
OpenApiToolDefinition
调用外部API
Azure Functions
AzureFunctionToolDefinition
调用Azure Functions
MCP
MCPToolDefinition
模型上下文协议(Model Context Protocol)工具

Key Types Reference

关键类型参考

TypePurpose
AIProjectClient
Main entry point
PersistentAgentsClient
Low-level agent operations
PromptAgentDefinition
Versioned agent definition
AgentVersion
Versioned agent instance
AIProjectConnection
Connection to Azure resource
AIProjectDeployment
Model deployment info
AIProjectDataset
Dataset metadata
AIProjectIndex
Search index metadata
Evaluation
Evaluation configuration and results
类型用途
AIProjectClient
主入口点
PersistentAgentsClient
低级别agent操作
PromptAgentDefinition
版本化agent定义
AgentVersion
版本化agent实例
AIProjectConnection
与Azure资源的连接
AIProjectDeployment
模型部署信息
AIProjectDataset
数据集元数据
AIProjectIndex
搜索索引元数据
Evaluation
评估配置与结果

Best Practices

最佳实践

  1. Use
    DefaultAzureCredential
    for production authentication
  2. Use async methods (
    *Async
    ) for all I/O operations
  3. Poll with appropriate delays (500ms recommended) when waiting for runs
  4. Clean up resources — delete threads, agents, and files when done
  5. Use versioned agents (via
    Azure.AI.Projects.OpenAI
    ) for production scenarios
  6. Store connection IDs rather than names for tool configurations
  7. Use
    includeCredentials: true
    only when credentials are needed
  8. Handle pagination — use
    AsyncPageable<T>
    for listing operations
  1. 生产环境认证使用
    DefaultAzureCredential
  2. 所有I/O操作使用异步方法
    *Async
  3. 等待运行时使用适当的延迟轮询(推荐500ms)
  4. 清理资源 —— 使用完毕后删除线程、agent和文件
  5. 生产场景使用版本化agents(通过
    Azure.AI.Projects.OpenAI
  6. 工具配置中存储连接ID而非名称
  7. 仅在需要凭据时使用
    includeCredentials: true
  8. 处理分页 —— 列表操作使用
    AsyncPageable<T>

Error Handling

错误处理

csharp
using Azure;

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

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

Related SDKs

相关SDK

SDKPurposeInstall
Azure.AI.Projects
High-level project client (this SDK)
dotnet add package Azure.AI.Projects
Azure.AI.Agents.Persistent
Low-level agent operations
dotnet add package Azure.AI.Agents.Persistent
Azure.AI.Projects.OpenAI
Versioned agents with OpenAI
dotnet add package Azure.AI.Projects.OpenAI
SDK用途安装命令
Azure.AI.Projects
高级项目客户端(本SDK)
dotnet add package Azure.AI.Projects
Azure.AI.Agents.Persistent
低级别agent操作
dotnet add package Azure.AI.Agents.Persistent
Azure.AI.Projects.OpenAI
带OpenAI的版本化agents
dotnet add package Azure.AI.Projects.OpenAI

Reference Links

参考链接