> ## 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 處理 API 錯誤與重試

> 透過區分請求結構問題、驗證失敗、速率限制與可重試的平台失敗，來處理 CometAPI 錯誤。

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

## 僅重試可重試的失敗

| Status or signal             | Retry? | Action                           |
| ---------------------------- | ------ | -------------------------------- |
| `400`                        | 否      | 修正請求本文或參數。                       |
| `401`                        | 否      | 修正 API key 與 `Authorization` 標頭。 |
| `403`                        | 通常否    | 移除不支援的欄位並確認模型存取權限。               |
| `429`                        | 是      | 以指數退避與 jitter 進行重試。              |
| `500` with `invalid_request` | 否      | 修正請求結構。                          |
| `500`, `503`, `504`, `524`   | 是      | 使用 backoff 重試並保留 request ID。     |

## 加入 backoff

以下 Python 範例僅重試可重試的失敗：

```python theme={null}
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.")
```

成功回應包含模型輸出：

```json theme={null}
{
  "choices": [
    {
      "message": {
        "role": "assistant",
        "content": "Hello."
      }
    }
  ],
  "usage": {
    "total_tokens": 9
  }
}
```

## 記錄有用的上下文

在移除使用者機密資訊與大型檔案後，以下 JSON 結構可安全儲存：

```json theme={null}
{
  "method": "POST",
  "path": "/v1/chat/completions",
  "model": "your-model-id",
  "status": 429,
  "request_id": "request_id_from_error_message",
  "retryable": true
}
```

## 常見錯誤

| Error                       | Fix                     |
| --------------------------- | ----------------------- |
| Retrying `401`              | 停止重試，並輪換或重新載入 API key。  |
| Retrying invalid JSON       | 在送出另一個請求前，先驗證請求本文。      |
| No request ID in logs       | 在 SDK 包裝錯誤之前，擷取精確的錯誤本文。 |
| Immediate retry after `429` | 加入 jitter 並降低並行度。       |

## 相關連結

* [錯誤代碼與處理](/zh-Hant/errors/error-codes-handling)
* [速率限制與並行](/zh-Hant/guides/rate-limits-and-concurrency)
* [模型頁面](/zh-Hant/overview/models)
* [模型目錄](https://www.cometapi.com/models/)
* [定價](https://www.cometapi.com/pricing/)
* [CometAPI 快速入門](/zh-Hant/overview/quick-start)

<script type="application/ld+json">
  {`
    {
    "@context": "https://schema.org",
    "@graph": [
      {
        "@type": "TechArticle",
        "@id": "https://apidoc.cometapi.com/guides/error-codes-and-retry-strategy",
        "headline": "如何使用 CometAPI 處理錯誤代碼與重試？",
        "description": "透過區分請求結構問題、驗證失敗、速率限制，以及可重試的平台失敗來處理 CometAPI 錯誤。",
        "url": "https://apidoc.cometapi.com/guides/error-codes-and-retry-strategy",
        "author": {
          "@type": "Organization",
          "name": "CometAPI"
        },
        "publisher": {
          "@type": "Organization",
          "name": "CometAPI",
          "url": "https://www.cometapi.com"
        }
      },
      {
        "@type": "BreadcrumbList",
        "itemListElement": [
          {
            "@type": "ListItem",
            "position": 1,
            "name": "CometAPI 文件",
            "item": "https://apidoc.cometapi.com/"
          },
          {
            "@type": "ListItem",
            "position": 2,
            "name": "指南",
            "item": "https://apidoc.cometapi.com/guides/use-cometapi-with-openai-sdk"
          },
          {
            "@type": "ListItem",
            "position": 3,
            "name": "如何使用 CometAPI 處理錯誤代碼與重試？",
            "item": "https://apidoc.cometapi.com/guides/error-codes-and-retry-strategy"
          }
        ]
      }
    ]
    }
    `}
</script>
