anhkhoiphan commited on
Commit
2b16f16
·
verified ·
1 Parent(s): ca4a5bd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +116 -89
app.py CHANGED
@@ -1,67 +1,92 @@
1
  """
2
- Chainlit UI for AI Agent with Login/Registration
3
  """
4
 
5
  import chainlit as cl
6
- import requests
7
  from typing import Optional, Dict
8
  import json
9
  import os
 
10
 
11
  # API Configuration
12
  API_BASE_URL = os.getenv("API_BASE_URL")
13
 
 
 
 
 
14
  # ============================================
15
- # API HELPER FUNCTIONS
16
  # ============================================
17
 
18
- def check_user_exists(user_id: str) -> bool:
19
  """Check if user exists in the system"""
20
  try:
21
- response = requests.get(f"{API_BASE_URL}/user-exists/{user_id}")
22
- if response.status_code == 200:
23
- return response.json().get("exists", False)
 
 
 
 
24
  return False
25
  except Exception as e:
26
  print(f"Error checking user: {e}")
27
  return False
28
 
29
 
30
- def register_user(user_id: str) -> Dict:
31
  """Register a new user"""
32
  try:
33
- response = requests.post(
34
- f"{API_BASE_URL}/register",
35
- json={"user_id": user_id}
36
- )
37
- if response.status_code == 201:
38
- return {"success": True, "message": response.json().get("message", "Đăng ký thành công!")}
39
- else:
40
- error_msg = response.json().get("detail", "Đăng ký thất bại")
41
- return {"success": False, "message": error_msg}
 
 
 
 
 
42
  except Exception as e:
43
- return {"success": False, "message": f"Lỗi kết nối: {str(e)}"}
44
 
45
 
46
- def send_chat_message(query: str, user_id: str) -> Dict:
47
- """Send chat message to API"""
48
  try:
49
- response = requests.post(
50
- f"{API_BASE_URL}/chat",
51
- json={"query": query, "user_id": user_id}
52
- )
53
- if response.status_code == 200:
54
- data = response.json()
55
- return {
56
- "success": True,
57
- "answer": data.get("answer", ""),
58
- "references": data.get("references", "Không có tài liệu tham khảo")
59
- }
60
- else:
61
- error_msg = response.json().get("detail", "Lỗi xử câu hỏi")
62
- return {"success": False, "message": error_msg}
 
 
 
 
 
 
 
 
 
 
 
63
  except Exception as e:
64
- return {"success": False, "message": f"Lỗi kết nối API: {str(e)}"}
65
 
66
 
67
  # ============================================
@@ -171,12 +196,14 @@ async def handle_command(command: str):
171
  loading_msg = cl.Message(content="🔍 Đang kiểm tra tài khoản...", author="Kumiko")
172
  await loading_msg.send()
173
 
174
- # Check if user exists
175
- if check_user_exists(user_id):
176
- await loading_msg.remove()
 
 
 
177
  await show_chat_interface(user_id)
178
  else:
179
- await loading_msg.remove()
180
  await cl.Message(
181
  content=f"❌ User ID `{user_id}` không tồn tại!\n\nVui lòng đăng ký bằng: `/register {user_id}`",
182
  author="Kumiko"
@@ -198,8 +225,9 @@ async def handle_command(command: str):
198
  loading_msg = cl.Message(content="📝 Đang đăng ký tài khoản...", author="Kumiko")
199
  await loading_msg.send()
200
 
201
- # Register user
202
- result = register_user(user_id)
 
203
  await loading_msg.remove()
204
 
205
  if result["success"]:
@@ -238,44 +266,55 @@ Sau khi đăng nhập, bạn có thể chat bình thường. Hệ thống sẽ t
238
 
239
 
240
  async def process_chat_message(query: str, user_id: str):
241
- """Process chat message and display response"""
242
  # Show thinking message
243
  thinking_msg = cl.Message(content="🤔 Đang suy nghĩ...", author="Kumiko")
244
  await thinking_msg.send()
245
 
246
- # Send request to API
247
- result = send_chat_message(query, user_id)
248
-
249
- # Remove thinking message
250
- await thinking_msg.remove()
251
-
252
- if not result["success"]:
253
- await cl.Message(content=f"❌ Lỗi: {result['message']}", author="Kumiko").send()
254
- return
255
-
256
- answer = result["answer"]
257
- references = result["references"]
258
-
259
- # Store references in session for the button
260
- cl.user_session.set("last_references", references)
261
-
262
- # Create message with action button
263
- actions = [
264
- cl.Action(
265
- name="show_references",
266
- value="show",
267
- label="𝄢 Tài liệu tham khảo",
268
- description="Xem các nguồn tham khảo",
269
- payload={"references": references}
270
- )
271
- ]
272
-
273
- # Send answer with reference button
274
- await cl.Message(
275
- content=answer,
276
- actions=actions,
277
- author="Kumiko"
278
- ).send()
 
 
 
 
 
 
 
 
 
 
 
279
 
280
 
281
  @cl.action_callback("show_references")
@@ -299,6 +338,7 @@ async def end():
299
  """Handle chat end"""
300
  print("Chat session ended")
301
 
 
302
  # ============================================
303
  # CONFIGURATION
304
  # ============================================
@@ -321,17 +361,4 @@ async def set_starters():
321
  label="Trợ giúp",
322
  message="/help",
323
  ),
