minh-4T commited on
Commit
b0da662
·
verified ·
1 Parent(s): c6458da

Thêm vào các Endpoint mới để lấy ra được danh sách các đoạn hội thoại và nội dung của nó.

Files changed (1) hide show
  1. main.py +59 -16
main.py CHANGED
@@ -15,6 +15,7 @@ from core.config import QDRANT_URL, QDRANT_API_KEY, DATABASE_URL
15
  from core.vectorstore import build_vectorstore_improved, load_vectorstore_improved
16
  from core.retriever import HybridRetriever
17
  from core.qa_pipeline import ask_ai_improved, ask_ai_stream_delta
 
18
  # Hàm log lỗi an toàn
19
  logging.basicConfig(level=logging.INFO)
20
  logger = logging.getLogger(__name__)
@@ -22,15 +23,17 @@ MAX_HISTORY_MESSAGES = int(os.getenv("MAX_HISTORY_MESSAGES", "20"))
22
  POOL_MIN_SIZE = int(os.getenv("DB_POOL_MIN_SIZE", "1"))
23
  POOL_MAX_SIZE = int(os.getenv("DB_POOL_MAX_SIZE", "10"))
24
 
25
- # Khởi tạo database để lưu lịch sử trò chuyện
26
  async def init_db_asyncpg(pool: asyncpg.Pool):
27
  async with pool.acquire() as conn:
28
  await conn.execute('''
29
  CREATE TABLE IF NOT EXISTS history (
30
  id SERIAL PRIMARY KEY,
31
  session_id TEXT NOT NULL,
 
32
  role TEXT NOT NULL,
33
  content TEXT NOT NULL,
 
34
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
35
  )
36
  ''')
@@ -38,11 +41,28 @@ async def init_db_asyncpg(pool: asyncpg.Pool):
38
  ALTER TABLE history
39
  ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
40
  ''')
 
 
 
 
41
  await conn.execute('''
42
  CREATE INDEX IF NOT EXISTS idx_history_session_id_id
43
  ON history(session_id, id)
44
  ''')
45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
46
  async def get_history_async(pool: asyncpg.Pool, session_id: str):
47
  try:
48
  query = """
@@ -60,21 +80,24 @@ async def get_history_async(pool: asyncpg.Pool, session_id: str):
60
  logger.exception("Lỗi khi truy vấn lịch sử trò chuyện:", exc_info=True)
61
  return []
62
 
63
- async def save_turn_async(pool: asyncpg.Pool, session_id: str, user_msg: str, assistant_msg: str):
 
64
  try:
65
  async with pool.acquire() as conn:
 
 
 
 
 
 
66
  async with conn.transaction():
67
  await conn.execute(
68
- "INSERT INTO history (session_id, role, content) VALUES ($1, $2, $3)",
69
- session_id,
70
- "user",
71
- user_msg,
72
  )
73
  await conn.execute(
74
- "INSERT INTO history (session_id, role, content) VALUES ($1, $2, $3)",
75
- session_id,
76
- "assistant",
77
- assistant_msg,
78
  )
79
  except Exception:
80
  logger.exception("Lỗi khi lưu lượt hội thoại:", exc_info=True)
@@ -128,6 +151,7 @@ def get_runtime_components(request: Request):
128
 
129
  #Cấu hình FastAPI với middleware CORS và lifespan để quản lý trạng thái hệ thống
130
  app = FastAPI(lifespan=lifespan, title= "RAG API SERVER")
 
131
  #Cho phép truy cập từ mọi nguồn
132
  allow_origins = [origin.strip() for origin in os.getenv("ALLOW_ORIGINS", "*").split(",") if origin.strip()]
133
  if not allow_origins:
@@ -143,6 +167,7 @@ app.add_middleware(
143
  #Định nghĩa Endpoint
144
  class ChatRequest(BaseModel):
145
  session_id: str
 
146
  message: str
147
 
148
  class ChatResponse(BaseModel):
@@ -154,7 +179,23 @@ async def health_check(request: Request):
154
  ready = bool(getattr(request.app.state, "retriever", None) and getattr(request.app.state, "db_pool", None))
155
  return {"status": "ok" if ready else "starting", "ready": ready}
156
 
157
- # Endpoint JSON thường (non-streaming) - trả toàn bộ câu trả lời một lúc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158
  @app.post("/chat", response_model=ChatResponse)
159
  async def chat_endpoint(payload: ChatRequest, request: Request):
160
  """Endpoint chat thông thường - trả JSON response đầy đủ"""
@@ -164,6 +205,7 @@ async def chat_endpoint(payload: ChatRequest, request: Request):
164
  raise HTTPException(status_code=400, detail="Bạn chưa nhập câu hỏi")
165
 
166
  session_id = payload.session_id
 
167
  history = await get_history_async(db_pool, session_id)
168
 
169
  # Tập hợp toàn bộ response từ generator
@@ -175,8 +217,8 @@ async def chat_endpoint(payload: ChatRequest, request: Request):
175
  logger.exception("Lỗi khi xử lý phản hồi từ AI:", exc_info=True)
176
  raise HTTPException(status_code=500, detail="Lỗi khi xử lý yêu cầu")
177
 
178
- # Lưu lịch sử sau khi có response đầy đủ
179
- await save_turn_async(db_pool, session_id, user_msg, full_response)
180
 
181
  return ChatResponse(response=full_response)
182
 
@@ -190,6 +232,7 @@ async def chat_stream_endpoint(payload: ChatRequest, request: Request):
190
  raise HTTPException(status_code=400, detail="Bạn chưa nhập câu hỏi")
191
 
192
  session_id = payload.session_id
 
193
  history = await get_history_async(db_pool, session_id)
194
 
195
  async def event_stream_generator():
@@ -206,8 +249,8 @@ async def chat_stream_endpoint(payload: ChatRequest, request: Request):
206
  # Gửi tín hiệu kết thúc
207
  yield 'data: {"delta": "", "done": true}\n\n'
208
 
209
- # Lưu lịch sử sau khi stream xong
210
- await save_turn_async(db_pool, session_id, user_msg, full_response)
211
 
212
  except Exception:
213
  logger.exception("Lỗi khi stream phản hồi từ AI:", exc_info=True)
@@ -227,4 +270,4 @@ async def chat_stream_endpoint(payload: ChatRequest, request: Request):
227
  if __name__ == "__main__":
228
  import uvicorn
229
  port = int(os.getenv("PORT", "7860"))
230
- uvicorn.run(app, host="0.0.0.0", port=port)
 
15
  from core.vectorstore import build_vectorstore_improved, load_vectorstore_improved
16
  from core.retriever import HybridRetriever
17
  from core.qa_pipeline import ask_ai_improved, ask_ai_stream_delta
18
+
19
  # Hàm log lỗi an toàn
20
  logging.basicConfig(level=logging.INFO)
21
  logger = logging.getLogger(__name__)
 
23
  POOL_MIN_SIZE = int(os.getenv("DB_POOL_MIN_SIZE", "1"))
24
  POOL_MAX_SIZE = int(os.getenv("DB_POOL_MAX_SIZE", "10"))
25
 
26
+ # Khởi tạo database để lưu lịch sử trò chuyện
27
  async def init_db_asyncpg(pool: asyncpg.Pool):
28
  async with pool.acquire() as conn:
29
  await conn.execute('''
