首页 > 教程攻略 > ai教程 >从零开始玩转 Microsoft Agent Framework:我的 MAF 实践之旅

从零开始玩转 Microsoft Agent Framework:我的 MAF 实践之旅

来源:互联网 时间:2026-07-25 07:18:09

前言

业务代码写得再多,脑子也会发僵。趁着周末,翻了一下微软刚推出的智能体开发框架——Microsoft Agent Framework,简称MAF。跟着官方文档跑了几个案例,发现这东西确实有点意思。它不是那种传统的LLM SDK,而是一套面向开发者的完整工具链,支持多轮对话、函数调用、工具集成、可观测性这些高阶功能,底子打得挺扎实。

什么是 Microsoft Agent Framework?

概念层面的东西,没有必要重复造轮子,直接引用微软官方文档的定义,我用翻译软件顺手转了一下。说起这个框架,难免让人想到微软之前的两款产品:Semantic Kernel和AutoGen。简单来说,MAF可以理解为前面两个框架的整合版。官方文档里也对它们之间的关系做了说明,感兴趣的话可以自己去搜一下。如果你之前没接触过SK和AutoGen,那恭喜你,完全不用绕弯路,直接上手MAF就行。如果已经了解过,也不用觉得白费功夫——MAF正是基于这两者,有这些基础经验,上手会顺滑很多。笔者之前也分别写过关于SK和AutoGen的博客,这里不再展开。

上手案例

概念铺垫完了,直接上案例。官方文档其实写得很详细,但如果没接触过模型开发,或者对相关工具链不太熟悉,那个文档的门槛还是有点高。至少OpenAI或AzureOpenAI的访问问题,就得花不少时间折腾。事实上,在SK时期就存在这个问题,到了MAF时代,处理起来反而更直接了。这篇我照着文档跑了几个案例,逐一介绍。

基础框架

第一个案例,先跑一个最基础的框架搭建,看看整个架子怎么立起来。

  1. 创建一个控制台项目
dotnet new console -o AgentFrameworkQuickStart
  1. 引入核心插件。注意,MAF目前还是预览版,通过命令行引入时要加上--preview参数,在IDE(如VS)里,要记得勾选“预览版”选项。
dotnet add package Azure.AI.OpenAI --prerelease dotnet add package Microsoft.Agents.AI.OpenAI --prerelease

官方文档里还安装了Azure.Identity,这个我们可以不用——因为要接入国内平台的大模型,而且只是测试跑案例,暂时不需要它。

另外,我踩了个坑,记下来供大家参考。今天(2025.12.13)使用命令行安装的Azure.AI.OpenAI版本是2.8.1-beta.1,这个版本有问题,依赖的OpenAI包与上级包有冲突。我是在IDE里手动将版本号上移了一个版本(2.7.0-beta2)才解决。如果各位刚好遇到同样的问题,可以试试这个办法。

  1. 定义Provider

我这里用的是国内硅基流动平台,其他平台也可以。定义一个类:

public class ModelProvider { public string ApiKey { get; init; } = string.Empty; public string ModelId { get; init; } = string.Empty; public string Endpoint { get; init; } = string.Empty; }

对应的搞一个配置文件,测试阶段不搞也行,但这样方便一点:

{ "ModelProvider": { "EndPoint": "https://api.moonshot.cn/v1", "ApiKey": "{你的key}", "ModelId": "kimi-k2-0905-preview" } }

然后常规操作,就OK了:

var config = new ConfigurationBuilder() .AddJsonFile($"llm.json", optional: false, reloadOnChange: true) .Build(); var modelProvider = new ModelProvider() { ApiKey = config["ModelProvider:ApiKey"] ?? string.Empty, ModelId = config["ModelProvider:ModelId"] ?? string.Empty, Endpoint = config["ModelProvider:Endpoint"] ?? string.Empty, }; Console.WriteLine($"正在使用【{modelProvider.ModelId}】模型", ConsoleColor.Yellow);

第一个智能体

文档里第一个案例是一个笑话大师,咱们稍微改造一下:

var agent = new OpenAIClient( new ApiKeyCredential(modelProvider.ApiKey), new OpenAIClientOptions { Endpoint = new Uri(modelProvider.Endpoint) }) .GetChatClient(modelProvider.ModelId) .CreateAIAgent( instructions: "你是个脱口秀大师,可以很轻松的逗笑大家.", name: "脱口秀大师" ); await foreach (var update in agent.RunStreamingAsync("来一段简短的脱口秀表演")) { Console.Write(update); }

视觉智能体

