Community寫作與編輯github.com

microsoft/azure-ai-agents-persistent-dotnet

Azure AI Agents Persistent SDK for .NET。低階 SDK,用於建立和管理具備執行緒、訊息、執行和工具的 AI Agent。支援 Agent CRUD、對話執行緒、串流回應、函式呼叫、檔案搜尋和程式碼解譯器。觸發詞:「PersistentAgentsClient」、「persistent agents」、「agent threads」、「agent runs」、「streaming agents」、「function calling agents .NET」。

azure-ai-agents-persistent-dotnet 是什麼?

此技能提供 Azure.AI.Agents.Persistent 套件,這是一個專為 .NET 開發人員設計的低階 SDK,用於建立和管理具有持久狀態的 AI Agent。它涵蓋完整的 Agent 生命週期管理,包括建立、更新和刪除 Agent(CRUD),以及管理對話執行緒、處理訊息和執行執行任務。關鍵功能包括支援串流回應以實現即時互動、透過定義自訂函式來擴充 Agent 能力的函式呼叫、整合 Azure AI Search 的檔案搜尋,以及內建的程式碼解譯器功能。此 SDK 適用於 Azure AI 專案,並需設定環境變數,如專案端點和模型部署名稱。開發人員可使用 `dotnet add package` 命令安裝,並透過 `PersistentAgentsClient` 類別來存取子用戶端(如 Administration、Threads 和 Runs)。工作流程通常涉及建立 Agent、建立執行緒、新增訊息,然後以輪詢或串流模式執行 Agent。此 SDK 目前穩定版為 v1.1.0,預覽版為 v1.2.0-beta.8。

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

Installed? Explore more 寫作與編輯 skills: steipete/notion, langchain-ai/langchain, bytedance/podcast-generation · View all 6 →

在你喜歡的 AI 中提問

開啟一個已預先載入此 Agent Skill 的新對話。

說明文件

Azure.AI.Agents.Persistent (.NET)

用於建立和管理持久性 AI 代理的低階 SDK,支援對話串、訊息、執行和工具。

安裝

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

目前版本: 穩定版 v1.1.0, 預覽版 v1.2.0-beta.8

環境變數

PROJECT_ENDPOINT=https://<resource>.services.ai.azure.com/api/projects/<project>  # 必填:Azure AI 專案端點
MODEL_DEPLOYMENT_NAME=gpt-4o-mini  # 必填:模型部署名稱
AZURE_BING_CONNECTION_ID=<bing-connection-resource-id>  # 必填:Bing 連線資源 ID
AZURE_AI_SEARCH_CONNECTION_ID=<search-connection-resource-id>  # 必填:Azure AI 搜尋連線資源 ID
AZURE_TOKEN_CREDENTIALS=prod  # 僅在生產環境使用 DefaultAzureCredential 時必填

驗證

using Azure.AI.Agents.Persistent;
using Azure.Identity;

var projectEndpoint = Environment.GetEnvironmentVariable("PROJECT_ENDPOINT");
// 本機開發:DefaultAzureCredential。生產環境:設定 AZURE_TOKEN_CREDENTIALS=prod 或 AZURE_TOKEN_CREDENTIALS=<特定憑證>
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();
PersistentAgentsClient client = new(projectEndpoint, credential);

用戶端階層

PersistentAgentsClient
├── Administration  → 代理 CRUD 操作
├── Threads         → 對話串管理
├── Messages        → 訊息操作
├── Runs            → 執行與串流
├── Files           → 檔案上傳/下載
└── VectorStores    → 向量儲存管理

核心工作流程

1. 建立代理

var modelDeploymentName = Environment.GetEnvironmentVariable("MODEL_DEPLOYMENT_NAME");

PersistentAgent agent = await client.Administration.CreateAgentAsync(
    model: modelDeploymentName,
    name: "Math Tutor",
    instructions: "You are a personal math tutor. Write and run code to answer math questions.",
    tools: [new CodeInterpreterToolDefinition()]
);

2. 建立對話串與訊息

// 建立對話串
PersistentAgentThread thread = await client.Threads.CreateThreadAsync();

// 建立訊息
await client.Messages.CreateMessageAsync(
    thread.Id,
    MessageRole.User,
    "I need to solve the equation `3x + 11 = 14`. Can you help me?"
);

3. 執行代理(輪詢)

// 建立執行
ThreadRun run = await client.Runs.CreateRunAsync(
    thread.Id,
    agent.Id,
    additionalInstructions: "Please address the user as Jane Doe."
);

