AI Integration Guide

Integration Approaches

There are two main approaches to integrating AI services in your Bolt.new application:

Using edge functions or backend services provides better security and control:

// Supabase Edge Function example
export async function aiCompletion(req: Request) {
  const apiKey = Deno.env.get('OPENAI_API_KEY');
  
  try {
    const response = await fetch('https://api.openai.com/v1/chat/completions', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${apiKey}`
      },
      body: JSON.stringify({
        model: 'gpt-4',
        messages: req.body.messages
      })
    });
    
    return new Response(JSON.stringify(await response.json()));
  } catch (error) {
    return new Response(JSON.stringify({ error: error.message }), { status: 500 });
  }
}

2. Client-Side Integration

While some AI services support client-side API calls, this approach exposes your API keys and should be used cautiously:

// Only use for services that explicitly support client-side calls
// and provide appropriate security measures
const response = await fetch('https://api.secure-ai-service.com/v1/generate', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ prompt: 'Hello' })
});

Best Practices

  1. Rate Limiting

    • Implement proper throttling
    • Cache responses when possible
    • Handle API limits gracefully
  2. Error Handling

    • Implement fallback options
    • Validate AI responses
    • Handle timeouts appropriately
    • Implement retry logic for failed requests
  3. Security

    • Never expose API keys in client-side code
    • Use environment variables for sensitive data
    • Implement proper authentication
    • Rate limit user requests