Ali2206 commited on
Commit
bfa497f
·
verified ·
1 Parent(s): cbd84d4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +36 -7
app.py CHANGED
@@ -139,9 +139,25 @@ def log_system_usage(tag=""):
139
  print(f"[{tag}] GPU/CPU monitor failed: {e}")
140
 
141
  def clean_response(text: str) -> str:
 
142
  text = sanitize_utf8(text)
143
- text = re.sub(r"\[TOOL_CALLS\].*", "", text, flags=re.DOTALL)
144
- text = re.sub(r"\n{3,}", "\n\n", text).strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145
  return text
146
 
147
  def init_agent():
@@ -211,11 +227,21 @@ def create_ui(agent):
211
  combined_response = ""
212
 
213
  prompt_template = """
214
- You are a medical analysis assistant. Analyze the following patient record excerpt for clinical oversights. Provide a concise, evidence-based summary in markdown format under these headings: Missed Diagnoses, Medication Conflicts, Incomplete Assessments, and Urgent Follow-up. For each finding, include:
215
  - Clinical context (why the issue was missed or relevant details from the record).
216
  - Potential risks if unaddressed (e.g., disease progression, adverse events).
217
  - Actionable recommendations (e.g., tests, referrals, medication adjustments).
218
- If no issues are found in a section, state "No issues identified." Ensure the output is specific to the provided text, formatted as markdown with bullet points under each heading, and avoids generic or static responses.
 
 
 
 
 
 
 
 
 
 
219
 
220
  Patient Record Excerpt (Chunk {0} of {1}):
221
  {chunk}
@@ -258,7 +284,7 @@ Patient Record Excerpt (Chunk {0} of {1}):
258
  for m in chunk_output:
259
  if hasattr(m, 'content') and m.content:
260
  cleaned = clean_response(m.content)
261
- if cleaned:
262
  chunk_response += cleaned + "\n"
263
  # Update UI with partial response
264
  if history[-1]["content"].startswith("Analyzing"):
@@ -268,7 +294,7 @@ Patient Record Excerpt (Chunk {0} of {1}):
268
  yield history, None
269
  elif isinstance(chunk_output, str) and chunk_output.strip():
270
  cleaned = clean_response(chunk_output)
271
- if cleaned:
272
  chunk_response += cleaned + "\n"
273
  # Update UI with partial response
274
  if history[-1]["content"].startswith("Analyzing"):
@@ -278,7 +304,10 @@ Patient Record Excerpt (Chunk {0} of {1}):
278
  yield history, None
279
 
280
  # Append completed chunk response to combined response
281
- combined_response += f"--- Analysis for Chunk {chunk_idx} ---\n{chunk_response}\n"
 
 
 
282
 
283
  # Finalize UI with complete response
284
  if combined_response:
 
139
  print(f"[{tag}] GPU/CPU monitor failed: {e}")
140
 
141
  def clean_response(text: str) -> str:
142
+ """Clean TxAgent response to remove tool calls, reasoning, and non-markdown content."""
143
  text = sanitize_utf8(text)
144
+ # Remove tool call artifacts, None, and reasoning
145
+ text = re.sub(r"\[.*?\]|\bNone\b|To analyze the patient record excerpt.*?medications\.|Since the previous attempts.*?\.|I need to.*?medications\.|Retrieving tools.*?\.", "", text, flags=re.DOTALL)
146
+ # Remove extra whitespace and non-markdown content
147
+ text = re.sub(r"\n{3,}", "\n\n", text)
148
+ text = re.sub(r"[^\n#\-\*\w\s\.\,\:\(\)]+", "", text) # Keep markdown-relevant characters
149
+ # Extract only markdown sections
150
+ markdown_pattern = r"(###\s*(?:Missed Diagnoses|Medication Conflicts|Incomplete Assessments|Urgent Follow-up).*?(?=\n###|\Z))|(-.*?)(?=\n-|\n###|\Z)"
151
+ matches = re.findall(markdown_pattern, text, re.DOTALL | re.MULTILINE)
152
+ cleaned = []
153
+ for match in matches:
154
+ section = match[0].strip() or match[1].strip()
155
+ if section:
156
+ cleaned.append(section)
157
+ text = "\n".join(cleaned).strip()
158
+ # Ensure consistent markdown formatting
159
+ if not text.startswith("###"):
160
+ text = "### Missed Diagnoses\n- No issues identified.\n\n### Medication Conflicts\n- No issues identified.\n\n### Incomplete Assessments\n- No issues identified.\n\n### Urgent Follow-up\n- No issues identified."
161
  return text
162
 
163
  def init_agent():
 
227
  combined_response = ""
228
 
229
  prompt_template = """
230
+ You are a medical analysis assistant. Analyze the following patient record excerpt for clinical oversights and provide a concise, evidence-based summary in markdown format under these headings: Missed Diagnoses, Medication Conflicts, Incomplete Assessments, and Urgent Follow-up. For each finding, include:
231
  - Clinical context (why the issue was missed or relevant details from the record).
232
  - Potential risks if unaddressed (e.g., disease progression, adverse events).
233
  - Actionable recommendations (e.g., tests, referrals, medication adjustments).
234
+ Output ONLY the markdown-formatted findings, with bullet points under each heading. Do NOT include reasoning, tool calls, or intermediate steps. If no issues are found in a section, state "No issues identified." Ensure the output is specific to the provided text and avoids generic responses.
235
+
236
+ Example Output:
237
+ ### Missed Diagnoses
238
+ - Elevated BP noted without diagnosis. Missed due to inconsistent visits. Risks: stroke. Recommend: BP monitoring, antihypertensives.
239
+ ### Medication Conflicts
240
+ - No issues identified.
241
+ ### Incomplete Assessments
242
+ - Chest pain not evaluated. Time constraints likely cause. Risks: cardiac issues. Recommend: ECG, stress test.
243
+ ### Urgent Follow-up
244
+ - Abnormal creatinine not addressed. Delayed lab review. Risks: renal failure. Recommend: nephrology referral.
245
 
246
  Patient Record Excerpt (Chunk {0} of {1}):
247
  {chunk}
 
284
  for m in chunk_output:
285
  if hasattr(m, 'content') and m.content:
286
  cleaned = clean_response(m.content)
287
+ if cleaned and re.search(r"###\s*(Missed Diagnoses|Medication Conflicts|Incomplete Assessments|Urgent Follow-up)", cleaned):
288
  chunk_response += cleaned + "\n"
289
  # Update UI with partial response
290
  if history[-1]["content"].startswith("Analyzing"):
 
294
  yield history, None
295
  elif isinstance(chunk_output, str) and chunk_output.strip():
296
  cleaned = clean_response(chunk_output)
297
+ if cleaned and re.search(r"###\s*(Missed Diagnoses|Medication Conflicts|Incomplete Assessments|Urgent Follow-up)", cleaned):
298
  chunk_response += cleaned + "\n"
299
  # Update UI with partial response
300
  if history[-1]["content"].startswith("Analyzing"):
 
304
  yield history, None
305
 
306
  # Append completed chunk response to combined response
307
+ if chunk_response:
308
+ combined_response += f"--- Analysis for Chunk {chunk_idx} ---\n{chunk_response}\n"
309
+ else:
310
+ combined_response += f"--- Analysis for Chunk {chunk_idx} ---\n### Missed Diagnoses\n- No issues identified.\n\n### Medication Conflicts\n- No issues identified.\n\n### Incomplete Assessments\n- No issues identified.\n\n### Urgent Follow-up\n- No issues identified.\n\n"
311
 
312
  # Finalize UI with complete response
313
  if combined_response: