-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
723 lines (591 loc) · 29.9 KB
/
Copy pathapp.py
File metadata and controls
723 lines (591 loc) · 29.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
"""
ComCare — ADRD Caregiver Assistant
FastAPI backend with Azure OpenAI + Ollama dual-AI support
"""
import json
import os
import sqlite3
import uuid
from datetime import datetime
from pathlib import Path
from typing import Optional
import httpx
from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
# ── App ────────────────────────────────────────────────────────────────────────
app = FastAPI(title="ComCare API", version="1.0")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
# Serve PWA static files (manifest, icons, service worker)
STATIC_DIR = Path("static")
STATIC_DIR.mkdir(exist_ok=True)
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
# ── Database ───────────────────────────────────────────────────────────────────
DB_PATH = Path("comcare.db")
def get_db():
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
return conn
def init_db():
with get_db() as conn:
conn.executescript("""
CREATE TABLE IF NOT EXISTS records (
id TEXT PRIMARY KEY,
card_type TEXT NOT NULL,
data TEXT NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS chat_messages (
id TEXT PRIMARY KEY,
session_id TEXT NOT NULL,
role TEXT NOT NULL,
content TEXT NOT NULL,
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
""")
# Seed default settings if not set
defaults = {
"ai_backend": "ollama",
"azure_endpoint": "",
"azure_api_key": "",
"azure_deployment": "gpt-4o",
"ollama_url": "http://localhost:11434",
"ollama_model": "llama3.1:latest",
"patient_name": "Margaret Flores",
"patient_age": "78",
"patient_diagnosis": "Alzheimer's disease — moderate stage",
"patient_physician": "Dr. Elena Reyes, MD",
"patient_next_visit": "2026-07-15",
"language": "en",
}
for k, v in defaults.items():
conn.execute(
"INSERT OR IGNORE INTO settings (key, value) VALUES (?, ?)", (k, v)
)
conn.commit()
init_db()
# ── Settings helpers ───────────────────────────────────────────────────────────
def get_settings() -> dict:
with get_db() as conn:
rows = conn.execute("SELECT key, value FROM settings").fetchall()
return {r["key"]: r["value"] for r in rows}
def update_setting(key: str, value: str):
with get_db() as conn:
conn.execute(
"INSERT OR REPLACE INTO settings (key, value) VALUES (?, ?)", (key, value)
)
conn.commit()
# ── AI routing ─────────────────────────────────────────────────────────────────
SYSTEM_CHAT = """You are ComCare, a compassionate AI assistant supporting family caregivers of people with Alzheimer's disease and related dementias (ADRD).
You help caregivers by:
- Listening to observations about the person they care for
- Asking brief, focused follow-up questions to clarify what happened
- Detecting when a caregiver's message contains information worth saving as a structured care record
- Auto-populating a draft record with all available details for the caregiver to review and confirm
- Preparing for clinical visits by summarizing concerns
Rules:
- Never diagnose, prescribe, or recommend dose changes
- Always use warm, plain language
- Keep your conversational reply concise (under 4 sentences)
- For urgent symptoms (severe fall, sudden confusion, chest pain, breathing difficulty), always say to call the doctor or 911 immediately
- Only suggest saving after the caregiver has provided enough context (at least what happened and when)
- Never auto-save; always let the caregiver confirm
RECORD DETECTION:
When you have enough information to create a record, append a JSON block at the very end of your reply (after your conversational text), on its own line, starting with <<<RECORD>>> and ending with <<<END>>>.
Use exactly this structure, filling every field you can infer. Leave unknown fields as empty string "".
For card_type "care_change":
<<<RECORD>>>
{"suggest_record":true,"card_type":"care_change","summary":"<one sentence>","fields":{"description":"<full description of the change>","first_noticed":"<YYYY-MM-DD or empty>","frequency":"<Once|Several times|Daily|Getting worse|Unsure>","severity":"<Mild|Moderate|Severe|Unsure>","reporter":"<Observed by me|PLWD reported|Other person|Concern / unsure>","tag":"<Health|Behavior|Function|Sleep / Eating|Safety>","notes":"<any extra context>"}}
<<<END>>>
For card_type "medication":
<<<RECORD>>>
{"suggest_record":true,"card_type":"medication","summary":"<one sentence>","fields":{"medication_name":"<name>","concern":"<what is worrying or confusing>","first_noticed":"<YYYY-MM-DD or empty>","source":"<PCP|Neurologist|Specialist|Pharmacist|Hospital|Family|Unsure>","question":"<question to ask clinician>","reporter":"<Observed by me|PLWD reported|Other>","notes":"<extra context>"}}
<<<END>>>
For card_type "coordination":
<<<RECORD>>>
{"suggest_record":true,"card_type":"coordination","summary":"<one sentence>","fields":{"follow_up_item":"<what needs handling>","responsible":"<Me|PCP|Specialist|Pharmacist|Insurer|Family|Agency|Unsure>","due_date":"<YYYY-MM-DD or empty>","status":"<Needs action|Waiting|Overdue|Done>","importance":"<Low|Medium|High>","notes":"<extra context>"}}
<<<END>>>
For card_type "visit_priority":
<<<RECORD>>>
{"suggest_record":true,"card_type":"visit_priority","summary":"<one sentence>","fields":{"question":"<what to discuss>","why_now":"<reason this matters>","priority":"<Top concern|If time allows|Later>","topic":"<Planning|Safety|Services|Family comms|Future planning>","notes":"<extra context>"}}
<<<END>>>
For card_type "caregiver_support":
<<<RECORD>>>
{"suggest_record":true,"card_type":"caregiver_support","summary":"<one sentence>","fields":{"challenge":"<what is hard>","impact":"<A little|Somewhat|A lot|Unsure>","help_type":"<Emotional|Practical|Skills / training|Family support|Services|Legal / financial|Unsure>","notes":"<extra context>"}}
<<<END>>>
For card_type "what_matters":
<<<RECORD>>>
{"suggest_record":true,"card_type":"what_matters","summary":"<one sentence>","fields":{"description":"<routine, preference or strength>","perspective":"<PLWD|Caregiver|Shared|Unsure>","when_relevant":"<Morning|Daytime|Evening|Night>","scenario":"<Meals|Personal care|Leaving home|Visits|Other>","tag":"<Comfort|Safety|Routine|Preference>","notes":"<extra context>"}}
<<<END>>>
Only include the <<<RECORD>>> block when you have enough detail to be useful. Do not include it for general questions."""
SYSTEM_SUMMARY = """You are ComCare. Generate a concise, professional pre-visit clinical summary for an ADRD caregiver to share with their physician.
Format the output as plain text with exactly these four sections:
1. PATIENT INFORMATION
2. VISIT PRIORITIES
3. DISCUSSION CHECKLIST
4. RECENT OVERALL PICTURE AND ROUTINES
Use clinical but accessible language. Never diagnose. Be specific and actionable."""
async def call_ollama(messages: list, system: str, settings: dict) -> str:
url = settings.get("ollama_url", "http://localhost:11434")
model = settings.get("ollama_model", "llama3.2")
# Build a single prompt string — works on all Ollama versions via /api/generate
prompt_parts = [f"System: {system}\n"]
for m in messages:
role = "User" if m["role"] == "user" else "Assistant"
prompt_parts.append(f"{role}: {m['content']}")
prompt_parts.append("Assistant:")
prompt = "\n".join(prompt_parts)
payload = {
"model": model,
"prompt": prompt,
"system": system,
"stream": False,
}
async with httpx.AsyncClient(timeout=120) as client:
resp = await client.post(f"{url}/api/generate", json=payload)
resp.raise_for_status()
return resp.json()["response"]
async def call_azure(messages: list, system: str, settings: dict) -> str:
endpoint = settings.get("azure_endpoint", "").rstrip("/")
api_key = settings.get("azure_api_key", "")
deployment = settings.get("azure_deployment", "gpt-4o")
if not endpoint or not api_key:
raise HTTPException(400, "Azure endpoint and API key not configured")
url = f"{endpoint}/openai/deployments/{deployment}/chat/completions?api-version=2024-02-01"
payload = {
"messages": [{"role": "system", "content": system}] + messages,
"max_tokens": 800,
"temperature": 0.7,
}
async with httpx.AsyncClient(timeout=60) as client:
resp = await client.post(
url,
json=payload,
headers={"api-key": api_key, "Content-Type": "application/json"},
)
resp.raise_for_status()
data = resp.json()
return data["choices"][0]["message"]["content"]
async def call_ai(messages: list, system: str, settings: dict) -> str:
backend = settings.get("ai_backend", "ollama")
if backend == "azure":
return await call_azure(messages, system, settings)
return await call_ollama(messages, system, settings)
def build_chat_system_prompt(message_count: int = 0) -> str:
"""Assemble a dynamic system prompt enriched with patient profile and recent records."""
s = get_settings()
# ── Patient profile block ──────────────────────────────────────────────────
patient_name = s.get("patient_name", "the patient")
patient_age = s.get("patient_age", "")
diagnosis = s.get("patient_diagnosis", "")
physician = s.get("patient_physician", "")
next_visit = s.get("patient_next_visit", "")
profile_block = f"""
PATIENT YOU ARE HELPING WITH:
Name: {patient_name}{f', age {patient_age}' if patient_age else ''}
Diagnosis: {diagnosis or 'Not specified'}
Primary physician: {physician or 'Not specified'}
Next visit: {next_visit or 'Not scheduled'}
Use the patient's name naturally in conversation. Reference their diagnosis when explaining symptoms or behaviors.
When the next visit is soon, encourage preparing visit questions."""
# ── Recent records block ───────────────────────────────────────────────────
cutoff = (datetime.utcnow().replace(hour=0, minute=0, second=0)
.__class__.utcnow() if False else datetime.utcnow())
# last 21 days
with get_db() as conn:
rows = conn.execute(
"""SELECT card_type, data, created_at FROM records
ORDER BY created_at DESC LIMIT 30"""
).fetchall()
CARD_SHORT = {
"care_change": "Care Change",
"medication": "Medication",
"coordination": "Task",
"visit_priority": "Visit Q",
"caregiver_support": "Support Need",
"what_matters": "Preference",
}
if rows:
lines = []
for r in rows:
d = json.loads(r["data"])
# Pull the most informative field per card type
summary = (
d.get("description") or d.get("concern") or d.get("follow_up_item")
or d.get("question") or d.get("challenge") or "—"
)
date_str = r["created_at"][:10]
label = CARD_SHORT.get(r["card_type"], r["card_type"])
sev = d.get("severity") or d.get("impact") or d.get("status") or ""
lines.append(f" [{date_str}] {label}: {summary[:120]}" + (f" ({sev})" if sev else ""))
records_block = "\nRECENT SAVED CARE RECORDS (newest first):\n" + "\n".join(lines) + """
Use these records to:
- Notice patterns (e.g., repeated falls, worsening confusion, recurring medication questions)
- Avoid asking the caregiver to repeat information already logged
- Reference specific past events when relevant (e.g., "You mentioned last week that...")
- Highlight anything that should definitely come up at the next visit
- Suggest a record type that complements what's already saved"""
else:
records_block = "\nNo care records saved yet. Encourage the caregiver to log observations."
# ── Medication shortlist ───────────────────────────────────────────────────
med_rows = [r for r in rows if r["card_type"] == "medication"]
if med_rows:
med_names = list({json.loads(r["data"]).get("medication_name","") for r in med_rows if json.loads(r["data"]).get("medication_name")})
meds_block = f"\nKNOWN MEDICATIONS (from records): {', '.join(med_names)}\nWhen the caregiver mentions side effects or changes, connect them to these medications where relevant."
else:
meds_block = ""
# ── Conversation pacing guidance ──────────────────────────────────────────
# message_count = number of messages already in history (user + assistant)
# Each full round = 2 messages. We want at least 3 rounds before wrapping up.
rounds = message_count // 2
if rounds == 0:
pacing_block = """
CONVERSATION STAGE: Opening
This is the first message. Greet the caregiver warmly, ask one open question to understand what's on their mind today. Do NOT suggest saving a record yet."""
elif rounds <= 1:
pacing_block = """
CONVERSATION STAGE: Early (round 1-2)
You're still gathering information. Ask 1-2 focused follow-up questions to better understand what happened — timing, frequency, severity, context. Do NOT suggest saving a record yet unless the situation is urgent."""
elif rounds <= 2:
pacing_block = """
CONVERSATION STAGE: Middle (round 2-3)
You have a reasonable picture now. Continue exploring if anything is still unclear. You MAY suggest saving a record if you have enough specific detail. Keep asking if important information is missing."""
else:
pacing_block = """
CONVERSATION STAGE: Ready to wrap up (3+ rounds completed)
You have gathered enough information across multiple exchanges. After your reply, the app will automatically show a full conversation summary. End your response naturally — e.g. "I think I have a good picture of what's been happening. I'll pull together a summary for you now." Then provide any final record suggestions if appropriate."""
return SYSTEM_CHAT + profile_block + records_block + meds_block + pacing_block
# ── Pydantic models ────────────────────────────────────────────────────────────
class ChatRequest(BaseModel):
messages: list
session_id: Optional[str] = None
class RecordCreate(BaseModel):
card_type: str
data: dict
class RecordUpdate(BaseModel):
data: dict
class SettingsUpdate(BaseModel):
settings: dict
class ChatSummarizeRequest(BaseModel):
messages: list # full conversation so far
session_id: Optional[str] = None
class SummaryRequest(BaseModel):
date_range: Optional[str] = None
concerns: Optional[str] = None
questions: Optional[str] = None
specialty: Optional[str] = None # e.g. "Neurology", "Cardiology", "Primary Care"
purpose: Optional[str] = None # free-text visit purpose
# ── Routes ─────────────────────────────────────────────────────────────────────
@app.get("/")
async def root():
return FileResponse("comcare.html")
# Service worker must be served from root scope (not /static/) so it can
# intercept all same-origin requests
@app.get("/sw.js")
async def service_worker():
return FileResponse(
STATIC_DIR / "sw.js",
media_type="application/javascript",
headers={"Service-Worker-Allowed": "/"},
)
@app.get("/manifest.json")
async def manifest():
return FileResponse(STATIC_DIR / "manifest.json", media_type="application/manifest+json")
# ── Chat ──────────────────────────────────────────────────────────────────────
@app.post("/api/chat")
async def chat(req: ChatRequest):
settings = get_settings()
system_prompt = build_chat_system_prompt(len(req.messages)) # patient profile + recent records + pacing
try:
reply = await call_ai(req.messages, system_prompt, settings)
except httpx.ConnectError:
backend = settings.get("ai_backend", "ollama")
if backend == "ollama":
raise HTTPException(
503,
f"Cannot reach Ollama at {settings.get('ollama_url')}. "
"Make sure Ollama is running: `ollama serve`",
)
raise HTTPException(503, "Cannot reach Azure OpenAI. Check endpoint and key.")
except Exception as e:
raise HTTPException(500, str(e))
# Persist messages
if req.session_id:
now = datetime.utcnow().isoformat()
with get_db() as conn:
for msg in req.messages[-2:]: # last user + save reply below
conn.execute(
"INSERT OR IGNORE INTO chat_messages VALUES (?, ?, ?, ?, ?)",
(str(uuid.uuid4()), req.session_id, msg["role"], msg["content"], now),
)
conn.execute(
"INSERT INTO chat_messages VALUES (?, ?, ?, ?, ?)",
(str(uuid.uuid4()), req.session_id, "assistant", reply, now),
)
conn.commit()
return {"reply": reply, "backend": settings.get("ai_backend")}
# ── Records ───────────────────────────────────────────────────────────────────
@app.get("/api/records")
async def list_records(card_type: Optional[str] = None):
with get_db() as conn:
if card_type:
rows = conn.execute(
"SELECT * FROM records WHERE card_type = ? ORDER BY created_at DESC",
(card_type,),
).fetchall()
else:
rows = conn.execute(
"SELECT * FROM records ORDER BY created_at DESC"
).fetchall()
return [
{
"id": r["id"],
"card_type": r["card_type"],
"data": json.loads(r["data"]),
"created_at": r["created_at"],
}
for r in rows
]
@app.post("/api/records")
async def create_record(rec: RecordCreate):
now = datetime.utcnow().isoformat()
rid = str(uuid.uuid4())
with get_db() as conn:
conn.execute(
"INSERT INTO records VALUES (?, ?, ?, ?, ?)",
(rid, rec.card_type, json.dumps(rec.data), now, now),
)
conn.commit()
return {"id": rid, "created_at": now}
@app.put("/api/records/{record_id}")
async def update_record(record_id: str, rec: RecordUpdate):
now = datetime.utcnow().isoformat()
with get_db() as conn:
row = conn.execute(
"SELECT * FROM records WHERE id = ?", (record_id,)
).fetchone()
if not row:
raise HTTPException(404, "Record not found")
existing = json.loads(row["data"])
existing.update(rec.data)
conn.execute(
"UPDATE records SET data = ?, updated_at = ? WHERE id = ?",
(json.dumps(existing), now, record_id),
)
conn.commit()
return {"id": record_id, "updated_at": now}
@app.delete("/api/records/{record_id}")
async def delete_record(record_id: str):
with get_db() as conn:
conn.execute("DELETE FROM records WHERE id = ?", (record_id,))
conn.commit()
return {"deleted": record_id}
# ── Chat summarize ────────────────────────────────────────────────────────────
SYSTEM_CHAT_SUMMARIZE = """You are ComCare. The caregiver has just finished a chat session sharing observations.
Review the conversation and produce a JSON-only response (no other text) in this exact structure:
{
"what_i_heard": "A warm 3–5 sentence paragraph summarising the key observations and concerns the caregiver shared. Use the patient's name. Write in plain, empathetic language.",
"gaps": "1–3 brief follow-up questions for anything still unclear — timing, frequency, severity. Omit this key (or set to empty string) if nothing is unclear.",
"suggested_records": [
{
"card_type": "care_change|medication|coordination|visit_priority|caregiver_support|what_matters",
"description": "One concise sentence describing what should be recorded."
}
]
}
Rules:
- Output ONLY valid JSON. No markdown, no prose outside the JSON.
- suggested_records may be an empty list [] if nothing is clearly recordable yet.
- Keep descriptions under 120 characters."""
@app.post("/api/chat/summarize")
async def chat_summarize(req: ChatSummarizeRequest):
"""Summarize the conversation, surface gaps, and batch-suggest records."""
settings = get_settings()
s = get_settings()
patient_name = s.get("patient_name", "the patient")
system = SYSTEM_CHAT_SUMMARIZE + f"\n\nPatient: {patient_name}. Diagnosis: {s.get('patient_diagnosis', 'ADRD')}."
trigger = {"role": "user", "content": "Please summarize our conversation now."}
messages = list(req.messages) + [trigger]
try:
reply = await call_ai(messages, system, settings)
except httpx.ConnectError:
raise HTTPException(503, "Cannot reach AI backend.")
except Exception as e:
raise HTTPException(500, str(e))
# Parse structured JSON from AI; fall back gracefully
import json as _json
try:
# Strip markdown code fences if present
clean = reply.strip()
if clean.startswith("```"):
clean = "\n".join(clean.split("\n")[1:])
if clean.endswith("```"):
clean = clean.rsplit("```", 1)[0]
structured = _json.loads(clean.strip())
except Exception:
# Fallback: return raw reply as what_i_heard
structured = {
"what_i_heard": reply,
"gaps": "",
"suggested_records": []
}
return {**structured, "backend": settings.get("ai_backend")}
# ── Visit Summary ─────────────────────────────────────────────────────────────
SPECIALTY_FOCUS = {
"Neurology": """Focus especially on:
- Cognitive symptoms: memory, confusion, disorientation, word-finding
- Behavioral and mood changes: agitation, anxiety, depression, sleep
- Medication efficacy and side effects for dementia drugs (cholinesterase inhibitors, memantine)
- Disease progression markers since last visit
- Safety concerns related to cognitive decline""",
"Cardiology": """Focus especially on:
- Cardiovascular symptoms: chest pain, shortness of breath, palpitations, swelling
- Blood pressure trends and medication (antihypertensives, diuretics)
- Activity tolerance and any changes in stamina or mobility
- Fluid intake, diet, and weight changes
- Any symptoms that could interact with cardiac medications""",
"Primary Care": """Provide a comprehensive general overview covering:
- All active symptoms and behavioral changes
- Full medication list and any concerns
- Functional status: ADLs, mobility, falls
- Upcoming specialist referrals or coordination needs
- Caregiver support and capacity""",
"Physical Therapy": """Focus especially on:
- Mobility and gait: changes, unsteadiness, near-falls or falls
- Functional abilities: transfers, dressing, bathing, walking distance
- Pain or discomfort affecting movement
- Home environment safety concerns (stairs, bathroom, rugs)
- Current activity level and any decline""",
"Pharmacy / Medication Review": """Focus especially on:
- Complete medication list with doses and schedule
- Any new medications, recent dose changes, or stopped medications
- Observed side effects or adverse reactions
- Medication adherence and administration challenges
- Questions about drug interactions or timing""",
"Social Work / Care Coordination": """Focus especially on:
- Caregiver stress, capacity, and support needs
- Home safety and living situation
- Community resources, respite care, or day programs needed
- Financial or insurance concerns related to care
- Family communication and decision-making dynamics""",
"Other Specialist": "", # No special focus — use general format
}
def build_summary_system_prompt(specialty: str, purpose: str) -> str:
base = """You are ComCare. Generate a concise, professional pre-visit clinical summary for an ADRD caregiver to share with their care team.
Format the output as plain text with exactly these four sections:
1. PATIENT INFORMATION
2. VISIT PURPOSE & PRIORITIES
3. DISCUSSION CHECKLIST
4. RECENT OVERALL PICTURE AND ROUTINES
Use clinical but accessible language. Never diagnose. Be specific and actionable."""
focus = SPECIALTY_FOCUS.get(specialty, "")
if focus:
base += f"\n\nSPECIALTY FOCUS — This summary is for a {specialty} visit:\n{focus}"
if purpose:
base += f"\n\nVISIT PURPOSE (caregiver-stated): {purpose}\nMake sure the summary is shaped around this purpose."
return base
@app.post("/api/summary")
async def generate_summary(req: SummaryRequest):
settings = get_settings()
specialty = req.specialty or "Primary Care"
purpose = req.purpose or ""
with get_db() as conn:
rows = conn.execute(
"SELECT card_type, data FROM records ORDER BY created_at DESC LIMIT 30"
).fetchall()
records_text = "\n".join(
f"[{r['card_type']}] {r['data']}" for r in rows
) or "No records saved yet."
user_msg = f"""
Patient: {settings.get('patient_name')}, {settings.get('patient_age')}, {settings.get('patient_diagnosis')}
Primary physician: {settings.get('patient_physician')}
Upcoming visit: {settings.get('patient_next_visit')}
Visit specialty: {specialty}
Visit purpose: {purpose or 'Routine follow-up'}
Date range covered: {req.date_range or 'past 2 weeks'}
Saved care records:
{records_text}
Caregiver concerns: {req.concerns or 'Not specified'}
Questions for clinician: {req.questions or 'Not specified'}
Generate the visit summary now.
"""
system_prompt = build_summary_system_prompt(specialty, purpose)
try:
summary = await call_ai(
[{"role": "user", "content": user_msg}], system_prompt, settings
)
except Exception as e:
raise HTTPException(500, str(e))
return {
"summary": summary,
"specialty": specialty,
"purpose": purpose,
"generated_at": datetime.utcnow().isoformat(),
}
# ── Settings ──────────────────────────────────────────────────────────────────
@app.get("/api/settings")
async def get_all_settings():
s = get_settings()
# Mask sensitive keys
if s.get("azure_api_key"):
s["azure_api_key"] = "••••••••" + s["azure_api_key"][-4:]
return s
@app.post("/api/settings")
async def save_settings(req: SettingsUpdate):
# Don't overwrite masked key placeholder
for k, v in req.settings.items():
if k == "azure_api_key" and v.startswith("••••"):
continue
update_setting(k, str(v))
return {"saved": True}
@app.get("/api/settings/test")
async def test_connection():
settings = get_settings()
backend = settings.get("ai_backend", "ollama")
try:
reply = await call_ai(
[{"role": "user", "content": "Reply with: ComCare ready"}],
"You are a test assistant. Follow the instruction exactly.",
settings,
)
return {"ok": True, "backend": backend, "reply": reply[:80]}
except Exception as e:
return {"ok": False, "backend": backend, "error": str(e)}
# ── Dashboard data ────────────────────────────────────────────────────────────
@app.get("/api/dashboard")
async def dashboard():
settings = get_settings()
with get_db() as conn:
records = conn.execute(
"SELECT card_type, data, created_at FROM records ORDER BY created_at DESC LIMIT 10"
).fetchall()
record_count = conn.execute("SELECT COUNT(*) as c FROM records").fetchone()["c"]
recent = [
{
"card_type": r["card_type"],
"data": json.loads(r["data"]),
"created_at": r["created_at"],
}
for r in records
]
return {
"patient_name": settings.get("patient_name"),
"patient_diagnosis": settings.get("patient_diagnosis"),
"patient_physician": settings.get("patient_physician"),
"next_visit": settings.get("patient_next_visit"),
"total_records": record_count,
"recent_records": recent,
"ai_backend": settings.get("ai_backend"),
}