Skip to content

使用 .NET 构建支持持久化会话的 Azure AI Agents

通过 Azure.AI.Agents.Persistent 低级 SDK,开发者可以在 .NET 环境中创建能够管理会话线程(Threads)、消息(Messages)和运行状态(Runs)的持久化 AI 智能体,并集成代码解释器、文件搜索及外部工具调用。

为什么需要这个技能

在构建复杂的 AI 应用时,简单的“请求-响应”模式无法满足需求。开发者需要 AI 能够“记得”之前的对话上下文,且能够调用外部工具(如搜索 Bing 或执行 Python 代码)来增强回答的准确性。

Azure.AI.Agents.Persistent SDK 提供了对 AI Agent 底层生命周期的精细控制。它将会话状态存储在云端(Persistent Threads),这意味着开发者无需在本地数据库中手动维护庞大的对话历史,即可实现跨会话的持久化交互。

适用场景

  • 专业领域助手:如数学导师,需要结合代码解释器执行计算并记录解题步骤。
  • 文档知识库问答:通过 Vector Store 实现 RAG(检索增强生成),让 AI 基于上传的私有文档回答问题。
  • 企业级自动化流程:通过 Function Calling 触发企业内部 API,实现从对话到执行的闭环。
  • 实时交互应用:利用 Streaming 响应提升用户体验,避免长时间等待 AI 生成完整回复。

核心工作流

1. 环境准备与认证

安装必要的 NuGet 包并配置资源端点。

bash
dotnet add package Azure.AI.Agents.Persistent --prerelease
dotnet add package Azure.Identity
csharp
using Azure.AI.Agents.Persistent;
using Azure.Identity;

var projectEndpoint = Environment.GetEnvironmentVariable("PROJECT_ENDPOINT");
PersistentAgentsClient client = new(projectEndpoint, new DefaultAzureCredential());

2. 创建智能体与会话

定义 Agent 的角色指令并创建持久化线程。

csharp
// 创建 Agent
PersistentAgent agent = await client.Administration.CreateAgentAsync(
    model: "gpt-4o-mini",
    name: "Math Tutor",
    instructions: "You are a personal math tutor.",
    tools: [new CodeInterpreterToolDefinition()]
);

// 创建会话线程并发送消息
PersistentAgentThread thread = await client.Threads.CreateThreadAsync();
await client.Messages.CreateMessageAsync(thread.Id, MessageRole.User, "Help me solve 3x + 11 = 14");

3. 执行与状态轮询

启动 Run 任务并轮询状态直到完成。

csharp
ThreadRun run = await client.Runs.CreateRunAsync(thread.Id, agent.Id);

do
{
    await Task.Delay(500);
    run = await client.Runs.GetRunAsync(thread.Id, run.Id);
} while (run.Status == RunStatus.Queued || run.Status == RunStatus.InProgress);

4. 高级能力集成

  • 函数调用 (Function Calling):定义 FunctionToolDefinition,在 RunStatus.RequiresAction 时执行本地代码并回传结果。
  • 文件搜索 (File Search):上传文件至 Files 接口 创建 VectorStore 将其关联至 Agent 的 ToolResources
  • 外部检索:集成 BingGroundingToolDefinition 实现实时联网搜索。

下载和安装

下载 azure-ai-agents-persistent-dotnet 中文版 Skill ZIP

解压后将目录放入你的 AI 工具 skills 文件夹,重启工具后即可使用。具体路径参考内附的 USAGE.zh.md

你可能还需要

暂无推荐