事件

工作流事件系统提供工作流执行的可观测性。 事件在执行过程中在关键点发出,可以通过流式处理实时使用。

内置事件类型

// Workflow lifecycle events
WorkflowStartedEvent     // Workflow execution begins
WorkflowOutputEvent      // Workflow outputs data
WorkflowErrorEvent       // Workflow encounters an error
WorkflowWarningEvent     // Workflow encountered a warning

// Executor events
ExecutorInvokedEvent     // Executor starts processing
ExecutorCompletedEvent   // Executor finishes processing
ExecutorFailedEvent      // Executor encounters an error
AgentResponseEvent       // An agent run produces output
AgentResponseUpdateEvent // An agent run produces a streaming update

// Superstep events
SuperStepStartedEvent    // Superstep begins
SuperStepCompletedEvent  // Superstep completes

// Request events
RequestInfoEvent         // A request is issued

注释

当代理使用需要审批的工具时,RequestInfoEvent 通常携带一个 ToolApprovalRequestContent 有效负载,用于需要人工审批的工具调用。 有关处理这些事件的详细信息,请参阅 Human-in-the-Loop

# All events use the unified WorkflowEvent class with a type discriminator:

# Workflow lifecycle events
WorkflowEvent.type == "started"             # Workflow execution begins
WorkflowEvent.type == "status"              # Workflow state changed (use .state)
WorkflowEvent.type == "output"              # Workflow produces a terminal (final) output
WorkflowEvent.type == "intermediate"        # Workflow produces an intermediate (observational) output
WorkflowEvent.type == "failed"              # Workflow terminated with error (use .details)
WorkflowEvent.type == "error"               # Non-fatal error from user code
WorkflowEvent.type == "warning"             # Workflow encountered a warning

# Executor events
WorkflowEvent.type == "executor_invoked"    # Executor starts processing
WorkflowEvent.type == "executor_completed"  # Executor finishes processing
WorkflowEvent.type == "executor_failed"     # Executor encounters an error
WorkflowEvent.type == "data"                # Deprecated alias for "intermediate"

# Superstep events
WorkflowEvent.type == "superstep_started"   # Superstep begins
WorkflowEvent.type == "superstep_completed" # Superstep completes

# Request events
WorkflowEvent.type == "request_info"        # A request is issued

注释

当代理使用需要审批的工具时,request_info事件通常会包含Content有效负载,其中包含type == "function_approval_request"信息,用于需要人工审批的工具调用。 有关处理这些事件的详细信息,请参阅 Human-in-the-Loop

注释

"output""intermediate" 是两个输出鉴别器。 指定为终端输出源的执行器会发出"output"事件(由WorkflowRunResult.get_outputs()消费)。 被指定为中间输出源的对象会发出"intermediate"事件(由WorkflowRunResult.get_intermediate_outputs()消费)。 "data" 类型是 "intermediate" 的已弃用别名,并将在未来版本中移除;在新代码中,建议优先基于 "intermediate" 进行筛选。

使用事件

using Microsoft.Agents.AI.Workflows;

await foreach (WorkflowEvent evt in run.WatchStreamAsync())
{
    switch (evt)
    {
        case ExecutorInvokedEvent invoke:
            Console.WriteLine($"Starting {invoke.ExecutorId}");
            break;

        case ExecutorCompletedEvent complete:
            Console.WriteLine($"Completed {complete.ExecutorId}: {complete.Data}");
            break;

        case WorkflowOutputEvent output:
            Console.WriteLine($"Workflow output: {output.Data}");
            return;

        case WorkflowErrorEvent error:
            Console.WriteLine($"Workflow error: {error.Exception}");
            return;
    }
}
from agent_framework import WorkflowEvent

async for event in workflow.run(input_message, stream=True):
    if event.type == "executor_invoked":
        print(f"Starting {event.executor_id}")
    elif event.type == "executor_completed":
        print(f"Completed {event.executor_id}: {event.data}")
    elif event.type == "intermediate":
        print(f"Intermediate output from {event.executor_id}: {event.data}")
    elif event.type == "output":
        print(f"Terminal output: {event.data}")
        return
    elif event.type == "error":
        print(f"Workflow error: {event.data}")
        return

自定义事件

自定义事件允许执行程序在工作流执行期间发出特定于域的信号,以满足应用程序的需求。 一些示例用例包括:

  • 跟踪进度 - 报告中间步骤,以便调用方可以显示状态更新。
  • 发出诊断 - 在不更改工作流输出的情况下显示警告、指标或调试信息。
  • 中继域数据 - 实时将结构化有效负载(例如数据库写入、工具调用)推送到侦听器。

定义自定义事件

