当模型反复调用一个失败的工具(通常使用相同的参数)时,AI 代理会陷入无限循环,因为代理循环中没有任何机制告诉它停止。每次重试都会重新发送整个对话,因此每一轮的开销都比上一轮更大,如果让这种循环在夜间运行,可能会花费数千美元。
本指南通过四个防护机制来阻止循环,我们在六个当前模型上进行了测试。其中三个通过 OpenRouter Agent SDK (@openrouter/agent 0.11.0) 在您的代理内部运行:死循环检测、定义哪些调用算作重复的规则,以及对步骤和成本的限制。第四个是 API 密钥的信用额度限制。我们在服务端强制执行此限制,因此即使您的代理代码存在漏洞,该限制依然有效。
TL;DR(太长不看)
开启死循环检测后,我们测试的所有六个模型都在第三次发出相同的工具调用时被阻止。未开启时,18 次运行中有 4 次重试直到达到 40 步的限制。开启后,18 次运行中有 16 次在两次实际工具调用后结束。
在 callModel 中设置 doomLoop: true 可阻止第三次相同的调用,并在第六次调用时结束运行。
某些模型通过略微更改参数来绕过检测。使用 normalize 参数的 loopKey 可以阻止这种情况。
stopWhen: [stepCountIs(n), maxCost(x)] 限制每次运行,无论导致循环的原因是什么。
密钥上的信用额度限制您的总花费。不符合条件的请求将失败,返回 402 状态码及 limit_source: “openrouter_key_limit”。
为什么 AI 代理会陷入无限循环?
当模型回答而不请求工具时,代理循环结束。一个不断失败的工具有理由让模型不这样做。错误信息被传回对话中,指令仍然要求完成任务,而另一次尝试看起来像是正确的下一步。除非您添加相关代码,否则循环中不会计算尝试次数。
随着循环的进行,费用也会越来越高,因为每一轮都会重新发送整个对话,包括之前所有的失败记录。在一次我们逐轮记录的运行中,输入从 131 个 token 增长到 3,262 个,每轮的开销几乎翻了两番。使用更昂贵的模型并让多个会话同时运行时,这种增长就是一夜之间累积出数千美元的原因。
为了观察这一过程,我们构建了一个计费代理,其唯一的工具以账单服务宕机时失败的方式运作。要运行它,将其保存为 agent.ts,运行 bun add @openrouter/agent zod,设置 OPENROUTER_API_KEY,然后运行 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:
Model Tool calls per run, no guard Hit the 40-step cap Tool calls per run, doomLoop: true
anthropic/claude-haiku-5.5 6, 6, 6 0 of 3 2, 2, 2
deepseek/deepseek-v4.1-flash 6, 5, 7 0 of 3 2, 2, 2
google/gemini-3.8-flash 5, 6, 5 0 of 3 2, 2, 2
mistralai/mistral-large-4-0 11, 41, 41 2 of 3 2, 12, 2
openai/gpt-6-luna 17, 37, 21 0 of 3 2, 2, 20
x-ai/grok-4.7 41, 12, 41 2 of 3 2, 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:检测到(连续次数 2)
fetch_invoice("INV-2291")
DoomLoopDetected:阻止(连续次数 3)
fetch_invoice("2291")
fetch_invoice("inv-2291")
fetch_invoice("INV-2291")
DoomLoopDetected:检测到(连续次数 2)
fetch_invoice("INV-2291")
fetch_invoice("INV2291")
...
SessionEnd:完成
尝试次数:13,成本:$0.0125
在另外五次开启检测的 Mistral Large 4 运行中,模型出现了这种情况五次,其中三次达到了 40 步的上限,主要是通过交替使用 INV-2291 和 inv-2291。GPT-6 Luna 则通过尾随空格和换行符实现了同样的效果。这些模型遵循了阻止消息的指示,该消息告诉它们采取不同的方法。由于只有一个工具,它们唯一的其他选择就是使用不同的输入。
工具上的 loopKey 告诉检测器输入的哪一部分用于标识调用。对于发票 ID,那就是数字:
loopKey: ({ invoice_id }) => invoice_id.replace(/\D/g, ''), // "inv-2291 " 和 "INV-2291" 视为同一次调用
fetch_invoice("INV-2291")
DoomLoopDetected:检测到(连续次数 2)
fetch_invoice("INV-2291")
DoomLoopDetected:阻止(连续次数 3)
DoomLoopDetected:阻止(连续次数 4)
DoomLoopDetected:阻止(连续次数 5)
SessionEnd:完成
尝试次数:2,成本:$0.0039
现在每个变体都映射到 2291,因此连续次数持续增长,重复调用被持续阻止。六次运行中有五次在两次实际调用后停止。在第六次运行中,模型尝试了另一张发票 INV-0000,这正确地重置了连续次数。
规范化大小写、间距、前缀以及任何不改变工具获取记录内容的其他内容。如果要完全忽略某个字段(例如模型每次重试时都会出现的超时),仅列出重要的字段:loopKey: ['invoice_id']。对于旨在重复执行的任务(如轮询作业状态的工具),使用 loopKey: false。
第三步:为每次运行设置步数和成本上限
检测只能捕获重复项。如果模型在每一步都尝试新内容,它永远不会重复指纹;如果模型在收到阻止后继续请求,直到触发 stop 条件才会停止。无论运行时间过长的原因是什么,stop 条件都会结束运行。导入 maxCost alongside stepCountIs,替换 stopWhen 并添加两个生命周期钩子:
let failuresInARow = 0; // 连续的工具错误,无论参数如何
stopWhen: [stepCountIs(15), maxCost(0.01), () => failuresInARow >= 5],
hooks: {
// ...之前的钩子,加上:
PostToolUse: [{ handler: () => { failuresInARow = 0; } }],
PostToolUseFailure: [{ handler: () => { failuresInARow++; } }],
},
stopWhen 在每一轮之后进行检查,当任何条件为真时运行停止。maxCost 汇总我们随每个响应返回的 usage.cost,因此它计算的是你被计费的内容。失败计数器忽略参数,因此即使没有 loopKey,它也能捕获第二步中改变的参数。在一次以相同方式改变参数的 Mistral Large 4 运行中,它在六次调用后结束了会话,成本为 $0.0062,状态为 SessionEnd: max_turns。
每个 stopWhen 条件都以 reason: max_turns 结束会话,因此如果需要区分不同的上限,请记录你自己的原因。当上限触发且模型仍有待处理的工具调用时,SDK 会运行这些调用,并禁用工具调用进行最后一次回合,从而使运行以书面答案结束。这就是为什么这次运行在限制为五次的情况下进行了六次调用,以及为什么第一个演示在限制为 40 次的情况下进行了 41 次调用的原因。设置 allowFinalResponse: false 以跳过该回合。
从你的正常运行中设置这两个上限。我们的运行在 Mistral Large 4 上花费了四到六个回合,成本在 $0.0018 到 $0.0053 之间,因此 15 步和 $0.01 的上限在不允许 40 次回合运行的情况下留出了余地。在这两者中,成本上限更为重要,因为后续回合的成本高于早期回合。
如果没有 Agent SDK,相同的防护措施可以适应任何循环。按工具名称和规范化参数计算调用次数,返回类似“已阻止:告知用户出错原因”的工具结果,而不是运行第三次重复,并在步数或累计 usage.cost 超过你的上限时停止。我们针对 chat completions API 的 Python 版本在所有三次运行中都在四步后停止了 Mistral Large 4,成本低于 $0.002。
第 4 步:为 API 密钥设置信用额度
到目前为止,所有防护机制都在您的智能体进程内运行。如果该代码存在漏洞、未包含限制措施,或者运行了一百个会话且每个会话都保持在 maxCost 以下,那么没有任何东西能限制总支出。而密钥上的信用额度可以限制总支出,因为我们在请求到达提供商之前会在我们这边进行检查。
在仪表板中或通过 create key API 设置限额(以美元为单位)和 limit_reset(每日、每周、每月或 null)。如果密钥使用 BYOK(自带密钥),还需将 include_byok_in_limit 设置为 true,因为它默认为 false,否则 BYOK 的支出不会计入限额。每日限额在 UTC 午夜重置,每周限额在周一重置。为每个智能体或客户分配其自己的密钥,这样单个循环只能花费该密钥份额内的金额。如果多个智能体必须共享一个密钥,请遵循“限制共享智能体密钥”指南。
在路由请求之前,我们会对其最坏情况进行定价,即输入加上 max_tokens。如果这超出了密钥剩余的额度,请求将失败,且您不会被收费。我们向一个昂贵模型发送了一个带有 max_tokens: 900000 的 chat completions 请求,该密钥剩余 $9.97,并收到了以下回复:
402
{
"error": {
"message": "此请求需要更多信用额度,或更少的 max_tokens。您请求了多达 900000 个令牌,但只能负担 664657 个。要增加额度,请访问 https://openrouter.ai/workspaces/
"code": 402,
"metadata": {
"limit_source": "openrouter_key_limit",
"remedy_hint": "在 https://openrouter.ai/settings/keys 提高或删除此 API 密钥的使用限制,或使用没有限制的密钥。",
"provider_name": null
}
},
"user_id": "
}
我们替换了工作区 slug、密钥哈希和组织 ID。
请根据 error.metadata.limit_source 进行分支判断,而不是根据消息文本或状态码。耗尽的密钥也会报告 openrouter_key_limit,且限额文档将该来源列在 402 信用错误和 403 预算错误之下。如果消息表明密钥只能负担更少的令牌(如上述示例),请使用较低的 max_tokens 重试。如果密钥已耗尽,直到限额重置前重试都无法成功,因此应将其视为停止信号。Agent SDK 将 402 抛出为 PaymentRequiredResponseError。唯一值得重试的 402 是 openrouter_in_flight_budget,在 Retry-After 标头之后。速率限制返回 429,这由我们的 LLM API 速率限制指南涵盖。
工作区预算将工作区内每个密钥的限额池化,按天、周、月或终身计算。被阻止的请求会收到 403 错误,消息类似“超出工作区每月 $500.00 预算。请联系您的组织管理员。”(我们并未触发此情况,因此消息来自文档。)已在进行中的请求仍会完成,因此支出可能会略微超出,但整夜运行的循环会在接近每日限额时停止。支出控制指南展示了工作区预算和按成员防护栏如何协同工作。
哪种防护机制阻止哪种循环?
每种防护机制捕获不同类型的循环。密钥限额可以捕获所有循环,但仅在密钥的限额用尽后才生效,因此它最适合用作最后一层防护。
| 循环类型 | doomLoop | loopKey | stopWhen | caps | 密钥限额或工作区预算 |
|---|---|---|---|---|---|
| 相同调用,相同参数 | 阻止它 | 不需要 | 在限额处停止 | 在限制处停止 | |
| 相同调用,略有不同的参数 | 错过它 | 阻止它 | 在限额处停止 | 在限制处停止 | |
| 每轮新方法 | 错过它 | 错过它 | 在限额处停止 | 在限制处停止 | |
| 多次运行,每次都在各自的限额下 | 仅按次 | 仅按次 | 仅按次 | 阻止总额 | |
| 缺少防护机制的部署 | 错过它 | 错过它 | 错过它 | 在限制处停止 |
常见问题解答
工具结果显示调用失败,而提示要求完成任务,因此对模型来说,再次尝试似乎是正确的做法。返回告诉模型下一步该做什么的错误,例如“计费服务宕机。告知用户并停止。”不要告诉模型重试直到成功。
最大迭代次数限制能阻止失控的成本吗?
最大迭代次数限制可防止单次运行无限期地持续下去,但它并不能限制你的花费,因为后续的对话轮次成本更高,且许多在限制范围内的运行累积起来仍会花费不菲。LangChain 的 AgentExecutor 中的 max_iterations 和 CrewAI 中的 max_iter 与 OpenRouter Agent SDK 中的 stepCountIs 功能相同。将其与每次运行的成本上限以及 API 密钥的信用额度限制配合使用。
下一步
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 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:
Model Tool calls per run, no guard Hit the 40-step cap Tool calls per run, doomLoop: true
anthropic/claude-haiku-5.5 6, 6, 6 0 of 3 2, 2, 2
deepseek/deepseek-v4.1-flash 6, 5, 7 0 of 3 2, 2, 2
google/gemini-3.8-flash 5, 6, 5 0 of 3 2, 2, 2
mistralai/mistral-large-4-0 11, 41, 41 2 of 3 2, 12, 2
openai/gpt-6-luna 17, 37, 21 0 of 3 2, 2, 20
x-ai/grok-4.7 41, 12, 41 2 of 3 2, 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: [{ handler: () => { failuresInARow++; } }],
},
stopWhen is checked after every round, and the run stops when any condition is true. maxCost sums the usage.cost we return with each response, so it counts what you’re billed. The failure counter ignores arguments, so it catches the changed arguments from Step 2 even without a loopKey. On a Mistral Large 4 run that changed its arguments the same way, it ended the session after six calls for $0.0062, with SessionEnd: max_turns.
Every stopWhen condition ends the session with reason: max_turns, so log your own reason if you need to tell the caps apart. When a cap fires while the model still has tool calls pending, the SDK runs them and makes one last turn with tool calling disabled, so the run ends with a written answer. That’s why this run made six calls against a cap of five, and why the first demo made 41 against a cap of 40. Set allowFinalResponse: false to skip that turn.
Set both caps from your normal runs. Ours took four to six turns and cost $0.0018 to $0.0053 on Mistral Large 4, so 15 steps and $0.01 leave room without allowing a 40-turn run. Of the two, the cost cap matters more, since later turns cost more than early ones.
Without the Agent SDK, the same guards fit in any loop. Count calls per tool name and normalized arguments, return a tool result like “Blocked: tell the user what went wrong” instead of running the third repeat, and stop when steps or summed usage.cost pass your cap. Our Python version against the chat completions API stopped Mistral Large 4 after four steps, for under $0.002, in all three runs.
Step 4: Put a credit limit on the API key
Every guard so far runs inside your agent’s process. If that code has a bug, ships without the caps, or runs a hundred sessions that each stay under maxCost, nothing limits the total. A credit limit on the key does, because we check it on our side before the request reaches a provider.
Set limit (in dollars) and limit_reset (daily, weekly, monthly or null) in the dashboard or with the create key API. If the key uses BYOK, also set include_byok_in_limit to true, because it defaults to false and BYOK spend doesn’t count toward the limit otherwise. Daily limits reset at midnight UTC, and weekly limits reset on Monday. Give each agent or customer its own key, so one loop can only spend that key’s share. If several agents have to share a key, follow Capping Shared Agent Keys .
Before we route a request, we price its worst case, which is the input plus max_tokens. If that doesn’t fit in what the key has left, the request fails, and you aren’t charged. We sent a chat completions request with max_tokens: 900000 to an expensive model on a key with $9.97 left, and got this back:
402
{
"error": {
"message": "This request requires more credits, or fewer max_tokens. You requested up to 900000 tokens, but can only afford 664657. To increase, visit https://openrouter.ai/workspaces/
"code": 402,
"metadata": {
"limit_source": "openrouter_key_limit",
"remedy_hint": "Raise or remove this API key's usage limit at https://openrouter.ai/settings/keys, or use a key without a limit.",
"provider_name": null
}
},
"user_id": "
}
We replaced the workspace slug, key hash and organization ID.
Branch on error.metadata.limit_source, not on the message text or the status code. An exhausted key also reports openrouter_key_limit, and the limits docs list that source under both 402 credit errors and 403 budget errors. If the message says the key can afford fewer tokens, as in the example above, retry with a lower max_tokens. If the key is exhausted, retrying can’t succeed until the limit resets, so treat it as a stop. The Agent SDK throws the 402 as PaymentRequiredResponseError. The one 402 worth retrying is openrouter_in_flight_budget, after its Retry-After header. Rate limits return 429 instead, which our LLM API rate limits guide covers.
Workspace budgets pool the cap across every key in a workspace, per day, week, month or lifetime. Blocked requests get a 403 with a message like Workspace monthly budget of $500.00 exceeded. Contact your org admin. (We didn’t trigger this one, so the message comes from the docs.) Requests already in flight still finish, so spend can go slightly over, but a loop that runs all night stops close to the daily cap. The spend controls guide shows how workspace budgets and per-member guardrails fit together.
Which guard stops which loop?
Each guard catches a different kind of loop. The key limit catches all of them, but only once the key’s cap is spent, so it works best as the last layer.
Loop doomLoop loopKey stopWhen caps Key limit or workspace budget
Same call, same arguments Stops it Not needed Stops it at the cap Stops it at the limit
Same call, slightly different arguments Misses it Stops it Stops it at the cap Stops it at the limit
A new approach every turn Misses it Misses it Stops it at the cap Stops it at the limit
Many runs, each under its own cap Per run only Per run only Per run only Stops the total
A deploy with the guards missing Misses it Misses it Misses it Stops it at the limit
Frequently asked questions
The tool result says the call failed and the prompt says to finish the task, so another try looks like the right move to the model. Return errors that tell the model what to do next, like “The billing service is down. Tell the user and stop.” Don’t tell the model to retry until it succeeds.
Does a max iterations limit stop runaway costs?
A max iterations limit stops a single run from going on forever, but it doesn’t cap what you spend, because later turns cost more and many runs under the limit still add up. Settings like max_iterations in LangChain’s AgentExecutor and max_iter in CrewAI do the same job as stepCountIs in the OpenRouter Agent SDK. Pair one with a cost cap per run and a credit limit on the API key.
Next steps
| 刊期 | 得分 | 排名 | 结果 |
|---|---|---|---|
| 2026-11-26 | 8.4 | 36 | 未入选 |
| 2026-11-25 | 8.4 | 31 | 未入选 |
| 2026-11-24 | 8.4 | 29 | 未入选 |
| 2026-11-23 | 8.4 | 19 | 未入选 |
| 2026-11-15 | 8.77 | 22 | 入选 |
| 2026-11-14 | 9.22 | 34 | 未入选 |
| 2026-11-13 | 9.95 | 30 | 未入选 |