次の方法で共有


マゼンティック オーケストレーション

Von Bedeutung

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

マゼンティック オーケストレーションは、AutoGen によって発明された Magentic-One システムに基づいて設計されています。 これは、動的なコラボレーションを必要とする複雑で自由なタスク用に設計された、柔軟で汎用のマルチエージェント パターンです。 このパターンでは、専用の Magentic マネージャーが専門エージェントのチームを調整し、進化するコンテキスト、タスクの進行状況、およびエージェントの機能に基づいて次に対応するエージェントを選択します。

Magentic マネージャーは、共有コンテキストを維持し、進行状況を追跡し、ワークフローをリアルタイムで調整します。 これにより、システムは複雑な問題を分解し、サブタスクを委任し、エージェントのコラボレーションを通じてソリューションを繰り返し絞り込むことができます。 オーケストレーションは、ソリューション パスが事前に不明で、複数の推論、調査、計算が必要になる場合があるシナリオに特に適しています。

ヒント

Magentic-One の詳細 については、こちらをご覧ください

ヒント

"Magentic" という名前は、"Magentic-One" から取得されます。 "Magentic-One" は、 WebSurferFileSurferなどの一連のエージェントを含むマルチエージェント システムです。 セマンティック カーネル マゼンティック オーケストレーションは、 Magentic マネージャーが特殊なエージェントのチームを調整して複雑なタスクを解決する Magentic-One システムに着想を得ました。 ただし、Magentic-One システムの直接的な実装ではなく、Magentic-One システムのエージェントは機能しません。

パターンを使用するタイミングや、ワークロードでパターンを回避するタイミングなど、パターンの詳細については、 マゼンティック オーケストレーションに関するページを参照してください。

一般的なユース ケース

ユーザーは、さまざまな機械学習モデルのエネルギー効率と CO₂ 排出量を比較する包括的なレポートを要求します。 Magentic マネージャーは、まず、関連するデータを収集する研究エージェントを割り当て、次に分析と計算をコーダー エージェントに委任します。 マネージャーは、複数の研究と計算のラウンドを調整し、結果を集計し、最終的な出力として詳細で構造化されたレポートを生成します。

ダイアグラム

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

  • Magentic オーケストレーションのエージェントを定義および構成する方法
  • エージェントのコラボレーションを調整するマゼンティック マネージャーを設定する方法
  • 計画、進行状況の追跡、最終的な回答の合成など、オーケストレーション プロセスのしくみ

エージェントの定義

マゼンティック パターンの各エージェントには、特殊な役割があります。 この例では:

  • ResearchAgent: 情報を検索して要約します (Web 検索など)。 このサンプルでは、web 検索機能にChatCompletionAgent モデルでgpt-4o-search-previewを使用しています。
  • CoderAgent: データを分析または処理するコードを書き込んで実行します。 コード インタープリターのような高度なツールがあるため、このサンプルでは AzureAIAgent を使用しています。

ヒント

ここでは ChatCompletionAgentAzureAIAgent を使用しますが、任意の エージェントの種類を使用できます。

using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Agents;
using Microsoft.SemanticKernel.Agents.AzureAI;
using Microsoft.SemanticKernel.Agents.Magentic;
using Microsoft.SemanticKernel.Agents.Orchestration;
using Microsoft.SemanticKernel.Agents.Runtime.InProcess;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.OpenAI;
using Azure.AI.Agents.Persistent;
using Azure.Identity;

// Helper function to create a kernel with chat completion
public static Kernel CreateKernelWithChatCompletion(...)
{
    ...
}

// Create a kernel with OpenAI chat completion for the research agent
Kernel researchKernel = CreateKernelWithChatCompletion("gpt-4o-search-preview");
ChatCompletionAgent researchAgent = new ChatCompletionAgent {
    Name = "ResearchAgent",
    Description = "A helpful assistant with access to web search. Ask it to perform web searches.",
    Instructions = "You are a Researcher. You find information without additional computation or quantitative analysis.",
    Kernel = researchKernel,
};

// Create a persistent Azure AI agent for code execution
PersistentAgentsClient agentsClient = AzureAIAgent.CreateAgentsClient(endpoint, new AzureCliCredential());
PersistentAgent definition = await agentsClient.Administration.CreateAgentAsync(
    modelId,
    name: "CoderAgent",
    description: "Write and executes code to process and analyze data.",
    instructions: "You solve questions using code. Please provide detailed analysis and computation process.",
    tools: [new CodeInterpreterToolDefinition()]);
