File size: 4,763 Bytes
296e46a | 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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 | const express = require('express');
const cors = require('cors');
const app = express();
// Enable global CORS to let Janitor AI handshake effortlessly
app.use(cors());
app.use(express.json({ limit: '100mb' }));
app.use(express.urlencoded({ limit: '100mb', extended: true }));
// Target Endpoint for DaSong API
const DASONG_URL = 'https://api.ai1833.shop/v1/chat/completions';
// Map Janitor's incoming models to the specific New-API dashboard options
const MODEL_MAPPING = {
'gpt-4': 'deepseek-v4-pro',
'gpt-4o': 'glm-5.1',
'gpt-3.5-turbo': 'deepseek-v4-flash'
};
// Health check route
app.get('*', (req, res) => {
res.json({ status: "alive", message: "DaSong API Node.js Proxy Bridge Active on 5000." });
});
// Main Reverse Proxy Handler
app.post('*', async (req, res) => {
try {
const body = req.body;
if (!body || !body.messages) {
return res.json({ status: "alive", message: "Connection baseline stable." });
}
// Pull the sk- token from Hugging Face Environment Secrets
const apiKey = (process.env.DASONG_API_KEY || '').trim();
if (!apiKey) {
return res.status(500).json({ error: "Configuration Error: DASONG_API_KEY secret is missing in Space settings." });
}
const inboundModel = body.model || 'gpt-4';
const targetModel = MODEL_MAPPING[inboundModel] || 'deepseek-v4-pro';
// --- Context Sanitization Layer ---
let sanitizedMessages = [];
let combinedSystemContent = "";
for (let msg of body.messages || []) {
let role = msg.role;
if (['example_user', 'user'].includes(role)) role = 'user';
if (['example_assistant', 'assistant'].includes(role)) role = 'assistant';
let content = typeof msg.content === 'string' ? msg.content.trim() : '';
if (!content) continue;
if (role === 'system') {
combinedSystemContent += combinedSystemContent ? "\n" + content : content;
} else if (['user', 'assistant'].includes(role)) {
// Squash consecutive identical roles to prevent parsing validation rejections
if (sanitizedMessages.length > 0 && sanitizedMessages[sanitizedMessages.length - 1].role === role) {
sanitizedMessages[sanitizedMessages.length - 1].content += "\n" + content;
} else {
sanitizedMessages.push({ role, content });
}
}
}
if (combinedSystemContent) {
sanitizedMessages.unshift({ role: 'system', content: combinedSystemContent });
}
// Re-assemble standard format
const pristineBody = {
model: targetModel,
messages: sanitizedMessages,
stream: body.stream !== undefined ? body.stream : true
};
// Forward optional safety/generation variables
if (typeof body.temperature === 'number') pristineBody.temperature = body.temperature;
if (typeof body.top_p === 'number') pristineBody.top_p = body.top_p;
if (typeof body.max_tokens === 'number') pristineBody.max_tokens = body.max_tokens;
console.log(`[Proxy Log] Forwarding request to DaSong API for model: ${targetModel}`);
// Upstream execution
const response = await fetch(DASONG_URL, {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(pristineBody)
});
if (!response.ok) {
const errorText = await response.text();
console.error(`[Upstream Error] Status: {response.status} | Body: ${errorText.slice(0, 500)}`);
return res.status(response.status).send(`Upstream provider returned an error: ${response.status}`);
}
// Setup streaming response headers back to Janitor AI
res.setHeader('Content-Type', response.headers.get('content-type') || 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
// Stream the incoming chunks out natively
for await (const chunk of response.body) {
res.write(chunk);
}
res.end();
} catch (err) {
console.error(`[Network Exception]: ${err.message}`);
if (!res.headersSent) {
res.status(500).send(`Proxy network loop error: ${err.message}`);
}
}
});
// Force explicit port binding for Hugging Face's container system
const PORT = 5000;
app.listen(PORT, '0.0.0.0', () => {
console.log(`OG Node Proxy running smoothly on native port ${PORT}`);
}); |