WebashalarForML commited on
Commit
5c0eb1b
·
verified ·
1 Parent(s): 57042f5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +101 -49
app.py CHANGED
@@ -13,7 +13,7 @@ from bloatectomy import bloatectomy
13
  from werkzeug.utils import secure_filename
14
  from langchain_groq import ChatGroq
15
  from typing_extensions import TypedDict, NotRequired
16
- from werkzeug.utils import secure_filename
17
  # --- Logging ---
18
  logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
19
  logger = logging.getLogger("patient-assistant")
@@ -57,18 +57,17 @@ def clean_notes_with_bloatectomy(text: str, style: str = "remov") -> str:
57
  return text
58
 
59
  # --- Agent prompt instructions ---
 
 
 
60
  PATIENT_ASSISTANT_PROMPT = """
61
- You are a patient assistant helping to analyze medical records and reports. Your primary task is to get the patient ID (PID) from the user at the start of the conversation.
62
 
63
- Once you have the PID, you will be provided with a summary of the patient's medical reports. Use this information, along with the conversation history, to provide a comprehensive response.
64
-
65
- Your tasks include:
66
- - **First, ask for the patient ID.** Do not proceed with any other task until you have the PID.
67
- - Analyzing medical records and reports to detect anomalies, redundant tests, or misleading treatments.
68
- - Suggesting preventive care based on the overall patient health history.
69
- - Optimizing healthcare costs by comparing past visits and treatments.
70
- - Offering personalized lifestyle recommendations.
71
- - Generating a natural, helpful reply to the user.
72
 
73
  STRICT OUTPUT FORMAT (JSON ONLY):
74
  Return a single JSON object with the following keys:
@@ -83,7 +82,52 @@ Rules:
83
  - Do not make up information that is not present in the provided medical reports or conversation history.
84
  """
85
 
86
- # --- JSON extraction helper ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  def extract_json_from_llm_response(raw_response: str) -> dict:
88
  """Safely extracts a JSON object from a string that might contain extra text or markdown."""
89
  default = {
@@ -135,14 +179,14 @@ def serve_frontend():
135
  try:
136
  return app.send_static_file("frontend.html")
137
  except Exception:
138
- return "<h3>frontend2.html not found in static/ — please add your frontend2.html there.</h3>", 404
139
 
140
  @app.route("/upload_report", methods=["POST"])
141
  def upload_report():
142
  """Handles the upload of a new PDF report for a specific patient."""
143
  if 'report' not in request.files:
144
  return jsonify({"error": "No file part in the request"}), 400
145
-
146
  file = request.files['report']
147
  patient_id = request.form.get("patient_id")
148
 
@@ -167,9 +211,11 @@ def chat():
167
  chat_history = data.get("chat_history") or []
168
  patient_state = data.get("patient_state") or {}
169
  patient_id = patient_state.get("patientDetails", {}).get("pid")
170
-
171
  # --- Prepare the state for the LLM ---
172
  state = patient_state.copy()
 
 
173
  state["lastUserMessage"] = ""
174
  if chat_history:
175
  # Find the last user message
@@ -178,25 +224,18 @@ def chat():
178
  state["lastUserMessage"] = msg["content"]
179
  break
180
 
 
 
 
 
 
 
 
181
  combined_text_parts = []
182
- # If a PID is not yet known, prompt the agent to ask for it.
183
- if not patient_id:
184
- # A simple prompt to get the agent to ask for the PID.
185
- user_prompt = "Hello. I need to get the patient's ID to proceed."
186
-
187
- # Check if the user's last message contains a possible number for the PID
188
- last_message = state.get("lastUserMessage", "")
189
- # A very basic check to see if the user provided a number
190
- if re.search(r'\d+', last_message):
191
- inferred_pid = re.search(r'(\d+)', last_message).group(1)
192
- state["patientDetails"] = {"pid": inferred_pid}
193
- patient_id = inferred_pid
194
- # Now that we have a PID, let the agent know to process the reports.
195
- user_prompt = f"The user provided a patient ID: {inferred_pid}. Please access their reports and respond."
196
- else:
197
- # If no PID is found, the agent should ask for it.
198
- user_prompt = "The patient has not provided a patient ID. Please ask them to provide it to proceed."
199
-
200
  # If a PID is known, load the patient reports.
201
  if patient_id:
202
  patient_folder = REPORTS_ROOT / f"p_{patient_id}"
@@ -215,12 +254,12 @@ def chat():
215
  page_text = file_path.read_text(encoding='utf-8', errors='ignore')
216
  except Exception:
217
  page_text = ""
218
-
219
  if page_text:
220
  cleaned = clean_notes_with_bloatectomy(page_text, style="remov")
221
  if cleaned:
222
  combined_text_parts.append(cleaned)
223
-
224
  # Update the conversation summary with the parsed documents
225
  base_summary = state.get("conversationSummary", "") or ""
226
  docs_summary = "\n\n".join(combined_text_parts)
@@ -229,12 +268,26 @@ def chat():
229
  else:
230
  state["conversationSummary"] = base_summary
231
 
232
- # --- Direct LLM Invocation ---
 
 
 
 
 
 
 
 
 
 
 
 
233
  user_prompt = f"""
234
  Current patientDetails: {json.dumps(state.get("patientDetails", {}))}
235
- Current conversationSummary: {state.get("conversationSummary", "")}
236
  Last user message: {state.get("lastUserMessage", "")}
237
-
 
 
238
  Return ONLY valid JSON with keys: assistant_reply, patientDetails, conversationSummary.
239
  """
240
 
@@ -242,7 +295,7 @@ Return ONLY valid JSON with keys: assistant_reply, patientDetails, conversationS
242
  {"role": "system", "content": PATIENT_ASSISTANT_PROMPT},
243
  {"role": "user", "content": user_prompt}
244
  ]
