Error Handling
Overview
Tokenlio API uses standard HTTP status codes and returns detailed error responses to help you diagnose and handle issues.
HTTP Status Codes
| Code | Meaning | Description |
|---|---|---|
| 200 | OK | Request succeeded |
| 400 | Bad Request | Invalid request parameters |
| 401 | Unauthorized | Invalid or missing API key |
| 403 | Forbidden | Insufficient permissions |
| 404 | Not Found | Resource not found |
| 429 | Too Many Requests | Rate limit exceeded |
| 500 | Internal Server Error | Server error |
| 502 | Bad Gateway | Upstream provider error |
| 503 | Service Unavailable | Temporary unavailability |
Error Response Format
All errors return JSON with the following structure:
{
"error": {
"code": "invalid_api_key",
"message": "Invalid authentication credentials",
"type": "authentication_error",
"param": null
}
}Fields
code: Machine-readable error codemessage: Human-readable error messagetype: Error categoryparam: Parameter that caused the error (if applicable)
Error Types
Authentication Errors (401)
Invalid API Key
{
"error": {
"code": "invalid_api_key",
"message": "Invalid API key provided",
"type": "authentication_error"
}
}Solution: Check your API key is correct and starts with tk-
Missing API Key
{
"error": {
"code": "missing_api_key",
"message": "No API key provided",
"type": "authentication_error"
}
}Solution: Include Authorization: Bearer tk-... header
Validation Errors (400)
Invalid Request
{
"error": {
"code": "invalid_request",
"message": "Missing required parameter: messages",
"type": "invalid_request_error",
"param": "messages"
}
}Solution: Check API documentation for required parameters
Invalid Model
{
"error": {
"code": "model_not_found",
"message": "The model 'gpt-5' does not exist",
"type": "invalid_request_error",
"param": "model"
}
}Solution: Use GET /v1/models to list available models
Rate Limit Errors (429)
{
"error": {
"code": "rate_limit_exceeded",
"message": "Rate limit exceeded. Please retry after 60 seconds",
"type": "rate_limit_error"
}
}Solution: Implement exponential backoff and respect Retry-After header
Insufficient Balance (402)
{
"error": {
"code": "insufficient_balance",
"message": "Insufficient account balance. Please top up",
"type": "payment_error"
}
}Solution: Add funds at app.tokenlio.ai/billing
Server Errors (500, 502, 503)
{
"error": {
"code": "internal_error",
"message": "An internal error occurred. Please try again",
"type": "server_error"
}
}Solution: Retry with exponential backoff. Contact support if persistent.
Best Practices
Retry Logic
Implement exponential backoff for retryable errors:
import time
from openai import OpenAI, APIError, RateLimitError
client = OpenAI(
api_key="your-tokenlio-key",
base_url="https://api.tokenlio.ai/v1"
)
def make_request_with_retry(max_retries=3):
for attempt in range(max_retries):
try:
response = client.chat.completions.create(
model="gpt-4-turbo",
messages=[{"role": "user", "content": "Hello"}]
)
return response
except RateLimitError:
if attempt == max_retries - 1:
raise
wait_time = 2 ** attempt # 1s, 2s, 4s
print(f"Rate limited. Waiting {wait_time}s...")
time.sleep(wait_time)
except APIError as e:
if e.status_code >= 500: # Server errors
if attempt == max_retries - 1:
raise
wait_time = 2 ** attempt
print(f"Server error. Retrying in {wait_time}s...")
time.sleep(wait_time)
else:
raise # Don't retry client errorsError Logging
Log errors for debugging:
import logging
logger = logging.getLogger(__name__)
try:
response = client.chat.completions.create(...)
except Exception as e:
logger.error(f"API request failed: {e}", exc_info=True)
# Handle error appropriatelyUser-Friendly Messages
Don't expose raw error messages to end users:
try:
response = make_api_call()
except RateLimitError:
return "Service is busy. Please try again in a moment."
except InsufficientBalanceError:
return "Account credit depleted. Please contact support."
except APIError:
return "Unable to process request. Please try again later."Response Headers
Useful headers in error responses:
X-Request-ID: req_abc123xyz
Retry-After: 60
X-RateLimit-Remaining: 0
X-RateLimit-Reset: 1704067200X-Request-ID: Include when contacting supportRetry-After: Seconds to wait before retryX-RateLimit-Remaining: Requests remaining in current windowX-RateLimit-Reset: Unix timestamp when limit resets
Common Issues
SSL Certificate Errors
Error: SSL: CERTIFICATE_VERIFY_FAILED
Solution:
# Ensure you're using https://
client = OpenAI(
api_key="tk-...",
base_url="https://api.tokenlio.ai/v1" # https, not http
)Timeout Errors
Error: Request timeout after 60s
Solution: Increase timeout for long-running requests:
import httpx
client = OpenAI(
api_key="tk-...",
base_url="https://api.tokenlio.ai/v1",
http_client=httpx.Client(timeout=120.0) # 120 seconds
)Connection Errors
Error: Connection refused or Name resolution failed
Solution:
- Check internet connectivity
- Verify firewall/proxy settings
- Check DNS resolution:
nslookup api.tokenlio.ai
Getting Help
If errors persist:
- Check Status Page for outages
- Review FAQ
- Contact support with:
X-Request-IDfrom error response- Error code and message
- Timestamp
- Request details (excluding sensitive data)
Support Email: support@tokenlio.ai
Error Code Reference
| Code | HTTP | Retryable | Description |
|---|---|---|---|
invalid_api_key | 401 | No | API key is invalid |
missing_api_key | 401 | No | No API key provided |
invalid_request | 400 | No | Invalid parameters |
model_not_found | 404 | No | Model doesn't exist |
rate_limit_exceeded | 429 | Yes | Too many requests |
insufficient_balance | 402 | No | Account balance too low |
internal_error | 500 | Yes | Server error |
upstream_error | 502 | Yes | Provider error |
service_unavailable | 503 | Yes | Temporary unavailability |