iT邦幫忙

2025 iThome 鐵人賽

DAY 20
0

今天要為大家帶來「AI 全餐」的第 20 道菜:腦力激盪:Concurrent & Group Chat Orchestration

在昨天的文章中,我們聊到了 Agent Orchestration 的重要性,以及它如何讓多個 AI 代理(Agent)像一個團隊一樣協作。今天,我們要親自動手,來看看兩種最常見的協作模式:並行模式(Concurrent)群聊模式(Group Chat)

想像一下,你是一位總鋪師,正在為一場盛大的宴會準備菜單。這時,客人問了一個棘手的問題:「什麼是溫度?」。這個問題看似簡單,但從不同角度看會有截然不同的答案。身為總鋪師,你決定把這個問題交給你的兩位頂級廚師:一位是專精物理學的「物理學家 Agent」,另一位則是精通化學的「化學家 Agent」。


Concurrent Orchestration:讓多位專家同時上菜

並行模式就像是一場烹飪競賽,你將問題同時分派給多位廚師,讓他們各自獨立思考並提出答案。這種模式的優點是效率高,可以同時獲得多個不同的觀點,非常適合需要快速收集資訊或處理多個子任務的場景。

在 Semantic Kernel 中,我們可以這樣實現:

using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Agents;
using Microsoft.Extensions.Configuration;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Agents.Orchestration.Concurrent;
using Microsoft.SemanticKernel.Agents.Runtime.InProcess;

var config = new ConfigurationBuilder()
    .AddUserSecrets<Program>()
    .Build();

var builder = Kernel.CreateBuilder()
    .AddOpenAIChatCompletion(
        modelId: "gpt-4o-mini",
        apiKey: config["OpenAI:ApiKey"]!);

var kernel = builder.Build();

// 1. 建立我們的法式廚師和中式廚師 Agent
var frenchChefAgent = new ChatCompletionAgent()
{
    Kernel = kernel,
    Name = "FrenchChef",
    Instructions = "You are an expert French chef. You answer questions from a French cuisine perspective, focusing on techniques, ingredients, and culinary traditions of France.",
    Description = "An expert in French cuisine"
};

var chineseChefAgent = new ChatCompletionAgent()
{
    Kernel = kernel,
    Name = "ChineseChef",
    Instructions = "You are an expert Chinese chef. You answer questions from a Chinese cuisine perspective, focusing on techniques, ingredients, and culinary traditions of China.",
    Description = "An expert in Chinese cuisine"
};

ConcurrentOrchestration orchestration = new(frenchChefAgent, chineseChefAgent);

InProcessRuntime runtime = new InProcessRuntime();
await runtime.StartAsync();

var result = await orchestration.InvokeAsync("製作湯品時,應該用大火快煮還是小火慢燉?哪種方法能做出最美味的湯?", runtime);

string[] output = await result.GetValueAsync(TimeSpan.FromSeconds(180));
Console.WriteLine($"# 結果:\n{string.Join("\n\n", output.Select(text => $"{text}"))}");
await runtime.RunUntilIdleAsync();

這段程式碼會讓法式廚師和中式廚師 Agent 同時收到「製作湯品時,應該用大火快煮還是小火慢燉?哪種方法能做出最美味的湯?」這個問題,並各自從自己的專業角度給出答案。你可以看到,法式廚師可能會從澄清湯底的技巧來解釋,而中式廚師則可能從文火慢燉的原理來闡述,這正是並行模式的精髓所在。


Group Chat Orchestration:模擬一場腦力激盪會議

群聊模式則更像是讓廚師們圍坐在圓桌前,共同討論如何完成一道菜。他們可以互相提問、補充,甚至推翻對方的想法,直到得出一個最完美的方案。這種模式更接近人類的溝通方式,適合需要多方協調、共同決策的複雜任務。

在 Semantic Kernel 中,我們可以利用 GroupChatOrchestration 來實現這種群聊模式。

history = [];
var orchestratorAgent = new ChatCompletionAgent()
{
    Name = "Orchestrator",
    Kernel = kernel,
    Instructions = "You are an orchestrator agent that decides which chef (FrenchChef or ChineseChef) is best suited to answer a given question about cooking techniques or recipes. You analyze the question and delegate it to the appropriate chef based on their expertise.",
    Description = "An agent that delegates cooking questions to the appropriate chef"
};

GroupChatOrchestration groupChatOrchestration =
            new(new RoundRobinGroupChatManager
            {
                MaximumInvocationCount = 5
            },
            frenchChefAgent,
            chineseChefAgent)
            {
                ResponseCallback = (response) =>
                {
                    history.Add(response);
                    return ValueTask.CompletedTask;
                }
            };

runtime = new InProcessRuntime();
await runtime.StartAsync();

var groupResult = await groupChatOrchestration.InvokeAsync(
    "如何製作一道既有法式精緻感又融合中式風味的創意料理?請提供具體的烹飪技巧和食材搭配建議。",
    runtime);
var groupOutput = await groupResult.GetValueAsync(TimeSpan.FromSeconds(180));
Console.WriteLine($"\n# 結果:\n{groupOutput}");
Console.WriteLine("\n\n協同運作歷程");
foreach (ChatMessageContent message in history)
{
    Console.WriteLine($"{message.Role} {message.AuthorName}: {message.Content}");
}

在這段程式碼中,我們將法式和中式廚師 Agent 放在一個群聊環境中。當我們提出一個需要跨越兩種料理風格的問題時,例如「如何製作一道既有法式精緻感又融合中式風味的創意料理?」,這兩個 Agent 就會開始一場協同合作。他們會像人類一樣輪流發言,互相補充和完善彼此的想法,最終產出一個整合了法式和中式精華的創意料理方案。ResponseCallback 則能幫助我們追蹤這場對話的完整過程。

小結與預告

今天,我們實作了兩種強大的 Agent 協作模式,見識到團隊合作如何解決複雜問題。無論是需要快速獲得多方意見的並行模式,還是需要深度討論的群聊模式,Semantic Kernel 都為我們提供了靈活的工具。

明天,我們將繼續深入探索 Agent 協作的更多可能性,看看 Sequential (循序模式)Handoff (交接模式) 又是如何讓 AI 流程像生產線一樣運作。準備好你的程式碼編輯器,我們明天見!

完整程式碼範例


上一篇
Day 19: 團隊合作的基礎:Agent Orchestration 概覽
系列文
AI 全餐,好吃嗎?用 Semantic Kernel 打造你的客製化滿漢全席!20
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言