import requests
import time
from typing import Optional
class CloreAPIError(Exception):
def __init__(self, code: int, message: str, response: dict):
self.code = code
self.message = message
self.response = response
super().__init__(f"[{code}] {message}")
class RateLimitError(CloreAPIError):
pass
class InsufficientBalanceError(CloreAPIError):
pass
class ServerNotAvailableError(CloreAPIError):
pass
def handle_clore_response(response: dict) -> dict:
"""Handle Clore API response with proper error typing."""
code = response.get("code", -1)
if code == 0:
return response
error = response.get("error", "Unknown error")
# Map error codes to exceptions
if code == 5:
raise RateLimitError(code, "Rate limit exceeded", response)
if code == 3:
raise CloreAPIError(code, "Invalid or missing API key", response)
if code == 6:
# Handle specific error messages
if "not_enough_balance" in str(error):
raise InsufficientBalanceError(code, error, response)
if "server-already-rented" in str(error) or "server-offline" in str(error):
raise ServerNotAvailableError(code, error, response)
raise CloreAPIError(code, error, response)
def clore_request_with_retry(
method: str,
url: str,
headers: dict,
max_retries: int = 3,
**kwargs
) -> dict:
"""Make Clore API request with retry logic."""
for attempt in range(max_retries):
try:
response = requests.request(method, url, headers=headers, **kwargs)
data = response.json()
return handle_clore_response(data)
except RateLimitError:
# Exponential backoff
wait_time = 2 ** attempt
print(f"Rate limited, waiting {wait_time}s...")
time.sleep(wait_time)
except InsufficientBalanceError as e:
# Don't retry - need user action
raise e
except ServerNotAvailableError as e:
# Don't retry - need different server
raise e
except CloreAPIError as e:
if attempt == max_retries - 1:
raise e
time.sleep(1)
raise Exception("Max retries exceeded")
# Usage example
try:
result = clore_request_with_retry(
"POST",
"https://api.clore.ai/v1/create_order",
headers={"auth": "YOUR_API_KEY"},
json={...}
)
except InsufficientBalanceError:
print("Please top up your wallet")
except ServerNotAvailableError:
print("Server not available, trying another...")
except RateLimitError:
print("API rate limit - slow down requests")
except CloreAPIError as e:
print(f"API error: {e}")