// 輪詢完成
 do
{
    await Task.Delay(TimeSpan.FromMilliseconds(500));
    run = await client.Runs.GetRunAsync(thread.Id, run.Id);
}
while (run.Status == RunStatus.Queued || run.Status == RunStatus.InProgress);

// 檢索訊息
await foreach (PersistentThreadMessage message in client.Messages.GetMessagesAsync(
    threadId: thread.Id, 
    order: ListSortOrder.Ascending))
{
    Console.Write($"{message.Role}: ");
    foreach (MessageContent content in message.ContentItems)
    {
        if (content is MessageTextContent textContent)
            Console.WriteLine(textContent.Text);
    }
}

4. 串流回應

AsyncCollectionResult<StreamingUpdate> stream = client.Runs.CreateRunStreamingAsync(
    thread.Id, 
    agent.Id
);

await foreach (StreamingUpdate update in stream)
{
    if (update.UpdateKind == StreamingUpdateReason.RunCreated)
    {
        Console.WriteLine("--- Run started! ---");
    }
    else if (update is MessageContentUpdate contentUpdate)
    {
        Console.Write(contentUpdate.Text);
    }
    else if (update.UpdateKind == StreamingUpdateReason.RunCompleted)
    {
        Console.WriteLine("\n--- Run completed! ---");
    }
}

5. 函數呼叫

// 定義函數工具
FunctionToolDefinition weatherTool = new(
    name: "getCurrentWeather",
    description: "Gets the current weather at a location.",
    parameters: BinaryData.FromObjectAsJson(new
    {
        Type = "object",
        Properties = new
        {
            Location = new { Type = "string", Description = "City and state, e.g. San Francisco, CA" },
            Unit = new { Type = "string", Enum = new[] { "c", "f" } }
        },
        Required = new[] { "location" }
    }, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase })
);

// 建立帶有函數的代理
PersistentAgent agent = await client.Administration.CreateAgentAsync(
    model: modelDeploymentName,
    name: "Weather Bot",
    instructions: "You are a weather bot.",
    tools: [weatherTool]
);

// 輪詢期間處理函數呼叫
 do
{
    await Task.Delay(500);
    run = await client.Runs.GetRunAsync(thread.Id, run.Id);

    if (run.Status == RunStatus.RequiresAction 
        && run.RequiredAction is SubmitToolOutputsAction submitAction)
    {
        List<ToolOutput> outputs = [];
        foreach (RequiredToolCall toolCall in submitAction.ToolCalls)
        {
            if (toolCall is RequiredFunctionToolCall funcCall)
            {
                // 執行函數並取得結果
                string result = ExecuteFunction(funcCall.Name, funcCall.Arguments);
                outputs.Add(new ToolOutput(toolCall, result));
            }
        }
        run = await client.Runs.SubmitToolOutputsToRunAsync(run, outputs, toolApprovals: null);
    }
}
while (run.Status == RunStatus.Queued || run.Status == RunStatus.InProgress);

6. 使用向量儲存進行檔案搜尋

// 上傳檔案
PersistentAgentFileInfo file = await client.Files.UploadFileAsync(
    filePath: "document.txt",
    purpose: PersistentAgentFilePurpose.Agents
);

// 建立向量儲存
PersistentAgentsVectorStore vectorStore = await client.VectorStores.CreateVectorStoreAsync(
    fileIds: [file.Id],
    name: "my_vector_store"
);

// 建立檔案搜尋資源
FileSearchToolResource fileSearchResource = new();
fileSearchResource.VectorStoreIds.Add(vectorStore.Id);

// 建立帶有檔案搜尋的代理
PersistentAgent agent = await client.Administration.CreateAgentAsync(
    model: modelDeploymentName,
    name: "Document Assistant",
    instructions: "You help users find information in documents.",
    tools: [new FileSearchToolDefinition()],
    toolResources: new ToolResources { FileSearch = fileSearchResource }
);

7. Bing 基準化

var bingConnectionId = Environment.GetEnvironmentVariable("AZURE_BING_CONNECTION_ID");

BingGroundingToolDefinition bingTool = new(
    new BingGroundingSearchToolParameters(
        [new BingGroundingSearchConfiguration(bingConnectionId)]
    )
);

PersistentAgent agent = await client.Administration.CreateAgentAsync(
    model: modelDeploymentName,
    name: "Search Agent",
    instructions: "Use Bing to answer questions about current events.",
    tools: [bingTool]
);