324
- ]
325
-
326
-
327
- # Custom CSS (optional - save as .chainlit/config.toml)
328
- # """
329
- # [UI]
330
- # name = "AI Agent Chat"
331
- # default_collapse_content = true
332
- # default_expand_messages = false
333
- # hide_cot = false
334
-
335
- # [UI.theme]
336
- # primary_color = "#2563eb"
337
- # """
 
1
  """
2
+ Chainlit UI for AI Agent with Login/Registration - FIXED VERSION
3
  """
4
 
5
  import chainlit as cl
6
+ import httpx # Thay thế requests bằng httpx cho async support
7
  from typing import Optional, Dict
8
  import json
9
  import os
10
+ import asyncio
11
 
12
  # API Configuration
13
  API_BASE_URL = os.getenv("API_BASE_URL")
14
 
15
+ # Timeout settings (giây)
16
+ API_TIMEOUT = 300.0 # 5 phút cho chat API (có thể điều chỉnh)
17
+ AUTH_TIMEOUT = 30.0 # 30 giây cho login/register
18
+
19
  # ============================================
20
+ # API HELPER FUNCTIONS - CONVERTED TO ASYNC
21
  # ============================================
22
 
23
+ async def check_user_exists(user_id: str) -> bool:
24
  """Check if user exists in the system"""
25
  try:
26
+ async with httpx.AsyncClient(timeout=AUTH_TIMEOUT) as client:
27
+ response = await client.get(f"{API_BASE_URL}/user-exists/{user_id}")
28
+ if response.status_code == 200:
29
+ return response.json().get("exists", False)
30
+ return False
31
+ except httpx.TimeoutException:
32
+ print(f"Timeout checking user: {user_id}")
33
  return False
34
  except Exception as e:
35
  print(f"Error checking user: {e}")
36
  return False
37
 
38
 
39
+ async def register_user(user_id: str) -> Dict:
40
  """Register a new user"""
41
  try:
42
+ async with httpx.AsyncClient(timeout=AUTH_TIMEOUT) as client:
43
+ response = await client.post(
44
+ f"{API_BASE_URL}/register",
45
+ json={"user_id": user_id}
46
+ )
47
+ if response.status_code == 201:
48
+ return {"success": True, "message": response.json().get("message", "Đăng ký thành công!")}
49
+ else:
50
+ error_msg = response.json().get("detail", "Đăng ký thất bại")
51
+ return {"success": False, "message": error_msg}
52
+ except httpx.TimeoutException:
53
+ return {"success": False, "message": "Timeout: Server không phản hồi"}
54
+ except httpx.ConnectError:
55
+ return {"success": False, "message": "Không thể kết nối đến server"}
56
  except Exception as e:
57
+ return {"success": False, "message": f"Lỗi: {str(e)}"}
58
 
59
 
60
+ async def send_chat_message(query: str, user_id: str) -> Dict:
61
+ """Send chat message to API with streaming support"""
62
  try:
