中文字幕精品亚洲无线码二区,国产黄a三级三级三级看三级,亚洲七七久久桃花影院,丰满少妇被猛烈进入,国产小视频在线观看网站

多(duo)Agent協作入門:并發編(bian)排模式

大家(jia)好,我是Edison。

上一篇我們學習(xi)了Semantic Kernel中的AgentGroupChat實現(xian)群聊的效果,但其(qi)(qi)實多Agent協作編排還有(you)一(yi)些其(qi)(qi)他(ta)的模式。今天就來(lai)和你嘮(lao)嘮(lao)其(qi)(qi)他(ta)支持的編排模式,每篇介(jie)紹一(yi)個(ge),持續更新完。

SK支持哪些編排模式?

傳(chuan)統的單Agent系統在處理復雜多(duo)面(mian)任務的能力方(fang)(fang)面(mian)受(shou)到較多(duo)限(xian)制,因此我(wo)們會有多(duo)Agent編排協作(zuo)完成任務的需求(qiu)。Semantic Kernel支(zhi)持多(duo)種多(duo)Agent編排流程模式(shi),每(mei)個模式(shi)都針對(dui)不同(tong)的協作(zuo)方(fang)(fang)案而設計。這些模式(shi)作(zuo)為框架的一部分提供出來,我(wo)們可以自己(ji)擴(kuo)展(zhan)。

目前,Semantic Kernel支持以下編排模式(shi):

上面所有的(de)編排(pai)模(mo)(mo)式都基于統一的(de)構造和接(jie)口來實現,它抽象了(le)Agent通信、協調和結果聚合(he)的(de)復(fu)雜性,如(ru)下代碼(ma)所示(shi),只需選擇不同(tong)的(de)編排(pai)模(mo)(mo)式類即可:

// 只需修(xiu)改下面(mian)的編排(pai)模式類型即(ji)可
// or ConcurrentOrchestration, GroupChatOrchestration, HandoffOrchestration, MagenticOrchestration, ...
SequentialOrchestration orchestration = new(agentA, agentB)
{
    LoggerFactory = this.LoggerFactory
};
InProcessRuntime runtime = new();
// Start the runtime
await runtime.StartAsync();
// Invoke the orchestration and get the result
OrchestrationResult<string> result = await orchestration.InvokeAsync(task, runtime);
string text = await result.GetValueAsync();
await runtime.RunUntilIdleAsync();

因此,我們無需學習(xi)新的(de)API或重寫Agent邏輯,可(ke)以專注于(yu)應用程序的(de)編(bian)寫,真的(de)是很(hen)方(fang)便!

下面,我們(men)就來看看第一種模式(shi):并(bing)發編排。

并發(fa)編(bian)排(pai)模(mo)式簡介

并(bing)(bing)發模式(shi)使用多個Agent并(bing)(bing)行處理同(tong)一(yi)個任務,每個Agent都(dou)可(ke)以(yi)獨立處理輸入,并(bing)(bing)收集(ji)并(bing)(bing)聚合結果。此模式(shi)比(bi)較適合多種觀點或(huo)解決方案很(hen)有價值的場景(jing),比(bi)如集(ji)思廣(guang)益、群體(ti)推理以(yi)及其他投(tou)票系統。

下圖展示了多個Agent生成同一問(wen)題的不(bu)同解決方案(an),并收集其響應以進一步分析或選(xuan)擇:

實現并發編排模式

這里我們(men)來實現一個DEMO,定義兩個Agent:Physicst(物理(li)學大佬(lao)) 和 Chemist (化學大佬(lao)),它們(men)可(ke)以對用戶提出(chu)的同一個問(wen)題(ti)并(bing)行地進行思考(kao)并(bing)給出(chu)自己的解釋。

為了簡單地實現這個(ge)功能,我們創建(jian)一個(ge).NET控制臺(tai)項目,然(ran)后安裝(zhuang)以下包:

Microsoft.SemanticKernel.Agents.Core
Microsoft.SemanticKernel.Agents.OpenAI (Preview版(ban)本(ben))
Microsoft.SemanticKernel.Agents.Orchestration (Preview版(ban)本(ben))
Microsoft.SemanticKernel.Agents.Runtime.InProcess (Preview版(ban)本(ben))

需要注意(yi)的是,由于Semantic Kernel的較多功能(neng)目前(qian)還處于實(shi)驗預覽階段,所(suo)以(yi)建議在該(gai)項目的csproj文件中加入以(yi)下配置,統一取消警告:

<PropertyGroup>
  <NoWarn>$(NoWarn);CA2007;IDE1006;SKEXP0001;SKEXP0110;OPENAI001</NoWarn>
</PropertyGroup>

創建一(yi)個appsettings.json配置文件,填入以(yi)下關(guan)于(yu)LLM API的(de)配置,其中(zhong)API_KEY請輸入你自(zi)己的(de):

{
  "LLM": 
  {
    "BASE_URL": "//api.siliconflow.cn",
    "API_KEY": "******************************",
    "MODEL_ID": "Qwen/Qwen2.5-32B-Instruct"
  }
}

這里我們使用SiliconCloud提供 Qwen2.5-32B-Instruct 模型,你可以通過這個URL注冊賬號: 獲取(qu)大量免費的Token來(lai)進行(xing)本次實驗。

有了LLM API,我們可以創建一個Kernel供后續使(shi)用,這也(ye)是老(lao)面(mian)孔了:

Console.WriteLine("Now loading the configuration...");
var config = new ConfigurationBuilder()
    .AddJsonFile($"appsettings.json", optional: false, reloadOnChange: true)
    .Build();
