Retry Policy

Retry Policy 是 LLM 调用失败时的重试策略,包括指数退避、最大重试次数、可重试错误类型判断和重试预算控制。

#type / concept #status / evergreen #tech / ai #tech / architecture

[!info] related notes

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()

常见坑

  1. 无限重试: 没有最大次数限制
  2. 不区分错误类型: 401 也重试,浪费时间
  3. 不做退避: 立即重试触发 Provider 限流
  4. 重试 + Fallback 冲突: 应该先重试当前 Provider,失败后再 Fallback

参考资料

创建于 2026/6/30 更新于 2026/7/15