The Kelly AI SDK provides several custom exception classes to help you handle different error scenarios. All errors inherit from a base BaseError class (except InvalidApiKey).
Raised when the API key is invalid or unauthorized.
class InvalidApiKey(Exception): pass
When it’s raised:
HTTP status codes 401 or 403
Missing or incorrect API key
Example:
from kellyapi import KellyAPIfrom kellyapi.errors import InvalidApiKeyasync def main(): api = KellyAPI(api_key="invalid_key") try: result = await api.llm(prompt="Hello") except InvalidApiKey: print("Invalid API key. Get an API key from @KellyAIBot")
Raised when the SDK fails to connect to the Kelly AI API server.
class ConnectionError(BaseError): message = "Failed to communicate server, Please report this: https://telegram.me/princexsupport"
When it’s raised:
HTTP status code 502
ClientConnectorError from aiohttp
Network connectivity issues
Example:
from kellyapi import KellyAPIfrom kellyapi.errors import ConnectionErrorasync def main(): api = KellyAPI(api_key="your_api_key_here") try: result = await api.llm(prompt="Hello") except ConnectionError: print("Failed to connect to server. Check your internet connection.")
Here’s a complete example showing how to handle all possible errors:
import asynciofrom kellyapi import KellyAPIfrom kellyapi.errors import ( InvalidApiKey, TimeoutError, ConnectionError, InvalidContent, InvalidRequest, GenericApiError, BaseError)async def generate_image_with_error_handling(): api = KellyAPI(api_key="your_api_key_here") try: image_data = await api.generate( prompt="A beautiful sunset over mountains", width=1024, height=1024 ) # Save the image with open("sunset.png", "wb") as f: f.write(image_data) print("Image generated successfully!") except InvalidApiKey: print("Error: Invalid API key. Get a key from @KellyAIBot") except TimeoutError: print("Error: Request timed out. The server took too long to respond.") except ConnectionError: print("Error: Failed to connect to server. Check your internet.") except InvalidContent: print("Error: Received invalid response from API.") except InvalidRequest: print("Error: Invalid request parameters.") except GenericApiError: print("Error: API call failed.") except BaseError as e: print(f"Error: {e.error_message}") except Exception as e: print(f"Unexpected error: {str(e)}")asyncio.run(generate_image_with_error_handling())
This is the most common error you’ll encounter during development. Always check your API key first:
try: result = await api.llm(prompt="Hello")except InvalidApiKey: print("Check your API key")
Implement retry logic for timeouts
For timeout errors, consider implementing exponential backoff:
from tenacity import retry, stop_after_attempt, wait_exponential@retry( stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=4, max=10))async def generate_with_retry(): api = KellyAPI(api_key="your_api_key_here") return await api.generate(prompt="Image")
Log errors for debugging
Always log errors with context for easier debugging:
import logginglogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)try: result = await api.llm(prompt="Hello")except BaseError as e: logger.error(f"API error: {e.error_message}", exc_info=True)
Provide user-friendly error messages
Catch specific errors and provide helpful messages to your users:
try: result = await api.generate(prompt=user_prompt)except InvalidApiKey: return "Please configure a valid API key in settings"except TimeoutError: return "Generation is taking longer than usual. Please try again."except ConnectionError: return "Cannot reach AI service. Please check your connection."