30
  CREATE TABLE IF NOT EXISTS history (
31
  id SERIAL PRIMARY KEY,
32
  session_id TEXT NOT NULL,
33
+ user_id TEXT,
34
  role TEXT NOT NULL,
35
  content TEXT NOT NULL,
36
+ title TEXT,
37
  created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
38
  )
39
  ''')
 
41
  ALTER TABLE history
42
  ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
43
  ''')
44
+ # 2 lệnh ALTER TABLE để cập nhật bảng cũ nếu đã tồn tại
45
+ await conn.execute('ALTER TABLE history ADD COLUMN IF NOT EXISTS user_id TEXT')
46
+ await conn.execute('ALTER TABLE history ADD COLUMN IF NOT EXISTS title TEXT')
47
+
48
  await conn.execute('''
49
  CREATE INDEX IF NOT EXISTS idx_history_session_id_id
50
  ON history(session_id, id)
51
  ''')
52
 
53
+ # Hàm lấy danh sách phiên chat theo user_id
54
+ async def get_user_sessions_async(pool: asyncpg.Pool, user_id: str):
55
+ query = """
56
+ SELECT DISTINCT ON (session_id)
57
+ session_id, title, created_at
58
+ FROM history
59
+ WHERE user_id = $1
60
+ ORDER BY session_id, created_at DESC
61
+ """
62
+ async with pool.acquire() as conn:
63
+ rows = await conn.fetch(query, user_id)
64
+ return [{"session_id": r["session_id"], "title": r["title"] or "Cuộc trò chuyện mới", "created_at": r["created_at"]} for r in rows]
65
+
66
  async def get_history_async(pool: asyncpg.Pool, session_id: str):
67
  try:
