How to Fix Graph recursion limit of 25 reached without halting (LangChain)
Quick Answer: This error occurs when a LangChain or LangGraph state graph exceeds the default maximum number of steps (25) without reaching an end node, usually due to an infinite loop in agent reasoning or node transitions. The fastest fix is to increase the recursion limit in your graph's invocation configuration or debug your agent's routing logic.
What Causes This Error
- An infinite loop in the agent's graph routing logic where nodes continually pass control back and forth without terminating.
- The task requires more reasoning steps than the default threshold of 25 iterations allowed by LangGraph.
- An LLM repeatedly generating the same invalid tool call or failing to recognize that a task is complete.
- Missing or improperly configured conditional edge termination conditions in a custom StateGraph.
Step-by-Step Fixes
Fix 1: Fix 1: Increase the recursion limit in graph configuration
Locate where you invoke or stream your graph (e.g., `graph.invoke(inputs, config)` or `graph.stream(...)`).,Pass a dictionary configuration object containing `recursion_limit` set to a higher number.,Example code: `response = graph.invoke(inputs, config={"configurable": {"recursion_limit": 50}})`.
Fix 2: Fix 2: Debug agent routing and conditional edges
Inspect the conditional edge functions that determine the next node based on state.,Ensure there is a clear exit path or terminal condition (e.g., routing to `END`) when a goal is achieved.,Add print statements or use LangSmith tracing to track the exact sequence of nodes being visited.
Fix 3: Fix 3: Refine system prompts and tool definitions
Review the prompt given to the underlying LLM to ensure it clearly understands when to stop executing tools.,Check if the LLM is getting stuck in a loop trying to fix malformed tool arguments.,Provide explicit instructions in the system prompt to finalize the answer after a specific number of tool calls.
Advanced Fixes
Advanced Fix 1: Advanced: Implement custom state tracking and step counters
Add a custom counter field to your graph's State schema to track how many times a specific node has been visited.,Modify your conditional routing edges to force a transition to the `END` node if the custom counter exceeds your safety threshold, allowing for graceful degradation instead of a crash.
FAQs
Q: What is the default recursion limit in LangChain / LangGraph?
A: The default recursion limit is 25 steps. This acts as a safety guardrail to prevent infinite loops from consuming excessive API tokens and compute resources.
Q: Can increasing the recursion limit cause high costs?
A: Yes. If your graph is trapped in a true infinite loop, increasing the limit will simply allow the loop to run longer, resulting in increased LLM token consumption and higher API costs. Always fix the root cause of the loop rather than arbitrarily raising the limit.