sitcod3 commited on
Commit
be36309
·
verified ·
1 Parent(s): 1d8f73e

Upload src/lib/aiService.ts with huggingface_hub

Browse files
Files changed (1) hide show
  1. src/lib/aiService.ts +45 -0
src/lib/aiService.ts ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import axios from 'axios';
2
+
3
+ const OPENROUTER_API_URL = 'https://openrouter.ai/api/v1/chat/completions';
4
+
5
+ const TARGET_MODELS = [
6
+ 'mistralai/mistral-small',
7
+ 'mistralai/mistral-medium',
8
+ 'mistralai/mistral-nemo' // fallback free-tier compatible model
9
+ ];
10
+
11
+ let currentModelIndex = 0;
12
+
13
+ export async function getAiCompletion(prompt: string) {
14
+ let attempts = 0;
15
+
16
+ while (attempts < TARGET_MODELS.length) {
17
+ const model = TARGET_MODELS[currentModelIndex];
18
+ try {
19
+ const response = await axios.post(
20
+ OPENROUTER_API_URL,
21
+ {
22
+ model: model,
23
+ messages: [{ role: 'user', content: prompt }],
24
+ },
25
+ {
26
+ headers: {
27
+ 'Authorization': `Bearer ${process.env.OPENROUTER_API_KEY}`,
28
+ 'HTTP-Referer': process.env.APP_URL || 'http://localhost:3000',
29
+ 'X-Title': 'BRIDGEModulE Dashboard',
30
+ },
31
+ }
32
+ );
33
+
34
+ // If successful, we keep this model as the active one for next time
35
+ return response.data.choices[0].message.content;
36
+ } catch (error: any) {
37
+ console.error(`Error with model ${model}:`, error?.response?.data || error.message);
38
+ attempts++;
39
+ // Rotate to the next model for the next attempt
40
+ currentModelIndex = (currentModelIndex + 1) % TARGET_MODELS.length;
41
+ }
42
+ }
43
+
44
+ throw new Error('All OpenRouter Mistral models failed. Please check your API key and quotas.');
45
+ }