Skip to main content
In this section, we will learn how to direct the flow of execution dynamically based on user input or state properties using conditional edges.

Objectives

  1. Implement conditional logic to route execution.
  2. Use START and END nodes explicitly in graph routing.
  3. Design multiple nodes for different operations (e.g., addition and subtraction).
  4. Create a router function to handle decision-making and control graph flow.

Graph IV: Conditional Graph

Goal

Build a graph that dynamically routes execution based on the operation symbol (+ or -).

Sample Input

Sample Output

Plan

  1. Define the AgentState schema containing number1, operation, number2, and finalNumber.
  2. Create the node functions (adder, subtractor) and the routing function (decide_next_node).
  3. Build the graph and connect the conditional edges.
  4. Compile and invoke the graph.

Code Implementation

1. Define the State Schema

We define the numbers, the operation indicator, and the final computation field:

2. Define the Nodes and Router Function

We write:
  • An adder node
  • A subtractor node
  • A routing function decide_next_node that returns a string mapping to the target node.

3. Create Graph with Conditional Edges

We add the nodes and define the routing connection using add_conditional_edges():

4. Invoke the Graph

Exercise: Double Routing Calculator 🛹

Goal

Build a double routing calculator that performs two consecutive calculations dynamically using conditional routing gates.

Sample Input

Sample Output

Plan

  1. Create AgentState schema to track numbers, operations, and results.
  2. Write mathematical operation nodes and two router functions to evaluate operation symbols.
  3. Connect both stages with conditional edges using a StateGraph, compile and invoke.

Practice & Exercises

To reinforce what you’ve learned in this section (conditional routing and dynamic paths), practice with the interactive notebook:

Practice & Exercises

Practice implementing routing functions, configuring conditional edges, and building a multi-path routing agent.💻 VS Code | 🚀 Colab | 📥 Download