LangGraph raises GraphRecursionError with the message Recursion limit of N reached without hitting a stop condition when one invocation runs more super-steps than recursion_limit without reaching END. The N tells you where you are: 25 is the default in LangGraph.js 1.7.7 and in Python langgraph 1.0.5 and earlier, Python moved to 10,000 in 1.0.6 and to 10,007 in 1.1.4, and LangChain's create_agent binds 9,999 from langchain 1.2.14. The limit counts super-steps, so a plain model and tools loop at a limit of 25 gets about 13 model calls, and every before_model or after_model hook a create_agent middleware overrides adds a step per turn. The counter restarts on every invoke, so the loop that tripped it happened inside one call. Give the loop its own exit first: ToolCallLimitMiddleware and ModelCallLimitMiddleware for create_agent, a RemainingSteps route for a hand-built StateGraph. LANGGRAPH_DEFAULT_RECURSION_LIMIT never changes a create_agent limit, and before 1.2.17 an explicit limit equal to the default was dropped. Start by streaming the failing run with recursion_limit set to 40 and reading which node repeats.
langgraph.errors.GraphRecursionError: Recursion limit of 25 reached without hitting a stop condition means one invocation of your LangGraph graph ran more super-steps than its recursion_limit allows without reaching END. A cycle in the graph never exited, and in an agent that cycle is the model calling a tool, reading the result and calling a tool again. The number in the message is the limit that ran out, and it tells you which runtime you are on: 25 is the default in LangGraph.js and in Python langgraph up to 1.0.5, current Python defaults to 10,007, and LangChain's create_agent binds 9,999. Raise the limit only after you have given the loop an exit of its own: a tool or model call cap, or a RemainingSteps route.
A Python graph that fails at 25 on a current release ran into a value someone chose, in the run config or in the LANGGRAPH_DEFAULT_RECURSION_LIMIT environment variable. A Python agent that fails at 9,999 or 10,007 made thousands of model calls first, and the loop started long before the exception.
Everything below was read from source at langgraph 1.2.25, langchain 1.5.2 and @langchain/langgraph 1.7.7, the latest releases on or before December 3, 2026. Nothing here comes from a test run. For where LangGraph sits among agent frameworks, see the AI agents pillar.
What the number in the message tells you
The Python and JavaScript runtimes split in January 2026. LangGraph.js still ships DEFAULT_RECURSION_LIMIT = 25 in LangGraph.js's pregel config at 1.7.7, with the key spelled recursionLimit. Python moved to 10,000 in 1.0.6, released January 12, 2026, and to 10,007 in 1.1.4, released March 31, 2026. LangGraph's _config.py at the 1.2.25 tag still reads getenv("LANGGRAPH_DEFAULT_RECURSION_LIMIT", "10007").
Python's default is 10,007 because, before 1.2.17, merge_configs treated a value equal to the default as unset, so a round 10,000 risked swallowing a limit a user had chosen on purpose, and PR #7355 moved the default to 10,007 to make that collision less likely. create_agent in langchain 1.5.2 binds 9,999 for the same reason, with a comment pointing at the LangGraph issue that tracked the problem. The Graph API documentation on the recursion limit lists both Python defaults and the environment variable.
Two other places carry a 25 you may run into. langchain_core keeps its own DEFAULT_RECURSION_LIMIT = 25 for plain runnables at 1.9.0, but a compiled LangGraph graph merges its config against LangGraph's default, so that constant does not set your graph's limit. The deprecated create_react_agent with a Pydantic state schema defaults remaining_steps to 25. Neither changes the point at which a current create_agent agent or StateGraph raises.
| Where the graph runs | Default limit | Where it is set |
|---|---|---|
| LangGraph.js 1.7.7 | 25 | DEFAULT_RECURSION_LIMIT in pregel/utils/config.ts |
Python langgraph 1.0.5 and earlier | 25 | _internal/_config.py |
Python langgraph 1.0.6 to 1.1.3 | 10,000 | _internal/_config.py |
Python langgraph 1.1.4 to 1.2.25 | 10,007 | _internal/_config.py |
create_agent, langchain 1.0.5 to 1.2.13 | 10,000 | Bound with .with_config in agents/factory.py |
create_agent, langchain 1.2.14 to 1.5.2 | 9,999 | Bound with .with_config in agents/factory.py |
LANGGRAPH_DEFAULT_RECURSION_LIMIT set | The value you set | Read once, when langgraph is imported |
recursion_limit in the run config | The value you pass | Per invocation |
How LangGraph counts toward the limit
recursion_limit counts super-steps. A super-step is one round of the graph: every node scheduled for that round runs, in parallel where there are several, and their writes are applied together. Nodes in sequence take separate super-steps, so a model node followed by a tools node costs two, and three tool calls executed by one tools node in the same round cost one. Tool calls and loop iterations only affect the count through the super-steps they occupy.
The arithmetic sits in pregel/_loop.py. When an invocation starts, the loop sets step to the checkpoint's step plus one and stop to step + recursion_limit + 1, and tick() marks the run out_of_steps once step passes stop. On a fresh thread the input checkpoint takes step -1, so node super-steps 0 through N run and the error fires before step N+1. A limit of N therefore allows N+1 node super-steps. The control-flow guide's recursion-limit example shows the same thing: with recursion_limit=4, nodes A and B run five times (A, B, A, B, A) before the error.
Three consequences for agents follow from that code:
create_agent, every before_model or after_model hook a middleware overrides becomes its own graph node, named <middleware>.before_model or <middleware>.after_model. Each one adds a super-step to every turn and lowers the number of turns a given limit allows.invoke restarts the counter from the thread's checkpoint, so a long conversation on one thread_id never accumulates toward the limit. A loop that trips it did so inside a single call.Why agents loop until the limit
A StateGraph with a conditional edge back to an earlier node needs that edge to stop choosing the loop at some point. In a tool-calling agent the router is the model: as long as its last message carries tool_calls, the run goes to the tools node and back. The mechanisms below are the ones to check in the transcript.
A tool error the model cannot act on
The model calls a tool, the tool fails, the error text comes back as a ToolMessage, and the model issues the same call again with the same or nearly the same arguments. Issue #6731 in the LangGraph repository shows this shape on 1.0.6: a create_agent text-to-SQL agent kept calling its query tool after two SQL errors, and kept going after later queries succeeded, until it stopped with Recursion limit of 20 reached without hitting a stop condition. The maintainers answered with the tool call limit middleware. When the error text names neither the cause nor a different next move, the model has no information to change its call with, so it repeats it.
A tool result that asks for another call
Some tool results invite more work: a search that returns a page token, a status check that returns pending, a fetched document whose text contains instructions. The model follows them, each round is a valid tool call, and nothing in the graph ends the sequence.
A local model losing track of what it did
Two server-side mechanisms on local stacks can make the model repeat calls it already made. Ollama v0.40.20 picks its default context from VRAM, 4k tokens on GPUs with less than 24 GiB, and Ollama's context length documentation recommends at least 64000 tokens for agents and coding tools. Once a tool loop outgrows the window, the earliest results fall out of the prompt and the model can request them again. The Ollama num_ctx truncation guide shows how to confirm it with ollama ps, and the No User Query Found in Messages fix for Qwen tool loops covers the case where truncation removes the user turn itself. On llama.cpp, tool calling runs through the Jinja chat template, which llama-server enables by default at b12972 (--no-jinja turns it off). When the model's chat template has no native handler, the server falls back to a generic one, logged as Chat format: Generic, and llama.cpp's function-calling docs at b12972 note that it may consume more tokens and be less efficient than the model's native format. Look for that log line when calls repeat, because a model emitting tool calls in a format it was not trained on is one more source of repeated or malformed calls. Framework-free step budgets and loop detection are covered in reducing AI agent reasoning steps. This post stays on the LangGraph mechanics.
Find the loop before you raise the limit
Raising the limit on a looping agent multiplies the calls and leaves the outcome unchanged. Before you touch the number, stream the run, catch the error and read the last messages:
from langgraph.errors import GraphRecursionError
config = {"recursion_limit": 40, "configurable": {"thread_id": "case-1042"}}
try:
for chunk in graph.stream(
{"messages": [{"role": "user", "content": "Summarise the open exceptions"}]},
config,
stream_mode="updates",
):
print(chunk)
except GraphRecursionError as exc:
print(f"Loop: {exc}")
state = graph.get_state(config)
for message in state.values["messages"][-6:]:
print(type(message).__name__, getattr(message, "tool_calls", None))stream_mode="updates" prints one entry per node as each super-step completes, so a repeating node shows up while the run is still going. Inside a node, config["metadata"]["langgraph_step"] gives the current step if you want it in your logs. get_state needs the graph compiled with a checkpointer, which the thread_id implies; running a LangGraph Postgres checkpointer in production covers that setup. The config sets the limit to 40 so that, while you debug, a loop fails after a few dozen steps instead of thousands. GraphRecursionError subclasses Python's built-in RecursionError, so an existing except RecursionError handler will also catch it.
Read the output against this table:
Only the last row calls for a larger recursion_limit.
| What the last messages show | Likely cause | First fix |
|---|---|---|
The same tool name with identical arguments, each answered by an error ToolMessage | A tool error the model cannot act on | Rewrite the error text, then cap that tool |
| The same tool with changing arguments, each result returning more work | A tool result that invites another call | Cap that tool's calls per run |
| The model requests data it received earlier in the same run | Context truncation on the inference server | Raise the server's context length, check ollama ps |
An AIMessage reading Sorry, need more steps to process this request. and no exception | The deprecated create_react_agent hit its remaining_steps check | Migrate to create_agent, or alert on the string |
| Long, varied, productive steps that end at the limit | The task needs more super-steps than the limit allows | Raise the limit to a number you derived |
Bound it on purpose: call limits and RemainingSteps
A designed exit ends the run with an answer or an error you handle, while GraphRecursionError ends it with a stack trace after the run has spent its whole step budget. In Pydantic AI the equivalent stop is a run that exhausts its output retry budget, covered in Exceeded maximum output retries in Pydantic AI, and the LangGraph vs CrewAI vs OpenAI Agents SDK comparison shows how the other two frameworks cap turns.
from langchain.agents import create_agent
from langchain.agents.middleware import ModelCallLimitMiddleware, ToolCallLimitMiddleware
agent = create_agent(
model,
tools=[search_filings, query_database],
system_prompt="Answer questions about filed documents. Cite the filing.",
middleware=[
ToolCallLimitMiddleware(tool_name="query_database", run_limit=3),
ModelCallLimitMiddleware(run_limit=12, exit_behavior="end"),
],
).with_config(recursion_limit=80)from typing import Annotated, Literal
from typing_extensions import TypedDict
from langgraph.graph import END
from langgraph.graph.message import add_messages
from langgraph.managed import RemainingSteps
class State(TypedDict):
messages: Annotated[list, add_messages]
remaining_steps: RemainingSteps
def route_after_model(state: State) -> Literal["tools", "finish", "__end__"]:
last = state["messages"][-1]
if not getattr(last, "tool_calls", None):
return END
if state["remaining_steps"] <= 2:
return "finish"
return "tools"create_agent: ToolCallLimitMiddleware and ModelCallLimitMiddleware
langchain.agents.middleware ships two caps at 1.5.2, documented on LangChain's built-in middleware page. ToolCallLimitMiddleware takes tool_name, run_limit, thread_limit and exit_behavior. Without tool_name it counts every tool call. At least one limit is required, and run_limit may not exceed thread_limit. The default exit_behavior="continue" blocks the over-limit call, sends the model a ToolMessage reading Tool call limit exceeded. Do not call 'query_database' again., and lets the model answer with what it has. "end" stops the run with a ToolMessage for each over-limit call and a final AI message, and "error" raises ToolCallLimitExceededError. It runs as an after_model hook. ModelCallLimitMiddleware takes run_limit, thread_limit and exit_behavior. The default "end" jumps to the end of the graph with an AIMessage such as Model call limits exceeded: run limit (12/12), and "error" raises ModelCallLimitExceededError. run_limit counts per invocation; thread_limit counts across every run on a thread and needs a checkpointer. The two caps stop the loop, and recursion_limit becomes the backstop in case they do not. In the 1.5.2 source, ModelCallLimitMiddleware overrides both before_model and after_model, and ToolCallLimitMiddleware overrides after_model. By our reading of the code, a turn in this agent therefore runs about five super-steps: the model-call check, the model, two after-model hooks and the tools node. Twelve turns need about 60, and 80 leaves headroom while staying far below the bound 9,999. Count your own middleware the same way instead of copying the number. What the agent should do once a cap fires (retry differently, reroute to a larger model, replan, or stop and hand the case to a person) is covered in recovering from agent tool failures.
Hand-built StateGraph: route on RemainingSteps
A graph you build yourself can read how many steps it has left. RemainingSteps and IsLastStep live in langgraph.managed, and when you declare one as a state key the runtime fills it on every step: RemainingSteps is stop - step, and IsLastStep is true when step == stop - 1. Route to a final-answer node before the budget runs out: finish is a node you add that asks the model for a final answer with no tools bound, and the threshold of 2 follows the documentation's own example. The documentation lists RemainingSteps as Python-only, so in LangGraph.js keep your own counter in state and route on it.
The deprecated create_react_agent returns a message instead of raising
create_react_agent in langgraph-prebuilt 1.1.3 is marked deprecated in favour of create_agent, and it handles the budget differently. Its model node checks remaining_steps and, when fewer than two remain and the response still has tool calls, returns an AIMessage with the content Sorry, need more steps to process this request. instead of raising. Issue #5548, ReAct Agent doesn't throw GraphRecursionError, was closed in November 2025 with the maintainers pointing to create_agent, which surfaces the error directly. create_agent at 1.5.2 has no remaining_steps key, so it raises GraphRecursionError at 9,999. On create_react_agent, a run that ran out of steps looks like a normal completion; alert on that string, as described in detecting silent AI agent failures.
| Setup | What stops the loop | What the caller sees |
|---|---|---|
create_agent + ToolCallLimitMiddleware, exit_behavior="continue" | Over-limit calls are blocked and the model answers without the tool | A normal final answer |
create_agent + ToolCallLimitMiddleware, exit_behavior="end" | The run stops before the over-limit call executes | A final AI message about the limit |
create_agent + ModelCallLimitMiddleware, exit_behavior="end" | The run jumps to the end before the next model call | Model call limits exceeded: run limit (N/N) |
Either middleware with exit_behavior="error" | The middleware raises | ToolCallLimitExceededError or ModelCallLimitExceededError |
StateGraph routing on RemainingSteps | Your router sends the run to a final node | Whatever your final node returns |
Deprecated create_react_agent | Its remaining_steps check | Sorry, need more steps to process this request. |
| Any graph without a designed exit | recursion_limit | GraphRecursionError |
Where to set recursion_limit, and the traps
recursion_limit is a top-level key of the run config, next to configurable, and the LangGraph documentation says not to put it under configurable. Pass it per call to invoke, stream or their async forms, or bind it once with .with_config(recursion_limit=...) as in the create_agent block above. In LangGraph.js the key is recursionLimit, and the default there is still 25:
const result = await graph.invoke(
{ messages: [{ role: "user", content: "Summarise the open exceptions" }] },
{ recursionLimit: 40 }
);For hand-built Python graphs, LANGGRAPH_DEFAULT_RECURSION_LIMIT sets the process-wide default:
LANGGRAPH_DEFAULT_RECURSION_LIMIT=200 python run_agent.py
Three traps follow from the source.
DEFAULT_RECURSION_LIMIT is a module-level value built from getenv when langgraph loads, so setting os.environ after langgraph is imported has no effect. Set it in the environment that starts the process.create_agent. That agent binds 9,999 with .with_config, and a filled-in default never overrides a bound value. The same rule protects subgraphs: a subgraph bound to 50 keeps 50 when its parent runs at the default. To change a create_agent limit, pass recursion_limit explicitly.LANGGRAPH_DEFAULT_RECURSION_LIMIT=1000, agent.with_config(recursion_limit=1000) silently kept create_agent's 9,999, and a looping agent ran to 9,999 steps. From 1.2.17 the default is a private int subclass, and merge_configs skips only values of that type. On an older release, upgrade, or choose a limit that differs from your default.Inside your own perimeter
A runaway loop on a hosted API shows up on the bill, while on a model you serve yourself a run that loops toward 9,999 or 10,007 super-steps occupies a slot on a shared inference server for as long as it runs, and the cost lands on everyone else's queue time. On the 4k default context of a smaller Ollama card, the same run is also the one most exposed to the truncation loop described above.
Size the limit from the graph. Count the super-steps one turn takes (the model node, the tools node, and one per middleware hook), multiply by the most turns a task should need before a reviewer would want to see it, and add headroom. A document-review agent expected to finish in 12 model turns at about five super-steps each lands near 80, and a run that needs more goes to a person for review.
Log every GraphRecursionError, and every middleware limit exit, to your own collector with the thread_id and the last few messages, so the loop can be replayed from the checkpoint. Those messages carry tool results drawn from your documents, so they belong in the same store as the rest of that data and stay off third-party tracing services. If you are building agents like this on infrastructure you control, our on-premise AI development work puts these caps in from the first version.
What to do this week
Pick the one tool in your agent that writes to or queries a system of record, and add ToolCallLimitMiddleware(tool_name="<that tool>", run_limit=3) for it. Then replace the inherited 9,999 or 10,007 with a recursion_limit you derived from the super-steps one turn takes, and run one known-hard task with stream_mode="updates" to confirm the node sequence matches your count.
FAQ
Quick answers to the questions this post tends to raise.



