Bagikan melalui


Konsep Inti Alur Kerja Microsoft Agent Framework - Eksekutor

Dokumen ini memberikan tampilan mendalam pada komponen Pelaksana dari sistem Microsoft Agent Framework Workflow.

Gambaran Umum

Pelaksana adalah blok penyusun mendasar yang memproses pesan dalam alur kerja. Mereka adalah unit pemrosesan otonom yang menerima pesan yang ditik, melakukan operasi, dan dapat menghasilkan pesan output atau peristiwa.

Eksekutor mewarisi dari kelas dasar Executor<TInput, TOutput>. Setiap pelaksana memiliki pengidentifikasi unik dan dapat menangani jenis pesan tertentu.

Struktur Pelaksana Dasar

using Microsoft.Agents.AI.Workflows;
using Microsoft.Agents.AI.Workflows.Reflection;

internal sealed class UppercaseExecutor() : Executor<string, string>("UppercaseExecutor")
{
    public async ValueTask<string> HandleAsync(string message, IWorkflowContext context)
    {
        string result = message.ToUpperInvariant();
        return result; // Return value is automatically sent to connected executors
    }
}

Dimungkinkan untuk mengirim pesan secara manual tanpa mengembalikan nilai:

internal sealed class UppercaseExecutor() : Executor<string>("UppercaseExecutor")
{
    public async ValueTask HandleAsync(string message, IWorkflowContext context)
    {
        string result = message.ToUpperInvariant();
        await context.SendMessageAsync(result); // Manually send messages to connected executors
    }
}

Anda juga dapat menangani beberapa jenis input dengan menimpa metode ConfigureRoutes.

internal sealed class SampleExecutor() : Executor("SampleExecutor")
{
    protected override RouteBuilder ConfigureRoutes(RouteBuilder routeBuilder)
    {
        return routeBuilder
            .AddHandler<string>(this.HandleStringAsync)
            .AddHandler<int>(this.HandleIntAsync);
    }

    /// <summary>
    /// Converts input string to uppercase
    /// </summary>
    public async ValueTask<string> HandleStringAsync(string message, IWorkflowContext context)
    {
        string result = message.ToUpperInvariant();
        return result;
    }

    /// <summary>
    /// Doubles the input integer
    /// </summary>
    public async ValueTask<int> HandleIntAsync(int message, IWorkflowContext context)
    {
        int result = message * 2;
        return result;
    }
}

Dimungkinkan juga untuk membuat pelaksana dari fungsi dengan menggunakan BindExecutor metode ekstensi:

Func<string, string> uppercaseFunc = s => s.ToUpperInvariant();
var uppercase = uppercaseFunc.BindExecutor("UppercaseExecutor");

Eksekutor mewarisi dari kelas dasar Executor. Setiap eksekutor memiliki pengidentifikasi unik dan dapat menangani jenis pesan tertentu menggunakan metode yang dihias dengan dekorator @handler. Handler harus memiliki anotasi yang tepat untuk menentukan jenis pesan yang dapat mereka proses.

Struktur Pelaksana Dasar

from agent_framework import (
    Executor,
    WorkflowContext,
    handler,
)

class UpperCase(Executor):

    @handler
    async def to_upper_case(self, text: str, ctx: WorkflowContext[str]) -> None:
        """Convert the input to uppercase and forward it to the next node.

        Note: The WorkflowContext is parameterized with the type this handler will
        emit. Here WorkflowContext[str] means downstream nodes should expect str.
        """
        await ctx.send_message(text.upper())

Dimungkinkan untuk membuat pelaksana dari fungsi dengan menggunakan @executor dekorator:

from agent_framework import (
    WorkflowContext,
    executor,
)

@executor(id="upper_case_executor")
async def upper_case(text: str, ctx: WorkflowContext[str]) -> None:
    """Convert the input to uppercase and forward it to the next node.

    Note: The WorkflowContext is parameterized with the type this handler will
    emit. Here WorkflowContext[str] means downstream nodes should expect str.
    """
    await ctx.send_message(text.upper())

Dimungkinkan juga untuk menangani beberapa jenis input dengan menentukan beberapa handler:

class SampleExecutor(Executor):

    @handler
    async def to_upper_case(self, text: str, ctx: WorkflowContext[str]) -> None:
        """Convert the input to uppercase and forward it to the next node.

        Note: The WorkflowContext is parameterized with the type this handler will
        emit. Here WorkflowContext[str] means downstream nodes should expect str.
        """
        await ctx.send_message(text.upper())

    @handler
    async def double_integer(self, number: int, ctx: WorkflowContext[int]) -> None:
        """Double the input integer and forward it to the next node.

        Note: The WorkflowContext is parameterized with the type this handler will
        emit. Here WorkflowContext[int] means downstream nodes should expect int.
        """
        await ctx.send_message(number * 2)

WorkflowContext Objek

Objek WorkflowContext menyediakan metode bagi handler untuk berinteraksi dengan alur kerja selama eksekusi. WorkflowContext diparameterkan dengan jenis pesan yang akan dipancarkan oleh handler dan jenis output yang dapat dihasilkannya.

Metode yang paling umum digunakan adalah send_message, yang memungkinkan handler mengirim pesan ke pelaksana yang terhubung.

from agent_framework import WorkflowContext

class SomeHandler(Executor):

    @handler
    async def some_handler(message: str, ctx: WorkflowContext[str]) -> None:
        await ctx.send_message("Hello, World!")

Handler dapat digunakan yield_output untuk menghasilkan output yang akan dianggap sebagai output alur kerja dan dikembalikan/dialirkan ke pemanggil sebagai peristiwa output:

from agent_framework import WorkflowContext

class SomeHandler(Executor):

    @handler
    async def some_handler(message: str, ctx: WorkflowContext[Never, str]) -> None:
        await ctx.yield_output("Hello, World!")

Jika handler tidak mengirim pesan atau menghasilkan output, tidak ada parameter jenis yang diperlukan untuk WorkflowContext:

from agent_framework import WorkflowContext

class SomeHandler(Executor):

    @handler
    async def some_handler(message: str, ctx: WorkflowContext) -> None:
        print("Doing some work...")

Langkah Berikutnya