Community写作与编辑github.com

microsoft/azure-ai-projects-dotnet

Azure AI Projects SDK for .NET。用于 Azure AI Foundry 项目的高级客户端,包括代理、连接、数据集、部署、评估和索引。可用于 AI Foundry 项目管理、版本化代理和编排。触发词:“AI Projects”、“AIProjectClient”、“Foundry project”、“versioned agents”、“evaluations”、“datasets”、“connections”、“deployments .NET”。

azure-ai-projects-dotnet 是什么?

这是一个适用于 .NET 的 Azure AI Projects SDK,为 Azure AI Foundry 项目提供高级管理能力。它支持代理(包括版本化代理)、连接、数据集、部署、评估和索引等核心操作,并提供了丰富的客户端层次结构和工具集成。该技能适用于所有主流 AI 编码助手(如 Claude Code、Cursor、Codex、GitHub Copilot Chat 等),开发者可通过自然语言指令快速调用相关功能。其核心工作流程包括:获取持久化代理客户端、使用工具创建版本化代理、管理连接与部署、上传数据集、创建搜索索引、运行模型评估,以及获取 Azure OpenAI 聊天客户端。SDK 还内置了代码解释器、文件搜索、函数调用、Bing 搜索、Azure AI 搜索、OpenAPI、Azure Functions 和 MCP 等多种代理工具,支持通过 `DefaultAzureCredential` 进行生产环境身份验证,并提供了最佳实践和错误处理示例。

兼容平台~Claude Code✓Codex CLI~Cursor
npx skills add https://github.com/microsoft/agent-skills/tree/main/.github/plugins/azure-sdk-dotnet/skills/azure-ai-projects-dotnet

Installed? Explore more 写作与编辑 skills: steipete/notion, langchain-ai/langchain, bytedance/podcast-generation · View all 6 →

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

Azure.AI.Projects (.NET)

用于 Azure AI Foundry 项目操作的高级 SDK,包括代理、连接、数据集、部署、评估和索引。

安装

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

# 可选:用于包含 OpenAI 扩展的版本化代理
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>  # 必需:Azure AI 项目终结点
MODEL_DEPLOYMENT_NAME=gpt-4o-mini  # 必需:模型部署名称
CONNECTION_NAME=<your-connection-name>  # 可选:项目连接名称
AI_SEARCH_CONNECTION_NAME=<ai-search-connection>  # 可选:Azure AI 搜索连接名称
AZURE_TOKEN_CREDENTIALS=prod  # 仅在生产环境中使用 DefaultAzureCredential 时需要

身份验证

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

var endpoint = Environment.GetEnvironmentVariable("PROJECT_ENDPOINT");
// 本地开发:使用 DefaultAzureCredential。生产环境:设置 AZURE_TOKEN_CREDENTIALS=prod 或 AZURE_TOKEN_CREDENTIALS=<specific_credential>
var credential = new DefaultAzureCredential(
    DefaultAzureCredential.DefaultEnvironmentVariableName
);
// 或者在生产环境中直接使用特定凭据:
// 请参见 https://learn.microsoft.com/dotnet/api/overview/azure/identity-readme?view=azure-dotnet#credential-classes
// var credential = new ManagedIdentityCredential();
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. 索引

// 创建 Azure AI 搜索索引
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 索引
OpenAPIOpenApiToolDefinition调用外部 API
Azure FunctionsAzureFunctionToolDefinition调用 Azure Functions
MCPMCPToolDefinition模型上下文协议工具

关键类型参考

类型用途
AIProjectClient主要入口点
PersistentAgentsClient低级代理操作
PromptAgentDefinition版本化代理定义
AgentVersion版本化代理实例
AIProjectConnection连接到 Azure 资源
AIProjectDeployment模型部署信息
AIProjectDataset数据集元数据
AIProjectIndex搜索索引元数据
Evaluation评估配置和结果

最佳实践

  1. 使用 DefaultAzureCredential 进行生产环境身份验证
  2. 使用异步方法 (*Async) 处理所有 I/O 操作
  3. 使用适当的延迟进行轮询(建议 500 毫秒)等待运行完成
  4. 清理资源 — 完成后删除线程、代理和文件
  5. 使用版本化代理(通过 Azure.AI.Projects.OpenAI)用于生产场景
  6. 存储连接 ID 而非名称,用于工具配置
  7. 仅在需要凭据时使用 includeCredentials: true
  8. 处理分页 — 使用 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

参考链接

资源链接
NuGet 包https://www.nuget.org/packages/Azure.AI.Projects
API 参考https://learn.microsoft.com/dotnet/api/azure.ai.projects
GitHub 源代码https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/ai/Azure.AI.Projects
示例https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/ai/Azure.AI.Projects/samples

Individual skills in this repo

This repo contains 12 individual skills — each has its own dedicated page.

microsoft/azure-ai-agents-persistent-dotnet

Azure AI Agents Persistent SDK for .NET. Low-level SDK for creating and managing AI agents with threads, messages, runs, and tools. Use for agent CRUD, conversation threads, streaming responses, function calling, file search, and code interpreter. Triggers: "PersistentAgentsClient", "persistent agents", "agent threads", "agent runs", "streaming agents", "function calling agents .NET".

microsoft/azure-ai-document-intelligence-dotnet

