Retry Policy
Retry Policy 是 LLM 调用失败时的重试策略,包括指数退避、最大重试次数、可重试错误类型判断和重试预算控制。
#type / concept
#status / evergreen
#tech / ai
#tech / architecture
[!info] related notes
- 所属 MOC: AI Agent Application MOC
- 相关: Fallback Strategy, Model Gateway
Retry Policy
一句话定义
Retry Policy 是 LLM 调用失败时的重试策略。不是所有错误都应该重试(401 认证失败重试也没用),也不是无限重试(可能永远成功不了)。
核心原理
可重试 vs 不可重试
| 错误类型 | HTTP 状态码 | 可重试 | 策略 |
|---|---|---|---|
| 限流 | 429 | ✅ | 等待后重试 |
| 超时 | - | ✅ | 立即重试 |
| 服务器错误 | 500, 502, 503 | ✅ | 指数退避 |
| 认证失败 | 401 | ❌ | 换 Provider |
| 参数错误 | 400 | ❌ | 修复参数 |
| 权限不足 | 403 | ❌ | 换 Key |
指数退避
class RetryPolicy:
def __init__(self, max_retries=3, base_delay=1.0, max_delay=30.0):
self.max_retries = max_retries
self.base_delay = base_delay
self.max_delay = max_delay
def get_delay(self, attempt: int) -> float:
delay = self.base_delay * (2 ** attempt)
return min(delay, self.max_delay)
def should_retry(self, error: Exception, attempt: int) -> bool:
if attempt >= self.max_retries:
return False
if isinstance(error, RateLimitError):
return True
if isinstance(error, TimeoutError):
return True
if isinstance(error, ServerError):
return True
return False
async def with_retry(func, policy: RetryPolicy):
for attempt in range(policy.max_retries + 1):
try:
return await func()
except Exception as e:
if not policy.should_retry(e, attempt):
raise
delay = policy.get_delay(attempt)
await asyncio.sleep(delay)
raise MaxRetriesExceeded()
常见坑
- 无限重试: 没有最大次数限制
- 不区分错误类型: 401 也重试,浪费时间
- 不做退避: 立即重试触发 Provider 限流
- 重试 + Fallback 冲突: 应该先重试当前 Provider,失败后再 Fallback