> ## 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 新增模型 fallback

> 透過依序嘗試 model ID、重試可重試的失敗，並在請求格式錯誤時停止，使用 CometAPI 新增模型 fallback。

在你的應用程式中維護一個小型且有序的 model ID 清單來新增模型 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 模型

以下請求會列出可用的 model ID，你可以評估哪些適合作為 fallback：

```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。       |

## 相關連結

* [錯誤代碼與重試策略](/zh-Hant/guides/error-codes-and-retry-strategy)
* [速率限制與並行](/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/model-fallback-with-cometapi",
        "headline": "如何使用 CometAPI 加入模型回退？",
        "description": "透過依序嘗試 model ID、重試可重試的失敗，並在請求形狀錯誤時停止，即可使用 CometAPI 加入模型回退。",
        "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 加入模型回退？",
            "item": "https://apidoc.cometapi.com/guides/model-fallback-with-cometapi"
          }
        ]
      }
    ]
    }
    `}
</script>
