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

Định dạng phản hồi lỗi

Tất cả các lỗi đều trả về một định dạng JSON nhất quán:
{
  "error": {
    "message": "Human-readable error description",
    "type": "error_type",
    "code": "error_code",
    "param": "parameter_name"  // Optional, for validation errors
  }
}

Mã trạng thái HTTP

Mô tả
400Bad Request - Các tham số không hợp lệ
401Unauthorized - API key không hợp lệ hoặc bị thiếu
402Payment Required - Số dư không đủ
403Forbidden - Truy cập bị từ chối hoặc mô hình không được phép
404Not Found - Không tìm thấy mô hình hoặc tài nguyên
413Payload Too Large - Kích thước đầu vào hoặc tệp vượt quá giới hạn
429Too Many Requests - Vượt quá giới hạn tốc độ (Rate limit)
500Internal Server Error - Lỗi máy chủ nội bộ
502Bad Gateway - Lỗi từ nhà cung cấp thượng nguồn (Upstream provider)
503Service Unavailable - Tất cả các kênh đều thất bại
504Gateway Timeout - Yêu cầu quá hạn

Các loại lỗi

Lỗi xác thực (401)

LoạiMô tả
invalid_api_keyinvalid_api_keyAPI key bị thiếu hoặc không hợp lệ
expired_api_keyexpired_api_keyAPI key đã bị thu hồi
from openai import OpenAI, AuthenticationError

try:
    response = client.chat.completions.create(...)
except AuthenticationError as e:
    print(f"Authentication failed: {e.message}")

Lỗi thanh toán (402)

LoạiMô tả
insufficient_quotainsufficient_quotaSố dư tài khoản quá thấp
quota_exceededquota_exceededĐã đạt đến giới hạn sử dụng API key
from openai import OpenAI, APIStatusError

try:
    response = client.chat.completions.create(...)
except APIStatusError as e:
    if e.status_code == 402:
        print("Please top up your account balance")

Lỗi truy cập (403)

LoạiMô tả
access_deniedaccess_deniedTruy cập vào tài nguyên bị từ chối
access_deniedmodel_not_allowedMô hình không được phép cho API key này
{
  "error": {
    "message": "You don't have permission to access this model",
    "type": "access_denied",
    "code": "model_not_allowed"
  }
}

Lỗi xác thực dữ liệu (400)

LoạiMô tả
invalid_request_errorCác tham số yêu cầu không hợp lệ
context_length_exceededĐầu vào quá dài đối với mô hình
model_not_foundMô hình được yêu cầu không tồn tại
{
  "error": {
    "message": "model: 'invalid-model' is not a valid model",
    "type": "model_not_found",
    "param": "model"
  }
}

Lỗi giới hạn tốc độ (429)

Khi bạn vượt quá giới hạn tốc độ (rate limits):
{
  "error": {
    "message": "Rate limit exceeded. Please slow down.",
    "type": "rate_limit_error",
    "code": "rate_limit_exceeded"
  }
}
Các Header bao gồm:
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1234567890
Retry-After: 60

Dữ liệu quá lớn (413)

Khi kích thước đầu vào hoặc tệp vượt quá giới hạn:
{
  "error": {
    "message": "Input size exceeds maximum allowed",
    "type": "invalid_request_error",
    "code": "payload_too_large"
  }
}
Các nguyên nhân phổ biến:
  • Tệp hình ảnh quá lớn (tối đa 20MB)
  • Tệp âm thanh quá lớn (tối đa 25MB)
  • Văn bản đầu vào vượt quá độ dài ngữ cảnh (context length) của mô hình

Lỗi từ phía thượng nguồn (502, 503)

LoạiMô tả
upstream_errorNhà cung cấp trả về một lỗi
all_channels_failedKhông có nhà cung cấp nào khả dụng
timeout_errorYêu cầu đã quá hạn

Xử lý lỗi trong Python

from openai import OpenAI, APIError, RateLimitError, APIConnectionError

client = OpenAI(
    api_key="sk-your-api-key",
    base_url="https://api.lemondata.cc/v1"
)

def chat_with_retry(messages, max_retries=3):
    for attempt in range(max_retries):
        try:
            return client.chat.completions.create(
                model="gpt-4o",
                messages=messages
            )
        except RateLimitError as e:
            if attempt < max_retries - 1:
                import time
                time.sleep(2 ** attempt)  # Exponential backoff
                continue
            raise
        except APIConnectionError as e:
            print(f"Connection error: {e}")
            raise
        except APIError as e:
            print(f"API error: {e.status_code} - {e.message}")
            raise

Xử lý lỗi trong JavaScript

import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: 'sk-your-api-key',
  baseURL: 'https://api.lemondata.cc/v1'
});

async function chatWithRetry(messages, maxRetries = 3) {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      return await client.chat.completions.create({
        model: 'gpt-4o',
        messages
      });
    } catch (error) {
      if (error instanceof OpenAI.RateLimitError) {
        if (attempt < maxRetries - 1) {
          await new Promise(r => setTimeout(r, 2 ** attempt * 1000));
          continue;
        }
      }
      throw error;
    }
  }
}

Các phương pháp hay nhất

Khi bị giới hạn tốc độ, hãy đợi lâu dần giữa các lần thử lại:
wait_time = 2 ** attempt  # 1s, 2s, 4s, 8s...
Luôn thiết lập thời gian chờ hợp lý để tránh các yêu cầu bị treo:
client = OpenAI(timeout=60.0)  # 60 second timeout
Ghi lại toàn bộ phản hồi lỗi bao gồm request ID để được hỗ trợ:
except APIError as e:
    logger.error(f"API Error: {e.status_code} - {e.message}")
Một số mô hình có các yêu cầu cụ thể (ví dụ: max tokens, định dạng hình ảnh). Hãy xác thực đầu vào trước khi thực hiện yêu cầu.