百炼 API 限流与错误码处理 — 429 限流、401 认证、500 服务端
常见错误码
| 错误码 | HTTP 状态 | 含义 | 处理 |
|---|---|---|---|
InvalidApiKey | 401 | API Key 无效 | 检查 Key 是否正确复制 |
Throttling | 429 | 限流 | 退避重试或升级配额 |
InsufficientQuota | 429 | 额度用完 | 充值或等新周期 |
InvalidParameter | 400 | 参数错误 | 检查请求格式 |
ServiceUnavailable | 500 | 服务端故障 | 重试 |
RequestTooLarge | 400 | 请求太大 | 缩短 prompt 或降低 max_tokens |
限流处理(最常见)
客户端限流保护
import time
import random
def call_with_backoff(api_func, max_retries=5):
for attempt in range(max_retries):
try:
return api_func()
except Exception as e:
error_code = getattr(e, "code", "")
if error_code == "Throttling":
# 指数退避 + 随机抖动
wait = (2 ** attempt) + random.uniform(0, 1)
print(f"限流,等待 {wait:.1f}s (第 {attempt + 1} 次重试)")
time.sleep(wait)
else:
raise e
raise Exception("超过最大重试次数")
异步环境中的限流
import asyncio
import random
async def async_call_with_backoff(async_api_func, max_retries=5):
for attempt in range(max_retries):
try:
return await async_api_func()
except Exception as e:
if getattr(e, "code", "") == "Throttling":
wait = (2 ** attempt) + random.uniform(0, 1)
await asyncio.sleep(wait)
else:
raise e
raise Exception("超过最大重试次数")
长期限流解决方案
- 联系阿里云升级账号配额
- 用多个 API Key 轮询(多账号池)
- 客户端做请求队列和批量合并
- 考虑本地部署(如果硬件允许)
API Key 错误
症状
HTTP 401 Unauthorized
code: InvalidApiKey
message: API key is invalid
排查步骤
- 确认环境变量是否正确设置
- 检查 Key 前后没有多余空格
- 如果 Key 已停用/删除,创建新 Key
- 确认 Key 属于正确的阿里云账号
服务端错误
500 ServiceUnavailable
通常是临时故障,直接重试即可。如果连续多次失败,关注阿里云百炼的状态页面。
503 模型过载
某些热门模型可能短暂过载。解决方案:
- 等一会儿再试
- 换一个类似规格的模型(如 qwen3-plus → qwen3-flash)
- 如果是思考模式,可以试试关掉思考
请求参数错误
常见原因:
messages格式不对(缺 role 或 content)- 上下文超限(超过模型的上下文长度)
max_tokens设得太大- 多模态请求中图片 URL 无法访问
网络问题
import requests
import os
# 设置代理(如果需要)
os.environ["HTTPS_PROXY"] = "http://your-proxy:port"
os.environ["HTTP_PROXY"] = "http://your-proxy:port"
# 或在 OpenAI Client 中设置
client = OpenAI(
api_key="...",
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
http_client=httpx.Client(proxies="http://your-proxy:port")
)
费用控制
即使技术上没问题,也要注意费用:
- 开启费用告警
- 定期检查用量
- 非必要场景关闭思考模式(省 token)
- 批量任务用异步 + 限流,避免突发大量请求