NamQT commited on
Commit
cf587bc
·
verified ·
1 Parent(s): 6e27bed

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +116 -48
app.py CHANGED
@@ -1,70 +1,138 @@
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
  def respond(
6
  message,
7
- history: list[dict[str, str]],
8
  system_message,
9
  max_tokens,
10
  temperature,
11
  top_p,
 
12
  hf_token: gr.OAuthToken,
13
  ):
14
- """
15
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
16
- """
17
- client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
 
 
 
18
 
19
- messages = [{"role": "system", "content": system_message}]
 
20
 
21
- messages.extend(history)
 
 
 
 
 
22
 
 
23
  messages.append({"role": "user", "content": message})
24
 
 
25
  response = ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
 
27
- for message in client.chat_completion(
28
- messages,
29
- max_tokens=max_tokens,
30
- stream=True,
31
- temperature=temperature,
32
- top_p=top_p,
33
- ):
34
- choices = message.choices
35
- token = ""
36
- if len(choices) and choices[0].delta.content:
37
- token = choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- chatbot = gr.ChatInterface(
47
- respond,
48
- type="messages",
49
- additional_inputs=[
50
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
51
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
52
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
53
- gr.Slider(
54
- minimum=0.1,
55
- maximum=1.0,
56
- value=0.95,
57
- step=0.05,
58
- label="Top-p (nucleus sampling)",
59
- ),
60
- ],
61
- )
62
 
63
- with gr.Blocks() as demo:
64
- with gr.Sidebar():
65
- gr.LoginButton()
66
- chatbot.render()
 
 
 
 
 
 
 
 
 
67
 
 
 
 
68
 
69
- if __name__ == "__main__":
70
- demo.launch()
 
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
 
4
+ # ================================
5
+ # CẤU HÌNH NHẬN THỨC CỦA AI (TÙY CHỈNH TẠI ĐÂY)
6
+ # ================================
7
+ AI_NAME = "AI Assistant"
8
+ AI_CREATOR = "AI "
9
+ AI_DESCRIPTION = (
10
+ "Tôi là một trợ lý trí tuệ nhân tạo được tạo ra bởi Trương Quốc Nam. "
11
+ "Tôi được huấn luyện để hỗ trợ học tập, giải đáp thắc mắc bằng tiếng Việt một cách thân thiện, chính xác và giàu thông tin. "
12
+ "Tôi luôn cố gắng trả lời ngắn gọn, dễ hiểu và có ví dụ minh họa khi cần."
13
+ )
14
+
15
+ DEFAULT_SYSTEM_MESSAGE = f"""
16
+ Bạn là {AI_NAME}, một trợ lý AI thông minh và thân thiện.
17
+ {AI_DESCRIPTION}
18
+
19
+ Khi được hỏi "bạn là ai", "ai tạo ra bạn", "ai làm ra bạn", hãy trả lời tự nhiên, ví dụ:
20
+ "Tôi là {AI_NAME}, được tạo ra bởi {AI_CREATOR} để hỗ trợ mọi người học tập và khám phá tri thức!"
21
+
22
+ Luôn trả lời bằng tiếng Việt, lịch sự, rõ ràng và có tính giáo dục.
23
+ """.strip()
24
+
25
+ # ================================
26
+ # MODEL MẠNH + HỖ TRỢ TIẾNG VIỆT TỐT NHẤT 2025 (miễn phí)
27
+ # ================================
28
+ # Bạn có thể thay bằng các model khác:
29
+ # - "Qwen/Qwen2.5-72B-Instruct" → cực mạnh, hiểu sâu tiếng Việt
30
+ # - "meta-llama/Meta-Llama-3.1-70B-Instruct"
31
+ # - "vinai/PhoGPT-7B5-Instruct"
32
+ # - "mistralai/Mistral-7B-Instruct-v0.3"
33
+ DEFAULT_MODEL = "Qwen/Qwen2.5-72B-Instruct" # Đề xuất: nhanh + thông minh + hiểu sâu văn hóa VN
34
 
35
  def respond(
36
  message,
37
+ history: list,
38
  system_message,
39
  max_tokens,
40
  temperature,
41
  top_p,
42
+ model_name,
43
  hf_token: gr.OAuthToken,
44
  ):
