Norsec93 commited on
Commit
70226ad
·
verified ·
1 Parent(s): f997a7e

Rename server.js to main.py

Browse files
Files changed (2) hide show
  1. main.py +238 -0
  2. server.js +0 -125
main.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import math
4
+ import re
5
+ from typing import List, Dict, Any
6
+ from fastapi import FastAPI, Request
7
+ from fastapi.middleware.cors import CORSMiddleware
8
+ from fastapi.responses import StreamingResponse
9
+ import httpx
10
+
11
+ app = FastAPI()
12
+
13
+ app.add_middleware(
14
+ CORSMiddleware,
15
+ allow_origins=["*"],
16
+ allow_methods=["*"],
17
+ allow_headers=["*"],
18
+ )
19
+
20
+ NVIDIA_URL = "https://integrate.api.nvidia.com/v1/chat/completions"
21
+
22
+ def estimate_tokens(text: str) -> int:
23
+ return math.ceil(len(text or "") / 3.2)
24
+
25
+ def count_tokens(messages: List[Dict]) -> int:
26
+ total = 0
27
+ for m in messages:
28
+ content = m.get("content", "") if isinstance(m.get("content"), str) else json.dumps(m.get("content"))
29
+ total += estimate_tokens(content) + estimate_tokens(m.get("role", "")) + 4
30
+ return total
31
+
32
+ def truncate_messages(messages: List[Dict], max_tokens: int = 120000) -> List[Dict]:
33
+ if not messages:
34
+ return []
35
+ system_msgs = [m for m in messages if m.get("role") == "system"]
36
+ convo_msgs = [m for m in messages if m.get("role") != "system"]
37
+
38
+ total = count_tokens(system_msgs) + count_tokens(convo_msgs)
39
+ if total <= max_tokens:
40
+ return messages
41
+
42
+ trimmed = list(convo_msgs)
43
+ while total > max_tokens and len(trimmed) > 1:
44
+ dropped = trimmed.pop(0)
45
+ total -= estimate_tokens(dropped.get("content", "")) + estimate_tokens(dropped.get("role", "")) + 4
46
+
47
+ if total > max_tokens and system_msgs:
48
+ kept = [system_msgs[-1]]
49
+ convo_tok = count_tokens(trimmed)
50
+ reserved = estimate_tokens(kept[0].get("role", "")) + 4
51
+ allowed = max(500, max_tokens - convo_tok - reserved)
52
+ if allowed > 500:
53
+ content = kept[0].get("content", "")
54
+ slice_len = math.floor(allowed * 3.2)
55
+ kept[0]["content"] = content[:slice_len] + "\n\n...[System prompt truncated to fit context window]"
56
+ return kept + trimmed
57
+
58
+ return system_msgs + trimmed
59
+
60
+ def extract_names(body: Dict) -> tuple:
61
+ user_name = body.get("user_name") or body.get("userName")
62
+ char_name = body.get("character_name") or body.get("characterName")
63
+
64
+ if not user_name or not char_name:
65
+ first_sys = next((m for m in body.get("messages", []) if m.get("role") == "system" and isinstance(m.get("content"), str)), None)
66
+ if first_sys:
67
+ content = first_sys["content"]
68
+ if not char_name:
69
+ match = re.search(r"You are\s+([^\n,.]+)", content, re.IGNORECASE)
70
+ if match:
71
+ char_name = match.group(1).strip()
72
+ if not user_name:
73
+ match = re.search(r"(?:user|player|{{user}})\s*(?:is|name[ds]?|:)\s*([^\n,.]+)", content, re.IGNORECASE)
74
+ if match:
75
+ user_name = match.group(1).strip()
76
+
77
+ return user_name or "User", char_name or "Assistant"
78
+
79
+ def replace_placeholders(messages: List[Dict], user_name: str, char_name: str) -> List[Dict]:
80
+ out = []
81
+ for m in messages:
82
+ if isinstance(m.get("content"), str):
83
+ content = m["content"].replace("{{user}}", user_name).replace("{{char}}", char_name)
84
+ content = content.replace("{{USER}}", user_name).replace("{{CHAR}}", char_name)
85
+ out.append({**m, "content": content})
86
+ else:
87
+ out.append(m)
88
+ return out
89
+
90
+ def inject_boundary(messages: List[Dict], user_name: str, char_name: str) -> List[Dict]:
91
+ block = f"""[CRITICAL INSTRUCTIONS — DO NOT IGNORE]
92
+ You are {char_name}. You ONLY narrate {char_name}'s thoughts, dialogue, body language, and actions.
93
+ You NEVER control, speak for, or narrate the internal thoughts of {user_name}.
94
+ {user_name} is an independent entity. When {user_name} speaks or acts, you STOP and await their input.
95
+ You do NOT write {user_name}'s dialogue, thoughts, or decisions under any circumstances.
96
+ If you must describe {user_name}, do so only from {char_name}'s external sensory perspective.
97
+
98
+ [MEMORY RULES]
99
+ - Maintain strict consistency with all previously established facts, traits, and events.
100
+ - If a detail conflicts with earlier messages, the EARLIER message is canon. Correct silently.
101
+ - Never introduce new backstory, relationships, or personality traits not previously established."""
102
+
103
+ idx = next((i for i, m in enumerate(messages) if m.get("role") == "system"), -1)
104
+ if idx >= 0:
105
+ original = messages[idx].get("content", "")
106
+ messages[idx]["content"] = block + "\n\n=== ORIGINAL INSTRUCTIONS ===\n\n" + original
107
+ else:
108
+ messages.insert(0, {"role": "system", "content": block})
109
+ return messages
110
+
111
+ @app.api_route("/", methods=["GET", "POST", "OPTIONS"])
112
+ async def proxy(request: Request):
113
+ if request.method == "OPTIONS":
114
+ return StreamingResponse(
115
+ iter(['']),
116
+ headers={
117
+ "Access-Control-Allow-Origin": "*",
118
+ "Access-Control-Allow-Methods": "POST, GET, OPTIONS",
119
+ "Access-Control-Allow-Headers": "Content-Type, Authorization",
120
+ }
121
+ )
122
+
123
+ if request.method != "POST":
124
+ return StreamingResponse(iter(["NVIDIA NIM Proxy (GLM-5.2 MAX) — Active"]))
125
+
126
+ try:
127
+ body = await request.json()
128
+ auth = request.headers.get("Authorization") or f"Bearer {os.environ.get('NVIDIA_API_KEY', '')}"
129
+
130
+ user_name, char_name = extract_names(body)
131
+ messages = replace_placeholders(body.get("messages", []), user_name, char_name)
132
+ messages = inject_boundary(messages, user_name, char_name)
133
+
134
+ max_ctx = min(body.get("max_context_tokens", 120000), 150000)
135
+ trimmed = truncate_messages(messages, max_ctx)
136
+
137
+ total_toks = count_tokens(trimmed)
138
+ sys_toks = count_tokens([m for m in trimmed if m.get("role") == "system"])
139
+ print(f"[NIM Proxy] Msgs: {len(trimmed)} | TotalToks: {total_toks} | SysToks: {sys_toks} | User: {user_name} | Char: {char_name}")
140
+
141
+ nim_body = {
142
+ "model": body.get("model", "z-ai/glm-5.2"),
143
+ "messages": trimmed,
144
+ "stream": body.get("stream", True),
145
+ "chat_template_kwargs": {"reasoning_effort": "max"}, # FULL POWER, no timeout
146
+ "temperature": body.get("temperature", 1.0),
147
+ "top_p": body.get("top_p", 0.95),
148
+ }
149
+ for key in ["max_tokens", "top_k", "frequency_penalty", "presence_penalty", "repetition_penalty", "stop", "seed"]:
150
+ if key in body and body[key] is not None:
151
+ nim_body[key] = body[key]
152
+
153
+ async def event_stream():
154
+ async with httpx.AsyncClient(timeout=httpx.Timeout(300.0, connect=60.0)) as client:
155
+ try:
156
+ async with client.stream("POST", NVIDIA_URL, headers={
157
+ "Content-Type": "application/json",
158
+ "Authorization": auth,
159
+ }, json=nim_body) as resp:
160
+ if resp.status_code != 200:
161
+ err = await resp.aread()
162
+ yield f"data: {json.dumps({'error': f'NIM {resp.status_code}: {err.decode()[:500]}'})}\n\n"
163
+ yield "data: [DONE]\n\n"
164
+ return
165
+
166
+ buffer = ""
167
+ thinking_started = False
168
+ thinking_ended = False
169
+
170
+ async for chunk in resp.aiter_text():
171
+ buffer += chunk
172
+ lines = buffer.split("\n")
173
+ buffer = lines.pop() or ""
174
+
175
+ for line in lines:
176
+ if not line.startswith("data: "):
177
+ continue
178
+ if "[DONE]" in line:
179
+ if thinking_started and not thinking_ended:
180
+ yield f"data: {json.dumps({'choices':[{'delta':{'content':'\\n</think>\\n\\n'}}]})}\n\n"
181
+ yield line + "\n\n"
182
+ continue
183
+
184
+ try:
185
+ data = json.loads(line[6:])
186
+ delta = data.get("choices", [{}])[0].get("delta", {})
187
+ if not delta:
188
+ yield line + "\n\n"
189
+ continue
190
+
191
+ reasoning = delta.get("reasoning_content", "")
192
+ content = delta.get("content", "")
193
+ output = ""
194
+
195
+ if reasoning:
196
+ if not thinking_started:
197
+ output += "<think>\\n"
198
+ thinking_started = True
199
+ output += reasoning
200
+
201
+ if content:
202
+ if thinking_started and not thinking_ended:
203
+ output += "\\n</think>\\n\\n"
204
+ thinking_ended = True
205
+ output += content
206
+
207
+ data["choices"][0]["delta"] = {"content": output}
208
+ if "reasoning_content" in data["choices"][0]["delta"]:
209
+ del data["choices"][0]["delta"]["reasoning_content"]
210
+
211
+ yield f"data: {json.dumps(data)}\\n\\n"
212
+ except Exception:
213
+ yield line + "\\n"
214
+
215
+ if thinking_started and not thinking_ended:
216
+ yield f"data: {json.dumps({'choices':[{'delta':{'content':'\\n</think>\\n\\n'}}]})}\n\n"
217
+
218
+ except Exception as e:
219
+ print(f"[NIM Proxy] Error: {e}")
220
+ yield f"data: {json.dumps({'error': str(e)})}\n\n"
221
+
222
+ return StreamingResponse(
223
+ event_stream(),
224
+ media_type="text/event-stream",
225
+ headers={
226
+ "Cache-Control": "no-cache",
227
+ "Access-Control-Allow-Origin": "*",
228
+ }
229
+ )
230
+
231
+ except Exception as e:
232
+ print(f"[NIM Proxy] Fatal: {e}")
233
+ return StreamingResponse(
234
+ iter([f"data: {json.dumps({'error': str(e)})}\n\n"]),
235
+ media_type="text/event-stream",
236
+ status_code=500,
237
+ headers={"Access-Control-Allow-Origin": "*"}
238
+ )
server.js DELETED
@@ -1,125 +0,0 @@
1
- const express = require('express');
2
- const cors = require('cors');
3
-
4
- const app = express();
5
-
6
- // Enable global CORS to let Janitor AI handshake effortlessly
7
- app.use(cors());
8
- app.use(express.json({ limit: '100mb' }));
9
- app.use(express.urlencoded({ limit: '100mb', extended: true }));
10
- // Target Endpoint for DaSong API
11
- const DASONG_URL = 'https://api.ai1833.shop/v1/chat/completions';
12
-
13
- // Map Janitor's incoming models to the specific New-API dashboard options
14
- const MODEL_MAPPING = {
15
- 'gpt-4': 'deepseek-v4-pro',
16
- 'gpt-4o': 'GLM-5.1',
17
- 'o1': 'deepseek-3.2',
18
- 'o3':'z-ai/glm-5.2'
19
- };
20
-
21
- // Health check route
22
- app.get('*', (req, res) => {
23
- res.json({ status: "alive", message: "DaSong API Node.js Proxy Bridge Active on 3000." });
24
- });
25
-
26
- // Main Reverse Proxy Handler
27
- app.post('*', async (req, res) => {
28
- try {
29
- const body = req.body;
30
-
31
- if (!body || !body.messages) {
32
- return res.json({ status: "alive", message: "Connection baseline stable." });
33
- }
34
-
35
- // Pull the sk- token from Hugging Face Environment Secrets
36
- const apiKey = (process.env.DASONG_API_KEY || '').trim();
37
- if (!apiKey) {
38
- return res.status(500).json({ error: "Configuration Error: DASONG_API_KEY secret is missing in Space settings." });
39
- }
40
-
41
- const inboundModel = body.model || 'gpt-4';
42
- const targetModel = MODEL_MAPPING[inboundModel] || 'deepseek-v4-pro';
43
-
44
- // --- Context Sanitization Layer ---
45
- let sanitizedMessages = [];
46
- let combinedSystemContent = "";
47
-
48
- for (let msg of body.messages || []) {
49
- let role = msg.role;
50
- if (['example_user', 'user'].includes(role)) role = 'user';
51
- if (['example_assistant', 'assistant'].includes(role)) role = 'assistant';
52
-
53
- let content = typeof msg.content === 'string' ? msg.content.trim() : '';
54
- if (!content) continue;
55
-
56
- if (role === 'system') {
57
- combinedSystemContent += combinedSystemContent ? "\n" + content : content;
58
- } else if (['user', 'assistant'].includes(role)) {
59
- // Squash consecutive identical roles to prevent parsing validation rejections
60
- if (sanitizedMessages.length > 0 && sanitizedMessages[sanitizedMessages.length - 1].role === role) {
61
- sanitizedMessages[sanitizedMessages.length - 1].content += "\n" + content;
62
- } else {
63
- sanitizedMessages.push({ role, content });
64
- }
65
- }
66
- }
67
-
68
- if (combinedSystemContent) {
69
- sanitizedMessages.unshift({ role: 'system', content: combinedSystemContent });
70
- }
71
-
72
- // Re-assemble standard format
73
- const pristineBody = {
74
- model: targetModel,
75
- messages: sanitizedMessages,
76
- stream: body.stream !== undefined ? body.stream : true
77
- };
78
-
79
- // Forward optional safety/generation variables
80
- if (typeof body.temperature === 'number') pristineBody.temperature = body.temperature;
81
- if (typeof body.top_p === 'number') pristineBody.top_p = body.top_p;
82
- if (typeof body.max_tokens === 'number') pristineBody.max_tokens = body.max_tokens;
83
-
84
- console.log(`[Proxy Log] Forwarding request to DaSong API for model: ${targetModel}`);
85
-
86
- // Upstream execution
87
- const response = await fetch(DASONG_URL, {
88
- method: 'POST',
89
- headers: {
90
- 'Authorization': `Bearer ${apiKey}`,
91
- 'Content-Type': 'application/json'
92
- },
93
- body: JSON.stringify(pristineBody)
94
- });
95
-
96
- if (!response.ok) {
97
- const errorText = await response.text();
98
- console.error(`[Upstream Error] Status: {response.status} | Body: ${errorText.slice(0, 500)}`);
99
- return res.status(response.status).send(`Upstream provider returned an error: ${response.status}`);
100
- }
101
-
102
- // Setup streaming response headers back to Janitor AI
103
- res.setHeader('Content-Type', response.headers.get('content-type') || 'text/event-stream');
104
- res.setHeader('Cache-Control', 'no-cache');
105
- res.setHeader('Connection', 'keep-alive');
106
-
107
- // Stream the incoming chunks out natively
108
- for await (const chunk of response.body) {
109
- res.write(chunk);
110
- }
111
- res.end();
112
-
113
- } catch (err) {
114
- console.error(`[Network Exception]: ${err.message}`);
115
- if (!res.headersSent) {
116
- res.status(500).send(`Proxy network loop error: ${err.message}`);
117
- }
118
- }
119
- });
120
-
121
- // Force explicit port binding for Hugging Face's container system
122
- const PORT = 3000;
123
- app.listen(PORT, '0.0.0.0', () => {
124
- console.log(`OG Node Proxy running smoothly on native port ${PORT}`);
125
- });