File size: 2,913 Bytes
dcad9a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import axios from 'axios';

export default async function handler(req, res) {
  if (req.method !== 'POST') {
    return res.status(405).json({ error: 'Method not allowed' });
  }

  const { 
    messages, 
    spotifyContext, 
    apiKey, 
    provider, 
    model 
  } = req.body;

  if (!apiKey) {
    return res.status(401).json({ error: 'Missing API Key' });
  }

  // Construct system prompt with Spotify Data
  const systemPrompt = `
    You are an expert music recommendation AI with deep knowledge of all genres, eras, and artists.
    You have access to the user's Spotify data. Use this data to personalize your recommendations.
    
    User's Spotify Data:
    Profile: ${JSON.stringify(spotifyContext.profile)}
    Top Tracks: ${JSON.stringify(spotifyContext.topTracks?.map(t => ({name: t.name, artist: t.artists[0].name, album: t.album.name})))}
    Top Artists: ${JSON.stringify(spotifyContext.topArtists?.map(a => a.name))}
    
    Instructions:
    1. Analyze the user's taste based on their top tracks and artists.
    2. Provide specific song or artist recommendations that align with their taste but also introduce variety.
    3. If asked for insights, analyze their listening patterns (genres, energy, era).
    4. Be conversational, helpful, and concise.
    5. If you recommend a song, format it like this: **Song Name** by Artist.
    6. Do NOT recommend songs that are already in their "Top Tracks" list unless they ask for similar ones.
  `;

  try {
    let apiUrl = '';
    let headers = {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${apiKey}`
    };
    let body = {};

    if (provider === 'openai' || provider === 'custom') {
      apiUrl = provider === 'openai' 
        ? 'https://api.openai.com/v1/chat/completions'
        : model; // Assuming model field holds the endpoint for custom
      
      body = {
        model: provider === 'custom' ? 'model-name-placeholder' : model,
        messages: [
          { role: 'system', content: systemPrompt },
          ...messages
        ],
        temperature: 0.7,
      };
    } else if (provider === 'anthropic') {
      apiUrl = 'https://api.anthropic.com/v1/messages';
      headers['anthropic-version'] = '2023-06-01';
      body = {
        model: model,
        max_tokens: 1024,
        system: systemPrompt,
        messages: messages
      };
    }

    const response = await axios.post(apiUrl, body, { headers });

    let content = '';
    if (provider === 'anthropic') {
      content = response.data.content[0].text;
    } else {
      content = response.data.choices[0].message.content;
    }

    res.status(200).json({ content });

  } catch (error) {
    console.error('AI API Error:', error.response?.data || error.message);
    res.status(500).json({ 
      error: 'Failed to get AI response',
      details: error.response?.data?.error?.message || error.message 
    });
  }
}