CrewAI Tutorial (TypeScript): debugging agent loops for beginners
This tutorial shows you how to identify and stop agent loops in a CrewAI TypeScript project. You’ll wire in basic observability, add hard stop conditions, and make the agent return useful output instead of spinning forever.
What You'll Need
- •Node.js 18+ installed
- •A TypeScript project with
crewaiinstalled - •An OpenAI API key set as
OPENAI_API_KEY - •A terminal and a code editor
- •Basic familiarity with CrewAI concepts like agents, tasks, and crews
Step-by-Step
- •Start with a minimal CrewAI setup that can reproduce the loop. The point is not to build a full app yet; it’s to create a small, inspectable case where an agent can get stuck repeating itself.
import { Agent, Task, Crew } from "crewai";
const researcher = new Agent({
name: "Researcher",
role: "Research assistant",
goal: "Answer the user question clearly",
backstory: "You are concise and avoid repetition.",
verbose: true,
});
const task = new Task({
description: "Explain why agent loops happen in CrewAI TypeScript.",
expectedOutput: "A short explanation with debugging tips.",
agent: researcher,
});
const crew = new Crew({
agents: [researcher],
tasks: [task],
});
async function main() {
const result = await crew.kickoff();
console.log(result);
}
main();
- •Turn on verbose logging and inspect the output for repeated tool calls or repeated reasoning patterns. In practice, loops usually show up as the same intent being restated over and over, or the model keeps trying to “think” without producing a final answer.
import { Agent, Task, Crew } from "crewai";
const debuggerAgent = new Agent({
name: "Debugger",
role: "Loop inspector",
goal: "Find repeated behavior and stop after one pass",
backstory: "You only diagnose once and then report findings.",
verbose: true,
});
const task = new Task({
description:
"Inspect the workflow for repeated steps. If you detect repetition, explain the exact cause.",
expectedOutput: "A concise loop diagnosis.",
agent: debuggerAgent,
});
const crew = new Crew({
agents: [debuggerAgent],
tasks: [task],
});
await crew.kickoff();
- •Add explicit stop conditions in your prompt so the model knows when to exit. Most beginner loops happen because the agent is asked to be thorough without being told what “done” means.
import { Agent } from "crewai";
export const safeAgent = new Agent({
name: "SafeAgent",
role: "Support analyst",
goal:
"Answer once, then stop. Do not repeat steps already completed.",
backstory:
"You are strict about completion criteria and never continue after final output.",
verbose: true,
});
export const stopRules = `
Rules:
- Provide exactly one final answer.
- Do not re-run analysis after you have enough evidence.
- If you are uncertain, state uncertainty and stop.
- Never restate the same conclusion twice.
`;
- •Reduce ambiguity in the task description and make expected output concrete. Loops often come from vague instructions like “analyze deeply” or “keep improving,” which can keep an agent searching for more work that does not exist.
import { Task } from "crewai";
import { safeAgent } from "./agent.js";
const task = new Task({
description:
`${"Review this error pattern:"}\n` +
`${"The agent repeats the same reasoning three times."}\n` +
`${"Return only:"}\n` +
`${"- root cause\n- one fix\n- one verification step"}`,
expectedOutput:
"Three bullets only: root cause, one fix, one verification step.",
agent: safeAgent,
});
- •Put a hard boundary around execution in your application code. If your workflow still loops because of upstream configuration or prompt drift, cap runtime at the app layer so your process does not hang indefinitely.
import { Agent, Task, Crew } from "crewai";
const agent = new Agent({
name: "BoundedAgent",
role: "Troubleshooter",
goal: "Diagnose once and finish",
backstory: "You never exceed one pass of analysis.",
});
const task = new Task({
description: "Explain why this crew might loop and how to prevent it.",
expectedOutput: "A short diagnostic summary.",
agent,
});
const crew = new Crew({ agents: [agent], tasks: [task] });
async function runWithTimeout() {
const timeoutMs = Number(process.env.CREW_TIMEOUT_MS ?? "30000");
const timeout = new Promise((_, reject) =>
setTimeout(() => reject(new Error("Crew execution timed out")), timeoutMs)
);
return Promise.race([crew.kickoff(), timeout]);
}
runWithTimeout().then(console.log).catch(console.error);
- •Make debugging repeatable by testing two versions of the same task: one that loops and one that exits cleanly. This is how you confirm whether the fix is actually in the prompt or just hidden by luck.
import { Agent, Task, Crew } from "crewai";
const agent = new Agent({
name: "Tester",
role: "QA analyst",
goal: "Return a single complete answer",
});
const loopingTask = new Task({
description:
"Keep refining your answer until it is perfect.",
expectedOutput:
"A final answer with no repetition.",
agent,
});
const fixedTask = new Task({
description:
[
"Answer this once:",
"- What causes agent loops?",
"- Give one prevention technique.",
"- Stop after three bullets."
].join("\n"),
expectedOutput:
"Exactly three bullets.",
agent,
});
new Crew({ agents: [agent], tasks: [loopingTask] });
new Crew({ agents: [agent], tasks: [fixedTask] });
Testing It
Run the looping version first and watch for repeated reasoning in verbose logs or stalled execution. Then run the fixed version and confirm it returns a single bounded response with no extra passes.
If you added a timeout wrapper, temporarily lower CREW_TIMEOUT_MS to something small like 5000 to verify your app fails fast instead of hanging. The clean version should finish well before that limit.
If output still repeats, tighten your prompt again before touching architecture. In most beginner cases, loops come from unclear completion criteria rather than anything wrong with CrewAI itself.
Next Steps
- •Add structured logging around
kickoff()so you can correlate prompts, outputs, and retries - •Learn how tool usage can trigger loops when tools return ambiguous results
- •Introduce validation on final outputs so your app rejects repeated or incomplete responses
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