AI Agent重试机制:API挂了,别直接告诉用户

📘 AI教程 💬 🔥 Trending

🩺 摘要

API调用一定会失败。不是会不会的问题,是什么时候的问题。好的重试机制让Agent悄无声息地自己修复。

📝 详情

第一版Agent上线第一天,OpenAI限流了——Agent直接给用户回了句"出错啦"。用户跑了。

从那以后所有API调用都加了重试机制。

三种重试策略

1. 立即重试 适合:网络抖动、临时超时

for i in range(3):
    try:
        return call_api()
    except Exception:
        if i == 2: raise  # 最后一次还失败就认输

2. 指数退避 适合:速率限制(429)

import time
for i in range(3):
    try:
        return call_api()
    except RateLimitError:
        time.sleep(2 ** i)  # 1, 2, 4秒

3. 备用API 适合:主API挂了

apis = ["gpt-4o", "claude-3", "deepseek"]
for api in apis:
    try:
        return call_model(api, prompt)
    except Exception:
        continue

总结

重试机制的三条原则:瞬时错误马上重试,限流错误等一会儿再试,全挂了切备用。 最重要的是——不要让用户看到你的错误。