File size: 12,113 Bytes
70226ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3dfcc1
70226ad
 
 
 
 
 
 
 
9354e9c
70226ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9354e9c
 
 
 
70226ad
 
 
 
9354e9c
4b98919
bfc8568
9354e9c
 
4b98919
bfc8568
 
70226ad
 
 
 
 
9354e9c
 
70226ad
 
 
 
 
 
 
 
 
d3dfcc1
 
70226ad
 
 
 
 
 
bfc8568
70226ad
 
 
 
 
 
 
 
 
 
 
63a8b77
d3dfcc1
70226ad
 
 
 
 
 
 
 
 
 
 
 
4b98919
 
 
9354e9c
4b98919
70226ad
 
 
 
63a8b77
70226ad
 
 
 
9354e9c
 
 
 
70226ad
 
9354e9c
d3dfcc1
70226ad
d3dfcc1
70226ad
 
63a8b77
d3dfcc1
4b98919
 
9354e9c
70226ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
import os
import json
import math
import re
from typing import List, Dict, Any
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse
import httpx

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

NVIDIA_URL = "https://integrate.api.nvidia.com/v1/chat/completions"

def estimate_tokens(text: str) -> int:
    return math.ceil(len(text or "") / 3.2)

def count_tokens(messages: List[Dict]) -> int:
    total = 0
    for m in messages:
        content = m.get("content", "") if isinstance(m.get("content"), str) else json.dumps(m.get("content"))
        total += estimate_tokens(content) + estimate_tokens(m.get("role", "")) + 4
    return total

def truncate_messages(messages: List[Dict], max_tokens: int = 120000) -> List[Dict]:
    if not messages:
        return []
    system_msgs = [m for m in messages if m.get("role") == "system"]
    convo_msgs = [m for m in messages if m.get("role") != "system"]
    
    total = count_tokens(system_msgs) + count_tokens(convo_msgs)
    if total <= max_tokens:
        return messages
    
    trimmed = list(convo_msgs)
    while total > max_tokens and len(trimmed) > 1:
        dropped = trimmed.pop(0)
        total -= estimate_tokens(dropped.get("content", "")) + estimate_tokens(dropped.get("role", "")) + 4
    
    if total > max_tokens and system_msgs:
        kept = [system_msgs[-1]]
        convo_tok = count_tokens(trimmed)
        reserved = estimate_tokens(kept[0].get("role", "")) + 4
        allowed = max(500, max_tokens - convo_tok - reserved)
        if allowed > 500:
            content = kept[0].get("content", "")
            slice_len = math.floor(allowed * 3.2)
            kept[0]["content"] = content[:slice_len] + "\n\n...[System prompt truncated to fit context window]"
        return kept + trimmed
    
    return system_msgs + trimmed

def extract_names(body: Dict) -> tuple:
    user_name = body.get("user_name") or body.get("userName")
    char_name = body.get("character_name") or body.get("characterName")
    
    if not user_name or not char_name:
        first_sys = next((m for m in body.get("messages", []) if m.get("role") == "system" and isinstance(m.get("content"), str)), None)
        if first_sys:
            content = first_sys["content"]
            if not char_name:
                match = re.search(r"You are\s+([^\n,.]+)", content, re.IGNORECASE)
                if match:
                    char_name = match.group(1).strip()
            if not user_name:
                match = re.search(r"(?:user|player|{{user}})\s*(?:is|name[ds]?|:)\s*([^\n,.]+)", content, re.IGNORECASE)
                if match:
                    user_name = match.group(1).strip()
    
    return user_name or "User", char_name or "Assistant"

def replace_placeholders(messages: List[Dict], user_name: str, char_name: str) -> List[Dict]:
    out = []
    for m in messages:
        if isinstance(m.get("content"), str):
            content = m["content"].replace("{{user}}", user_name).replace("{{char}}", char_name)
            content = content.replace("{{USER}}", user_name).replace("{{CHAR}}", char_name)
            out.append({**m, "content": content})
        else:
            out.append(m)
    return out

def inject_boundary(messages: List[Dict], user_name: str, char_name: str) -> List[Dict]:
    block = f"""[CRITICAL INSTRUCTIONS — DO NOT IGNORE]
You are {char_name}. You ONLY narrate {char_name}'s thoughts, dialogue, body language, and actions.
You NEVER control, speak for, or narrate the internal thoughts of {user_name}.
{user_name} is an independent entity. When {user_name} speaks or acts, you STOP and await their input.
You do NOT write {user_name}'s dialogue, thoughts, or decisions under any circumstances.
If you must describe {user_name}, do so only from {char_name}'s external sensory perspective.

[MEMORY RULES]
- Maintain strict consistency with all previously established facts, traits, and events.
- If a detail conflicts with earlier messages, the EARLIER message is canon. Correct silently.
- Never introduce new backstory, relationships, or personality traits not previously established."""
    
    idx = next((i for i, m in enumerate(messages) if m.get("role") == "system"), -1)
    if idx >= 0:
        original = messages[idx].get("content", "")
        messages[idx]["content"] = block + "\n\n=== ORIGINAL INSTRUCTIONS ===\n\n" + original
    else:
        messages.insert(0, {"role": "system", "content": block})
    return messages

