Update app.py
Browse files148 unmodified lines1491501511521531541551561571581591601611621631641651661671681691701 unmodified line1721731741751761771781791801811821831841851861 unmodified line1881891901911921931941951961971981992002013 unmodified lines2052062072082092102112122132142152162172182196 unmodified lines2262272282292302312323 unmodified lines2362372382392402412422432442452462472482492502512522533 unmodified lines2572582592602612622632642652662672681 unmodified line2702712722732742752762772782792802812 unmodified lines2842852862872882892902912922932942952962972 unmodified lines300301302303304305306307308148 unmodified lines@app.route("/medical", methods=["GET", "POST"])def medical_page():# Use session for history and document contextif request.method == "GET":# Load all latest data from session (or default to empty if not found)latest_response = session.pop('latest_medical_response', {}) # POP to clear it after one displayanswer = latest_response.get('answer', "")thoughts = latest_response.get('thoughts', "")validation = latest_response.get('validation', "")source = latest_response.get('source', "")# Clear history only when a user first navigates (not on redirect)if not latest_response and 'medical_history' not in session:session.pop('current_medical_document', None)return render_template("medical_page.html",history=session.get('medical_history', []),answer=answer,thoughts=thoughts,validation=validation,1 unmodified line# POST Requestanswer, thoughts, validation, source = "", "", "", ""# 1. Get raw history (list of dicts) from sessionraw_history_list = session.get('medical_history', [])# 2. Hydrate it for the agenthistory_for_agent = hydrate_history(raw_history_list)current_medical_document = session.get('current_medical_document', "")try:query=standardize_query(request.form.get("query", ""))has_image = 'image' in request.files and request.files['image'].filenamehas_document = 'document' in request.files and request.files['document'].filenamehas_query = request.form.get("query") or request.form.get("question", "")1 unmodified linelogger.info(f"POST request received: has_image={has_image}, has_document={has_document}, has_query={has_query}")if has_document:# Scenario 3: Query + Documentlogger.info("Processing Scenario 3: Query + Document with Medical Swarm")file = request.files['document']try:# Store the new document text in the sessiondocument_text = file.read().decode("utf-8")session['current_medical_document'] = document_textcurrent_medical_document = document_text # Use the new document for this turnexcept UnicodeDecodeError:answer = "Error: Could not decode the uploaded document. Please ensure it is a valid text or PDF file."logger.error("Scenario 3: Document decode error")3 unmodified linesanswer = markdown_bold_to_html(swarm_answer)thoughts = "Swarm analysis complete. The process is orchestrated and does not use the ReAct thought process. You can now ask follow-up questions."source= "Medical Swarm"validation = (True, "Swarm output generated.") # Swarm has its own validation logichistory_for_agent.append(HumanMessage(content=f"[Document Uploaded] Query: '{query}'"))history_for_agent.append(AIMessage(content=answer))elif has_image :#Scenario 1logger.info("Processing Multimodal RAG: Query + Image")# --- Step 1 & 2: Image Setup & Vision Analysis ---file = request.files['image']upload_dir = "Uploads"os.makedirs(upload_dir, exist_ok=True)6 unmodified lineswith open(image_path, "rb") as img_file:img_data = base64.b64encode(img_file.read()).decode("utf-8")vision_prompt = f"Analyze this image and identify the main subject in a single, concise sentence. The user's query is: '{query}'"message = HumanMessage(content=[{"type": "text", "text": vision_prompt},3 unmodified linesvisual_prediction = vision_response.contentlogger.info(f"Vision Prediction: {visual_prediction}")# --- Create an Enhanced Query ---enhanced_query = (f'User Query: "{query}" 'f'Context from an image provided by the LLM: "{visual_prediction}" ''Based on the user\'s query and the context from LLM, provide a comprehensive answer.')logger.info(f"Enhanced query : {enhanced_query}")agent = rag_systems['medical']if not agent: raise Exception("Medical RAG system is not loaded.")response_dict = agent.answer(enhanced_query, chat_history=history_for_agent)answer, thoughts, validation, source = parse_agent_response(response_dict)history_for_agent.append(HumanMessage(content=query))history_for_agent.append(AIMessage(content=answer))3 unmodified linesos.remove(image_path)logger.info(f"Successfully deleted temporary image file: {image_path}")except PermissionError as e:logger.warning(f"Could not remove {image_path} after processing. "f"File may be locked by another process. Error: {e}")elif query:# --- SCENARIO 2: TEXT-ONLY QUERY OR SWARM FOLLOW-UP ---history_doc_context = history_for_agent # Use hydrated listif current_medical_document:logger.info("Processing Follow-up Query for Document")history_doc_context = [HumanMessage(content=f"We are discussing this document:\n{current_medical_document}")] + history_for_agent1 unmodified linelogger.info("Processing Text RAG query for Medical domain")logger.info(f"Original Query: '{query}'")print(f"📚 Using chat history with {len(history_doc_context)} previous messages to create standalone query")standalone_query = get_standalone_question(query, history_doc_context,llm)logger.info(f"Standalone Query: '{standalone_query}'")agent = rag_systems['medical']if not agent: raise Exception("Medical RAG system is not loaded.")response_dict = agent.answer(standalone_query, chat_history=history_doc_context)answer, thoughts, validation, source = parse_agent_response(response_dict)2 unmodified lineselse:raise ValueError("No query or file provided.")except Exception as e:logger.error(f"Error on /medical page: {e}", exc_info=True)answer = f"An error occurred: {e}"thoughts = traceback.format_exc()# 4. DEHYDRATE the full history back into dicts for session savingsession['medical_history'] = dehydrate_history(history_for_agent)# This (latest_response) is ALREADY JSON-serializable, so it's fine.session['latest_medical_response'] = {'answer': answer,'thoughts': thoughts,2 unmodified lines}session.modified = Truelogger.info(f"DEBUG: Saving to session: ANSWER='{answer[:50]}...', THOUGHTS='{thoughts[:50]}...'")logger.debug(f"Redirecting after saving latest response.")return redirect(url_for('medical_page'))@app.route("/medical/clear")148 unmodified lines1491501511521531541551561571581591601611621631641651661671681691701711721731741 unmodified line1761771781791801811821831841851861871 unmodified line1891901911921931941951961971981992003 unmodified lines2042052062072082092102112122132142152162176 unmodified lines2242252262272282293 unmodified lines2332342352362372382392402412422432442452462472482492502512523 unmodified lines2562572582592602612622632642651 unmodified line2672682692702712722732742752762772782792 unmodified lines2822832842852862872882892902912922932942952962972 unmodified lines300301302303304305306307308309148 unmodified lines@app.route("/medical", methods=["GET", "POST"])def medical_page():if request.method == "GET":# ✅ USE .get() instead of .pop() - don't remove it yetlatest_response = session.get('latest_medical_response', {})answer = latest_response.get('answer', "")thoughts = latest_response.get('thoughts', "")validation = latest_response.get('validation', "")source = latest_response.get('source', "")# ✅ NOW clear it after reading (for next request)if latest_response:session.pop('latest_medical_response', None)session.modified = True# Load historyraw_history_list = session.get('medical_history', [])history = hydrate_history(raw_history_list)return render_template("medical_page.html",history=history, # ✅ Pass hydrated historyanswer=answer,thoughts=thoughts,validation=validation,1 unmodified line# POST Requestanswer, thoughts, validation, source = "", "", "", ""raw_history_list = session.get('medical_history', [])history_for_agent = hydrate_history(raw_history_list)current_medical_document = session.get('current_medical_document', "")try:query = standardize_query(request.form.get("query", ""))has_image = 'image' in request.files and request.files['image'].filenamehas_document = 'document' in request.files and request.files['document'].filenamehas_query = request.form.get("query") or request.form.get("question", "")1 unmodified linelogger.info(f"POST request received: has_image={has_image}, has_document={has_document}, has_query={has_query}")if has_document:logger.info("Processing Scenario 3: Query + Document with Medical Swarm")file = request.files['document']try:document_text = file.read().decode("utf-8")session['current_medical_document'] = document_textcurrent_medical_document = document_textexcept UnicodeDecodeError:answer = "Error: Could not decode the uploaded document. Please ensure it is a valid text or PDF file."logger.error("Scenario 3: Document decode error")3 unmodified linesanswer = markdown_bold_to_html(swarm_answer)thoughts = "Swarm analysis complete. The process is orchestrated and does not use the ReAct thought process. You can now ask follow-up questions."source = "Medical Swarm"validation = "Swarm output generated."history_for_agent.append(HumanMessage(content=f"[Document Uploaded] Query: '{query}'"))history_for_agent.append(AIMessage(content=answer))elif has_image:logger.info("Processing Multimodal RAG: Query + Image")file = request.files['image']upload_dir = "Uploads"os.makedirs(upload_dir, exist_ok=True)6 unmodified lineswith open(image_path, "rb") as img_file:img_data = base64.b64encode(img_file.read()).decode("utf-8")vision_prompt = f"Analyze this image and identify the main subject in a single, concise sentence. The user's query is: '{query}'"message = HumanMessage(content=[{"type": "text", "text": vision_prompt},3 unmodified linesvisual_prediction = vision_response.contentlogger.info(f"Vision Prediction: {visual_prediction}")enhanced_query = (f'User Query: "{query}" 'f'Context from an image provided by the LLM: "{visual_prediction}" ''Based on the user\'s query and the context from LLM, provide a comprehensive answer.')logger.info(f"Enhanced query: {enhanced_query}")agent = rag_systems['medical']if not agent:raise Exception("Medical RAG system is not loaded.")response_dict = agent.answer(enhanced_query, chat_history=history_for_agent)answer, thoughts, validation, source = parse_agent_response(response_dict)history_for_agent.append(HumanMessage(content=query))history_for_agent.append(AIMessage(content=answer))3 unmodified linesos.remove(image_path)logger.info(f"Successfully deleted temporary image file: {image_path}")except PermissionError as e:logger.warning(f"Could not remove {image_path}: {e}")elif query:history_doc_context = history_for_agentif current_medical_document:logger.info("Processing Follow-up Query for Document")history_doc_context = [HumanMessage(content=f"We are discussing this document:\n{current_medical_document}")] + history_for_agent1 unmodified linelogger.info("Processing Text RAG query for Medical domain")logger.info(f"Original Query: '{query}'")standalone_query = get_standalone_question(query, history_doc_context, llm)logger.info(f"Standalone Query: '{standalone_query}'")agent = rag_systems['medical']if not agent:raise Exception("Medical RAG system is not loaded.")response_dict = agent.answer(standalone_query, chat_history=history_doc_context)answer, thoughts, validation, source = parse_agent_response(response_dict)2 unmodified lineselse:raise ValueError("No query or file provided.")except Exception as e:logger.error(f"Error on /medical page: {e}", exc_info=True)answer = f"An error occurred: {e}"thoughts = traceback.format_exc()# ✅ DEHYDRATE history back to dictssession['medical_history'] = dehydrate_history(history_for_agent)# ✅ Save the responsesession['latest_medical_response'] = {'answer': answer,'thoughts': thoughts,2 unmodified lines}session.modified = True# ✅ ADD DEBUG LOGlogger.info(f"💾 SAVED TO SESSION - Answer length: {len(answer)}, First 100 chars: {answer[:100]}")logger.info(f"💾 Session ID: {session.get('_id', 'NO ID')}")return redirect(url_for('medical_page'))@app.route("/medical/clear")
app.py+35-34