frabbani commited on
Commit
b522513
·
1 Parent(s): fec464a

Fix fact extraction - pass raw data for simple tools..

Browse files
Files changed (2) hide show
  1. server.py +77 -0
  2. tools.py +21 -1
server.py CHANGED
@@ -430,13 +430,90 @@ from agent_v2 import run_agent_v2
430
 
431
  @app.post("/api/agent/chat")
432
  async def agent_chat_endpoint(request: ChatRequest):
 
433
  async def generate():
434
  try:
435
  async for event in run_agent_v2(request.patient_id, request.message):
436
  yield f"data: {json.dumps(event)}\n\n"
437
  except Exception as e:
 
 
 
438
  yield f"data: {json.dumps({'type': 'error', 'message': str(e)})}\n\n"
439
  yield "data: [DONE]\n\n"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
440
 
441
  return StreamingResponse(
442
  generate(),
 
430
 
431
  @app.post("/api/agent/chat")
432
  async def agent_chat_endpoint(request: ChatRequest):
433
+ print(f"DEBUG agent_chat_endpoint: patient_id={request.patient_id}, message={request.message[:50]}...")
434
  async def generate():
435
  try:
436
  async for event in run_agent_v2(request.patient_id, request.message):
437
  yield f"data: {json.dumps(event)}\n\n"
438
  except Exception as e:
439
+ print(f"DEBUG agent_chat_endpoint error: {e}")
440
+ import traceback
441
+ traceback.print_exc()
442
  yield f"data: {json.dumps({'type': 'error', 'message': str(e)})}\n\n"
443
  yield "data: [DONE]\n\n"
444
+
445
+
446
+ # Debug endpoint to test database directly
447
+ @app.get("/api/debug/medications/{patient_id}")
448
+ async def debug_medications(patient_id: str):
449
+ conn = get_db()
450
+ try:
451
+ # Check patient exists
452
+ cursor = conn.execute("SELECT id, given_name, family_name FROM patients WHERE id = ?", (patient_id,))
453
+ patient = cursor.fetchone()
454
+
455
+ # Get all medications for this patient
456
+ cursor = conn.execute("SELECT id, display, status FROM medications WHERE patient_id = ?", (patient_id,))
457
+ meds = [dict(row) for row in cursor.fetchall()]
458
+
459
+ # Get all patient_ids in medications table
460
+ cursor = conn.execute("SELECT DISTINCT patient_id FROM medications")
461
+ med_patient_ids = [row[0] for row in cursor.fetchall()]
462
+
463
+ # Get all patient_ids in observations table
464
+ cursor = conn.execute("SELECT DISTINCT patient_id FROM observations LIMIT 5")
465
+ obs_patient_ids = [row[0] for row in cursor.fetchall()]
466
+
467
+ return {
468
+ "queried_patient_id": patient_id,
469
+ "patient_found": patient is not None,
470
+ "patient_name": f"{patient['given_name']} {patient['family_name']}" if patient else None,
471
+ "medications_count": len(meds),
472
+ "medications": meds[:5],
473
+ "all_medication_patient_ids": med_patient_ids,
474
+ "sample_observation_patient_ids": obs_patient_ids
475
+ }
476
+ finally:
477
+ conn.close()
478
+
479
+
480
+ @app.get("/api/debug/bp/{patient_id}")
481
+ async def debug_bp(patient_id: str):
482
+ conn = get_db()
483
+ try:
484
+ # Check BP observations
485
+ cursor = conn.execute("""
486
+ SELECT code, display, COUNT(*) as count
487
+ FROM observations
488
+ WHERE patient_id = ? AND code IN ('8480-6', '8462-4')
489
+ GROUP BY code, display
490
+ """, (patient_id,))
491
+ bp_counts = [dict(row) for row in cursor.fetchall()]
492
+
493
+ # Get sample BP readings
494
+ cursor = conn.execute("""
495
+ SELECT code, value_quantity, effective_date
496
+ FROM observations
497
+ WHERE patient_id = ? AND code = '8480-6'
498
+ ORDER BY effective_date DESC LIMIT 5
499
+ """, (patient_id,))
500
+ sample_systolic = [dict(row) for row in cursor.fetchall()]
501
+
502
+ # Get all patient_ids that have BP data
503
+ cursor = conn.execute("""
504
+ SELECT DISTINCT patient_id FROM observations
505
+ WHERE code IN ('8480-6', '8462-4')
506
+ """)
507
+ bp_patient_ids = [row[0] for row in cursor.fetchall()]
508
+
509
+ return {
510
+ "queried_patient_id": patient_id,
511
+ "bp_observation_counts": bp_counts,
512
+ "sample_systolic": sample_systolic,
513
+ "patient_ids_with_bp_data": bp_patient_ids
514
+ }
515
+ finally:
516
+ conn.close()
517
 
518
  return StreamingResponse(
519
  generate(),
tools.py CHANGED
@@ -10,11 +10,15 @@ import sqlite3
10
  from datetime import datetime, timedelta
11
  from typing import Optional
12
 
13
- DB_PATH = "data/fhir.db"
 
14
 
15
 
16
  def get_db():
17
  """Get database connection."""
 
 
 
18
  conn = sqlite3.connect(DB_PATH)
19
  conn.row_factory = sqlite3.Row
20
  return conn
@@ -231,15 +235,18 @@ def get_conditions(patient_id: str, status: Optional[str] = None) -> str:
231
 
232
  def get_medications(patient_id: str, status: Optional[str] = None) -> str:
233
  """Get patient medications."""
 
234
  conn = get_db()
235
  try:
236
  if status:
 
237
  cursor = conn.execute("""
238
  SELECT display, status, dosage_text, dosage_route, start_date
239
  FROM medications WHERE patient_id = ? AND status = ?
240
  ORDER BY start_date DESC
241
  """, (patient_id, status))
242
  else:
 
243
  cursor = conn.execute("""
244
  SELECT display, status, dosage_text, dosage_route, start_date
245
  FROM medications WHERE patient_id = ?
@@ -247,7 +254,12 @@ def get_medications(patient_id: str, status: Optional[str] = None) -> str:
247
  """, (patient_id,))
248
 
249
  medications = cursor.fetchall()
 
250
  if not medications:
 
 
 
 
251
  return "No medications found."
252
 
253
  lines = ["Medications:\n"]
@@ -557,6 +569,14 @@ def get_vital_chart_data(patient_id: str, vital_type: str, days: int = 30) -> st
557
 
558
  if not systolic and not diastolic:
559
  print(f"DEBUG: No BP data found!")
 
 
 
 
 
 
 
 
560
  return json_module.dumps({"error": "No blood pressure data found"})
561
 
562
  print(f"DEBUG: Returning BP chart data")
 
10
  from datetime import datetime, timedelta
11
  from typing import Optional
12
 
13
+ import os
14
+ DB_PATH = os.getenv("DB_PATH", "data/fhir.db")
15
 
16
 
17
  def get_db():
18
  """Get database connection."""
19
+ abs_path = os.path.abspath(DB_PATH)
20
+ exists = os.path.exists(DB_PATH)
21
+ print(f"DEBUG get_db: DB_PATH={DB_PATH}, abs_path={abs_path}, exists={exists}")
22
  conn = sqlite3.connect(DB_PATH)
23
  conn.row_factory = sqlite3.Row
24
  return conn
 
235
 
236
  def get_medications(patient_id: str, status: Optional[str] = None) -> str:
237
  """Get patient medications."""
238
+ print(f"DEBUG get_medications: patient_id={patient_id}, status={status}")
239
  conn = get_db()
240
  try:
241
  if status:
242
+ print(f"DEBUG: Querying medications with status filter: {status}")
243
  cursor = conn.execute("""
244
  SELECT display, status, dosage_text, dosage_route, start_date
245
  FROM medications WHERE patient_id = ? AND status = ?
246
  ORDER BY start_date DESC
247
  """, (patient_id, status))
248
  else:
249
+ print(f"DEBUG: Querying all medications")
250
  cursor = conn.execute("""
251
  SELECT display, status, dosage_text, dosage_route, start_date
252
  FROM medications WHERE patient_id = ?
 
254
  """, (patient_id,))
255
 
256
  medications = cursor.fetchall()
257
+ print(f"DEBUG: Found {len(medications)} medications")
258
  if not medications:
259
+ # Debug: check what patient_ids exist
260
+ cursor = conn.execute("SELECT DISTINCT patient_id FROM medications LIMIT 5")
261
+ existing_ids = [row[0] for row in cursor.fetchall()]
262
+ print(f"DEBUG: Existing patient_ids in medications: {existing_ids}")
263
  return "No medications found."
264
 
265
  lines = ["Medications:\n"]
 
569
 
570
  if not systolic and not diastolic:
571
  print(f"DEBUG: No BP data found!")
572
+ # Debug: Check what patient_ids have BP data
573
+ cursor = conn.execute("""
574
+ SELECT DISTINCT patient_id FROM observations
575
+ WHERE code IN ('8480-6', '8462-4') LIMIT 5
576
+ """)
577
+ bp_patient_ids = [row[0] for row in cursor.fetchall()]
578
+ print(f"DEBUG: Patient IDs with BP data: {bp_patient_ids}")
579
+ print(f"DEBUG: Queried patient_id was: {patient_id}")
580
  return json_module.dumps({"error": "No blood pressure data found"})
581
 
582
  print(f"DEBUG: Returning BP chart data")