Skip to main content
Docs
Error Handling

Error Handling

Understand and handle API errors from the Elyxir API.

The Elyxir API uses standard HTTP status codes and returns JSON error responses. This guide covers common errors and how to handle them.

Error Response Format

All errors return a JSON object with this structure:

{
  "error": {
    "message": "Human-readable error description",
    "type": "error_type",
    "code": "error_code"
  }
}

HTTP Status Codes

Client Errors (4xx)

StatusMeaningCommon Cause
400Bad RequestInvalid parameters
401UnauthorizedInvalid or missing API key
402Payment RequiredInsufficient credits
403ForbiddenAccess denied
404Not FoundInvalid endpoint
429Too Many RequestsRate limit exceeded

Server Errors (5xx)

StatusMeaningCommon Cause
500Internal Server ErrorServer-side issue
502Bad GatewayUpstream provider error
503Service UnavailableTemporary overload
504Gateway TimeoutRequest took too long

Common Errors

401 Unauthorized

Invalid API Key

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

Solutions:

  • Check that your API key starts with elyxir_
  • Verify the key hasn't been revoked
  • Ensure proper Bearer prefix in header

402 Payment Required

Insufficient Credits

{
  "error": {
    "message": "Insufficient credits to complete this request",
    "type": "payment_error",
    "code": "insufficient_credits"
  }
}

Solutions:

  • Check your credit balance in Studio
  • Add credits or upgrade your plan
  • Monitor usage to avoid running out

400 Bad Request

Invalid Parameters

{
  "error": {
    "message": "Invalid value for 'temperature': must be between 0 and 2",
    "type": "invalid_request_error",
    "code": "invalid_parameter"
  }
}

Common causes:

  • Missing required parameters (model, messages)
  • Invalid parameter values (temperature > 2)
  • Malformed JSON

429 Rate Limited

Too Many Requests

{
  "error": {
    "message": "Rate limit exceeded. Please slow down.",
    "type": "rate_limit_error",
    "code": "rate_limit_exceeded"
  }
}

Solutions:

  • Implement exponential backoff
  • Reduce request frequency
  • Upgrade your plan for higher limits
  • Check the Retry-After header

Handling Errors in Code

Python Example

import requests
from requests.exceptions import RequestException
 
def make_api_request(messages):
    try:
        response = requests.post(
            "https://api.elyxir.ai/v1/chat/completions",
            headers={
                "Authorization": "Bearer elyxir_your_api_key",
                "Content-Type": "application/json"
            },
            json={"model": "gpt-4o-mini", "messages": messages}
        )
 
        # Raise exception for 4xx/5xx status codes
        response.raise_for_status()
        return response.json()
 
    except requests.exceptions.HTTPError as e:
        error_data = e.response.json().get("error", {})
 
        if e.response.status_code == 401:
            print("Authentication failed. Check your API key.")
        elif e.response.status_code == 402:
            print("Insufficient credits. Add credits to continue.")
        elif e.response.status_code == 429:
            print("Rate limited. Waiting before retry...")
            # Implement backoff
        else:
            print(f"API error: {error_data.get('message')}")
 
        return None
 
    except RequestException as e:
        print(f"Request failed: {e}")
        return None

Exponential Backoff

For rate limits and transient errors:

import time
import random
 
def request_with_backoff(messages, max_retries=5):
    for attempt in range(max_retries):
        try:
            response = make_api_request(messages)
            if response:
                return response
        except RateLimitError:
            if attempt < max_retries - 1:
                # Exponential backoff with jitter
                wait_time = (2 ** attempt) + random.uniform(0, 1)
                print(f"Rate limited. Waiting {wait_time:.2f}s...")
                time.sleep(wait_time)
            else:
                raise
    return None

Error Prevention

Validate Before Sending

def validate_request(model, messages):
    if not model:
        raise ValueError("Model is required")
    if not messages or not isinstance(messages, list):
        raise ValueError("Messages must be a non-empty list")
    for msg in messages:
        if "role" not in msg or "content" not in msg:
            raise ValueError("Each message must have role and content")

Monitor Usage

  • Track API calls and token usage
  • Set up alerts for approaching limits
  • Review usage patterns in Studio analytics

Use Timeouts

response = requests.post(
    url,
    headers=headers,
    json=data,
    timeout=30  # 30 second timeout
)

Debugging Tips

  1. Check the error message - It usually tells you exactly what's wrong
  2. Verify your request - Log the full request before sending
  3. Test with minimal payload - Start simple, add complexity
  4. Check API status - Visit the status page for outages
  5. Review rate limits - Check your plan's limits in Settings
Error Handling | elyxir