Spaces:
Running
Running
Download server.js from Norsec93/nvidia-janitor-proxy: direct link, hf CLI and curl.
- Browser
- Download file 6.02 kB
-
https://huggingface.co/spaces/Norsec93/nvidia-janitor-proxy/resolve/main/server.js
- Command line
-
hf download hf://spaces/Norsec93/nvidia-janitor-proxy/server.js
-
curl -L -o server.js https://huggingface.co/spaces/Norsec93/nvidia-janitor-proxy/resolve/main/server.js
6.02 kB
| const express = require('express'); | |
| const cors = require('cors'); | |
| const axios = require('axios'); | |
| const app = express(); | |
| const PORT = process.env.PORT || 7860; | |
| const NIM_API_BASE = 'https://integrate.api.nvidia.com/v1'; | |
| app.use(cors()); | |
| app.use(express.json({ limit: '50mb' })); | |
| function estimateTokens(text) { | |
| return Math.ceil((text || '').length / 4); | |
| } | |
| function truncateMessages(messages, maxTokens = 128000) { | |
| if (!Array.isArray(messages)) return []; | |
| const systemMsgs = messages.filter((m) => m.role === 'system'); | |
| const convoMsgs = messages.filter((m) => m.role !== 'system'); | |
| const count = (arr) => | |
| arr.reduce((sum, m) => sum + estimateTokens(m.content) + estimateTokens(m.role) + 4, 0); | |
| let total = count(systemMsgs) + count(convoMsgs); | |
| if (total <= maxTokens) return messages; | |
| const trimmedConvo = [...convoMsgs]; | |
| while (total > maxTokens && trimmedConvo.length > 6) { | |
| const dropped = trimmedConvo.shift(); | |
| total -= estimateTokens(dropped.content) + estimateTokens(dropped.role) + 4; | |
| } | |
| return [...systemMsgs, ...trimmedConvo]; | |
| } | |
| app.get('/', (req, res) => { | |
| res.send('NVIDIA NIM Proxy on Hugging Face is running!'); | |
| }); | |
| app.get('/health', (req, res) => { | |
| res.json({ status: 'ok' }); | |
| }); | |
| app.post(['/', '/v1', '/chat/completions', '/v1/chat/completions'], async (req, res) => { | |
| try { | |
| // 1. Grab API key passed directly from Janitor AI | |
| const authHeader = req.headers.authorization || `Bearer ${process.env.NVIDIA_API_KEY || ''}`; | |
| const { | |
| model, | |
| messages, | |
| temperature, | |
| max_tokens, | |
| top_p, | |
| top_k, | |
| frequency_penalty, | |
| presence_penalty, | |
| repetition_penalty, | |
| stop, | |
| seed, | |
| stream = true, | |
| max_context_tokens | |
| } = req.body; | |
| // 2. Direct model string pass-through from Janitor AI | |
| const modelName = model || 'z-ai/glm-5.2'; | |
| const trimmedMessages = truncateMessages(messages, max_context_tokens || 128000); | |
| // 3. Build payload with Full Power Thinking Mode forced | |
| const nimRequest = { | |
| model: modelName, | |
| messages: trimmedMessages, | |
| stream: stream, | |
| chat_template_kwargs: { thinking: true } | |
| }; | |
| // 4. Pass parameters straight from Janitor AI settings | |
| if (temperature !== undefined) nimRequest.temperature = temperature; | |
| if (max_tokens !== undefined) nimRequest.max_tokens = max_tokens; | |
| if (top_p !== undefined) nimRequest.top_p = top_p; | |
| if (top_k !== undefined) nimRequest.top_k = top_k; | |
| if (frequency_penalty !== undefined) nimRequest.frequency_penalty = frequency_penalty; | |
| if (presence_penalty !== undefined) nimRequest.presence_penalty = presence_penalty; | |
| if (repetition_penalty !== undefined) nimRequest.repetition_penalty = repetition_penalty; | |
| if (stop !== undefined) nimRequest.stop = stop; | |
| if (seed !== undefined) nimRequest.seed = seed; | |
| if (!stream) { | |
| const nimRes = await axios.post(`${NIM_API_BASE}/chat/completions`, nimRequest, { | |
| headers: { Authorization: authHeader, 'Content-Type': 'application/json' }, | |
| timeout: 300000, | |
| }); | |
| return res.json(nimRes.data); | |
| } | |
| // 5. Persistent Stream Relay (No 100s serverless timeout cutoff) | |
| const nimRes = await axios.post(`${NIM_API_BASE}/chat/completions`, nimRequest, { | |
| headers: { Authorization: authHeader, 'Content-Type': 'application/json' }, | |
| responseType: 'stream', | |
| timeout: 300000, | |
| }); | |
| res.setHeader('Content-Type', 'text/event-stream'); | |
| res.setHeader('Cache-Control', 'no-cache'); | |
| res.setHeader('Connection', 'keep-alive'); | |
| res.setHeader('Access-Control-Allow-Origin', '*'); | |
| let buffer = ''; | |
| let thinkingStarted = false; | |
| let thinkingEnded = false; | |
| nimRes.data.on('data', (chunk) => { | |
| buffer += chunk.toString(); | |
| const lines = buffer.split('\n'); | |
| buffer = lines.pop() || ''; | |
| for (const line of lines) { | |
| if (!line.startsWith('data: ')) continue; | |
| if (line.includes('[DONE]')) { | |
| if (thinkingStarted && !thinkingEnded) { | |
| const closeTag = { choices: [{ delta: { content: '\n</think>\n\n' } }] }; | |
| res.write(`data: ${JSON.stringify(closeTag)}\n\n`); | |
| } | |
| res.write(line + '\n\n'); | |
| continue; | |
| } | |
| try { | |
| const data = JSON.parse(line.slice(6)); | |
| const delta = data.choices?.[0]?.delta; | |
| if (delta) { | |
| const reasoning = delta.reasoning_content || ''; | |
| const content = delta.content || ''; | |
| let outputContent = ''; | |
| if (reasoning) { | |
| if (!thinkingStarted) { | |
| outputContent += '<think>\n'; | |
| thinkingStarted = true; | |
| } | |
| outputContent += reasoning; | |
| } | |
| if (content) { | |
| if (thinkingStarted && !thinkingEnded) { | |
| outputContent += '\n</think>\n\n'; | |
| thinkingEnded = true; | |
| } | |
| outputContent += content; | |
| } | |
| data.choices[0].delta = { content: outputContent }; | |
| delete data.choices[0].delta.reasoning_content; | |
| res.write(`data: ${JSON.stringify(data)}\n\n`); | |
| } else { | |
| res.write(`data: ${JSON.stringify(data)}\n\n`); | |
| } | |
| } catch { | |
| res.write(line + '\n'); | |
| } | |
| } | |
| }); | |
| nimRes.data.on('end', () => res.end()); | |
| nimRes.data.on('error', (err) => { | |
| console.error('Upstream stream error:', err.message); | |
| res.end(); | |
| }); | |
| } catch (error) { | |
| console.error('Proxy error:', error.message); | |
| const status = error.response?.status || 500; | |
| const message = error.response?.data?.error?.message || error.message || 'Internal server error'; | |
| if (!res.headersSent) { | |
| res.status(status).json({ error: { message, type: 'proxy_error', code: status } }); | |
| } | |
| } | |
| }); | |
| app.listen(PORT, '0.0.0.0', () => { | |
| console.log(`NVIDIA Proxy listening on port ${PORT}`); | |
| }); |