-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
419 lines (348 loc) · 14.4 KB
/
Copy pathapp.py
File metadata and controls
419 lines (348 loc) · 14.4 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
from __future__ import annotations
import logging
from datetime import datetime, timezone
from pathlib import Path
from fastapi import BackgroundTasks, FastAPI, File, HTTPException, Query, Request, UploadFile
from fastapi.responses import FileResponse, JSONResponse, PlainTextResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
from olumide.ingestion.vision import analyze_image
from olumide.agents.clinical_reasoning import ClinicalReasoningAgent
from olumide.agents.clinic_liaison import ClinicLiaisonAgent
from olumide.agents.crisis_response import CrisisResponseAgent
from olumide.agents.family_circle import FamilyCircleAgent
from olumide.agents.medication_safety import MedicationSafetyAgent
from olumide.agents.primary_care import PrimaryCareAgent
from olumide.config import get_settings
from olumide.context.store import PatientContextStore
from olumide.ingestion.router import MessageRouter
from olumide.models.message import IncomingMessage, MessageType, SignalSeverity
from olumide.orchestrator.openclaw import OpenCLAW
from olumide.seed import seed_patient
from olumide.tools.communication import send_whatsapp
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s | %(message)s")
logger = logging.getLogger(__name__)
settings = get_settings()
app = FastAPI(title="Olumide Health Agent", version="0.2.0")
context_store = PatientContextStore(settings)
router = MessageRouter(settings, context_store)
orchestrator = OpenCLAW(settings, context_store)
for agent_cls in [
PrimaryCareAgent,
ClinicalReasoningAgent,
MedicationSafetyAgent,
FamilyCircleAgent,
ClinicLiaisonAgent,
CrisisResponseAgent,
]:
agent = agent_cls(settings)
orchestrator.register_agent(agent.name, agent)
# Serve static dashboard (clinician dashboard polls ./clinician_notes.json)
DASHBOARD_DIR = Path(__file__).parent / "dashboard"
DASHBOARD_DIR.mkdir(exist_ok=True)
app.mount("/dashboard", StaticFiles(directory=str(DASHBOARD_DIR), html=True), name="dashboard")
@app.on_event("startup")
async def startup():
await context_store.initialize()
await seed_patient(settings, context_store, router)
logger.info("Olumide Health Agent started; Bamidele seeded.")
@app.get("/health")
async def health_check():
return {"status": "healthy", "service": "olumide", "version": "0.2.0"}
# --- WhatsApp Cloud API webhook (existing) ---
@app.get("/webhook")
async def verify_webhook(
hub_mode: str = Query(None, alias="hub.mode"),
hub_verify_token: str = Query(None, alias="hub.verify_token"),
hub_challenge: str = Query(None, alias="hub.challenge"),
):
if hub_mode == "subscribe" and hub_verify_token == settings.whatsapp_verify_token:
return PlainTextResponse(hub_challenge or "")
raise HTTPException(status_code=403, detail="Verification failed")
@app.post("/webhook")
async def handle_webhook(request: Request, background_tasks: BackgroundTasks):
try:
body = await request.json()
entry = body.get("entry", [{}])[0]
changes = entry.get("changes", [{}])[0]
value = changes.get("value", {})
messages = value.get("messages", [])
if not messages:
return {"status": "ok", "message": "no messages"}
msg_data = messages[0]
background_tasks.add_task(_process_whatsapp_message, msg_data, body)
return {"status": "accepted", "messages": len(messages)}
except Exception as e:
logger.error(f"Webhook error: {e}")
raise HTTPException(status_code=500, detail=str(e))
async def _process_whatsapp_message(msg_data: dict, raw_body: dict):
try:
msg_type_raw = msg_data.get("type", "text")
try:
msg_type = MessageType(msg_type_raw)
except ValueError:
msg_type = MessageType.TEXT
content = None
media_id = None
if msg_type == MessageType.TEXT:
content = msg_data.get("text", {}).get("body", "")
elif msg_type in (MessageType.VOICE, MessageType.IMAGE, MessageType.DOCUMENT):
media_id = msg_data.get(msg_type_raw, {}).get("id")
incoming = IncomingMessage(
id=msg_data.get("id", ""),
sender_phone=msg_data.get("from", ""),
message_type=msg_type,
content=content,
media_id=media_id,
timestamp=datetime.now(timezone.utc),
raw_payload=raw_body,
)
processed = await router.route(incoming)
responses = await orchestrator.process(processed)
reply = _select_patient_reply(responses)
if not reply:
logger.warning("[whatsapp] no reply generated for message_id=%s", incoming.id)
return
if not settings.whatsapp_token or not settings.whatsapp_phone_number_id:
logger.warning("[whatsapp] credentials missing; skipped outbound reply")
return
result = await send_whatsapp(incoming.sender_phone, reply, settings=settings)
if result.get("error"):
logger.error("[whatsapp] outbound send failed: %s", result.get("error"))
else:
logger.info("[whatsapp] outbound reply sent for message_id=%s", incoming.id)
except Exception as e:
logger.error("[whatsapp] background processing error: %s", e)
def _select_patient_reply(responses) -> str:
clinical = next((r for r in responses if r.agent_name == "clinical_reasoning"), None)
if clinical and clinical.response_text:
return clinical.response_text
return responses[0].response_text if responses else ""
# --- Arduino bridge webhook: device -> agent ---
@app.post("/webhook/device")
async def handle_device_event(request: Request):
try:
evt = await request.json()
etype = evt.get("e")
logger.info("[device-webhook] %s %s", etype, evt)
# For RFID taps and button presses we just log for the demo. A future
# version would inject these as ingress signals to the orchestrator.
return {"status": "ok", "received": evt}
except Exception as e:
logger.error(f"device webhook error: {e}")
raise HTTPException(status_code=400, detail=str(e))
# --- Sim chat UI fallback (no Twilio/Meta needed) ---
class SimMessage(BaseModel):
text: str
patient_id: str | None = None
SIM_HTML = Path(__file__).parent / "static" / "sim.html"
@app.get("/sim", include_in_schema=False)
async def sim_page():
return FileResponse(SIM_HTML)
@app.get("/sim/", include_in_schema=False)
async def sim_page_slash():
return FileResponse(SIM_HTML)
@app.post("/sim/message")
async def sim_message(payload: SimMessage):
profile_phone = "+2348012345001"
incoming = IncomingMessage(
id=f"sim-{int(datetime.now().timestamp() * 1000)}",
sender_phone=profile_phone,
message_type=MessageType.TEXT,
content=payload.text,
timestamp=datetime.now(timezone.utc),
raw_payload={"sim": True, "text": payload.text},
)
processed = await router.route(incoming)
responses = await orchestrator.process(processed)
reply = ""
trace: dict = {
"severity": processed.severity.value if processed.severity else None,
"agents": [r.agent_name for r in responses],
"tier": None,
"actions_dispatched": [],
"reasoning": None,
}
for r in responses:
if r.agent_name == "clinical_reasoning":
md = r.metadata or {}
trace["tier"] = md.get("tier")
trace["actions_dispatched"] = [
a.get("type") for a in (md.get("actions") or [])
]
trace["reasoning"] = md.get("reasoning")
reply = r.response_text
break
if not reply and responses:
reply = responses[0].response_text
if not reply:
reply = "(no agent response)"
return JSONResponse({"reply": reply, "trace": trace})
def _vision_severity_override(vision: dict) -> SignalSeverity | None:
"""Force a non-routine severity when the vision values are clearly clinical.
Skips the LLM severity classifier (which is noisy) for unambiguous cases:
glucose <70 / >250 -> URGENT, BP >=180 sys or >=120 dia -> CRISIS.
"""
detected = (vision.get("detected_type") or "").lower()
values = vision.get("extracted_values") or {}
if detected == "glucose_reading":
g = (
values.get("glucose")
or values.get("glucose_level")
or values.get("glucose_mg_dl")
or values.get("value")
or values.get("reading")
or values.get("level")
)
try:
gnum = float(g)
except (TypeError, ValueError):
return None
if gnum < 54 or gnum > 300:
return SignalSeverity.CRISIS
if gnum < 70 or gnum > 250:
return SignalSeverity.URGENT
if detected == "bp_reading":
sys_v = values.get("systolic") or values.get("systolic_bp")
dia_v = values.get("diastolic") or values.get("diastolic_bp")
try:
s_n, d_n = float(sys_v), float(dia_v)
except (TypeError, ValueError):
return None
if s_n >= 180 or d_n >= 120:
return SignalSeverity.CRISIS
if s_n >= 160 or d_n >= 100 or s_n <= 90 or d_n <= 60:
return SignalSeverity.URGENT
return None
def _vision_to_message(vision: dict) -> str:
"""Build the synthetic patient message from the vision JSON.
Glucose / BP readings get phrased so the clinical agent's red-flag
keyword matchers fire as expected.
"""
detected = (vision.get("detected_type") or "").lower()
values = vision.get("extracted_values") or {}
if detected == "glucose_reading":
g = (
values.get("glucose")
or values.get("glucose_level")
or values.get("glucose_mg_dl")
or values.get("value")
or values.get("reading")
or values.get("level")
)
if g is not None:
unit = values.get("unit") or values.get("units") or "mg/dL"
try:
gnum = float(g)
except (TypeError, ValueError):
gnum = None
base = f"I just measured my glucose. Reading is {g} {unit}."
if gnum is not None and (gnum < 70 or gnum > 250):
base += " This looks abnormal sir, what should I do?"
return base
if detected == "bp_reading":
sys = values.get("systolic") or values.get("systolic_bp")
dia = values.get("diastolic") or values.get("diastolic_bp")
hr = values.get("heart_rate") or values.get("pulse")
if sys and dia:
base = f"My BP just measured {sys}/{dia}"
if hr:
base += f" with pulse {hr}"
try:
s_n, d_n = float(sys), float(dia)
except (TypeError, ValueError):
s_n = d_n = None
if s_n is not None and d_n is not None and (
s_n >= 180 or d_n >= 120 or s_n <= 90 or d_n <= 60
):
base += ". This looks abnormal sir, what should I do"
return base + "."
desc = vision.get("raw_description") or "I just took a photo."
return f"I just took a photo, please look at this: {desc}"
@app.post("/sim/upload")
async def sim_upload(file: UploadFile = File(...)):
raw = await file.read()
if not raw:
raise HTTPException(status_code=400, detail="empty upload")
if len(raw) > 6 * 1024 * 1024:
raise HTTPException(status_code=413, detail="file too large (max 6 MB)")
media_type = file.content_type or "image/jpeg"
try:
vision = await analyze_image(raw, settings, media_type=media_type)
except Exception as e:
logger.error(f"vision analysis failed: {e}")
raise HTTPException(status_code=502, detail=f"vision analysis failed: {e}")
synthesised = _vision_to_message(vision)
forced_severity = _vision_severity_override(vision)
profile_phone = "+2348012345001"
incoming = IncomingMessage(
id=f"sim-img-{int(datetime.now().timestamp() * 1000)}",
sender_phone=profile_phone,
message_type=MessageType.IMAGE,
content=synthesised,
timestamp=datetime.now(timezone.utc),
raw_payload={"sim": True, "vision": vision, "filename": file.filename},
)
processed = await router.route(incoming)
if forced_severity is not None:
processed.severity = forced_severity
responses = await orchestrator.process(processed)
reply = ""
trace: dict = {
"severity": processed.severity.value if processed.severity else None,
"agents": [r.agent_name for r in responses],
"tier": None,
"actions_dispatched": [],
"reasoning": None,
}
for r in responses:
if r.agent_name == "clinical_reasoning":
md = r.metadata or {}
trace["tier"] = md.get("tier")
trace["actions_dispatched"] = [
a.get("type") for a in (md.get("actions") or [])
]
trace["reasoning"] = md.get("reasoning")
reply = r.response_text
break
if not reply and responses:
reply = responses[0].response_text
if not reply:
reply = "(no agent response)"
return JSONResponse(
{
"vision": vision,
"message": synthesised,
"reply": reply,
"trace": trace,
}
)
@app.post("/sim/reset", include_in_schema=False)
async def sim_reset():
"""Wipe demo runtime state between takes (clinician notes + circle log).
Useful when re-recording the demo: keeps the seeded patient + DB intact
but clears the dashboard cards and Funmi's chat panel.
"""
import json
DASHBOARD_DIR.mkdir(parents=True, exist_ok=True)
(DASHBOARD_DIR / "clinician_notes.json").write_text(
json.dumps({"notes": []}, indent=2), encoding="utf-8"
)
(DASHBOARD_DIR / "circle_log.json").write_text(
json.dumps({"entries": []}, indent=2), encoding="utf-8"
)
return {"status": "ok", "reset": ["clinician_notes.json", "circle_log.json"]}
# --- Convenience root ---
@app.get("/", include_in_schema=False)
async def root():
return JSONResponse({
"service": "olumide",
"version": "0.2.0",
"endpoints": {
"sim_chat": "/sim",
"clinician_dashboard": "/dashboard/",
"health": "/health",
"whatsapp_webhook": "/webhook",
"device_webhook": "/webhook/device",
},
})