
Avoiding Infinite Loops
Structural patterns for safety.
Avoiding Infinite Loops
1. The Hard Limit (Recursion Limit)
LangGraph has a built-in recursion_limit config. Used as a last line of defense.
# Will raise Error after 25 steps
graph.invoke(inputs, {"recursion_limit": 25})
2. The Simplification Strategy
If an agent fails 3 times, you probably shouldn't try a 4th time with the same strategy. Design your loop to degrade complexity.
- Tries 1-3: "Use complex Python tool."
- Tries 4-5: "Use simple Calculator tool."
- Tries 6: "Ask human for help."
The graph structure defines these shifting strategies based on the loop count.