File size: 9,397 Bytes
567f406
 
ac8f3b3
a8721bb
6596b9c
567f406
 
a8721bb
567f406
a8721bb
ac8f3b3
567f406
 
ac8f3b3
 
 
 
a8721bb
 
ac8f3b3
a8721bb
 
567f406
 
a8721bb
 
 
 
 
 
 
d80ab0d
a8721bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6596b9c
d80ab0d
a8721bb
6596b9c
a8721bb
6596b9c
 
a8721bb
 
 
 
 
 
 
 
 
 
 
 
 
6596b9c
 
a8721bb
ac8f3b3
a8721bb
 
 
 
6596b9c
 
a8721bb
 
 
 
 
 
 
 
 
 
 
 
 
 
6596b9c
 
a8721bb
 
6596b9c
a8721bb
 
6596b9c
a8721bb
6596b9c
a8721bb
6596b9c
 
a8721bb
6596b9c
 
a8721bb
6596b9c
a8721bb
6596b9c
 
a8721bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6596b9c
 
a8721bb
 
 
 
 
 
 
 
 
 
 
 
567f406
6596b9c
567f406
a8721bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
567f406
 
 
ac8f3b3
567f406
 
a8721bb
 
 
 
 
 
 
 
 
567f406
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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
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));
});