Skip to content
Blog

Conditional Edge Routing: Directing Graph Execution Based on Node Output

Learn how ADK graph workflows dispatch execution with router nodes, Event(route=...), DEFAULT_ROUTE, and dict-based edge maps for deterministic branching.

Published on • November 30, 2026

AI Assistant

Ask a prompt-based agent to classify a support ticket and then handle it, and you are hoping the model both classifies correctly and follows your procedure afterward. Hoping is not a control-flow primitive. The classification may be right while the execution path is wrong: a refund gets issued twice, an escalation gets skipped, or the “else” branch quietly never runs. Every one of those failures is a routing failure, and routing is exactly the kind of deterministic work code does better than a language model.

ADK 2.0’s graph workflows solve this by splitting the two concerns: an LLM node can do the classification, and a plain Python router plus a conditional edge does the dispatch. In this tutorial you will learn how conditional routes are declared in a Workflow, how a node emits a route value, what the engine does with it, and the validation rules that catch broken graphs before they run.

1. Anatomy of a conditional route

A graph workflow is a directed graph of nodes — agents, tools, human-input tasks, and plain functions — wired together with edges. Sequential flow is a tuple that starts with the START keyword. Conditional flow is a two-part construct: a node that emits a route value, and an edge row that maps route values to the nodes that handle them.

                      ┌──────────────────┐
   START ─────────────▶│  process_message │   (LLM agent: classifies)
                      │   (Agent node)   │
                      └────────┬─────────┘
                               │ output
                               ▼
                      ┌──────────────────┐
                      │     router       │   (Function node)
                      │ returns route=X  │
                      └───┬──────┬───────┘
            "BUG" ────────┘      └──────── "SUPPORT"
              ▼                            ▼
      ┌────────────────┐          ┌──────────────────┐
      │  handle_bug    │          │ handle_support   │
      └────────────────┘          └──────────────────┘

The router never “returns the next node.” It returns a value — a string, a number, or a boolean — and the edge dictionary decides where that value goes. That indirection is what keeps the branch topology visible in one place while the decision logic stays testable in isolation.

2. The router node emits Event(route=...)

In Python, branching is handled by a function node that returns an Event whose route field carries the dispatch key:

from google.adk import Event

def router(node_input: str):
    """Route to task B or C based on node_input."""
    if condition(node_input):
        return Event(route="RUN_TASK_C")
    return Event(route="RUN_TASK_B")

A few properties of this mechanism are worth internalizing early:

  • route is independent of output. One event can select a branch and forward a payload to it, because the route key and the data are separate fields.
  • Route values can be strings, numbers, or booleans. Nothing forces you into stringly-typed enums; "2" or True dispatch exactly like "BUG".
  • A route can be a list. If the classifier decides a message applies to two categories, returning Event(route=["BUG", "SUPPORT"]) dispatches to every matching branch — fan-out driven by the router itself.
  • The router can be pure code. Nothing requires a model call. Keyword matching, a threshold, a database lookup — anything that produces a value works, and it is unit-testable without an API key.

3. The dispatch edge is a dictionary

Emitting a route does nothing until the graph declares what each route means. That declaration is a second edge row whose first element is the router and whose second element is a dict mapping route value to target:

from google.adk import Workflow

root_agent = Workflow(
    name="routing_workflow",
    edges=[
        ("START", task_A_node, router),
        (router,
          {
            # "route value": node_to_run
            "RUN_TASK_B": task_B_node,
            "RUN_TASK_C": task_C_node,
          },
        ),
    ],
)

The dispatch table is deliberately dumb: it is data, not logic. The graph can be printed, reviewed, and diffed in a code review, while the decision rule lives in router.

DEFAULT_ROUTE is your safety net

A route value with no matching key has nowhere to go. ADK provides DEFAULT_ROUTE, which matches whenever no other branch on the same source node matched:

from google.adk import Workflow
from google.adk.workflow import DEFAULT_ROUTE  # exported alongside Edge and JoinNode

root_agent = Workflow(
    name="triage_workflow",
    edges=[
        ("START", process_message, router),
        (router, {
            "BUG": handle_bug,
            "SUPPORT": handle_support,
            "LOGISTICS": handle_logistics,
            DEFAULT_ROUTE: handle_unknown,   # anything the classifier botched
        }),
    ],
)

Treat the default branch as mandatory, not optional. Classifiers fail in production in ways your happy-path tests never anticipate — new labels, empty strings, comma-separated multi-labels — and a graph with an exhaustive DEFAULT_ROUTE degrades into a known handler instead of a runtime dispatch error.

4. A worked example: support ticket triage

Here is the full pattern: an agent classifies, a function routes, and each handler is whichever node type fits the job.

from google.adk import Agent, Event, Workflow
from google.adk.workflow import DEFAULT_ROUTE

