找回密码
 立即注册
首页 业界区 业界 多Agent协作入门:并发编排模式

多Agent协作入门:并发编排模式

柴古香 9 小时前
大家好,我是Edison。
上一篇我们学习了Semantic Kernel中的AgentGroupChat实现群聊的效果,但其实多Agent协作编排还有一些其他的模式。今天就来和你唠唠其他支持的编排模式,每篇介绍一个,持续更新完。
SK支持哪些编排模式?

传统的单Agent系统在处理复杂多面任务的能力方面受到较多限制,因此我们会有多Agent编排协作完成任务的需求。Semantic Kernel支持多种多Agent编排流程模式,每个模式都针对不同的协作方案而设计。这些模式作为框架的一部分提供出来,我们可以自己扩展。
目前,Semantic Kernel支持以下编排模式:
1.png

上面所有的编排模式都基于统一的构造和接口来实现,它抽象了Agent通信、协调和结果聚合的复杂性,如下代码所示,只需选择不同的编排模式类即可:
  1. // 只需修改下面的编排模式类型即可
  2. // or ConcurrentOrchestration, GroupChatOrchestration, HandoffOrchestration, MagenticOrchestration, ...
  3. SequentialOrchestration orchestration = new(agentA, agentB)
  4. {
  5.     LoggerFactory = this.LoggerFactory
  6. };
  7. InProcessRuntime runtime = new();
  8. // Start the runtime
  9. await runtime.StartAsync();
  10. // Invoke the orchestration and get the result
  11. OrchestrationResult<string> result = await orchestration.InvokeAsync(task, runtime);
  12. string text = await result.GetValueAsync();
  13. await runtime.RunUntilIdleAsync();
复制代码
因此,我们无需学习新的API或重写Agent逻辑,可以专注于应用程序的编写,真的是很方便!
下面,我们就来看看第一种模式:并发编排。
并发编排模式简介

并发模式使用多个Agent并行处理同一个任务,每个Agent都可以独立处理输入,并收集并聚合结果。此模式比较适合多种观点或解决方案很有价值的场景,比如集思广益、群体推理以及其他投票系统。
下图展示了多个Agent生成同一问题的不同解决方案,并收集其响应以进一步分析或选择:
2.png

实现并发编排模式

这里我们来实现一个DEMO,定义两个Agent:Physicst(物理学大佬) 和 Chemist (化学大佬),它们可以对用户提出的同一个问题并行地进行思考并给出自己的解释。
为了简单地实现这个功能,我们创建一个.NET控制台项目,然后安装以下包:
  1. Microsoft.SemanticKernel.Agents.Core
  2. Microsoft.SemanticKernel.Agents.OpenAI (Preview版本)
  3. Microsoft.SemanticKernel.Agents.Orchestration (Preview版本)
  4. Microsoft.SemanticKernel.Agents.Runtime.InProcess (Preview版本)
复制代码
需要注意的是,由于Semantic Kernel的较多功能目前还处于实验预览阶段,所以建议在该项目的csproj文件中加入以下配置,统一取消警告:
  1. <PropertyGroup>
  2.   <NoWarn>$(NoWarn);CA2007;IDE1006;SKEXP0001;SKEXP0110;OPENAI001</NoWarn>
  3. </PropertyGroup>
复制代码
创建一个appsettings.json配置文件,填入以下关于LLM API的配置,其中API_KEY请输入你自己的:
  1. {
  2.   "LLM":
  3.   {
  4.     "BASE_URL": "https://api.siliconflow.cn",
  5.     "API_KEY": "******************************",
  6.     "MODEL_ID": "Qwen/Qwen2.5-32B-Instruct"
  7.   }
  8. }
复制代码
这里我们使用SiliconCloud提供的 Qwen2.5-32B-Instruct 模型,你可以通过这个URL注册账号:https://cloud.siliconflow.cn/i/DomqCefW 获取大量免费的Token来进行本次实验。
有了LLM API,我们可以创建一个Kernel供后续使用,这也是老面孔了:
  1. Console.WriteLine("Now loading the configuration...");
  2. var config = new ConfigurationBuilder()
  3.     .AddJsonFile($"appsettings.json", optional: false, reloadOnChange: true)
  4.     .Build();
  5. Console.WriteLine("Now loading the chat client...");
  6. var chattingApiConfiguration = new OpenAiConfiguration(
  7.     config.GetSection("LLM:MODEL_ID").Value,
  8.     config.GetSection("LLM:BASE_URL").Value,
  9.     config.GetSection("LLM:API_KEY").Value);
  10. var openAiChattingClient = new HttpClient(new OpenAiHttpHandler(chattingApiConfiguration.EndPoint));
  11. var kernel = Kernel.CreateBuilder()
  12.     .AddOpenAIChatCompletion(chattingApiConfiguration.ModelId, chattingApiConfiguration.ApiKey, httpClient: openAiChattingClient)
  13.     .Build();
