SHERWYNLUCIAN commited on
Commit
a60d28a
·
verified ·
1 Parent(s): 881bb63

Upload 5 files

Browse files
Files changed (1) hide show
  1. main.py +19 -36
main.py CHANGED
@@ -325,45 +325,27 @@ except ImportError:
325
 
326
  import re
327
 
328
- def fallback_infer(prompt):
329
  if llm is None:
330
  return "Xin lỗi, hệ thống đang bị lỗi tải mô hình GGUF."
331
 
332
- system_prompt = "Bạn là trợ lý AI tiếng Việt tên là EvoNet. Hãy trả lời ngắn gọn, trực tiếp và chính xác."
333
-
334
- # Assistant Prefill: Ép model bắt đầu bằng một từ tiếng Việt để chặn nó sinh thẻ <think> tiếng Anh
335
- formatted_prompt = f"<|im_start|>system\n{system_prompt}<|im_end|>\n<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\n"
336
-
337
- res = llm.create_completion(
338
- formatted_prompt,
339
- max_tokens=512,
340
- stop=["<|im_end|>", "<|im_start|>"],
341
- temperature=0.7
342
- )
343
- text = res["choices"][0]["text"].strip()
344
-
345
- # Lọc rác (nếu có)
346
- text = re.sub(r'<think>.*?</think>', '', text, flags=re.DOTALL)
347
- text = re.sub(r'<think>.*', '', text, flags=re.DOTALL)
348
-
349
- text = text.strip()
350
-
351
- # Nếu text vẫn rỗng, thử gọi lại 1 lần nữa với prefill mạnh hơn
352
- if not text:
353
- formatted_prompt_retry = f"<|im_start|>system\n{system_prompt}<|im_end|>\n<|im_start|>user\n{prompt}<|im_end|>\n<|im_start|>assistant\nTôi"
354
- res_retry = llm.create_completion(
355
- formatted_prompt_retry,
356
  max_tokens=512,
357
- stop=["<|im_end|>", "<|im_start|>"],
358
- temperature=0.8
359
  )
360
- text = "Tôi" + res_retry["choices"][0]["text"]
361
- text = re.sub(r'<think>.*?</think>', '', text, flags=re.DOTALL).strip()
362
-
363
- if not text:
364
- return "Xin lỗi, hiện tại tôi không thể trả lời câu hỏi này."
365
-
366
- return text
367
 
368
 
369
 
@@ -444,6 +426,7 @@ async def chat_completions(req: ChatCompletionRequest, request: Request, token:
444
  if not req.messages:
445
  raise HTTPException(status_code=400, detail="messages array cannot be empty")
446
 
 
447
  last_message = req.messages[-1].content
448
  print(f"[Gateway] B2B Request for model {req.model}")
449
 
@@ -488,11 +471,11 @@ async def chat_completions(req: ChatCompletionRequest, request: Request, token:
488
  raise Exception("Swarm returned non-200 after retries")
489
  except Exception as e:
490
  print(f"[Gateway Routing] Lỗi từ DePIN Swarm ({e}), chuyển sang Fallback Local.")
491
- result_text = f"[Extreme JIT] {await asyncio.to_thread(fallback_infer, last_message)}"
492
  else:
493
  # Step 2b: Fallback to Local Extreme Batching
494
  print(f"[Gateway Routing] ➡️ DePIN bận/thiếu Node. Chuyển hướng xử lý tại Cụm Server Nội bộ.")
495
- result_text = f"[Extreme JIT] {await asyncio.to_thread(fallback_infer, last_message)}"
496
 
497
  # Step 3: Format OpenAI response
498
  prompt_tokens = len(last_message.split())
 
325
 
326
  import re
327
 
328
+ def fallback_infer(messages_dicts):
329
  if llm is None:
330
  return "Xin lỗi, hệ thống đang bị lỗi tải mô hình GGUF."
331
 
332
+ # Ép model phải dùng tiếng Việt cho cả quá trình suy nghĩ lẫn trả lời
333
+ for m in messages_dicts:
334
+ if m["role"] == "system":
335
+ m["content"] += "\n[LUẬT TỐI CAO: Bạn được phép suy nghĩ (nếu cần), nhưng MỌI QUÁ TRÌNH SUY NGHĨ VÀ CÂU TRẢ LỜI ĐỀU PHẢI VIẾT BẰNG TIẾNG VIỆT 100%. Tuyệt đối không dùng tiếng Anh.]"
336
+ break
337
+
338
+ try:
339
+ res = llm.create_chat_completion(
340
+ messages=messages_dicts,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
341
  max_tokens=512,
342
+ temperature=0.7
 
343
  )
344
+ text = res["choices"][0]["message"]["content"]
345
+ return text.strip()
346
+ except Exception as e:
347
+ print(f"[Gateway Error] Lỗi inference: {e}")
348
+ return "Xin lỗi, hệ thống gặp lỗi khi xử lý câu hỏi của bạn."
 
 
349
 
350
 
351
 
 
426
  if not req.messages:
427
  raise HTTPException(status_code=400, detail="messages array cannot be empty")
428
 
429
+ messages_dicts = [{"role": m.role, "content": m.content} for m in req.messages]
430
  last_message = req.messages[-1].content
431
  print(f"[Gateway] B2B Request for model {req.model}")
432
 
 
471
  raise Exception("Swarm returned non-200 after retries")
472
  except Exception as e:
473
  print(f"[Gateway Routing] Lỗi từ DePIN Swarm ({e}), chuyển sang Fallback Local.")
474
+ result_text = f"[Extreme JIT] {await asyncio.to_thread(fallback_infer, messages_dicts)}"
475
  else:
476
  # Step 2b: Fallback to Local Extreme Batching
477
  print(f"[Gateway Routing] ➡️ DePIN bận/thiếu Node. Chuyển hướng xử lý tại Cụm Server Nội bộ.")
478
+ result_text = f"[Extreme JIT] {await asyncio.to_thread(fallback_infer, messages_dicts)}"
479
 
480
  # Step 3: Format OpenAI response
481
  prompt_tokens = len(last_message.split())