Velamuvi AIAcademy

Lesson 27 of 39 · Workflows

Branching, Fan-Out, Fan-In and Loops

Route Agent Framework workflows with conditional, switch-case and multi-selection edges, run steps in parallel with fan-out and fan-in, and build safe loops.

  • 12 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Send a message down different paths with conditional edges
  • Choose exactly one path with a switch-case edge group
  • Choose several paths at once with a multi-selection edge group
  • Run executors in parallel with fan-out and collect their results with fan-in
  • Build a loop and keep it safe with max_iterations

Every edge is a routing rule

In the last lesson, every message followed one fixed path. Real processes branch: a refund request goes to billing, a late parcel to delivery. Some work splits into parallel jobs that meet again, and some steps repeat until a check passes.

Agent Framework handles all of this with different kinds of edges. Each builder method creates an edge group: a rule that decides which targets get a message.

Builder methodEdge group it createsWhere a message goes
add_edge(a, b)SingleEdgeGroupalways to b
add_edge(a, b, condition=f)SingleEdgeGroupto b, only when f(message) is true
add_switch_case_edge_group(a, [...])SwitchCaseEdgeGroupto the target of the first case that matches
add_multi_selection_edge_group(a, targets, selection_func=f)FanOutEdgeGroupto the targets your function picks
add_fan_out_edges(a, targets)FanOutEdgeGroupto every target, in parallel
add_fan_in_edges(sources, b)FanInEdgeGroupto b, once, as a list of every source's message

Inside each group, the connections are Edge objects (a source_id, a target_id and an optional condition). You only meet them when you inspect a workflow, for example in workflow.to_dict().

Conditional edges

Give add_edge a condition: a function that receives the message and returns True or False. The message only travels along edges whose condition is true.

import asyncio
from dataclasses import dataclass
from typing import Never

from agent_framework import WorkflowBuilder, WorkflowContext, executor


@dataclass
class Ticket:
    text: str
    category: str = ""


@executor(id="classify")
async def classify(ticket: Ticket, ctx: WorkflowContext[Ticket]) -> None:
    words = ticket.text.lower()
    ticket.category = "billing" if "refund" in words or "charged" in words else "other"
    await ctx.send_message(ticket)


@executor(id="billing")
async def billing(ticket: Ticket, ctx: WorkflowContext[Never, str]) -> None:
    await ctx.yield_output(f"Billing team: {ticket.text}")


@executor(id="general")
async def general(ticket: Ticket, ctx: WorkflowContext[Never, str]) -> None:
    await ctx.yield_output(f"General queue: {ticket.text}")


async def main():
    workflow = (
        WorkflowBuilder(start_executor=classify)
        .add_edge(classify, billing, condition=lambda t: t.category == "billing")
        .add_edge(classify, general, condition=lambda t: t.category != "billing")
        .build()
    )
    for text in ["I was charged twice", "Do you ship to Iceland?"]:
        result = await workflow.run(Ticket(text))
        print(result.get_outputs())


asyncio.run(main())
Output
['Billing team: I was charged twice']
['General queue: Do you ship to Iceland?']

A condition has the type EdgeCondition: a function that takes the message and returns a bool, or an async function that returns one.

Switch-case: exactly one path

When a message should go to exactly one of several places, use a switch-case edge group. The cases are checked in order, the first match wins, and Default catches everything else:

import asyncio
from dataclasses import dataclass
from typing import Never

from agent_framework import Case, Default, WorkflowBuilder, WorkflowContext, executor


@dataclass
class Ticket:
    text: str
    category: str = ""


@executor(id="classify")
async def classify(ticket: Ticket, ctx: WorkflowContext[Ticket]) -> None:
    words = ticket.text.lower()
    if "refund" in words or "charged" in words:
        ticket.category = "billing"
    elif "parcel" in words or "delivery" in words:
        ticket.category = "delivery"
    await ctx.send_message(ticket)


def team(name: str):                                        # makes one executor per team
    @executor(id=name)
    async def handle(ticket: Ticket, ctx: WorkflowContext[Never, str]) -> None:
        await ctx.yield_output(f"{name}: {ticket.text}")
    return handle


billing, delivery, general = team("billing"), team("delivery"), team("general")


def is_billing(ticket: Ticket) -> bool:
    return ticket.category == "billing"


async def is_delivery(ticket: Ticket) -> bool:              # conditions may be async too
    return ticket.category == "delivery"


async def main():
    workflow = (
        WorkflowBuilder(start_executor=classify)
        .add_switch_case_edge_group(classify, [
            Case(condition=is_billing, target=billing),     # checked first
            Case(condition=is_delivery, target=delivery),   # checked second
            Default(target=general),                        # everything else
        ])
        .build()
    )
    for text in ["Please refund order 1182", "My parcel is late", "Love the new bike!"]:
        print((await workflow.run(Ticket(text))).get_outputs())


