MAF 实战入门指南1. MAF 框架简介2. 项目创建与配置2.1 项目初始化2.2 配置AI服务2.3 项目结构3. 核心组件解析3.1 Agent代理3.2 Workflow工作流3.3 工具集成3.4 服务注册与端点映射3.5 完整的项目代码4. 项目运行与测试4.1 启动应用4.2 使用 DevUI 测试4.3 使用API测试5. 实际应用场景6. 扩展与定制6.1 自定义Agent6.2 自定义工具6.3 集成其他AI服务7. 高级配置与最佳实践7.1 配置管理7.2 错误处理7.3 监控与日志8. 总结与展望9. 资源与参考1. MAF 框架简介Microsoft Agent Framework(简称MAF) 是微软推出的一个强大的AI代理开发框架它允许开发者轻松创建、部署和管理AI代理及其工作流程。MAF提供了一套简洁而强大的API使得构建复杂的AI应用变得更加容易。MAF的核心优势包括简化AI Agent / AI代理的创建和管理支持多种AI服务提供商GitHub Models、Azure OpenAI、OpenAI、Ollama等内置工作流引擎支持复杂的代理协作提供OpenAI兼容的API接口包含开发 UIDevUI便于测试和调试2. 项目创建与配置2.1 项目初始化使用Microsoft.Agents.AI.ProjectTemplates模板创建MAF项目非常简单安装MAF项目模板包dotnet newinstallMicrosoft.Agents.AI.ProjectTemplates1.0.0-preview.1.26160.2创建MAF默认项目# 创建默认项目使用GitHub Modelsdotnet new aiagent-webapi-nDemo.MAF.WebApi# 或指定其他AI服务提供商dotnet new aiagent-webapi-nDemo.MAF.WebApi--providerazureopenai2.2 配置AI服务默认项目使用GitHub Models作为AI服务提供商需要配置API令牌使用用户密钥推荐开发环境dotnet user-secretssetGITHUB_TOKENyour-github-models-token-here使用环境变量Windows (PowerShell)# Windows (PowerShell)$env:GITHUB_TOKEN your-github-models-token-hereLinux/macOS# Linux/macOSexportGITHUB_TOKENyour-github-models-token-here除了上面两种方式还可自行修改使用appsettings.json应用程序配置。2.3 项目结构创建的项目包含以下主要文件Program.cs- 应用程序入口点和配置appsettings.json- 应用程序配置Properties/launchSettings.json- 开发环境启动配置3. 核心组件解析3.1 Agent代理Agent是MAF的核心概念代表一个具有特定功能的AI实体。在示例项目中定义了两个Agent// 创建Writer Agentbuilder.AddAIAgent(writer,You write short stories (300 words or less) about the specified topic.);// 创建Editor Agentbuilder.AddAIAgent(editor,(sp,key)newChatClientAgent(chatClient,name:key,instructions:You edit short stories to improve grammar and style, ensuring the stories are less than 300 words. Once finished editing, you select a title and format the story for publishing.,tools:[AIFunctionFactory.Create(FormatStory)]));Agent可以通过两种方式创建简单方式直接提供名称和指令高级方式使用工厂方法可添加Tool工具和自定义配置3.2 Workflow工作流Workflow允许将多个Agent组合成一个序列实现复杂的任务处理// 创建Publisher工作流builder.AddWorkflow(publisher,(sp,key)AgentWorkflowBuilder.BuildSequential(workflowName:key,agents:[sp.GetRequiredKeyedServiceAIAgent(writer),sp.GetRequiredKeyedServiceAIAgent(editor)])).AddAsAIAgent(publisher-agent);这里创建了一个顺序工作流先使用writer agent生成故事然后使用editor agent编辑故事。3.3 工具集成MAF允许为Agent添加工具扩展其能力// 定义工具函数[Description(Formats the story for publication, revealing its title.)]stringFormatStory(stringtitle,stringstory)$**Title**:{title}{story};// 在创建Agent时添加工具builder.AddAIAgent(editor,(sp,key)newChatClientAgent(chatClient,name:key,instructions:You edit short stories to improve grammar and style...,tools:[AIFunctionFactory.Create(FormatStory)]));3.4 服务注册与端点映射MAF需要注册必要的服务并映射相应的端点// 注册OpenAI响应和对话服务builder.Services.AddOpenAIResponses();builder.Services.AddOpenAIConversations();// 映射端点app.MapOpenAIResponses();app.MapOpenAIConversations();// 开发环境映射DevUIif(builder.Environment.IsDevelopment()){app.MapDevUI();}3.5 完整的项目代码Demo.MAF.WebApi1.slnxSolutionProjectPathDemo.MAF.WebApi1.csproj//SolutionDemo.MAF.WebApi.csprojProjectSdkMicrosoft.NET.Sdk.WebPropertyGroupTargetFrameworknet10.0/TargetFrameworkNullableenable/NullableImplicitUsingsenable/ImplicitUsingsUserSecretsIdf3d8b192-2b5f-4b91-b3e6-aa10e0c3ac1a/UserSecretsId/PropertyGroupItemGroupPackageReferenceIncludeMicrosoft.Agents.AIVersion1.0.0-rc4/PackageReferenceIncludeMicrosoft.Agents.AI.DevUIVersion1.0.0-preview.260311.1/PackageReferenceIncludeMicrosoft.Agents.AI.HostingVersion1.0.0-preview.260311.1/PackageReferenceIncludeMicrosoft.Agents.AI.Hosting.OpenAIVersion1.0.0-alpha.260311.1/PackageReferenceIncludeMicrosoft.Agents.AI.OpenAIVersion1.0.0-rc4/PackageReferenceIncludeMicrosoft.Agents.AI.WorkflowsVersion1.0.0-rc4//ItemGroup/ProjectProgram.csusingSystem.ClientModel;usingSystem.ComponentModel;usingMicrosoft.Agents.AI;usingMicrosoft.Agents.AI.DevUI;usingMicrosoft.Agents.AI.Hosting;usingMicrosoft.Agents.AI.Workflows;usingMicrosoft.Extensions.AI;usingOpenAI;usingOpenAI.Chat;varbuilderWebApplication.CreateBuilder(args);// You will need to set the token to your own value// You can do this using Visual Studios Manage User Secrets UI, or on the command line:// cd this-project-directory// dotnet user-secrets set GITHUB_TOKEN your-github-models-token-herevarchatClientnewChatClient(gpt-4o-mini,newApiKeyCredential(builder.Configuration[GITHUB_TOKEN]??thrownewInvalidOperationException(Missing configuration: GITHUB_TOKEN)),newOpenAIClientOptions{EndpointnewUri(https://models.inference.ai.azure.com)}).AsIChatClient();builder.Services.AddChatClient(chatClient);builder.AddAIAgent(writer,You write short stories (300 words or less) about the specified topic.);builder.AddAIAgent(editor,(sp,key)newChatClientAgent(chatClient,name:key,instructions:You edit short stories to improve grammar and style, ensuring the stories are less than 300 words. Once finished editing, you select a title and format the story for publishing.,tools:[AIFunctionFactory.Create(FormatStory)]));builder.AddWorkflow(publisher,(sp,key)AgentWorkflowBuilder.BuildSequential(workflowName:key,agents:[sp.GetRequiredKeyedServiceAIAgent(writer),sp.GetRequiredKeyedServiceAIAgent(editor)])).AddAsAIAgent(publisher-agent);// Register services for OpenAI responses and conversations (also required for DevUI)builder.Services.AddOpenAIResponses();builder.Services.AddOpenAIConversations();varappbuilder.Build();app.UseHttpsRedirection();// Map endpoints for OpenAI responses and conversations (also required for DevUI)app.MapOpenAIResponses();app.MapOpenAIConversations();if(builder.Environment.IsDevelopment()){// Map DevUI endpoint to /devuiapp.MapDevUI();}awaitapp.RunAsync();[Description(Formats the story for publication, revealing its title.)]stringFormatStory(stringtitle,stringstory)$**Title**:{title}{story};4. 项目运行与测试4.1 启动应用dotnet run-lphttps应用将在以下地址运行HTTP:http://localhost:5275HTTPS:https://localhost:7167说明此处端口以实际创建项目为准。4.2 使用 DevUI 测试在开发环境中应用提供了DevUI界面可通过https://localhost:7167/devui/访问。DevUI提供了一个Web界面用于与Agent和工作流交互。4.3 使用API测试应用暴露了OpenAI兼容的API端点可以使用任何OpenAI兼容的客户端或工具进行交互。5. 实际应用场景MAF框架适用于多种AI应用场景内容创作如示例中的故事创作和编辑客户服务创建智能客服代理数据分析构建数据分析和可视化代理代码生成创建代码生成和审查代理多步骤任务处理通过工作流组合多个代理处理复杂任务6. 扩展与定制6.1 自定义Agent可以通过实现AIAgent接口创建自定义AgentpublicsealedclassMyCustomAgent:AIAgent{// 实现必要的方法}6.2 自定义工具可以创建更复杂的工具扩展Agent的能力[Description(执行复杂计算)]publicsealedclassCalculatorTool{publicintAdd(inta,intb)ab;publicintSubtract(inta,intb)a-b;// 其他方法...}6.3 集成其他AI服务MAF支持多种AI服务提供商可以根据需要切换// 使用Azure OpenAIvarchatClientnewAzureOpenAIClient(newUri(https://your-azure-openai-endpoint),newDefaultAzureCredential()).GetChatClient(your-deployment-name);7. 高级配置与最佳实践7.1 配置管理对于生产环境建议使用Azure Key Vault或其他安全的配置管理解决方案存储API密钥和其他敏感信息。7.2 错误处理在实际应用中应添加适当的错误处理try{// Agent调用}catch(Exceptionex){// 错误处理}7.3 监控与日志添加监控和日志记录以便跟踪Agent的性能和行为builder.Services.AddLogging(logging{logging.AddConsole();// 添加其他日志提供程序});8. 总结与展望Microsoft Agent Framework (MAF)为开发者提供了一个强大而灵活的平台用于构建和部署AI代理应用。通过简单的API和丰富的功能MAF使得创建复杂的AI工作流变得更加容易。随着AI技术的不断发展MAF也在持续进化未来将提供更多功能和集成选项。对于希望构建AI驱动应用的.NET 开发者来说MAF是一个值得学习和使用的框架。9. 资源与参考AI apps for .NET developersMAF DocumentationGitHub ModelsNuget MAFGithub MAF通过本文的介绍相信你已经对MAF有了基本的了解并可以开始构建自己的AI代理应用了。祝你在MAF的学习和使用过程中取得成功