This guide demonstrates robust error handling patterns for the Claro SDK. Proper error handling ensures your application remains stable and provides helpful feedback when issues occur.
import osfrom baytos.claro import BaytClient, BaytNotFoundError, BaytAuthError, BaytAPIErrorclient = BaytClient(api_key=os.getenv("BAYT_API_KEY"))try: prompt = client.get_prompt("@workspace/my-prompt:v1") print(f"Successfully loaded: {prompt.title}")except BaytNotFoundError as e: print(f"Prompt not found: {e}") print("Check the package name and version")except BaytAuthError as e: print(f"Authentication failed: {e}") print("Verify your API key is correct")except BaytAPIError as e: print(f"API error occurred: {e}") print("Please try again later")except Exception as e: print(f"Unexpected error: {e}")
Example output when prompt not found
Prompt not found: Prompt not found: @workspace/my-prompt:v1Check the package name and version
Example 2: Handle Missing API Key
Validate API key before making requests:
import osfrom baytos.claro import BaytClient, BaytAuthErrordef get_client(): """Initialize client with proper error handling""" api_key = os.getenv("BAYT_API_KEY") if not api_key: print("Error: BAYT_API_KEY environment variable not set") print("\nTo fix this:") print("1. Get your API key from: https://claro.baytos.ai") print("2. Set it with: export BAYT_API_KEY='your_api_key_here'") exit(1) try: return BaytClient(api_key=api_key) except ValueError as e: print(f"Invalid API key format: {e}") exit(1)# Usageclient = get_client()prompt = client.get_prompt("@workspace/my-prompt:v1")
Example 3: Retry Logic
Automatically retry failed requests:
import osimport timefrom baytos.claro import BaytClient, BaytRateLimitError, BaytAPIErrordef get_prompt_with_retry(package_name, max_retries=3): """Fetch prompt with automatic retry""" client = BaytClient(api_key=os.getenv("BAYT_API_KEY")) for attempt in range(max_retries): try: return client.get_prompt(package_name) except BaytRateLimitError as e: if attempt < max_retries - 1: wait_time = 2 ** attempt # Exponential backoff: 1s, 2s, 4s print(f"Rate limited. Retrying in {wait_time}s...") time.sleep(wait_time) else: print("Rate limit exceeded after all retries") raise except BaytAPIError as e: if attempt < max_retries - 1: print(f"API error. Retry {attempt + 1}/{max_retries}...") time.sleep(1) else: print("Failed after all retries") raise# Usagetry: prompt = get_prompt_with_retry("@workspace/my-prompt:v1") print(f"Successfully loaded: {prompt.title}")except Exception as e: print(f"Failed to load prompt: {e}")
The SDK already includes automatic retry logic for rate limits. This example shows how to add additional retry logic for other scenarios.
Example 4: Graceful Degradation
Provide fallback behavior when prompts aren’t available:
import osfrom baytos.claro import BaytClient, BaytNotFoundError, BaytAPIErrordef get_prompt_or_fallback(package_name, fallback_content): """Get prompt or use fallback""" client = BaytClient(api_key=os.getenv("BAYT_API_KEY")) try: prompt = client.get_prompt(package_name) return prompt.generator except BaytNotFoundError: print(f"Prompt not found, using fallback") return fallback_content except BaytAPIError as e: print(f"API error, using fallback: {e}") return fallback_content# Usagefallback = "You are a helpful assistant."content = get_prompt_or_fallback("@workspace/assistant:v1", fallback)print(f"Using content: {content[:50]}...")
Example 5: Validate Prompt Before Use
Check that a prompt has the expected structure:
import osfrom baytos.claro import BaytClient, BaytNotFoundErrorclass PromptValidationError(Exception): """Raised when prompt doesn't meet requirements""" passdef get_validated_prompt(package_name): """Get and validate prompt""" client = BaytClient(api_key=os.getenv("BAYT_API_KEY")) try: prompt = client.get_prompt(package_name) # Validate prompt has content if not prompt.generator: raise PromptValidationError("Prompt has no generator content") # Validate minimum length if len(prompt.generator) < 10: raise PromptValidationError("Prompt content too short") return prompt except BaytNotFoundError: raise PromptValidationError(f"Prompt not found: {package_name}")# Usagetry: prompt = get_validated_prompt("@workspace/my-prompt:v1") print("Prompt is valid")except PromptValidationError as e: print(f"Validation failed: {e}") exit(1)
Example 6: Handle File Download Errors
Robust error handling for file downloads:
import osfrom baytos.claro import BaytClient, BaytNotFoundError, BaytAPIErrorclient = BaytClient(api_key=os.getenv("BAYT_API_KEY"))try: # Get prompt prompt = client.get_prompt("@workspace/prompt-with-files:v1") # Check for files if not prompt.has_context(): print("No files attached to this prompt") exit(0) files = prompt.get_file_contexts() # Download each file for file in files: try: print(f"Downloading {file.file_name}...") content = client.download_context_file(file.id) # Save file with open(file.file_name, 'wb') as f: f.write(content) print(f"✓ Downloaded successfully ({len(content):,} bytes)") except BaytNotFoundError: print(f"✗ File not found: {file.file_name}") except BaytAPIError as e: print(f"✗ Download failed: {e}") except IOError as e: print(f"✗ Could not save file: {e}")except BaytNotFoundError as e: print(f"Prompt not found: {e}")except Exception as e: print(f"Unexpected error: {e}")
import osfrom baytos.claro import BaytClient, BaytNotFoundError, BaytAuthError, BaytRateLimitErrordef get_user_friendly_error(error): """Convert exception to user-friendly message""" if isinstance(error, BaytAuthError): return ( "Authentication failed. Please check your API key.\n" "Get a new key from: https://claro.baytos.ai" ) if isinstance(error, BaytNotFoundError): return ( "The requested prompt could not be found.\n" "Please verify the package name and version." ) if isinstance(error, BaytRateLimitError): return ( "You've made too many requests. Please wait a moment.\n" "Rate limits help ensure fair usage for all users." ) return f"An unexpected error occurred: {error}"# Usageclient = BaytClient(api_key=os.getenv("BAYT_API_KEY"))try: prompt = client.get_prompt("@workspace/my-prompt:v1") print(f"Loaded: {prompt.title}")except Exception as e: print(get_user_friendly_error(e))
Example 9: Context Manager Pattern
Use context managers for resource cleanup:
import osfrom contextlib import contextmanagerfrom baytos.claro import BaytClient, BaytAPIError@contextmanagerdef prompt_context(package_name): """Context manager for prompt operations""" client = BaytClient(api_key=os.getenv("BAYT_API_KEY")) prompt = None try: prompt = client.get_prompt(package_name) yield prompt except BaytAPIError as e: print(f"Error loading prompt: {e}") raise finally: # Cleanup if needed if prompt: print(f"Finished with prompt: {prompt.title}")# Usagetry: with prompt_context("@workspace/my-prompt:v1") as prompt: print(f"Using prompt: {prompt.title}") # Do work with promptexcept Exception as e: print(f"Failed: {e}")