磁性编排

重要

代理框架中的代理编排功能处于实验阶段。 它们处于积极开发阶段,在升级到预览版或候选发布阶段之前可能会发生重大变化。

Magentic 编排是根据 AutoGen 发明的 Magentic-One 系统设计的。 它是一种灵活的常规用途多代理模式,专为需要动态协作的复杂开放式任务而设计。 在此模式中,专用的 Magentic 管理器协调一个专用代理团队,根据不断发展的上下文、任务进度和代理功能选择下一个代理应执行下一步作。

Magentic 经理维护共享上下文、跟踪进度并实时调整工作流。 这使系统能够分解复杂的问题、委托子任务,并通过代理协作迭代优化解决方案。 编排特别适用于解决方案路径事先未知的情境,可能需要多次推理、研究和计算。

小窍门

在此处阅读有关 Magentic-One 的详细信息。

小窍门

名称“Magentic”来自“Magentic-One”。 “Magentic-One”是一个多代理系统,包括一组代理,例如 WebSurferFileSurfer。 语义内核磁性编排的灵感来自 Magentic-One 系统,其中 Magentic 经理协调一个由专门代理组成的团队来解决复杂任务。 但是,它不是 Magentic-One 系统的直接实现,也不具有来自 Magentic-One 系统的代理的功能。

若要详细了解模式,例如何时使用模式或何时避免工作负荷中的模式,请参阅 磁性编排

常见用例

用户请求一份综合报告,比较不同机器学习模型的节能和二氧化碳排放量。 Magentic 管理器首先分配一个研究代理来收集相关数据,然后将分析和计算委托给编码器代理。 经理协调多轮研究和计算,聚合结果,并生成详细的结构化报告作为最终输出。

图解

学习内容

  • 如何定义和配置 Magentic 编排的代理
  • 如何设置 Magentic 管理器以协调代理协作
  • 协调过程的工作原理,包括规划、进度跟踪和最终结果汇总

定义你的代理

Magentic 模式中的每个代理都有一个专用角色。 在本示例中:

  • ResearchAgent:查找和汇总信息(例如,通过 Web 搜索)。 此示例使用 ChatCompletionAgentgpt-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 管理器协调代理、规划工作流、跟踪进度并合成最终答案。 标准管理器 (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;
}

创建 Magnetic 编排

将代理和管理器合并到一个 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 ...

小窍门

此处提供了完整的示例代码

定义你的代理

Magentic 模式中的每个代理都有一个专用角色。 在本示例中:

  • ResearchAgent:查找和汇总信息(例如,通过 Web 搜索)。 此示例使用 ChatCompletionAgentgpt-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 管理器协调代理、规划工作流、跟踪进度并合成最终答案。 标准管理器 (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}")

创建 Magnetic 编排

将代理和管理器合并到一个 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 中尚不可用。

后续步骤