复制代码
接下来,我们就一步一步地来看看核心的代码。
定义两个Agent

这里我们来定义两个Agent:Chemist & Physicst
(1)Chemist
  1. var chemist = new ChatCompletionAgent()
  2. {
  3.     Name = "ChemistryExpert",
  4.     Instructions = "You're an expert in chemistry, you can answer questions from a chemistry expert perspective.",
  5.     Description = "Chemistry expert agent for answering questions in the perspective of a chemist.",
  6.     Kernel = kernel
  7. };
复制代码
(2)Physicst
  1. var physicist = new ChatCompletionAgent()
  2. {
  3.     Name = "PhysicsExpert",
  4.     Instructions = "You're an expert in physics, you can answer questions from a physics expert perspective.",
  5.     Description = "Physics expert agent for answering questions in the perspective of a physicst.",
  6.     Kernel = kernel
  7. };
复制代码
选择编排模式

这里我们选择的是并发编排模式:ConcurrentOrchestration,将需要编排的两个Agent作为参数传递给它:
  1. // Set up the Concurrent Orchestration
  2. var orchestration = new ConcurrentOrchestration(physicist, chemist);
复制代码
启动运行时

在Semantic Kernel中,需要运行时(Runtime)才能管理Agent的执行,因此这里我们需要在正式开始前使用InProcessRuntime并启动起来。
  1. // Start the Runtime
  2. var runtime = new InProcessRuntime();
  3. await runtime.StartAsync();
复制代码
调用编排 并 收集结果

准备工作差不多了,现在我们可以开始调用编排了。编排任务时它会将任务广播到所有Agent中,并发运行多个Agent进行任务处理,最后收集每个Agent的处理结果。
这里的案例就是将用户的问题传给多个Agent并发思考并给出自己的回答。
  1. // Start the Chat
  2. Console.WriteLine("----------Agents are Ready. Let's Start Working!----------");
  3. while (true)
  4. {
  5.     Console.WriteLine("User> ");
  6.     var input = Console.ReadLine();
  7.     if (string.IsNullOrWhiteSpace(input))
  8.         continue;
  9.     input = input.Trim();
  10.     if (input.Equals("EXIT", StringComparison.OrdinalIgnoreCase))
  11.     {
  12.         // Stop the Runtime
  13.         await runtime.RunUntilIdleAsync();
  14.         break;
  15.     }
  16.     try
  17.     {
  18.         // Invoke the Orchestration
  19.         var result = await orchestration.InvokeAsync(input, runtime);
  20.         // Collect Results from multi Agents
  21.         var output = await result.GetValueAsync(TimeSpan.FromSeconds(10 * 2));
  22.         var texts = output.Select(text => $"{text}");
  23.         for (int i = 0; i < texts.Count(); i++)
  24.         {
  25.             Console.WriteLine($"# RESULT {i+1}:{Environment.NewLine}");
  26.             Console.WriteLine($"{texts.ElementAt(i).Trim()}{Environment.NewLine}");
  27.         }
  28.     }
  29.     catch (HttpOperationException ex)
  30.     {
  31.         Console.WriteLine($"Exception: {ex.Message}");
  32.     }
  33.     finally
  34.     {
  35.         Console.ResetColor();
  36.         Console.WriteLine();
  37.     }
  38. }
复制代码
需要注意的是:上面的代码示例中我手动使用了一个for循环将收集到的结果进行显示,期望显示格式为RESULT 1, RESULT 2等。
效果展示

用户输入问题:What is temperature?
NOTE:temperature中文意思为温度
3.png

可以看到,Chemist 和 Physicst 两个Agent并行思考并给出了从自己的视角出发的对于温度这个概念的解释。
因此,可以看出并发编排模式非常适合并行分析、独立子任务并集成决策的任务场景。
小结

本文介绍了Agent编排的概念以及Semantic Kernel支持的编排模式,最后通过一个案例介绍了如何实现一个并发编排模式,相信通过这个案例你能够有个感性的认识。
下一篇,我们将学习顺序编排模式,它按定义的顺序讲一个Agent的处理结果传递给下一个Agent,非常适合于工作流、管道、多阶段处理类任务。
示例源码

GitHub: https://github.com/EdisonTalk/MultiAgentOrchestration
参考资料

Microsoft Learn: https://learn.microsoft.com/zh-cn/semantic-kernel/frameworks/agent/agent-orchestration
推荐学习

圣杰:《.NET+AI | Semantic Kernel入门到精通》
 
4.jpeg

作者:爱迪生
出处:https://edisontalk.cnblogs.com
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
您需要登录后才可以回帖 登录 | 立即注册