AzureAIAgent coderAgent = new AzureAIAgent(definition, agentsClient);

Magentic Manager を設定する

Magentic マネージャーは、エージェントの調整、ワークフローの計画、進行状況の追跡、最終的な回答の合成を行います。 標準マネージャー (StandardMagenticManager) は、構造化された出力をサポートするチャット完了モデルを使用します。

Kernel managerKernel = CreateKernelWithChatCompletion("o3-mini");
StandardMagenticManager manager = new StandardMagenticManager(
    managerKernel.GetRequiredService<IChatCompletionService>(),
    new OpenAIPromptExecutionSettings())
{
    MaximumInvocationCount = 5,
};

省略可能: エージェントの応答を観察する

ResponseCallback プロパティを使用してオーケストレーションの進行に応じてエージェントの応答をキャプチャするコールバックを作成できます。

ChatHistory history = [];

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

マゼンティック オーケストレーションを作成する

エージェントとマネージャーを MagenticOrchestration オブジェクトに結合します。

MagenticOrchestration orchestration = new MagenticOrchestration(
    manager,
    researchAgent,
    coderAgent)
{
    ResponseCallback = responseCallback,
};

ランタイムを開始する

エージェントの実行を管理するには、ランタイムが必要です。 ここでは、オーケストレーションを呼び出す前に、 InProcessRuntime を使用して開始します。

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

オーケストレーションを呼び出す

複雑なタスクでオーケストレーションを呼び出します。 マネージャーは、問題を解決するためにエージェントを計画、委任、調整します。

string input = @"I am preparing a report on the energy efficiency of different machine learning model architectures.\nCompare the estimated training and inference energy consumption of ResNet-50, BERT-base, and GPT-2 on standard datasets (e.g., ImageNet for ResNet, GLUE for BERT, WebText for GPT-2). Then, estimate the CO2 emissions associated with each, assuming training on an Azure Standard_NC6s_v3 VM for 24 hours. Provide tables for clarity, and recommend the most energy-efficient model per task type (image classification, text classification, and text generation).";
var result = await orchestration.InvokeAsync(input, runtime);

結果の収集

オーケストレーションが完了するのを待ち、最終的な出力を取得します。

string output = await result.GetValueAsync(TimeSpan.FromSeconds(300));
Console.WriteLine($"\n# RESULT: {output}");
Console.WriteLine("\n\nORCHESTRATION HISTORY");
foreach (ChatMessageContent message in history)
{
    // Print each message
    Console.WriteLine($"# {message.Role} - {message.AuthorName}: {message.Content}");
}

省略可能: ランタイムを停止する

処理が完了したら、ランタイムを停止してリソースをクリーンアップします。

await runtime.RunUntilIdleAsync();

サンプル出力

# RESULT: ```markdown
# Report: Energy Efficiency of Machine Learning Model Architectures

This report assesses the energy consumption and related CO₂ emissions for three popular ...

ORCHESTRATION HISTORY

# Assistant - ResearchAgent: Comparing the energy efficiency of different machine learning ...

# assistant - CoderAgent: Below are tables summarizing the approximate energy consumption and ...

# assistant - CoderAgent: The estimates provided in our tables align with a general understanding ...

# assistant - CoderAgent: Here's the updated structure for the report integrating both the ...

ヒント

完全なサンプル コードについては、こちらを参照してください

エージェントの定義

マゼンティック パターンの各エージェントには、特殊な役割があります。 この例では:

  • ResearchAgent: 情報を検索して要約します (Web 検索など)。 このサンプルでは、web 検索機能にChatCompletionAgent モデルでgpt-4o-search-previewを使用しています。
  • CoderAgent: データを分析または処理するコードを書き込んで実行します。 コード インタープリターのような高度なツールがあるため、このサンプルでは OpenAIAssistantAgent を使用しています。

ヒント

ここでは ChatCompletionAgentOpenAIAssistantAgent を使用しますが、任意の エージェントの種類を使用できます。

from semantic_kernel.agents import ChatCompletionAgent, OpenAIAssistantAgent
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion

research_agent = ChatCompletionAgent(
    name="ResearchAgent",
    description="A helpful assistant with access to web search. Ask it to perform web searches.",
    instructions="You are a Researcher. You find information without additional computation or quantitative analysis.",
    service=OpenAIChatCompletion(ai_model_id="gpt-4o-search-preview"),
)

# Create an OpenAI Assistant agent with code interpreter capability
client, model = OpenAIAssistantAgent.setup_resources()
code_interpreter_tool, code_interpreter_tool_resources = OpenAIAssistantAgent.configure_code_interpreter_tool()
definition = await client.beta.assistants.create(
    model=model,
    name="CoderAgent",
    description="A helpful assistant that writes and executes code to process and analyze data.",
    instructions="You solve questions using code. Please provide detailed analysis and computation process.",
    tools=code_interpreter_tool,
    tool_resources=code_interpreter_tool_resources,
)
coder_agent = OpenAIAssistantAgent(
    client=client,
    definition=definition,
)

Magentic Manager を設定する

Magentic マネージャーは、エージェントの調整、ワークフローの計画、進行状況の追跡、最終的な回答の合成を行います。 標準マネージャー (StandardMagenticManager) は、慎重に設計されたプロンプトを使用し、構造化された出力をサポートするチャット完了モデルを必要とします。

from semantic_kernel.agents import StandardMagenticManager
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion

manager = StandardMagenticManager(chat_completion_service=OpenAIChatCompletion())

省略可能: エージェントの応答を観察する

オーケストレーションの進行に合わせ、各エージェントのメッセージを出力するコールバックを定義できます。

from semantic_kernel.contents import ChatMessageContent

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

マゼンティック オーケストレーションを作成する

エージェントとマネージャーを MagenticOrchestration オブジェクトに結合します。

from semantic_kernel.agents import MagenticOrchestration

magentic_orchestration = MagenticOrchestration(
    members=[research_agent, coder_agent],
    manager=manager,
    agent_response_callback=agent_response_callback,
)

ランタイムを開始する

ランタイムを起動してエージェントの実行を管理します。

from semantic_kernel.agents.runtime import InProcessRuntime

runtime = InProcessRuntime()
runtime.start()

オーケストレーションを呼び出す

複雑なタスクでオーケストレーションを呼び出します。 マネージャーは、問題を解決するためにエージェントを計画、委任、調整します。

orchestration_result = await magentic_orchestration.invoke(
    task=(
        "I am preparing a report on the energy efficiency of different machine learning model architectures. "
        "Compare the estimated training and inference energy consumption of ResNet-50, BERT-base, and GPT-2 "
        "on standard datasets (e.g., ImageNet for ResNet, GLUE for BERT, WebText for GPT-2). "
        "Then, estimate the CO2 emissions associated with each, assuming training on an Azure Standard_NC6s_v3 VM "
        "for 24 hours. Provide tables for clarity, and recommend the most energy-efficient model "
        "per task type (image classification, text classification, and text generation)."
    ),
    runtime=runtime,
)

結果の収集

オーケストレーションが完了するのを待ち、最終的な結果を出力します。

value = await orchestration_result.get()
print(f"\nFinal result:\n{value}")

省略可能: ランタイムを停止する

処理が完了したら、ランタイムを停止してリソースをクリーンアップします。

await runtime.stop_when_idle()

サンプル出力

**ResearchAgent**
Estimating the energy consumption and associated CO₂ emissions for training and inference of ResNet-50, BERT-base...

**CoderAgent**
Here is the comparison of energy consumption and CO₂ emissions for each model (ResNet-50, BERT-base, and GPT-2)
over a 24-hour period:

| Model     | Training Energy (kWh) | Inference Energy (kWh) | Total Energy (kWh) | CO₂ Emissions (kg) |
|-----------|------------------------|------------------------|---------------------|---------------------|
| ResNet-50 | 21.11                  | 0.08232                | 21.19232            | 19.50               |
| BERT-base | 0.048                  | 0.23736                | 0.28536             | 0.26                |
| GPT-2     | 42.22                  | 0.35604                | 42.57604            | 39.17               |

...

Final result:
Here is the comprehensive report on energy efficiency and CO₂ emissions for ResNet-50, BERT-base, and GPT-2 models...

ヒント

完全なサンプル コードについては、 こちらをご覧ください

エージェント オーケストレーションは、Java SDK ではまだ使用できません。

次のステップ