245
-
246
  try:
247
  logger.info("Invoking LLM with prepared state and prompt...")
248
  llm_response = llm.invoke(messages)
@@ -254,21 +307,26 @@ Return ONLY valid JSON with keys: assistant_reply, patientDetails, conversationS
254
 
255
  logger.info(f"Raw LLM response: {raw_response}")
256
  parsed_result = extract_json_from_llm_response(raw_response)
257
-
258
  except Exception as e:
259
  logger.exception("LLM invocation failed")
260
  return jsonify({"error": "LLM invocation failed", "detail": str(e)}), 500
261
 
262
  updated_state = parsed_result or {}
263
 
 
 
 
 
264
  assistant_reply = updated_state.get("assistant_reply")
265
  if not assistant_reply or not isinstance(assistant_reply, str) or not assistant_reply.strip():
266
  # Fallback to a polite message if the LLM response is invalid or empty
267
- assistant_reply = "I'm here to help — could you tell me more about your symptoms?"
268
 
 
269
  response_payload = {
270
  "assistant_reply": assistant_reply,
271
- "updated_state": updated_state,
272
  }
273
 
274
  return jsonify(response_payload)
@@ -281,12 +339,6 @@ def upload_reports():
281
  Expects multipart/form-data with:
282
  - patient_id (form field)
283
  - files (one or multiple files; use the same field name 'files' for each file)
284
-
285
- Example curl:
286
- curl -X POST http://localhost:7860/upload_reports \
287
- -F "patient_id=12345" \
288
- -F "files[]=@/path/to/report1.pdf" \
289
- -F "files[]=@/path/to/report2.pdf"
290
  """
291
  try:
292
  # patient id can be in form or args (for convenience)
@@ -365,4 +417,4 @@ def ping():
365
 
366
  if __name__ == "__main__":
367
  port = int(os.getenv("PORT", 7860))
368
- app.run(host="0.0.0.0", port=port, debug=True)
 
13
  from werkzeug.utils import secure_filename
14
  from langchain_groq import ChatGroq
15
  from typing_extensions import TypedDict, NotRequired
16
+
17
  # --- Logging ---
18
  logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
19
  logger = logging.getLogger("patient-assistant")
 
57
  return text
58
 
59
  # --- Agent prompt instructions ---
60
+ # Important change: the assistant should NOT insist on PID at the start of conversation.
61
+ # It should only ask for patient ID when the user asks for something that requires accessing previous medical records.
62
+ # Also, avoid asking for additional identity details (name/DOB) purely for "verification" — accept PID as sufficient for record access in this flow.
63
  PATIENT_ASSISTANT_PROMPT = """
64
+ You are a patient assistant helping to analyze medical records and reports. You should be helpful for general medical questions even when no patient ID (PID) is provided.
65
 
66
+ Behavior rules (follow these strictly):
67
+ - Do NOT ask for the patient ID at the start of every conversation. Only request the PID when the user's question explicitly requires accessing prior medical records (for example: "show my previous lab report", "what does my thyroid test from last month say", "what was my doctor's note for PID 12345", etc.).
68
+ - When you do ask for a PID, be concise and ask only for the PID (e.g., "Please provide the patient ID (PID) to retrieve previous records."). Do not request name/DOB/other verification unless the user explicitly asks for an extra verification step.
69
+ - If the user supplies a PID in their message (patterns like "pid 5678", "p5678", "patient id: 5678"), accept and use it — do not ask again.
70
+ - Avoid repeating unnecessary clarifying questions. If the user has already given the PID, proceed to use it. If you previously asked for the PID and the user didn't provide it, ask once more succinctly and then offer to help with general guidance without records.
 
 
 
 
71
 
