from baytos.claro import BaytClientdef fetch_prompts_efficiently(package_names, batch_size=10): """Fetch prompts in batches with progress tracking""" client = BaytClient(api_key="...") prompts = [] for i in range(0, len(package_names), batch_size): batch = package_names[i:i + batch_size] print(f"Fetching batch {i//batch_size + 1}...") for name in batch: try: prompt = client.get_prompt(name) prompts.append(prompt) except Exception as e: print(f"Failed to fetch {name}: {e}") return prompts# Usagepackages = ["@workspace/p1:v1", "@workspace/p2:v1", ...]prompts = fetch_prompts_efficiently(packages)
Minimize Data Transfer
Only fetch what you need:
# ✅ Good: Fetch specific promptprompt = client.get_prompt("@workspace/support:v1")content = prompt.generator# ❌ Wasteful: List all, then filterresult = client.list_prompts(limit=100)prompt = [p for p in result['prompts'] if p.title == "Support"][0]
Lazy Loading
Load context files only when needed:
from baytos.claro import BaytClientclient = BaytClient(api_key="...")prompt = client.get_prompt("@workspace/research:v1")# ✅ Good: Check before downloadingif prompt.has_context(): files = prompt.get_file_contexts() # Only download if needed if any(f.mime_type == 'application/pdf' for f in files): for file in files: if file.mime_type == 'application/pdf': content = client.download_context_file(file.id) # Process PDF...
Production Best Practices
Environment-Based Configuration
Configure differently per environment:
import osfrom baytos.claro import BaytClientdef create_client(): """Create client with environment-specific config""" env = os.getenv("ENVIRONMENT", "production") if env == "development": return BaytClient( api_key=os.getenv("BAYT_API_KEY"), base_url="http://localhost:8000", max_retries=0 # Fast-fail in dev ) elif env == "staging": return BaytClient( api_key=os.getenv("BAYT_API_KEY"), base_url="https://staging-api.baytos.ai", max_retries=2 ) else: # production return BaytClient( api_key=os.getenv("BAYT_API_KEY"), max_retries=3 )client = create_client()
Health Checks
Implement health checks for monitoring:
from baytos.claro import BaytClient, BaytAPIErrordef health_check(): """Check if API is accessible""" try: client = BaytClient(api_key="...") # Try to list prompts (lightweight operation) result = client.list_prompts(limit=1) return { 'status': 'healthy', 'api_accessible': True } except BaytAPIError as e: return { 'status': 'unhealthy', 'api_accessible': False, 'error': str(e) }# Usage in health endpoint# GET /healthstatus = health_check()
import timefrom baytos.claro import BaytClient, BaytAPIErrorclass CircuitBreaker: def __init__(self, failure_threshold=5, timeout=60): self.failure_threshold = failure_threshold self.timeout = timeout self.failures = 0 self.last_failure_time = None self.state = 'closed' # closed, open, half-open def call(self, func, *args, **kwargs): """Execute function with circuit breaker""" # Check if circuit is open if self.state == 'open': if time.time() - self.last_failure_time > self.timeout: self.state = 'half-open' else: raise Exception("Circuit breaker is open") try: result = func(*args, **kwargs) # Success - reset on half-open if self.state == 'half-open': self.failures = 0 self.state = 'closed' return result except BaytAPIError as e: self.failures += 1 self.last_failure_time = time.time() # Open circuit if threshold reached if self.failures >= self.failure_threshold: self.state = 'open' raise# Usageclient = BaytClient(api_key="...")breaker = CircuitBreaker(failure_threshold=5, timeout=60)def fetch_with_breaker(package_name): return breaker.call(client.get_prompt, package_name)try: prompt = fetch_with_breaker("@workspace/test:v1")except Exception as e: print(f"Circuit breaker prevented call: {e}")
Best Practices Summary
Use Connection Pooling
Reuse client instances to benefit from connection pooling:
# ✅ Good: Singleton pattern_client = Nonedef get_client(): global _client if _client is None: _client = BaytClient(api_key="...") return _client
Implement Caching
Cache prompts to reduce API calls:
# Use version pinning with caching@lru_cache(maxsize=100)def get_cached_prompt(package_name: str): return client.get_prompt(package_name)# Always use specific versions when cachingprompt = get_cached_prompt("@workspace/support:v1") # ✅prompt = get_cached_prompt("@workspace/support:latest") # ❌