Objectives
- Implement conditional logic to route execution.
- Use
STARTandENDnodes explicitly in graph routing. - Design multiple nodes for different operations (e.g., addition and subtraction).
- 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
- Define the
AgentStateschema containingnumber1,operation,number2, andfinalNumber. - Create the node functions (
adder,subtractor) and the routing function (decide_next_node). - Build the graph and connect the conditional edges.
- 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
addernode - A
subtractornode - A routing function
decide_next_nodethat returns a string mapping to the target node.
3. Create Graph with Conditional Edges
We add the nodes and define the routing connection usingadd_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
- Create
AgentStateschema to track numbers, operations, and results. - Write mathematical operation nodes and two router functions to evaluate operation symbols.
- Connect both stages with conditional edges using a
StateGraph, compile and invoke.
Solution
Solution
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