72
  STRICT OUTPUT FORMAT (JSON ONLY):
73
  Return a single JSON object with the following keys:
 
82
  - Do not make up information that is not present in the provided medical reports or conversation history.
83
  """
84
 
85
+ # --- Helper utilities ---
86
+ PID_PATTERN = re.compile(r"(?:\bpid\b|\bpatient\s*id\b|\bp\b)\s*[:#\-]?\s*(p?\d+)", re.IGNORECASE)
87
+ DIGIT_PATTERN = re.compile(r"\b(p?\d{3,})\b") # fallback: any 3+ digit cluster
88
+
89
+ RECORD_KEYWORDS = [
90
+ "report", "lab", "result", "results", "previous", "history", "record", "records",
91
+ "test", "tests", "scan", "imaging", "radiology", "thyroid", "tsh", "t3", "t4",
92
+ "prescription", "doctor", "referral", "visit", "consultation",
93
+ ]
94
+
95
+
96
+ def extract_pid_from_text(text: str) -> str | None:
97
+ """Try to extract PID from a free-form text string.
98
+ Accepts patterns like: 'pid 5678', 'p5678', 'patient id: 5678', or a bare number if clearly intended as an id.
99
+ """
100
+ if not text:
101
+ return None
102
+ m = PID_PATTERN.search(text)
103
+ if m:
104
+ return m.group(1).lstrip('pP')
105
+ # fallback: look for explicit mention like 'pid p5678' with different casing
106
+ # final fallback: any 3+ digit cluster but only if message also contains a record keyword
107
+ if any(k in text.lower() for k in RECORD_KEYWORDS):
108
+ m2 = DIGIT_PATTERN.search(text)
109
+ if m2:
110
+ return m2.group(1).lstrip('pP')
111
+ return None
112
+
113
+
114
+ def needs_pid_for_query(text: str) -> bool:
115
+ """Decide whether the user's message requires looking up prior records (thus needs a PID).
116
+ Simple heuristic: if message contains any keyword from RECORD_KEYWORDS or explicit phrases asking for previous tests/records.
117
+ """
118
+ if not text:
119
+ return False
120
+ lower = text.lower()
121
+ # direct phrases that clearly require historical records
122
+ phrases = ["previous report", "previous lab", "my report", "my records", "past report", "last report", "previous test", "previous results"]
123
+ if any(p in lower for p in phrases):
124
+ return True
125
+ # if message contains any record-related keyword, treat as needing PID
126
+ if any(k in lower for k in RECORD_KEYWORDS):
127
+ return True
128
+ return False
129
+
130
+ # --- JSON extraction helper (unchanged) ---
131
  def extract_json_from_llm_response(raw_response: str) -> dict:
132
  """Safely extracts a JSON object from a string that might contain extra text or markdown."""
133
  default = {
 
179
  try:
180
  return app.send_static_file("frontend.html")
181
  except Exception:
182
+ return "<h3>frontend.html not found in static/ — please add your frontend.html there.</h3>", 404
183
 
184
  @app.route("/upload_report", methods=["POST"])
185
  def upload_report():
186
  """Handles the upload of a new PDF report for a specific patient."""
187
  if 'report' not in request.files:
188
  return jsonify({"error": "No file part in the request"}), 400
189
+
190
  file = request.files['report']
191
  patient_id = request.form.get("patient_id")
192
 
 
211
  chat_history = data.get("chat_history") or []
212
  patient_state = data.get("patient_state") or {}
213
  patient_id = patient_state.get("patientDetails", {}).get("pid")
214
+
215
  # --- Prepare the state for the LLM ---
216
  state = patient_state.copy()
217
+ state.setdefault("asked_for_pid", False)
218
+ state.setdefault("conversationSummary", state.get("conversationSummary", ""))
219
  state["lastUserMessage"] = ""
220
  if chat_history:
221
  # Find the last user message
 
224
  state["lastUserMessage"] = msg["content"]
225
  break
226
 
227
+ # Try to infer PID from the last message (user might include it inline)
228
+ inferred_pid = extract_pid_from_text(state.get("lastUserMessage", "") or "")
229
+ if not patient_id and inferred_pid:
230
+ logger.info("Inferred PID from user message: %s", inferred_pid)
231
+ state.setdefault("patientDetails", {})["pid"] = inferred_pid
232
+ patient_id = inferred_pid
233
+
234
  combined_text_parts = []
235
+
236
+ # Decide whether this query actually needs patient records
237
+ wants_records = needs_pid_for_query(state.get("lastUserMessage", "") or "")
238
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
239
  # If a PID is known, load the patient reports.
240
  if patient_id:
241
  patient_folder = REPORTS_ROOT / f"p_{patient_id}"
 
254
  page_text = file_path.read_text(encoding='utf-8', errors='ignore')
255
  except Exception:
256
  page_text = ""
257
+
258
  if page_text:
259
  cleaned = clean_notes_with_bloatectomy(page_text, style="remov")
260
  if cleaned:
261
  combined_text_parts.append(cleaned)
262
+
263
  # Update the conversation summary with the parsed documents
264
  base_summary = state.get("conversationSummary", "") or ""
265
  docs_summary = "\n\n".join(combined_text_parts)
 
268
  else:
269
  state["conversationSummary"] = base_summary
270
 
271
+ # Build the user prompt for the LLM. We explicitly tell the LLM whether a PID is available and whether the user's message requires records.
272
+ if patient_id:
273
+ action_hint = f"Use the patient ID {patient_id} to retrieve and summarize any relevant reports."
274
+ else:
275
+ if wants_records and not state.get("asked_for_pid", False):
276
+ action_hint = "The user is asking for information that requires prior medical records. Ask succinctly for the Patient ID (PID) if needed."
277
+ # mark that we asked for PID so we don't repeatedly ask
278
+ state["asked_for_pid"] = True
279
+ elif wants_records and state.get("asked_for_pid", False):
280
+ action_hint = "The user previously was asked for a PID but has not supplied one. Ask once more concisely for the PID; otherwise offer to help with general guidance without accessing records."
281
+ else:
282
+ action_hint = "No PID provided and the user's request does not need prior records. Provide helpful, general medical guidance and offer to retrieve records if the user later supplies a PID."
283
+
284
  user_prompt = f"""
