When a loop will not stop
The last loop stopped because the answer got longer. Take that away and it never stops. LangGraph does not let it run forever, and the error is one you should meet on purpose rather than at midnight.
A loop with nothing to stop it
A node that counts, and an edge straight back to itself. No condition anywhere.
from typing_extensions import TypedDict
class State(TypedDict):
tries: int
def draft(state):
return {"tries": state["tries"] + 1}from langgraph.graph import StateGraph, START
builder = StateGraph(State)
builder.add_node("draft", draft)
builder.add_edge(START, "draft")
builder.add_edge("draft", "draft")That last edge goes from the node straight back to itself. No question is being asked anywhere, so nothing can ever send the run to END.
Run it, with a small limit so it fails quickly
from langgraph.errors import GraphRecursionError
try:
builder.compile().invoke({"tries": 0}, {"recursion_limit": 5})
except GraphRecursionError as e:
print("stopped:", e)The second argument to invoke is settings for this one run, and recursion_limit is the setting that says how many steps to allow. It is set very low here so the failure arrives quickly. When the count runs out you get GraphRecursionError and the run is abandoned, so nothing is left half applied.
The limit counts steps, not loops. One step is one round of the graph doing work. It was set to 5 here to make the point quickly. Left alone it is far higher, high enough that a sensible program never reaches it and a broken one still stops before it becomes your problem.
What to do when you see it
Raising the limit is almost never the fix. The error is telling you the loop cannot make progress, and a bigger number only delays the same ending.
- Check that something changes. Something in the state has to move, and the condition has to be watching the thing that moves.
- Count the attempts. A counter in the state, and a branch to
ENDwhen it gets too high, is the standard shape. Lesson 7 has it. - Print the state at the top of the node. If it looks the same every time, you have found your bug.
- Set the limit to 50 and confirm the message changes but the ending does not.
- Add a counter and a branch to
ENDat ten attempts, so the same graph finishes cleanly. - Remove the
tryand read the full traceback once, so you recognise it later.
Slow is fine. Stopping is the only problem.