How to Fix 'agent infinite loop' in CrewAI (TypeScript)
What the error means
agent infinite loop in CrewAI usually means one of your agents keeps getting called with no valid stopping condition, no tool result that satisfies the task, or a task loop that never converges. In TypeScript projects, it often shows up when an agent is allowed to re-run the same step repeatedly because the prompt, tool output, or task config never gives it a clean exit.
You’ll usually see this after a few repeated iterations in logs, or as a runtime failure from Crew, Agent, or task execution when the framework detects the agent is stuck cycling.
The Most Common Cause
The #1 cause is a task that depends on an agent producing structured output, but the prompt and config don’t enforce a strict final answer. The agent keeps trying to “improve” the output or re-call tools because it never reaches a terminal state.
Here’s the broken pattern versus the fixed pattern.
| Broken | Fixed |
|---|---|
| Agent can keep reasoning forever | Agent has explicit completion criteria |
| Tool output is vague | Tool output is constrained and validated |
| Task asks for “best effort” | Task asks for one final deliverable |
// BROKEN: agent can loop because nothing forces a final stop
import { Agent, Task, Crew } from "crewai";
const researcher = new Agent({
role: "Researcher",
goal: "Find information about mortgage rates",
backstory: "You are an expert analyst.",
allowDelegation: true,
});
const task = new Task({
description: "Research mortgage rates and keep refining until perfect.",
expectedOutput: "A good summary.",
agent: researcher,
});
const crew = new Crew({
agents: [researcher],
tasks: [task],
});
await crew.kickoff();
// FIXED: explicit stopping condition + concrete expected output
import { Agent, Task, Crew } from "crewai";
const researcher = new Agent({
role: "Researcher",
goal: "Return one concise summary of current mortgage rate trends",
backstory: "You produce structured financial summaries.",
allowDelegation: false,
});
const task = new Task({
description:
"Summarize current mortgage rate trends in exactly 5 bullets. Stop after one response.",
expectedOutput:
"Exactly 5 bullets with trend, driver, risk, regional note, and source caveat.",
agent: researcher,
});
const crew = new Crew({
agents: [researcher],
tasks: [task],
});
await crew.kickoff();
The key difference is not just wording. You’re removing ambiguity around what “done” looks like.
If you’re using tools, make sure the tool result can actually satisfy the task. A common trap is giving an agent a search tool but asking it to produce an answer that requires deterministic data validation the tool never returns.
Other Possible Causes
1) Recursive delegation between agents
If two agents delegate work to each other without a hard boundary, they can bounce tasks back and forth until CrewAI flags an infinite loop.
// BAD
const underwriter = new Agent({
role: "Underwriter",
goal: "Review policy risk",
allowDelegation: true,
});
const reviewer = new Agent({
role: "Reviewer",
goal: "Validate underwriting decisions",
allowDelegation: true,
});
Fix it by making only one side delegate, or by assigning clear ownership.
// GOOD
const underwriter = new Agent({
role: "Underwriter",
goal: "Review policy risk",
allowDelegation: false,
});
const reviewer = new Agent({
role: "Reviewer",
goal: "Validate underwriting decisions",
allowDelegation: true,
});
2) Tool output does not change state
If your tool returns the same payload every time, the agent may keep calling it because it thinks it needs more evidence. This happens with wrappers around APIs that always return cached or empty responses.
// BAD
async function lookupCustomer(id: string) {
return { status: "ok", data: null };
}
Fix by returning enough signal for completion or failure.
// GOOD
async function lookupCustomer(id: string) {
const record = await db.customers.findById(id);
if (!record) {
return { status: "not_found", done: true };
}
return { status: "ok", done: true, data: record };
}
3) Missing max iteration or step limits
Some setups rely on defaults that are too loose for production. If your version exposes iteration controls, set them explicitly.
// Example config pattern
const crew = new Crew({
agents,
tasks,
processType: "sequential",
maxIterationsPerTask: 5,
});
If your installed version uses different names, check the actual Crew constructor options in your package version. The point is simple: cap retries at the orchestration layer.
4) Prompt asks for open-ended refinement
Phrases like “keep improving,” “iterate until perfect,” or “analyze deeply” can be enough to trigger repeated reasoning with no stop condition.
// BAD
description:
"Keep improving this insurance claim summary until you are fully satisfied."
Use bounded instructions instead.
// GOOD
description:
"Produce one claim summary with these fields only: claimant, loss type, estimate range, fraud risk flag."
How to Debug It
- •
Check whether delegation is enabled
- •Look at every
Agentinvolved. - •If more than one has
allowDelegation: true, disable it temporarily and rerun.
- •Look at every
- •
Inspect the task prompt for open-ended language
- •Search for words like:
- •
refine - •
iterate - •
improve - •
keep going - •
until complete
- •
- •Replace them with exact output constraints.
- •Search for words like:
- •
Log every tool call and return value
- •If a tool returns identical results across calls, that’s your loop.
- •Add logging around wrappers so you can see whether state changes between calls.
- •
Set hard limits
- •Add max iterations if your CrewAI TypeScript version supports it.
- •Reduce task scope to one action and one output.
- •If the error disappears after lowering limits, you’ve confirmed runaway reasoning rather than a broken dependency.
Prevention
- •Use bounded prompts:
- •Define exact output shape
- •Define exact stop condition
- •Keep delegation narrow:
- •One owner per task
- •Avoid mutual delegation chains
- •Make tools deterministic:
- •Return success/failure clearly
- •Include enough data for the agent to finish on first pass
If you want a quick rule of thumb: when CrewAI says agent infinite loop, assume your system forgot to tell the agent what “done” means.
Keep learning
- •The complete AI Agents Roadmap — my full 8-step breakdown
- •Free: The AI Agent Starter Kit — PDF checklist + starter code
- •Work with me — I build AI for banks and insurance companies
By Cyprian Aarons, AI Consultant at Topiax.
Want the complete 8-step roadmap?
Grab the free AI Agent Starter Kit — architecture templates, compliance checklists, and a 7-email deep-dive course.
Get the Starter Kit