接下来试试视觉能力。注意,这时候要换一个支持视觉的模型,前面用的kimi不支持,可以换成qwen系列:

var agent = new OpenAIClient( new ApiKeyCredential(modelProvider.ApiKey), new OpenAIClientOptions { Endpoint = new Uri(modelProvider.Endpoint) }) .GetChatClient(modelProvider.ModelId) .CreateAIAgent( instructions: "你是一个能够分析图像的实用助手。", name: "视觉袋里" ); ChatMessage message = new ChatMessage(ChatRole.User, [ new TextContent("你在这张图片中看到了什么?"), new UriContent("{图片实际地址}", "image/png") ]); // Console.WriteLine(await agent.RunAsync(message)); await foreach (var update in agent.RunStreamingAsync(message)) { Console.Write(update); }

Function Tool

这个例子我基本没动,直接拿来用:

var agent = new OpenAIClient( new ApiKeyCredential(modelProvider.ApiKey), new OpenAIClientOptions { Endpoint = new Uri(modelProvider.Endpoint) }) .GetChatClient(modelProvider.ModelId) .CreateAIAgent( instructions: "你是一个智能助手。", tools: [AIFunctionFactory.Create(GetWeather)] ); Console.WriteLine(await agent.RunAsync("保定的天气怎么样?")); [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.";

需要多说一句,定义工具函数时,不再需要像SK时代那样标记方法工具名特性,直接写工具作用的描述就行,更简洁了。工具调用在LLM发展初期就已经比较普及,这也是Agent的灵魂——让Agent不再只是“回答问题”,而是能像人一样去“执行动作”。

需要人批准的函数工具

这个功能挺关键,实际业务里,很多时候我们不能——或者不应该——让智能体直接执行操作,而是需要人类授权后再决定是否执行,也就是“人机协同”模式。案例给得比较简单,但可以在这个基础上扩充很多业务逻辑,比如权限模块等。它的价值在于实现安全可控的自动化流程,避免误操作。

AIFunction weatherFunction = AIFunctionFactory.Create(GetWeather); AIFunction approvalRequiredWeatherFunction = new ApprovalRequiredAIFunction(weatherFunction); var agent = new OpenAIClient( new ApiKeyCredential(modelProvider.ApiKey), new OpenAIClientOptions { Endpoint = new Uri(modelProvider.Endpoint) }) .GetChatClient(modelProvider.ModelId) .CreateAIAgent( instructions: "你是一个智能助手。", tools: [approvalRequiredWeatherFunction] ); AgentThread thread = agent.GetNewThread(); AgentRunResponse response = await agent.RunAsync("保定的天气如何?", thread); var functionApprovalRequests = response.Messages .SelectMany(x => x.Contents) .OfType() .ToList(); FunctionApprovalRequestContent requestContent = functionApprovalRequests.First(); Console.WriteLine($"我需要您的批准才能执行 '{requestContent.FunctionCall.Name}'"); var approvalMessage = new ChatMessage(ChatRole.User, [ requestContent.CreateResponse(true) ]); Console.WriteLine(await agent.RunAsync(approvalMessage, thread)); [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.";

将 Agent 暴露为 MCP 工具

通过MAF,可以轻松把Agent包装成一个MCP Server,然后在任意MCP客户端中注册这个工具,直接调用它。效果很丝滑,就像写接口一样简单:

var agent = new OpenAIClient( new ApiKeyCredential(modelProvider.ApiKey), new OpenAIClientOptions { Endpoint = new Uri(modelProvider.Endpoint) }) .GetChatClient(modelProvider.ModelId) .CreateAIAgent( instructions: "你是个笑话大师.", name: "笑话大师" ); var jokerMcpTool = McpServerTool.Create(agent.AsAIFunction()); var builder = Host.CreateEmptyApplicationBuilder(settings: null); builder.Services .AddMcpServer() .WithStdioServerTransport() .WithTools([jokerMcpTool]); await builder.Build().RunAsync();

然后在Cline中调用它的效果——

结语

跑完这几个案例,整体感觉不错。微软通过MAF提供了一条清晰的技术路径,让开发者能轻松构建属于自己的“智能助手”。接下来,会继续探索MAF,因为现在的项目也要接入智能体框架。这东西绝不是什么“锦上添花”的定位,而是办公效率提质增效的核心因素——当然,有个前提条件:你的业务系统里基础操作是稳定可靠的。基于这个基础,智能体的接入才能真正释放生产力。

这篇对MAF的介绍只是冰山一角,还有更有特点的工作流、AG-UI、DevUI等,下次有机会再细聊。晚安啦,攻城狮们。