← 返回 2026-11-15 简报

如何阻止陷入无限循环的AI智能体

How to Stop an AI Agent Stuck in an Infinite Loop

语音播报
摘要
事件:OpenRouter发布新SDK功能,通过doom-loop检测等机制阻止AI智能体因工具失败陷入无限循环重试。 要点:开启检测后六款模型均被阻断,调用从314降至64次,花费由0.29美元减至0.05美元,并引入stepCountIs限制。 影响:防止开发者因模型逻辑缺陷产生巨额API账单,保障Agent系统稳定性,避免资源浪费和成本失控风险。

当模型反复调用一个失败的工具(通常使用相同的参数)时,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//keys/ 并调整密钥的总限额",
"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 密钥的信用额度限制配合使用。

下一步

本条评分 8.8 score-v1
  • 来源权威 8
    注册表 priority=8(OpenRouter)
  • 时效 0.772
    发布 70.5 小时前,衰减到 0.77/3.0
  • 多源印证 0
    只有 1 家在报(无旁证)
  • 社区信号 0
    无社区数据(本管线走 RSS,HN 的 hn_fetcher 未接入)
历史
刊期得分排名结果
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 未入选
原文链接:https://openrouter.ai/blog/tutorials/ai-agent-infinite-loop/
来源:OpenRouter
以上内容由 AI 自动翻译,仅供参考。
← 返回简报