Error Response Format

{
  "error": {
    "message": "Invalid API key provided",
    "type": "invalid_request_error",
    "code": "invalid_api_key"
  }
}

Status Codes

CodeError TypeDescription
400Bad RequestInvalid parameters
401UnauthorizedInvalid API key
403ForbiddenInsufficient credits
404Not FoundModel/endpoint doesn’t exist
429Rate LimitToo many requests
500Server ErrorInternal error
503UnavailableService temporarily down

Python Error Handling

from openai import OpenAI, APIError, AuthenticationError, RateLimitError

client = OpenAI(
    api_key="YOUR_API_KEY",
    base_url="https://api.redpill.ai/v1"
)

try:
    response = client.chat.completions.create(
        model="openai/gpt-4o",
        messages=[{"role": "user", "content": "Hello"}]
    )
except AuthenticationError:
    print("❌ Invalid API key")
except RateLimitError:
    print("❌ Rate limit exceeded, retry later")
    time.sleep(60)
except APIError as e:
    print(f"❌ API error: {e.status_code} - {e.message}")
except Exception as e:
    print(f"❌ Unexpected error: {e}")

Retry Logic

import time
from openai import RateLimitError, APIError

def make_request_with_retry(max_retries=3):
    for attempt in range(max_retries):
        try:
            return client.chat.completions.create(
                model="openai/gpt-4o",
                messages=[{"role": "user", "content": "Hello"}]
            )
        except RateLimitError:
            if attempt < max_retries - 1:
                wait_time = 2 ** attempt  # Exponential backoff
                print(f"Rate limited, waiting {wait_time}s...")
                time.sleep(wait_time)
            else:
                raise
        except APIError as e:
            if e.status_code >= 500 and attempt < max_retries - 1:
                time.sleep(2 ** attempt)
            else:
                raise

JavaScript Error Handling

try {
  const response = await client.chat.completions.create({
    model: 'gpt-4',
    messages: [{ role: 'user', content: 'Hello' }]
  });
} catch (error) {
  if (error.status === 401) {
    console.error('Invalid API key');
  } else if (error.status === 429) {
    console.error('Rate limit exceeded');
    // Implement retry logic
  } else if (error.status === 403) {
    console.error('Insufficient credits');
  } else {
    console.error('API error:', error.message);
  }
}

Common Errors

Cause: API key is invalid or missingSolution:
  • Check API key in dashboard
  • Ensure “Bearer ” prefix in Authorization header
  • Verify no extra spaces
Cause: Account has insufficient creditsSolution:
  • Add credits in dashboard
  • Check usage with /v1/usage endpoint
Cause: Too many requestsSolution:
  • Implement exponential backoff
  • Reduce request rate
  • Upgrade account tier
Cause: Invalid model IDSolution:
  • Check model ID spelling
  • Use /v1/models to list available models
Cause: Input too long for modelSolution:
  • Reduce prompt length
  • Use model with larger context
  • Split into multiple requests

Best Practices

  1. Always use try-catch
  2. Implement exponential backoff
  3. Log errors for debugging
  4. Monitor credit balance
  5. Handle rate limits gracefully