錯誤處理

本指南介紹 诺玛AI 的錯誤回應格式、常見錯誤場景以及推薦的處理策略。

錯誤回應格式#

所有錯誤回應遵循統一的 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 — 速率限制

解決方案:

  • 檢查回應 Header 中的 `x-ratelimit-reset-requests`
  • 實作指數退避重試
  • 如需更高配額,聯絡支援申請調整

502 — 上游錯誤

解決方案:

  • 使用故障回復自動切換到備選模型
  • 稍後重試
  • 檢查模型供應商狀態頁

重試策略#

推薦使用**指數退避(Exponential Backoff)**策略:

程式碼
import time
import random
from openai import OpenAI, APIError, RateLimitError, APIConnectionError
 
client = OpenAI(
    base_url="https://as.apinoma.com/v1",
    api_key="<你的 APINOMA_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://as.apinoma.com/v1",
    api_key="<你的 APINOMA_API_KEY>",
    timeout=60.0,  # 60 秒超時
    max_retries=3  # SDK 內建重試
)

串流請求建議使用更長的超時時間(120-300 秒),因為模型可能需要較長時間生成完整內容。

最佳實踐#

  • 區分可重試和不可重試錯誤 — 4xx 通常需要修改請求,5xx 可以重試
  • 使用指數退避 — 避免在限流時頻繁重試
  • 設定最大重試次數 — 防止無限重試
  • 記錄錯誤日誌 — 便於排查問題
  • 設定故障回復 — 使用 诺玛AI 的 `provider.fallback` 引數自動切換模型
  • 監控錯誤率 — 在控制台關注錯誤趨勢

最後更新於 2026 年 6 月 23 日