错误处理
- Python
- JavaScript
- curl
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("请求失败,已达最大重试次数")
import OpenAI from "openai";
const client = new OpenAI({ apiKey: "your-api-key", baseURL: "https://www.cheapertoken.work/v1" });
async function generateWithRetry(prompt, maxRetries = 3) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
const response = await client.chat.completions.create({
model: "gemini-2.5-flash",
messages: [{ role: "user", content: prompt }],
});
return response.choices[0].message.content;
} catch (err) {
if (err instanceof OpenAI.RateLimitError) {
const wait = 2 ** attempt;
console.log(`触发限速,${wait}秒后重试...`);
await new Promise((r) => setTimeout(r, wait * 1000));
} else if (err instanceof OpenAI.APIConnectionError) {
console.error(`连接错误: ${err.message}`);
break;
} else {
console.log("请求超时,重试中...");
}
}
}
throw new Error("请求失败,已达最大重试次数");
}
for attempt in 1 2 3; do
HTTP_STATUS=$(curl -s -o /tmp/response.json -w "%{http_code}" \
https://www.cheapertoken.work/v1/chat/completions \
-H "Authorization: Bearer your-api-key" \
-H "Content-Type: application/json" \
-d '{"model": "gemini-2.5-flash", "messages": [{"role": "user", "content": "你好"}]}')
if [ "$HTTP_STATUS" = "200" ]; then
cat /tmp/response.json; break
elif [ "$HTTP_STATUS" = "429" ]; then
echo "触发限速,等待后重试..."
sleep $((2 ** attempt))
else
echo "请求失败: $HTTP_STATUS"; break
fi
done
常见错误码
| 状态码 | 原因 | 处理方式 |
|---|---|---|
| 401 | API Key 无效 | 检查 Key |
| 429 | 请求频率超限 | 指数退避重试 |
| 500 | 服务端错误 | 稍后重试 |
| 503 | 模型不存在或不可用 | 检查模型名称 |