File size: 1,464 Bytes
16cf865
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import axios from 'axios';

const OPENROUTER_API_URL = 'https://openrouter.ai/api/v1/chat/completions';

const TARGET_MODELS = [
  'mistralai/mistral-small',
  'mistralai/mistral-medium',
  'mistralai/mistral-nemo' // fallback free-tier compatible model
];

let currentModelIndex = 0;

export async function getAiCompletion(prompt: string) {
  let attempts = 0;
  
  while (attempts < TARGET_MODELS.length) {
    const model = TARGET_MODELS[currentModelIndex];
    try {
      const response = await axios.post(
        OPENROUTER_API_URL,
        {
          model: model,
          messages: [{ role: 'user', content: prompt }],
        },
        {
          headers: {
            'Authorization': `Bearer ${process.env.OPENROUTER_API_KEY}`,
            'HTTP-Referer': process.env.APP_URL || 'http://localhost:3000',
            'X-Title': 'BRIDGE ModulS Dashboard',
          },
        }
      );
      
      // If successful, we keep this model as the active one for next time
      return response.data.choices[0].message.content;
    } catch (error: any) {
      console.error(`Error with model ${model}:`, error?.response?.data || error.message);
      attempts++;
      // Rotate to the next model for the next attempt
      currentModelIndex = (currentModelIndex + 1) % TARGET_MODELS.length;
    }
  }
  
  throw new Error('All OpenRouter Mistral models failed. Please check your API key and quotas.');
}