次の方法で共有


シーケンシャル オーケストレーション

Von Bedeutung

エージェント フレームワークのエージェント オーケストレーション機能は、試験段階にあります。 これらはアクティブな開発中であり、プレビューまたはリリース候補ステージに進む前に大幅に変更される可能性があります。

順次オーケストレーションでは、エージェントはパイプラインに編成されます。 各エージェントはタスクを順番に処理し、その出力をシーケンス内の次のエージェントに渡します。 これは、ドキュメント レビュー、データ処理パイプライン、マルチステージ推論など、各ステップが前の手順に基づいて構築されるワークフローに最適です。

パターンを使用するタイミングや、ワークロードでパターンを回避するタイミングなど、パターンの詳細については、「 シーケンシャル オーケストレーション」を参照してください。

一般的なユース ケース

ドキュメントは、要約エージェント、翻訳エージェント、そして最後に品質保証エージェントを順に通過し、それぞれが前の出力を基にします。

ダイアグラム

ここでは、次の内容について学習します

  • エージェントのシーケンスを定義する方法(それぞれが特殊なロールを持つ)
  • 各エージェントが前のエージェントの出力を処理するようにこれらのエージェントを調整する方法
  • 中間出力を観察し、最終的な結果を収集する方法

エージェントの定義

エージェントは、タスクを順番に処理する特殊なエンティティです。 ここでは、アナリスト、コピーライター、エディターの 3 つのエージェントを定義します。

ヒント

ここでは 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 ではまだ使用できません。

次のステップ