68
  query = """
 
80
  logger.exception("Lỗi khi truy vấn lịch sử trò chuyện:", exc_info=True)
81
  return []
82
 
83
+ # Hàm lưu lượt chat để hỗ trợ title user_id
84
+ async def save_turn_async(pool: asyncpg.Pool, session_id: str, user_msg: str, assistant_msg: str, user_id: str = None):
85
  try:
86
  async with pool.acquire() as conn:
87
+ # Kiểm tra xem session này đã có tiêu đề chưa
88
+ existing_title = await conn.fetchval("SELECT title FROM history WHERE session_id = $1 LIMIT 1", session_id)
89
+
90
+ # Nếu chưa có, lấy 40 ký tự đầu làm tiêu đề
91
+ title = existing_title if existing_title else user_msg[:40] + "..."
92
+
93
  async with conn.transaction():
94
  await conn.execute(
95
+ "INSERT INTO history (session_id, user_id, role, content, title) VALUES ($1, $2, $3, $4, $5)",
96
+ session_id, user_id, "user", user_msg, title
 
 
97
  )
98
  await conn.execute(
99
+ "INSERT INTO history (session_id, user_id, role, content, title) VALUES ($1, $2, $3, $4, $5)",
100
+ session_id, user_id, "assistant", assistant_msg, title
 
 
101
  )
102
  except Exception:
103
  logger.exception("Lỗi khi lưu lượt hội thoại:", exc_info=True)
 
151
 
152
  #Cấu hình FastAPI với middleware CORS và lifespan để quản lý trạng thái hệ thống
153
  app = FastAPI(lifespan=lifespan, title= "RAG API SERVER")
154
+
155
  #Cho phép truy cập từ mọi nguồn
156
  allow_origins = [origin.strip() for origin in os.getenv("ALLOW_ORIGINS", "*").split(",") if origin.strip()]
157
  if not allow_origins:
 
167
  #Định nghĩa Endpoint
168
  class ChatRequest(BaseModel):
169
  session_id: str
170
+ user_id: str = None
171
  message: str
172
 
173
  class ChatResponse(BaseModel):
 
179
  ready = bool(getattr(request.app.state, "retriever", None) and getattr(request.app.state, "db_pool", None))
180
  return {"status": "ok" if ready else "starting", "ready": ready}
181
 
182
+ #Endpoint lấy danh sách session Sidebar
183
+ @app.get("/sessions/{user_id}")
184
+ async def list_sessions(user_id: str, request: Request):
185
+ _, db_pool = get_runtime_components(request)
186
+ sessions = await get_user_sessions_async(db_pool, user_id)
187
+ return {"sessions": sessions}
188
+
189
+ @app.get("/chat/history/{session_id}")
190
+ async def get_session_history(session_id: str, request: Request):
191
+ """API để lấy toàn bộ nội dung tin nhắn cũ của một phiên chat cụ thể"""
192
+ _, db_pool = get_runtime_components(request)
193
+ history = await get_history_async(db_pool, session_id)
194
+ if not history:
195
+ return {"messages": []}
196
+ return {"messages": history}
197
+
198
+
199
  @app.post("/chat", response_model=ChatResponse)
200
  async def chat_endpoint(payload: ChatRequest, request: Request):
201
  """Endpoint chat thông thường - trả JSON response đầy đủ"""
 
205
  raise HTTPException(status_code=400, detail="Bạn chưa nhập câu hỏi")
206
 
207
  session_id = payload.session_id
208
+ user_id = payload.user_id # Lấy user_id từ request
209
  history = await get_history_async(db_pool, session_id)
210
 
211
  # Tập hợp toàn bộ response từ generator
 
217
  logger.exception("Lỗi khi xử lý phản hồi từ AI:", exc_info=True)
218
  raise HTTPException(status_code=500, detail="Lỗi khi xử lý yêu cầu")
219
 
220
+ # Lưu lịch sử sau khi có response đầy đủ (Kèm theo user_id)
221
+ await save_turn_async(db_pool, session_id, user_msg, full_response, user_id)
222
 
223
  return ChatResponse(response=full_response)
224
 
 
232
  raise HTTPException(status_code=400, detail="Bạn chưa nhập câu hỏi")
233
 
234
  session_id = payload.session_id
235
+ user_id = payload.user_id # Lấy user_id từ request
236
  history = await get_history_async(db_pool, session_id)
237
 
238
  async def event_stream_generator():
 
249
  # Gửi tín hiệu kết thúc
250
  yield 'data: {"delta": "", "done": true}\n\n'
251
 
252
+ # Lưu lịch sử sau khi stream xong (Kèm theo user_id)
253
+ await save_turn_async(db_pool, session_id, user_msg, full_response, user_id)
254
 
255
  except Exception:
256
  logger.exception("Lỗi khi stream phản hồi từ AI:", exc_info=True)
 
270
  if __name__ == "__main__":
271
  import uvicorn
272
  port = int(os.getenv("PORT", "7860"))
273
+ uvicorn.run(app, host="0.0.0.0", port=port)