mrbui1990 commited on
Commit
30a4018
·
verified ·
1 Parent(s): 8551cf4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +103 -24
app.py CHANGED
@@ -14,45 +14,124 @@ model = AutoModelForCausalLM.from_pretrained(
14
  )
15
 
16
  @spaces.GPU(duration=60) # cấp GPU tạm cho 1 phút
17
- def chat_with_model(prompt, system_prompt):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
- # 1. Tạo danh sách messages theo chuẩn ChatML
20
- messages = [
21
- {"role": "system", "content": system_prompt},
22
- {"role": "user", "content": prompt}
23
- ]
24
 
25
- # 2. Dùng apply_chat_template để tokenizer tự động thêm các thẻ <|im_start|>
 
 
 
26
  inputs = tokenizer.apply_chat_template(
27
- messages,
28
  tokenize=True,
29
- add_generation_prompt=True, # Thêm thẻ <|im_start|>assistant
30
  return_tensors="pt"
31
  ).to(model.device)
32
 
33
- # 3. Generate
34
  output_tokens = model.generate(
35
  inputs,
36
- max_new_tokens=10024,
37
  do_sample=True,
38
  temperature=0.7,
39
  top_p=0.9
40
  )
41
 
42
- # 4. Decode (chỉ decode phần nội dung mới, bỏ qua phần prompt)
43
  response_text = tokenizer.decode(output_tokens[0][inputs.shape[-1]:], skip_special_tokens=True)
44
- return response_text
45
-
46
- # Cập nhật Gradio Interface
47
- demo = gr.Interface(
48
- fn=chat_with_model,
49
- inputs=[
50
- gr.Textbox(label="Prompt"),
51
- gr.Textbox(label="System Prompt", value="You are an uncensored and helpful AI assistant.", lines=15) # Đặt ví dụ 2 làm mặc định
52
- ],
53
- outputs="text",
54
- title="Xyntrai-Mistral 2.5 7B Chat"
55
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
  if __name__ == "__main__":
58
  demo.launch()
 
14
  )
15
 
16
  @spaces.GPU(duration=60) # cấp GPU tạm cho 1 phút
17
+ def chat_with_model(prompt, system_prompt, chatbot_display, internal_history):
18
+ """
19
+ Hàm này nhận prompt mới, system_prompt, lịch sử hiển thị (của gr.Chatbot)
20
+ và lịch sử nội bộ (của gr.State).
21
+ """
22
+
23
+ # 1. Khởi tạo nếu đây là lần chạy đầu tiên
24
+ # chatbot_display là [[user_msg, ai_msg], ...]
25
+ if chatbot_display is None:
26
+ chatbot_display = []
27
+ # internal_history là [{"role": "user", ...}, {"role": "assistant", ...}]
28
+ if internal_history is None:
29
+ internal_history = []
30
+
31
+ # 2. Xây dựng toàn bộ lịch sử để đưa cho model
32
+ # Bắt đầu với System Prompt (luôn lấy cái mới nhất từ Textbox)
33
+ messages_for_model = [{"role": "system", "content": system_prompt}]
34
 
35
+ # Thêm toàn bộ các lượt nói (user/assistant) từ "bộ nhớ" gr.State
36
+ messages_for_model.extend(internal_history)
 
 
 
37
 
38
+ # Thêm prompt MỚI của người dùng
39
+ messages_for_model.append({"role": "user", "content": prompt})
40
+
41
+ # 3. Áp dụng Chat Template
42
  inputs = tokenizer.apply_chat_template(
43
+ messages_for_model,
44
  tokenize=True,
45
+ add_generation_prompt=True,
46
  return_tensors="pt"
47
  ).to(model.device)
48
 
49
+ # 4. Generate
50
  output_tokens = model.generate(
51
  inputs,
52
+ max_new_tokens=5120, # Tăng số token tối đa lên một chút
53
  do_sample=True,
54
  temperature=0.7,
55
  top_p=0.9
56
  )
57
 
58
+ # 5. Decode *chỉ* phần trả lời mới
59
  response_text = tokenizer.decode(output_tokens[0][inputs.shape[-1]:], skip_special_tokens=True)
60
+
61
+ # 6. Cập nhật "bộ nhớ" (gr.State) với lượt nói MỚI
62
+ internal_history.append({"role": "user", "content": prompt})
63
+ internal_history.append({"role": "assistant", "content": response_text})
64
+
65
+ # 7. Cập nhật lịch sử hiển thị (gr.Chatbot)
66
+ chatbot_display.append([prompt, response_text])
67
+
68
+ # 8. Trả về cả hai để cập nhật UI
69
+ # (chuỗi rỗng "" để xóa nội dung trong ô prompt_box)
70
+ return "", chatbot_display, internal_history
71
+
72
+ def clear_chat():
73
+ """Xóa lịch sử."""
74
+ return None, None
75
+
76
+ # --- 4. Xây dựng giao diện Gradio Blocks ---
77
+ with gr.Blocks(theme=gr.themes.Monochrome()) as demo:
78
+ # "Bộ nhớ" ẩn để lưu lịch sử ChatML (list of dicts)
79
+ internal_history = gr.State()
80
+
81
+ gr.Markdown("# 💬 Xyntrai-Mistral 2.5 7B (Có trí nhớ)")
82
+
83
+ with gr.Row():
84
+ with gr.Column(scale=3):
85
+ # Khung chat chính
86
+ chatbot_display = gr.Chatbot(
87
+ label="Chat History",
88
+ bubble_full_width=False,
89
+ height=500
90
+ )
91
+
92
+ # Ô nhập prompt
93
+ prompt_box = gr.Textbox(
94
+ label="Your Message",
95
+ placeholder="Nhập tin nhắn của bạn và nhấn Enter...",
96
+ lines=1
97
+ )
98
+
99
+ with gr.Row():
100
+ clear_button = gr.Button("Clear Chat")
101
+ # Nút submit này ẩn đi, chúng ta dùng Enter từ prompt_box
102
+ submit_button = gr.Button("Send", visible=False)
103
+
104
+ with gr.Column(scale=1):
105
+ # Ô System Prompt
106
+ system_prompt_box = gr.Textbox(
107
+ label="System Prompt (AI's Role & Rules)",
108
+ value=SYSTEM_PROMPT_DEFAULT,
109
+ lines=30
110
+ )
111
+
112
+ # --- 5. Kết nối các hành động ---
113
+
114
+ # Khi người dùng nhấn Enter trong `prompt_box`
115
+ prompt_box.submit(
116
+ fn=chat_with_model,
117
+ inputs=[prompt_box, system_prompt_box, chatbot_display, internal_history],
118
+ outputs=[prompt_box, chatbot_display, internal_history]
119
+ )
120
+
121
+ # Khi người dùng nhấn nút "Send" (ẩn)
122
+ submit_button.click(
123
+ fn=chat_with_model,
124
+ inputs=[prompt_box, system_prompt_box, chatbot_display, internal_history],
125
+ outputs=[prompt_box, chatbot_display, internal_history]
126
+ )
127
+
128
+ # Khi người dùng nhấn nút "Clear Chat"
129
+ clear_button.click(
130
+ fn=clear_chat,
131
+ inputs=None,
132
+ outputs=[chatbot_display, internal_history]
133
+ )
134
+
135
 
136
  if __name__ == "__main__":
137
  demo.launch()