Azure AI Document Intelligence SDK for .NET. Extract text, tables, and structured data from documents using prebuilt and custom models. Use for invoice processing, receipt extraction, ID document analysis, and custom document models. Triggers: "Document Intelligence", "DocumentIntelligenceClient", "form recognizer", "invoice extraction", "receipt OCR", "document analysis .NET".

microsoft/azure-ai-openai-dotnet

Azure OpenAI SDK for .NET. Client library for Azure OpenAI and OpenAI services. Use for chat completions, embeddings, image generation, audio transcription, and assistants. Triggers: "Azure OpenAI", "AzureOpenAIClient", "ChatClient", "chat completions .NET", "GPT-4", "embeddings", "DALL-E", "Whisper", "OpenAI .NET".

microsoft/azure-ai-voicelive-dotnet

Azure AI Voice Live SDK for .NET. Build real-time voice AI applications with bidirectional WebSocket communication. Use for voice assistants, conversational AI, real-time speech-to-speech, and voice-enabled chatbots. Triggers: "voice live", "real-time voice", "VoiceLiveClient", "VoiceLiveSession", "voice assistant .NET", "bidirectional audio", "speech-to-speech".

microsoft/azure-eventgrid-dotnet

Azure Event Grid SDK for .NET. Client library for publishing and consuming events with Azure Event Grid. Use for event-driven architectures, pub/sub messaging, CloudEvents, and EventGridEvents. Triggers: "Event Grid", "EventGridPublisherClient", "CloudEvent", "EventGridEvent", "publish events .NET", "event-driven", "pub/sub".

microsoft/azure-eventhub-dotnet

Azure Event Hubs SDK for .NET. Use for high-throughput event streaming: sending events (EventHubProducerClient, EventHubBufferedProducerClient), receiving events (EventProcessorClient with checkpointing), partition management, and real-time data ingestion. Triggers: "Event Hubs", "event streaming", "EventHubProducerClient", "EventProcessorClient", "send events", "receive events", "checkpointing", "partition".

microsoft/azure-identity-dotnet

Azure Identity library for .NET. Authentication library for Azure SDK clients using Microsoft Entra ID. Use for DefaultAzureCredential, managed identity, service principals, and developer credentials. Triggers: "Azure Identity", "DefaultAzureCredential", "ManagedIdentityCredential", "ClientSecretCredential", "authentication .NET", "Azure auth", "credential chain".

microsoft/azure-kusto-graph

Build and query Kusto graphs from natural language. Covers transient graphs (make-graph), persistent graph models/snapshots, pattern matching (graph-match), shortest paths, connected components, and graph-to-table export. Generates the edges-first thinking: define edges, define node lookups, union, make-graph. WHEN: make-graph, graph-match, graph-shortest-paths, graph-to-table, graph-mark-components, persistent graph, graph model, graph snapshot, build a graph from data, find paths between nodes, pattern matching in graph, connected components, transient graph, Kusto graph, KQL graph.

microsoft/azure-kusto-irql

Compose IRQL (Incident Response Query Language) queries for Kusto cybersecurity investigations. Translates natural language hunting questions into composable IRQL pipelines using Get_*, Extract_*, and Enrich_* functions. WHEN: IRQL query, security hunt, threat hunting KQL, incident response query, compose hunting pipeline, failed logins, phishing investigation, lateral movement, process execution, file creation events.

microsoft/azure-kusto-irql-graph

Apply IRQL graph functions to KQL or IRQL query results for Kusto Explorer visualization. Generates Lift_To_Graph mappings and composes Graph_Render_View, Graph_Fold_By_Property, Extract_Node_*, Enrich_Node_*, and Enrich_Graph_* calls. Accepts a supplied query or limited basic natural-language source request; it is not a general natural-language-to-KQL/IRQL skill. WHEN: Lift_To_Graph, Graph_Render_View, Graph_Fold_By_Property, IRQL graph enrichment, graph mapping for existing query results, icon-decorated graph, fold graph nodes. Use azure-kusto-graph for native make-graph analysis, graph-match, shortest paths, components, or persistent graphs.

microsoft/azure-local

Plan, deploy, operate, and troubleshoot Azure Local (formerly Azure Stack HCI): sizing and prerequisites, Arc registration, lifecycle updates, workloads (Azure Local VMs, AKS on Azure Local, images, disks, logical networks), SDN and network security, and failure triage — starting read-only and confirming before risky changes. WHEN: Azure Local, Azure Stack HCI, Arc resource bridge, custom location, Azure Local VM, Arc VM, AKS on Azure Local, AKS hybrid, SDN, Lifecycle Manager, Azure Local update, disconnected site.

microsoft/azure-local-multi-rack

Plan, deploy, operate, and troubleshoot multi-rack (rack scale) deployments of Azure Local — preintegrated racks scaling to hundreds of machines, built on Network Fabric Controller, Cluster Manager, SAN storage, and managed network fabric. Use for the Microsoft.NetworkCloud and Microsoft.ManagedNetworkFabric control plane. NOT for standard 1-16 node Azure Local, and NOT for rack-aware clusters (two racks as availability zones, up to 8 nodes, synchronous replication) — those are standard scale. WHEN: multi-rack, rack scale Azure Local, aggregation rack, compute rack, Network Fabric Controller, NFC, Cluster Manager, network fabric, isolation domain, az networkcloud, az networkfabric, multi-rack logical network, multi-rack Arc VM.

相关技能