錯誤處理
本指南介紹 OfoxAI API 的錯誤回應格式、常見錯誤場景以及推薦的處理策略。
錯誤回應格式
所有錯誤回應遵循統一的 JSON 格式:
{
"error": {
"code": "invalid_api_key",
"message": "提供的 API Key 無效,請檢查後重試。",
"type": "authentication_error"
}
}HTTP 狀態碼
| 狀態碼 | 類型 | 說明 | 是否應重試 |
|---|---|---|---|
400 | invalid_request_error | 請求參數錯誤 | ❌ 修改參數後重試 |
401 | authentication_error | API Key 無效或缺失 | ❌ 檢查 API Key |
403 | permission_error | 權限不足 | ❌ 檢查帳戶權限 |
404 | not_found_error | 模型或資源不存在 | ❌ 檢查模型 ID |
429 | rate_limit_error | 觸發速率限制 | ✅ 等待後重試 |
500 | internal_error | 伺服器內部錯誤 | ✅ 稍後重試 |
502 | upstream_error | 上游模型供應商錯誤 | ✅ 換模型或重試 |
503 | service_unavailable | 服務暫時不可用 | ✅ 稍後重試 |
常見錯誤和解決方案
401 — API Key 無效
{"error": {"code": "invalid_api_key", "message": "The API key provided is invalid."}}解決方案:
- 檢查 API Key 是否正確複製(包含
sk-前綴) - 確認 Key 未過期或被停用
- 檢查環境變數是否正確載入
429 — 速率限制
{"error": {"code": "rate_limit_exceeded", "message": "Rate limit reached. Please retry after 1s."}}解決方案:
- 檢查回應 Header 中的
x-ratelimit-reset-requests - 實作指數退避重試
- 如需更高配額,聯繫支援申請調整
502 — 上游錯誤
{"error": {"code": "upstream_error", "message": "The upstream provider returned an error."}}解決方案:
- 使用故障回退自動切換到備選模型
- 稍後重試
- 檢查模型供應商狀態頁
重試策略
推薦使用**指數退避(Exponential Backoff)**策略:
retry.py
import time
import random
from openai import OpenAI, APIError, RateLimitError, APIConnectionError
client = OpenAI(
base_url="https://api.ofox.ai/v1",
api_key="<你的 OFOXAI_API_KEY>"
)
def chat_with_retry(max_retries=5, **kwargs):
"""帶指數退避的重試封裝"""
for attempt in range(max_retries):
try:
return client.chat.completions.create(**kwargs)
except RateLimitError:
# 429: 等待後重試
wait = (2 ** attempt) + random.uniform(0, 1)
print(f"觸發限流,等待 {wait:.1f}s 後重試...")
time.sleep(wait)
except APIConnectionError:
# 網路錯誤:短暫等待後重試
wait = 2 ** attempt
print(f"連線錯誤,等待 {wait}s 後重試...")
time.sleep(wait)
except APIError as e:
if e.status_code and e.status_code >= 500:
# 5xx: 伺服器錯誤,重試
wait = 2 ** attempt
time.sleep(wait)
else:
# 4xx: 用戶端錯誤,不重試
raise
raise Exception(f"重試 {max_retries} 次後仍然失敗")
# 使用
response = chat_with_retry(
model="openai/gpt-4o",
messages=[{"role": "user", "content": "你好"}]
)逾時設定
建議為 API 呼叫設定合理的逾時時間:
# Python OpenAI SDK
client = OpenAI(
base_url="https://api.ofox.ai/v1",
api_key="<你的 OFOXAI_API_KEY>",
timeout=60.0, # 60 秒逾時
max_retries=3 # SDK 內建重試
)// TypeScript OpenAI SDK
const client = new OpenAI({
baseURL: 'https://api.ofox.ai/v1',
apiKey: '<你的 OFOXAI_API_KEY>',
timeout: 60000, // 60 秒逾時
maxRetries: 3 // SDK 內建重試
})串流請求建議使用更長的逾時時間(120-300 秒),因為模型可能需要較長時間生成完整內容。
最佳實踐
- 區分可重試和不可重試錯誤 — 4xx 通常需要修改請求,5xx 可以重試
- 使用指數退避 — 避免在限流時頻繁重試
- 設定最大重試次數 — 防止無限重試
- 記錄錯誤日誌 — 便於排查問題
- 設定故障回退 — 使用 OfoxAI 的
provider.fallback參數自動切換模型 - 監控錯誤率 — 在控制台關注錯誤趨勢
Last updated on