96SEO 2026-08-14 12:14 5
在一个普通的后端服务里“容错”通常指的是网络请求失败后怎么重试、超时怎么处理。不过,但当服务的主体变成一个会自主决策、多轮调用工具的 Agent 之后“故障”的定义也变了——它不再只是一次 HTTP 请求的失败。还可能是模型陷入了一种“技术上没有报错,但逻辑上原地打转”的状态。
这篇文章基于一个简单的 Agent Demo,拆解其中的容错设计。整个程序叠了三层防护,外加工具执行层面的兜底,层层递进,缺一不可。

使用者痛点:在实际业务中,LLM API 调用经常因为限流、服务过载或网络抖动而失败。老实说,盲目重试会导致资源浪费甚至雪崩式故障。
最基础的一层,应对的是 LLM API 调用本身的失败:限流、服务过载、网络抖动。这类失败的关键不是“要不要重试”,而是先判断“这次失败值不值得重试”。
export const isRetryable = : boolean => {
if ) return false;不过,const message = error.message;const statusMatch = message.match/);其实,if {
const status = parseInt;// 4xx 中可重试的特殊码
if ) return true;// 5xx 通常是瞬时错误
if return true;// 其它 4xx 不可重试
if return false;}
if || message.includes) return true;if || message.includes) return true;if || message.includes) return true;if ) return true;return false;},不过,
这段代码本质上是一份错误分类表:
使用者痛点:很多第三方 SDK 把错误包装成只有 message 的普通 Error缺少结构化字段。此时只能靠正则从文本中提取状态码,这种“务实退路”在生产环境里非常常见。
判断完“值不值得重试”,接下来才是“怎么重试”。
export function calculateDelay {
const exponential = baseMs * Math.pow;const capped = Math.min;// ±30% 随机抖动
const jitterFactor = Math.random * - 0.3;// -30% ~ +30%
return Math.max);}
指数退避叠加封顶(maxMs) 再加上 ±% 的随机抖动。抖动不是可有可无的装饰——如果多个客户端在同一时刻遇到限流。都按固定间隔重试,会形成新一轮拥堵;抖动把这些请求在时间上错开,是低成本但非常有效的解法。
在 Agent 主循环里这套逻辑包了一层 循环:
for {
try {
const result = streamText({
model。system,tools,messages,maxRetries: /* 禁用 SDK 自带重试 */
undefined,});for await {
/* ... */
}
stepResponse = await result.response;break,// 成功
} catch {
if ) throw error;const delay = calculateDelay;await sleep,// 重置局部状态,以免半成品残留
hasToolCall = false;fullText = "";老实说,shouldBreak = false;lastToolCall = null;说起来,}
}
streamText 显式传了 maxRetries: null/undefined 把 AI SDK 自带的重试关掉。如果两套重试逻辑叠在一起,实际次数和延迟会变得难以预测。既然要自己控制退避策略和错误分类,就必须完全接管。fullText、hasToolCall、lastToolCall 等局部状态。流式响应中途出错时上一次尝试看到了部分文本或记录了一次工具调用。
如果不清空,这些“半成品”会与新一次结果混合,引发重复文本或幽灵调用。*关键概念*:重新发起一次流式请求。就是重新启动整个流生命周期,而不是仅仅再发一次 HTTP 请求。使用者痛点:AIGC 程序经常出现模型虽然没有报错,却反复调用相同工具、返回相同结果,导致对话无限循环。这类隐蔽故障传统监控几乎捕捉不到。
第一层解决的是“请求失败了怎么办”。但 Agent 程序还有一类更隐蔽的故障:请求全部成功,模型也在正常输出,但它反复调用同一个工具、拿到一样结果,逻辑上毫无进展。按理说,这种 “卡住” 不会抛异常,传统的 retry 完全捕捉不到。
The core idea is to turn each tool call into a comparable fingerprint.
const stableStringify = : string => {
if return JSON.stringify;if )
return ``;const keys = Object.keys.sort;return `{${keys
.map => `${JSON.stringify}:${stableStringify)}`)
.join}}`;},export function hashToolCall: string {
return `${toolName}:${hash)}`;老实说,}
The sorting of object keys guarantees that {city:"北京",unit:"c"} and {unit:"c"。city:"北京"}} produce same hash—orwise trivial key‑order differences would break detection.
The system keeps three detectors inside a sliding window of length N=20. Each detector watches for a different “stuck” pattern:
The response strategy mirrors network layer:
if {
return {
至于stuck。true,level: "warning",detector,count: recentCount,message: 检测到 ${detector} 重复 ${recentCount} 次,};}
When a warning threshold is hit。instead of cutting off immediately we inject a system prompt so model can self‑correct:
messages.push({
至于role,"user",content:
${detection.message}。请换一个思路处理问题,不要重复一样的操作,});
Only when higher threshold is crossed do we actually break out of loop. This “warn‑first,abort‑later” pattern is exactly analogous to “retry‑first。give‑up‑later” on network side. User Pain Point: Developers often see endless token consumption without any error logs—this layered detection makes such silent stalls visible and recoverable.
User Pain Point: 即使有循环检测,也仍然可能漏掉极端卡死场景;若不设上限,一个失控 Agent 会耗尽算力、产生巨额费用。
The simplest safety net is a hard step limit:
const MAX_STEPS = 15;
let step = 0;while { step++;// ,主体逻辑 …if break,// 检测器触发熔断 messages.push;if break,// 模型主动结束 }
Three exit paths guarantee termination:
A fault in a tool should never bubble up as an uncaught exception that crashes whole Agent. Instead it should be transformed into a normal textual result that LLM can reason about.
execute: async => {
try {
const result = new Function;return `${expression} = ${result}`;} catch {
// 把异常包装成可读文本返回给模型
return `无法计算: ${expression}`;}
},If we didn’t catch here,an illegal expression would throw all way out of main loop and bring down entire service.
Returning a descriptive string turns “tool failure” into anor possible input for downstream reasoning—e.g.。let model decide wher to retry with a different expression or tell user it can’t compute it.
Wear lookup follows identical thinking:
return mockWear || `${city}:暂无数据`;User Pain Point: Production systems often crash because an unexpected exception from one auxiliary service propagates up unchecked. Converting every error into an explicit textual payload prevents that cascade.
用 Mock 模型给容错逻辑做故障演练
The biggest challenge of testing fault‑tolerance code is that real failures are hard to reproduce on demand—rate limits fire randomly,network glitches are sporadic. The demo solves this by using a mock LLM that can be instructed to emit deterministic failure scenarios.
if (
text.includes ||
text.includes
) {
retryTestCount++;if {
throw new Error(
"Too Many Requests - Rate limit exceeded"
);}
// 第三次固定成功
}
if (
text.includes ||
text.includes
) {
return {
toolName:"get_wear",args:{ city : alternating === true?"北京":"上海"} };}
-
First two calls deliberately throw
"Too Many Requests" so we can verify exponential backoff and jitter.
-
The third call succeeds → confirms that after retries we recover correctly.
-
The alternating wear scenario reproduces a ping‑pong loop → validates our cycle detector thresholds.
By turning unpredictable external faults into deterministic mock scripts we can write reliable unit / integration tests for every layer of our fault‑tolerance stack.
User Pain Point: Without such mocks developers spend hours chasing flaky CI runs caused by random API throttling.*
小结
A layered fault‑tolerant design for AI Agents can be distilled into a handful of universal principles:
-
先分类,再重试: 不是所有错误都值得
尝试;先判断是否有成功可能再决定是否进行回退。
-
退避要带抖动: 固定间隔容易形成同步拥堵;随机抖动让大量并发客户端自然分散。说起来,
-
Agent 的故障不仅是异常: 成功返回但行为停滞一样需要检测与恢复。话说回来,
-
分级响应。先给自我修正机会: 警告→提示→最终强制停止,比“一碰到问题立刻终止”更稳健。
-
Z兜底只需确定性: 步数上限这种最朴素保护不依赖任何判断,对程序安全提供绝对保障。
-
Anomaly 不应穿透边界: 工具或子模块出错时转换为模型能理解的文本,而不是直接抛异常导致崩溃。
-
Containerizable 测试必不可少: 把难以复现的大规模故障做成确定性的 mock,让容错代码本身可以被可靠地验证。
`
作为专业的SEO优化服务提供商,我们致力于通过科学、系统的搜索引擎优化策略,帮助企业在百度、Google等搜索引擎中获得更高的排名和流量。我们的服务涵盖网站结构优化、内容优化、技术SEO和链接建设等多个维度。
| 服务项目 | 基础套餐 | 标准套餐 | 高级定制 |
|---|---|---|---|
| 关键词优化数量 | 10-20个核心词 | 30-50个核心词+长尾词 | 80-150个全方位覆盖 |
| 内容优化 | 基础页面优化 | 全站内容优化+每月5篇原创 | 个性化内容策略+每月15篇原创 |
| 技术SEO | 基本技术检查 | 全面技术优化+移动适配 | 深度技术重构+性能优化 |
| 外链建设 | 每月5-10条 | 每月20-30条高质量外链 | 每月50+条多渠道外链 |
| 数据报告 | 月度基础报告 | 双周详细报告+分析 | 每周深度报告+策略调整 |
| 效果保障 | 3-6个月见效 | 2-4个月见效 | 1-3个月快速见效 |
我们的SEO优化服务遵循科学严谨的流程,确保每一步都基于数据分析和行业最佳实践:
全面检测网站技术问题、内容质量、竞争对手情况,制定个性化优化方案。
基于用户搜索意图和商业目标,制定全面的关键词矩阵和布局策略。
解决网站技术问题,优化网站结构,提升页面速度和移动端体验。
创作高质量原创内容,优化现有页面,建立内容更新机制。
获取高质量外部链接,建立品牌在线影响力,提升网站权威度。
持续监控排名、流量和转化数据,根据效果调整优化策略。
基于我们服务的客户数据统计,平均优化效果如下:
我们坚信,真正的SEO优化不仅仅是追求排名,而是通过提供优质内容、优化用户体验、建立网站权威,最终实现可持续的业务增长。我们的目标是与客户建立长期合作关系,共同成长。
Demand feedback