> ## 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`, timeout 계열 장애, 일시적인 서버 장애는 backoff와 함께 재시도하고, 잘못된 요청이나 인증 실패는 재시도하지 마세요.

## 재시도 가능한 실패만 재시도하기

| Status or signal             | Retry? | Action                               |
| ---------------------------- | ------ | ------------------------------------ |
| `400`                        | 아니요    | 요청 본문 또는 파라미터를 수정하세요.                |
| `401`                        | 아니요    | API 키와 `Authorization` 헤더를 수정하세요.    |
| `403`                        | 보통 아니요 | 지원되지 않는 필드를 제거하고 model 접근 권한을 확인하세요. |
| `429`                        | 예      | 지수 백오프와 지터를 사용해 재시도하세요.              |
| `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.")
```

성공한 응답에는 model 출력이 포함됩니다:

```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                              |
| ----------------- | -------------------------------- |
| `401` 재시도         | 재시도를 중지하고 API 키를 교체하거나 다시 로드하세요. |
| 잘못된 JSON 재시도      | 다른 요청을 보내기 전에 요청 본문을 검증하세요.      |
| 로그에 request ID 없음 | SDK가 감싸기 전에 정확한 오류 본문을 캡처하세요.    |
| `429` 직후 즉시 재시도   | 지터를 추가하고 동시성을 줄이세요.              |

## 관련 링크

* [오류 코드 및 처리](/ko/errors/error-codes-handling)
* [속도 제한 및 동시성](/ko/guides/rate-limits-and-concurrency)
* [모델 페이지](/ko/overview/models)
* [모델 디렉터리](https://www.cometapi.com/models/)
* \[요금][https://www.cometapi.com/pricing/](https://www.cometapi.com/pricing/))
* [CometAPI 빠른 시작](/ko/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>