285
  Current patientDetails: {json.dumps(state.get("patientDetails", {}))}
286
+ Current conversationSummary: {state.get("conversationSummary", "")[:4000]}
287
  Last user message: {state.get("lastUserMessage", "")}
288
+
289
+ SYSTEM_HINT: {action_hint}
290
+
291
  Return ONLY valid JSON with keys: assistant_reply, patientDetails, conversationSummary.
292
  """
293
 
 
295
  {"role": "system", "content": PATIENT_ASSISTANT_PROMPT},
296
  {"role": "user", "content": user_prompt}
297
  ]
298
+
299
  try:
300
  logger.info("Invoking LLM with prepared state and prompt...")
301
  llm_response = llm.invoke(messages)
 
307
 
308
  logger.info(f"Raw LLM response: {raw_response}")
309
  parsed_result = extract_json_from_llm_response(raw_response)
310
+
311
  except Exception as e:
312
  logger.exception("LLM invocation failed")
313
  return jsonify({"error": "LLM invocation failed", "detail": str(e)}), 500
314
 
315
  updated_state = parsed_result or {}
316
 
317
+ # Merge patientDetails back into state (but avoid overwriting asked_for_pid)
318
+ state.setdefault("patientDetails", {}).update(updated_state.get("patientDetails", {}))
319
+ state["conversationSummary"] = updated_state.get("conversationSummary", state.get("conversationSummary", ""))
320
+
321
  assistant_reply = updated_state.get("assistant_reply")
322
  if not assistant_reply or not isinstance(assistant_reply, str) or not assistant_reply.strip():
323
  # Fallback to a polite message if the LLM response is invalid or empty
324
+ assistant_reply = "I'm here to help — could you tell me more about your symptoms or provide a Patient ID (PID) if you want me to fetch past reports?"
325
 
326
+ # Return the new assistant reply and the updated state so the frontend can persist it.
327
  response_payload = {
328
  "assistant_reply": assistant_reply,
329
+ "updated_state": state,
330
  }
331
 
332
  return jsonify(response_payload)
 
339
  Expects multipart/form-data with:
340
  - patient_id (form field)
341
  - files (one or multiple files; use the same field name 'files' for each file)
 
 
 
 
 
 
342
  """
343
  try:
344
  # patient id can be in form or args (for convenience)
 
417
 
418
  if __name__ == "__main__":
419
  port = int(os.getenv("PORT", 7860))
420
+ app.run(host="0.0.0.0", port=port, debug=True)