三类常见异常的根因拆解
1. 429 Too Many Requests
通常对应以下三种情况之一:
- 并发超限:单条 API Key 或所属分组的瞬时并发槽位已满(常见于批量并发跑脚本未加信号量控制)。
- 上游账号池短时抖动:高峰期某个上游通道触发速率保护,稍作退避即可被网关自动路由至健康上游。
- 账户余额不足或达到 Key 预算上限:需在控制台查看实时余额与单 Key 限额。
2. 504 Gateway Timeout / 流式半途截断
- 客户端未开启
stream: true,等待完整响应超过客户端默认timeout(很多 HTTP 库默认仅 30s–60s)。 - 客户端前面串了公司内部代理或自建反代,未配置
proxy_buffering off与proxy_read_timeout 600s。
3. 413 Request Entity Too Large
- 一次性传入过多高分辨率未压缩图片或超长日志。请优先压缩图片为 WebP 或拆分超长上下文。
生产级 Python 指数退避 + 并发控制模板
在批处理或自动化流水线中,不要裸写 for 循环无限制并发,建议使用 asyncio.Semaphore + 带抖动的指数退避:
import asyncio
import random
from openai import AsyncOpenAI, RateLimitError, APITimeoutError, InternalServerError
client = AsyncOpenAI(
base_url="https://www.aiozium.com/v1",
api_key="sk-your-aiozium-api-key",
timeout=300.0,
max_retries=0, # 由自定义退避逻辑精细控制
)
SEM = asyncio.Semaphore(5) # 建议按分组额度控制并发数
async def call_with_backoff(prompt: str, model: str = "gpt-6.2-sol", max_attempts: int = 5) -> str:
async with SEM:
for attempt in range(max_attempts):
try:
resp = await client.chat.completions.create(
model=model,
messages=[{"role": "user", "content": prompt}],
stream=True,
)
chunks = []
async for chunk in resp:
if chunk.choices and chunk.choices[0].delta.content:
chunks.append(chunk.choices[0].delta.content)
return "".join(chunks)
except (RateLimitError, APITimeoutError, InternalServerError) as exc:
if attempt == max_attempts - 1:
raise
delay = min(30.0, (2 ** attempt) + random.uniform(0.1, 0.6))
await asyncio.sleep(delay)
如果你自己还套了一层反向代理
若你的后端服务通过内网 Nginx 转发至 aiozium.com,请确保加入:
proxy_buffering off;
proxy_cache off;
proxy_read_timeout 600s;
client_max_body_size 50m; 相关问答
为什么非流式请求容易 504,而开启 stream=true 就稳定?
强推理模型在思考阶段可能耗时 30–120 秒。非流式请求在全部生成完毕前没有任何字节返回,极易触发中间链路或客户端的 60 秒空闲超时;开启 SSE 流式后网关会持续发送增量分片保持长连接活跃。
触发 429 后应该间隔多久重试?
优先读取响应头 Retry-After;若无该头,建议从 1s 起步按 2^n 指数退避并叠加 0–500ms 随机抖动,最多重试 4–5 次。