Essential coding tips and best practices for building with AI. Learn the vibe of good code through practical wisdom and proven patterns.
Practical tips and proven patterns for building amazing AI applications
Copy-paste patterns you can use right away
import os from dotenv import load_dotenv # Load environment variables load_dotenv() # Safe way to get API key api_key = os.getenv('OPENAI_API_KEY') if not api_key: raise ValueError("OPENAI_API_KEY not found in environment variables") # Never do this! # api_key = "sk-your-key-here" # β BAD
import requests import time def call_ai_api(prompt, max_retries=3): for attempt in range(max_retries): try: response = requests.post( "https://api.openai.com/v1/chat/completions", headers={"Authorization": f"Bearer {api_key}"}, json={ "model": "gpt-3.5-turbo", "messages": [{"role": "user", "content": prompt}], "max_tokens": 150 }, timeout=30 # Always set timeouts! ) response.raise_for_status() return response.json() except requests.exceptions.Timeout: print(f"Request timed out (attempt {attempt + 1})") except requests.exceptions.RequestException as e: print(f"Request failed: {e} (attempt {attempt + 1})") if attempt < max_retries - 1: time.sleep(2 ** attempt) # Exponential backoff return {"error": "Max retries exceeded"}
def validate_user_input(text): """Validate user input before sending to AI""" # Check if input exists if not text or not text.strip(): return False, "Input cannot be empty" # Check length limits if len(text) > 4000: return False, "Input too long (max 4000 characters)" # Basic content filtering prohibited_words = ['password', 'secret', 'private_key'] if any(word in text.lower() for word in prohibited_words): return False, "Input contains prohibited content" # Check for injection attempts if '<script>' in text.lower() or 'javascript:' in text.lower(): return False, "Input contains invalid content" return True, "Valid input" # Usage is_valid, message = validate_user_input(user_prompt) if not is_valid: print(f"Invalid input: {message}") else: # Safe to send to AI result = call_ai_api(user_prompt)
Simple changes that make a big difference
Use descriptive variable names
user_prompt = "Write a blog post about..."
ai_response = call_openai_api(user_prompt)
Add loading states
st.write("π€ AI is thinking...")
response = get_ai_response(prompt)
st.write(response)
Set reasonable limits
if len(prompt) > 1000:
Β Β return "Prompt too long, please shorten"
Hardcoded API keys
api_key = "sk-proj-abc123..." # β Never!
openai.api_key = api_key
No error handling
response = requests.post(url, data) # β What if it fails?
return response.json()['choices'][0]['message']
Unclear variable names
x = input() # β What is x?
result = api(x) # β Which API?
You now have the essential patterns and practices to build responsible AI applications. Remember: start simple, prioritize security, and always keep the human element central to your designs.
β’ Build a personal knowledge base with Q&A
β’ Create a content generator for your business
β’ Develop a code review assistant
β’ Make a language learning conversation partner