跳到主要内容

错误处理与重试

使用内置重试

from openai import OpenAI

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

手动处理错误

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

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

def chat_stream(messages, max_retries=3):
for attempt in range(max_retries):
try:
stream = client.chat.completions.create(
model="gpt-5.4",
messages=messages,
stream=True,
)
result = ""
for chunk in stream:
if chunk.choices[0].delta.content:
result += chunk.choices[0].delta.content
return result
except RateLimitError:
wait = 2 ** attempt
print(f"触发限速,{wait}秒后重试...")
time.sleep(wait)
except APITimeoutError:
print("请求超时,重试中...")
except APIConnectionError as e:
print(f"连接错误: {e}")
break
raise Exception("请求失败,已达最大重试次数")

常见错误码

错误类型状态码原因处理方式
AuthenticationError401API Key 无效检查 Key
PermissionDeniedError403无访问权限检查账户
NotFoundError404模型不存在检查模型名称
RateLimitError429频率/额度超限指数退避重试
InternalServerError500服务端错误稍后重试