Error from Custom OpenAI: AI_RetryError: Failed after 5 attempts. Last error: AP...
错误信息
API Error: Error from Custom OpenAI: AI_RetryError: Failed after 5 attempts. Last error: API Error: Status Code 503
AI 解决方案
报错分析报告
1.错误翻译
原文:AI_RetryError: Failed after 5 attempts. Last error: API Error: Status Code 503
译文:AI重试错误:尝试5次后失败。最后一次错误:API错误,状态码503
2.原因分析
3.解决方案
以Python为例,优化重试策略并明确处理503错误:
import requests
from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type
# 自定义重试异常
class APIServiceUnavailableError(Exception):
pass
@retry(
stop=stop_after_attempt(3), # 减少重试次数(避免无效消耗)
wait=wait_exponential(multiplier=1, min=2, max=10), # 指数退避等待(2→4→8秒)
retry=retry_if_exception_type(requests.exceptions.RequestException)
)
def call_custom_openai_api():
url = "YOUR_CUSTOM_OPENAI_ENDPOINT"
headers = {"Authorization": "Bearer YOUR_API_KEY"}
payload = {"prompt": "Your input"} # 替换为实际参数
response = requests.post(url, headers=headers, json=payload, timeout=15)
# 主动捕获503错误并抛出异常
if response.status_code == 503:
raise APIServiceUnavailableError("API服务暂时不可用(503)")
response.raise_for_status() # 抛出其他HTTP错误(如401/400)
return response.json()
# 调用示例
try:
result = call_custom_openai_api()
print("API调用成功:", result)
except APIServiceUnavailableError as e:
print(f"错误:{e},请10分钟后再试或联系服务商")
except requests.exceptions.RequestException as e:
print(f"请求失败:{str(e)[:100]}") # 截断长错误信息
4. 预防措施
tenacity库),避免短时间密集重试加重服务负担; 推荐工具: