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 並降低並行數。 |
相關連結