Spaces:
Running
Running
| const express = require('express'); | |
| const path = require('path'); | |
| const app = express(); | |
| const PORT = 7860; | |
| app.use(express.json({ limit: '10mb' })); | |
| app.use(express.static(path.join(__dirname, 'public'))); | |
| const MODEL_MAP = { | |
| 'kimi-k2': 'moonshotai/kimi-k2-instruct', | |
| 'glm-4': 'thudm/glm-4-9b-chat', | |
| 'minimax-m2':'minimax/minimax-m2', | |
| 'devstral': 'mistralai/devstral-small-2505', | |
| 'default': 'moonshotai/kimi-k2-instruct', | |
| }; | |
| function resolveModel(name) { | |
| if (!name) return MODEL_MAP['default']; | |
| const key = Object.keys(MODEL_MAP).find(k => name.toLowerCase().includes(k)); | |
| return key ? MODEL_MAP[key] : MODEL_MAP['default']; | |
| } | |
| app.get('/api/status', (_req, res) => { | |
| const key = process.env.NVIDIA_API_KEY || ''; | |
| res.json({ | |
| status: 'ok', | |
| nvidia_key_set: key.length > 10, | |
| models: Object.keys(MODEL_MAP).filter(k => k !== 'default'), | |
| }); | |
| }); | |
| app.post('/api/chat', async (req, res) => { | |
| const apiKey = process.env.NVIDIA_API_KEY; | |
| if (!apiKey || apiKey.length < 10) { | |
| return res.status(500).json({ error: 'NVIDIA_API_KEY manquante. Ajoute-la dans Settings > Secrets.' }); | |
| } | |
| const { messages = [], model = 'kimi-k2', max_tokens = 2048 } = req.body; | |
| const nvidiaModel = resolveModel(model); | |
| try { | |
| const response = await fetch('https://integrate.api.nvidia.com/v1/chat/completions', { | |
| method: 'POST', | |
| headers: { | |
| 'Content-Type': 'application/json', | |
| 'Authorization': `Bearer ${apiKey}`, | |
| }, | |
| body: JSON.stringify({ | |
| model: nvidiaModel, | |
| messages, | |
| max_tokens, | |
| temperature: 0.7, | |
| stream: false, | |
| }), | |
| }); | |
| if (!response.ok) { | |
| const err = await response.text(); | |
| return res.status(response.status).json({ error: `NVIDIA API ${response.status}: ${err}` }); | |
| } | |
| const data = await response.json(); | |
| const reply = data?.choices?.[0]?.message?.content || ''; | |
| res.json({ content: [{ type: 'text', text: reply }] }); | |
| } catch (err) { | |
| res.status(500).json({ error: err.message }); | |
| } | |
| }); | |
| app.listen(PORT, '0.0.0.0', () => { | |
| const key = process.env.NVIDIA_API_KEY || ''; | |
| console.log(`Server on port ${PORT}`); | |
| console.log(`NVIDIA key: ${key.length > 10 ? 'OK' : 'MISSING'}`); | |
| }); |