Skip to main content
In this section, we will learn how to make nodes loop back to previous steps using conditional edges. This is a key building block for creating iterative reasoning loops (like agents trying to solve a problem, getting feedback, and trying again).

Objectives

  1. Implement looping logic to route execution back to previous nodes.
  2. 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

  1. Define the AgentState schema tracking target, guess, attempts, feedback, and won.
  2. Create node functions (guess_node, evaluate_node) and routing function (should_continue).
  3. 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

  1. Define the state schema tracking bounds and guess attempts.
  2. Write the guesser node to calculate midpoint, and evaluator node to adjust lower/upper bounds.
  3. Define routing logic to stop or loop based on guess feedback, compile and run.

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