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 是什麼?

此技能提供 **Azure.AI.Projects** .NET SDK 的完整功能,作為 Azure AI Foundry 專案的高階用戶端,讓開發者能透過統一的 API 管理代理程式(包括版本化代理程式)、連線、資料集、部署、評估與索引。支援低階代理程式操作(`PersistentAgentsClient`)以及搭配 Azure OpenAI 使用進階工具(如網路搜尋、程式碼直譯器、Azure AI 搜尋等)。主要應用於 Cursor 和 Codex 等 .NET 開發環境,依賴 Azure 環境變數(`PROJECT_ENDPOINT`、`MODEL_DEPLOYMENT_NAME`)進行驗證。透過 `DefaultAzureCredential` 簡化安全性設定,並提供異步操作方法與資源清理最佳實務,是建構 AI 協作工作流程的核心工具。

相容平台~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: "Math Tutor",
    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);

可用的代理程式工具

工具類別用途
Code InterpreterCodeInterpreterToolDefinition執行 Python 程式碼
File SearchFileSearchToolDefinition搜尋已上傳的檔案
Function CallingFunctionToolDefinition呼叫自訂函式
Bing GroundingBingGroundingToolDefinition透過 Bing 進行網路搜尋
Azure AI SearchAzureAISearchToolDefinition搜尋 Azure AI 索引
OpenAPIOpenApiToolDefinition呼叫外部 API
Azure FunctionsAzureFunctionToolDefinition叫用 Azure Functions
MCPMCPToolDefinition模型上下文協定工具

重要類型參考

類型用途
AIProjectClient主要進入點
PersistentAgentsClient低階代理程式操作
PromptAgentDefinition版本化代理程式定義
AgentVersion版本化代理程式實例
AIProjectConnectionAzure 資源連線
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

參考連結

資源URL
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.

相關技能