A ReAct agent loops through Thought, Action and Observation until the model stops calling tools and answers. When a tool keeps returning confusing results, the model keeps calling it, and without a bound the loop never ends. The classic ReAct executor caps this with max_iterations, commonly 5 in examples and 15 in the older LangChain default, and setting it to None can lead to an infinite loop. Pick a small number for a first version, and treat hitting the cap as a signal to fix the tool or the prompt, not to raise the cap.
What you need
- A ReAct agent with at least one tool already working
- A task the agent sometimes loops on, or a guess at a safe cap such as 5
- Access to the run log so you can see how many iterations a run took
Step 1: Set the iteration cap on the executor
Set max_iterations on the agent executor to a small number, such as 5 for a short task. The cap counts Thought-Action-Observation rounds, not model calls alone.
Step 2: Run a task that used to loop
Run the task that looped before and watch the log: the run should stop at the cap with a message that it stopped because of the limit, instead of running on.
Step 3: Fix the cause, not the cap
Read the last few iterations to see which tool result confused the model, and fix that tool’s description or the prompt. Raise the cap only when the task genuinely needs more rounds.
Worked example: synthetic loop cap check
The table below is a synthetic example. It shows the expected result of the iteration cap; no agent was run.
| Check | Expected | Result |
|---|---|---|
| Looping task stops | At 5 iterations | Pass |
| Run reports the limit | Yes | Pass |
| Normal task still finishes | Within 5 | Pass |
| No runaway run | 0 runaway | Pass |
Expected result (UNTESTED). the looping task stops at 5 iterations with a clear limit message, and normal tasks still finish inside the cap. This check was not run live; the table shows the expected result for the synthetic example.
Limits
- The cap stops the loop, it does not fix the confusion that caused it.
- A cap that is too low cuts off tasks that genuinely need more rounds.
- Each iteration adds tokens, so a high cap is also a high cost cap.
- Setting the cap to no limit risks an infinite loop, so always set a number.
