> ## 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.

# Thêm fallback model với CometAPI

> Thêm fallback model với CometAPI bằng cách thử các model ID theo thứ tự, retry các lỗi có thể retry, và dừng lại khi gặp lỗi hình dạng request.

Thêm fallback model bằng cách giữ một danh sách nhỏ các model ID được sắp xếp theo thứ tự trong ứng dụng của bạn và chỉ thử model tiếp theo khi lỗi có thể retry hoặc mang tính đặc thù theo model. Không retry các request sai định dạng; hãy sửa các lỗi `400`, `401`, và invalid request trước khi gọi sang model khác.

## Triển khai fallback theo thứ tự

Ví dụ Python sau sẽ thử các model ID theo thứ tự và dừng lại khi gặp lỗi không thể retry:

```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.")
```

Phản hồi thành công sẽ đến từ model đầu tiên hoàn tất:

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

## Chọn các model fallback

Request sau liệt kê các model ID khả dụng mà bạn có thể đánh giá để dùng làm fallback:

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

Phản hồi chứa các bản ghi model:

```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"
    }
  ]
}
```

## Các lỗi thường gặp

| Error                                       | Fix                                                                           |
| ------------------------------------------- | ----------------------------------------------------------------------------- |
| Fallback che khuất các request không hợp lệ | Không fallback khi gặp lỗi `400`, `401`, hoặc invalid request.                |
| Các model có định dạng đầu ra khác nhau     | Chuẩn hóa phản hồi trong ứng dụng của bạn trước khi trả về cho người dùng.    |
| Fallback làm tăng chi phí                   | Ước tính chi phí cho từng model trước khi thêm vào danh sách fallback.        |
| Quá nhiều fallback song song                | Hãy thử fallback tuần tự trừ khi sản phẩm của bạn yêu cầu chạy đua song song. |

## Liên kết liên quan

* [Mã lỗi và chiến lược retry](/vi/guides/error-codes-and-retry-strategy)
* [Giới hạn tốc độ và tính đồng thời](/vi/guides/rate-limits-and-concurrency)
* [Trang models](/vi/overview/models)
* [Danh mục model](https://www.cometapi.com/models/)
* [Bảng giá](https://www.cometapi.com/pricing/)
* [Hướng dẫn bắt đầu nhanh CometAPI](/vi/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": "Làm cách nào để thêm model fallback với CometAPI?",
        "description": "Thêm model fallback với CometAPI bằng cách thử các model ID theo thứ tự, retry các lỗi có thể retry và dừng lại khi gặp lỗi về dạng yêu cầu.",
        "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": "Tài liệu CometAPI",
            "item": "https://apidoc.cometapi.com/"
          },
          {
            "@type": "ListItem",
            "position": 2,
            "name": "Hướng dẫn",
            "item": "https://apidoc.cometapi.com/guides/use-cometapi-with-openai-sdk"
          },
          {
            "@type": "ListItem",
            "position": 3,
            "name": "Làm cách nào để thêm model fallback với CometAPI?",
            "item": "https://apidoc.cometapi.com/guides/model-fallback-with-cometapi"
          }
        ]
      }
    ]
    }
    `}
</script>
