MAF快速入门(21)RC5引入的Script运行能力
大家好我是Edison。最近我一直在跟着圣杰的《.NETAI智能体开发进阶》课程学习MAF开发多智能体工作流我强烈推荐你也上车跟我一起出发上一篇我们了解下.NET 10新推出的File-Based App模式它和MAF一起可以形成一个强大的“王牌组合”。而就在这两天MAF 1.0.0-rc5发布了之前github demo中的agent skills demo也可以运行了1 RC5的新变化在RC5之前我们使用Skills的方式还主要是静态知识注入一方面解决如何让Agent知道领域知识另一方面让Agent通过渐进式披露策略降低Token消耗。而至于script能力MAF一直为开放而前面的内容圣杰也给出了一个思路。但是到了RC5官方实现来了别激动请接住Skill的定位变化有了script的运行能力skill从 静态知识包 开始走向 可执行能力包其新增的接口 run_skill_script 就是来执行script的入口。根据之前的了解现在AgentSkillProvider就能有三个接口来构建Skill了load_skillread_skill_resourcerun_skill_script因此我们对Agent Skills的定义也会更加完善即 Agent Skill 指令 资源 脚本 共同组成的可移植能力包MAF Skills的4层架构从MAF对Skills的实现来看它做了较多的抽象 和 工程化基本可以拆分为4层如下图所示1. 对象层定义 Skill 是什么2. Source 层定义 Skill 从哪里来3. Decorator 层定义 Skill 怎么过滤、去重、组合4. Provider 层定义 Skill 怎么进入 Agent 运行时更多地解析推荐大家阅读圣杰的《MAF悄悄更新到RC5Agent Skills的脚本运行能力Ready了》这里我就不再重复了下面我们具体看看DEMO。Code as Skill 代码定义Skill在RC5中支持在代码中定义Skill而不再限制于目录中的markdown文档在Source层它叫做 AgentInMemorySkillsSource。下面也会给出一个例子展示这个代码定义Skill的模式。2 快速开始单位转换器这里我们直接来看官方团队给出的案例单位转换器。虽然这个案例有点脱了裤子放屁的意思但是足够简单和覆盖知识点。我们希望创建一个单位转换的Agent能够通过查询skill及其相关计算规则 和 运行脚本 回复用户关于单位转换的结果。老规矩我们先写Skill的内容SKILL.mdreferences 和 scripts。SKILL.md首先我们创建这个SKILL.md内容如下---name: unit-converterdescription: 使用乘法换算系数在常见单位之间进行转换。在需要将英里/公里、磅/千克等单位互相换算时使用。--- ## 使用方法 当用户请求单位换算时1. 先查看 references/conversion-table.md找到正确的换算系数2. 使用 --value 数值 --factor 系数 运行 scripts/convert.py 脚本例如--value 26.2 --factor 1.609343. 输出内容需要清晰地展示换算系数、换算过程和换算结果并同时标明换算前后的两个单位reference: 转换公式表其次我们创建一个conversion-table.md用于告诉Agent转换的系数和公式# Conversion Tables换算表 Formula公式: **result value × factor结果 数值 × 系数** Note说明: - From / To 列请保持英文miles, kilometers, pounds, kilograms便于在工具参数/代码中稳定引用。 - 中文列仅用于阅读理解。 | From | To | Factor | From (中文) | To (中文) ||------------|------------|----------|------------ |----------|| miles | kilometers | 1.60934 | 英里 | 千米/公里 || kilometers | miles | 0.621371 | 千米/公里 | 英里 || pounds | kilograms | 0.453592 | 磅 | 千克/公斤 || kilograms | pounds | 2.20462 | 千克/公斤 | 磅 |scripts: 可执行脚本这里我们编写了一个python脚本 convert.py 来做一个简单的运算虽然它太简单了# 单位换算脚本# 使用乘法系数对数值进行换算result value × factor## 用法# python scripts/convert.py --value 26.2 --factor 1.60934# python scripts/convert.py --value 75 --factor 2.20462 import argparseimport json def main() - None: parser argparse.ArgumentParser( descriptionConvert a value using a multiplication factor., epilogExamples:\n python scripts/convert.py --value 26.2 --factor 1.60934\n python scripts/convert.py --value 75 --factor 2.20462, formatter_classargparse.RawDescriptionHelpFormatter, ) parser.add_argument(--value, typefloat, requiredTrue, helpThe numeric value to convert.) parser.add_argument(--factor, typefloat, requiredTrue, helpThe conversion factor from the table.) args parser.parse_args() result round(args.value * args.factor, 4) print(json.dumps({value: args.value, factor: args.factor, result: result})) if __name__ __main__: main()自定义脚本执行器这里官方定义了一个ScriptRunner它会通过一个本地进程来执行Skill中的脚本也就是上面的 convert.py 代码脚本。internal static class SubprocessScriptRunner{ /// summary /// Runs a skill script as a local subprocess. /// /summary public static async Taskobject? RunAsync( AgentFileSkill skill, AgentFileSkillScript script, AIFunctionArguments arguments, CancellationToken cancellationToken) { if (!File.Exists(script.FullPath)) { return $Error: Script file not found: {script.FullPath}; } string extension Path.GetExtension(script.FullPath); string? interpreter extension switch { .py python3, .js node, .sh bash, .ps1 pwsh, _ null, }; var startInfo new ProcessStartInfo { RedirectStandardOutput true, RedirectStandardError true, UseShellExecute false, CreateNoWindow true, WorkingDirectory Path.GetDirectoryName(script.FullPath) ?? ., }; if (interpreter is not null) { startInfo.FileName interpreter; startInfo.ArgumentList.Add(script.FullPath); } else { startInfo.FileName script.FullPath; } if (arguments is not null) { foreach (var (key, value) in arguments) { if (value is bool boolValue) { if (boolValue) { startInfo.ArgumentList.Add(NormalizeKey(key)); } } else if (value is not null) { startInfo.ArgumentList.Add(NormalizeKey(key)); startInfo.ArgumentList.Add(value.ToString()!); } } } Process? process null; try { process Process.Start(startInfo); if (process is null) { return $Error: Failed to start process for script {script.Name}.; } Taskstring outputTask process.StandardOutput.ReadToEndAsync(cancellationToken); Taskstring errorTask process.StandardError.ReadToEndAsync(cancellationToken); await process.WaitForExitAsync(cancellationToken).ConfigureAwait(false); string output await outputTask.ConfigureAwait(false); string error await errorTask.ConfigureAwait(false); if (!string.IsNullOrEmpty(error)) { output $\nStderr:\n{error}; } if (process.ExitCode ! 0) { output $\nScript exited with code {process.ExitCode}; } return string.IsNullOrEmpty(output) ? (no output) : output.Trim(); } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { // Kill the process on cancellation to avoid leaving orphaned subprocesses. process?.Kill(entireProcessTree: true); throw; } catch (OperationCanceledException) { throw; } catch (Exception ex) { return $Error: Failed to execute script {script.Name}: {ex.Message}; } finally { process?.Dispose(); } } /// summary /// Normalizes a parameter key to a consistent --flag format. /// Models may return keys with or without leading dashes (e.g., value vs --value). /// /summary private static string NormalizeKey(string key) -- key.TrimStart(-);}可以看到在该Runner中定义了一些基本的校验规则然后就通过启动一个本地进程去执行脚本。主文件C#代码这里我们还是一步一步来看Step1. 创建SkillsProvidervar skillsProvider new AgentSkillsProvider( skillPath: Path.Combine(Directory.GetCurrentDirectory(), skills), scriptRunner: SubprocessScriptRunner.RunAsync);Console.WriteLine(✅ AgentSkillsProvider 创建成功);Console.WriteLine( 自动注册工具: load_skill, read_skill_resource, run_skill_script);Console.WriteLine();Step2. 创建AgentAIAgent agent chatClient.AsAIAgent(new ChatClientAgentOptions{ Name UnitConverterAgent, ChatOptions new() { Instructions 你是一个专业的AI助手负责帮助用户实现单位的转换。, }, // 知识层通过 AIContextProviders 注入 Skills AIContextProviders [skillsProvider],});Console.WriteLine(✅ Agent 创建成功);Console.WriteLine();Step3. 测试Agentvar session await agent.CreateSessionAsync();Console.WriteLine(━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━);Console.WriteLine($开始测试基于 File-Based Skills);// 中文问题英里 - 公里var question1 马拉松比赛的距离26.2 英里是多少公里;Console.WriteLine($ 用户: {question1});Console.WriteLine();var response1 await agent.RunAsync(question1, session);Console.WriteLine(━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━);Console.WriteLine($ Agent: {response1.Text});Console.WriteLine(━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━);Console.WriteLine();// 英文问题磅 - 千克var question2 How many pounds is 75 kilograms?;Console.WriteLine($ 用户: {question2});Console.WriteLine();var response2 await agent.RunAsync(question2, session);Console.WriteLine(━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━);Console.WriteLine($ Agent: {response2.Text});Console.WriteLine(━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━);Console.WriteLine();测试效果如下图可以看到无论是中文还是英文它都严格按照skill中的要求输出了换算系数、换算过程 和 最终结果。3 快速开始代码定义Skills这里我们再来看看官方的第二个DEMO通过代码定义Skills这里就会用到 AgentInlineSkill 这个新增对象。var unitConverterSkill new AgentInlineSkill( name: unit-converter, description: 使用乘法换算系数在常见单位之间进行转换。在需要将英里/公里、磅/千克等单位互相换算时使用。, instructions: 当用户请求单位换算时请使用本 Skill。 1. 查看 conversion-table 资源找到正确的换算系数。 2. 查看 conversion-policy 资源了解取整和格式化规则。 3. 使用 convert 脚本并传入从表中查到的数值和系数。 ) // 1. 静态资源: conversion tables .AddResource( conversion-table, # 换算表 公式: **结果 数值 × 系数** | From | To | Factor | |-------------|-------------|----------| | miles | kilometers | 1.60934 | | kilometers | miles | 0.621371 | | pounds | kilograms | 0.453592 | | kilograms | pounds | 2.20462 | ) // 2. 动态资源: conversion policy (运行时计算) .AddResource(conversion-policy, () { const int Precision 4; return $ # 换算策略 **小数位数:** {Precision} **格式:** 始终同时显示原始值、换算后值以及单位 **生成时间:** {DateTime.UtcNow:O} ; }) // 3. 代码脚本: convert by C# code .AddScript(convert, (double value, double factor) { double result Math.Round(value * factor, 4); return JsonSerializer.Serialize(new { value, factor, result }); });var skillsProvider new AgentSkillsProvider(unitConverterSkill);可以看到MAF释放的信号很明确Skill不只是磁盘中的markdown文件Code as Skill!那么这类型的动态skill适合哪些场景呢答案它特别适合那些只存在于运行时的信息比如当前租户配置当前区域实时配额当前系统状态动态生成的业务规则。这些信息如果硬要放到磁盘中形成文件反而不自然。4 小结本文介绍了RC5引入的令人激动的script执行能力有了script执行能力Agent Skill才变得更加完整也从静态知识包 开始走向 可执行能力包Agent Skill 知识 资源 脚本。由此也可见MAF对Skill的理解也在不断地进化开始往软件工程层面迈进不过要真的走上生产环境还需要在应用层面考虑安全性 和 扩展性方面的内容毕竟企业级应用还是得控制风险示例源码Github: https://github.com/EdisonTalk/MAFD参考资料圣杰《.NET AI 智能体开发进阶》
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2482116.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!