Azure.AI.Projects (.NET)
用于 Azure AI Foundry 项目操作的高级 SDK,包括代理、连接、数据集、部署、评估和索引。
安装
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
当前版本:正式版 v1.1.0,预览版 v1.2.0-beta.5
环境变量
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
身份验证
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);
客户端层次结构
AIProjectClient
├── Agents → AIProjectAgentsOperations(版本化代理)
├── Connections → ConnectionsClient
├── Datasets → DatasetsClient
├── Deployments → DeploymentsClient
├── Evaluations → EvaluationsClient
├── Evaluators → EvaluatorsClient
├── Indexes → IndexesClient
├── Telemetry → AIProjectTelemetry
├── OpenAI → ProjectOpenAIClient(预览版)
└── GetPersistentAgentsClient() → PersistentAgentsClient
核心工作流
1. 获取持久化代理客户端
PersistentAgentsClient agentsClient = projectClient.GetPersistentAgentsClient();
PersistentAgent agent = await agentsClient.Administration.CreateAgentAsync(
model: "gpt-4o-mini",
name: "数学家教",
instructions: "你是一名个人数学家教。");
PersistentAgentThread thread = await agentsClient.Threads.CreateThreadAsync();
await agentsClient.Messages.CreateMessageAsync(thread.Id, MessageRole.User, "解方程 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. 带工具的版本化代理(预览版)
using Azure.AI.Projects.OpenAI;
PromptAgentDefinition agentDefinition = new(model: "gpt-4o-mini")
{
Instructions = "你是一个乐于助人的助手,可以搜索网络",
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("西雅图的天气怎么样?");
Console.WriteLine(response.GetOutputText());
projectClient.Agents.DeleteAgentVersion(agentName: agentVersion.Name, agentVersion: agentVersion.Version);
3. 连接
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. 部署
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. 数据集
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. 索引
AzureAISearchIndex searchIndex = new(aiSearchConnectionName, aiSearchIndexName)
{
Description = "示例索引"
};
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. 评估
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 = "示例评估"
};
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 聊天客户端
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。");
uri = new Uri($"https://{uri.Host}");
AzureOpenAIClient azureOpenAIClient = new AzureOpenAIClient(uri, new DefaultAzureCredential());
ChatClient chatClient = azureOpenAIClient.GetChatClient("gpt-4o-mini");
ChatCompletion result = chatClient.CompleteChat("列出所有彩虹颜色");
Console.WriteLine(result.Content[0].Text);
可用的代理工具
| 工具 | 类 | 用途 |
|---|
| 代码解释器 | CodeInterpreterToolDefinition | 执行 Python 代码 |
| 文件搜索 | FileSearchToolDefinition | 搜索上传的文件 |
| 函数调用 | FunctionToolDefinition | 调用自定义函数 |
| Bing 搜索 | BingGroundingToolDefinition | 通过 Bing 进行网络搜索 |
| Azure AI 搜索 | AzureAISearchToolDefinition | 搜索 Azure AI 索引 |
| OpenAPI | OpenApiToolDefinition | 调用外部 API |
| Azure Functions | AzureFunctionToolDefinition | 调用 Azure Functions |
| MCP | MCPToolDefinition | 模型上下文协议工具 |
关键类型参考
| 类型 | 用途 |
|---|
AIProjectClient | 主要入口点 |
PersistentAgentsClient | 低级代理操作 |
PromptAgentDefinition | 版本化代理定义 |
AgentVersion | 版本化代理实例 |
AIProjectConnection | 连接到 Azure 资源 |
AIProjectDeployment | 模型部署信息 |
AIProjectDataset | 数据集元数据 |
AIProjectIndex | 搜索索引元数据 |
Evaluation | 评估配置和结果 |
最佳实践
- 使用
DefaultAzureCredential 进行生产环境身份验证
- 使用异步方法 (
*Async) 处理所有 I/O 操作
- 使用适当的延迟进行轮询(建议 500 毫秒)等待运行完成
- 清理资源 — 完成后删除线程、代理和文件
- 使用版本化代理(通过
Azure.AI.Projects.OpenAI)用于生产场景
- 存储连接 ID 而非名称,用于工具配置
- 仅在需要凭据时使用
includeCredentials: true
- 处理分页 — 使用
AsyncPageable<T> 进行列表操作
错误处理
using Azure;
try
{
var result = await projectClient.Evaluations.CreateAsync(evaluation);
}
catch (RequestFailedException ex)
{
Console.WriteLine($"错误:{ex.Status} - {ex.ErrorCode}: {ex.Message}");
}
相关 SDK
| SDK | 用途 | 安装 |
|---|
Azure.AI.Projects | 高级项目客户端(此 SDK) | dotnet add package Azure.AI.Projects |
Azure.AI.Agents.Persistent | 低级代理操作 | dotnet add package Azure.AI.Agents.Persistent |
Azure.AI.Projects.OpenAI | 带 OpenAI 的版本化代理 | dotnet add package Azure.AI.Projects.OpenAI |
参考链接