Velamuvi AIAcademy

Lesson 26 of 39 · Workflows

Workflow Basics: Executors, Edges and Events

Build your first Microsoft Agent Framework workflow: executors with handlers, WorkflowContext, edges, supersteps, events, streaming and graph validation.

  • 14 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Explain when a workflow is a better fit than a single agent
  • Write executors as classes with @handler and as functions with @executor
  • Pass messages with send_message and return results with yield_output
  • Connect executors with WorkflowBuilder and run them, with or without streaming
  • Read workflow events and catch graph mistakes before a run starts

Agents decide, workflows follow a plan

An agent chooses its own next step: the model reads the conversation and decides whether to call a tool, which one, and when to stop. That freedom is great for open questions, but sometimes you already know the steps. Check an order, then charge the card, then send the email, always in that order.

For those jobs, Agent Framework has workflows.

AgentWorkflow
Who chooses the next stepThe modelYour graph
Good forOpen questions, conversations, tool useKnown processes: pipelines, approvals, routing
Same input, same path?Not alwaysYes, so it is easier to test and audit
Can use the other?Agents can call workflows as toolsExecutors can wrap agents (a later lesson)

You don't have to choose one forever: most real systems mix both. This module teaches workflows from the ground up; the next module adds ready-made multi-agent workflows called orchestrations.

Your first workflow

This workflow cleans up a piece of text, then counts its words:

import asyncio
from typing import Never

from agent_framework import Executor, WorkflowBuilder, WorkflowContext, executor, handler


class CleanText(Executor):                                   # an executor written as a class
    @handler
    async def clean(self, text: str, ctx: WorkflowContext[str]) -> None:
        cleaned = " ".join(text.split())                     # remove extra spaces
        await ctx.send_message(cleaned)                      # pass it along the edge


@executor(id="count_words")                                  # an executor written as a function
async def count_words(text: str, ctx: WorkflowContext[Never, int]) -> None:
    await ctx.yield_output(len(text.split()))                # a result for the caller


async def main():
    clean = CleanText(id="clean_text")
    workflow = (
        WorkflowBuilder(start_executor=clean)                # where every run begins
        .add_edge(clean, count_words)                        # clean_text -> count_words
        .build()                                             # checks the graph, returns a Workflow
    )
    result = await workflow.run("  Agents   make   plans  ")
    print("Outputs:", result.get_outputs())
    print("State:", result.get_final_state())
    print()
    for event in result:                                     # the result is a list of events
        where = event.executor_id or f"superstep {event.iteration}"
        print(f"{event.type:<20} {where}")


asyncio.run(main())
Output
Outputs: [3]
State: WorkflowRunState.IDLE

superstep_started    superstep 1
executor_invoked     clean_text
executor_completed   clean_text
superstep_completed  superstep 1
superstep_started    superstep 2
executor_invoked     count_words
output               count_words
executor_completed   count_words
superstep_completed  superstep 2

Step by step:

  1. A class executor. CleanText subclasses Executor. Its method marked with @handler runs when a message arrives. Every executor needs a unique id, given when you create it: CleanText(id="clean_text").
  2. A function executor. For small steps, the @executor decorator turns an async function into an executor (a FunctionExecutor). Its id goes in the decorator.
  3. Type hints matter. The type of the first parameter (text: str) says which messages the executor accepts. The framework reads it to route messages and to check the graph.
  4. The context. The second parameter, WorkflowContext, is how an executor talks to the workflow. await ctx.send_message(...) passes a message along the outgoing edges; await ctx.yield_output(...) hands a result to whoever ran the workflow.
  5. The builder. WorkflowBuilder(start_executor=...) names the first executor, .add_edge(a, b) connects two executors, and .build() checks everything and returns a Workflow. For a straight line of steps, .add_chain([a, b, c]) adds all the edges at once.
  6. The result. await workflow.run(message) returns a WorkflowRunResult: a list of every event of the run, with helper methods such as get_outputs().

What the WorkflowContext type says

The square brackets after WorkflowContext declare what an executor may send and yield. The first type is for messages to other executors; the second is for workflow outputs.

Annotationsend_message sendsyield_output yields
WorkflowContextnothingnothing
WorkflowContext[str]strnothing
WorkflowContext[Never, int]nothingint
WorkflowContext[str, int]strint
WorkflowContext[str | int]str or intnothing

Never comes from Python's typing module and means "nothing". Agent Framework needs Python 3.11 or newer, which has it built in.

Supersteps: how messages move

A workflow runs in rounds called supersteps. In each superstep, every executor that has a message waiting runs once (at the same time, if there are several). The messages they send are delivered at the end of the superstep, so their targets run in the next one. The run ends when no messages are left.

Here is that idea as a tiny engine in plain Python. Change the starting text, or add a third step:

Try it yourselfPython
# A tiny workflow engine in plain Python, to see how supersteps work.
def clean(text):
    return [("count", " ".join(text.split()))], []         # (messages to send, outputs)

def count(text):
    return [], [len(text.split())]

