跳轉到主要內容

Documentation Index

Fetch the complete documentation index at: https://apidoc.cometapi.com/llms.txt

Use this file to discover all available pages before exploring further.

透過判斷請求應該修正還是重試來處理 CometAPI 錯誤。對 429、逾時類失敗,以及暫時性的伺服器失敗使用退避重試;不要重試格式錯誤的請求或驗證失敗。

僅重試可重試的失敗

狀態或信號是否重試操作
400修正請求主體或參數。
401修正 API key 與 Authorization header。
403通常否移除不支援的欄位並確認模型存取權限。
429使用指數退避與 jitter 重試。
500 with invalid_request修正請求結構。
500, 503, 504, 524使用退避重試,並保留 request ID。

加入退避機制

以下 Python 範例只會重試可重試的失敗:
import os
import random
import time
from openai import APIError, OpenAI, RateLimitError

client = OpenAI(
    api_key=os.environ["COMETAPI_KEY"],
    base_url="https://api.cometapi.com/v1",
)

for attempt in range(5):
    try:
        response = client.chat.completions.create(
            model="your-model-id",
            messages=[{"role": "user", "content": "Say hello."}],
        )
        print(response.choices[0].message.content)
        break
    except RateLimitError:
        delay = min(30, 2**attempt) + random.random()
        time.sleep(delay)
    except APIError as error:
        status_code = getattr(error, "status_code", None)
        if status_code in {500, 503, 504, 524}:
            delay = min(30, 2**attempt) + random.random()
            time.sleep(delay)
            continue
        raise
else:
    raise RuntimeError("The request failed after retries.")
成功的回應會包含模型輸出:
{
  "choices": [
    {
      "message": {
        "role": "assistant",
        "content": "Hello."
      }
    }
  ],
  "usage": {
    "total_tokens": 9
  }
}

記錄有用的上下文

在移除使用者密鑰與大型檔案後,以下 JSON 結構可安全儲存:
{
  "method": "POST",
  "path": "/v1/chat/completions",
  "model": "your-model-id",
  "status": 429,
  "request_id": "request_id_from_error_message",
  "retryable": true
}

常見錯誤

錯誤修復方法
重試 401停止重試,並輪替或重新載入 API key。
重試無效的 JSON在送出另一個請求前先驗證請求主體。
日誌中沒有 request ID在 SDK 包裝錯誤之前,擷取原始錯誤主體。
429 後立即重試加入 jitter 並降低並行數。

相關連結

Last modified on May 28, 2026