《AI Agent 开发入门》14.1 分类错误与重试

可重试状态来自 status 或 SDK 常见 status_code。错误分类只给候选策略,超时、429 和 5xx 不自动意味着写操作可安全重发。适配器关闭 SDK 自动重试,避免两层叠加。生产还需要 Retry-After、总时间预算与业务幂等判断;不可把所有 Exception 都归为暂时故障。

14.1 错误分类与显式退避

可重试状态来自 status 或 SDK 常见 status_code。错误分类只给候选策略,超时、429 和 5xx 不自动意味着写操作可安全重发。

实现选择

with_retry 默认真正 sleep,设置尝试上限、指数退避、随机扰动与 cap。演示显式注入零等待和固定随机源,所以可复现而不延迟读者。

适配器关闭 SDK 自动重试,避免两层叠加。生产还需要 Retry-After、总时间预算与业务幂等判断;不可把所有 Exception 都归为暂时故障。

minagent/reliable.py

# file: minagent/reliable.py | write
from __future__ import annotations
import time

from dataclasses import dataclass

@dataclass(frozen=True)
class Retryable:
    reason: str

@dataclass(frozen=True)
class Fatal:
    reason: str

class ToolError(Exception):
    def __init__(self, message: str, status: int | None = None):
        super().__init__(message)
        self.status = status

class ModelError(Exception):
    def __init__(self, message: str, status: int | None = None):
        super().__init__(message)
        self.status = status

RETRY_STATUS = {408, 429, 500, 502, 503, 504}

def classify(exc: Exception) -> Retryable | Fatal:
    status = getattr(exc, "status", getattr(exc, "status_code", None))
    if status in RETRY_STATUS:
        return Retryable(f"HTTP {status}")
    if isinstance(exc, (ConnectionError, TimeoutError)):
        return Retryable(type(exc).__name__)
    return Fatal(type(exc).__name__)

import random

def with_retry(fn, *, max_attempts=4, base=0.5, cap=8.0, jitter=0.2,
               sleep=None, rng=None):
    if max_attempts<1 or base<0 or cap<0 or not 0<=jitter<=1: raise ValueError("invalid retry settings")
    rng = rng or random.Random()
    sleep = sleep or time.sleep
    for attempt in range(1, max_attempts + 1):
        try:
            return fn(), attempt
        except Exception as exc:
            tag = classify(exc)
            if isinstance(tag, Fatal) or attempt == max_attempts:
                raise
            delay = min(cap, base * 2 ** (attempt - 1))
            delay = min(cap, delay * (1 + rng.uniform(-jitter, jitter)))
            print(f"  attempt {attempt} 失败({tag.reason})→ 退避 {delay:.3f}s")
            if sleep:
                sleep(delay)

demo_retry.py

# file: demo_retry.py | write
from __future__ import annotations
from minagent.reliable import *
import random

calls = {"n": 0}
def flaky_call():
    calls["n"] += 1
    if calls["n"] <= 2:
        raise ModelError("upstream unavailable", status=503)
    return {"ok": True, "attempt": calls["n"]}

result, attempts = with_retry(flaky_call,sleep=lambda _:None,rng=random.Random(0))
print("结果:", result, "总尝试:", attempts)

def bad_call():
    raise ToolError("bad argument: query must be str", status=400)

try:
    with_retry(bad_call)
except ToolError as e:
    print("不可重试:", e, "| 尝试次数:", 1)

运行与练习

运行 demo_retry.py,503 两次后成功;400 立即失败。练习 SDK status_code=429 的异常应分类为 Retryable,参考 ReliabilityTests.test_sdk_status_code_classification。

下载全卷项目 。在项目根运行本节 demo 文件;练习检查与故障用例见 tests/test_book.py、tests/test_extensions.py 和附录 B。

阅读导航:上一节:13.3 协作模式对照 · 下一节:14.2 超时、取消与结构化并发 。

继续阅读

探索更多技术文章

浏览归档,发现更多关于系统设计、工具链和工程实践的内容。

全部文章 返回首页

「agent」更多文章

  1. 《AI Agent 高级编程》目录
  2. 《AI Agent 高级编程》11.3 全景回顾:从零到框架的完整路径与展望
  3. 《AI Agent 高级编程》11.2 真实 API 冒烟:假模型 vs 真模型量化差距