Community写作与编辑github.com

microsoft/azure-ai-agents-persistent-dotnet

适用于 .NET 的 Azure AI Agents 持久化 SDK。用于创建和管理 AI 代理的低级 SDK,支持线程、消息、运行和工具操作。

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

该技能提供了 Microsoft 的 Azure.AI.Agents.Persistent 低级 SDK 的完整使用指南。它面向 .NET 开发者,旨在通过客户端层次结构(PersistentAgentsClient)简化持久化 AI 代理的创建、管理和执行流程。核心工作流包括创建代理、管理会话线程、通过轮询或流式传输处理运行、以及多种工具集成(代码解释器、文件搜索、函数调用、Bing 搜索、Azure AI 搜索等)。SDK 支持在本地开发环境使用 DefaultAzureCredential,在生产环境可指定托管标识等特定凭证。文档详细说明了环境变量配置、安装步骤、流式处理响应、函数调用处理、错误处理以及最佳实践,并提供了 NuGet 包、API 参考和 GitHub 源码链接。

兼容平台~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=<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();
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: "你是一名个人数学导师。编写并运行代码来回答数学问题。",
    tools: [new CodeInterpreterToolDefinition()]
);

2. 创建线程和消息

// 创建线程
PersistentAgentThread thread = await client.Threads.CreateThreadAsync();

// 创建消息
await client.Messages.CreateMessageAsync(
    thread.Id,
    MessageRole.User,
    "我需要解方程 `3x + 11 = 14`。你能帮我吗?"
);

3. 运行代理(轮询)

// 创建运行
ThreadRun run = await client.Runs.CreateRunAsync(
    thread.Id,
    agent.Id,
    additionalInstructions: "请称呼用户为 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("--- 运行开始! ---");
    }
    else if (update is MessageContentUpdate contentUpdate)
    {
        Console.Write(contentUpdate.Text);
    }
    else if (update.UpdateKind == StreamingUpdateReason.RunCompleted)
    {
        Console.WriteLine("\n--- 运行完成! ---");
    }
}

5. 函数调用

// 定义函数工具
FunctionToolDefinition weatherTool = new(
    name: "getCurrentWeather",
    description: "获取某个地点的当前天气。",
    parameters: BinaryData.FromObjectAsJson(new
    {
        Type = "object",
        Properties = new
        {
            Location = new { Type = "string", Description = "城市和州,例如 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: "天气机器人",
    instructions: "你是一个天气机器人。",
    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: "文档助手",
    instructions: "你帮助用户在文档中查找信息。",
    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: "搜索代理",
    instructions: "使用 Bing 回答有关时事的问题。",
    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: "搜索代理",
    instructions: "搜索文档索引以回答问题。",
    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);

可用工具

工具类用途
代码解释器CodeInterpreterToolDefinition执行 Python 代码,生成可视化
文件搜索FileSearchToolDefinition通过向量存储搜索上传的文件
函数调用FunctionToolDefinition调用自定义函数
Bing 接地BingGroundingToolDefinition通过 Bing 进行网络搜索
Azure AI 搜索AzureAISearchToolDefinition搜索 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代理针对线程的执行
RunStatusQueued、InProgress、RequiresAction、Completed、Failed
ToolResources组合工具资源
ToolOutput函数调用响应

最佳实践

  1. 始终释放客户端 — 使用 using 语句或显式释放
  2. 使用适当的延迟进行轮询 — 建议状态检查间隔为 500ms
  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("未找到资源");
}
catch (RequestFailedException ex)
{
    Console.WriteLine($"错误:{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.

相关技能