资讯动态

Microsoft Agent Framework – AI 构建基石(第三部分)

发布时间:2026/8/4 18:45:06 来源:尧图企业网站定制
作者Jeremy Likness · 首席项目经理.NET AI 体验发布日期2026 年 5 月 4 日原文链接https://devblogs.microsoft.com/dotnet/microsoft-agent-framework-building-blocks-for-ai-part-3/欢迎回到 .NET AI 构建基石系列在第一部分[1]中我们介绍了 Microsoft Extensions for AIMEAI了解了它如何为与大型语言模型交互提供统一接口。在第二部分[2]中我们深入探讨了 Microsoft.Extensions.VectorData了解了它如何将语义搜索和 RAG 模式引入 .NET。今天我们要探索第三块构建基石Microsoft Agent Framework。到目前为止我们一直在打地基。MEAI 提供了与模型对话的通用方式VectorData 赋予了我们存储和检索知识的能力。但如果你想要一个能够真正做事情的 AI 呢不仅仅是回答问题而是采取行动、使用工具、在对话中记住上下文并与其他 Agent 协作解决复杂问题这正是 Agent 的用武之地。什么是 AI AgentAI Agent 不只是一个聊天机器人。聊天机器人接收输入将其传递给模型然后返回输出。而 Agent 则具有自主性。它能够对任务进行推理决定使用哪些工具调用这些工具评估结果并决定下一步该做什么——所有这些都无需你为每个场景编写明确的逐步指令。可以这样理解如果 MEAI 就像在和同事对话那么 Agent 就像是把一张待办事项清单交给那位同事让他自己想办法搞定。他可能会查阅资料、进行计算、查看天气、查询数据库用你提供给他的一切工具来完成任务。Microsoft Agent Framework[3]提供了一个生产就绪的 SDK用于在 .NET 中构建这些智能 Agent也支持 Python 等其他语言但这里我们专注于 C#。它于 2026 年 4 月发布了1.0 正式版支持从简单的单 Agent 场景到基于图的多 Agent 复杂工作流。你的第一个 Agent让我们从简单的开始。如果你用过 MEAI 或读过第一部分[1]Agent Framework 会让你感到熟悉因为它直接构建在IChatClient之上。创建一个控制台应用然后安装 Agent Frameworkdotnet add package Microsoft.Agents.AI创建一个 Agent 就是这么简单01_hello_agent[4]using Azure.AI.OpenAI; using Azure.Identity; using Microsoft.Agents.AI; var endpoint Environment.GetEnvironmentVariable(AZURE_OPENAI_ENDPOINT) ?? throw new InvalidOperationException(AZURE_OPENAI_ENDPOINT is not set.); var deploymentName Environment.GetEnvironmentVariable(AZURE_OPENAI_DEPLOYMENT_NAME) ?? gpt-5.4-mini; AIAgent agent new AzureOpenAIClient( new Uri(endpoint), new DefaultAzureCredential()) .GetChatClient(deploymentName) .AsAIAgent( instructions: You are good at telling jokes., name: Joker); Console.WriteLine(await agent.RunAsync(Tell me a joke about a pirate.));注意.AsAIAgent()扩展方法。就像.AsIChatClient()将提供商的 SDK 桥接到 MEAI 抽象层一样.AsAIAgent()更进一步将其包装成一个能够管理会话、工具和记忆的 Agent。这适用于多种提供商包括 Azure OpenAI、OpenAI、GitHub Models、Microsoft Foundry甚至是通过 Foundry Local 或 Ollama 运行的本地模型。Agent 也支持开箱即用的流式输出await foreach (var update in agent.RunStreamingAsync(Tell me a joke about a pirate.)) { Console.Write(update); }为 Agent 配备工具一个会讲笑话的 Agent 很有趣但当你给 Agent 配备工具时它才会真正强大起来。工具本质上是一些函数模型可以根据用户的请求决定是否调用它们。Agent Framework 使用了与 MEAI 相同的AIFunctionFactory所以如果你已经为聊天客户端定义了工具这里同样适用。下面是一个带有天气工具的 Agent02_add_tools[5]using System.ComponentModel; using Microsoft.Agents.AI; using Microsoft.Extensions.AI; [Description(Get the weather for a given location.)] static string GetWeather( [Description(The location to get the weather for.)] string location) $The weather in {location} is cloudy with a high of 15°C.; AIAgent agent new AzureOpenAIClient( new Uri(endpoint), new DefaultAzureCredential()) .GetChatClient(deploymentName) .AsAIAgent( instructions: You are a helpful assistant, tools: [AIFunctionFactory.Create(GetWeather)]); Console.WriteLine(await agent.RunAsync(What is the weather like in Amsterdam?));当用户询问天气时Agent 不会凭空猜测而是识别出自己拥有一个GetWeather工具用合适的参数调用它并利用返回结果来组织回答。你不需要编写任何如果用户问天气就调用这个函数的逻辑模型自己会搞定。Description特性非常重要它们告诉模型这个工具是做什么的每个参数的含义是什么帮助它决定何时以及如何使用该工具。可以把它们看作是 AI 的工具使用说明书。使用 Session 实现多轮对话真实的对话不会在单次交换中完成。用户会追问、提供额外上下文并期望 Agent 记住之前讨论的内容。Agent Framework 通过AgentSession来处理这个问题03_multi_turn[6]AgentSession session await agent.CreateSessionAsync(); Console.WriteLine( await agent.RunAsync(Tell me a joke about a pirate., session)); Console.WriteLine( await agent.RunAsync( Now add some emojis to the joke and tell it in the voice of a pirates parrot., session));Session 会在多次调用之间保留对话历史。当用户说给这个笑话加上一些表情符号时Agent 知道指的是哪个笑话因为 Session 维护了上下文。Session 还支持序列化和反序列化这对于在无状态服务中运行 Agent 的生产场景至关重要// Save the session state JsonElement sessionState await agent.SerializeSessionAsync(session); // Later, restore it var restoredSession await agent.DeserializeSessionAsync(sessionState); Console.WriteLine( await agent.RunAsync(What were we just talking about?, restoredSession));让 Agent 拥有记忆Session 保留的是对话历史但更长期的记忆呢如果你希望 Agent 在多个 Session 之间记住有关用户的信息——比如他们的名字、偏好或过往交互记录——该怎么做Agent Framework 提供了AIContextProvider这是一种将上下文信息注入 Agent 工作流的机制。以下是记忆示例的简化版本04_memory[7]它能提取并记住用户信息internal sealed class UserInfoMemory : AIContextProvider { private readonly ProviderSessionStateUserInfo _sessionState; private readonly IChatClient _chatClient; public UserInfoMemory(IChatClient chatClient) { _sessionState new ProviderSessionStateUserInfo( _ new UserInfo(), GetType().Name); _chatClient chatClient; } protected override async ValueTask StoreAIContextAsync( InvokedContext context, CancellationToken cancellationToken default) { var userInfo _sessionState.GetOrInitializeState(context.Session); if (userInfo.UserName is null context.RequestMessages.Any(x x.Role ChatRole.User)) { var result await _chatClient.GetResponseAsyncUserInfo( context.RequestMessages, new ChatOptions() { Instructions Extract the users name from the message if present. }, cancellationToken: cancellationToken); userInfo.UserName ?? result.Result.UserName; } _sessionState.SaveState(context.Session, userInfo); } protected override ValueTaskAIContext ProvideAIContextAsync( InvokingContext context, CancellationToken cancellationToken default) { var userInfo _sessionState.GetOrInitializeState(context.Session); var instructions userInfo.UserName is null ? Ask the user for their name. : $The users name is {userInfo.UserName}.; return new ValueTaskAIContext( new AIContext { Instructions instructions }); } }AIContextProvider有两个关键方法•StoreAIContextAsync在每次交互之后执行是 Agent 从刚刚发生的事情中学习的机会——在这个例子中从对话中提取用户的名字。•ProvideAIContextAsync在每次交互之前执行向 Agent 提供额外的上下文——在这里要么告诉 Agent 用户的名字要么指示它先询问用户的名字。在创建 Agent 时将其连接起来AIAgent agent chatClient.AsAIAgent(new ChatClientAgentOptions() { ChatOptions new() { Instructions You are a friendly assistant. Always address the user by their name. }, AIContextProviders [new UserInfoMemory(chatClient.AsIChatClient())] });这个模式非常强大因为它将Agent 记住什么和Agent 如何对话分离开来。你可以叠加多个上下文提供者——一个负责用户偏好另一个负责最近的交互第三个从你的 VectorData 存储中拉取相关文档。工作流协调多个 Agent单个 Agent 很有用但许多现实问题可以通过将工作分配给多个专用 Agent 来更好地解决。Agent Framework 提供了一个基于图的工作流系统你可以将执行器处理单元和边数据流路径连接起来。下面是一个将两个文本处理器串联在一起的简单工作流05_first_workflow[8]using Microsoft.Agents.AI.Workflows; Funcstring, string uppercaseFunc s s.ToUpperInvariant(); var uppercase uppercaseFunc.BindAsExecutor(UppercaseExecutor); var reverse new ReverseTextExecutor(); WorkflowBuilder builder new(uppercase); builder.AddEdge(uppercase, reverse).WithOutputFrom(reverse); var workflow builder.Build(); await using Run run await InProcessExecution.RunAsync( workflow, Hello, World!); foreach (WorkflowEvent evt in run.NewEvents) { if (evt is ExecutorCompletedEvent executorComplete) { Console.WriteLine( ${executorComplete.ExecutorId}: {executorComplete.Data}); } }文本处理的例子保持了简单但当你把 Agent 作为执行器时工作流的真正威力才会显现。以下是框架支持的一些模式•顺序工作流——Agent 依次处理每个 Agent 的输出作为下一个 Agent 的输入•并发工作流——扇出到多个并行 Agent然后将结果汇总•条件路由交接——根据前一步的输出动态地将工作路由给不同的 Agent•反馈循环——写手-评审模式一个 Agent 负责生产内容另一个评估内容循环直到满足质量标准•子工作流——通过将一个工作流嵌入另一个工作流来进行层次化组合作家-评审家示例最实用的模式之一是创作-评审工作流。设想你有一个撰写营销文案的 Agent 和另一个负责质量审核的 AgentWorkflowBuilder builder new(writerAgent); builder .AddEdge(writerAgent, criticAgent) .AddEdge(criticAgent, writerAgent, condition: result !result.IsApproved) .WithOutputFrom(criticAgent, condition: result result.IsApproved); var workflow builder.Build();写手产出草稿评审者进行评估如果未获批准草稿返回给作者进行修改。这个循环会持续下去直到评审者满意为止。当然出于安全考虑你可能需要设置最大迭代次数。人机协作AI 并不能取代人类很多时候也需要人工输入。把 Agent 想象成由人类通过代码指挥的专业工作者。Agent Framework 支持工具审批工作流即 Agent 提议调用某个工具并在执行前等待人工审批。对于涉及敏感操作的生产场景——例如数据库写入、金融交易或发送通信——这一点至关重要。审批机制构建在FunctionApprovalRequestContent和FunctionApprovalResponseContent之上这些内容类型是我们在第一部分介绍的 MEAI 内容模型的一部分。当 Agent 想要调用一个需要审批的工具时它会发出一个请求并等待。你的应用代码可以将这个请求呈现给用户而用户的响应决定该工具调用是否继续执行。整合起来构建基石方法的美妙之处在于每个组件都能自然地与其他组件组合。以下是它们的协作方式1.MEAIIChatClient提供基础——与任何模型交互的通用接口。2.VectorData实现 RAG 模式——你的 Agent 可以通过语义搜索检索组织知识库将响应建立在你的数据之上。3.Agent Framework统筹全局——Agent 在底层使用IChatClient可以通过上下文提供者整合向量搜索并通过工作流进行协调。例如你可以构建一个AIContextProvider在每次 Agent 调用之前搜索你的 VectorData 存储将相关文档作为额外上下文提供——就像第二部分中的 RAG 模式一样只不过现在它会作为每次 Agent 交互的一部分自动运行。总结Microsoft Agent Framework 将第一部分和第二部分的基础元素转化为能够独立工作或在复杂工作流中协同合作的、具有自主性、可使用工具且拥有记忆的 Agent。本文涵盖了以下内容•创建 Agent使用AsAIAgent()创建 Agent并通过RunAsync()运行•配备工具使用AIFunctionFactory和Description特性为 Agent 配备工具•管理对话使用AgentSession跨轮次管理对话•构建记忆使用AIContextProvider实现跨 Session 的持久知识•编排工作流使用执行器、边以及写手-评审循环等模式•人机协作针对敏感操作的人工审批机制在下一篇也是最后一篇文章中我们将探索模型上下文协议MCP以及它如何为 Agent 提供一种标准化的方式来发现和使用外部工具和资源——让你的 Agent 与更广泛的 AI 生态系统实现互操作。资源通过代码学习• Agent Framework 代码仓库[9]• Agent Framework 示例[10]通过教程学习• Agent Framework 文档[11]• 快速入门指南[12]• 从 Semantic Kernel 迁移[13]通过视频学习• Agent Framework 介绍30 分钟[14]• DevUI 实战演示[15]祝编码愉快引用链接[1]第一部分:https://devblogs.microsoft.com/dotnet/dotnet-ai-essentials-the-core-building-blocks-explained/[2]第二部分:https://devblogs.microsoft.com/dotnet/vector-data-in-dotnet--building-blocks-for-ai-part-2/[3]Microsoft Agent Framework:https://github.com/microsoft/agent-framework[4]01_hello_agent:https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/01-get-started/01_hello_agent/Program.cs[5]02_add_tools:https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/01-get-started/02_add_tools/Program.cs[6]03_multi_turn:https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/01-get-started/03_multi_turn/Program.cs[7]04_memory:https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/01-get-started/04_memory/Program.cs[8]05_first_workflow:https://github.com/microsoft/agent-framework/blob/main/dotnet/samples/01-get-started/05_first_workflow/Program.cs[9]Agent Framework 代码仓库:https://github.com/microsoft/agent-framework/tree/main/dotnet[10]Agent Framework 示例:https://github.com/microsoft/Agent-Framework-Samples[11]Agent Framework 文档:https://learn.microsoft.com/agent-framework/[12]快速入门指南:https://learn.microsoft.com/agent-framework/tutorials/quick-start[13]从 Semantic Kernel 迁移:https://learn.microsoft.com/agent-framework/migration-guide/from-semantic-kernel[14]Agent Framework 介绍30 分钟:https://www.youtube.com/watch?vAAgdMhftj8w[15]DevUI 实战演示:https://www.youtube.com/watch?vmOAaGY4WPvc

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价