# MicrosoftAgentFrameworkLearning **Repository Path**: haoasq/microsoft-agent-framework-learning ## Basic Information - **Project Name**: MicrosoftAgentFrameworkLearning - **Description**: Microsoft Agent Framework 的入门学习案列,代码参照了微信公众号EdisonTalk,MAF使用最新版本号1.1.0。 - **Primary Language**: C# - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 1 - **Created**: 2026-04-21 - **Last Updated**: 2026-05-01 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # AI Agent App 本项目是一个基于 Microsoft.Agents.AI v1.3.0 的学习示例库,代码参照微信公众号 EdisonTalk,展示了如何使用该框架构建各种 AI 工作流和代理应用。 ## 项目结构 ``` AIAgnetApp/ ├── AIAgnetApp/ # 控制台应用程序 - 工作流示例 │ ├── Executors/ # 各类执行器实现 │ ├── Workflows/ # 工作流定义 │ ├── ConditionalWorkflow/ # 条件工作流模型 │ ├── ConditionalWorkflowSwitch/ # Switch 条件工作流模型 │ ├── WorkflowFan/ # Fan-out/Fan-in 工作流模型 │ ├── WorkflowLoop/ # 循环工作流模型 │ ├── WorkflowState/ # 状态管理模型 │ ├── WorklfowSub/ # 子工作流模型 │ ├── Persisted/ # 持久化存储 │ ├── Providers/ # 服务提供者 │ └── ToolApproval/ # 工具审批示例 │ ├── AIWebApp/ # Web API 应用程序 - A2A Agent 示例 │ ├── Agents/ # Agent 实现 │ │ ├── HotelAgent.cs # 酒店预订代理 │ │ ├── PlanAgent.cs # 行程规划代理 │ │ └── WeatherAgent.cs # 天气查询代理 │ ├── Extensions/ # 扩展方法 │ │ ├── RegisterAgent.cs # Agent 注册扩展方法 │ │ ├── Agent2Function.cs # Agent 转换为 AIFunction 工具 │ │ └── AgentFunctionHelper.cs # Agent Function 辅助类 │ ├── Controllers/ # API 控制器 │ └── Models/ # 数据模型 │ ├── AGUIApp/ # Web 应用程序 - AG-UI 服务端示例 │ ├── Program.cs # AG-UI 服务端配置 │ └── OpenAIProvider.cs # OpenAI 配置提供者 │ ├── AGUIConsoleApp/ # 控制台应用程序 - AG-UI 客户端示例 │ └── Program.cs # AG-UI 客户端实现 │ ├── AGUIToolsApp/ # Web 应用程序 - AG-UI 混合工具服务端示例 │ ├── Program.cs # AG-UI 服务端配置(含后端工具) │ ├── BackendTools.cs # 后端工具定义 │ └── OpenAIProvider.cs # OpenAI 配置提供者 │ ├── AGUIToolConsoleApp/ # 控制台应用程序 - AG-UI 混合工具客户端示例 │ ├── Program.cs # AG-UI 客户端实现(含前端工具) │ └── FrontendTools.cs # 前端工具定义 │ ├── DevUIApp/ # Web 应用程序 - DevUI 开发者界面示例 │ ├── Program.cs # DevUI 配置与多 Agent 注册 │ └── OpenAIProvider.cs # OpenAI 配置提供者 │ ├── SkillConsoleApp/ # 控制台应用程序 - Agent Skills 示例 │ ├── Program.cs # 主程序入口 │ ├── OpenAIProvider.cs # OpenAI 配置提供者 │ ├── ShellTools.cs # Shell 工具定义 │ ├── SkillToolTest.cs # Skills 工具测试 │ ├── TravelSkillTest.cs # 差旅 Skills 测试 │ └── Skills/ # Skills 定义目录 │ ├── expense-report/ # 费用报销 Skill │ │ ├── SKILL.md # Skill 定义文件 │ │ ├── assets/ # 资源文件 │ │ │ └── expense-report-template.md # 报销模板 │ │ └── references/ # 参考文档 │ │ └── POLICY_FAQ.md # 政策 FAQ │ ├── travel-policy/ # 差旅政策 Skill │ │ └── SKILL.md # Skill 定义文件 │ └── system-ops/ # 系统运维 Skill │ ├── SKILL.md # Skill 定义文件 │ ├── references/ # 参考文档 │ │ └── troubleshooting-guide.md # 故障排查指南 │ └── scripts/ # 可执行脚本 │ ├── check-disk-usage.ps1 # 磁盘使用检查 │ ├── check-system-info.ps1 # 系统信息检查 │ └── check-top-processes.ps1 # 进程监控 │ ├── SkillScriptConsoleApp/ # 控制台应用程序 - Agent Skills 脚本执行示例 │ ├── Program.cs # 主程序入口 │ ├── OpenAIProvider.cs # OpenAI 配置提供者 │ ├── SubprocessScriptRunner.cs # 子进程脚本运行器 │ └── Skills/ # Skills 定义目录 │ └── unit-converter/ # 单位换算 Skill │ ├── SKILL.md # Skill 定义文件 │ ├── references/ # 参考文档 │ │ └── conversion-table.md # 换算系数表 │ └── scripts/ # 可执行脚本 │ └── convert.py # 单位换算脚本 │ ├── SkillCSharpConsoleApp/ # 控制台应用程序 - 强类型 Skills 示例 │ ├── Program.cs # 主程序入口 │ ├── OpenAIProvider.cs # OpenAI 配置提供者 │ ├── UnitConverterSkill.cs # 强类型 Skill 定义(类方式) │ └── ToolExecutionLoggingMiddleware.cs # 工具执行日志中间件 │ ├── DeclarativeAgent/ # 控制台应用程序 - 声明式 Agent 示例 │ ├── Program.cs # 主程序入口 │ ├── OpenAIProvider.cs # OpenAI 配置提供者 │ ├── CustomerSupportAgent.prompt.yml # Agent YAML 定义文件 │ └── CustomerSupportResponse.cs # 响应模型定义 │ ├── SkillsMultiConsoleApp/ # 控制台应用程序 - 多源 Skills 与角色过滤示例 │ ├── Program.cs # 主程序入口 │ ├── OpenAIProvider.cs # OpenAI 配置提供者 │ ├── CachingSkillsSource.cs # 带缓存的 Skills Source │ ├── SimulatedLocalApiSkillsFactory.cs # 模拟本地 API Skills 工厂 │ ├── SimulatedRemoteApiSkillsSource.cs # 模拟远程 API Skills Source │ ├── UserRoleHelper.cs # 用户角色过滤辅助类 │ └── Models/ # 数据模型 │ ├── EmployeeRole.cs # 员工角色枚举 │ └── SkillApiEntry.cs # Skill API 条目模型 │ └── File-Based/ # 单文件应用程序 - Agent Skills 最简示例 ├── Main.cs # 主程序(dotnet script 格式) ├── appsettings.json # 配置文件 └── Skills/ # Skills 定义目录 ├── expense-report/ # 费用报销 Skill │ ├── Skill.md # Skill 定义文件 │ ├── assets/ # 资源文件 │ │ └── expense-report-template.md # 报销模板 │ └── references/ # 参考文档 │ └── POLICY_FAQ.md # 政策 FAQ └── travel-policy/ # 差旅政策 Skill └── SKILL.md # Skill 定义文件 ``` ## 项目简介 该项目通过多个实际示例演示了 Microsoft Agent Framework 的核心功能,包括: - **条件工作流**:根据 AI 判断结果动态选择不同的处理路径 - **检测工作流**:识别恶意输入(如越狱攻击) - **状态管理**:跨步骤共享数据和聚合结果 - **工具审批**:多人协作的部署审批流程 - **持久化存储**:保存对话历史和向量存储 - **子工作流**:将复杂流程拆分为可复用的子工作流模块 - **A2A Agent**:Agent-to-Agent 通信协议实现 - **AG-UI**:基于 HTTP 的 Agent-UI 通信协议,支持流式响应 - **AG-UI 混合工具**:前端工具(客户端执行)与后端工具(服务端执行)的协同调用 - **DevUI**:开发者调试界面,支持多 Agent 交互和工作流测试 - **Agent Skills**:基于文件系统的 Skills 加载与管理,支持动态扩展 AI Agent 能力 - **Agent Skills 脚本执行**:支持 AI Agent 自动调用外部脚本(Python、PowerShell 等)完成任务 - **强类型 Skills**:使用 C# 类定义 Skills,提供编译时类型安全和更好的 IDE 支持 - **多源 Skills**:支持从多个来源(本地、远程 API)加载 Skills,支持缓存、优先级覆盖和角色过滤 - **声明式 Agent**:使用 YAML 文件定义 Agent 配置,包括指令、模型参数和输出 Schema ## 核心组件 ### 1. 执行器 (Executors) | 执行器 | 功能描述 | |--------|-----------| | `SpamDetectionExecutor` | 垃圾邮件检测 | | `EmailAssistantExecutor` | 邮件助手处理 | | `EmailSendingExecutor` | 邮件发送执行器 | | `SpamHandlingExecutor` | 垃圾邮件处理执行器 | | `UncertainHandlingExecutor` | 不确定情况处理执行器 | | `JailbreakDetectExecutor` | 越狱攻击检测 | | `SloganWriterExecutor` | 标语生成(含反馈循环) | | `AggregationExecutor` | 文件统计聚合 | | `AdaptiveReplyDraftExecutor` | 自适应回复草稿生成 | | `AdaptiveQualityCheckExecutor` | 自适应质量检测 | | `IntelligentImproveExecutor` | 智能改进执行器 | | `PriceQueryStartExecutor` | 价格查询启动执行器(Fan-out) | | `PlatformPriceExecutor` | 平台价格查询执行器 | | `PricingStrategyExecutor` | 定价策略汇总执行器(Fan-in) | | `ComplaintClassifierExecutor` | 投诉分类执行器 | | `ProductEvaluationExecutor` | 产品评估执行器 | | `ReturnPolicyExecutor` | 退货政策执行器 | | `AIResponseGeneratorExecutor` | AI 响应生成执行器 | | `LogisticsTrackingExecutor` | 物流跟踪执行器 | | `DelayAnalysisExecutor` | 延迟分析执行器 | | `ComplianceCheckExecutor` | 合规检查执行器 | | `SentimentAnalysisExecutor` | 情绪分析执行器 | ### 2. 工作流模式 - **ConditionalWorkflow**: 条件分支工作流 - **ConditionalWorkflowSwitch**: Switch 条件工作流 - **DetectionExecutor**: 检测工作流 - **SloganExecutor**: 标语生成工作流 - **StateExecutor**: 状态管理工作流 - **WorkflowEvent**: 工作流事件 - **WorkflowLoop**: 循环工作流(客服回复优化) - **WorkflowFan**: Fan-out/Fan-in 工作流(多平台价格查询) - **WorkflowSub**: 子工作流(投诉处理流水线) ### 3. A2A Agents AIWebApp 项目包含三个 A2A (Agent-to-Agent) 代理示例: | Agent | 功能描述 | |-------|-----------| | `WeatherAgent` | 天气查询代理 - 提供城市天气预报和穿衣建议 | | `HotelAgent` | 酒店预订代理 - 推荐不同档次的酒店选择 | | `PlanAgent` | 行程规划代理 - 推荐景点和旅游路线 | ### 4. AIWebApp 扩展组件 AIWebApp 项目包含以下扩展组件: | 组件 | 功能描述 | |------|-----------| | `RegisterAgent` | 提供 `AddWeatherAgent`、`AddHotelAgent`、`AddPlanAgent` 扩展方法,用于注册 Agent 端点 | | `Agent2Function` | 将 A2A Agent 转换为 `AIFunction` 工具列表,支持 Agent 间调用 | | `AgentFunctionHelper` | 根据 `AgentCard` 创建 `AIFunction` 工具的辅助类 | ### 5. 代理工厂 `FunctionAgentFactory` 提供了多种预设代理创建方法: - 邮件助手 (`CreateEmailAssistantAgent`) - 垃圾邮件检测 (`CreateSpamDetectionAgent`) - 订单处理 (`CreateOrderAgent`) - 数学导师 (`CreateMathTutorAgent`) - 作家/编辑 (`CreateWriterAgent` / `CreateEditorAgent`) - QA 工程师 (`CreateQAEngineerAgent`) - DevOps 工程师 (`CreateDevopsEngineerAgent`) ### 6. AG-UI 应用 AGUIApp 和 AGUIConsoleApp 项目展示了 AG-UI (Agent-UI) 协议的实现: | 项目 | 类型 | 功能描述 | |------|------|-----------| | `AGUIApp` | Web 服务端 | AG-UI 服务端实现,提供 HTTP 端点供客户端连接 | | `AGUIConsoleApp` | 控制台客户端 | AG-UI 客户端实现,支持流式对话交互 | **AG-UI 特点**: - 基于 HTTP 的 Agent-UI 通信协议 - 支持流式响应 (Streaming Response) - 简单易用的客户端 API - 支持会话管理 ### 7. AG-UI 混合工具 AGUIToolsApp 和 AGUIToolConsoleApp 项目展示了 AG-UI 混合工具(前端+后端工具)的实现: | 项目 | 类型 | 功能描述 | |------|------|-----------| | `AGUIToolsApp` | Web 服务端 | AG-UI 服务端,注册后端工具(搜索餐厅、获取详情) | | `AGUIToolConsoleApp` | 控制台客户端 | AG-UI 客户端,注册前端工具(获取位置、用户偏好) | **混合工具特点**: - **前端工具**:在客户端执行,可访问客户端资源(如用户位置、本地存储) - **后端工具**:在服务端执行,可访问服务端资源(如数据库、外部 API) - **协同调用**:AI Agent 可同时调用前端和后端工具,实现端到端功能 **示例场景**: ``` 用户: "附近有什么餐厅?" ↓ AI Agent 调用前端工具: GetUserLocation() → 获取用户位置 ↓ AI Agent 调用后端工具: SearchNearbyRestaurants(location) → 搜索附近餐厅 ↓ 返回餐厅列表给用户 ``` ### 8. DevUI 开发者界面 DevUIApp 项目提供了一个开发者调试界面: | Agent | 功能描述 | |-------|-----------| | `Assistant` | 通用助手 - 回答问题简洁准确 | | `Poet` | 诗人 - 使用优美的诗篇回答请求 | | `Coder` | 程序员 - 协助解决编程问题,提供代码示例 | | `Writer` | 写作者 - 善于回答各种问题 | | `Reviewer` | 审阅者 - 审阅并评价回复 | **DevUI 特点**: - 内置多 Agent 交互界面 - 支持工作流可视化测试 - 提供 OpenAI Responses 和 Conversations API - 适合开发和调试 Agent 应用 ### 9. Agent Skills SkillConsoleApp 和 File-Based 项目展示了 Agent Skills 的使用方式: | Skill | 功能描述 | |-------|-----------| | `expense-report` | 费用报销 - 处理员工费用报销申请,包含报销规则、收据要求、审批流程 | | `travel-policy` | 差旅政策 - 处理差旅预订与审批,包含航班、酒店、租车等政策指引 | | `system-ops` | 系统运维 - 系统健康检查、性能监控、故障排查等运维操作 | ### 10. Agent Skills 脚本执行 SkillScriptConsoleApp 项目展示了 Agent Skills 的脚本执行能力: | Skill | 功能描述 | |-------|-----------| | `unit-converter` | 单位换算 - 在常见单位之间进行转换(英里/公里、磅/千克等) | **Skills 目录结构**: ``` Skills/ └── unit-converter/ # 单位换算 Skill ├── SKILL.md # Skill 定义(名称、描述、使用方法) ├── references/ # 参考文档 │ └── conversion-table.md # 换算系数表 └── scripts/ # 可执行脚本 └── convert.py # 单位换算脚本 ``` **脚本执行特点**: - 支持通过 `SubprocessScriptRunner` 执行外部脚本 - AI Agent 可自动调用脚本完成计算任务 - 脚本输出直接返回给 Agent 进行处理 - 支持多种脚本语言(Python、JavaScript、Bash、PowerShell) **SubprocessScriptRunner 支持的脚本类型**: | 扩展名 | 解释器 | 说明 | |--------|--------|------| | `.py` | `python3` | Python 脚本 | | `.js` | `node` | JavaScript 脚本 | | `.sh` | `bash` | Bash Shell 脚本 | | `.ps1` | `pwsh` | PowerShell 脚本 | **自定义脚本运行器**: ```csharp // SubprocessScriptRunner 核心实现 public static async Task RunAsync( AgentFileSkill skill, AgentFileSkillScript script, AIFunctionArguments arguments, CancellationToken cancellationToken) { // 根据脚本扩展名选择解释器 string? interpreter = extension switch { ".py" => "python3", ".js" => "node", ".sh" => "bash", ".ps1" => "pwsh", _ => null, }; // 启动子进程执行脚本 // 将参数传递给脚本 // 返回脚本输出结果 } ``` **示例场景**: ``` 用户: "马拉松比赛的距离26.2英里是多少公里?" ↓ AI Agent 调用: load_skill("unit-converter") ↓ AI Agent 读取: references/conversion-table.md (获取换算系数) ↓ AI Agent 执行: scripts/convert.py --value 26.2 --factor 1.60934 ↓ 返回结果: 42.195 公里 ``` ### 11. 强类型 Skills SkillCSharpConsoleApp 项目展示了使用 C# 类定义 Skills 的方式: **强类型 Skill 定义**: ```csharp internal sealed class UnitConverterSkill : AgentClassSkill { public override AgentSkillFrontmatter Frontmatter { get; } = new( "unit-converter", "Convert between common units using multiplication factors."); protected override string Instructions => """ 当用户询问距离或重量换算时: 1. 先读取 conversion-table 资源,找到对应换算系数。 2. 再调用 convert 脚本执行计算,参数为用户输入的数值value和换算系数factor。 3. 回复内容需要清晰地展示换算系数、换算过程和换算结果。 """; [AgentSkillResource("conversion-table")] [Description("常见距离与重量换算系数表。")] public string ConversionTable => """ # Conversion Table | From | To | Factor | |------------|------------|----------| | miles | kilometers | 1.60934 | | kilometers | miles | 0.621371 | | pounds | kilograms | 0.453592 | | kilograms | pounds | 2.20462 | """; [AgentSkillScript("convert")] [Description("按 value × factor 执行换算,并返回 JSON。")] public static string ConvertUnits(double value, double factor) { double result = Math.Round(value * factor, 4); return JsonSerializer.Serialize(new { value, factor, result }); } } ``` **强类型 Skills 特点**: - 使用 C# 类定义 Skill,提供编译时类型安全 - 通过特性(Attribute)标注资源和脚本方法 - 支持 IDE 智能提示和重构 - 资源和方法都在同一个类中,便于维护 - 脚本方法直接在进程内执行,无需外部解释器 **强类型 Skill 与文件型 Skill 对比**: | 特性 | 文件型 Skill | 强类型 Skill | |------|-------------|-------------| | 定义方式 | SKILL.md 文件 | C# 类继承 `AgentClassSkill` | | 资源定义 | references/ 目录 | `[AgentSkillResource]` 特性标注属性 | | 脚本定义 | scripts/ 目录 | `[AgentSkillScript]` 特性标注方法 | | 脚本执行 | 子进程调用外部解释器 | 进程内直接调用 C# 方法 | | 类型安全 | 无(运行时解析) | 编译时类型检查 | | IDE 支持 | 无 | 完整智能提示、重构支持 | | 适用场景 | 动态加载、非开发人员维护 | 开发人员维护、高性能场景 | **AgentClassSkill 核心成员**: | 成员 | 类型 | 说明 | |------|------|------| | `Frontmatter` | 属性 | Skill 元数据(名称、描述) | | `Instructions` | 属性 | Skill 指令文本 | | `[AgentSkillResource]` | 特性 | 标注资源属性 | | `[AgentSkillScript]` | 特性 | 标注脚本方法 | **使用方式**: ```csharp // 创建强类型 Skill 实例 var skillsProvider = new AgentSkillsProvider(new UnitConverterSkill()); // 创建 Agent 并注入 SkillsProvider AIAgent agent = chatClient.AsAIAgent(new ChatClientAgentOptions { Name = "UnitConverterAgent", ChatOptions = new() { Instructions = "..." }, AIContextProviders = [skillsProvider], }); // 可选:添加工具执行日志中间件 agent = agent.AsBuilder() .Use(ToolExecutionLoggingMiddleware.ExecuteAsync) .Build(); ``` ### 12. 多源 Skills 与角色过滤 SkillsMultiConsoleApp 项目展示了多源 Skills 加载、缓存、优先级覆盖和角色过滤: **核心概念**: | 概念 | 说明 | |------|------| | `AgentSkillsSource` | Skills 来源抽象基类,可自定义实现 | | `AgentSkillsProviderBuilder` | Builder 模式构建 Provider,支持链式配置 | | 多源合并 | 多个 Source 按"先注册优先"原则合并 | | 角色过滤 | 根据用户角色动态过滤可见 Skills | **多源 Skills 架构**: ``` ┌─────────────────────────────────────────────────────────────────────┐ │ AgentSkillsProviderBuilder │ │ │ │ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │ │ │ 本地定制 Skills │ │ 远程 API Skills │ │ 缓存装饰器 │ │ │ │ (LocalFactory) │───→│ (RemoteSource) │───→│ (CachingSource) │ │ │ │ 优先级最高 │ │ 全局技能库 │ │ TTL: 60分钟 │ │ │ └─────────────────┘ └─────────────────┘ └─────────────────┘ │ │ │ │ │ │ └──────────────── UseSkills() ─────────────────┘ │ │ UseSource() │ │ UseFilter() │ │ UsePromptTemplate() │ └─────────────────────────────────────────────────────────────────────┘ ↓ ┌─────────────────────┐ │ AgentSkillsProvider │ │ (按角色过滤输出) │ └─────────────────────┘ ``` **自定义 Skills Source 实现**: ```csharp // 远程 API Skills Source public sealed class SimulatedRemoteApiSkillsSource : AgentSkillsSource { private readonly string _apiEndpoint; public override async Task> GetSkillsAsync(CancellationToken ct = default) { // 从远程 API 拉取 Skills var skills = await httpClient.GetFromJsonAsync>(_apiEndpoint, ct); return skills.Select(s => new AgentInlineSkill(s.Name, s.Description, s.Instructions)).ToList(); } } // 带缓存的 Skills Source(装饰器模式) public sealed class CachingSkillsSource : AgentSkillsSource { private readonly AgentSkillsSource _innerSource; private readonly TimeSpan _ttl; private IList? _cache; private DateTime _cacheExpiresAt = DateTime.MinValue; public override async Task> GetSkillsAsync(CancellationToken ct = default) { if (_cache != null && DateTime.UtcNow < _cacheExpiresAt) return _cache; // 缓存命中 _cache = await _innerSource.GetSkillsAsync(ct); _cacheExpiresAt = DateTime.UtcNow.Add(_ttl); return _cache; } } ``` **角色过滤实现**: ```csharp // 员工角色枚举 public enum EmployeeRole { Employee, Manager, HRAdmin } // 角色过滤辅助类 public static class UserRoleHelper { public static bool IsSkillVisibleTo(AgentSkill skill, EmployeeRole role) { var name = skill.Frontmatter.Name; // 管理技能仅经理和HR可见 if (name.StartsWith("manager-") && role == EmployeeRole.Employee) return false; // HR管理技能仅HR可见 if (name.StartsWith("hr-admin-") && role != EmployeeRole.HRAdmin) return false; return true; } } // 构建角色专属 Provider AgentSkillsProvider BuildProviderForRole(EmployeeRole role) { return new AgentSkillsProviderBuilder() .UseSkills(localCustomSkills) // 本地定制优先 .UseSource(cachedGlobalSource) // 全局技能库(带缓存) .UseFilter(s => UserRoleHelper.IsSkillVisibleTo(s, role)) // 角色过滤 .UsePromptTemplate("...") // 自定义提示词 .Build(); } ``` **优先级覆盖示例**: ``` 本地定制 Skills (优先): • expense-report (Contoso定制v2) - 覆盖全局版本 • contoso-benefits - Contoso 特有技能 全局 Skills (远程 API): • expense-report (全局v1) - 被本地覆盖 • hr-onboarding - 新员工入职流程 • leave-policy - 请假制度 • manager-review - 绩效评估(仅经理/HR可见) • hr-admin-audit - HR审计(仅HR可见) 按角色过滤结果: 👤 [Employee] 可见: expense-report, contoso-benefits, hr-onboarding, leave-policy 👤 [Manager] 可见: expense-report, contoso-benefits, hr-onboarding, leave-policy, manager-review 👤 [HRAdmin] 可见: 所有技能 ``` **多源 Skills 特点**: - 支持本地、远程 API、数据库等多种 Skills 来源 - 装饰器模式实现缓存,减少网络请求 - "先注册优先"原则实现本地覆盖全局 - 角色过滤实现权限控制 - Builder 模式灵活组合各种功能 ### 13. 声明式 Agent DeclarativeAgent 项目展示了使用 YAML 文件定义 Agent 的方式: **YAML 定义文件**: ```yaml kind: Prompt Name: CustomerSupportAgent description: 多语言客服助手 instructions: | 你是一个专业的客服助手。 你的任务是: 1. 使用用户的语言回答问题 2. 提供清晰、礼貌、专业的回复 3. 判断问题类型(订单/退款/技术/其他) 4. 判断用户情绪(正面/中性/负面) model: options: temperature: 0.3 topP: 0.9 outputSchema: properties: language: type: string description: 用户使用的语言 category: type: string description: 问题分类(order/refund/technical/other) sentiment: type: string description: 情绪(positive/neutral/negative) answer: type: string description: 客服回复内容 ``` **声明式 Agent 特点**: - 使用 YAML 文件定义 Agent 配置 - 支持定义指令(instructions)、模型参数(model options)和输出 Schema(outputSchema) - 通过 `ChatClientPromptAgentFactory.CreateFromYamlAsync()` 创建 Agent - 输出自动按 Schema 结构化,便于程序处理 **示例代码**: ```csharp // 读取 YAML 定义文件 var yamlContent = await File.ReadAllTextAsync("CustomerSupportAgent.prompt.yml"); // 从 YAML 创建 Agent var agentFactory = new ChatClientPromptAgentFactory(chatClient); var agent = await agentFactory.CreateFromYamlAsync(yamlContent); // 运行 Agent 并获取结构化输出 var response = await agent.RunAsync("用中文回答为什么我的订单货还没有到。", session); var result = JsonSerializer.Deserialize(response.Text); ``` **Skills 目录结构**: ``` Skills/ ├── expense-report/ # 费用报销 Skill │ ├── SKILL.md # Skill 定义(名称、描述、规则) │ ├── assets/ # 资源文件 │ │ └── expense-report-template.md # 报销模板 │ └── references/ # 参考文档 │ └── POLICY_FAQ.md # 政策 FAQ ├── travel-policy/ # 差旅政策 Skill │ └── SKILL.md # Skill 定义 └── system-ops/ # 系统运维 Skill ├── SKILL.md # Skill 定义 ├── references/ # 参考文档 │ └── troubleshooting-guide.md # 故障排查指南 └── scripts/ # 可执行脚本 ├── check-disk-usage.ps1 # 磁盘使用检查 ├── check-system-info.ps1 # 系统信息检查 └── check-top-processes.ps1 # 进程监控 ``` **Skills 特点**: - 基于文件系统,易于扩展和维护 - 支持 Markdown 格式定义 - 可包含资源文件和参考文档 - 通过 `AgentSkillsProvider` 自动加载 **自定义 SkillsInstructionPrompt 模板**: `AgentSkillsProviderOptions.SkillsInstructionPrompt` 模板必须包含以下占位符: | 占位符 | 用途 | |--------|------| | `{skills}` | 插入可用技能列表 | | `{resource_instructions}` | 插入资源读取指令说明 | | `{script_instructions}` | 插入脚本执行指令说明 | 示例模板: ``` {skills} {resource_instructions} {script_instructions} 工作流程: 1. 当用户任务匹配技能描述时,使用 `load_skill` 加载该技能 2. 需要时使用 `read_skill_resource` 读取参考资料 ``` ## 环境要求 - .NET 10.0 或更高版本 - Microsoft.Agents.AI v1.2.0 及相关包 - OpenAI API 或兼容的 Chat API ## 配置 1. 复制配置文件: ```bash cp appsettings.example.json appsettings.json ``` 2. 在 `appsettings.json` 中配置你的 API 密钥和端点: ```json { "OpenAI": { "Endpoint": "https://api.openai.com/v1", "ApiKey": "your-api-key", "ModelId": "gpt-4" } } ``` ## 运行示例 ### 控制台应用 (AIAgnetApp) 项目包含多个测试类,可以单独运行: ```csharp // 运行条件工作流测试 await new ConditionalWorkflowTest().RunAsync(chatClient); // 运行检测执行器测试 await new DetectionExecutorTest().RunAsync(chatClient); // 运行标语生成器测试 await new SloganExecutorTest().RunAsync(chatClient); // 运行工作流状态测试 await new WorkflowStateTest().RunAsync(chatClient); // 运行条件工作流Switch测试 await new ConditionalWorkflowSwitchTest().RunAsync(chatClient); // 运行循环工作流测试(客服回复优化) await new WorkflowLoopExecutorTest().RunAsync(chatClient); // 运行 Fan-out/Fan-in 工作流测试(多平台价格查询) await new WorkflowFanExecutorTest().RunAsync(chatClient); // 运行子工作流测试(投诉处理流水线) await new WorklfowSubExecutorTest().RunAsync(chatClient); ``` ### Web API 应用 (AIWebApp) ```bash cd AIWebApp dotnet run ``` A2A Agent 将通过 HTTP 端点提供服务,支持 Agent-to-Agent 通信协议。 ### AG-UI 服务端 (AGUIApp) ```bash cd AGUIApp dotnet run ``` AG-UI 服务将在 `https://localhost:8443/` 启动,提供 Agent-UI 通信端点。 ### AG-UI 客户端 (AGUIConsoleApp) ```bash cd AGUIConsoleApp dotnet run ``` 客户端将连接到 AG-UI 服务端,支持流式对话交互。输入 `:q` 或 `quit` 退出。 ### DevUI 开发者界面 (DevUIApp) ```bash cd DevUIApp dotnet run ``` DevUI 提供开发者调试界面,支持多 Agent 交互和工作流测试。 ### AG-UI 混合工具服务端 (AGUIToolsApp) ```bash cd AGUIToolsApp dotnet run ``` AG-UI 混合工具服务端,注册后端工具(SearchNearbyRestaurants、GetRestaurantDetail)。 ### AG-UI 混合工具客户端 (AGUIToolConsoleApp) ```bash cd AGUIToolConsoleApp dotnet run ``` 客户端注册前端工具(GetUserLocation、GetUserPreferences),与服务端后端工具协同工作。 ### Agent Skills 示例 (SkillConsoleApp) ```bash cd SkillConsoleApp dotnet run ``` 加载并使用 Agent Skills,支持费用报销、差旅政策、系统运维等场景。 **内置 Skills**: | Skill | 功能描述 | 测试类 | |-------|-----------|--------| | `expense-report` | 费用报销处理 - 包含报销规则、收据要求、审批流程 | - | | `travel-policy` | 差旅政策查询 - 航班、酒店、租车等政策指引 | `TravelSkillTest.cs` | | `system-ops` | 系统运维操作 - 健康检查、性能监控、故障排查 | `SkillToolTest.cs` | **测试类说明**: | 测试类 | 功能描述 | 主要特点 | |--------|-----------|----------| | `TravelSkillTest.cs` | 差旅政策查询测试 | 演示基础 Skills 加载和使用 | | `SkillToolTest.cs` | 系统运维测试 | 结合 ShellTools 执行系统命令 | **ShellTools 安全护栏**: `ShellTools.cs` 提供了 `run_shell` 工具,支持执行系统命令并内置安全护栏: | 安全措施 | 说明 | |----------|------| | 危险命令黑名单 | 阻止 `rm -rf /`、`sudo`、`shutdown`、`mkfs` 等危险命令 | | 输出截断 | 限制输出大小为 50KB,防止内存溢出 | | 超时控制 | 命令执行超时 60 秒自动终止 | | 跨平台支持 | Windows 使用 `cmd`,Linux/Mac 使用 `bash` | ```csharp // ShellTools 使用示例 [AIFunction("run_shell", "执行 Shell 命令")] public static string RunShell(string command, string? workingDirectory = null) { // 安全护栏:危险命令检查 if (dangerousPatterns.Any(d => command.Contains(d))) return "❌ 安全拦截:检测到危险命令"; // 跨平台 Shell 适配 var fileName = OperatingSystem.IsWindows() ? "cmd" : "bash"; // ... 执行命令 } ``` **系统运维示例**: ``` 👤 用户: 帮我检查一下当前系统的整体健康状态,包括 CPU、内存和磁盘使用情况 🤖 Agent: 加载 system-ops 技能... 执行脚本: pwsh -File check-system-info.ps1 执行脚本: pwsh -File check-disk-usage.ps1 系统健康状态报告: - CPU 使用率: 45% - 内存使用: 8.2GB / 16GB - 磁盘空间: C盘剩余 120GB ``` **注意**:`AgentSkillsProvider` 是实验性 API,项目已通过 `` 配置禁用相关诊断警告 (MAAI001, EXTEXP0001)。 ### Agent Skills 脚本执行示例 (SkillScriptConsoleApp) ```bash cd SkillScriptConsoleApp dotnet run ``` 展示 Agent Skills 的脚本执行能力,支持 AI Agent 自动调用外部脚本完成任务。 **特点**: - 使用 `SubprocessScriptRunner` 执行外部脚本 - AI Agent 可读取参考文档获取换算系数 - 自动调用 Python 脚本进行计算 - 支持中英文单位换算问答 **示例对话**: ``` 👤 用户: 马拉松比赛的距离26.2英里是多少公里? 🤖 Agent: 首先加载 unit-converter 技能... 查看换算系数表,1英里 = 1.60934公里 执行脚本计算: 26.2 × 1.60934 = 42.195公里 马拉松距离为 42.195 公里。 ``` ### 强类型 Skills 示例 (SkillCSharpConsoleApp) ```bash cd SkillCSharpConsoleApp dotnet run ``` 展示使用 C# 类定义 Skills 的强类型方式。 **特点**: - 使用 C# 类定义 Skill,编译时类型安全 - 通过特性标注资源和脚本方法 - 支持 IDE 智能提示和重构 - 可添加工具执行日志中间件 **示例代码**: ```csharp // 创建强类型 Skill 并注入 Agent var skillsProvider = new AgentSkillsProvider(new UnitConverterSkill()); AIAgent agent = chatClient.AsAIAgent(new ChatClientAgentOptions { Name = "UnitConverterAgent", AIContextProviders = [skillsProvider], }); // 添加工具执行日志中间件 agent = agent.AsBuilder() .Use(ToolExecutionLoggingMiddleware.ExecuteAsync) .Build(); ``` ### 多源 Skills 示例 (SkillsMultiConsoleApp) ```bash cd SkillsMultiConsoleApp dotnet run ``` 展示多源 Skills 加载、缓存、优先级覆盖和角色过滤。 **特点**: - 支持本地、远程 API 等多种 Skills 来源 - 装饰器模式实现缓存,减少网络请求 - "先注册优先"原则实现本地覆盖全局 - 角色过滤实现权限控制 **示例输出**: ``` 🔨 开始构建 Employee 角色的 Provider... 🏠 [LocalApiFactory] 正在从本地获取技能列表... ✅ [LocalApiFactory] 已成功加载 2 个本地技能 📡 [RemoteApiSource] 从 https://global-skills.contoso.com/api 拉取技能列表... ✅ [RemoteApiSource] 已成功加载 5 个远程技能 🔄 [CachingSource] 缓存未命中,从内层 Source 刷新... ✅ [CachingSource] 缓存已更新,有效至 14:30:00 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 👤 [Employee] 可见技能(4 个): • expense-report (本地定制) • contoso-benefits (本地定制) • hr-onboarding (全局库) • leave-policy (全局库) ``` ### 声明式 Agent 示例 (DeclarativeAgent) ```bash cd DeclarativeAgent dotnet run ``` 展示使用 YAML 文件定义 Agent 的声明式方式。 **特点**: - 使用 YAML 文件定义 Agent 配置 - 支持结构化输出(outputSchema) - 自动识别用户语言和情绪 - 输出按 Schema 结构化,便于程序处理 **示例对话**: ``` 👤 用户: 用中文回答为什么我的订单货还没有到。 🤖 Agent: { "language": "zh", "category": "order", "sentiment": "negative", "answer": "..." } 👤 用户: When my order can be handled? 🤖 Agent: { "language": "en", "category": "order", "sentiment": "neutral", "answer": "..." } ``` ### File-Based 单文件应用 (File-Based) ```bash cd File-Based dotnet run Main.cs ``` 这是一个最简化的 Agent Skills 示例,使用 dotnet script 格式(单文件应用程序): **特点**: - 单文件即可运行,无需项目文件 (.csproj) - 使用 `#:package` 指令声明依赖 - 集成 DevUI 开发者界面 - 适合快速原型开发和测试 **代码结构**: ```csharp #!/usr/bin/dotnet run #:sdk Microsoft.NET.Sdk.Web #:package Microsoft.Agents.AI.OpenAI@1.2.0 // ... 其他依赖 // Step0: 创建 ChatClient // Step1: 创建 SkillsProvider — 从文件系统加载 Skills // Step2: 创建 Agent — 注入 SkillsProvider // Step3: 注册 DevUI 服务 // Step4: 启动应用 ``` ## 主要功能示例 ### 1. 垃圾邮件检测工作流 ``` 用户邮件 → SpamDetectionExecutor → 判断结果 → ConditionalWorkflow ↓ ┌─────────────────────┴─────────────────────┐ ↓ ↓ 正常邮件 垃圾邮件 ↓ ↓ EmailAssistantExecutor SpamHandlingExecutor ↓ ↓ EmailSendingExecutor 处理 发送 ``` ### 2. 越狱检测工作流 ``` 用户输入 → StringToChatMessageAdapter → JailbreakDetectExecutor → FinalOutputExecutor (字符串转换) (AI 检测越狱攻击) (安全输出) ``` ### 3. 标语生成工作流(含反馈) ``` 创作请求 → SloganWriterExecutor ──→ FeedbackExecutor ──→ SloganWriterExecutor (生成标语) (获取评分反馈) (根据反馈改进) ↓ ↓ SloganGeneratedEvent FeedbackFinishedEvent ``` ### 4. 循环工作流(客服回复优化) ``` 工单请求 → AdaptiveReplyDraftExecutor ──→ AdaptiveQualityCheckExecutor ──→ IntelligentImproveExecutor (生成回复草稿) (AI 质量检测) (智能改进) ↓ ↓ ↓ ReplyDraft QualityReport QualityCheckSignal (通过则输出) (返回重试) ↑ │ └──────────────────────────────────────────────────────────────┘ (循环直到质量达标或达到最大次数) ``` ### 5. Fan-out/Fan-in 工作流(多平台价格查询) ``` ┌──────────────────→ AmazonPriceExecutor ──────────────────┐ │ (Amazon 查询) │ │ ↓ │ 价格查询 → PriceQueryStartExecutor ──→ eBayPriceExecutor ──→ PricingStrategyExecutor → 汇总报告 请求 (广播查询) (eBay 查询) (收集结果) │ ↓ │ └──────────────────→ ShopeePriceExecutor ─────────────────┘ (Shopee 查询) ←────────────────── Fan-out ──────────────────→ ←────────────────── Fan-in ───────────────────→ ``` ### 6. 子工作流(投诉处理流水线) ``` ┌──────────────────────────────────────┐ │ 产品质量子工作流 │ │ ProductEvaluationExecutor │ │ ↓ │ 客户投诉 → ComplaintClassifierExecutor → ReturnPolicyExecutor │ (分类) (投诉分类) │ ↓ │ │ │ AIResponseGeneratorExecutor │ │ └──────────────────────────────────────┘ │ ↓ │ ┌──────────────────────────────────────┐ ├─────────────────────→│ 物流问题子工作流 │ │ │ LogisticsTrackingExecutor │ │ │ ↓ │ │ │ DelayAnalysisExecutor │ │ │ ↓ │ │ │ AIResponseGeneratorExecutor │ │ └──────────────────────────────────────┘ │ ↓ └──────────────────→ ComplianceCheckExecutor → SentimentAnalysisExecutor → 最终回复 (合规检查) (情绪分析) ``` **子工作流特点**: - 主工作流根据投诉类型动态路由到不同的子工作流 - 产品质量投诉:产品评估 → 退货政策 → AI 响应生成 - 物流问题投诉:物流跟踪 → 延迟分析 → AI 响应生成 - 所有子工作流结果汇聚后进行合规检查和情绪分析 ### 7. A2A Agent 通信 ``` ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ WeatherAgent│────→│ PlanAgent │────→│ HotelAgent │ │ (天气查询) │ │ (行程规划) │ │ (酒店预订) │ └─────────────┘ └─────────────┘ └─────────────┘ ↑ ↑ ↑ └───────────────────┴───────────────────┘ 用户请求 ``` **A2A 特点**: - 基于 HTTP 的 Agent-to-Agent 通信协议 - 支持任务管理和消息传递 - 每个 Agent 独立部署,可横向扩展 - 通过 Agent Card 描述 Agent 能力 ### 8. AG-UI 通信 ``` ┌─────────────────┐ ┌─────────────────┐ │ AGUIApp │ │ AGUIConsoleApp │ │ (服务端) │◄─── HTTP/SSE ─────│ (客户端) │ │ │ │ │ │ AGUI-Assistant │ │ agui-client │ │ (AI Agent) │ │ (Console UI) │ └─────────────────┘ └─────────────────┘ ``` **AG-UI 特点**: - 基于 HTTP 的 Agent-UI 通信协议 - 支持流式响应 (Server-Sent Events) - 简单易用的客户端 API (`AGUIChatClient`) - 支持会话管理和多轮对话 ### 9. DevUI 开发者界面 ``` ┌─────────────────────────────────────────────────────────┐ │ DevUIApp │ │ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ │ │Assistant│ │ Poet │ │ Coder │ │ Writer │ │ │ │ (助手) │ │ (诗人) │ │ (程序员) │ │ (作者) │ │ │ └─────────┘ └─────────┘ └─────────┘ └─────────┘ │ │ ↓ ↓ │ │ ┌─────────────────────────────────────────────────┐ │ │ │ TestWorkflow (顺序工作流) │ │ │ │ Writer → Reviewer (写作审阅流程) │ │ │ └─────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────┘ ``` **DevUI 特点**: - 内置多 Agent 交互界面 - 支持工作流可视化测试 - 提供 OpenAI Responses 和 Conversations API - 适合开发和调试 Agent 应用 ### 10. AG-UI 混合工具 ``` ┌─────────────────────────────────────────────────────────────────────┐ │ AG-UI 混合工具架构 │ │ │ │ ┌─────────────────────────────┐ ┌─────────────────────────────┐│ │ │ AGUIToolConsoleApp │ │ AGUIToolsApp ││ │ │ (客户端) │ │ (服务端) ││ │ │ │ │ ││ │ │ 🔧 前端工具 (客户端执行): │ │ 🔧 后端工具 (服务端执行): ││ │ │ • GetUserLocation │ │ • SearchNearbyRestaurants ││ │ │ • GetUserPreferences │ │ • GetRestaurantDetail ││ │ │ │ │ ││ │ │ 📍 可访问客户端资源: │ │ 🗄️ 可访问服务端资源: ││ │ │ • 用户地理位置 │ │ • 数据库 ││ │ │ • 本地存储 │ │ • 外部 API ││ │ │ • 用户偏好设置 │ │ • 业务逻辑 ││ │ └───────────────┬─────────────┘ └───────────────┬─────────────┘│ │ │ │ │ │ │ HTTP/SSE │ │ │ └──────────────────────────────────┘ │ │ ↓ │ │ ┌─────────────────────────────┐ │ │ │ AI Agent (服务端) │ │ │ │ MixedToolsAssistant │ │ │ │ 可调用前端+后端工具 │ │ │ └─────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────────┘ ``` **混合工具调用流程示例**: ``` 用户: "附近有什么好吃的餐厅?" ↓ AI Agent 分析: 需要获取用户位置 + 搜索餐厅 ↓ ┌─────────────────────────────────────────────────────┐ │ 1. 调用前端工具: GetUserLocation() │ │ → 客户端执行,返回用户当前位置 (如: 北京市朝阳区) │ ├─────────────────────────────────────────────────────┤ │ 2. 调用后端工具: SearchNearbyRestaurants(location) │ │ → 服务端执行,查询数据库/外部API,返回餐厅列表 │ ├─────────────────────────────────────────────────────┤ │ 3. AI Agent 整合结果,生成回复 │ │ → "为您找到以下附近的餐厅..." │ └─────────────────────────────────────────────────────┘ ``` **混合工具优势**: - **隐私保护**:敏感数据(如位置)在客户端处理,不上传服务端 - **资源优化**:客户端处理轻量任务,服务端处理重量任务 - **灵活部署**:前后端工具独立开发、独立部署 - **协同工作**:AI Agent 自动协调前后端工具调用顺序 ## Executor 类型说明 ### Executor 基类泛型参数 Microsoft Agent Framework 中的 `Executor` 基类支持两种泛型形式: - `Executor` - 仅定义输入类型,不产生输出,适用于终端节点 - `Executor` - 定义输入和输出类型,输出通过返回值传递给下游 **重要规则**: 1. **输出结果**:如果需要调用 `YieldOutputAsync` 方法,必须使用 `Executor` 形式,且输出对象类型必须与 `TOutput` 匹配。 2. **消息传递**:Executor 之间的消息传递通过返回值实现,框架会自动将返回值路由到 `AddEdge` 定义的下游 Executor。 ```csharp // ❌ 错误:无法输出字符串 public class MyExecutor : Executor("MyExecutor") { public override async ValueTask HandleAsync(MyInput msg, IWorkflowContext ctx, CancellationToken ct) { await ctx.YieldOutputAsync("output", ct); // 运行时错误 } } // ❌ 错误:无法发送未声明的消息类型 public class MyExecutor : Executor("MyExecutor") { public override async ValueTask HandleAsync(MyInput msg, IWorkflowContext ctx, CancellationToken ct) { await ctx.SendMessageAsync(new MyOutput(), targetId: "Next", ct); // 运行时错误 } } // ✅ 正确:定义输出类型,通过返回值传递 public class MyExecutor : Executor("MyExecutor") { public override async ValueTask HandleAsync(MyInput msg, IWorkflowContext ctx, CancellationToken ct) { var result = new MyOutput { Data = "output" }; await ctx.YieldOutputAsync(result, ct); // 可选:输出到工作流结果流 return result; // 返回值自动传递给下游 Executor } } ``` ## 技术实现细节 ### AG-UI 服务端实现 AGUIApp 使用 `Microsoft.Agents.AI.Hosting.AGUI.AspNetCore` 包实现 AG-UI 协议: ```csharp // 1. 注册 AG-UI 服务 builder.Services.AddAGUI(); // 2. 创建 ChatClient var chatClient = new OpenAIClient( new ApiKeyCredential(openAIProvider.ApiKey), new OpenAIClientOptions { Endpoint = new Uri(openAIProvider.Endpoint) }) .GetChatClient(openAIProvider.ModelId) .AsIChatClient(); // 3. 创建 AI Agent var agent = chatClient.AsAIAgent( name: "AGUI-Assistant", instructions: "你是一个友好的AI助手,请使用中文回答用户的问题。"); // 4. 映射 AG-UI 端点 app.MapAGUI("/", agent); ``` **关键 API**: - `AddAGUI()` - 注册 AG-UI 所需的服务 - `MapAGUI(path, agent)` - 映射 AG-UI HTTP 端点 - 支持 Server-Sent Events (SSE) 流式响应 ### AG-UI 客户端实现 AGUIConsoleApp 使用 `AGUIChatClient` 连接服务端: ```csharp // 1. 创建 HTTP 客户端 using HttpClient httpClient = new() { Timeout = TimeSpan.FromSeconds(60) }; // 2. 创建 AG-UI 客户端 var chatClient = new AGUIChatClient(httpClient, serverEndpoint); // 3. 创建 Agent var agent = chatClient.AsAIAgent( name: "agui-client", description: "AG-UI Client Agent"); // 4. 创建会话并交互 var session = await agent.CreateSessionAsync(); var response = await agent.RunStreamingAsync(messages, session); ``` ### DevUI 实现细节 DevUIApp 支持多 Agent 注册和工作流定义: ```csharp // 1. 注册 ChatClient builder.Services.AddChatClient(chatClient); // 2. 注册多个 Agent builder.AddAIAgent("Assistant", "你是一位乐于助人的助手。回答问题简洁准确。"); builder.AddAIAgent("Poet", "你是一位富有创造力的诗人。使用优美的诗篇回答所有的请求"); builder.AddAIAgent("Coder", "你是一位资深的程序员。请协助用户解决编程问题。"); // 3. 注册工作流 var writerAgent = builder.AddAIAgent("Writer", "..."); var reviewerAgent = builder.AddAIAgent("Reviewer", "..."); builder.AddWorkflow("TestWorkflow", (sp, key) => { return AgentWorkflowBuilder.BuildSequential( workflowName: key, agents: [writerAgent, reviewerAgent]); }).AddAsAIAgent(); // 4. 注册 DevUI 服务和端点 builder.Services.AddOpenAIResponses(); builder.Services.AddOpenAIConversations(); app.MapOpenAIResponses(); app.MapOpenAIConversations(); app.MapDevUI(); // 开发环境下映射 DevUI 界面 ``` **关键 API**: - `AddAIAgent(name, instructions)` - 注册 AI Agent - `AddWorkflow(name, factory)` - 注册工作流 - `BuildSequential()` - 构建顺序执行工作流 - `MapDevUI()` - 映射开发者界面 ### AG-UI 混合工具实现 AGUIToolsApp 和 AGUIToolConsoleApp 展示了前后端工具协同工作: **服务端 (AGUIToolsApp) - 注册后端工具**: ```csharp // 定义后端工具 AITool[] backendTools = [ AIFunctionFactory.Create(BackendTools.SearchNearbyRestaurants), AIFunctionFactory.Create(BackendTools.GetRestaurantDetail) ]; // 创建 Agent 并注册后端工具 var agent = chatClient.AsAIAgent( name: "MixedToolsAssistant", instructions: "你是一个智能餐厅推荐助手...", tools: backendTools); // 映射 AG-UI 端点 app.MapAGUI("/", agent); ``` **客户端 (AGUIToolConsoleApp) - 注册前端工具**: ```csharp // 定义前端工具 AITool[] frontendTools = [ AIFunctionFactory.Create(FrontendTools.GetUserLocation), AIFunctionFactory.Create(FrontendTools.GetUserPreferences) ]; // 创建 AG-UI 客户端并注册前端工具 var chatClient = new AGUIChatClient(httpClient, serverEndpoint); var agent = chatClient.AsAIAgent( name: "agui-client", description: "AG-UI 混合工具客户端", tools: frontendTools); // 👈 注册前端工具 ``` **工具定义示例**: ```csharp // 前端工具 - 在客户端执行 public static class FrontendTools { [Description("获取用户当前位置")] public static string GetUserLocation() { // 可访问客户端资源(如 GPS、本地存储) return "北京市朝阳区"; } } // 后端工具 - 在服务端执行 public static class BackendTools { [Description("搜索附近餐厅")] public static List SearchNearbyRestaurants(string location) { // 可访问服务端资源(如数据库、外部 API) return dbContext.Restaurants.Where(r => r.Location == location).ToList(); } } ``` **关键概念**: - 前端工具在客户端执行,可访问客户端资源 - 后端工具在服务端执行,可访问服务端资源 - AI Agent 自动协调工具调用顺序 ### A2A Agent 实现细节 AIWebApp 使用 A2A 协议实现 Agent 间通信: ```csharp public class WeatherAgent { public void Attach(ITaskManager taskManager) { taskManager.OnMessageReceived = QueryWeatherAsync; taskManager.OnAgentCardQuery = GetAgentCardAsync; } private Task GetAgentCardAsync(string agentUrl, CancellationToken ct) { return Task.FromResult(new AgentCard() { Name = "weather agent", Description = "weather information agent", Url = agentUrl, Version = "1.0.0", Capabilities = new AgentCapabilities() { Streaming = true, PushNotifications = false, }, Skills = [new AgentSkill { Id = "weather-query", Name = "天气查询" }] }); } } ``` **关键概念**: - `AgentCard` - Agent 能力描述卡片 - `AgentCapabilities` - Agent 能力定义(流式、推送通知等) - `AgentSkill` - Agent 技能描述 - `ITaskManager` - 任务管理器接口 ### Agent 转换为 AIFunction AIWebApp 提供了将 A2A Agent 转换为可调用工具的扩展: ```csharp // 将 Agent 转换为 AIFunction 列表 var functions = await agent.AsAIFunctionsAsync(); // 在其他 Agent 中使用 var plannerAgent = chatClient.AsAIAgent( name: "Planner", instructions: "你是一个行程规划助手,使用工具获取信息。", tools: functions); ``` ## NuGet 依赖包 ### Microsoft.Agents.AI 系列 | 包名 | 版本 | 说明 | |------|------|------| | Microsoft.Agents.AI | 1.3.0 | 核心 Agent 框架 | | Microsoft.Agents.AI.Abstractions | 1.3.0 | 抽象接口定义 | | Microsoft.Agents.AI.Foundry | 1.3.0 | Agent Foundry 支持 | | Microsoft.Agents.AI.OpenAI | 1.3.0 | OpenAI 集成 | | Microsoft.Agents.AI.Workflows | 1.3.0 | 工作流引擎 | | Microsoft.Agents.AI.Workflows.Generators | 1.3.0 | 工作流代码生成器 | | Microsoft.Agents.AI.Declarative | 1.3.0-rc1 | 声明式 Agent 支持 | | Microsoft.Agents.AI.AGUI | 1.3.0-preview.260423.1 | AG-UI 客户端支持 | ### 托管与托管支持 | 包名 | 版本 | 说明 | |------|------|------| | Microsoft.Agents.AI.Hosting | 1.3.0-preview.260423.1 | Agent 托管核心 | | Microsoft.Agents.AI.Hosting.A2A.AspNetCore | 1.3.0-preview.260423.1 | A2A 托管支持 | | Microsoft.Agents.AI.Hosting.AGUI.AspNetCore | 1.3.0-preview.260423.1 | AG-UI 托管支持 | | Microsoft.Agents.AI.Hosting.OpenAI | 1.3.0-alpha.260423.1 | OpenAI 托管支持 | | Microsoft.Agents.AI.DevUI | 1.3.0-preview.260423.1 | DevUI 开发者界面 | ### Microsoft.Extensions.AI 系列 | 包名 | 版本 | 说明 | |------|------|------| | Microsoft.Extensions.AI | 10.5.0 | AI 扩展核心 | | Microsoft.Extensions.AI.Abstractions | 10.5.0 | AI 抽象层 | | Microsoft.Extensions.AI.OpenAI | 10.5.0 | OpenAI 扩展 | ### 配置与基础设施 | 包名 | 版本 | 说明 | |------|------|------| | Microsoft.Extensions.Configuration | 10.0.7 | 配置管理 | | Microsoft.Extensions.Configuration.Binder | 10.0.7 | 配置绑定 | | Microsoft.Extensions.Configuration.Json | 10.0.7 | JSON 配置支持 | | Azure.Core | 1.54.0 | Azure 核心库 | | OpenTelemetry | 1.15.3 | 遥测支持 | | OpenTelemetry.Exporter.Console | 1.15.3 | 控制台遥测导出 | ## 贡献指南 欢迎提交 Pull Request 或创建 Issue 来改进本项目。 ## 许可证 MIT License - 详见 LICENSE 文件