通过子类化 WorkflowEvent定义自定义事件。 基本构造函数接受一个可选的object? data有效负载,该有效负载通过Data属性公开。

using Microsoft.Agents.AI.Workflows;

// Simple event with a string payload
internal sealed class ProgressEvent(string step) : WorkflowEvent(step) { }

// Event with a structured payload
internal sealed class MetricsEvent(MetricsData metrics) : WorkflowEvent(metrics) { }

在 Python 中,直接使用 WorkflowEvent 类和自定义类型鉴别器字符串来创建自定义事件。 参数 typedata 携带所有信息。

from agent_framework import WorkflowEvent

# Create a custom event with a custom type string and payload
event = WorkflowEvent(type="progress", data="Step 1 complete")

# Custom event with a structured payload
event = WorkflowEvent(type="metrics", data={"latency_ms": 42, "tokens": 128})

注释

事件类型 "started""status""failed" 保留用于框架生命周期通知。 如果执行程序尝试发出其中一种类型,则会忽略该事件并记录警告。

通过创建实现 workflow.Event 接口的类型来定义自定义事件。 该方法 Data 返回事件有效负载。

type ProgressEvent struct {
    Step string
}

func (e ProgressEvent) Data() any {
    return e.Step
}

发出自定义事件

通过在AddEventAsync上调用IWorkflowContext,从执行程序的消息处理程序发出自定义事件:

using Microsoft.Agents.AI.Workflows;

internal sealed class ProgressEvent(string step) : WorkflowEvent(step) { }

internal sealed partial class CustomExecutor() : Executor("CustomExecutor")
{
    [MessageHandler]
    private async ValueTask HandleAsync(string message, IWorkflowContext context)
    {
        await context.AddEventAsync(new ProgressEvent("Validating input"));

        // Executor logic...

        await context.AddEventAsync(new ProgressEvent("Processing complete"));
    }
}

通过从处理程序调用 add_event 来触发 WorkflowContext 以下项的自定义事件:

from agent_framework import (
    handler,
    Executor,
    WorkflowContext,
    WorkflowEvent,
)

class CustomExecutor(Executor):

    @handler
    async def handle(self, message: str, ctx: WorkflowContext[str]) -> None:
        await ctx.add_event(WorkflowEvent(type="progress", data="Validating input"))

        # Executor logic...

        await ctx.add_event(WorkflowEvent(type="progress", data="Processing complete"))

通过在 workflow.Context 上调用 AddEvent,从执行器处理程序发出自定义事件:

customExecutor := workflow.NewExecutor("CustomExecutor", func(ctx *workflow.Context, message string) error {
    if err := ctx.AddEvent(ProgressEvent{Step: "Validating input"}); err != nil {
        return err
    }

    // Executor logic...

    return ctx.AddEvent(ProgressEvent{Step: "Processing complete"})
}).Bind()

消费自定义事件

使用模式匹配筛选事件流中的自定义事件类型:

await foreach (WorkflowEvent evt in run.WatchStreamAsync())
{
    switch (evt)
    {
        case ProgressEvent progress:
            Console.WriteLine($"Progress: {progress.Data}");
            break;

        case WorkflowOutputEvent output:
            Console.WriteLine($"Done: {output.Data}");
            return;
    }
}

根据自定义类型鉴别器字符串进行筛选:

async for event in workflow.run(input_message, stream=True):
    if event.type == "progress":
        print(f"Progress: {event.data}")
    elif event.type == "output":
        print(f"Done: {event.data}")
        return

使用类型开关或类型断言筛选事件流中的自定义事件类型:

for evt, err := range run.WatchStream(ctx) {
    if err != nil {
        return err
    }

    switch e := evt.(type) {
    case ProgressEvent:
        fmt.Printf("Progress: %v\n", e.Data())
    case workflow.OutputEvent:
        fmt.Printf("Done: %v\n", e.Output)
        return nil
    }
}

事件

工作流在执行期间会产生事件。 可以通过运行对象观察事件。

观察事件

run, err := inproc.Default.Run(ctx, wf, input)
for evt := range run.NewEvents() {
    switch e := evt.(type) {
    case workflow.ExecutorCompletedEvent:
        fmt.Printf("Executor %s completed: %v\n", e.ExecutorID, e.Result)
    case workflow.OutputEvent:
        fmt.Printf("Output from %s: %v\n", e.ExecutorID, e.Output)
    }
}

流媒体事件

对于流式工作流,请使用 inproc.Default.RunStreamingWatchStream

run, err := inproc.Default.RunStreaming(ctx, wf, input)
for evt, err := range run.WatchStream(ctx) {
    if err != nil {
        panic(err)
    }
    // process streaming events
}

后续步骤

相关主题