executors = {"clean": clean, "count": count}
inbox = [("clean", "  Agents   make   plans  ")]           # messages waiting for delivery
outputs, superstep = [], 0
while inbox:                                               # stop when no messages are left
    superstep += 1
    print(f"superstep {superstep}: running {[name for name, _ in inbox]}")
    next_inbox = []
    for name, message in inbox:                            # every executor with mail runs once
        sent, yielded = executors[name](message)
        next_inbox += sent                                 # delivered in the NEXT superstep
        outputs += yielded
    inbox = next_inbox
print("outputs:", outputs)

Look back at the real events above: the same two supersteps, clean_text in the first and count_words in the second. Supersteps make runs predictable. Parallel branches always meet at a superstep boundary, and a workflow can be saved between supersteps (the checkpoint lesson uses this).

A workflow stops with an error after max_iterations supersteps, which is DEFAULT_MAX_ITERATIONS (100) unless you pass another number to WorkflowBuilder. That protects you from endless loops; the next lesson shows when you meet it.

Events: what happened during a run

Every run produces a stream of WorkflowEvent objects. Each one has a type; the possible values are listed in WorkflowEventType:

Event typeWhen it appearsUseful fields
started, statusThe run started or its state changedstate
superstep_started, superstep_completedA superstep began or endediteration
executor_invoked, executor_completedAn executor's handler started or finishedexecutor_id, data
executor_failed, failedAn executor raised an error; the run stoppedexecutor_id, details
output, intermediateAn executor yielded a final result or a progress updateexecutor_id, data
warning, errorYour code reported a problem that doesn't stop the rundata
request_infoAn executor is waiting for a person (a later lesson)request_id, data
group_chat, handoff_sent, magentic_orchestratorEvents from the orchestrations moduledata
executor_bypassedA step was skipped because its result was replayed from a saved runexecutor_id

A WorkflowRunResult has helpers so you rarely loop over the events yourself:

MethodReturns
get_outputs()Everything executors yielded as output
get_intermediate_outputs()Progress updates (next section)
get_final_state()A WorkflowRunState: IDLE when finished, IDLE_WITH_PENDING_REQUESTS when waiting for a person, FAILED and others
get_request_info_events()Questions the workflow is waiting to have answered
status_timeline()The status events, in order

status events are only included in a normal run if you ask for them: workflow.run(message, include_status_events=True).

Streaming events as they happen

run() waits until the workflow has finished. Pass stream=True to get each event the moment it happens, which is how you show live progress in a user interface:

import asyncio
from typing import Never

from agent_framework import WorkflowBuilder, WorkflowContext, executor


@executor(id="clean_text")
async def clean_text(text: str, ctx: WorkflowContext[str, str]) -> None:   # sends str, yields str
    cleaned = " ".join(text.split())
    await ctx.yield_output(f"cleaned {len(text) - len(cleaned)} extra characters")  # progress
    await ctx.send_message(cleaned)


@executor(id="count_words")
async def count_words(text: str, ctx: WorkflowContext[Never, int]) -> None:
    await ctx.yield_output(len(text.split()))


async def main():
    workflow = WorkflowBuilder(
        start_executor=clean_text,
        output_from=[count_words],                 # the final answer
        intermediate_output_from=[clean_text],     # progress updates
    ).add_edge(clean_text, count_words).build()

    stream = workflow.run("  one   two three   four ", stream=True)
    async for event in stream:                     # events arrive while the workflow runs
        if event.type == "executor_invoked":
            print("running:", event.executor_id)
        elif event.type == "intermediate":
            print("progress:", event.data)
        elif event.type == "output":
            print("output:", event.data)
    result = await stream.get_final_response()     # the same WorkflowRunResult as run()
    print("final:", result.get_outputs(), result.get_final_state().value)


asyncio.run(main())
Output
running: clean_text
progress: cleaned 7 extra characters
running: count_words
output: 4
final: [4] IDLE
  • With stream=True, run() returns a stream you read with async for. Afterwards, await stream.get_final_response() gives the same WorkflowRunResult that a normal run returns. A streamed run also includes the started and status events.
  • output_from says which executors give the final answer, and intermediate_output_from which ones give progress updates. Their yield_output calls become output and intermediate events. If you set neither, every yield_output is an output. If you set either one, executors you didn't list are hidden.

One executor, several message types

An executor can have several handlers. The framework calls the one whose parameter type matches the message:

import asyncio
from typing import Never

from agent_framework import Executor, WorkflowBuilder, WorkflowContext, WorkflowEvent, executor, handler


@executor(id="split")
async def split(text: str, ctx: WorkflowContext[str | int]) -> None:    # may send str or int
    await ctx.send_message(text)
    await ctx.send_message(len(text))


class Describe(Executor):
    @handler                                                   # chosen for str messages
    async def on_text(self, text: str, ctx: WorkflowContext[Never, str]) -> None:
        if len(text) > 20:
            await ctx.add_event(WorkflowEvent.warning("long text, showing the first 20 characters"))
        await ctx.yield_output(f"text: {text[:20]}")

    @handler                                                   # chosen for int messages
    async def on_number(self, number: int, ctx: WorkflowContext[Never, str]) -> None:
        await ctx.yield_output(f"length: {number}")


