> ## Documentation Index
> Fetch the complete documentation index at: https://genai.codewithsiva.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Graph V: Looping Graph

> Implement iterative/looping logic in your AI agent workflows using LangGraph

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

```python theme={null}
{"target": 7, "attempts": 0, "won": False}
```

#### Sample Output

```python theme={null}
{"target": 7, "guess": 7, "attempts": 3, "won": True}
```

#### 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:

```python theme={null}
from typing import TypedDict

class AgentState(TypedDict):
    target: int
    guess: int
    attempts: int
    feedback: str
    won: bool
```

#### 2. Define the Nodes

We define the logic to make a guess and the logic to evaluate the guess:

```python theme={null}
import random

def guess_node(state: AgentState) -> AgentState:
    state["guess"] = random.randint(1, 10)
    state["attempts"] = state.get("attempts", 0) + 1
    return state

def evaluate_node(state: AgentState) -> AgentState:
    guess = state["guess"]
    target = state["target"]
    
    if guess == target:
        state["feedback"] = "Correct!"
        state["won"] = True
    elif guess < target:
        state["feedback"] = "Higher"
        state["won"] = False
    else:
        state["feedback"] = "Lower"
        state["won"] = False
    return state
```

#### 3. Routing Logic

The router function decides whether to continue guessing (loop back) or stop:

```python theme={null}
def should_continue(state: AgentState) -> str:
    if state["won"] or state["attempts"] >= 5:
        return "stop"
    else:
        return "go_on"
```

#### 4. Create and Compile the Graph

```python theme={null}
from langgraph.graph import StateGraph, START, END

graph = StateGraph(AgentState)

graph.add_node("guesser", guess_node)
graph.add_node("evaluator", evaluate_node)

graph.add_edge(START, "guesser")
graph.add_edge("guesser", "evaluator")

# Add conditional loop connection
graph.add_conditional_edges(
    "evaluator",
    should_continue,
    {
        "go_on": "guesser",
        "stop": END
    }
)

app = graph.compile()
```

#### 5. Invoke the Graph

```python theme={null}
result = app.invoke({"target": 7, "attempts": 0, "won": False})
print(f"Target: {result['target']}, Final Guess: {result['guess']}, Attempts: {result['attempts']}, Won: {result['won']}")
```

## 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

```python theme={null}
{
    "target": 13,
    "lower_bound": 1,
    "upper_bound": 20,
    "attempts": 0,
    "won": False
}
```

#### Sample Output

```python theme={null}
"Attempts: 3, Last Guess: 13, Won: True"
```

#### 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.

<Accordion title="Solution">
  ```python theme={null}
  from typing import TypedDict
  from langgraph.graph import StateGraph, START, END

  # 1. State Schema
  class AgentState(TypedDict):
      target: int
      guess: int
      lower_bound: int
      upper_bound: int
      attempts: int
      won: bool
      feedback: str

  # 2. Node Functions
  def guesser_node(state: AgentState) -> AgentState:
      state["guess"] = (state["lower_bound"] + state["upper_bound"]) // 2
      state["attempts"] = state.get("attempts", 0) + 1
      return state

  def evaluator_node(state: AgentState) -> AgentState:
      guess = state["guess"]
      target = state["target"]
      if guess == target:
          state["won"] = True
          state["feedback"] = "Correct"
      elif guess < target:
          state["lower_bound"] = guess + 1
          state["won"] = False
          state["feedback"] = "Higher"
      else:
          state["upper_bound"] = guess - 1
          state["won"] = False
          state["feedback"] = "Lower"
      return state

  # Routing Logic
  def check_loop(state: AgentState) -> str:
      if state["won"] or state["attempts"] >= 7:
          return "end"
      return "loop"

  # 3. Create Graph
  graph = StateGraph(AgentState)
  graph.add_node("guesser", guesser_node)
  graph.add_node("evaluator", evaluator_node)

  graph.add_edge(START, "guesser")
  graph.add_edge("guesser", "evaluator")

  graph.add_conditional_edges(
      "evaluator",
      check_loop,
      {
          "loop": "guesser",
          "end": END
      }
  )

  # 4. Compile and Run
  app = graph.compile()
  output = app.invoke({
      "target": 13,
      "lower_bound": 1,
      "upper_bound": 20,
      "attempts": 0,
      "won": False
  })
  print(f"Attempts: {output['attempts']}, Last Guess: {output['guess']}, Won: {output['won']}")
  ```
</Accordion>

## Practice & Exercises

To reinforce what you've learned in this section (iterative loop connections and state feedback cycles), practice with the interactive notebook:

<CardGroup cols={1}>
  <Card title="Practice & Exercises" icon="laptop-code">
    Practice setting up loops in workflows, using conditional routers for loop conditions, and building an automated game agent.

    [💻 VS Code](vscode://file/Users/sivaprasad/Downloads/GenAI%20With%20Python/public/notebooks/langgraph/Graph5_Looping.ipynb) | [🚀 Colab](https://colab.research.google.com/github/prasad230776/genai-course/blob/master/public/notebooks/langgraph/Graph5_Looping.ipynb) | <a href="/public/notebooks/langgraph/Graph5_Looping.ipynb" download>📥 Download</a>
  </Card>
</CardGroup>
