Best Practices
Learn how to write effective prompts, handle files efficiently, monitor progress, and implement robust error handling.
1. Write Clear Prompts
The quality of your prompt directly affects the output. Be specific and detailed.
Good:
"Create a React Native mobile app for tracking daily water intake"Better:
"Build a React Native water tracking app with:- Daily water intake logging- Progress visualization with charts- Local storage for offline use- Push notifications for reminders- Material Design UI- iOS and Android support"2. Handle Files Efficiently
Save generated files to disk with proper error handling:
import base64import os def save_files(results): """Save generated files to disk""" os.makedirs("generated_files", exist_ok=True) for file_info in results.get('files', []): filename = file_info['file_name'] filepath = f"generated_files/{filename}" if file_info['included_inline']: # File content is included if file_info['encoding'] == 'utf-8': # Text file with open(filepath, 'w', encoding='utf-8') as f: f.write(file_info['content']) else: # Binary file (base64) with open(filepath, 'wb') as f: f.write(base64.b64decode(file_info['content'])) else: # Download from URL import requests response = requests.get(file_info['download_url']) with open(filepath, 'wb') as f: f.write(response.content) print(f"✅ Saved: {filename}")3. Monitor Progress
Implement polling with progress updates to track task completion:
def wait_for_completion(thread_id, project_id, max_minutes=10): """Wait for task completion with progress updates""" import time start_time = time.time() max_seconds = max_minutes * 60 while time.time() - start_time < max_seconds: results = get_results(thread_id, project_id, timeout=30) if results['status'] == 'completed': print("✅ Task completed!") return results elif results['status'] == 'failed': print("❌ Task failed!") return results elif results['status'] == 'running': elapsed = int(time.time() - start_time) print(f"⏳ Still working... ({elapsed}s)") time.sleep(10) print("⏰ Timeout reached") return results4. Implement Retry Logic
Add automatic retry for transient failures with exponential backoff:
def robust_request(prompt, max_retries=3): """Create task with automatic retry""" for attempt in range(max_retries): try: task = create_task(prompt) results = wait_for_completion( task['thread_id'], task['project_id'] ) if results['status'] == 'completed': return results elif attempt < max_retries - 1: print(f"Attempt {attempt + 1} failed, retrying...") time.sleep(5 * (attempt + 1)) except Exception as e: if attempt < max_retries - 1: print(f"Error: {e}. Retrying...") time.sleep(2 ** attempt) else: raise e5. Use Streaming for Real-Time Updates
Enable real-time streaming to get live updates as the AI works:
import requestsimport json def stream_response(thread_id, project_id): """Stream real-time updates""" url = f"https://api.he2.ai/api/v1/public/threads/{thread_id}/response" params = { "project_id": project_id, "realtime": "true", "timeout": 300 } headers = {"X-API-Key": "he-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"} response = requests.get(url, params=params, headers=headers, stream=True) for line in response.iter_lines(): if line: line = line.decode('utf-8') if line.startswith('data: '): data = json.loads(line[6:]) print(f"Event: {data.get('type')}") if data.get('type') == 'content': print(f"Content: {data.get('content')}") elif data.get('type') == 'status': print(f"Status: {data.get('status')}")6. Error Handling
Always handle errors gracefully:
- Check HTTP status codes before processing responses
- Handle rate limit errors (429) with exponential backoff
- Validate API key format before making requests
- Log errors with context for debugging
- Provide user-friendly error messages
7. Security Considerations
- Never commit API keys to version control
- Use environment variables for sensitive data
- Rotate API keys regularly
- Validate and sanitize user inputs
- Implement rate limiting on your side