Introduction
In our last lesson, we established the Directed Acyclic Graph (DAG) as a robust architectural pattern for modeling predictable, multi-step agentic workflows. We focused on defining the static structure of these graphs—the nodes representing tasks and the edges representing dependencies—with a critical emphasis on type alignment between them. This provided us with a blueprint for reliable execution.
This lesson breathes life into those static blueprints. We will introduce dynamic behavior by implementing conditional routing nodes. These nodes function as the decision-making logic within our graph, directing the flow of execution down different paths based on LLM outputs or deterministic business rules. By the end of this lesson, you will be able to build workflows that are not only structured and reliable but also adaptive and intelligent, capable of changing their course based on runtime information.
Part 1: The Essence of Conditional Routing
A static DAG defines a fixed path of execution. However, most non-trivial processes require branching logic. For instance:
- Does a generated piece of code pass its unit tests? If yes, complete the task. If no, route it to a "fix code" agent.
- Is the user asking to retrieve information or to perform an action? Route the request to a
SearchAgentor aToolUsingAgentaccordingly.
A conditional routing node is a special type of node in our graph that encapsulates this decision-making logic. It takes the current state of the workflow as input and its sole output is the name of the next node to execute. This effectively transforms our graph into a state machine, where the transitions between states (nodes) are governed by explicit conditions.
We can categorize the logic inside these routing nodes into two main types:
- LLM-Based Routing: The decision is delegated to an LLM. This is ideal for tasks involving semantic understanding, such as classifying user intent or determining the nature of a query.
- Rule-Based Routing: The decision is made by deterministic code based on predefined business rules. This is essential for validation, error handling, and enforcing process constraints.
Let's explore how to implement both from first principles.
Part 2: Implementing LLM-Based Routing
The most common use of LLM-based routing is to direct an incoming request to the correct specialized agent or sub-workflow. The core pattern involves an initial LLM call whose only purpose is to classify the request and output a structured tag representing the chosen route.
The key to making this reliable is using the structured output techniques we covered in Module 1. The LLM must be constrained to produce a predictable, machine-readable output (e.g., a Pydantic model or a JSON object with an enum field). This output can then be consumed by simple, deterministic code.
The following video provides an excellent, from-scratch implementation of this pattern.
Building AI Agents in Pure Python - Beginner Course
This video, from the "Building AI Agents in Pure Python" course by Dave Ebbelaar, demonstrates a clear, framework-free implementation of a router for a calendar agent.
Watch the segment on routing from getting into routing. Pay close attention to these implementation details: The CalendarRequestType Pydantic model, which uses a Literal type to constrain the LLM's classification output to 'new_event', 'modify_event', or 'other'. The process_calendar_request function, which first calls the LLM to get the classification. The simple and clear if/elif/else block that acts as the router, checking the request_type from the LLM's output and branching the execution accordingly.
This example perfectly illustrates the principle: an LLM provides the semantic decision, but the actual control flow is managed by robust, predictable Python code. The if statement is the conditional routing node in its most fundamental form.
Part 3: Rule-Based Routing for Workflow Reliability
While LLMs handle semantic decisions, deterministic rules are the bedrock of reliable execution, especially for validation and error recovery. A powerful pattern enabled by rule-based routing is the generate-validate-fix loop.
This pattern is common in agentic coding assistants but applies to any task where an agent's output can be programmatically verified.
- Generate: An agentic node generates an output (e.g., code, a report, a configuration file).
- Validate: One or more deterministic nodes check the output against a set of rules (e.g., run a linter, execute unit tests, check against a schema).
- Route & Fix: A conditional routing node inspects the validation results. If they pass, it routes the workflow to completion. If they fail, it routes back to a "fix" agent, providing the errors as feedback.
The article below provides an exceptional breakdown of this pattern.
How to Build a Structured AI Coding Workflow with Deterministic and ...
This article from MindStudio details a structured coding workflow, providing a perfect example of rule-based conditional routing for building reliable agentic systems.
First, read the section Conditional Routing. The route_after_validation function is a prime example of a deterministic router. It uses simple if/elif/else logic on the workflow's state (lint_errors, test_results, iteration_count) to decide the next step. Next, read the overview of the core pattern: Generate, Validate, Fix. This contextualizes how the routing function enables this crucial reliability loop. Finally, look at the code that wires the graph together in the section "Wire the Graph". The should_continue function and the call to workflow.add_conditional_edges show how a framework formalizes the routing logic we've discussed.
This generate-validate-fix loop, powered by a deterministic conditional router, is a fundamental pattern for moving beyond simple agentic toys to production-grade systems that can self-correct.
Part 4: Formalizing the Model with State Machines
As we build these graphs with conditional routing, we are, in fact, constructing Finite State Machines (FSMs). Thinking in terms of FSMs provides a powerful formal vocabulary for reasoning about our agentic systems.
An FSM is a model of computation consisting of:
- States: A finite number of conditions a system can be in (our nodes).
- Transitions: The paths from one state to another (our edges).
- Events: Triggers that cause a transition (e.g., task completion).
- Guards: Conditions that must be true for a transition to occur (our routing logic!).
This video provides an excellent introduction to FSMs and their application to agentic systems.
Building Multi agent Systems with Finite State Machines
This talk from the AI Engineer channel explains how Finite State Machines provide the structure and predictability that LLMs lack, making them a perfect match for orchestrating agent behavior.
Watch the introduction to understand the core components of a state machine from what is a finite State machine. Notice how the "guard" is exactly what we are implementing with our routing logic. Next, watch the segment from what I want to draw your attention to, which argues that combining the dynamic intelligence of LLMs with the predictable structure of state machines is the key to building robust systems. Finally, see how this applies directly to orchestration in the clip from agentic orchestration. The presenter describes a "centralized planning node" that directs the next state—this is precisely our LLM-based router.
The diagram below shows a simple agent designed as a state machine. The diamond-shaped "Choice State" is a visual representation of a conditional routing node.