Console.WriteLine("Now loading the chat client...");
var chattingApiConfiguration = new OpenAiConfiguration(
    config.GetSection("LLM:MODEL_ID").Value,
    config.GetSection("LLM:BASE_URL").Value,
    config.GetSection("LLM:API_KEY").Value);
var openAiChattingClient = new HttpClient(new OpenAiHttpHandler(chattingApiConfiguration.EndPoint));
var kernel = Kernel.CreateBuilder()
    .AddOpenAIChatCompletion(chattingApiConfiguration.ModelId, chattingApiConfiguration.ApiKey, httpClient: openAiChattingClient)
    .Build();

接下來,我們就一(yi)步一(yi)步地來看看核(he)心的代碼。

定義兩個Agent

這(zhe)里(li)我們來定(ding)義兩個Agent:Chemist & Physicst

(1)Chemist

var chemist = new ChatCompletionAgent()
{
    Name = "ChemistryExpert",
    Instructions = "You're an expert in chemistry, you can answer questions from a chemistry expert perspective.",
    Description = "Chemistry expert agent for answering questions in the perspective of a chemist.",
    Kernel = kernel
};

(2)Physicst

var physicist = new ChatCompletionAgent()
{
    Name = "PhysicsExpert",
    Instructions = "You're an expert in physics, you can answer questions from a physics expert perspective.",
    Description = "Physics expert agent for answering questions in the perspective of a physicst.",
    Kernel = kernel
};

選擇編排(pai)模式

這里我們選擇的是并發編排模式:ConcurrentOrchestration,將(jiang)需要(yao)編排的兩個Agent作為參數(shu)傳(chuan)遞給它:

// Set up the Concurrent Orchestration
var orchestration = new ConcurrentOrchestration(physicist, chemist);

啟動運(yun)行(xing)時

在Semantic Kernel中,需要(yao)運(yun)行時(shi)(Runtime)才能管(guan)理Agent的(de)執行,因(yin)此這里我們需要(yao)在正式開(kai)始前使用(yong)InProcessRuntime并啟動起來。

// Start the Runtime
var runtime = new InProcessRuntime();
await runtime.StartAsync();

調用編排 并(bing) 收(shou)集結果

準備工(gong)作差不多了,現在(zai)我們(men)可以開始調用編(bian)排了。編(bian)排任務(wu)時(shi)它(ta)會將任務(wu)廣(guang)播到(dao)所有Agent中,并發運行多個Agent進行任務(wu)處理,最后(hou)收集(ji)每個Agent的(de)處理結(jie)果。

這里(li)的案(an)例就是將用戶的問題傳給多(duo)個(ge)Agent并發思考并給出(chu)自己的回答。

// Start the Chat
Console.WriteLine("----------Agents are Ready. Let's Start Working!----------");
while (true)
{
    Console.WriteLine("User> ");
    var input = Console.ReadLine();
    if (string.IsNullOrWhiteSpace(input))
        continue;
    input = input.Trim();
    if (input.Equals("EXIT", StringComparison.OrdinalIgnoreCase))
    {
        // Stop the Runtime
        await runtime.RunUntilIdleAsync();
        break;
    }
    try
    {
        // Invoke the Orchestration
        var result = await orchestration.InvokeAsync(input, runtime);
        // Collect Results from multi Agents
        var output = await result.GetValueAsync(TimeSpan.FromSeconds(10 * 2));
        var texts = output.Select(text => $"{text}");
        for (int i = 0; i < texts.Count(); i++)
        {
            Console.WriteLine($"# RESULT {i+1}:{Environment.NewLine}");
            Console.WriteLine($"{texts.ElementAt(i).Trim()}{Environment.NewLine}");
        }
    }
    catch (HttpOperationException ex)
    {
        Console.WriteLine($"Exception: {ex.Message}");
    }
    finally
    {
        Console.ResetColor();
        Console.WriteLine();
    }
}

需要注意的(de)是:上(shang)面(mian)的(de)代碼示(shi)例(li)中我手動(dong)使用了一(yi)個for循環將收集到的(de)結果進(jin)行顯(xian)示(shi),期(qi)望顯(xian)示(shi)格(ge)式為RESULT 1, RESULT 2等。

效(xiao)果展(zhan)示

用戶輸入問題:What is temperature?

NOTE:temperature中(zhong)文(wen)意思為溫度

可以看到,Chemist 和 Physicst 兩(liang)個(ge)Agent并行思考并給出(chu)了從自己的視角出(chu)發(fa)的對于溫度這個(ge)概念的解釋。

因(yin)此,可以看出并(bing)發編排模式(shi)非常適合并(bing)行分(fen)析、獨立子任務(wu)并(bing)集成決策(ce)的任務(wu)場(chang)景。

小結

本文(wen)介(jie)紹(shao)了(le)Agent編排(pai)的概念以及Semantic Kernel支持(chi)的編排(pai)模(mo)式,最后(hou)通過一個案(an)例(li)介(jie)紹(shao)了(le)如何實(shi)現一個并發編排(pai)模(mo)式,相信通過這個案(an)例(li)你能夠有個感性的認識。

下一(yi)(yi)篇,我(wo)們將(jiang)學習順(shun)序(xu)編排模式,它按定義的(de)(de)順(shun)序(xu)講一(yi)(yi)個Agent的(de)(de)處(chu)理結(jie)果傳遞給(gei)下一(yi)(yi)個Agent,非常適合于工作流、管道、多(duo)階(jie)段處(chu)理類任務。

示例源碼

GitHub: 

參考資料

Microsoft Learn: 

推薦學習

圣杰:.NET+AI | Semantic Kernel入門到精通

 

posted @ 2025-07-14 08:30  EdisonZhou  閱讀(520)  評論(0)    收藏  舉報