kn29 commited on
Commit
21cc4ca
·
verified ·
1 Parent(s): fef0353

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -15
app.py CHANGED
@@ -46,6 +46,7 @@ logger = logging.getLogger(__name__)
46
  MONGO_CLIENT = None
47
  DB = None
48
  RAG_MODELS_INITIALIZED = False
 
49
  APP_STATE = {
50
  "startup_time": None,
51
  "mongodb_connected": False,
@@ -185,21 +186,6 @@ def load_session_from_mongodb(session_id: str) -> Dict[str, Any]:
185
  session_logger.info("Session loaded from MongoDB with existing embeddings")
186
  return session_store
187
 
188
- def build_indices_for_session(session_id: str) -> Dict[str, Any]:
189
- """Builds all indices for a session using its SessionRAG instance."""
190
- session_logger = create_session_logger(session_id)
191
- with STORE_LOCK:
192
- store = SESSION_STORES[session_id]
193
- session_rag = store["session_rag"]
194
-
195
- session_logger.info(f"Building indices for {store['metadata']['chunk_count']} chunks...")
196
- session_rag.build_all_indices(session_rag.chunks_data) # Correctly passing chunks
197
-
198
- with STORE_LOCK:
199
- SESSION_STORES[session_id]["indexed"] = True
200
-
201
- session_logger.info("All session-specific indices built successfully")
202
- return store["metadata"]
203
 
204
  def get_chat_history_safely(session_id: str, limit: int = 50) -> List[Dict[str, Any]]:
205
  """Get chat history with error handling."""
@@ -323,6 +309,33 @@ async def chat_with_document(session_id: str, request: ChatRequest):
323
  # Update last access time
324
  SESSION_LAST_ACCESS[session_id] = datetime.utcnow()
325
  session_rag = SESSION_STORES[session_id]["session_rag"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
326
 
327
  @app.get("/history/{session_id}")
328
  async def get_session_history(session_id: str):
 
46
  MONGO_CLIENT = None
47
  DB = None
48
  RAG_MODELS_INITIALIZED = False
49
+ SESSION_LAST_ACCESS = {} # Track last access time for each session
50
  APP_STATE = {
51
  "startup_time": None,
52
  "mongodb_connected": False,
 
186
  session_logger.info("Session loaded from MongoDB with existing embeddings")
187
  return session_store
188
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
189
 
190
  def get_chat_history_safely(session_id: str, limit: int = 50) -> List[Dict[str, Any]]:
191
  """Get chat history with error handling."""
 
309
  # Update last access time
310
  SESSION_LAST_ACCESS[session_id] = datetime.utcnow()
311
  session_rag = SESSION_STORES[session_id]["session_rag"]
312
+ # Process the query
313
+ session_logger.info(f"Processing query: {request.message[:100]}...")
314
+ result = await asyncio.to_thread(session_rag.query_documents, request.message, top_k=5)
315
+ APP_STATE["total_queries"] += 1
316
+
317
+ answer = result.get('answer', 'Unable to generate an answer.')
318
+
319
+ # Save chat messages asynchronously
320
+ asyncio.create_task(save_chat_message_safely(session_id, "user", request.message))
321
+ asyncio.create_task(save_chat_message_safely(session_id, "assistant", answer))
322
+
323
+ processing_time = time.time() - start_time
324
+ session_logger.info(f"Query processed in {processing_time:.2f}s.")
325
+
326
+ return ChatResponse(
327
+ success=True,
328
+ answer=answer,
329
+ sources=result.get('sources', []),
330
+ chat_history=[],
331
+ processing_time=processing_time,
332
+ session_id=session_id,
333
+ query_analysis=result.get('query_analysis'),
334
+ confidence=result.get('confidence')
335
+ )
336
+ except Exception as e:
337
+ session_logger.error(f"Chat processing failed: {e}", exc_info=True)
338
+ raise HTTPException(status_code=500, detail=f"Chat processing error: {e}")
339
 
340
  @app.get("/history/{session_id}")
341
  async def get_session_history(session_id: str):