asyncio.run(main())
Output
['billing: Please refund order 1182']
['delivery: My parcel is late']
['general: Love the new bike!']
  • Case(condition=..., target=...) pairs a condition with a target. As the code shows, conditions can be normal functions or async ones.
  • Default(target=...) is required: leave it out and you get ValueError: SwitchCaseEdgeGroup must contain exactly one default case.
  • Because the first match wins, the order of the cases is part of your logic. Here is that rule in plain Python. Try moving the delivery case first:
Try it yourselfPython
# How a switch-case edge group chooses, in plain Python:
# the cases are checked in order, the FIRST match wins, and Default catches the rest.
cases = [
    (lambda t: "refund" in t or "charged" in t, "billing"),
    (lambda t: "parcel" in t or "delivery" in t, "delivery"),
]
default = "general"

def route(ticket):
    for condition, target in cases:
        if condition(ticket):
            return target
    return default

for ticket in ["refund my parcel", "my parcel is late", "hello there"]:
    print(f"{ticket!r:22} -> {route(ticket)}")

Multi-selection: several paths

Sometimes a message should go to some of the targets, and which ones depends on the message. A multi-selection edge group asks your selection_func(message, target_ids) and sends the message to every id it returns:

import asyncio
from dataclasses import dataclass
from typing import Never

from agent_framework import WorkflowBuilder, WorkflowContext, executor


@dataclass
class Alert:
    customer: str
    text: str
    urgent: bool
    channels: tuple[str, ...]                     # what the customer agreed to


@executor(id="new_alert")
async def new_alert(alert: Alert, ctx: WorkflowContext[Alert]) -> None:
    await ctx.send_message(alert)


def channel(name: str):
    @executor(id=name)
    async def send(alert: Alert, ctx: WorkflowContext[Never, str]) -> None:
        await ctx.yield_output(f"{name} -> {alert.customer}: {alert.text}")
    return send


email, sms, push = channel("email"), channel("sms"), channel("push")


def pick_channels(alert: Alert, target_ids: list[str]) -> list[str]:
    chosen = [t for t in target_ids if t in alert.channels]
    if not alert.urgent and "sms" in chosen:
        chosen.remove("sms")                      # texts only for urgent alerts
    return chosen


async def main():
    workflow = (
        WorkflowBuilder(start_executor=new_alert)
        .add_multi_selection_edge_group(new_alert, [email, sms, push], selection_func=pick_channels)
        .build()
    )
    alerts = [
        Alert("Ana", "Your bike is ready", urgent=False, channels=("email", "sms")),
        Alert("Ravi", "Card payment failed", urgent=True, channels=("sms", "push")),
    ]
    for alert in alerts:
        print((await workflow.run(alert)).get_outputs())


asyncio.run(main())
Output
['email -> Ana: Your bike is ready']
['sms -> Ravi: Card payment failed', 'push -> Ravi: Card payment failed']

pick_channels receives the alert and the ids of all connected targets (["email", "sms", "push"]) and returns a list. If it returns an empty list, nobody gets the message.

Fan-out and fan-in: work in parallel

Fan-out sends the same message to several executors at once. They all run in the same superstep, so slow steps such as model calls happen at the same time. Fan-in waits until every source has sent its message, then delivers them together as a list.

import asyncio
from typing import Never

from agent_framework import WorkflowBuilder, WorkflowContext, executor


@executor(id="start")
async def start(review: str, ctx: WorkflowContext[str]) -> None:
    await ctx.send_message(review)                       # one message...


@executor(id="sentiment")
async def sentiment(review: str, ctx: WorkflowContext[str]) -> None:
    await asyncio.sleep(1)                               # pretend this calls a model
    mood = "positive" if "love" in review.lower() else "negative"
    await ctx.send_message(f"sentiment={mood}")


@executor(id="length")
async def length(review: str, ctx: WorkflowContext[str]) -> None:
    await asyncio.sleep(1)
    await ctx.send_message(f"words={len(review.split())}")


@executor(id="topics")
async def topics(review: str, ctx: WorkflowContext[str]) -> None:
    await asyncio.sleep(1)
    found = [w for w in ("brakes", "price", "delivery") if w in review.lower()]
    await ctx.send_message(f"topics={found}")


@executor(id="report")
async def report(results: list[str], ctx: WorkflowContext[Never, str]) -> None:   # gets a list
    await ctx.yield_output(" | ".join(sorted(results)))


