Bagikan melalui


Orkestrasi Magnetik

Penting

Fitur Agent Orchestration dalam Kerangka Kerja Agen sedang dalam tahap eksperimental. Mereka sedang dalam pengembangan aktif dan dapat berubah secara signifikan sebelum maju ke tahap pratinjau atau tahap kandidat rilis.

Orkestrasi magentik dirancang berdasarkan sistem Magentic-One yang ditemukan oleh AutoGen. Ini adalah pola multi-agen tujuan umum yang fleksibel yang dirancang untuk tugas kompleks dan terbuka yang memerlukan kolaborasi dinamis. Dalam pola ini, manajer Magentic khusus mengoordinasikan tim agen khusus, memilih agen mana yang harus bertindak selanjutnya berdasarkan konteks yang berkembang, kemajuan tugas, dan kemampuan agen.

Manajer Magentic mempertahankan konteks bersama, melacak kemajuan, dan mengadaptasi alur kerja secara real time. Ini memungkinkan sistem untuk memecah masalah kompleks, mendelegasikan subtugas, dan memperbaiki solusi secara berulang melalui kolaborasi agen. Orkestrasi sangat cocok untuk skenario di mana jalur solusi tidak diketahui sebelumnya dan mungkin memerlukan beberapa putaran penalaran, penelitian, dan komputasi.

Petunjuk / Saran

Baca selengkapnya tentang Magentic-One di sini.

Petunjuk / Saran

Nama "Magentic" berasal dari "Magentic-One". "Magentic-One" adalah sistem multi-agen yang mencakup satu set agen, seperti WebSurfer dan FileSurfer. Orkestrasi Semantic Kernel Magentic terinspirasi oleh sistem Magentic-One di mana Magentic manajer mengoordinasikan tim agen khusus untuk menyelesaikan tugas yang kompleks. Namun, ini bukan implementasi langsung dari sistem Magentic-One dan tidak menampilkan agen dari sistem Magentic-One.

Kasus penggunaan umum

Pengguna meminta laporan komprehensif yang membandingkan efisiensi energi dan emisi CO₂ dari model pembelajaran mesin yang berbeda. Manajer Magentic pertama-tama menetapkan agen penelitian untuk mengumpulkan data yang relevan, kemudian mendelegasikan analisis dan komputasi ke agen coder. Manajer mengoordinasikan beberapa putaran penelitian dan komputasi, menggabungkan temuan, dan menghasilkan laporan terstruktur yang terperinci sebagai output akhir.

bagan

Apa yang akan Anda Pelajari

  • Cara menentukan dan mengonfigurasi agen untuk orkestrasi Magentic
  • Cara menyiapkan manajer Magentic untuk mengoordinasikan kolaborasi agen
  • Cara kerja proses orkestrasi, termasuk perencanaan, pelacakan kemajuan, dan sintesis jawaban akhir

Tentukan Agen Anda

Setiap agen dalam pola Magentic memiliki peran khusus. Dalam contoh ini:

  • ResearchAgent: Menemukan dan meringkas informasi (misalnya, melalui pencarian web). Di sini sampel menggunakan ChatCompletionAgent dengan gpt-4o-search-preview model untuk kemampuan pencarian webnya.
  • CoderAgent: Menulis dan menjalankan kode untuk menganalisis atau memproses data. Di sini sampel menggunakan AzureAIAgent karena memiliki alat tingkat lanjut seperti penerjemah kode.

Petunjuk / Saran

ChatCompletionAgent dan AzureAIAgent digunakan di sini, tetapi Anda dapat menggunakan jenis agen apa pun.

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);

Menyiapkan Magnetic Manager

Manajer Magentic mengoordinasikan agen, merencanakan alur kerja, melacak kemajuan, dan mensintesis jawaban akhir. Manajer standar (StandardMagenticManager) menggunakan model penyelesaian obrolan yang mendukung output terstruktur.

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

Opsional: Perhatikan Respons Agen

Anda dapat membuat panggilan balik untuk menangkap respons agen saat orkestrasi berlangsung melalui ResponseCallback properti .

ChatHistory history = [];

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

Membuat Orkestrasi Magentik

Gabungkan agen dan manajer Anda ke dalam MagenticOrchestration objek.

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

Mulai Runtime

Runtime diperlukan untuk mengelola eksekusi agen. Di sini, kita menggunakan InProcessRuntime dan memulainya sebelum memanggil orkestrasi.

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

Memanggil Orkestrasi

Panggil orkestrasi dengan tugas kompleks Anda. Manajer akan merencanakan, mendelegasikan, dan mengoordinasikan agen untuk menyelesaikan masalah.

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);

Kumpulkan Hasil

Tunggu hingga orkestrasi selesai dan ambil output akhir.

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}");
}

Opsional: Hentikan Runtime

Setelah pemrosesan selesai, hentikan runtime untuk membersihkan sumber daya.

await runtime.RunUntilIdleAsync();

Sampel Output

# 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 ...

Petunjuk / Saran

Kode sampel lengkap tersedia di sini

Tentukan Agen Anda

Setiap agen dalam pola Magentic memiliki peran khusus. Dalam contoh ini:

  • ResearchAgent: Menemukan dan meringkas informasi (misalnya, melalui pencarian web). Di sini sampel menggunakan ChatCompletionAgent dengan gpt-4o-search-preview model untuk kemampuan pencarian webnya.
  • CoderAgent: Menulis dan menjalankan kode untuk menganalisis atau memproses data. Di sini sampel menggunakan OpenAIAssistantAgent karena memiliki alat tingkat lanjut seperti penerjemah kode.

Petunjuk / Saran

ChatCompletionAgent dan OpenAIAssistantAgent digunakan di sini, tetapi Anda dapat menggunakan jenis agen apa pun.

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,
)

Menyiapkan Magnetic Manager

Manajer Magentic mengoordinasikan agen, merencanakan alur kerja, melacak kemajuan, dan mensintesis jawaban akhir. Manajer standar (StandardMagenticManager) menggunakan perintah yang dirancang dengan cermat dan memerlukan model penyelesaian obrolan yang mendukung output terstruktur.

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

manager = StandardMagenticManager(chat_completion_service=OpenAIChatCompletion())

Opsional: Perhatikan Respons Agen

Anda dapat menentukan panggilan balik untuk mencetak pesan setiap agen saat orkestrasi berlangsung.

from semantic_kernel.contents import ChatMessageContent

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

Membuat Orkestrasi Magentik

Gabungkan agen dan manajer Anda ke dalam MagenticOrchestration objek.

from semantic_kernel.agents import MagenticOrchestration

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

Mulai Runtime

Mulai runtime untuk mengelola eksekusi agen.

from semantic_kernel.agents.runtime import InProcessRuntime

runtime = InProcessRuntime()
runtime.start()

Memanggil Orkestrasi

Panggil orkestrasi dengan tugas kompleks Anda. Manajer akan merencanakan, mendelegasikan, dan mengoordinasikan agen untuk menyelesaikan masalah.

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,
)

Kumpulkan Hasil

Tunggu hingga orkestrasi selesai dan cetak hasil akhir.

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

Opsional: Hentikan Runtime

Setelah pemrosesan selesai, hentikan runtime untuk membersihkan sumber daya.

await runtime.stop_when_idle()

Sampel Output

**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...

Petunjuk / Saran

Kode sampel lengkap tersedia di sini.

Nota

Orkestrasi agen belum tersedia di Java SDK.

Langkah selanjutnya