Bagikan melalui


Orkestrasi Berurutan

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.

Dalam orkestrasi berurutan, agen diatur dalam sebuah pipeline. Setiap agen memproses tugas secara bergantian, meneruskan outputnya ke agen berikutnya secara berurutan. Ini sangat ideal untuk alur kerja di mana setiap langkah dibangun berdasarkan yang sebelumnya, seperti tinjauan dokumen, alur pemrosesan data, atau penalaran multi-tahap.

Untuk mempelajari selengkapnya tentang pola, seperti kapan menggunakan pola atau kapan harus menghindari pola dalam beban kerja Anda, lihat Orkestrasi berurutan.

Kasus penggunaan umum

Dokumen melewati agen ringkasan, lalu agen terjemahan, dan akhirnya agen jaminan kualitas, masing-masing membangun di atas hasil sebelumnya.

bagan

Apa yang akan Anda Pelajari

  • Cara menentukan urutan agen, masing-masing dengan peran khusus
  • Cara mengatur agen ini sehingga setiap memproses output dari yang sebelumnya
  • Cara mengamati output perantara dan mengumpulkan hasil akhir

Tentukan Agen Anda

Agen adalah entitas khusus yang memproses tugas secara berurutan. Di sini, kami mendefinisikan tiga agen: analis, copywriter, dan editor.

Petunjuk / Saran

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

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,
};

Opsional: Perhatikan Respons Agen

Anda dapat membuat panggilan balik untuk mengambil respons agen saat urutan berlangsung melalui ResponseCallback properti .

ChatHistory history = [];

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

Menyiapkan Orkestrasi Berurutan

Buat objek SequentialOrchestration, dengan menyertakan agen dan panggilan balik respons opsional.

SequentialOrchestration orchestration = new(analystAgent, writerAgent, editorAgent)
{
    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 awal Anda (misalnya, deskripsi produk). Hasil akan mengalir melalui setiap agen dalam urutan satu per satu.

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

Kumpulkan Hasil

Tunggu hingga orkestrasi selesai dan ambil output akhir.

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

Opsional: Hentikan Runtime

Setelah pemrosesan selesai, hentikan runtime untuk membersihkan sumber daya.

await runtime.RunUntilIdleAsync();

Sampel Output

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

Petunjuk / Saran

Kode sampel lengkap tersedia di sini

Tentukan Agen Anda

Setiap agen dalam urutan memiliki tanggung jawab tertentu. Dalam contoh ini, kita memiliki:

  • ConceptExtractorAgent: Mengekstrak fitur utama, audiens target, dan titik penjualan unik dari deskripsi produk.
  • WriterAgent: Menyusun salinan pemasaran berdasarkan informasi yang diekstrak.
  • FormatProofAgent: Mengedit dan memoles salinan draf untuk kejelasan dan konsistensi.

Petunjuk / Saran

ChatCompletionAgent digunakan di sini bersama Azure OpenAI; namun, Anda dapat menggunakan jenis agen atau layanan model apa pun.

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]

Opsional: Perhatikan Respons Agen

Anda dapat mendefinisikan fungsi callback untuk mengamati dan mencetak output dari setiap agen seiring dengan perkembangan urutan.

from semantic_kernel.contents import ChatMessageContent

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

Menyiapkan Orkestrasi Berurutan

Objek SequentialOrchestration, memasukkan agen dan pemanggilan balik respons yang bersifat opsional.

from semantic_kernel.agents import SequentialOrchestration

agents = get_agents()
sequential_orchestration = SequentialOrchestration(
    members=agents,
    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 awal Anda (misalnya, deskripsi produk). Hasil akan mengalir melalui setiap agen dalam urutan satu per satu.

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

Kumpulkan Hasil

Tunggu hingga orkestrasi selesai.

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

Opsional: Hentikan Runtime

Setelah pemrosesan selesai, hentikan runtime untuk membersihkan sumber daya.

await runtime.stop_when_idle()

Sampel Output

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

Petunjuk / Saran

Kode sampel lengkap tersedia di sini.

Nota

Orkestrasi agen belum tersedia di Java SDK.

Langkah selanjutnya