from flask import Blueprint, session, request, jsonify from utils.logging.logger_setup import logger from utils.db.db import mongo, get_next_id from ai_agents.patient_rag import rag_pipeline # Corrected import from datetime import datetime chat_bp = Blueprint('chat', __name__) @chat_bp.route("/api/chat", methods=["POST"]) def handle_chat(): """ Handle chat messages between user and AI. 1. Validates session. 2. Logs user message. 3. Generates AI response (Normal RAG or Similar Case Search). 4. Logs AI message. """ if not session.get('logged_in') or not session.get('active_patient_id'): return jsonify({"error": "Unauthorized or no active session"}), 403 data = request.json user_message = data.get("message") session_id = data.get("session_id") try: patient_id = int(session.get('active_patient_id')) except (ValueError, TypeError): return jsonify({"error": "Invalid patient ID in session"}), 400 if not user_message or not session_id: return jsonify({"error": "Missing message or session ID"}), 400 # 1. Log user message try: user_msg_id = get_next_id('chatmessage') mongo.db.chatmessage.insert_one({ "id": user_msg_id, "sql_id": user_msg_id, "session_id": int(session_id), "sender": "user", "content": user_message, "timestamp": datetime.now() }) except Exception as e: logger.error(f"Error logging user message: {e}") # Continue to try getting a response even if logging fails? # Ideally we should probably fail here, but let's proceed for UX if possible. # 2. Get AI response (with similar patient logic) ai_response = "I encountered an error processing your request." try: if user_message.strip().startswith("/similar"): query = user_message.strip().replace("/similar", "").strip() if not query: ai_response = "Please provide symptoms or conditions after the /similar command. For example: `/similar high fever and headache`" else: similar_patients = rag_pipeline.similar_patient_search( query=query, current_patient_id=patient_id ) if not similar_patients: ai_response = "No similar patient cases were found based on your query." else: ai_response = "Found similar patient cases:\n\n" for p in similar_patients: ai_response += f"- **Patient ID:** {p['patient_id']}\n" ai_response += f" - **Similarity:** {p['similarity_score']:.2%}\n" ai_response += f" - **Matching Aspects:** {p['similar_aspects']}\n" ai_response += f" - **Medications:** { ', '.join(p['medicines']) if p['medicines'] else 'N/A'}\n\n" else: ai_response = rag_pipeline.rag_query(user_message, patient_id) except Exception as e: logger.error(f"Error processing chat command: {e}", exc_info=True) ai_response = f"An error occurred while processing your request: {e}" # 3. Log AI message try: ai_msg_id = get_next_id('chatmessage') mongo.db.chatmessage.insert_one({ "id": ai_msg_id, "sql_id": ai_msg_id, "session_id": int(session_id), "sender": "ai", "content": ai_response, "timestamp": datetime.now() }) except Exception as e: logger.error(f"Error logging AI message: {e}") return jsonify({"response": ai_response}) @chat_bp.route("/api/history", methods=["GET"]) def get_history_list(): if not session.get('logged_in') or session.get('user_type') != 'doctor': return jsonify({"error": "Unauthorized"}), 403 doctor_id = session['user_id'] try: sessions = mongo.db.chatsession.find( {"doctor_id": doctor_id} ).sort("created_at", -1) history_items = [] for s in sessions: session_id = s.get('sql_id', s.get('id')) patient_id = s.get('patient_id', 'N/A') created_at = s.get('created_at') if isinstance(created_at, datetime): display_time = created_at.strftime("%b %d, %Y at %I:%M %p") else: display_time = str(created_at) history_items.append({ "session_id": session_id, "title": f"Chat with Patient #{patient_id}", "display_time": display_time, "type": "chat" }) return jsonify({"history": history_items}) except Exception as e: logger.error(f"Error fetching history for doctor {doctor_id}: {e}") return jsonify({"error": "Failed to load history."}), 500 @chat_bp.route("/api/history/chat/", methods=["GET"]) def get_history_messages(session_id): if not session.get('logged_in'): return jsonify({"error": "Unauthorized"}), 403 try: session_doc = mongo.db.chatsession.find_one({ "doctor_id": session['user_id'], "$or": [{"id": int(session_id)}, {"sql_id": int(session_id)}] }) if not session_doc: return jsonify({"error": "Session not found or access denied"}), 404 messages = mongo.db.chatmessage.find( {"session_id": int(session_id)} ).sort("timestamp", 1) message_list = [] for msg in messages: timestamp = msg.get('timestamp') if isinstance(timestamp, datetime): ts_str = timestamp.isoformat() else: ts_str = str(timestamp) message_list.append({ "sender": msg.get("sender"), "content": msg.get("content"), "timestamp": ts_str }) return jsonify({"messages": message_list}) except Exception as e: logger.error(f"Error fetching messages for session {session_id}: {e}") return jsonify({"error": f"An error occurred while fetching the chat log."}), 500