共用方式為


循序編排

這很重要

Agent Framework 中的代理程序協調流程功能處於實驗階段。 它們處於積極開發狀態,在晉級預覽或發行候選階段之前可能會大幅變更。

在循序編排中,代理被安置在管道中。 每個代理程式會接著處理工作,並將其輸出傳遞至序列中的下一個代理程式。 這很適合工作流程,其中每個步驟都是以上一個步驟為基礎而建置,例如檔檢閱、數據處理管線或多階段推理。

若要深入瞭解此模式,例如何時在工作負載中使用此模式或避免使用此模式,請參閱序列式協作流程

常見的使用案例

文件會經過摘要代理程式,再經過翻譯代理程式,最後是品質保證代理程式,每個都基於先前的輸出來構建:

圖表

您將學到的內容

  • 如何定義一連串代理程式,每個代理程式都有特製化角色
  • 如何協調這些代理程式,讓每個代理程序處理前一個代理程序的輸出
  • 如何觀察中繼輸出並收集最終結果

定義您的代理程式

代理程式是依序處理工作的特製化實體。 在這裡,我們會定義三個角色:分析師、撰稿人和編輯。

小提示

ChatCompletionAgent用於此處,但您可以使用任何代理程序類型

using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Agents;
using Microsoft.SemanticKernel.Agents.Orchestration;
using Microsoft.SemanticKernel.Agents.Orchestration.Sequential;
using Microsoft.SemanticKernel.Agents.Runtime.InProcess;

// Create a kernel with an AI service
Kernel kernel = ...;

ChatCompletionAgent analystAgent = new ChatCompletionAgent {
    Name = "Analyst",
    Instructions = "You are a marketing analyst. Given a product description, identify:\n- Key features\n- Target audience\n- Unique selling points",
    Kernel = kernel,
};

ChatCompletionAgent writerAgent = new ChatCompletionAgent {
    Name = "Copywriter",
    Instructions = "You are a marketing copywriter. Given a block of text describing features, audience, and USPs, compose a compelling marketing copy (like a newsletter section) that highlights these points. Output should be short (around 150 words), output just the copy as a single text block.",
    Kernel = kernel,
};

ChatCompletionAgent editorAgent = new ChatCompletionAgent {
    Name = "Editor",
    Instructions = "You are an editor. Given the draft copy, correct grammar, improve clarity, ensure consistent tone, give format and make it polished. Output the final improved copy as a single text block.",
    Kernel = kernel,
};

選項:觀察代理回應

您可以透過 ResponseCallback 屬性建立回呼,以在序列進行時擷取代理的回應。

ChatHistory history = [];

ValueTask responseCallback(ChatMessageContent response)
{
    history.Add(response);
    return ValueTask.CompletedTask;
}

設定循序協調流程

建立 SequentialOrchestration 物件,傳入代理程式和選用的回應回呼。

SequentialOrchestration orchestration = new(analystAgent, writerAgent, editorAgent)
{
    ResponseCallback = responseCallback,
};

啟動執行階段

管理代理程序的執行需要運行時間。 在這裡,我們會在叫用協調流程之前先啟動 InProcessRuntime

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

叫用協調流程

使用最初的任務(例如產品描述)來啟動協作流程。 輸出會依序流經每個代理程式。

var result = await orchestration.InvokeAsync(
    "An eco-friendly stainless steel water bottle that keeps drinks cold for 24 hours",
    runtime);

收集結果

等候協調流程完成並擷取最終輸出。

string output = await result.GetValueAsync(TimeSpan.FromSeconds(20));
Console.WriteLine($"\n# RESULT: {text}");
Console.WriteLine("\n\nORCHESTRATION HISTORY");
foreach (ChatMessageContent message in history)
{
    this.WriteAgentChatMessage(message);
}

選擇性:停止運行時間

處理完成之後,請停止運行時間以清除資源。

await runtime.RunUntilIdleAsync();

範例輸出

# RESULT: Introducing our Eco-Friendly Stainless Steel Water Bottles – the perfect companion for those who care about the planet while staying hydrated! Our bottles ...


ORCHESTRATION HISTORY