As workflows grow, they can become complex graphs of interconnected states, as seen in this advanced RAG system.

Part 5: Integrating Routing into the Orchestrator
Let's integrate this concept into the first-principles DAG orchestrator we designed in the previous lesson. How does our execution loop handle a node that can lead to multiple different children?
We can adapt our model by defining a special node type, ConditionalRouterNode. Our orchestrator's execution loop will treat it differently from a standard TaskNode.
Here's an updated execution algorithm:
- Poll for Runnable Tasks: The orchestrator fetches a task from the state store with
status = RUNNABLE. - Dispatch and Execute: The task is dispatched to a worker, and its status is set to
RUNNING. - Process Completion: When the worker completes the task, it updates the task's status to
COMPLETEDand writes its output to the state store. - Determine Next Step (The Routing Logic):
- If the completed node is a
TaskNode: The orchestrator looks up all its children from the static DAG definition. For each child, it checks if all its dependencies are now met. If so, the child's status is updated toRUNNABLE. - If the completed node is a
ConditionalRouterNode: The orchestrator inspects the node's output, which is expected to be a string (e.g.,'fix_code','generate_article_content'). This string is the name of the single child node to activate. The orchestrator finds this specific child in the DAG, checks if its other dependencies are met (if any), and if so, updates its status toRUNNABLE. All other potential paths from the router are ignored for this execution.
- If the completed node is a
This approach maintains the clean separation of concerns. The graph definition still declares all possible paths, but the ConditionalRouterNode and the orchestrator's logic provide the runtime mechanism for choosing which path to take.
Conclusion
In this lesson, we have made our structured workflows dynamic and intelligent. We have moved beyond static DAGs by introducing conditional routing nodes, which act as the brains of our orchestration layer.
Key Takeaways:
- Conditional routing adds branching logic to a workflow graph, turning it into a state machine.
- LLM-based routing uses the semantic understanding of a language model to make decisions, typically by classifying a request and producing a structured output.
- Rule-based routing uses deterministic code to make decisions, which is essential for validation, error handling, and implementing reliability patterns like the generate-validate-fix loop.
- Finite State Machines (FSMs) provide a formal and powerful mental model for designing and reasoning about these dynamic, stateful workflows.
- Our DAG orchestrator can be extended to handle conditional routing by recognizing a special router node type whose output dictates the next single node to execute.
We can now direct our workflows down different paths. But what if we want to go down multiple paths at once?
Preview of the Next Lesson: We will explore fan-out/fan-in patterns for dynamic parallelism. This will allow us to design workflows that can execute independent tasks concurrently, significantly improving efficiency. We will learn how to split the execution flow into parallel branches and then aggregate the results back together, a crucial pattern for complex, high-performance agentic systems.