GraphRecursionError
langgraph.errors.GraphRecursionError
Stack trace
Traceback (most recent call last):
File "app.py", line 42, in <module>
result = graph.traverse(start_node)
File "/usr/local/lib/python3.9/site-packages/langgraph/graph.py", line 128, in traverse
self._recursive_traverse(node, steps=0)
File "/usr/local/lib/python3.9/site-packages/langgraph/graph.py", line 145, in _recursive_traverse
raise GraphRecursionError('Max recursion steps exceeded')
langgraph.errors.GraphRecursionError: Max recursion steps exceeded Why it happens
LangGraph's graph traversal uses recursion with a step limit to prevent infinite loops. This error occurs when the traversal hits the maximum recursion depth due to cycles or missing termination conditions in the graph structure or traversal logic.
Detection
Monitor traversal step counts and catch GraphRecursionError exceptions to log the current node path and detect cycles or missing base cases before the application crashes.
Causes & fixes
Graph contains cycles causing infinite recursion during traversal
Implement cycle detection by tracking visited nodes and stop recursion when a node is revisited.
Traversal function lacks a proper base case or termination condition
Add explicit base cases in the recursive traversal to end recursion when leaf nodes or max depth are reached.
Max recursion steps limit is set too low for the graph size
Increase the max recursion steps parameter to accommodate larger graphs or deeper traversals.
Code: broken vs fixed
from langgraph import Graph
graph = Graph()
# This traversal causes GraphRecursionError due to cycles
result = graph.traverse('start_node') # Raises GraphRecursionError here
print(result) import os
from langgraph import Graph, GraphRecursionError
# Set environment variable for API key if needed
os.environ['LANGGRAPH_API_KEY'] = os.environ.get('LANGGRAPH_API_KEY', 'your_api_key_here')
graph = Graph()
try:
# Enable cycle detection by passing visited set
result = graph.traverse('start_node', visited=set()) # Fixed: cycle detection prevents infinite recursion
print(result)
except GraphRecursionError as e:
print(f'Error: {e}') Workaround
Wrap the traversal call in try/except GraphRecursionError, and on exception, log the current traversal path and manually break cycles by skipping revisited nodes.
Prevention
Design graph traversal algorithms with explicit cycle detection and base cases, and configure max recursion steps according to graph complexity to avoid infinite recursion errors.