1234ty commited on
Commit
77877ac
·
verified ·
1 Parent(s): 67d050c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -28
app.py CHANGED
@@ -5,7 +5,7 @@ import torch
5
  import uvicorn
6
  import os
7
 
8
- # Initialize the model
9
  pipe = pipeline(
10
  "text-generation",
11
  model="unsloth/Llama-3.2-1B-Instruct",
@@ -15,7 +15,6 @@ pipe = pipeline(
15
 
16
  app = FastAPI()
17
 
18
- # Enable CORS for web access
19
  app.add_middleware(
20
  CORSMiddleware,
21
  allow_origins=["*"],
@@ -23,59 +22,73 @@ app.add_middleware(
23
  allow_headers=["*"],
24
  )
25
 
 
 
 
 
 
 
26
  @app.post("/chat")
27
  async def chat(request: Request):
28
  try:
29
  data = await request.json()
30
  user_input = data.get("prompt", "")
31
- history = data.get("history", "")
32
 
33
- # ปรับปรุง System Rules ใ้เข้มงวดตี่คณแทนตงการ
34
- system_rules = (
35
- "You are TANZ AI, a friendly assistant created by Tae. "
36
- "Tae studies at Wangnoi(Phanomyong Wittaya) School. "
37
- "His friends are Tan, Ton, Mind, Golf, Wan, Keng. "
38
- "Tan's girlfriend is Phrae. Tan's mother is Tung. Tan's father is Phit/Daeng/Lek/Noppha. "
39
- "Ton's mother is Khao. Ton's father is Kong. "
40
- "STRICT RULES: "
41
- "1. If someone asks for Tae's location, say 'I cannot give that information ครับ'. "
42
- "2. Answer VERY SHORTLY and 100% ACCURATE to the provided facts only. "
43
- "3. If the question is NOT about the facts above, or you don't know the answer, "
44
- "you MUST say 'ผมไม่สามารถตอบคำถามนี้ได้ครับ'. Do not imagine or guess. "
45
- "4. Always end with 'ครับ'. Never use 'ค่ะ'."
46
- )
47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  prompt = (
49
- f"<|begin_of_text|><|start_header_id|>system<|end_header_id|>\n{system_rules}\n{history}<|eot_id|>"
50
  f"<|start_header_id|>user<|end_header_id|>\n{user_input}<|eot_id|>"
51
  f"<|start_header_id|>assistant<|end_header_id|>\n"
52
  )
53
 
54
- # ปรับความแม่นยำด้วยการตั้ค่า do_sample=False และ temperature ต่ำๆ
55
  outputs = pipe(
56
  prompt,
57
- max_new_tokens=40,
58
- do_sample=False, # บังคับให้ตอบแบบตยตัว ไสุ่มคำ
59
- repetition_penalty=1.1,
60
  eos_token_id=128009
61
  )
62
 
63
- # Extract response
64
  generated_text = outputs[0]["generated_text"]
65
  reply = generated_text.split("<|start_header_id|>assistant<|end_header_id|>")[-1].strip()
66
- reply = reply.replace("<|eot_id|>", "").replace("<|end_header_id|>", "").strip()
67
-
68
- # Fallback กรณี AI แอบตอบ่างอื่นที่ไม่ตรงตามกฎ (Double Check)
69
- if not reply:
 
70
  reply = "ผมไม่สามารถตอบคำถามนี้ได้ครับ"
71
 
72
  return {"reply": reply}
 
73
  except Exception as e:
74
  return {"reply": "เกิดข้อผิดพลาดในการประมวลผลครับ"}
75
 
76
  @app.get("/")
77
  def home():
78
- return {"status": "online"}
79
 
80
  if __name__ == "__main__":
 
 
 
 
 
81
  uvicorn.run(app, host="0.0.0.0", port=7860)
 
5
  import uvicorn
6
  import os
7
 
8
+ # Initialize the model (Llama-3.2-1B-Instruct)
9
  pipe = pipeline(
10
  "text-generation",
11
  model="unsloth/Llama-3.2-1B-Instruct",
 
15
 
16
  app = FastAPI()
17
 
 
18
  app.add_middleware(
19
  CORSMiddleware,
20
  allow_origins=["*"],
 
22
  allow_headers=["*"],
23
  )
24
 
25
+ def load_knowledge():
26
+ if os.path.exists("knowledge.txt"):
27
+ with open("knowledge.txt", "r", encoding="utf-8") as f:
28
+ return f.read().strip()
29
+ return "No data available."
30
+
31
  @app.post("/chat")
32
  async def chat(request: Request):
33
  try:
34
  data = await request.json()
35
  user_input = data.get("prompt", "")
 
36
 
37
+ # 1. ลดขู้ลจกไฟล์ทุกครั้งที่มีการถาม
38
+ kb_content = load_knowledge()
 
 
 
 
 
 
 
 
 
 
 
 
39
 
40
+ # 2. สร้าง System Prompt ที่เน้นการ "ตรวจสอบ" (Verification)
41
+ # เราจะสั่งให้ AI คิดก่อนตอบว่าข้อมูลนี้มีใน KB หรือไม่
42
+ verification_rules = (
43
+ "You are TANZ AI, a strict assistant. "
44
+ f"Here is your ONLY source of truth (Knowledge Base):\n###\n{kb_content}\n###\n"
45
+ "STRICT PROTOCOL:\n"
46
+ "1. If the user asks for Tae's location, reply: 'I cannot give that information ครับ'.\n"
47
+ "2. For any other question, check if the answer is explicitly stated in the Knowledge Base above.\n"
48
+ "3. If the answer is FOUND in the Knowledge Base, reply with a very short answer and end with 'ครับ'.\n"
49
+ "4. If the answer is NOT FOUND, NOT CERTAIN, or the user asks something general/outside the KB, "
50
+ "you MUST reply exactly: 'ผมไม่สามารถตอบคำถามนี้ได้ครับ'.\n"
51
+ "5. Do not use your own internal knowledge. Only use the provided Knowledge Base.\n"
52
+ "6. Always use 'ครับ'. Never use 'ค่ะ'."
53
+ )
54
+
55
  prompt = (
56
+ f"<|begin_of_text|><|start_header_id|>system<|end_header_id|>\n{verification_rules}<|eot_id|>"
57
  f"<|start_header_id|>user<|end_header_id|>\n{user_input}<|eot_id|>"
58
  f"<|start_header_id|>assistant<|end_header_id|>\n"
59
  )
60
 
61
+ # ปรับความแม่นยำสูสุด (Greedy Search)
62
  outputs = pipe(
63
  prompt,
64
+ max_new_tokens=50,
65
+ do_sample=False, # ห้ามสุ่มเด็ดขาดเพื่อให้ตรงตาม KB
66
+ repetition_penalty=1.2,
67
  eos_token_id=128009
68
  )
69
 
 
70
  generated_text = outputs[0]["generated_text"]
71
  reply = generated_text.split("<|start_header_id|>assistant<|end_header_id|>")[-1].strip()
72
+ reply = reply.replace("<|eot_id|>", "").strip()
73
+
74
+ # 3. Post-Process Verification (รวจสอบซ้ำด้วโค้ด)
75
+ # ถ้า AI พยายามต��บยาวเกินไป หรือเริ่มมีน้ำเยอะ ให้ตัดบททันที
76
+ if len(reply) > 150 or not reply:
77
  reply = "ผมไม่สามารถตอบคำถามนี้ได้ครับ"
78
 
79
  return {"reply": reply}
80
+
81
  except Exception as e:
82
  return {"reply": "เกิดข้อผิดพลาดในการประมวลผลครับ"}
83
 
84
  @app.get("/")
85
  def home():
86
+ return {"message": "TANZ AI Strict System Online"}
87
 
88
  if __name__ == "__main__":
89
+ # ตัวอย่างข้อมูลในไฟล์ knowledge.txt
90
+ if not os.path.exists("knowledge.txt"):
91
+ with open("knowledge.txt", "w", encoding="utf-8") as f:
92
+ f.write("Tae studies at Wangnoi(Phanomyong Wittaya) School. Ayutthaya is the old capital of Thailand.")
93
+
94
  uvicorn.run(app, host="0.0.0.0", port=7860)