Chuyển đến nội dung chính

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.

Xử lý lỗi CometAPI bằng cách quyết định xem request cần được sửa hay nên retry. Hãy retry 429, các lỗi thuộc nhóm timeout, và các lỗi máy chủ tạm thời với backoff; không retry các request sai định dạng hoặc lỗi xác thực.

Chỉ retry các lỗi có thể retry

Status hoặc tín hiệuThử lại?Hành động
400KhôngSửa request body hoặc các tham số.
401KhôngSửa API key và header Authorization.
403Thường là khôngXóa các field không được hỗ trợ và xác minh quyền truy cập model.
429Retry với exponential backoff và jitter.
500 với invalid_requestKhôngSửa cấu trúc request.
500, 503, 504, 524Retry với backoff và giữ lại request ID.

Thêm backoff

Ví dụ Python sau chỉ retry các lỗi có thể retry:
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.")
Phản hồi thành công bao gồm đầu ra của model:
{
  "choices": [
    {
      "message": {
        "role": "assistant",
        "content": "Hello."
      }
    }
  ],
  "usage": {
    "total_tokens": 9
  }
}

Ghi log ngữ cảnh hữu ích

Cấu trúc JSON sau an toàn để lưu trữ sau khi bạn đã xóa bí mật người dùng và các tệp lớn:
{
  "method": "POST",
  "path": "/v1/chat/completions",
  "model": "your-model-id",
  "status": 429,
  "request_id": "request_id_from_error_message",
  "retryable": true
}

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

LỗiCách khắc phục
Retry 401Dừng retry và xoay vòng hoặc nạp lại API key.
Retry JSON không hợp lệXác thực request body trước khi gửi request khác.
Không có request ID trong logGhi lại chính xác error body trước khi SDK của bạn bọc nó.
Retry ngay sau 429Thêm jitter và giảm concurrency.

Liên kết liên quan

Last modified on May 28, 2026