45
+ # Nếu người dùng chưa đăng nhập → thông báo nhẹ nhàng
46
+ if hf_token is None or hf_token.token is None:
47
+ yield "Vui lòng đăng nhập Hugging Face (nút bên trái) để sử dụng chatbot nhé! 😊"
48
+ return
49
+
50
+ # Tạo client với token tự động
51
+ client = InferenceClient(token=hf_token.token)
52
 
53
+ # Tạo danh sách tin nhắn theo chuẩn OpenAI
54
+ messages = [{"role": "system", "content": system_message or DEFAULT_SYSTEM_MESSAGE}]
55
 
56
+ # Thêm lịch sử chat
57
+ for user_msg, assistant_msg in history:
58
+ if user_msg:
59
+ messages.append({"role": "user", "content": user_msg})
60
+ if assistant_msg:
61
+ messages.append({"role": "assistant", "content": assistant_msg})
62
 
63
+ # Thêm tin nhắn mới
64
  messages.append({"role": "user", "content": message})
65
 
66
+ # Streaming response
67
  response = ""
68
+ try:
69
+ for chunk in client.chat_completion(
70
+ messages,
71
+ model=model_name or DEFAULT_MODEL,
72
+ max_tokens=max_tokens,
73
+ temperature=temperature,
74
+ top_p=top_p,
75
+ stream=True,
76
+ ):
77
+ if chunk.choices and chunk.choices[0].delta.content:
78
+ token = chunk.choices[0].delta.content
79
+ response += token
80
+ yield response
81
+ except Exception as e:
82
+ yield f"Xin lỗi, có lỗi xảy ra: {str(e)}\nBạn thử lại hoặc chọn model nhẹ hơn nhé!"
83
 
84
+ # ================================
85
+ # GIAO DIỆN GRADIO ĐẸP + DỄ DÙNG
86
+ # ================================
87
+ with gr.Blocks(title=f"{AI_NAME} - Trợ lý AI của HHH", theme=gr.themes.Soft()) as demo:
88
+ gr.Markdown(f"# 🤖 {AI_NAME}\n{AI_DESCRIPTION}")
89
+
90
+ with gr.Row():
91
+ with gr.Column(scale=1):
92
+ gr.LoginButton() # Nút đăng nhập Hugging Face (bắt buộc để dùng Inference API an toàn)
93
+ gr.Markdown("##### Cài đặt nâng cao")
94
+
95
+ model_dropdown = gr.Dropdown(
96
+ label="Chọn hình AI",
97
+ choices=[
98
+ "Qwen/Qwen2.5-72B-Instruct",
99
+ "meta-llama/Meta-Llama-3.1-70B-Instruct",
100
+ "mistralai/Mistral-7B-Instruct-v0.3",
101
+ "vinai/PhoGPT-7B5-Instruct",
102
+ "google/gemma-2-27b-it",
103
+ ],
104
+ value=DEFAULT_MODEL,
105
+ allow_custom_value=True,
106
+ )
107
+
108
+ system_box = gr.Textbox(
109
+ label="System Prompt (nhận thức của AI)",
110
+ value=DEFAULT_SYSTEM_MESSAGE,
111
+ lines=6,
112
+ )
113
+
114
+ with gr.Accordion("Tham số kỹ thuật", open=False):
115
+ max_tokens = gr.Slider(1, 4096, value=1024, step=64, label="Max tokens")
116
+ temperature = gr.Slider(0.1, 2.0, value=0.7, step=0.1, label="Temperature")
117
+ top_p = gr.Slider(0.1, 1.0, value=0.95, step=0.05, label="Top-p")
 
118
 
119
+ with gr.Column(scale=3):
120
+ chatbot = gr.ChatInterface(
121
+ fn=respond,
122
+ type="messages",
123
+ autofocus=True,
124
+ additional_inputs=[
125
+ system_box,
126
+ max_tokens,
127
+ temperature,
128
+ top_p,
129
+ model_dropdown,
130
+ ],
131
+ )
132
 
133
+ gr.Markdown(
134
+ "<small>© 2025 - Được xây dựng bởi HHH | Dùng công nghệ Hugging Face Spaces + OAuth (không lộ token)</small>"
135
+ )
136
 
137
+ if __name__ == "app":
138
+ demo.launch()