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

# Tangani error API dan retry dengan CometAPI

> Tangani error CometAPI dengan memisahkan masalah bentuk request, kegagalan autentikasi, rate limit, dan kegagalan platform yang dapat di-retry.

Tangani error CometAPI dengan memutuskan apakah request harus diperbaiki atau di-retry. Retry `429`, kegagalan kelas timeout, dan kegagalan server sementara dengan backoff; jangan retry request yang malformed atau kegagalan autentikasi.

## Retry hanya kegagalan yang dapat di-retry

| Status atau sinyal             | Retry?         | Tindakan                                                    |
| ------------------------------ | -------------- | ----------------------------------------------------------- |
| `400`                          | Tidak          | Perbaiki body request atau parameter.                       |
| `401`                          | Tidak          | Perbaiki API key dan header `Authorization`.                |
| `403`                          | Biasanya tidak | Hapus field yang tidak didukung dan verifikasi akses model. |
| `429`                          | Ya             | Retry dengan exponential backoff dan jitter.                |
| `500` dengan `invalid_request` | Tidak          | Perbaiki bentuk request.                                    |
| `500`, `503`, `504`, `524`     | Ya             | Retry dengan backoff dan simpan request ID.                 |

## Tambahkan backoff

Contoh Python berikut hanya me-retry kegagalan yang dapat di-retry:

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

Respons yang berhasil mencakup output model:

```json theme={null}
{
  "choices": [
    {
      "message": {
        "role": "assistant",
        "content": "Hello."
      }
    }
  ],
  "usage": {
    "total_tokens": 9
  }
}
```

## Catat konteks yang berguna

Bentuk JSON berikut aman untuk disimpan setelah Anda menghapus secret pengguna dan file berukuran besar:

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

| Error                        | Perbaikan                                                      |
| ---------------------------- | -------------------------------------------------------------- |
| Retry `401`                  | Hentikan retry dan rotasi atau muat ulang API key.             |
| Retry JSON yang tidak valid  | Validasi body request sebelum mengirim request lain.           |
| Tidak ada request ID di log  | Tangkap body error yang persis sebelum SDK Anda membungkusnya. |
| Retry langsung setelah `429` | Tambahkan jitter dan kurangi concurrency.                      |

## Tautan terkait

* [Kode error & penanganan](/id/errors/error-codes-handling)
* [Rate limits dan konkurensi](/id/guides/rate-limits-and-concurrency)
* [Halaman model](/id/overview/models)
* [Direktori model](https://www.cometapi.com/models/)
* [Harga](https://www.cometapi.com/pricing/)
* [CometAPI quickstart](/id/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": "Bagaimana cara menangani kode error dan retry dengan CometAPI?",
        "description": "Tangani error CometAPI dengan memisahkan masalah bentuk permintaan, kegagalan autentikasi, rate limit, dan kegagalan platform yang dapat di-retry.",
        "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": "Dokumentasi CometAPI",
            "item": "https://apidoc.cometapi.com/"
          },
          {
            "@type": "ListItem",
            "position": 2,
            "name": "Panduan",
            "item": "https://apidoc.cometapi.com/guides/use-cometapi-with-openai-sdk"
          },
          {
            "@type": "ListItem",
            "position": 3,
            "name": "Bagaimana cara menangani kode error dan retry dengan CometAPI?",
            "item": "https://apidoc.cometapi.com/guides/error-codes-and-retry-strategy"
          }
        ]
      }
    ]
    }
    `}
</script>
