Module 7 Lesson 2: Loop Guards
·Agentic AI

Module 7 Lesson 2: Loop Guards

Setting boundaries. How to implement hard limits on cycles and token usage within your agent graphs.

Loop Guards: The Safety Brake

In Module 5, we learned why loops are dangerous. In Module 6, we learned that LangGraph allows cycles. This lesson connects the two: How do we allow an agent to loop while ensuring it never loops too much?

1. The Native recursion_limit

LangGraph has a built-in safety switch. When you invoke a graph, you can set a maximum number of total node steps.

# The graph will crash automatically if it hits 10 steps.
app.invoke({"input": "task"}, config={"recursion_limit": 10})

While effective, this is a "Hard Crash." Your app will just error out. For a better user experience, we want a Logical Loop Guard.


2. The State-Based Counter

A logical loop guard lives inside your State and your Edges.

Step A: Add to State

class AgentState(TypedDict):
    messages: Annotated[list, add_messages]
    iteration_count: int # <--- Track this!

Step B: Increment in a Node

def agent_node(state: AgentState):
    # Perform work...
    return {
        "messages": [response],
        "iteration_count": state["iteration_count"] + 1
    }

Step C: Route at the Edge

def check_loop_guard(state: AgentState):
    if state["iteration_count"] > 3:
        return "too_many_turns"
    return "continue"

3. Why 3-5 is the "Magic Number"

If an agent hasn't solved a problem in 3 to 5 steps, it is usually because:

  1. The prompt is bad. (The model doesn't understand the task).
  2. The data is missing. (The search results are empty).
  3. The model is too small. (It lacks the reasoning for this specific task).

Continuing to loop 10 or 20 times almost never fixes these issues; it just burns money.


4. Visualizing the Guard

graph TD
    Start --> NodeA[Agent Thinking]
    NodeA --> Counter[Incr Counter]
    Counter --> Edge{Count > 5?}
    Edge -- Yes --> Finish[Output: 'I tried 5 times and failed']
    Edge -- No --> Tool[Run Tool]
    Tool --> NodeA

5. Token-Based Loop Guards

For high-volume production, you can even guard based on Cost.

  • Add a total_cost field to your state.
  • Every node adds its token cost to the state.
  • The edge says: if state['total_cost'] > 0.50: return END.

Key Takeaways

  • Recursion limits prevent the entire graph from overrunning.
  • State-based counters allow for graceful exits (returning a "Best Effort" answer).
  • Most tasks should finish in under 5 loops.
  • Loop guards protect your API budget and user experience.

Subscribe to our newsletter

Get the latest posts delivered right to your inbox.

Subscribe on LinkedIn