async def main():
    workers = [sentiment, length, topics]
    workflow = (
        WorkflowBuilder(start_executor=start)
        .add_fan_out_edges(start, workers)                # ...goes to all three
        .add_fan_in_edges(workers, report)                # report waits for all three
        .build()
    )
    started = asyncio.get_running_loop().time()
    result = await workflow.run("I love these brakes, but delivery took ages")
    seconds = asyncio.get_running_loop().time() - started
    print(result.get_outputs()[0])
    print(f"took about {seconds:.0f} second(s)")
    step, ran = 0, {}
    for event in result:
        if event.type == "superstep_started":
            step = event.iteration
        elif event.type == "executor_invoked":
            ran.setdefault(step, []).append(event.executor_id)
    for step, names in ran.items():
        print(f"superstep {step}: {', '.join(names)}")


asyncio.run(main())
Output
sentiment=positive | topics=['brakes', 'delivery'] | words=8
took about 1 second(s)
superstep 1: start
superstep 2: sentiment, length, topics
superstep 3: report

Three steps that each take one second finished in about one second, because they ran together in superstep 2. report declares results: list[str]: a fan-in target receives a list with one message from each source. The order of that list isn't guaranteed, so sort it, as report does, or use a type that says where each result came from.

You can also aim a single message at one fan-out target with ctx.send_message(message, target_id="sms"). The other targets don't get it.

Loops

An edge can point back to an earlier executor, which makes a loop. The loop ends when an executor stops sending messages; usually it yields a result instead. This workflow plays "guess my number" by halving the range each time:

import asyncio
from dataclasses import dataclass

from agent_framework import WorkflowBuilder, WorkflowContext, WorkflowConvergenceException, executor

SECRET = 73


@dataclass
class Range:                    # numbers that are still possible
    low: int
    high: int
    tries: int = 0


@dataclass
class Guess:
    value: int
    range: Range


@executor(id="guesser")
async def guesser(r: Range, ctx: WorkflowContext[Guess]) -> None:
    value = (r.low + r.high) // 2                                     # guess the middle
    await ctx.send_message(Guess(value, Range(r.low, r.high, r.tries + 1)))


@executor(id="judge")
async def judge(guess: Guess, ctx: WorkflowContext[Range, str]) -> None:
    r = guess.range
    if guess.value == SECRET:
        await ctx.yield_output(f"Found {guess.value} in {r.tries} tries")   # stop: no message
    elif guess.value < SECRET:
        await ctx.send_message(Range(guess.value + 1, r.high, r.tries))      # loop back
    else:
        await ctx.send_message(Range(r.low, guess.value - 1, r.tries))


async def main():
    for limit in (100, 10):
        workflow = (
            WorkflowBuilder(max_iterations=limit, start_executor=guesser)
            .add_edge(guesser, judge)
            .add_edge(judge, guesser)                    # the edge back makes the loop
            .build()
        )
        try:
            result = await workflow.run(Range(1, 100))
            print(f"max_iterations={limit}:", result.get_outputs()[0])
        except WorkflowConvergenceException as error:
            print(f"max_iterations={limit}:", error)


asyncio.run(main())
Output
max_iterations=100: Found 73 in 6 tries
max_iterations=10: Runner did not converge after 10 iterations.
  • judge either yields a result (and sends nothing, so the run ends) or sends a new Range back to guesser.
  • Everything the loop needs (low, high, tries) travels inside the messages. That keeps each run independent; the next lesson covers other ways to keep state.
  • Each round takes two supersteps (guesser, then judge), so six guesses need 12 supersteps. With max_iterations=10, the run stops with a WorkflowConvergenceException. That limit is your safety net against loops that never finish, for example when two agents keep handing work back and forth.

Common mistakes

Practice exercise

Write the selection function for a multi-selection edge group: it receives the message and the target ids, and returns the ids that should get the message.

Your solutionPython
def pick_channels(alert, target_ids):
    # alert is a dict with "urgent" (True or False) and "channels" (the ones the customer allows).
    # Return the target ids to use, in the same order as target_ids:
    # - only channels the customer allows
    # - "sms" only when the alert is urgent
    # - if nothing is left, return ["email"] so the customer still hears from you
    return []

targets = ["email", "sms", "push"]
alerts = [
    {"urgent": False, "channels": ["email", "sms"]},
    {"urgent": True, "channels": ["sms", "push"]},
    {"urgent": False, "channels": ["sms"]},
]
for alert in alerts:
    print(pick_channels(alert, targets))
Knowledge check

An executor has fan-in edges from three sources. In one run, one source decides not to send a message. What happens?

Summary

  • Conditional edges (add_edge(..., condition=f)) send a message only where the condition is true. A message that matches nothing is dropped without an error.
  • A switch-case group picks exactly one target: cases are checked in order and Default is required.
  • A multi-selection group sends to the targets your selection_func returns.
  • Fan-out runs targets in parallel in one superstep; fan-in waits for all sources and delivers a list.
  • Loops are edges back to an earlier step. End them with a yield, carry their state in messages, and rely on max_iterations, which raises a WorkflowConvergenceException.

Next: Workflow State, Types and Visualization.

Finished reading? Tick it off to track your progress.