页面简介
An AI agent gets stuck in an infinite loop when a model keeps calling a tool that fails, usually with the same arguments, because nothing in the agent loop
正文摘录
How to Stop an AI Agent Stuck in an Infinite LoopOpenRouter ·11/12/2026TL;DRTL;DRWhy do AI agents get stuck in infinite loops?Step 1: Turn on doom-loop detectionStep 2: Tell the detector what counts as the same callStep 3: Cap steps and cost for every runStep 4: Put a credit limit on the API keyWhich guard stops which loop?Frequently asked questionsNext stepsAn AI agent gets stuck in an infinite loop when a model keeps calling a tool that fails, usually with the same arguments, because nothing in the agent loop tells it to stop. Each retry resends the whole conversation, so every turn costs more than the last, and a loop left running overnight can cost thousands of dollars. This guide stops the loop with four guards, which we tested on six current models. Three run inside your agent through the OpenRouter Agent SDK (@openrouter/agent 0.11.0): doom-loop detection, a rule for which calls count as repeats, and caps on steps and cost. The fourth is a credit limit on your API key. We enforce it on our side, so it holds even when your agent code has a bug. TL;DR With doom-loop detection on, all six models we tested were blocked on their third identical tool call. Without it, 4 of 18 runs retried until a 40-step cap. With it, 16 of 18 runs ended after two real tool calls. doomLoop: true in callModel blocks the third identical call and ends the run at the sixth. Some models get past detection by changing the argument slightly. A loopKey that normalizes the argument stops them. stopWhen: [stepCountIs(n), maxCost(x)] caps every run, whatever causes the loop. A credit limit on the key caps your total spend. A request that doesn’t fit fails with a 402 and limit_source: “openrouter_key_limit”. Why do AI agents get stuck in infinite loops? An agent loop ends when the model answers without asking for a tool. A tool that keeps failing gives the model no reason to do that. The error goes back into the conversation, the instructions still say to finish the task, and another attempt looks like the right next step. Nothing in the loop counts attempts unless you add code that does. The loop also gets more expensive as it goes, because every turn resends the whole conversation, including every earlier failure. In one run we logged turn by turn, input grew from 131 tokens to 3,262, and the cost per turn nearly quadrupled. With a pricier model and many sessions running at once, that growth is how one night adds up to thousands of dollars. To watch it happen, we built a billing agent whose only tool fails the way a billing service that’s down would. To run it, save it as agent.ts, run bun add @openrouter/agent zod, set OPENROUTER_API_KEY, and run bun agent.ts: import { OpenRouter, tool, stepCountIs } from '@openrouter/agent'; import { z } from 'zod'; const openrouter = new OpenRouter({ apiKey: process.env.OPENROUTER_API_KEY }); let attempts = 0; const fetchInvoice = tool({ name: 'fetch_invoice', description: 'Fetch an invoice from the billing service by ID.', inputSchema: z.object({ invoice_id: z.string() }), execute: async ({ invoice_id }) => { attempts++; console.log(` fetch_invoice("${invoice_id}")`); throw new Error(`billing-service timeout after 30s fetching ${invoice_id}`); }, }); let cost = 0; const result = openrouter.callModel({ model: 'mistralai/mistral-large-4-0', instructions: 'You are a billing agent. Complete the task. If a tool call fails, retry it. ' + 'Do not stop until you have the invoice total.', input: 'Get the total of invoice INV-2291.', tools: [fetchInvoice] as const, stopWhen: stepCountIs(40), // so the demo ends hooks: { PostModelCall: [{ handler: ({ usage }) => { cost += usage?.cost ?? 0; } }], DoomLoopDetected: [{ handler: ({ action, streak }) => console.log(`DoomLoopDetected: ${action} (streak ${streak})`) }], SessionEnd: [{ handler: ({ reason }) => console.log(`SessionEnd: ${reason}`) }], }, }); const text = await result.getText(); const verdict = await result.getDoomLoopVerdict(); // set only when detection stopped the run console.log(`attempts: ${attempts}, cost: $${cost.toFixed(4)}`); console.log(verdict ? `stopped: ${verdict.message}` : text.slice(0, 160)); fetch_invoice("INV-2291") fetch_invoice("INV-2291") fetch_invoice("INV-2291") ... SessionEnd: max_turns attempts: 41, cost: $0.0309 I was unable to retrieve the total for invoice INV-2291. The billing service consistently timed out after 30 seconds on all 41 attempts to fetch this invoice, r All 41 calls were identical, and the run ended only because of stepCountIs(40). The extra call is one the model had already asked for when the cap fired, which the SDK still runs (Step 3 covers this). Without a stopWhen, the Agent SDK keeps looping until the model stops asking for tools, so this run wouldn’t have stopped on its own. The final answer says the service was timing out, so the model knew that on every turn and retried anyway. We ran the same agent three times on each of six models, with and without detection: ModelTool calls per run, no guardHit the 40-step capTool calls per run, doomLoop: trueanthropic/claude-haiku-5.56, 6, 60 of 32, 2, 2deepseek/deepseek-v4.1-flash6, 5, 70 of 32, 2, 2google/gemini-3.8-flash5, 6, 50 of 32, 2, 2mistralai/mistral-large-4-011, 41, 412 of 32, 12, 2openai/gpt-6-luna17, 37, 210 of 32, 2, 20x-ai/grok-4.741, 12, 412 of 32, 2, 2 Looping also changes from run to run. Grok 4.7 made 41, 12 and 41 calls on the same input, so one clean test doesn’t prove your agent won’t loop. Across all 18 runs, detection cut tool calls from 314 to 64 and spend from $0.29 to $0.05. Step 1: Turn on doom-loop detection Add one option to the callModel call: doomLoop: true, fetch_invoice("INV-2291") DoomLoopDetected: observe (streak 2) fetch_invoice("INV-2291") DoomLoopDetected: block (streak 3) DoomLoopDetected: block (streak 4) DoomLoopDetected: block (streak 5) DoomLoopDetected: stop (streak 6) SessionEnd: doom_loop attempts: 2, cost: $0.0034 stopped: Doom loop suspected: tool "fetch_invoice" was invoked in 6 consecutive rounds with identical arguments (fingerprint 64be4614c5ea3e26…). Repeating the call will not change the result. Take a different approach, or explain why repetition is required. Doom-loop detection fingerprints each tool call by its name and arguments. It canonicalizes the arguments first, so reordered JSON keys don’t hide a repeat. A repeat only counts when the model has seen the previous result and asks again, so five identical calls in one turn count as one. As the streak grows, it climbs the default ladder: observe at 2, block at 3 and stop at 6. When a call is blocked, the SDK skips execute and returns a tool error telling the model it’s repeating itself. Unlike the timeout, this error says another try won’t help. In most runs, the model read it and wrote a final answer straight away, ending with SessionEnd: complete. In the run above it kept asking, so stop ended the run with reason: doom_loop. getDoomLoopVerdict() returns a message only when detection ended the run, which makes it the signal to alert on. To stop sooner, lower the thresholds. With doomLoop: { ladder: { observe: 2, block: 3, stop: 4 } }, a GPT-6 Luna run ended at streak 4 for $0.0002. The ladder also has two rungs that are off by default. steer sends the model a note that it’s repeating itself, and escalate runs the next turn on a stronger model you pick. Step 2: Tell the detector what counts as the same call By default, two calls count as the same only when their arguments match exactly. After a block, some models changed the argument slightly, which gives the call a new fingerprint and starts a new streak: fetch_invoice("INV-2291") DoomLoopDetected: observe (streak 2) fetch_invoice("INV-2291") DoomLoopDetected: block (streak 3) fetch_invoice("2291") fetch_invoice("inv-2291") fetch_invoice("INV-2291") DoomLoopDetected: observe (streak 2) fetch_invoice("INV-2291") fetch_invoice("INV2291") ... SessionEnd: complete attempts: 13, cost: $0.0125 In nine more Mistral Large 4 runs with detection on, the model did this five times, and three of those reached the 40-step cap, mostly by alternating INV-2291 and inv-2291. GPT-6 Luna did the same with trailing spaces and newlines. The models are following the block message, which tells them to take a different approach. With only one tool, the only other approach they have is a different input. A loopKey on the tool tells the detector which part of the input identifies the call. For an invoice ID, that’s the digits: loopKey: ({ invoice_id }) => invoice_id.replace(/\D/g, ''), // "inv-2291 " and "INV-2291" are one call fetch_invoice("INV-2291") DoomLoopDetected: observe (streak 2) fetch_invoice("INV-2291") DoomLoopDetected: block (streak 3) DoomLoopDetected: block (streak 4) DoomLoopDetected: block (streak 5) SessionEnd: complete attempts: 2, cost: $0.0039 Every variant now maps to 2291, so the streak keeps growing and the repeats stay blocked. Five of six runs stopped after two real calls. In the sixth, the model tried a different invoice, INV-0000, which correctly reset the streak. Normalize case, spacing, prefixes and anything else that doesn’t change which record the tool fetches. To ignore a field entirely, like a timeout the model raises on each retry, list only the fields that matter: loopKey: [‘invoice_id’]. A tool whose job is to repeat, like one that polls a job’s status, takes loopKey: false. Step 3: Cap steps and cost for every run Detection only catches repeats. A model that tries something new every turn never repeats a fingerprint, and a model that keeps asking after a block isn’t stopped until stop fires. Stop conditions end the run no matter why it ran long. Import maxCost alongside stepCountIs, replace stopWhen and add two lifecycle hooks: let failuresInARow = 0; // tool errors in a row, whatever the arguments stopWhen: [stepCountIs(15), maxCost(0.01), () => failuresInARow >= 5], hooks: { // ...the hooks from before, plus: PostToolUse: [{ handler: () => { failuresInARow = 0; } }], PostToolUseFailure: [{