@app.api_route("/", methods=["GET", "POST", "OPTIONS"])
async def proxy(request: Request):
    if request.method == "OPTIONS":
        return StreamingResponse(
            iter([""]),
            headers={
                "Access-Control-Allow-Origin": "*",
                "Access-Control-Allow-Methods": "POST, GET, OPTIONS",
                "Access-Control-Allow-Headers": "Content-Type, Authorization",
            }
        )
    
    if request.method != "POST":
        return StreamingResponse(iter(["NVIDIA NIM Proxy (GLM-5.2 MAX) — Active"]))
    
    try:
        body = await request.json()
        auth = request.headers.get("Authorization") or f"Bearer {os.environ.get('NVIDIA_API_KEY', '')}"
        
        user_name, char_name = extract_names(body)
        messages = replace_placeholders(body.get("messages", []), user_name, char_name)
        messages = inject_boundary(messages, user_name, char_name)
        
        max_ctx = min(body.get("max_context_tokens", 120000), 150000)
        trimmed = truncate_messages(messages, max_ctx)
        
        total_toks = count_tokens(trimmed)
        sys_toks = count_tokens([m for m in trimmed if m.get("role") == "system"])
        print(f"[NIM Proxy] Msgs: {len(trimmed)} | TotalToks: {total_toks} | SysToks: {sys_toks} | User: {user_name} | Char: {char_name}")
        
        # RP-optimized defaults:
        # - reasoning_effort: "max" at TOP LEVEL (nested inside chat_template_kwargs is ignored by NIM)
        # - temperature defaults to 0.85 for tighter character consistency if Janitor doesn't send one
        # - top_p 0.95 keeps creativity while preventing token drift
        nim_body = {
            "model": body.get("model", "z-ai/glm-5.2"),
            "messages": trimmed,
            "stream": body.get("stream", True),
            "reasoning_effort": "max",
            "chat_template_kwargs": {
                "thinking": True,
                "enable_thinking": True,
                "clear_thinking": False,
            },
            "temperature": body.get("temperature") if body.get("temperature") is not None else 0.85,
            "top_p": body.get("top_p") if body.get("top_p") is not None else 0.95,
        }
        for key in ["max_tokens", "top_k", "frequency_penalty", "presence_penalty", "repetition_penalty", "stop", "seed"]:
            if key in body and body[key] is not None:
                nim_body[key] = body[key]
        
        print(f"[NIM Proxy] Request body keys: {list(nim_body.keys())}")
        
        async def event_stream():
            async with httpx.AsyncClient(timeout=httpx.Timeout(300.0, connect=60.0)) as client:
                try:
                    async with client.stream("POST", NVIDIA_URL, headers={
                        "Content-Type": "application/json",
                        "Authorization": auth,
                    }, json=nim_body) as resp:
                        if resp.status_code != 200:
                            err = await resp.aread()
                            payload = {"error": f"NIM {resp.status_code}: {err.decode()[:500]}"}
                            yield f"data: {json.dumps(payload)}\n\n"
                            yield "data: [DONE]\n\n"
                            return
                        
                        buffer = ""
                        thinking_started = False
                        thinking_ended = False
                        reasoning_seen = False
                        
                        async for chunk in resp.aiter_text():
                            buffer += chunk
                            lines = buffer.split("\n")
                            buffer = lines.pop() or ""
                            
                            for line in lines:
                                if not line.startswith("data: "):
                                    continue
                                if "[DONE]" in line:
                                    if thinking_started and not thinking_ended:
                                        close_data = {"choices": [{"delta": {"content": "\n  \n\n"}}]}
                                        yield f"data: {json.dumps(close_data)}\n\n"
                                    yield line + "\n\n"
                                    continue
                                
                                try:
                                    data = json.loads(line[6:])
                                    delta = data.get("choices", [{}])[0].get("delta", {})
                                    if not delta:
                                        yield line + "\n\n"
                                        continue
                                    
                                    reasoning = delta.get("reasoning_content", "")
                                    content = delta.get("content", "")
                                    
                                    if reasoning and not reasoning_seen:
                                        reasoning_seen = True
                                        print(f"[NIM Proxy] REASONING DETECTED: {reasoning[:120]}...")
                                    
                                    output = ""
                                    
                                    if reasoning:
                                        if not thinking_started:
                                            output += "  \n"
                                            thinking_started = True
                                        output += reasoning
                                    
                                    if content:
                                        if thinking_started and not thinking_ended:
                                            output += "\n  \n\n"
                                            thinking_ended = True
                                        output += content
                                    
                                    data["choices"][0]["delta"] = {"content": output}
                                    
                                    yield f"data: {json.dumps(data)}\n\n"
                                except Exception:
                                    yield line + "\n"
                        
                        if thinking_started and not thinking_ended:
                            close_data = {"choices": [{"delta": {"content": "\n  \n\n"}}]}
                            yield f"data: {json.dumps(close_data)}\n\n"
                        
                        if not reasoning_seen:
                            print("[NIM Proxy] WARNING: No reasoning_content tokens received in this stream.")
                                
                except Exception as e:
                    print(f"[NIM Proxy] Error: {e}")
                    yield f"data: {json.dumps({'error': str(e)})}\n\n"
        
        return StreamingResponse(
            event_stream(),
            media_type="text/event-stream",
            headers={
                "Cache-Control": "no-cache",
                "Access-Control-Allow-Origin": "*",
            }
        )
        
    except Exception as e:
        print(f"[NIM Proxy] Fatal: {e}")
        return StreamingResponse(
            iter([f"data: {json.dumps({'error': str(e)})}\n\n"]),
            media_type="text/event-stream",
            status_code=500,
            headers={"Access-Control-Allow-Origin": "*"}
        )