const express = require('express'); const axios = require('axios'); const cors = require('cors'); const http = require('http'); const https = require('https'); const app = express(); const PORT = process.env.PORT || 3000; // ── TARGET ────────────────────────────────────────────────────────────── const TARGET_URL = 'https://api.us-west-2.modal.direct/v1/chat/completions'; const MODEL_MAPPING = { 'gpt-4': 'zai-org/GLM-5.1-FP8', 'gpt-4o': 'zai-org/GLM-5.1-FP8', 'gpt-3.5-turbo': 'zai-org/GLM-5.1-FP8', 'claude-3-opus': 'zai-org/GLM-5.1-FP8', 'claude-3.5-sonnet': 'zai-org/GLM-5.1-FP8', 'claude-3.7-sonnet': 'zai-org/GLM-5.1-FP8', 'glm-5': 'zai-org/GLM-5.1-FP8', 'zai-org/GLM-5.1': 'zai-org/GLM-5.1-FP8', 'zai-org/GLM-5.1-FP8': 'zai-org/GLM-5.1-FP8' }; // ── RETRY CONFIG ───────────────────────────────────────────────────────── const RETRY = { maxRetries: 4, // 4 retries = 5 total attempts baseDelayMs: 1500, // Start at 1.5s maxDelayMs: 30000, // Cap at 30s retryableStatus: [429, 502, 503, 504] }; // ── HTTP AGENTS (Keep-Alive) ───────────────────────────────────────────── // Reuses TCP connections to Modal — massive latency win on HF Spaces const agentOpts = { keepAlive: true, keepAliveMsecs: 60000, maxSockets: 16, maxFreeSockets: 8, timeout: 120000, freeSocketTimeout: 30000 }; const httpAgent = new http.Agent(agentOpts); const httpsAgent = new https.Agent(agentOpts); const axiosInstance = axios.create({ httpAgent, httpsAgent, timeout: 300000, // 5 min total timeout headers: { 'Accept-Encoding': 'gzip, deflate', 'Connection': 'keep-alive' } }); // ── MIDDLEWARE ─────────────────────────────────────────────────────────── app.use(cors()); app.use(express.json({ limit: '50mb' })); app.use(express.urlencoded({ limit: '50mb', extended: true })); // ── HELPERS ────────────────────────────────────────────────────────────── const sleep = (ms) => new Promise(r => setTimeout(r, ms)); function getRetryDelay(attempt, headers = {}) { // Honor Modal's Retry-After header exactly const retryAfter = headers['retry-after']; if (retryAfter) { const sec = parseInt(retryAfter, 10); if (!isNaN(sec)) return (sec * 1000) + (Math.random() * 500); } // Exponential backoff with 25% jitter let delay = RETRY.baseDelayMs * Math.pow(2, attempt); delay = Math.min(delay, RETRY.maxDelayMs); delay += Math.random() * (delay * 0.25); return delay; } // ── MAIN ROUTE ─────────────────────────────────────────────────────────── app.post('/v1/chat/completions', async (req, res) => { if (!req.body || !Array.isArray(req.body.messages)) { return res.status(400).json({ error: { message: 'Invalid request: messages array required', code: 400 } }); } const requestedModel = req.body.model; const targetModel = MODEL_MAPPING[requestedModel] || 'zai-org/GLM-5.1-FP8'; // ── BUILD BODY ─────────────────────────────────────────────────────── // We take EVERYTHING from Janitor (temp, max_tokens, top_p, penalties, etc.) // and ONLY override model + thinking power. const body = { ...req.body, // Janitor's settings pass through untouched model: targetModel, // Force the GLM model // MAX POWER THINKING — locked on, cannot be disabled by Janitor thinking: { type: 'enabled' }, reasoning_effort: 'high', include_reasoning: true // Ensures reasoning_content flows to Janitor's box }; const isStream = !!body.stream; const authHeader = req.headers['authorization'] || `Bearer ${process.env.MODAL_API_KEY || ''}`; // ── RETRY LOOP ───────────────────────────────────────────────────────── let lastError = null; for (let attempt = 0; attempt <= RETRY.maxRetries; attempt++) { try { const response = await axiosInstance({ method: 'post', url: TARGET_URL, data: body, headers: { 'Content-Type': 'application/json', 'Authorization': authHeader }, responseType: isStream ? 'stream' : 'json' }); // ── STREAM PATH ──────────────────────────────────────────────── if (isStream) { res.setHeader('Content-Type', response.headers['content-type'] || 'text/event-stream'); res.setHeader('Cache-Control', 'no-cache'); res.setHeader('X-Accel-Buffering', 'no'); // Stop nginx/HF proxy from buffering SSE let clientClosed = false; req.on('close', () => { clientClosed = true; }); response.data.on('data', (chunk) => { if (clientClosed) return; res.write(chunk); }); await new Promise((resolve, reject) => { response.data.on('end', () => { if (!res.writableEnded) res.end(); resolve(); }); response.data.on('error', (err) => { console.error(`[Stream Error] ${err.message}`); reject(err); }); }); return; // Stream completed successfully } // ── NON-STREAM PATH ────────────────────────────────────────── return res.json(response.data); } catch (error) { lastError = error; const status = error.response?.status; const headers = error.response?.headers || {}; // If client disconnected, die quietly if (req.destroyed || req.aborted) { console.log('[Proxy] Client disconnected, aborting retries.'); return; } // Don't retry non-retryable errors if (!RETRY.retryableStatus.includes(status)) { break; } if (attempt < RETRY.maxRetries) { const delay = getRetryDelay(attempt, headers); console.warn( `[Retry ${attempt + 1}/${RETRY.maxRetries}] ` + `Upstream ${status} — backing off ${Math.round(delay)}ms` ); await sleep(delay); } } } // ── ALL RETRIES FAILED ─────────────────────────────────────────────── const statusCode = lastError?.response?.status || 500; const errMsg = lastError?.response?.data?.error?.message || lastError?.message || 'Unknown upstream error'; console.error(`[Proxy Fatal] ${statusCode}: ${errMsg}`); if (!res.headersSent) { return res.status(statusCode).json({ error: { message: `Upstream error (${statusCode}): ${errMsg}`, type: 'proxy_upstream_error', code: statusCode } }); } res.end(); }); // ── HEALTH CHECK (HF Spaces / Uptime) ────────────────────────────────── app.get('/health', (req, res) => { res.json({ status: 'ok', model: 'zai-org/GLM-5.1-FP8', thinking: 'max', timestamp: new Date().toISOString() }); }); app.all('*', (req, res) => { res.status(404).json({ error: { message: `Endpoint ${req.path} not found`, code: 404 } }); }); // ── START ──────────────────────────────────────────────────────────────── const server = app.listen(PORT, () => { console.log(`[GLM 5.1 Max Power Proxy] Port ${PORT}`); console.log(`[Config] Keep-Alive: ON | Retries: ${RETRY.maxRetries} | Thinking: MAX`); }); process.on('SIGTERM', () => { console.log('[Shutdown] SIGTERM received, closing...'); server.close(() => process.exit(0)); });