> ## 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`、超时类故障以及临时服务器故障使用退避重试；不要重试格式错误的请求或身份验证失败。

## 仅重试可重试的故障

| Status or signal             | Retry? | Action                            |
| ---------------------------- | ------ | --------------------------------- |
| `400`                        | 否      | 修复请求体或参数。                         |
| `401`                        | 否      | 修复 API key 和 `Authorization` 请求头。 |
| `403`                        | 通常否    | 移除不受支持的字段并验证模型访问权限。               |
| `429`                        | 是      | 使用指数退避和抖动重试。                      |
| `500` with `invalid_request` | 否      | 修复请求格式。                           |
| `500`, `503`, `504`, `524`   | 是      | 使用退避重试并保留请求 ID。                   |

## 添加退避

以下 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` | 添加抖动并降低并发度。             |

## 相关链接

* [错误代码与处理](/zh-Hans/errors/error-codes-handling)
* [速率限制与并发](/zh-Hans/guides/rate-limits-and-concurrency)
* [模型页面](/zh-Hans/overview/models)
* [模型目录](https://www.cometapi.com/models/)
* [定价](https://www.cometapi.com/pricing/)
* [CometAPI 快速开始](/zh-Hans/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>
