메인 콘텐츠로 건너뛰기

오류 응답 형식

모든 오류는 일관된 JSON 형식을 반환합니다:
{
  "error": {
    "message": "Human-readable error description",
    "type": "error_type",
    "code": "error_code",
    "param": "parameter_name"  // Optional, for validation errors
  }
}

HTTP 상태 코드

코드설명
400Bad Request - 잘못된 파라미터
401Unauthorized - 유효하지 않거나 누락된 API 키
402Payment Required - 잔액 부족
403Forbidden - 액세스 거부 또는 허용되지 않은 모델
404Not Found - 모델 또는 리소스를 찾을 수 없음
413Payload Too Large - 입력 또는 파일 크기 초과
429Too Many Requests - 속도 제한 초과
500Internal Server Error
502Bad Gateway - 업스트림 제공자 오류
503Service Unavailable - 모든 채널 실패
504Gateway Timeout - 요청 시간 초과

오류 유형

인증 오류 (401)

유형코드설명
invalid_api_keyinvalid_api_keyAPI 키가 누락되었거나 유효하지 않음
expired_api_keyexpired_api_keyAPI 키가 취소됨
from openai import OpenAI, AuthenticationError

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

결제 오류 (402)

유형코드설명
insufficient_quotainsufficient_quota계정 잔액이 너무 낮음
quota_exceededquota_exceededAPI 키 사용량 한도 도달
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")

액세스 오류 (403)

유형코드설명
access_deniedaccess_denied리소스 액세스 거부됨
access_deniedmodel_not_allowed이 API 키에 허용되지 않은 모델
{
  "error": {
    "message": "You don't have permission to access this model",
    "type": "access_denied",
    "code": "model_not_allowed"
  }
}

유효성 검사 오류 (400)

유형설명
invalid_request_error요청 파라미터가 유효하지 않음
context_length_exceeded모델에 비해 입력이 너무 김
model_not_found요청한 모델이 존재하지 않음
{
  "error": {
    "message": "model: 'invalid-model' is not a valid model",
    "type": "model_not_found",
    "param": "model"
  }
}

속도 제한 오류 (429)

속도 제한을 초과한 경우:
{
  "error": {
    "message": "Rate limit exceeded. Please slow down.",
    "type": "rate_limit_error",
    "code": "rate_limit_exceeded"
  }
}
포함된 헤더:
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1234567890
Retry-After: 60

페이로드 너무 큼 (413)

입력 또는 파일 크기가 제한을 초과한 경우:
{
  "error": {
    "message": "Input size exceeds maximum allowed",
    "type": "invalid_request_error",
    "code": "payload_too_large"
  }
}
일반적인 원인:
  • 이미지 파일이 너무 큼 (최대 20MB)
  • 오디오 파일이 너무 큼 (최대 25MB)
  • 입력 텍스트가 모델 컨텍스트 길이를 초과함

업스트림 오류 (502, 503)

유형설명
upstream_error제공자가 오류를 반환함
all_channels_failed사용 가능한 제공자 없음
timeout_error요청 시간 초과

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

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;
    }
  }
}

권장 사항

속도 제한이 발생하면 재시도 간격을 점진적으로 늘리십시오:
wait_time = 2 ** attempt  # 1s, 2s, 4s, 8s...
요청이 중단되는 것을 방지하기 위해 항상 적절한 타임아웃을 설정하십시오:
client = OpenAI(timeout=60.0)  # 60 second timeout
지원을 받기 위해 요청 ID를 포함한 전체 오류 응답을 로깅하십시오:
except APIError as e:
    logger.error(f"API Error: {e.status_code} - {e.message}")
일부 모델에는 특정 요구 사항(예: 최대 토큰, 이미지 형식)이 있습니다. 요청을 보내기 전에 입력을 유효성 검사하십시오.