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)
| Status | Meaning | Common Cause |
|---|---|---|
| 400 | Bad Request | Invalid parameters |
| 401 | Unauthorized | Invalid or missing API key |
| 402 | Payment Required | Insufficient credits |
| 403 | Forbidden | Access denied |
| 404 | Not Found | Invalid endpoint |
| 429 | Too Many Requests | Rate limit exceeded |
Server Errors (5xx)
| Status | Meaning | Common Cause |
|---|---|---|
| 500 | Internal Server Error | Server-side issue |
| 502 | Bad Gateway | Upstream provider error |
| 503 | Service Unavailable | Temporary overload |
| 504 | Gateway Timeout | Request 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
Bearerprefix 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-Afterheader
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 NoneExponential 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 NoneError 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
- Check the error message - It usually tells you exactly what's wrong
- Verify your request - Log the full request before sending
- Test with minimal payload - Start simple, add complexity
- Check API status - Visit the status page for outages
- Review rate limits - Check your plan's limits in Settings
Related
- API Overview - Getting started
- Authentication - API key setup
- Virtual Keys - Rate limit configuration