thanglekdi commited on
Commit
d805091
·
1 Parent(s): 55f9458

test deepseek

Browse files
Files changed (3) hide show
  1. app.py +45 -63
  2. call_api.py +180 -180
  3. requirements.txt +1 -1
app.py CHANGED
@@ -1,78 +1,60 @@
1
  # app.py
2
  import gradio as gr
3
- # from openai import OpenAI # type: ignore
4
- import os
5
-
6
- # chat = gr.ChatInterface(
7
- # call_api.call_deepseek, #chat
8
- # title="Trợ Học Tập AI",
9
- # description="Nhập câu hỏi của bạn về Toán, Lý, Hóa, Văn… và nhận giải đáp chi tiết ngay lập tức!",
10
- # additional_inputs=[
11
- # gr.Textbox("Bạn một chatbot tiếng Việt thân thiện.", label="System message"),
12
- # gr.Slider(1, 2048, value=200, step=1, label="Max new tokens"),
13
- # gr.Slider(0.1, 4.0, value=0.7, step=0.1, label="Temperature"),
14
- # gr.Slider(0.1, 1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"),
15
 
16
- # gr.Image(label="Attach an image (optional)"), # báo lỗi
17
- # gr.File(label="Upload a file (optional)"), # báo lỗi
18
- # ],
19
- # # examples=[
20
- # # # Mỗi item: [message, system_message, max_tokens, temperature, top_p]
21
- # # ["tích phân của x^2 từ 0 đến 2 là gì? vui lòng lập luận từng bước, và đặt kết quả cuối cùng trong \boxed{}", "bạn là nhà toán học", 100, 0.7, 0.95],
22
- # # ],
23
- # )
24
-
25
-
26
 
 
 
 
27
 
28
- def call_deepseek_new(
29
- user_prompt,
30
- chat_history
31
- ):
32
- history = chat_history or []
33
- history.append({"role": "user", "content": user_prompt})
34
 
35
- # # Gọi API DeepSeek Chat (OpenAI-compatible, không stream)
36
- # response = deepseek.chat.completions.create(
37
- # model = "deepseek-chat", # hoặc model bạn đã config
38
- # messages = history,
39
- # )
40
 
41
- # Lấy nội dung assistant trả về
42
- reply = "response.choices[0].message.content"
43
 
44
- # Append vào history
45
- history.append({"role": "assistant", "content": reply})
46
 
47
- # Trả về 2 outputs: toàn bộ history và đúng reply để render Markdown
48
- return history, reply
49
 
50
- with gr.Blocks() as demo: # Bắt đầu Blocks
51
- # Thành phần hiển thị lịch sử chat
52
- chatbot = gr.Chatbot(type="messages") # hỗ trợ subset Markdown:contentReference[oaicite:3]{index=3}
53
 
54
- # Thành phần Markdown để render kết quả đã format (Markdown + LaTeX)
55
- markdown = gr.Markdown(
56
- latex_delimiters=[{"left": "$$", "right": "$$", "display": True}]
57
- ) # cho phép render LaTeX:contentReference[oaicite:4]{index=4}
58
 
59
- # Các input controls
60
- with gr.Row():
61
- txt = gr.Textbox(label="Nhập câu hỏi")
62
- sys_msg = gr.Textbox(value="Bạn một chatbot tiếng Việt thân thiện.", label="System message")
63
- with gr.Row():
64
- max_t = gr.Slider(1, 2048, value=500, step=1, label="Max new tokens")
65
- temp = gr.Slider(0.1, 4.0, value=0.7, step=0.1, label="Temperature")
66
- top_p = gr.Slider(0.1, 1.0, value=0.95, step=0.05, label="Top-p")
67
 
68
- # Sự kiện submit
69
- txt.submit(
70
- call_deepseek_new,
71
- inputs=[txt, chatbot],
72
- outputs=[chatbot, markdown],
73
- )
74
 
 
 
 
 
 
 
 
 
75
 
76
- # Chạy app
77
- if __name__ == "__main__":
78
- demo.launch(show_error=True)
 
 
 
 
1
  # app.py
2
  import gradio as gr
