跳到主要内容

错误处理

import time
from openai import OpenAI, RateLimitError, APITimeoutError, APIConnectionError

client = OpenAI(api_key="your-api-key", base_url="https://www.cheapertoken.work/v1")

def generate_with_retry(prompt, max_retries=3):
for attempt in range(max_retries):
try:
return client.chat.completions.create(
model="gemini-2.5-flash",
messages=[{"role": "user", "content": prompt}],
).choices[0].message.content
except RateLimitError:
wait = 2 ** attempt
print(f"触发限速,{wait}秒后重试...")
time.sleep(wait)
except APITimeoutError:
print("请求超时,重试中...")
except APIConnectionError as e:
print(f"连接错误: {e}")
break
raise Exception("请求失败,已达最大重试次数")

常见错误码

状态码原因处理方式
401API Key 无效检查 Key
429请求频率超限指数退避重试
500服务端错误稍后重试
503模型不存在或不可用检查模型名称