Vibe Coding 101

Essential coding tips and best practices for building with AI. Learn the vibe of good code through practical wisdom and proven patterns.

Pro Tips
Best Practices
Smart Patterns

Essential Coding Wisdom

Practical tips and proven patterns for building amazing AI applications

Code Organization
Keep your AI projects clean and maintainable
  • Separate API logic from UI
  • Use meaningful variable names
  • Comment your AI prompts
  • Keep functions small and focused
AI Integration Patterns
Smart ways to work with AI APIs and responses
  • Always handle API failures gracefully
  • Cache responses when appropriate
  • Set reasonable timeouts
  • Validate AI outputs before use
Security Best Practices
Keep your AI applications secure and private
  • Never hardcode API keys
  • Validate all user inputs
  • Use environment variables
  • Monitor API usage and costs
Performance & UX
Make your AI apps fast and user-friendly
  • Show loading states for AI requests
  • Implement request cancellation
  • Use streaming when possible
  • Provide fallback responses
Testing & Debugging
Ensure your AI code works reliably
  • Test with various input types
  • Log API requests and responses
  • Handle rate limits gracefully
  • Mock AI responses for testing

Quick Code Examples

Copy-paste patterns you can use right away

Secure API Key Management
Always protect your API keys
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
Robust Error Handling
Handle AI API calls gracefully
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"}
Input Validation
Validate user inputs before sending to AI
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)

⚑ Quick Wins

Simple changes that make a big difference

βœ… Do This

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"

❌ Avoid This

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?

🎯 Key Takeaways

Security First

  • β€’ Always use environment variables for API keys
  • β€’ Validate and sanitize all user inputs
  • β€’ Implement proper error handling
  • β€’ Never expose sensitive data in logs

User Experience

  • β€’ Provide clear feedback and loading states
  • β€’ Handle errors gracefully with helpful messages
  • β€’ Implement reasonable input limits
  • β€’ Test thoroughly before deployment

πŸš€ Ready to Build Something Amazing?

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.

πŸ’‘ Project Ideas to Try Next:

β€’ 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