Download src/lib/aiService.ts from sitcod3/modul-s: direct link, hf CLI and curl.
- Browser
- Download file 1.46 kB
-
https://huggingface.co/spaces/sitcod3/modul-s/resolve/main/src/lib/aiService.ts
- Command line
-
hf download hf://spaces/sitcod3/modul-s/src/lib/aiService.ts
-
curl -L -o aiService.ts https://huggingface.co/spaces/sitcod3/modul-s/resolve/main/src/lib/aiService.ts
1.46 kB
| 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.'); | |
| } | |