Objectives
- Implement looping logic to route execution back to previous nodes.
- Create a single conditional edge that handles decision-making and controls loop termination.
Graph V: Looping Graph
Goal
Build a looping graph that routes execution back to a previous node until a specific condition is met.Sample Input
Sample Output
Plan
- Define the
AgentStateschema trackingtarget,guess,attempts,feedback, andwon. - Create node functions (
guess_node,evaluate_node) and routing function (should_continue). - Build the graph, register nodes, add conditional loop connections, compile and run.
Code Implementation
1. Define the State Schema
We define the state to track the target number, the current guess, the number of attempts, and whether the game is won:2. Define the Nodes
We define the logic to make a guess and the logic to evaluate the guess:3. Routing Logic
The router function decides whether to continue guessing (loop back) or stop:4. Create and Compile the Graph
5. Invoke the Graph
Exercise: Automatic Higher or Lower Game 🗃
Goal
Implement an automated guessing game using binary search logic, looping guesser and evaluator nodes until the target number is guessed (max 7 attempts).Sample Input
Sample Output
Plan
- Define the state schema tracking bounds and guess attempts.
- Write the guesser node to calculate midpoint, and evaluator node to adjust lower/upper bounds.
- Define routing logic to stop or loop based on guess feedback, compile and run.
Solution
Solution
Practice & Exercises
To reinforce what you’ve learned in this section (iterative loop connections and state feedback cycles), practice with the interactive notebook:Practice & Exercises
Practice setting up loops in workflows, using conditional routers for loop conditions, and building an automated game agent.💻 VS Code | 🚀 Colab | 📥 Download