Agent重试策略设计:从盲目重试到智能恢复
引言 在Agent系统中,失败是常态。LLM API超时、工具调用失败、网络波动——这些故障随时会发生。如何处理这些失败,决定了系统的可靠性。 重试是最直接的容错手段,但"盲目重试"——不分析原因、不调整策略地反复重试——不仅浪费资源,还可能加剧问题。2026年的Agent系统需要的是"智能重试"——根据故障类型、上下文和历史数据做出最优的重试决策。 一、何时应该重试 1.1 可重试错误 vs 不可重试错误 可重试错误: 网络超时 服务暂时不可用(503) 速率限制(429) 临时性数据冲突 不可重试错误: 参数错误(400) 认证失败(401/403) 资源不存在(404) 业务逻辑错误(如"余额不足") 1.2 判断框架 def should_retry(error, attempt_count, context): # 不可重试错误直接返回False if error.type in NON_RETRYABLE_ERRORS: return False # 超过最大重试次数 if attempt_count >= context.max_retries: return False # 速率限制:可以重试,但需要等待 if error.type == "rate_limit": wait_time = error.retry_after or calculate_backoff(attempt_count) return True, wait_time # 网络超时:检查是否值得重试 if error.type == "timeout": if context.estimated_remaining_time > context.deadline: return False # 重试也无法在截止时间内完成 return True, calculate_backoff(attempt_count) # 服务不可用:重试 if error.type == "service_unavailable": return True, calculate_backoff(attempt_count) # 未知错误:保守重试 return True, calculate_backoff(attempt_count) 二、退避算法 2.1 固定间隔 每次重试间隔相同时间。简单但可能造成"重试风暴"——所有失败请求同时重试。 2.2 指数退避 每次重试间隔按指数增长: Retry 1: wait 1s Retry 2: wait 2s Retry 3: wait 4s Retry 4: wait 8s Retry 5: wait 16s def exponential_backoff(attempt, base=1, factor=2, max_delay=60): delay = min(base * (factor ** attempt), max_delay) return delay 指数退避是最常用的策略,有效避免重试风暴。 ...