Fix: AI Agent Stuck in a Loop (Repeating the Same Tool Call)
Updated 2026-10-15
An agent that calls the same tool again and again burns tokens and never answers. The causes are predictable, and so are the fixes.
Why it happens
- The tool result doesn’t tell the model it succeeded (empty string,
None, or"OK"with no data), so it tries again. - Errors are swallowed or vague, so the model retries the same arguments.
- No stop condition: the prompt never says when the job is done.
- The tool result isn’t added to the history (a bug), so the model never sees it.
- No hard step limit.
Steps
1. Always enforce a maximum number of steps
for step in range(MAX_STEPS): # e.g. 8–15
...
else:
return "I couldn't finish within the step limit. Here's what I found so far: ..."
Framework equivalents: LangGraph recursion_limit (guide), OpenAI Agents SDK Runner.run(..., max_turns=10), CrewAI max_iter on the Agent, n8n AI Agent Max Iterations option.
2. Return informative tool results
# Bad
return ""
# Good
return "No orders found for customer 42 in October 2026. Do not search again; tell the user."
3. Return errors as text, with a hint
try:
...
except ValueError as e:
return f"error: {e}. The 'date' argument must be YYYY-MM-DD."
4. Detect repeated calls and intervene
seen = {}
for call in msg.tool_calls:
key = (call.function.name, call.function.arguments)
seen[key] = seen.get(key, 0) + 1
if seen[key] > 2:
result = "You already made this exact call twice with the same result. Use what you have and answer."
else:
result = run_tool(call)
messages.append({"role": "tool", "tool_call_id": call.id, "content": result})
5. Give the model a clear stop condition
Add to the system prompt: “When you have enough information to answer, reply to the user without calling more tools. If a tool returns no data, say so instead of retrying.”
6. Check your history handling
Print len(messages) each step. If it isn’t growing, tool results aren’t being appended, which is the bug behind many “infinite” loops.
Common symptoms
Same search query over and over: the search returns nothing useful. Return “no results” explicitly (step 2).
Alternates between two tools: conflicting instructions. Simplify the system prompt and tool descriptions.
n8n agent loops until “Max iterations reached”: a tool sub-node returns an empty item. Make it output a clear text field.