8. Azure AI 搜尋

AzureAISearchToolResource searchResource = new(
    connectionId: searchConnectionId,
    indexName: "my_index",
    topK: 5,
    filter: "category eq 'documentation'",
    queryType: AzureAISearchQueryType.Simple
);

PersistentAgent agent = await client.Administration.CreateAgentAsync(
    model: modelDeploymentName,
    name: "Search Agent",
    instructions: "Search the documentation index to answer questions.",
    tools: [new AzureAISearchToolDefinition()],
    toolResources: new ToolResources { AzureAISearch = searchResource }
);

9. 清理

await client.Threads.DeleteThreadAsync(thread.Id);
await client.Administration.DeleteAgentAsync(agent.Id);
await client.VectorStores.DeleteVectorStoreAsync(vectorStore.Id);
await client.Files.DeleteFileAsync(file.Id);

可用工具

工具類別目的
Code InterpreterCodeInterpreterToolDefinition執行 Python 程式碼、產出視覺化圖表
File SearchFileSearchToolDefinition透過向量儲存搜尋上傳的檔案
Function CallingFunctionToolDefinition呼叫自訂函數
Bing GroundingBingGroundingToolDefinition透過 Bing 進行網頁搜尋
Azure AI SearchAzureAISearchToolDefinition搜尋 Azure AI 搜尋索引
OpenAPIOpenApiToolDefinition透過 OpenAPI 規格呼叫外部 API
Azure FunctionsAzureFunctionToolDefinition叫用 Azure Functions
MCPMCPToolDefinition模型內容協定工具
SharePointSharepointToolDefinition存取 SharePoint 內容
Microsoft FabricMicrosoftFabricToolDefinition存取 Fabric 資料

串流更新類型

更新類型描述
StreamingUpdateReason.RunCreated執行已開始
StreamingUpdateReason.RunInProgress執行處理中
StreamingUpdateReason.RunCompleted執行已完成
StreamingUpdateReason.RunFailed執行發生錯誤
MessageContentUpdate文字內容片段
RunStepUpdate步驟狀態變更

關鍵類型參考

類型目的
PersistentAgentsClient主要進入點
PersistentAgent具有模型、指令和工具的代理
PersistentAgentThread對話串
PersistentThreadMessage對話串中的訊息
ThreadRun代理對對話串的執行
RunStatus佇列中、處理中、需要操作、已完成、失敗
ToolResources組合的工具資源
ToolOutput函數呼叫回應

最佳實務

  1. 始終處置用戶端 — 使用 using 陳述式或明確處置
  2. 以適當間隔輪詢 — 建議在狀態檢查之間延遲 500 毫秒
  3. 清理資源 — 完成後刪除對話串和代理
  4. 處理所有執行狀態 — 檢查 RequiresAction、Failed、Cancelled
  5. 使用串流改善即時體驗 — 比輪詢提供更好的使用者體驗
  6. 儲存 ID 而非物件 — 透過 ID 引用代理/對話串
  7. 使用非同步方法 — 所有操作應為非同步

錯誤處理

using Azure;

try
{
    var agent = await client.Administration.CreateAgentAsync(...);
}
catch (RequestFailedException ex) when (ex.Status == 404)
{
    Console.WriteLine("Resource not found");
}
catch (RequestFailedException ex)
{
    Console.WriteLine($"Error: {ex.Status} - {ex.ErrorCode}: {ex.Message}");
}

相關 SDK

SDK目的安裝
Azure.AI.Agents.Persistent低階代理(此 SDK)dotnet add package Azure.AI.Agents.Persistent
Azure.AI.Projects高階專案用戶端dotnet add package Azure.AI.Projects

參考連結

資源URL
NuGet 套件https://www.nuget.org/packages/Azure.AI.Agents.Persistent
API 參考https://learn.microsoft.com/dotnet/api/azure.ai.agents.persistent
GitHub 原始碼https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/ai/Azure.AI.Agents.Persistent
範例https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/ai/Azure.AI.Agents.Persistent/samples

Individual skills in this repo

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

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-projects-dotnet

Azure AI Projects SDK for .NET. High-level client for Azure AI Foundry projects including agents, connections, datasets, deployments, evaluations, and indexes. Use for AI Foundry project management, versioned agents, and orchestration. Triggers: "AI Projects", "AIProjectClient", "Foundry project", "versioned agents", "evaluations", "datasets", "connections", "deployments .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.

相關技能