mrbui1990 commited on
Commit
8abbd5c
·
verified ·
1 Parent(s): 34afcf5

Update app.py

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