async def main():
    describe = Describe(id="describe")
    workflow = WorkflowBuilder(start_executor=split).add_edge(split, describe).build()
    result = await workflow.run("Workflows route messages by type")
    for event in result:
        if event.type in ("warning", "output"):
            print(event.type, "->", event.data)


asyncio.run(main())
Output
warning -> long text, showing the first 20 characters
output -> text: Workflows route mess
output -> length: 32

split declares WorkflowContext[str | int], so it may send both types. Describe handles the text with on_text and the number with on_number. ctx.add_event(WorkflowEvent.warning(...)) adds a warning event that callers can show, without stopping the run.

Mistakes caught before the run: validation

build() checks the graph before anything runs and raises a WorkflowValidationError if something is wrong. Runtime errors are different: they stop a run that has already started. This program shows both:

import asyncio
from typing import Never

from agent_framework import GraphConnectivityError, WorkflowBuilder, WorkflowContext, WorkflowValidationError, executor


@executor(id="clean_text")
async def clean_text(text: str, ctx: WorkflowContext[str]) -> None:
    await ctx.send_message(" ".join(text.split()))


@executor(id="count_words")
async def count_words(text: str, ctx: WorkflowContext[Never, int]) -> None:
    if not text:
        raise ValueError("nothing to count")
    await ctx.yield_output(len(text.split()))


@executor(id="audit")
async def audit(text: str, ctx: WorkflowContext[str]) -> None:
    await ctx.send_message(text)


async def main():
    # 1. Mistakes in the graph are caught by build(), before anything runs.
    try:
        (WorkflowBuilder(start_executor=clean_text)
         .add_edge(clean_text, count_words)
         .add_edge(audit, count_words)             # nothing ever sends to audit
         .build())
    except GraphConnectivityError as error:        # a kind of WorkflowValidationError
        print(isinstance(error, WorkflowValidationError), error)

    # 2. An exception inside an executor stops the run.
    workflow = WorkflowBuilder(start_executor=clean_text).add_edge(clean_text, count_words).build()
    try:
        async for event in workflow.run("    ", stream=True):
            if event.type == "executor_failed":
                print("failed in", event.executor_id, "with", event.details.error_type)
    except ValueError as error:
        print("run raised:", error)


asyncio.run(main())
Output
True [GRAPH_CONNECTIVITY] The following executors are unreachable from the start executor 'clean_text': ['audit']. This may indicate a disconnected workflow graph.
failed in count_words with ValueError
run raised: nothing to count

build() runs these checks (the function behind them is validate_workflow_graph):

ErrorCause
GraphConnectivityErrorAn executor can't be reached from the start executor
TypeCompatibilityErrorAn edge connects a sender to an executor that can't handle its message type (see the Workflow State, Types and Visualization lesson)
EdgeDuplicationErrorThe same edge was added twice
WorkflowValidationErrorThe base class of all of them: catch this one to handle any graph problem

Two different executors with the same id are caught even earlier: add_edge raises ValueError: Duplicate executor ID 'same' detected in workflow.

When an executor raises an exception, the run stops. A streamed run emits executor_failed and failed events whose details is a WorkflowErrorDetails object (error_type, message, traceback, executor_id). Then run() raises the original exception. For safety, details.message and the traceback only contain the exception's text when sensitive telemetry is switched on (see the observability lesson); otherwise they just repeat the error type. Problems in the engine itself, such as running too many supersteps, raise a WorkflowRunnerException.

Common mistakes

Practice exercise

Finish the tiny workflow engine: run the steps superstep by superstep, following the edges, and collect the outputs.

Your solutionPython
def clean(text):
    return " ".join(text.split()), None        # (message to send, output)

def shout(text):
    return text.upper() + "!", None

def count(text):
    return None, len(text)

steps = {"clean": clean, "shout": shout, "count": count}
edges = {"clean": ["shout"], "shout": ["count"], "count": []}

# Run the workflow, starting with the message "  hi   there " for "clean".
# Each superstep: run every step that has a message waiting, then deliver what
# it sends to every step its edges point to (they run in the NEXT superstep).
# Print one line per superstep, like:  superstep 1: clean
# At the end print:  outputs: [...]
Knowledge check

A handler's context is annotated WorkflowContext[Never, int]. What can it do?

Summary

  • A workflow is a graph you design: executors do the work and edges carry messages between them.
  • Write executors as an Executor subclass with @handler methods, or as functions with @executor. Type hints decide which messages they accept.
  • send_message passes a message along the edges; yield_output returns a result. WorkflowContext[Send, Yield] declares both.
  • WorkflowBuilder connects executors and validates the graph in build(). run() returns a WorkflowRunResult; run(stream=True) streams events live.
  • Runs move in supersteps and stop after max_iterations. Graph mistakes raise a WorkflowValidationError subclass before anything runs.

Next: Branching, Fan-Out, Fan-In and Loops.

Finished reading? Tick it off to track your progress.