> ## 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로 model fallback 추가하기

> CometAPI에서 model ID를 순서대로 시도하고, 재시도 가능한 실패는 다시 시도하며, 요청 형식 오류에서는 중단하여 model fallback을 추가합니다.

앱에서 model ID의 작은 정렬된 목록을 유지하고, 실패가 재시도 가능하거나 모델별 문제일 때만 다음 모델을 시도하여 model fallback을 추가하세요. 잘못된 요청은 재시도하지 말고, 다른 모델을 호출하기 전에 `400`, `401`, 및 잘못된 요청 오류를 수정하세요.

## 순서 있는 fallback 구현

다음 Python 예제는 model ID를 순서대로 시도하고 재시도할 수 없는 오류에서는 중단합니다:

```python theme={null}
import os
import time
from openai import OpenAI, APIError, RateLimitError

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

models = ["your-primary-model-id", "your-fallback-model-id"]

for model in models:
    try:
        completion = client.chat.completions.create(
            model=model,
            messages=[
                {
                    "role": "user",
                    "content": "Summarize CometAPI in one sentence.",
                }
            ],
        )
        print(completion.choices[0].message.content)
        break
    except RateLimitError:
        time.sleep(2)
        continue
    except APIError as error:
        status_code = getattr(error, "status_code", None)
        if status_code in {500, 503, 504, 524}:
            time.sleep(2)
            continue
        raise
else:
    raise RuntimeError("All configured model fallbacks failed.")
```

성공한 응답은 완료에 성공한 첫 번째 모델에서 반환됩니다:

```json theme={null}
{
  "model": "your-fallback-model-id",
  "choices": [
    {
      "message": {
        "role": "assistant",
        "content": "CometAPI gives developers one API surface for multiple model providers."
      }
    }
  ]
}
```

## fallback 모델 선택

다음 요청은 fallback용으로 평가할 수 있는 사용 가능한 model ID를 나열합니다:

```bash theme={null}
curl https://api.cometapi.com/api/models
```

응답에는 모델 레코드가 포함됩니다:

```json theme={null}
{
  "success": true,
  "page": 0,
  "page_size": 0,
  "total": 301,
  "data": [
    {
      "id": "deepseek-v4-pro",
      "provider": "DeepSeek",
      "model_type": "text",
      "features": [
        "text-to-text"
      ],
      "pricing": {
        "currency": "USD / M Tokens",
        "input": 0.416,
        "output": 0.832,
        "per_request": null,
        "per_second": null
      },
      "api_doc_url": "https://apidoc.cometapi.com/api/text/chat"
    }
  ]
}
```

## 일반적인 오류

| 오류                     | 해결 방법                                         |
| ---------------------- | --------------------------------------------- |
| Fallback이 잘못된 요청을 가려버림 | `400`, `401`, 또는 잘못된 요청 오류에서는 fallback하지 마세요. |
| 모델마다 출력 형식이 다름         | 사용자에게 반환하기 전에 앱에서 응답을 정규화하세요.                 |
| Fallback으로 비용이 증가함     | fallback 목록에 추가하기 전에 각 모델의 비용을 추정하세요.         |
| 병렬 fallback이 너무 많음     | 제품에서 병렬 레이싱이 필요하지 않다면 fallback을 순차적으로 시도하세요.  |

## 관련 링크

* [오류 코드 및 재시도 전략](/ko/guides/error-codes-and-retry-strategy)
* [속도 제한 및 동시성](/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/model-fallback-with-cometapi",
        "headline": "CometAPI로 model fallback을 추가하려면 어떻게 하나요?",
        "description": "CometAPI에서 model ID를 순서대로 시도하고, 재시도 가능한 실패는 재시도하며, 요청 형태 오류에서는 중지하여 model fallback을 추가하세요.",
        "url": "https://apidoc.cometapi.com/guides/model-fallback-with-cometapi",
        "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로 model fallback을 추가하려면 어떻게 하나요?",
            "item": "https://apidoc.cometapi.com/guides/model-fallback-with-cometapi"
          }
        ]
      }
    ]
    }
    `}
</script>
