qwen3 中文文档 下载 App

百炼 API 限流与错误码处理 — 429 限流、401 认证、500 服务端

常见错误码

错误码HTTP 状态含义处理
InvalidApiKey401API Key 无效检查 Key 是否正确复制
Throttling429限流退避重试或升级配额
InsufficientQuota429额度用完充值或等新周期
InvalidParameter400参数错误检查请求格式
ServiceUnavailable500服务端故障重试
RequestTooLarge400请求太大缩短 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 错误

症状

HTTP 401 Unauthorized
code: InvalidApiKey
message: API key is invalid

排查步骤

  1. 确认环境变量是否正确设置
  2. 检查 Key 前后没有多余空格
  3. 如果 Key 已停用/删除,创建新 Key
  4. 确认 Key 属于正确的阿里云账号

服务端错误

500 ServiceUnavailable

通常是临时故障,直接重试即可。如果连续多次失败,关注阿里云百炼的状态页面。

503 模型过载

某些热门模型可能短暂过载。解决方案:

请求参数错误

常见原因:

网络问题

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")
)

费用控制

即使技术上没问题,也要注意费用:

相关阅读