# Assistant - Analyst: **Key Features:**
- Made from eco-friendly stainless steel
- Insulation technology that maintains cold temperatures for up to 24 hours
- Reusable and sustainable design
- Various sizes and colors available (assumed based on typical offerings)
- Leak-proof cap
- BPA-free ...

# Assistant - copywriter: Introducing our Eco-Friendly Stainless ...

# Assistant - editor: Introducing our Eco-Friendly Stainless Steel Water Bottles – the perfect companion for those who care about the planet while staying hydrated! Our bottles ...

小提示

這裡提供完整的範例程序代碼

定義您的代理程式

序列中的每個代理程式都有特定的責任。 在此範例中,我們有:

  • ConceptExtractorAgent:從產品描述擷取主要功能、目標對象和獨特銷售點。
  • WriterAgent:根據擷取的資訊撰寫行銷文案。
  • FormatProofAgent:編輯和潤色草稿,以清晰和一致性為目標。

小提示

ChatCompletionAgent這裡與 Azure OpenAI 搭配使用,不過您可以使用任何代理程式類型模型服務

from semantic_kernel.agents import Agent, ChatCompletionAgent
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion

def get_agents() -> list[Agent]:
    concept_extractor_agent = ChatCompletionAgent(
        name="ConceptExtractorAgent",
        instructions=(
            "You are a marketing analyst. Given a product description, identify:\n"
            "- Key features\n"
            "- Target audience\n"
            "- Unique selling points\n\n"
        ),
        service=AzureChatCompletion(),
    )
    writer_agent = ChatCompletionAgent(
        name="WriterAgent",
        instructions=(
            "You are a marketing copywriter. Given a block of text describing features, audience, and USPs, "
            "compose a compelling marketing copy (like a newsletter section) that highlights these points. "
            "Output should be short (around 150 words), output just the copy as a single text block."
        ),
        service=AzureChatCompletion(),
    )
    format_proof_agent = ChatCompletionAgent(
        name="FormatProofAgent",
        instructions=(
            "You are an editor. Given the draft copy, correct grammar, improve clarity, ensure consistent tone, "
            "give format and make it polished. Output the final improved copy as a single text block."
        ),
        service=AzureChatCompletion(),
    )
    return [concept_extractor_agent, writer_agent, format_proof_agent]

選項:觀察代理回應

您可以定義一個回呼,以觀察並列印每個代理的輸出,隨著序列的進行。

from semantic_kernel.contents import ChatMessageContent

def agent_response_callback(message: ChatMessageContent) -> None:
    print(f"# {message.name}\n{message.content}")

設定循序協調流程

SequentialOrchestration 物件,傳入代理程式和可選回應回呼。

from semantic_kernel.agents import SequentialOrchestration

agents = get_agents()
sequential_orchestration = SequentialOrchestration(
    members=agents,
    agent_response_callback=agent_response_callback,
)

啟動執行階段

開始執行環境以管理代理程式執行。

from semantic_kernel.agents.runtime import InProcessRuntime

runtime = InProcessRuntime()
runtime.start()

叫用協調流程

使用最初的任務(例如產品描述)來啟動協作流程。 輸出會依序流經每個代理程式。

orchestration_result = await sequential_orchestration.invoke(
    task="An eco-friendly stainless steel water bottle that keeps drinks cold for 24 hours",
    runtime=runtime,
)

收集結果

等候協調流程完成。

value = await orchestration_result.get(timeout=20)
print(f"***** Final Result *****\n{value}")

選擇性:停止運行時間

處理完成之後,請停止運行時間以清除資源。

await runtime.stop_when_idle()

範例輸出

# ConceptExtractorAgent
- Key Features:
- Made of eco-friendly stainless steel
- Keeps drinks cold for 24 hours
...
# WriterAgent
Keep your beverages refreshingly chilled all day long with our eco-friendly stainless steel bottles...
# FormatProofAgent
Keep your beverages refreshingly chilled all day long with our eco-friendly stainless steel bottles...
***** Final Result *****
Keep your beverages refreshingly chilled all day long with our eco-friendly stainless steel bottles...

小提示

這裡提供完整的範例程序代碼。

備註

Java SDK 尚未提供代理程式協調流程。

後續步驟