process_message = Agent(
    name="process_message",
    model="gemini-flash-latest",
    instruction='Classify the user message as "BUG", "CUSTOMER_SUPPORT" or '
                '"LOGISTICS". If it applies to more than one, reply with a '
                "comma separated list of categories.",
    mode="single_turn",
)

def router(node_input: str):
    """Pure-code dispatch: no model call on this path."""
    routes = [r.strip() for r in node_input.split(",") if r.strip()]
    return Event(route=routes)          # multi-route fan-out

def handle_bug(node_input: str):
    return Event(message="Filing a bug ticket...")

def handle_logistics(node_input: str):
    return Event(message="Checking warehouse status...")

handle_support = Agent(
    name="handle_support",
    model="gemini-flash-latest",
    instruction="Draft one short, empathetic reply to the customer message.",
    mode="single_turn",
)

root_agent = Workflow(
    name="routing_workflow",
    edges=[
        ("START", process_message, router),
        (router, {
            "BUG": handle_bug,
            "CUSTOMER_SUPPORT": handle_support,
            "LOGISTICS": handle_logistics,
            DEFAULT_ROUTE: handle_bug,   # fail safe, not fail silent
        }),
    ],
)

Note the mixture of targets: handle_bug and handle_logistics are deterministic functions, handle_support is an LlmAgent. A branch target can be any node-like value, including another Workflow, so the same dispatch table can send one route to three lines of code and another to an entire sub-process.

5. Nested workflows as branch targets

When a branch is itself a multi-step process, nest a Workflow rather than flattening it into the parent graph:

from google.adk import Workflow

workflow_B = Workflow(
    name="workflow_B",
    edges=[("START", b_title_case, b_frame)],
)
workflow_C = Workflow(
    name="workflow_C",
    edges=[("START", c_lower_case, c_frame)],
)

root_agent = Workflow(
    name="parent_workflow",
    edges=[
        ("START", task_A1, router),
        (router, {
            "RUN_WORKFLOW_B": workflow_B,
            "RUN_WORKFLOW_C": workflow_C,
        }),
    ],
)

While the inner workflow runs, its node events bubble up to the parent for traceability. When it completes, the output of its terminal node becomes the output of the nested-workflow node on the outer edge — so the parent sees one value, and the child keeps its own local topology.

One constraint follows from this: a workflow must have at most one terminal node that produces output. If two parallel branches both end in an output, the workflow fails with a ValueError. Merge those branches with a JoinNode before the graph ends, and the conditional structure stays valid.

6. Loops are back-edges — and must contain a routed edge

The same dispatch table expresses iteration. Instead of pointing forward, a route points back to an earlier node:

from google.adk import Event, Workflow

def router(node_input: str):
    """Exit the loop when the task is done, otherwise iterate again."""
    if condition(node_input):
        return Event(route="DONE")
    return Event(route="RETRY")

root_agent = Workflow(
    name="looping_workflow",
    edges=[
        ("START", task_A_node, router),
        (router, {
            "RETRY": task_A_node,   # back-edge: re-runs task_A_node
            "DONE": final_task_node,
        }),
    ],
)

The engine validates this at build time: a cycle must contain at least one routed, conditional edge. A cycle made only of unconditional edges is rejected when the Workflow is constructed. That rule is a feature — it guarantees every loop has an escape hatch expressed in code, which is the graph equivalent of a while loop with a condition you can actually read.

7. Rules that catch broken graphs early

Beyond the single-terminal-output and no-unconditional-cycle checks, three operational rules shape conditional graphs:

  1. Agents in a graph run in single_turn mode by default. A chat-mode agent is only allowed directly after START, because it consumes conversational history rather than a node’s input. Branch handlers are almost always single_turn.
  2. Route values are matched per source node. Two routers can both define a "RETRY" route without colliding; the dispatch table belongs to the edge row, not to the graph globally.
  3. Routing is not the only dispatch mechanism. If you instead use the prebuilt sequentialagent / parallelagent / loopagent agents, there is no route dispatch at all — you would encode the decision in session state via OutputKey and let downstream instructions inspect it. Route dispatch belongs to the graph engine.

8. Checklist

Before you ship a conditionally routed graph:

  • Every router returns Event(route=...) with a value type (string, number, bool) you can enumerate in a test.
  • The dispatch dict covers every route the router can emit — plus DEFAULT_ROUTE.
  • The default branch is a real handler, not pass.
  • The graph has exactly one terminal node producing output; parallel ends are merged with a JoinNode.
  • Every cycle contains at least one routed edge.
  • Branch targets are single_turn agents or functions unless they sit directly after START.
  • The router itself is unit-tested as a pure function of its input.

Conditional edges turn branching from a prompt suggestion into a reviewed artifact. The model still decides what the message is; your code decides where it goes — and that is the split that makes agent behavior auditable.

References