Norsec93 commited on
Commit
63a8b77
·
verified ·
1 Parent(s): f6028b7

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +36 -19
main.py CHANGED
@@ -19,9 +19,6 @@ app.add_middleware(
19
 
20
  NVIDIA_URL = "https://integrate.api.nvidia.com/v1/chat/completions"
21
 
22
- THINK_START = " \n"
23
- THINK_END = "\n \n\n"
24
-
25
  def estimate_tokens(text: str) -> int:
26
  return math.ceil(len(text or "") / 3.2)
27
 
@@ -91,13 +88,23 @@ def replace_placeholders(messages: List[Dict], user_name: str, char_name: str) -
91
  return out
92
 
93
  def inject_boundary(messages: List[Dict], user_name: str, char_name: str) -> List[Dict]:
 
 
94
  block = f"""[CRITICAL INSTRUCTIONS — DO NOT IGNORE]
 
95
  You are {char_name}. You ONLY narrate {char_name}'s thoughts, dialogue, body language, and actions.
96
  You NEVER control, speak for, or narrate the internal thoughts of {user_name}.
97
  {user_name} is an independent entity. When {user_name} speaks or acts, you STOP and await their input.
98
  You do NOT write {user_name}'s dialogue, thoughts, or decisions under any circumstances.
99
  If you must describe {user_name}, do so only from {char_name}'s external sensory perspective.
100
 
 
 
 
 
 
 
 
101
  [MEMORY RULES]
102
  - Maintain strict consistency with all previously established facts, traits, and events.
103
  - If a detail conflicts with earlier messages, the EARLIER message is canon. Correct silently.
@@ -124,7 +131,7 @@ async def proxy(request: Request):
124
  )
125
 
126
  if request.method != "POST":
127
- return StreamingResponse(iter(["NVIDIA NIM Proxy (GLM-5.2 MAX) — Active"]))
128
 
129
  try:
130
  body = await request.json()
@@ -141,15 +148,14 @@ async def proxy(request: Request):
141
  sys_toks = count_tokens([m for m in trimmed if m.get("role") == "system"])
142
  print(f"[NIM Proxy] Msgs: {len(trimmed)} | TotalToks: {total_toks} | SysToks: {sys_toks} | User: {user_name} | Char: {char_name}")
143
 
 
 
144
  nim_body = {
145
  "model": body.get("model", "z-ai/glm-5.2"),
146
  "messages": trimmed,
147
  "stream": body.get("stream", True),
148
- "reasoning_effort": "max",
149
  "chat_template_kwargs": {
150
  "thinking": True,
151
- "enable_thinking": True,
152
- "clear_thinking": False,
153
  },
154
  "temperature": body.get("temperature") if body.get("temperature") is not None else 0.85,
155
  "top_p": body.get("top_p") if body.get("top_p") is not None else 0.95,
@@ -158,8 +164,6 @@ async def proxy(request: Request):
158
  if key in body and body[key] is not None:
159
  nim_body[key] = body[key]
160
 
161
- print(f"[NIM Proxy] Request body keys: {list(nim_body.keys())}")
162
-
163
  async def event_stream():
164
  async with httpx.AsyncClient(timeout=httpx.Timeout(300.0, connect=60.0)) as client:
165
  try:
@@ -189,7 +193,7 @@ async def proxy(request: Request):
189
  continue
190
  if "[DONE]" in line:
191
  if thinking_started and not thinking_ended:
192
- close_data = {"choices": [{"delta": {"content": THINK_END}}]}
193
  yield f"data: {json.dumps(close_data)}\n\n"
194
  yield line + "\n\n"
195
  continue
@@ -204,36 +208,49 @@ async def proxy(request: Request):
204
  reasoning = delta.get("reasoning_content", "")
205
  content = delta.get("content", "")
206
 
 
207
  if reasoning and not reasoning_seen:
208
  reasoning_seen = True
209
- print(f"[NIM Proxy] REASONING DETECTED: {reasoning[:120]}...")
210
 
211
  output = ""
212
 
 
213
  if reasoning:
214
  if not thinking_started:
215
- output += THINK_START
216
  thinking_started = True
217
  output += reasoning
218
 
219
  if content:
220
- if thinking_started and not thinking_ended:
221
- output += THINK_END
222
- thinking_ended = True
223
- output += content
 
 
 
 
 
 
 
 
 
 
 
224
 
225
  data["choices"][0]["delta"] = {"content": output}
226
-
227
  yield f"data: {json.dumps(data)}\n\n"
228
  except Exception:
229
  yield line + "\n"
230
 
 
231
  if thinking_started and not thinking_ended:
232
- close_data = {"choices": [{"delta": {"content": THINK_END}}]}
233
  yield f"data: {json.dumps(close_data)}\n\n"
234
 
235
  if not reasoning_seen:
236
- print("[NIM Proxy] WARNING: No reasoning_content tokens received in this stream.")
237
 
238
  except Exception as e:
239
  print(f"[NIM Proxy] Error: {e}")
 
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
 
 
88
  return out
89
 
90
  def inject_boundary(messages: List[Dict], user_name: str, char_name: str) -> List[Dict]:
91
+ # CRITICAL: This block is prepended to the system prompt.
92
+ # Because truncation cuts from the END, these instructions are unkillable.
93
  block = f"""[CRITICAL INSTRUCTIONS — DO NOT IGNORE]
94
+
95
  You are {char_name}. You ONLY narrate {char_name}'s thoughts, dialogue, body language, and actions.
96
  You NEVER control, speak for, or narrate the internal thoughts of {user_name}.
97
  {user_name} is an independent entity. When {user_name} speaks or acts, you STOP and await their input.
98
  You do NOT write {user_name}'s dialogue, thoughts, or decisions under any circumstances.
99
  If you must describe {user_name}, do so only from {char_name}'s external sensory perspective.
100
 
101
+ [THINKING FORMAT — MANDATORY]
102
+ You MUST begin every single response with on its own line.
103
+ Then write your step-by-step planning, character analysis, and scene logic.
104
+ End your planning with on its own line.
105
+ Then write the roleplay response.
106
+ Do NOT skip the tags under any circumstances.
107
+
108
  [MEMORY RULES]
109
  - Maintain strict consistency with all previously established facts, traits, and events.
110
  - If a detail conflicts with earlier messages, the EARLIER message is canon. Correct silently.
 
131
  )
132
 
133
  if request.method != "POST":
134
+ return StreamingResponse(iter(["NVIDIA NIM Proxy (GLM-5.2) — Active"]))
135
 
136
  try:
137
  body = await request.json()
 
148
  sys_toks = count_tokens([m for m in trimmed if m.get("role") == "system"])
149
  print(f"[NIM Proxy] Msgs: {len(trimmed)} | TotalToks: {total_toks} | SysToks: {sys_toks} | User: {user_name} | Char: {char_name}")
150
 
151
+ # Use ONLY thinking: true in chat_template_kwargs.
152
+ # Top-level reasoning_effort conflicts on NIM and breaks reasoning_content separation.
153
  nim_body = {
154
  "model": body.get("model", "z-ai/glm-5.2"),
155
  "messages": trimmed,
156
  "stream": body.get("stream", True),
 
157
  "chat_template_kwargs": {
158
  "thinking": True,
 
 
159
  },
160
  "temperature": body.get("temperature") if body.get("temperature") is not None else 0.85,
161
  "top_p": body.get("top_p") if body.get("top_p") is not None else 0.95,
 
164
  if key in body and body[key] is not None:
165
  nim_body[key] = body[key]
166
 
 
 
167
  async def event_stream():
168
  async with httpx.AsyncClient(timeout=httpx.Timeout(300.0, connect=60.0)) as client:
169
  try:
 
193
  continue
194
  if "[DONE]" in line:
195
  if thinking_started and not thinking_ended:
196
+ close_data = {"choices": [{"delta": {"content": "\n \n\n"}}]}
197
  yield f"data: {json.dumps(close_data)}\n\n"
198
  yield line + "\n\n"
199
  continue
 
208
  reasoning = delta.get("reasoning_content", "")
209
  content = delta.get("content", "")
210
 
211
+ # Debug: log first reasoning token
212
  if reasoning and not reasoning_seen:
213
  reasoning_seen = True
214
+ print(f"[NIM Proxy] REASONING_CONTENT detected: {reasoning[:120]}...")
215
 
216
  output = ""
217
 
218
+ # Path A: NIM sends reasoning as separate field (original behavior)
219
  if reasoning:
220
  if not thinking_started:
221
+ output += " \n"
222
  thinking_started = True
223
  output += reasoning
224
 
225
  if content:
226
+ # Path B: Model followed system instruction and put in content itself
227
+ # Don't double-wrap if already tagged
228
+ if " " in content and not thinking_started:
229
+ # Pass through as-is; Janitor will render the box
230
+ output += content
231
+ # Mark states so we don't inject closing tags later
232
+ if " " not in content:
233
+ thinking_started = True
234
+ thinking_ended = True
235
+ else:
236
+ # Normal path: close reasoning box if open, then content
237
+ if thinking_started and not thinking_ended:
238
+ output += "\n \n\n"
239
+ thinking_ended = True
240
+ output += content
241
 
242
  data["choices"][0]["delta"] = {"content": output}
 
243
  yield f"data: {json.dumps(data)}\n\n"
244
  except Exception:
245
  yield line + "\n"
246
 
247
+ # Safety close
248
  if thinking_started and not thinking_ended:
249
+ close_data = {"choices": [{"delta": {"content": "\n \n\n"}}]}
250
  yield f"data: {json.dumps(close_data)}\n\n"
251
 
252
  if not reasoning_seen:
253
+ print("[NIM Proxy] No reasoning_content field this stream (model may have merged it into content).")
254
 
255
  except Exception as e:
256
  print(f"[NIM Proxy] Error: {e}")