3
+ import call_api
4
+
5
+ chat = gr.ChatInterface(
6
+ call_api.call_deepseek, #chat
7
+ title="Trợ lý Học Tập AI",
8
+ description="Nhập câu hỏi của bạn về Toán, Lý, Hóa, Văn… và nhận giải đáp chi tiết ngay lập tức!",
9
+ additional_inputs=[
10
+ gr.Textbox("Bạn là một chatbot tiếng Việt thân thiện.", label="System message"),
11
+ gr.Slider(1, 2048, value=200, step=1, label="Max new tokens"),
12
+ gr.Slider(0.1, 4.0, value=0.7, step=0.1, label="Temperature"),
13
+ gr.Slider(0.1, 1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"),
 
14
 
15
+ gr.Image(label="Attach an image (optional)"), # báo lỗi
16
+ gr.File(label="Upload a file (optional)"), # báo lỗi
17
+ ],
18
+ # examples=[
19
+ # # Mỗi item: [message, system_message, max_tokens, temperature, top_p]
20
+ # ["tích phân của x^2 từ 0 đến 2 là gì? vui lòng lập luận từng bước, và đặt kết quả cuối cùng trong \boxed{}", "bạn là nhà toán học", 100, 0.7, 0.95],
21
+ # ],
22
+ )
 
 
23
 
24
+ # Chạy app
25
+ if __name__ == "__main__":
26
+ chat.launch(show_error=True)
27
 
 
 
 
 
 
 
28
 
 
 
 
 
 
29
 
 
 
30
 
 
 
31
 
 
 
32
 
 
 
 
33
 
34
+ """
 
 
 
35
 
36
+ """
37
+ # with gr.Blocks() as demo: # Bắt đầu Blocks
38
+ # # Thành phần hiển thị lịch sử chat
39
+ # chatbot = gr.Chatbot(type="messages") # hỗ trợ subset Markdown:contentReference[oaicite:3]{index=3}
 
 
 
 
40
 
41
+ # # Thành phần Markdown để render kết quả đã format (Markdown + LaTeX)
42
+ # markdown = gr.Markdown(
43
+ # latex_delimiters=[{"left": "$$", "right": "$$", "display": True}]
44
+ # ) # cho phép render LaTeX:contentReference[oaicite:4]{index=4}
 
 
45
 
46
+ # # Các input controls
47
+ # with gr.Row():
48
+ # txt = gr.Textbox(label="Nhập câu hỏi")
49
+ # sys_msg = gr.Textbox(value="Bạn là một chatbot tiếng Việt thân thiện.", label="System message")
50
+ # with gr.Row():
51
+ # max_t = gr.Slider(1, 2048, value=500, step=1, label="Max new tokens")
52
+ # temp = gr.Slider(0.1, 4.0, value=0.7, step=0.1, label="Temperature")
53
+ # top_p = gr.Slider(0.1, 1.0, value=0.95, step=0.05, label="Top-p")
54
 
55
+ # # Sự kiện submit
56
+ # txt.submit(
57
+ # call_deepseek_new,
58
+ # inputs=[txt, chatbot],
59
+ # outputs=[chatbot, markdown],
60
+ # )
call_api.py CHANGED
@@ -1,188 +1,188 @@
1
- # from openai import OpenAI # type: ignore
2
- # import os
3
-
4
-
5
- # def call_openai(
6
- # user_prompt,
7
- # chat_history: list[tuple[str, str]],
8
- # system_prompt,
9
- # max_tokens,
10
- # temperature,
11
- # top_p,
12
- # file_upload=None,
13
- # image_upload=None
14
- # ):
15
-
16
- # if file_upload == None:
17
- # try:
18
- # pass
19
- # except:
20
- # pass
21
-
22
- # if image_upload == None:
23
- # try:
24
- # pass
25
- # except:
26
- # pass
27
-
28
- # #read system message
29
- # messages = [{"role": "system", "content": system_prompt}]
30
 
31
- # #read history
32
- # for user_chat, assistant_chat in chat_history:
33
- # if user_chat:
34
- # messages.append({"role": "user", "content": user_chat})
35
- # if assistant_chat:
36
- # messages.append({"role": "assistant", "content": assistant_chat})
37
 
38
- # #read output
39
- # messages.append({"role": "user", "content": user_prompt})
40
- # print("## Messages: \n", messages) #debug output
41
-
42
- # #create output
43
- # response = OpenAI().responses.create(
44
- # model="gpt-4.1-nano",
45
- # input=messages,
46
- # temperature=temperature,
47
- # top_p=top_p,
48
- # max_output_tokens=max_tokens
49
- # )
50
-
51
- # #read output
52
- # response = response.output_text
53
- # print("## Response: ", response) #debug output
54
- # print("\n")
55
- # yield response #chat reply
56
-
57
- # deepseek = OpenAI(api_key = os.getenv("DEEPSEEK_API_KEY"), base_url="https://api.deepseek.com")
58
- # def call_deepseek(
59
- # user_prompt: str,
60
- # chat_history: list[tuple[str, str]],
61
- # system_prompt: str,
62
- # max_tokens: int,
63
- # temperature: float,
64
- # top_p: float,
65
- # file_upload=None,
66
- # image_upload=None
67
- # ):
68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  # """
70
- # Gọi DeepSeek Chat qua OpenAI-compatible API (không stream).
71
- # - file_upload và image_upload tùy chọn (None để bỏ qua xử lý).
72
  # Trả về:
73
- # - reply (str): nội dung model sinh ra.
74
  # """
75
- # # 1. Xử tùy chọn file (nếu có)
76
- # if file_upload == None:
77
- # try:
78
- # pass
79
- # except:
80
- # pass
81
-
82
- # if image_upload == None:
83
- # try:
84
- # pass
85
- # except:
86
- # pass
87
-
88
- # # 3. Xây dựng messages lịch sử chat
89
- # messages = [{"role": "system", "content": system_prompt}]
90
- # for user_msg, ai_msg in chat_history:
91
- # if user_msg:
92
- # messages.append({"role": "user", "content": user_msg})
93
- # if ai_msg:
94
- # messages.append({"role": "assistant", "content": ai_msg})
95
- # # Thêm prompt hiện tại của user
96
- # messages.append({"role": "user", "content": user_prompt})
97
-
98
- # # 4. Gọi API DeepSeek Chat (OpenAI-compatible)
99
- # response = OpenAI(api_key = os.getenv("DEEPSEEK_API_KEY"), base_url="https://api.deepseek.com").chat.completions.create(
100
- # model="deepseek-chat", # hoặc model bạn cấu hình
101
- # messages=messages,
102
- # temperature=temperature,
103
- # top_p=top_p,
104
- # max_tokens=max_tokens
105
- # )
106
-
107
- # # 5. Trích xuất kết quả trả về
108
- # reply = response.choices[0].message.content
109
- # return reply
110
-
111
- # # 1. Hàm gọi DeepSeek + build/append history
112
- # def call_deepseek_new(
113
- # user_prompt,
114
- # chat_history, # sẽ là [{"role":"user"/"assistant","content":...}, …]
115
- # # system_prompt: str,
116
- # # max_tokens: int,
117
- # # temperature: float,
118
- # # top_p: float,
119
- # # file_upload=None,
120
- # # image_upload=None
121
- # ):
122
- # # Khởi tạo history nếu None
123
- # history = chat_history or []
124
-
125
- # # Append system prompt (chỉ ở lần đầu nếu bạn muốn)
126
- # # if not any(m["role"]=="system" for m in history):
127
- # # history.insert(0, {"role": "system", "content": system_prompt})
128
-
129
- # # Append message mới của user
130
- # history.append({"role": "user", "content": user_prompt})
131
-
132
- # # Gọi API DeepSeek Chat (OpenAI-compatible, không stream)
133
- # response = deepseek.chat.completions.create(
134
- # model = "deepseek-chat", # hoặc model bạn đã config
135
- # messages = history,
136
- # # temperature= temperature,
137
- # # top_p = top_p,
138
- # # max_tokens = max_tokens
139
  # )
140
 
141
- # # Lấy nội dung assistant trả về
142
- # reply = response.choices[0].message.content
143
-
144
- # # Append vào history
145
- # history.append({"role": "assistant", "content": reply})
146
-
147
- # # Trả về 2 outputs: toàn bộ history và đúng reply để render Markdown
148
- # return history, reply
149
-
150
-
151
- # """
152
- # Không có billing nên không xài được replicate
153
- # """
154
- # # import replicate
155
-
156
- # # def deepseek_api_replicate(
157
- # # user_prompt,
158
- # # history: list[tuple[str, str]],
159
- # # system_prompt,
160
- # # max_new_tokens,
161
- # # temperature,
162
- # # top_p):
163
- # # """
164
- # # Gọi DeepSeek Math trên Replicate và trả ngay kết quả.
165
-
166
- # # Trả về:
167
- # # str hoặc [bytes]: output model sinh ra
168
- # # """
169
- # # # 1. Khởi tạo client và xác thực
170
- # # # token = os.getenv("REPLICATE_API_TOKEN")
171
- # # # if not token:
172
- # # # raise RuntimeError("Missing REPLICATE_API_TOKEN") # bảo mật bằng biến môi trường
173
- # # client = replicate.Client(api_token="REPLICATE_API_TOKEN")
174
-
175
- # # # 2. Gọi model
176
- # # output = client.run(
177
- # # "deepseek-ai/deepseek-math-7b-base:61f572dae0985541cdaeb4a114fd5d2d16cb40dac3894da10558992fc60547c7",
178
- # # input={
179
- # # "system_prompt": system_prompt,
180
- # # "user_prompt": user_prompt,
181
- # # "max_new_tokens": max_new_tokens,
182
- # # "temperature": temperature,
183
- # # "top_p": top_p
184
- # # }
185
- # # )
186
-
187
- # # # 3. Trả kết quả
188
- # # return output
 
1
+ from openai import OpenAI # type: ignore
2
+ import os
3
+
4
+
5
+ def call_openai(
6
+ user_prompt,
7
+ chat_history: list[tuple[str, str]],
8
+ system_prompt,
9
+ max_tokens,
10
+ temperature,
11
+ top_p,
12
+ file_upload=None,
13
+ image_upload=None
14
+ ):
15
+
16
+ if file_upload == None:
17
+ try:
18
+ pass
19
+ except:
20
+ pass
21
+
22
+ if image_upload == None:
23
+ try:
24
+ pass
25
+ except:
26
+ pass
27
+
28
+ #read system message
29
+ messages = [{"role": "system", "content": system_prompt}]
30
 
31
+ #read history
32
+ for user_chat, assistant_chat in chat_history:
33
+ if user_chat:
34
+ messages.append({"role": "user", "content": user_chat})
35
+ if assistant_chat:
36
+ messages.append({"role": "assistant", "content": assistant_chat})
37
 
38
+ #read output
39
+ messages.append({"role": "user", "content": user_prompt})
40
+ print("## Messages: \n", messages) #debug output
41
+
42
+ #create output
43
+ response = OpenAI().responses.create(
44
+ model="gpt-4.1-nano",
45
+ input=messages,
46
+ temperature=temperature,
47
+ top_p=top_p,
48
+ max_output_tokens=max_tokens
49
+ )
50
+
51
+ #read output
52
+ response = response.output_text
53
+ print("## Response: ", response) #debug output
54
+ print("\n")
55
+ yield response #chat reply
56
+
57
+ deepseek = OpenAI(api_key = os.getenv("DEEPSEEK_API_KEY"), base_url="https://api.deepseek.com")
58
+ def call_deepseek(
59
+ user_prompt: str,
60
+ chat_history: list[tuple[str, str]],
61
+ system_prompt: str,
62
+ max_tokens: int,
63
+ temperature: float,
64
+ top_p: float,
65
+ file_upload=None,
66
+ image_upload=None
67
+ ):
68
 
69
+ """
70
+ Gọi DeepSeek Chat qua OpenAI-compatible API (không stream).
71
+ - file_upload và image_upload tùy chọn (None để bỏ qua xử lý).
72
+ Trả về:
73
+ - reply (str): nội dung model sinh ra.
74
+ """
75
+ # 1. Xử lý tùy chọn file (nếu có)
76
+ if file_upload == None:
77
+ try:
78
+ pass
79
+ except:
80
+ pass
81
+
82
+ if image_upload == None:
83
+ try:
84
+ pass
85
+ except:
86
+ pass
87
+
88
+ # 3. Xây dựng messages lịch sử chat
89
+ messages = [{"role": "system", "content": system_prompt}]
90
+ for user_msg, ai_msg in chat_history:
91
+ if user_msg:
92
+ messages.append({"role": "user", "content": user_msg})
93
+ if ai_msg:
94
+ messages.append({"role": "assistant", "content": ai_msg})
95
+ # Thêm prompt hiện tại của user
96
+ messages.append({"role": "user", "content": user_prompt})
97
+
98
+ # 4. Gọi API DeepSeek Chat (OpenAI-compatible)
99
+ response = OpenAI(api_key = os.getenv("DEEPSEEK_API_KEY"), base_url="https://api.deepseek.com").chat.completions.create(
100
+ model="deepseek-chat", # hoặc model bạn cấu hình
101
+ messages=messages,
102
+ temperature=temperature,
103
+ top_p=top_p,
104
+ max_tokens=max_tokens
105
+ )
106
+
107
+ # 5. Trích xuất kết quả trả về
108
+ reply = response.choices[0].message.content
109
+ return reply
110
+
111
+ # 1. Hàm gọi DeepSeek + build/append history
112
+ def call_deepseek_new(
113
+ user_prompt,
114
+ chat_history, # sẽ là [{"role":"user"/"assistant","content":...}, …]
115
+ # system_prompt: str,
116
+ # max_tokens: int,
117
+ # temperature: float,
118
+ # top_p: float,
119
+ # file_upload=None,
120
+ # image_upload=None
121
+ ):
122
+ # Khởi tạo history nếu None
123
+ history = chat_history or []
124
+
125
+ # Append system prompt (chỉ ở lần đầu nếu bạn muốn)
126
+ # if not any(m["role"]=="system" for m in history):
127
+ # history.insert(0, {"role": "system", "content": system_prompt})
128
+
129
+ # Append message mới của user
130
+ history.append({"role": "user", "content": user_prompt})
131
+
132
+ # Gọi API DeepSeek Chat (OpenAI-compatible, không stream)
133
+ response = deepseek.chat.completions.create(
134
+ model = "deepseek-chat", # hoặc model bạn đã config
135
+ messages = history,
136
+ # temperature= temperature,
137
+ # top_p = top_p,
138
+ # max_tokens = max_tokens
139
+ )
140
+
141
+ # Lấy nội dung assistant trả về
142
+ reply = response.choices[0].message.content
143
+
144
+ # Append vào history
145
+ history.append({"role": "assistant", "content": reply})
146
+
147
+ # Trả về 2 outputs: toàn bộ history và đúng reply để render Markdown
148
+ return history, reply
149
+
150
+
151
+ """
152
+ Không có billing nên không xài được replicate
153
+ """
154
+ # import replicate
155
+
156
+ # def deepseek_api_replicate(
157
+ # user_prompt,
158
+ # history: list[tuple[str, str]],
159
+ # system_prompt,
160
+ # max_new_tokens,
161
+ # temperature,
162
+ # top_p):
163
  # """
164
+ # Gọi DeepSeek Math trên Replicate trả ngay kết quả.
165
+
166
  # Trả về:
167
+ # str hoặc [bytes]: output model sinh ra
168
  # """
169
+ # # 1. Khởi tạo client xác thực
170
+ # # token = os.getenv("REPLICATE_API_TOKEN")
171
+ # # if not token:
172
+ # # raise RuntimeError("Missing REPLICATE_API_TOKEN") # bảo mật bằng biến môi trường
173
+ # client = replicate.Client(api_token="REPLICATE_API_TOKEN")
174
+
175
+ # # 2. Gọi model
176
+ # output = client.run(
177
+ # "deepseek-ai/deepseek-math-7b-base:61f572dae0985541cdaeb4a114fd5d2d16cb40dac3894da10558992fc60547c7",
178
+ # input={
179
+ # "system_prompt": system_prompt,
180
+ # "user_prompt": user_prompt,
181
+ # "max_new_tokens": max_new_tokens,
182
+ # "temperature": temperature,
183
+ # "top_p": top_p
184
+ # }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
  # )
186
 
187
+ # # 3. Trả kết quả
188
+ # return output
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
requirements.txt CHANGED
@@ -1,5 +1,5 @@
1
  gradio
2
- # openai
3
  # replicate
4
  # torch
5
  # transformers
 
1
  gradio
2
+ openai
3
  # replicate
4
  # torch
5
  # transformers