63
+ # Sử dụng timeout dài hơn cho chat vì có thể xử lý lâu
64
+ async with httpx.AsyncClient(timeout=API_TIMEOUT) as client:
65
+ response = await client.post(
66
+ f"{API_BASE_URL}/chat",
67
+ json={"query": query, "user_id": user_id}
68
+ )
69
+
70
+ if response.status_code == 200:
71
+ data = response.json()
72
+ return {
73
+ "success": True,
74
+ "answer": data.get("answer", ""),
75
+ "references": data.get("references", "Không tài liệu tham khảo")
76
+ }
77
+ else:
78
+ error_msg = response.json().get("detail", "Lỗi xử lý câu hỏi")
79
+ return {"success": False, "message": error_msg}
80
+
81
+ except httpx.TimeoutException:
82
+ return {
83
+ "success": False,
84
+ "message": f"⏱️ Server đang xử lý quá lâu (>{API_TIMEOUT}s). Vui lòng thử lại hoặc đặt câu hỏi đơn giản hơn."
85
+ }
86
+ except httpx.ConnectError:
87
+ return {"success": False, "message": "❌ Không thể kết nối đến server. Vui lòng kiểm tra API_BASE_URL."}
88
  except Exception as e:
89
+ return {"success": False, "message": f"Lỗi: {str(e)}"}
90
 
91
 
92
  # ============================================
 
196
  loading_msg = cl.Message(content="🔍 Đang kiểm tra tài khoản...", author="Kumiko")
197
  await loading_msg.send()
198
 
199
+ # Check if user exists (now async)
200
+ exists = await check_user_exists(user_id)
201
+
202
+ await loading_msg.remove()
203
+
204
+ if exists:
205
  await show_chat_interface(user_id)
206
  else:
 
207
  await cl.Message(
208
  content=f"❌ User ID `{user_id}` không tồn tại!\n\nVui lòng đăng ký bằng: `/register {user_id}`",
209
  author="Kumiko"
 
225
  loading_msg = cl.Message(content="📝 Đang đăng ký tài khoản...", author="Kumiko")
226
  await loading_msg.send()
227
 
228
+ # Register user (now async)
229
+ result = await register_user(user_id)
230
+
231
  await loading_msg.remove()
232
 
233
  if result["success"]:
 
266
 
267
 
268
  async def process_chat_message(query: str, user_id: str):
269
+ """Process chat message and display response with progress updates"""
270
  # Show thinking message
271
  thinking_msg = cl.Message(content="🤔 Đang suy nghĩ...", author="Kumiko")
272
  await thinking_msg.send()
273
 
274
+ try:
275
+ # Tạo task để track progress
276
+ start_time = asyncio.get_event_loop().time()
277
+
278
+ # Send request to API (now async)
279
+ result = await send_chat_message(query, user_id)
280
+
281
+ # Remove thinking message
282
+ await thinking_msg.remove()
283
+
284
+ if not result["success"]:
285
+ await cl.Message(content=f"{result['message']}", author="Kumiko").send()
286
+ return
287
+
288
+ answer = result["answer"]
289
+ references = result["references"]
290
+
291
+ # Store references in session for the button
292
+ cl.user_session.set("last_references", references)
293
+
294
+ # Create message with action button
295
+ actions = [
296
+ cl.Action(
297
+ name="show_references",
298
+ value="show",
299
+ label="𝄢 Tài liệu tham khảo",
300
+ description="Xem các nguồn tham khảo",
301
+ payload={"references": references}
302
+ )
303
+ ]
304
+
305
+ # Send answer with reference button
306
+ await cl.Message(
307
+ content=answer,
308
+ actions=actions,
309
+ author="Kumiko"
310
+ ).send()
311
+
312
+ except Exception as e:
313
+ await thinking_msg.remove()
314
+ await cl.Message(
315
+ content=f"❌ Đã xảy ra lỗi không mong muốn: {str(e)}",
316
+ author="Kumiko"
317
+ ).send()
318
 
319
 
320
  @cl.action_callback("show_references")
 
338
  """Handle chat end"""
339
  print("Chat session ended")
340
 
341
+
342
  # ============================================
343
  # CONFIGURATION
344
  # ============================================
 
361
  label="Trợ giúp",
362
  message="/help",
363
  ),
364
+ ]