How to Fix 'agent infinite loop during development' in LlamaIndex (TypeScript)
What this error means
agent infinite loop during development usually means your LlamaIndex agent kept calling tools or re-entering the reasoning loop without ever reaching a terminal answer. In TypeScript, this most often shows up when the agent has no clear stop condition, a tool keeps returning something that triggers the same tool again, or the prompt encourages recursive behavior.
You’ll typically see this during local dev when testing an OpenAIAgent, ReActAgent, or workflow-style agent with one or more tools that can be called repeatedly.
The Most Common Cause
The #1 cause is a tool that returns something the agent treats as a new instruction instead of final output. That creates a self-reinforcing loop: the model calls the tool, reads the result, decides it needs the same tool again, and never exits.
A common broken pattern is using a tool that returns ambiguous text like “Try again” or echoes the user input.
| Broken | Fixed |
|---|---|
| Tool output feeds back into another tool call | Tool output is concrete and final |
| No max-iteration guard | Explicit stop condition |
| Prompt encourages retrying | Prompt asks for one pass and answer |
import { OpenAIAgent } from "llamaindex";
import { FunctionTool } from "llamaindex";
const brokenTool = FunctionTool.from(async ({ query }: { query: string }) => {
// Bad: this looks like an instruction, not data
return `I couldn't find it. Try searching again for: ${query}`;
});
const agent = new OpenAIAgent({
tools: [brokenTool],
systemPrompt: `
You are a helpful assistant.
If you can't answer, keep trying until you can.
`,
});
import { OpenAIAgent } from "llamaindex";
import { FunctionTool } from "llamaindex";
const fixedTool = FunctionTool.from(async ({ query }: { query: string }) => {
// Good: return data, not instructions
const result = await lookupCustomerRecord(query);
return JSON.stringify({
found: !!result,
customerId: result?.id ?? null,
status: result?.status ?? "not_found",
});
});
const agent = new OpenAIAgent({
tools: [fixedTool],
systemPrompt: `
You are a helpful assistant.
Call each tool at most once per user request unless new information appears.
If data is missing, answer with what you know and say what is missing.
`,
});
The important part is that your tool should return structured output that lets the model finish. If you hand it vague retry language, you’re basically telling it to continue looping.
Other Possible Causes
1) The tool schema is too broad
If your function accepts almost anything, the model may keep finding reasons to call it again.
// Too vague
const searchTool = FunctionTool.from(async (input: any) => {
return await search(input);
});
Use strict input shapes:
const searchTool = FunctionTool.from(async ({ term }: { term: string }) => {
return await search(term);
});
2) Your prompt explicitly encourages recursion
This is a real footgun in agent systems. Phrases like “keep trying,” “retry until successful,” or “use tools until certain” can trigger repeated calls.
const systemPrompt = `
Keep searching until you are completely sure.
Never stop early.
`;
Prefer bounded behavior:
const systemPrompt = `
Use tools only when needed.
If the first result is insufficient, answer with uncertainty instead of retrying forever.
`;
3) A tool calls the same agent again
This creates direct recursion. It’s easy to do when wrapping an agent inside another helper.
const recursiveTool = FunctionTool.from(async ({ message }: { message: string }) => {
// Bad: calling the same agent from inside its own tool path
return await agent.chat(message);
});
Fix by separating responsibilities:
const recursiveTool = FunctionTool.from(async ({ message }: { message: string }) => {
return await summarizeMessage(message); // no agent re-entry
});
4) No iteration cap in your runtime config
Depending on how you wire your workflow, you may need to set explicit limits. If you don’t bound iterations, a bad prompt/tool combo can spin indefinitely.
const agent = new OpenAIAgent({
tools,
maxIterations: 3,
});
If your version uses workflow steps or runner config instead of maxIterations, apply the same idea there: hard cap retries and stop after N turns.
How to Debug It
- •
Log every tool call
- •Print tool name, input, and output.
- •If you see the same call repeating with nearly identical arguments, that’s your loop source.
- •
Check whether the tool output is actionable
- •If it returns phrases like:
- •
Try again - •
Need more info - •
Search failed
- •
- •Replace those with structured data such as
{ status: "not_found" }.
- •If it returns phrases like:
- •
Temporarily disable all but one tool
- •Start with a single deterministic tool.
- •If the loop disappears, add tools back one by one until it returns.
- •
Inspect the prompt for retry language
- •Search for words like:
- •
always - •
keep trying - •
repeat - •
until success
- •
- •Replace them with bounded instructions.
- •Search for words like:
A useful debugging log looks like this:
console.log("[tool]", {
name: "customerLookup",
input,
});
const result = await customerLookup(input);
console.log("[tool-result]", {
name: "customerLookup",
result,
});
If you’re using LlamaIndex workflows, also watch for messages like:
- •
WorkflowError: exceeded max steps - •
AgentWorkflowError: step limit reached - •repeated
tool_callevents with no final response
Those are strong signals that your control flow never reaches an exit state.
Prevention
- •Return structured data from tools:
- •Prefer JSON objects over natural-language retries.
- •Add hard limits:
- •Cap iterations, retries, and workflow steps.
- •Keep prompts bounded:
- •Tell the agent when to stop instead of asking it to keep going.
If you’re building agents for production systems like banking or insurance workflows, treat every tool as an external dependency with failure modes. The safest agents are boring ones: strict inputs, strict outputs, explicit termination.
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