forked from Do-yoon/medgemma-hackathon
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_server.py
More file actions
1206 lines (1060 loc) · 70.2 KB
/
Copy pathapi_server.py
File metadata and controls
1206 lines (1060 loc) · 70.2 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
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# api_server.py
from fastapi import FastAPI, HTTPException, Header, Depends
from pydantic import BaseModel
from typing import Dict, Any, Optional, Literal
import torch, traceback, random, os, json, asyncio, subprocess, base64, re
from fastapi.responses import HTMLResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
from clinical_flow_coordinator import (
ClinicalBlackboard, ClinicalReasoningCoordinator, MedGemmaClient,
ClinicalState, WorkflowState, HITLDecision,
AcuityReasoner, ReadinessReasoner, ComplianceReasoner, FinancialClearanceReasoner,
ResourceCoordinationReasoner, OperationalPrioritizationReasoner, CareTeamCommunicationAgent, AdministrativeInterventionAgent
)
from intent_engine import ClinicalIntentEngine, apply_emergency_override, recompute_priority
intent_engine = ClinicalIntentEngine()
app = FastAPI(title="Clinical Flow Coordinator API", version="1.0")
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_DIR = os.path.join(BASE_DIR, "static")
if os.path.exists(STATIC_DIR):
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
orchestrator = None
medgemma_client = None
CASE_CONTEXT: Dict[str, Dict[str, Any]] = {}
GCP_PROJECT_ID = os.getenv("GCP_PROJECT_ID", "project-1123e1e7-231b-45b8-981")
VERTEX_LOCATION = os.getenv("VERTEX_LOCATION", "asia-southeast1")
VERTEX_MEDGEMMA_LOCATION = os.getenv("VERTEX_MEDGEMMA_LOCATION", VERTEX_LOCATION)
VERTEX_MEDASR_LOCATION = os.getenv("VERTEX_MEDASR_LOCATION", "asia-east1")
MEDGEMMA_MODEL_ID = os.getenv("VERTEX_MEDGEMMA_MODEL_ID", "google_medgemma-1_5-4b-it-1771927636658")
MEDGEMMA_ENDPOINT = os.getenv("VERTEX_MEDGEMMA_ENDPOINT", "google_medgemma-1_5-4b-it-mg-one-click-deploy")
MEDASR_MODEL_ID = os.getenv("VERTEX_MEDASR_MODEL_ID", "google_medasr-1771927583544")
MEDASR_ENDPOINT = os.getenv("VERTEX_MEDASR_ENDPOINT", "google_medasr-mg-one-click-deploy")
AI_READER_SA = os.getenv("AI_READER_SERVICE_ACCOUNT", "medgemma@project-1123e1e7-231b-45b8-981.iam.gserviceaccount.com")
CLINICIAN_WRITER_SA = os.getenv("CLINICIAN_WRITER_SERVICE_ACCOUNT", "clinician@project-1123e1e7-231b-45b8-981.iam.gserviceaccount.com")
ENABLE_SA_IMPERSONATION = os.getenv("ENABLE_SA_IMPERSONATION", "0") == "1"
READ_TOKEN = os.getenv("ORCHESTRATOR_READ_TOKEN", "")
WRITE_TOKEN = os.getenv("CLINICIAN_WRITE_TOKEN", "")
MODEL_BACKEND = os.getenv("MODEL_BACKEND", "vertex").lower()
def _check_token(required: str, provided: Optional[str], token_type: str):
if not required:
return
if provided != required:
raise HTTPException(status_code=403, detail=f"Invalid {token_type} token")
async def require_read_access(x_read_token: Optional[str] = Header(default=None, alias="X-Read-Token")):
_check_token(READ_TOKEN, x_read_token, "read")
async def require_write_access(x_write_token: Optional[str] = Header(default=None, alias="X-Write-Token")):
_check_token(WRITE_TOKEN, x_write_token, "write")
def build_fhir_bundle(case_data: Dict[str, Any], execution_type: str = "AI_DRAFT_READONLY") -> Dict[str, Any]:
patient_id = case_data["patient_id"]
pat_id_short = patient_id.split(" ")[0]
priority_code = "routine"
if case_data.get("intent") == "emergent":
priority_code = "stat"
elif case_data.get("triage_level") == "URGENT":
priority_code = "urgent"
return {
"resourceType": "Bundle",
"type": "transaction",
"entry": [
{
"fullUrl": f"urn:uuid:patient-{pat_id_short}",
"resource": {"resourceType": "Patient", "id": pat_id_short},
},
{
"fullUrl": "urn:uuid:servicerequest-1",
"resource": {
"resourceType": "ServiceRequest",
"status": "active",
"intent": "order",
"priority": priority_code,
"subject": {"reference": f"urn:uuid:patient-{pat_id_short}"},
"code": {"text": case_data.get("procedure", "Unknown")},
},
},
{
"fullUrl": "urn:uuid:task-1",
"resource": {
"resourceType": "Task",
"status": "in-progress",
"intent": "order",
"description": "AI Clinical Flow Orchestration",
"note": [{"text": f"Blockers detected: {case_data.get('blocker_msg', 'None')}"}],
"executionType": {"text": execution_type},
},
},
],
}
def post_bundle_to_cloud_healthcare(bundle: Dict[str, Any]) -> Dict[str, Any]:
if os.getenv("ENABLE_CLOUD_HEALTHCARE_WRITE", "0") != "1":
return {"mode": "mock", "detail": "Cloud Healthcare write disabled"}
project_id = os.getenv("GCP_PROJECT_ID") or os.getenv("GOOGLE_CLOUD_PROJECT")
location = os.getenv("GCP_LOCATION", "us-central1")
dataset_id = os.getenv("GCP_HEALTHCARE_DATASET_ID")
fhir_store_id = os.getenv("GCP_FHIR_STORE_ID")
if not all([project_id, dataset_id, fhir_store_id]):
raise RuntimeError("GCP_PROJECT_ID/GOOGLE_CLOUD_PROJECT, GCP_HEALTHCARE_DATASET_ID, GCP_FHIR_STORE_ID are required")
session = _authorized_session(target_service_account=CLINICIAN_WRITER_SA)
url = (
f"https://healthcare.googleapis.com/v1/projects/{project_id}/locations/{location}/"
f"datasets/{dataset_id}/fhirStores/{fhir_store_id}/fhir"
)
response = session.post(url, json=bundle, timeout=20)
body = response.text[:500]
if response.status_code >= 400:
raise RuntimeError(f"Cloud Healthcare API error {response.status_code}: {body}")
return {"mode": "cloud", "status_code": response.status_code, "detail": body}
def _authorized_session(target_service_account: Optional[str] = None):
from google.auth import default, impersonated_credentials
from google.auth.transport.requests import AuthorizedSession
credentials, _ = default(scopes=["https://www.googleapis.com/auth/cloud-platform"])
if target_service_account and ENABLE_SA_IMPERSONATION:
try:
credentials = impersonated_credentials.Credentials(
source_credentials=credentials,
target_principal=target_service_account,
target_scopes=["https://www.googleapis.com/auth/cloud-platform"],
lifetime=3600,
)
except Exception as e:
# Fall back to direct ADC when impersonation isn't configured.
print(f"⚠️ SA impersonation fallback to ADC for {target_service_account}: {e}")
return AuthorizedSession(credentials)
def _get_with_auth_fallback(url: str, *, params: Optional[Dict[str, Any]] = None, timeout: int = 20):
try:
session = _authorized_session(target_service_account=AI_READER_SA)
return session.get(url, params=params, timeout=timeout)
except Exception as e:
print(f"⚠️ Auth fallback(GET) due to impersonation issue: {e}")
session = _authorized_session(target_service_account=None)
return session.get(url, params=params, timeout=timeout)
def _post_with_auth_fallback(url: str, *, json_body: Dict[str, Any], timeout: int = 60):
try:
session = _authorized_session(target_service_account=AI_READER_SA)
return session.post(url, json=json_body, timeout=timeout)
except Exception as e:
print(f"⚠️ Auth fallback(POST) due to impersonation issue: {e}")
session = _authorized_session(target_service_account=None)
return session.post(url, json=json_body, timeout=timeout)
def _post_json_with_fallback_hosts(resource: str, location: str, json_body: Dict[str, Any], timeout: int = 60):
dedicated_dns = _get_dedicated_dns(resource, location)
urls = []
if dedicated_dns:
urls.append(f"https://{dedicated_dns}/v1/{resource}:predict")
urls.append(f"https://{location}-aiplatform.googleapis.com/v1/{resource}:predict")
last_response = None
last_exception: Optional[str] = None
for url in urls:
try:
response = _post_with_auth_fallback(url, json_body=json_body, timeout=timeout)
last_response = response
if response.status_code < 400:
return response
# Dedicated endpoint hint can be returned from shared-domain 400 errors.
if response.status_code == 400:
m = re.search(r"dedicated domain name '([^']+)'", response.text or "", re.IGNORECASE)
if m:
dedicated_from_error = m.group(1).strip()
retry_url = f"https://{dedicated_from_error}/v1/{resource}:predict"
try:
retry = _post_with_auth_fallback(retry_url, json_body=json_body, timeout=timeout)
if retry.status_code < 400:
return retry
last_response = retry
except Exception as e:
last_exception = str(e)
continue
except Exception as e:
last_exception = str(e)
continue
if last_response is not None:
return last_response
raise RuntimeError(
"All endpoint hosts failed without HTTP response. "
f"Likely DNS/network issue for dedicated endpoint domain. last_exception={last_exception}"
)
def _resource_candidates(model_id: str, endpoint_id: str, location: str):
resources = []
if endpoint_id:
resources.append(endpoint_id if endpoint_id.startswith("projects/") else f"projects/{GCP_PROJECT_ID}/locations/{location}/endpoints/{endpoint_id}")
if model_id:
resources.append(f"projects/{GCP_PROJECT_ID}/locations/{location}/publishers/google/models/{model_id}")
return resources
def _vertex_predict(resource: str, body: Dict[str, Any], location: str) -> Dict[str, Any]:
response = _post_json_with_fallback_hosts(resource, location, body, timeout=60)
if response.status_code >= 400:
raise RuntimeError(f"{resource} predict failed ({response.status_code}): {response.text[:400]}")
return response.json()
def _resolve_endpoint_resource(endpoint_hint: str, location: str) -> str:
if endpoint_hint.startswith("projects/"):
return endpoint_hint
if endpoint_hint.isdigit():
return f"projects/{GCP_PROJECT_ID}/locations/{location}/endpoints/{endpoint_hint}"
list_url = f"https://aiplatform.googleapis.com/v1/projects/{GCP_PROJECT_ID}/locations/{location}/endpoints"
filt = f'display_name="{endpoint_hint}"'
resp = _get_with_auth_fallback(list_url, params={"filter": filt}, timeout=20)
if resp.status_code < 400:
endpoints = resp.json().get("endpoints", [])
if endpoints:
name = endpoints[0].get("name")
if name:
return name
return f"projects/{GCP_PROJECT_ID}/locations/{location}/endpoints/{endpoint_hint}"
def _get_dedicated_dns(endpoint_resource: str, location: str) -> str:
url = f"https://{location}-aiplatform.googleapis.com/v1/{endpoint_resource}"
resp = _get_with_auth_fallback(url, timeout=20)
if resp.status_code < 400:
dns = (resp.json().get("dedicatedEndpointDns") or "").strip()
if dns:
return dns.replace("https://", "").strip("/")
return ""
def _extract_asr_text(payload: Dict[str, Any]) -> str:
preds = payload.get("predictions", [])
if not preds:
return ""
first = preds[0]
if isinstance(first, str):
return first.strip()
if isinstance(first, dict):
for key in ["transcript", "text", "prediction", "output", "generated_text"]:
value = first.get(key)
if isinstance(value, str) and value.strip():
return value.strip()
return ""
def _has_adc_credentials() -> bool:
try:
from google.auth import default
default(scopes=["https://www.googleapis.com/auth/cloud-platform"])
return True
except Exception:
return False
def _extract_context_fields(patient_context: str) -> Dict[str, str]:
text = patient_context or ""
out = {"procedure": "", "vitals": "", "labs": ""}
m_proc = re.search(r"Procedure:\s*([^,]+)", text, re.IGNORECASE)
m_vitals = re.search(r"Vitals:\s*([^,]+(?:,[^,]+)*)", text, re.IGNORECASE)
m_labs = re.search(r"Labs:\s*(.+)$", text, re.IGNORECASE)
if m_proc:
out["procedure"] = m_proc.group(1).strip()
if m_vitals:
out["vitals"] = m_vitals.group(1).strip()
if m_labs:
out["labs"] = m_labs.group(1).strip()
return out
def _keyword_route_tool(message: str, patient_context: str) -> Optional[Dict[str, str]]:
msg = (message or "").lower()
ctx = _extract_context_fields(patient_context)
consent_kw = ["unconscious", "consent impossible", "no guardian", "surrogate", "consent unavailable"]
pa_kw = ["pa", "prior authorization", "payer", "insurance", "clinical justification", "summary"]
transport_kw = ["transport", "stretcher", "wheelchair", "bed transfer"]
sms_kw = ["sms", "text message", "contact guardian", "notify surrogate"]
order_kw = ["order", "submit ehr", "update record", "place order"]
if any(k in msg for k in pa_kw):
reply = (
f"Here is a PA clinical justification draft.\n"
f"- Procedure: {ctx['procedure']}\n"
f"- Clinical status: {ctx['vitals']}\n"
f"- Supporting labs: {ctx['labs']}\n"
f"Based on these findings, the requested imaging is medically necessary to evaluate current risk and guide treatment."
)
return {"tool": "generate_pa_summary", "reply": reply}
if ("guardian" in msg or "surrogate" in msg or "consent" in msg) and any(k in msg for k in consent_kw):
return {"tool": "emergency_consent_bypass", "reply": "Recommend emergency consent exception path (2-MD override). On approval, an audit-compliant exception log will be recorded."}
if any(k in msg for k in transport_kw):
return {"tool": "update_transport_mode", "reply": "Transport mode change has been applied. Transfer tasks were updated to match current patient condition."}
if any(k in msg for k in sms_kw):
return {"tool": "sms_surrogate", "reply": "Created a text-notification task for surrogate contact and consent coordination."}
if any(k in msg for k in order_kw):
return {"tool": "submit_ehr_order", "reply": "Your instruction has been translated into an EHR order/update task."}
return None
PATIENT_SCENARIOS = {
"p1_routine": {
"patient_id": "P1 - Lee, S. (52/M)", "procedure_code": "CTCHEST", "procedure_display": "Chest CT (No Contrast)",
"location": "Pulmo Ward Room 777", "insurance_plan": "Private", "vitals_summary": "Stable, BP 128/74, HR 72",
"labs_summary": "Cr 0.92 (Normal)", "comorbidities": ["HTN", "Hyperlipidemia"], "allergies": ["None"],
},
"p2_prep_blocker": {
"patient_id": "P2 - Park, J. (61/F)", "procedure_code": "CTABD", "procedure_display": "APCT w/ Contrast (13:00)",
"location": "GI Ward Room 802", "insurance_plan": "Private", "vitals_summary": "Abdominal pain, HR 94, Temp 37.2",
"labs_summary": "Cr 1.08 (Outdated >30 days)", "comorbidities": ["T2DM"], "allergies": ["Penicillin"],
},
"p3_consent_allergy": {
"patient_id": "P3 - Kim, D. (78/M)", "procedure_code": "CTBRAIN", "procedure_display": "Brain CT w/ Contrast (15:10)",
"location": "Neuro Ward Room 605", "insurance_plan": "Private", "vitals_summary": "Confused, BP 142/86, HR 88",
"labs_summary": "Cr 1.02", "comorbidities": ["Stroke history", "AFib"], "allergies": ["Contrast Allergy (Mild rash)"],
},
"p4_emergent_stat": {
"patient_id": "P4 - Choi, M. (67/F)", "procedure_code": "CTBRAIN_STAT", "procedure_display": "STAT Brain CT (Contrast)",
"location": "ED Resus-2", "insurance_plan": "ED (Unknown)", "vitals_summary": "Acute mental change, HR 112, BP 160/95",
"labs_summary": "Cr 1.14", "comorbidities": ["Unknown"], "allergies": ["Unknown"],
},
"p5_pa_blocker": {
"patient_id": "P5 - Han, K. (45/M)", "procedure_code": "CTCHEST_ABD", "procedure_display": "Fever Focus: Chest+APCT",
"location": "ID Ward Room 1007", "insurance_plan": "HMO", "vitals_summary": "Persistent fever 39.1, HR 105",
"labs_summary": "CRP 18.2, WBC 14K", "comorbidities": ["None"], "allergies": ["None"],
}
}
def init_scenario_blackboard(scenario_name: str = "p1_routine"):
data = PATIENT_SCENARIOS.get(scenario_name, PATIENT_SCENARIOS["p1_routine"])
cs = ClinicalState(
patient_id=data["patient_id"], procedure_code=data["procedure_code"], procedure_display=data["procedure_display"],
location=data["location"], insurance_plan=data["insurance_plan"], vitals_summary=data["vitals_summary"],
labs_summary=data["labs_summary"], comorbidities=data["comorbidities"], allergies=data["allergies"]
)
return ClinicalBlackboard(clinical_state=cs, workflow_state=WorkflowState(), hitl_state=HITLDecision())
@app.on_event("startup")
async def startup_event():
global orchestrator, medgemma_client
os.environ.setdefault("GCP_PROJECT_ID", GCP_PROJECT_ID)
os.environ.setdefault("GOOGLE_CLOUD_PROJECT", GCP_PROJECT_ID)
os.environ.setdefault("VERTEX_LOCATION", VERTEX_LOCATION)
os.environ.setdefault("VERTEX_MEDGEMMA_LOCATION", VERTEX_MEDGEMMA_LOCATION)
os.environ.setdefault("VERTEX_MEDASR_LOCATION", VERTEX_MEDASR_LOCATION)
os.environ.setdefault("VERTEX_MEDGEMMA_MODEL_ID", MEDGEMMA_MODEL_ID)
os.environ.setdefault("VERTEX_MEDGEMMA_ENDPOINT", MEDGEMMA_ENDPOINT)
os.environ.setdefault("VERTEX_MEDASR_MODEL_ID", MEDASR_MODEL_ID)
os.environ.setdefault("VERTEX_MEDASR_ENDPOINT", MEDASR_ENDPOINT)
auth_mode = "enabled" if (READ_TOKEN or WRITE_TOKEN) else "disabled"
print(f"Starting API... (model_backend={MODEL_BACKEND}, project={GCP_PROJECT_ID}, medgemma={MEDGEMMA_MODEL_ID}@{VERTEX_MEDGEMMA_LOCATION}, medasr={MEDASR_MODEL_ID}@{VERTEX_MEDASR_LOCATION}, auth={auth_mode})")
if MODEL_BACKEND == "vertex" and not _has_adc_credentials():
print("ADC not found. Run: gcloud auth application-default login && gcloud auth application-default set-quota-project project-1123e1e7-231b-45b8-981")
# Keep coordinator wiring explicit for clarity.
orchestrator = ClinicalReasoningCoordinator(
AcuityReasoner(), ReadinessReasoner(), ComplianceReasoner(),
FinancialClearanceReasoner(), ResourceCoordinationReasoner(), OperationalPrioritizationReasoner(),
CareTeamCommunicationAgent(), AdministrativeInterventionAgent()
)
print("API ready.")
# Optional local GPU telemetry endpoint.
@app.get("/api/system/gpu")
async def get_gpu_status():
if MODEL_BACKEND == "vertex":
return {"gpu_count": 0, "avg_util": 0, "mode": "vertex"}
try:
# Query all GPU utilization percentages through nvidia-smi.
result = subprocess.check_output(
["nvidia-smi", "--query-gpu=utilization.gpu", "--format=csv,noheader,nounits"],
encoding="utf-8", timeout=2
)
lines = result.strip().split('\n')
utils = [int(line.strip()) for line in lines if line.strip().isdigit()]
if not utils:
return {"gpu_count": 8, "avg_util": 0}
avg_util = sum(utils) // len(utils)
return {"gpu_count": len(utils), "avg_util": avg_util, "mode": "local_gpu"}
except Exception as e:
# Safe fallback on telemetry error.
return {"gpu_count": 8, "avg_util": 0, "mode": "local_gpu"}
@app.post("/api/flow/run_patient_stream")
async def run_patient_stream(scenario: str, _auth: None = Depends(require_read_access)):
global orchestrator
async def event_generator():
bb = init_scenario_blackboard(scenario)
try:
async for step_data in orchestrator.step_stream(bb):
if step_data["status"] == "running":
yield f"data: {json.dumps({'event': 'running', 'agent_name': step_data['agent']})}\n\n"
await asyncio.sleep(0.01)
elif step_data["status"] == "agent_done":
yield f"data: {json.dumps({'event': 'agent_log', 'agent_name': step_data['agent'], 'decision': step_data['decision']})}\n\n"
await asyncio.sleep(0.01)
elif step_data["status"] == "done":
final_bb = recompute_priority(step_data["bb"])
cs = final_bb.clinical_state
comm_result = next((a for a in reversed(final_bb.agent_history) if a.agent_id == "communication_agent"), None)
blockers = cs.readiness_blocking.copy()
if cs.pa_status.value == "REQUIRED_MISSING": blockers.append("PA Pending")
if cs.consent_status.value == "REQUIRED_MISSING": blockers.append("Consent Needed")
is_blocked = len(blockers) > 0 or cs.intent == "emergent"
blocker_msg = " | ".join(blockers) if blockers else "Ready for Transport"
if cs.intent == "emergent": blocker_msg = "⚠️ STAT ALERT: Immediate Action Required"
result_dict = {
"patient_id": cs.patient_id, "scenario": scenario, "intent": cs.intent,
"triage_level": cs.triage_level, "priority_score": cs.priority_score,
"procedure": cs.procedure_display, "location": cs.location, "blocker_msg": blocker_msg,
"action_msg": comm_result.decision.get("action_label", "Action") if comm_result else "Ready",
"chatbot_message": comm_result.ui_message if comm_result else "Completed.",
"is_blocked": is_blocked
}
CASE_CONTEXT[cs.patient_id] = result_dict.copy()
yield f"data: {json.dumps({'event': 'complete', 'result': result_dict})}\n\n"
except Exception as e:
err = str(e)
if "default credentials were not found" in err.lower():
err = "Vertex authentication failed: ADC not found. Run gcloud auth application-default login."
payload = {"event": "error", "message": err}
yield f"data: {json.dumps(payload, ensure_ascii=False)}\n\n"
return StreamingResponse(event_generator(), media_type="text/event-stream")
class ChatRequest(BaseModel):
message: str; patient_context: str
class ASRRequest(BaseModel):
audio_base64: str
mime_type: str = "audio/webm"
language_code: str = "en-US"
@app.post("/api/chat/tool_call")
async def chat_tool_call(req: ChatRequest, _auth: None = Depends(require_read_access)):
global medgemma_client
routed = _keyword_route_tool(req.message, req.patient_context)
if routed:
return routed
sys = """You are a medical Tool Call router.
Tools: [update_transport_mode, sms_surrogate, submit_ehr_order, emergency_consent_bypass, generate_pa_summary, general_reply].
CRITICAL RULE 1: If the user states the patient is unconscious AND without guardians, use 'emergency_consent_bypass'.
CRITICAL RULE 2: If the user asks for a PA (Prior Authorization) document or summary, you MUST use 'generate_pa_summary' and WRITE a 2-3 sentence clinical justification (in English) proving medical necessity from vitals and labs.
Output valid JSON: {"tool": "one_of_tools", "reply": "English reply..."}"""
# Tool-call structured output
class ToolCallOutput(BaseModel):
tool: Literal[
"update_transport_mode",
"sms_surrogate",
"submit_ehr_order",
"emergency_consent_bypass",
"generate_pa_summary",
"general_reply",
]
reply: str
try:
res = await MedGemmaClient.get_instance(0).chat(
sys,
f"Context: {req.patient_context}. User says: '{req.message}'. Determine the correct tool and generate an English reply.",
ToolCallOutput
)
return res
except Exception:
return {"tool": "general_reply", "reply": "Request logged. The coordinator can review and convert this into an execution task."}
@app.post("/api/asr/transcribe")
async def asr_transcribe(req: ASRRequest, _auth: None = Depends(require_read_access)):
try:
if not req.audio_base64:
raise HTTPException(status_code=400, detail="audio_base64 is required")
# MedASR is English-only for this demo.
language_code = "en-US"
resolved_endpoint = _resolve_endpoint_resource(MEDASR_ENDPOINT, VERTEX_MEDASR_LOCATION)
# ASR uses dedicated endpoint serving; endpoint-only is the most stable path.
resources = [resolved_endpoint]
payload_variants = [
# Variant group A: Vertex Predict envelope
{
"instances": [{"content": req.audio_base64, "mimeType": req.mime_type}],
"parameters": {"languageCode": language_code},
},
{
"instances": [{"audio": {"bytesBase64Encoded": req.audio_base64, "mimeType": req.mime_type}}],
"parameters": {"languageCode": language_code},
},
{
"instances": [{"bytesBase64Encoded": req.audio_base64}],
"parameters": {"languageCode": language_code},
},
# Variant group B: MedASR dedicated schema (raw request object)
{
"content": req.audio_base64,
"mimeType": req.mime_type,
"languageCode": language_code,
},
{
"audio": {
"bytesBase64Encoded": req.audio_base64,
"mimeType": req.mime_type,
},
"languageCode": language_code,
},
{
"audioBytesBase64": req.audio_base64,
"mimeType": req.mime_type,
"languageCode": language_code,
},
]
errors = []
for resource in resources:
for payload in payload_variants:
try:
# For raw schema payloads, call endpoint host directly with the same predict path.
out = await asyncio.to_thread(_vertex_predict, resource, payload, VERTEX_MEDASR_LOCATION)
transcript = _extract_asr_text(out)
if transcript:
return {"transcript": transcript, "resource": resource, "mode": "vertex_medasr", "language": language_code}
errors.append(f"{resource}: empty transcript")
except Exception as e:
errors.append(str(e))
raise HTTPException(status_code=502, detail={"message": "MedASR transcription failed", "errors": errors[:3]})
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail={"message": "MedASR unexpected error", "error": str(e)})
class FHIRDraftRequest(BaseModel):
patient_id: str
class HITLExecuteRequest(BaseModel):
patient_id: str
reviewer_role: str = "coordinator"
reviewer_comment: Optional[str] = None
@app.post("/api/fhir/draft")
async def create_fhir_draft(req: FHIRDraftRequest, _auth: None = Depends(require_read_access)):
case_data = CASE_CONTEXT.get(req.patient_id)
if not case_data:
raise HTTPException(status_code=404, detail="Patient context not found. Run flow first.")
bundle = build_fhir_bundle(case_data, execution_type="AI_DRAFT_READONLY")
return {"patient_id": req.patient_id, "bundle": bundle}
@app.post("/api/hitl/approve_execute")
async def approve_execute(req: HITLExecuteRequest, _auth: None = Depends(require_write_access)):
case_data = CASE_CONTEXT.get(req.patient_id)
if not case_data:
raise HTTPException(status_code=404, detail="Patient context not found. Run flow first.")
bundle = build_fhir_bundle(case_data, execution_type="HITL_EXECUTED_WRITE")
try:
healthcare_result = await asyncio.to_thread(post_bundle_to_cloud_healthcare, bundle)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
return {
"status": "executed",
"patient_id": req.patient_id,
"reviewer_role": req.reviewer_role,
"reviewer_comment": req.reviewer_comment,
"healthcare_result": healthcare_result,
"bundle": bundle,
}
@app.get("/", response_class=HTMLResponse)
async def dashboard():
return """
<!DOCTYPE html>
<html>
<head>
<title>Clinical Flow Coordinator OS</title>
<meta charset="utf-8">
<style>
body { font-family: -apple-system, sans-serif; background: #eef2f5; margin: 0; padding: 15px; color: #2c3e50; }
.header { margin-bottom: 15px; display: flex; justify-content: space-between; align-items: center; }
.header h1 { margin: 0; font-size: 1.6em; color: #1a252f; display:flex; align-items:center; gap:15px; }
/* Live GPU telemetry badge styling */
.privacy-badge { background: #2ecc71; color: white; padding: 4px 10px; border-radius: 20px; font-size: 0.55em; font-weight: bold; letter-spacing: 0.5px; display:flex; align-items:center; gap:5px; box-shadow: 0 0 10px rgba(46,204,113,0.4); transition: all 0.3s ease;}
.privacy-badge.high-load { background: #e74c3c; box-shadow: 0 0 15px rgba(231,76,60,0.6); animation: pulse-red 1s infinite; }
.privacy-badge.mid-load { background: #f39c12; box-shadow: 0 0 12px rgba(243,156,18,0.5); }
.privacy-badge span { width:6px; height:6px; background:#fff; border-radius:50%; display:inline-block; animation: blink 1.5s infinite;}
@keyframes pulse-red { 0%, 100% { transform: scale(1); } 50% { transform: scale(1.05); } }
@keyframes blink { 0%, 100% { opacity: 0.3; } 50% { opacity: 1; } }
.main-layout { display: grid; grid-template-columns: 320px 1.2fr 450px; gap: 15px; align-items: start; height: 90vh; }
.emr-panel { background: #fff; border-radius: 8px; height: 100%; display: flex; flex-direction: column; box-shadow: 0 4px 10px rgba(0,0,0,0.08); border: 1px solid #dfe6e9; overflow: hidden; }
.emr-top-nav { background: #182C4F; color: white; padding: 12px 15px; font-weight: bold; font-size: 0.9em; display: flex; justify-content: space-between; align-items: center;}
.order-entry { padding: 15px; background: #f8f9fa; border-bottom: 1px solid #dfe6e9; }
.order-entry-title { font-size: 0.8em; color: #7f8c8d; font-weight: bold; text-transform: uppercase; margin-bottom: 8px; }
.emr-btn { width: 100%; padding: 8px; background: #fff; color: #2c3e50; border: 1px solid #bdc3c7; border-radius: 4px; margin-bottom: 6px; cursor: pointer; text-align: left; font-size: 0.85em; font-weight: bold; transition: 0.2s; box-shadow: 0 1px 2px rgba(0,0,0,0.05);}
.emr-btn:hover { border-color: #3498db; background: #f0f8ff; }
.emr-btn-stat { border-left: 4px solid #e74c3c; }
.patient-chart { flex: 1; padding: 15px; overflow-y: auto; }
.ehr-status-header { color: #182C4F; border-bottom: 2px solid #3498db; padding-bottom: 5px; margin-top: 0; margin-bottom: 15px; font-size: 1.1em; font-weight: bold; display: flex; align-items: center; gap: 8px;}
.chart-name { font-size: 1.15em; font-weight: bold; color: #2c3e50; margin-bottom: 15px;}
.chart-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; font-size: 0.8em; margin-bottom: 15px; }
.chart-box { background: #fdfdfd; border: 1px solid #ecf0f1; padding: 8px; border-radius: 4px; }
.chart-label { color: #7f8c8d; font-weight: bold; margin-bottom: 3px; font-size: 0.9em;}
.chart-val { color: #2c3e50; font-weight: 600; }
.ehr-timeline { border-left: 2px solid #bdc3c7; margin-left: 10px; padding-left: 15px; font-size: 0.85em; }
.tl-item { margin-bottom: 15px; position: relative; }
.tl-item::before { content: ''; position: absolute; left: -21px; top: 2px; width: 10px; height: 10px; border-radius: 50%; background: #bdc3c7; }
.tl-time { color: #7f8c8d; font-weight: bold; margin-bottom: 2px; }
.tl-desc { color: #2c3e50; }
.tl-item.order::before { background: #3498db; }
.tl-item.alert::before { background: #e74c3c; }
.tl-item.resolve::before { background: #2ecc71; }
.tl-item.hold::before { background: #f39c12; }
.tl-item.reject::before { background: #e74c3c; border: 2px solid #c0392b; }
.queue-panel { display: flex; flex-direction: column; gap: 10px; height: 100%; overflow-y: auto; padding-right: 5px; }
.kpi-bar { display: flex; gap: 10px; margin-bottom: 10px; }
.kpi-mini { flex: 1; background: white; padding: 10px; border-radius: 6px; text-align: center; font-weight: bold; font-size: 0.9em; box-shadow: 0 2px 4px rgba(0,0,0,0.05); }
.patient-card { background: white; padding: 12px 15px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.05); border: 1px solid #dfe6e9; cursor: pointer; display: flex; align-items: flex-start; gap: 12px; transition: 0.3s;}
.card-active { border: 2px solid #3498db; transform: translateX(5px); }
.rank-badge { width: 28px; height: 28px; background: #2c3e50; color: white; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-weight: bold; font-size: 1em; flex-shrink: 0; margin-top: 2px; }
.rank-1 { background: #d94852; transform: scale(1.15); box-shadow: 0 0 8px rgba(217,72,82,0.5); }
.rank-2 { background: #f1a94e; }
.card-content { flex: 1; }
.badge { padding: 3px 6px; border-radius: 4px; font-size: 0.65em; font-weight: bold; color: white; float: right; }
.badge-emergent { background: #d94852; } .badge-urgent { background: #f1a94e; } .badge-routine { background: #55af7b; }
.card-header { font-size: 1.05em; font-weight: bold; margin-bottom: 3px; color:#2c3e50; }
.card-loc { font-size: 0.8em; color: #7f8c8d; margin-bottom: 8px; }
.card-proc { color: #34495e; font-size: 0.85em; font-weight: 600; margin-bottom: 8px; }
.blocker-alert { font-size: 0.8em; font-weight: 600; color: #7f8c8d; }
.red-box { background: #d94852; color: white; padding: 4px 8px; border-radius: 4px; display: inline-block; font-size: 0.8em; }
.agent-loading { font-size: 0.85em; color: #3498db; font-family: monospace; display: flex; align-items: center; gap: 8px; margin-top: 5px; font-weight: bold;}
.spinner { width: 14px; height: 14px; border: 2px solid #3498db; border-top: 2px solid transparent; border-radius: 50%; animation: spin 1s linear infinite; }
@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
.chat-panel { background: white; border-radius: 8px; border: 1px solid #dfe6e9; display: flex; flex-direction: column; height: 100%; box-shadow: 0 4px 10px rgba(0,0,0,0.05); position: relative;}
.chat-header { padding: 12px; font-weight: bold; border-bottom: 1px solid #dfe6e9; font-size: 1em; background: #f8f9fa; border-radius: 8px 8px 0 0; display:flex; justify-content:space-between; align-items:center;}
.chat-body { flex: 1; padding: 15px; overflow-y: auto; display: flex; flex-direction: column; gap: 12px; background: #fff; }
.bubble { max-width: 85%; padding: 10px 14px; border-radius: 12px; font-size: 0.85em; line-height: 1.4; word-break: keep-all; }
.bubble-ai { background: #f1f4f8; align-self: flex-start; border-bottom-left-radius: 2px; }
.bubble-human { background: #3498db; color: white; align-self: flex-end; border-bottom-right-radius: 2px; }
.bubble-log { background: #2c3e50; color: #2ecc71; align-self: center; width: 90%; font-family: monospace; border-radius: 6px; padding: 10px; font-size: 0.8em; box-shadow: inset 0 0 5px rgba(0,0,0,0.5);}
.bubble-log strong { color: #f1c40f; display: block; margin-bottom: 5px; font-size: 1.1em;}
.hitl-gate { padding: 15px; background: #fdfdfd; border-top: 1px solid #dfe6e9; }
.action-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-bottom: 10px; }
.btn-action { padding: 8px; border: none; border-radius: 4px; font-weight: bold; cursor: pointer; font-size: 0.85em; transition: 0.2s;}
.btn-approve { background: #55af7b; color: white; }
.btn-edit { background: #f39c12; color: white; }
.btn-hold { background: #95a5a6; color: white; }
.btn-reject { background: #e74c3c; color: white; }
.btn-action:disabled { opacity: 0.5; cursor: not-allowed; }
.input-group { display: flex; gap: 8px; }
.chat-input { flex: 1; padding: 8px; border: 1px solid #dfe6e9; border-radius: 4px; outline: none; font-size: 0.85em; }
.send-btn { padding: 8px 12px; background: #34495e; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 0.85em;}
.mic-btn { padding: 8px 10px; background: #1f6fb2; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 0.85em; }
.mic-btn.recording { background: #c0392b; }
.impact-popup { position: absolute; top: 40%; left: 50%; transform: translate(-50%, -50%); background: rgba(46, 204, 113, 0.95); color: white; padding: 15px 25px; border-radius: 10px; font-weight: bold; text-align: center; box-shadow: 0 10px 25px rgba(0,0,0,0.2); z-index: 100; animation: popUpOut 3.5s forwards; font-size:1.1em;}
@keyframes popUpOut { 0% { opacity:0; transform: translate(-50%, -40%); } 15% { opacity:1; transform: translate(-50%, -50%); } 85% { opacity:1; transform: translate(-50%, -50%); } 100% { opacity:0; transform: translate(-50%, -60%); } }
.fhir-btn { font-size: 0.7em; background: #8e44ad; color: white; padding: 4px 8px; border-radius: 4px; cursor: pointer; border:none; font-weight:bold;}
.fhir-modal { position: fixed; top: 10%; left: 20%; right: 20%; bottom: 10%; background: #2c3e50; color: #ecf0f1; z-index: 999; padding: 20px; border-radius: 10px; box-shadow: 0 0 0 1000px rgba(0,0,0,0.5); overflow-y:auto; font-family: monospace;}
.fhir-modal pre { font-size: 0.85em; color: #a29bfe; white-space: pre-wrap; }
.close-fhir { float: right; background: #e74c3c; color: white; border:none; padding: 5px 10px; cursor: pointer; border-radius:4px;}
</style>
<script src="/static/vue.js"></script>
</head>
<body>
<div id="app">
<div class="header">
<h1>
Clinical Flow Coordinator OS
<div class="privacy-badge" :class="gpuLoadClass">
<span></span> {{ gpuStats.mode === 'vertex' ? 'VERTEX AI (Serverless)' : ('MEDGEMMA CLUSTER (' + gpuStats.gpu_count + ' GPUs) | UTIL: ' + gpuStats.avg_util + '%') }}
</div>
</h1>
<div>
<span style="background:#d94852; color:white; padding:5px 10px; border-radius:15px; font-size:0.8em; font-weight:bold;" v-if="urgentCount > 0">
⚠️ STAT ALERT ACTIVE
</span>
</div>
</div>
<div class="fhir-modal" v-if="showFhirModal">
<button class="close-fhir" @click="showFhirModal = false">Close</button>
<h3 style="margin-top:0; color:#2ecc71;">HL7 FHIR R4 Bundle (Generated Payload)</h3>
<p style="font-size:0.8em; color:#bdc3c7;">Interoperability Check: Dynamic AI insights mapped to standard FHIR resources.</p>
<pre>{{ fhirPayload }}</pre>
</div>
<div class="main-layout">
<div class="emr-panel">
<div class="emr-top-nav">
<span>🏥 EPIC CPOE Simulator</span>
<span>MD_KIM</span>
</div>
<div class="order-entry">
<div class="order-entry-title">Quick Order Entry</div>
<button class="emr-btn" @click="triggerEvent('p1_routine')">📝 P1 - Routine Chest CT</button>
<button class="emr-btn" @click="triggerEvent('p2_prep_blocker')">📝 P2 - APCT (Inpatient)</button>
<button class="emr-btn" @click="triggerEvent('p3_consent_allergy')">📝 P3 - Brain CT (Neuro)</button>
<button class="emr-btn emr-btn-stat" @click="triggerEvent('p4_emergent_stat')">🚨 P4 - STAT Brain CT (ED)</button>
<button class="emr-btn" @click="triggerEvent('p5_pa_blocker')">📝 P5 - Bundle CT (ID Ward)</button>
</div>
<div class="patient-chart" v-if="activePatient && activePatient.ehr_data">
<div class="ehr-status-header">▶ EHR STATUS</div>
<div class="chart-name">{{ activePatient.ehr_data.patient_id }}</div>
<div class="chart-grid">
<div class="chart-box"><div class="chart-label">Location</div><div class="chart-val">{{ activePatient.ehr_data.location }}</div></div>
<div class="chart-box"><div class="chart-label">Insurance</div><div class="chart-val">{{ activePatient.ehr_data.insurance_plan }}</div></div>
<div class="chart-box"><div class="chart-label">Vitals</div><div class="chart-val">{{ activePatient.ehr_data.vitals_summary }}</div></div>
<div class="chart-box"><div class="chart-label">Labs</div><div class="chart-val">{{ activePatient.ehr_data.labs_summary }}</div></div>
<div class="chart-box" style="grid-column: span 2;"><div class="chart-label">Allergies</div><div class="chart-val text-red">{{ activePatient.ehr_data.allergies.join(', ') }}</div></div>
</div>
<div class="order-entry-title" style="margin-top:20px;">Order Progress Timeline</div>
<div class="ehr-timeline">
<div class="tl-item" v-for="(tl, idx) in activePatient.timeline" :key="idx" :class="tl.type">
<div class="tl-time">{{ tl.time }}</div>
<div class="tl-desc">{{ tl.desc }}</div>
</div>
</div>
</div>
<div v-else style="padding: 30px; text-align: center; color: #bdc3c7; font-size: 0.9em;">
Select a patient from the queue to view EHR Chart.
</div>
</div>
<div class="queue-panel">
<div class="kpi-bar">
<div class="kpi-mini">Total: {{ patients.length }}</div>
<div class="kpi-mini" style="color:#d94852;">STAT: {{ urgentCount }}</div>
<div class="kpi-mini" style="color:#f39c12;">Blocked: {{ blockedCount }}</div>
</div>
<transition-group name="list" tag="div" style="display:flex; flex-direction:column; gap:10px;">
<div v-for="(p, index) in sortedPatients" :key="p.patient_id"
class="patient-card"
:class="{'card-active': activePatient && activePatient.patient_id === p.patient_id}"
@click="selectPatient(p)">
<div class="rank-badge" :class="{'rank-1': index === 0, 'rank-2': index === 1}">{{ index + 1 }}</div>
<div class="card-content">
<template v-if="p.processing">
<div class="card-header" style="color:#7f8c8d;">{{ p.ehr_data.patient_id }}</div>
<div class="card-proc" style="color:#bdc3c7;">{{ p.ehr_data.procedure_display }}</div>
<div class="agent-loading">
<div class="spinner"></div>
<span style="margin-left:5px;">{{ p.loading_agent }}</span>
</div>
</template>
<template v-else>
<span class="badge" :class="'badge-' + (p.intent ? p.intent.replace('_stat', '') : 'routine')">{{ p.triage_level }}</span>
<div class="card-header">{{ p.patient_id }}</div>
<div class="card-loc">📍 {{ p.location }}</div>
<div class="card-proc">{{ p.procedure }}</div>
<div v-if="p.intent === 'emergent' && !p.resolved" class="red-box">{{ p.blocker_msg }}</div>
<div v-else class="blocker-alert" :style="{color: p.is_blocked && !p.resolved ? '#d94852' : '#2ecc71'}">
{{ p.resolved ? '✔ Ready for Execution' : p.blocker_msg }}
</div>
</template>
</div>
</div>
</transition-group>
</div>
<div class="chat-panel">
<div class="chat-header">
<span>Communication & Action Panel</span>
<button class="fhir-btn" @click="generateFhirMockup" v-if="activePatient">🏥 View FHIR Payload</button>
</div>
<div v-if="impactPopup" class="impact-popup">
⏱️ Estimated Time Saved: +45 mins<br>
<span style="font-size:0.8em; color:#e0f7fa;">(Automated PA & Communication)</span>
</div>
<div class="chat-body" id="chat-body">
<div v-if="!activePatient" style="text-align:center; color:#95a5a6; margin-top:40%;">
Select a patient card to start communication and actions.
</div>
<template v-if="activePatient">
<div v-for="(msg, idx) in activePatient.chatHistory" :key="idx"
class="bubble" :class="{'bubble-ai': msg.role === 'ai', 'bubble-human': msg.role === 'human', 'bubble-log': msg.role === 'log'}">
<template v-if="msg.role === 'log'">
<strong>⚙️ {{ msg.agent_name }}</strong>
<div v-for="(val, key) in msg.decision" :key="key" style="margin-left:5px;">
<span style="color:#ecf0f1;">- {{ key }}:</span> {{ val }}
</div>
</template>
<template v-else>
<div style="white-space: pre-wrap;">{{ msg.text }}</div>
</template>
</div>
<div v-if="isTyping" class="bubble bubble-ai" style="color:#7f8c8d; font-style:italic;">
MedGemma is processing tool call...
</div>
</template>
</div>
<div class="hitl-gate">
<div style="font-size:0.8em; font-weight:bold; color:#7f8c8d; margin-bottom:8px;">HUMAN-IN-THE-LOOP (HITL)</div>
<div class="action-grid">
<button class="btn-action btn-approve" :disabled="!activePatient || activePatient.resolved || activePatient.processing" @click="hitlAction('Approve & Execute')">✅ Approve & Execute</button>
<button class="btn-action btn-edit" :disabled="!activePatient || activePatient.resolved || activePatient.processing" @click="hitlAction('Edit')">✏️ Edit</button>
<button class="btn-action btn-hold" :disabled="!activePatient || activePatient.resolved || activePatient.processing" @click="hitlAction('Hold')">⏸️ Hold</button>
<button class="btn-action btn-reject" :disabled="!activePatient || activePatient.resolved || activePatient.processing" @click="hitlAction('Reject')">❌ Reject</button>
</div>
<div class="input-group">
<input type="text" v-model="userInput" class="chat-input" placeholder="LLM tool call (e.g., Draft a PA clinical justification)" @keyup.enter="sendMessage" :disabled="!activePatient || isTyping || activePatient.processing">
<button class="mic-btn" :class="{recording: isRecording}" @click="toggleRecording" :disabled="!activePatient || isTyping || activePatient.processing">
{{ isRecording ? '⏹ Stop' : '🎤 MedASR' }}
</button>
<button class="send-btn" @click="sendMessage" :disabled="!activePatient || isTyping || activePatient.processing">Send</button>
</div>
</div>
</div>
</div>
</div>
<script>
if (typeof Vue === 'undefined') throw new Error("Vue is not loaded");
const { createApp } = Vue;
function getTimeStr() { return new Date().toLocaleTimeString('en-US', {hour12:false, hour:'2-digit', minute:'2-digit', second:'2-digit'}); }
const PATIENT_DATA = {
"p1_routine": { "patient_id": "P1 - Lee, S. (52/M)", "procedure_display": "Chest CT (No Contrast)", "location": "Pulmo Ward Room 777", "insurance_plan": "Private", "vitals_summary": "Stable, BP 128/74, HR 72", "labs_summary": "Cr 0.92 (Normal)", "allergies": ["None"] },
"p2_prep_blocker": { "patient_id": "P2 - Park, J. (61/F)", "procedure_display": "APCT w/ Contrast (13:00)", "location": "GI Ward Room 802", "insurance_plan": "Private", "vitals_summary": "Abdominal pain, HR 94, Temp 37.2", "labs_summary": "Cr 1.08 (Outdated >30 days)", "allergies": ["Penicillin"] },
"p3_consent_allergy": { "patient_id": "P3 - Kim, D. (78/M)", "procedure_display": "Brain CT w/ Contrast (15:10)", "location": "Neuro Ward Room 605", "insurance_plan": "Private", "vitals_summary": "Confused, BP 142/86, HR 88", "labs_summary": "Cr 1.02", "allergies": ["Contrast Allergy (Mild rash)"] },
"p4_emergent_stat": { "patient_id": "P4 - Choi, M. (67/F)", "procedure_display": "STAT Brain CT (Contrast)", "location": "ED Resus-2", "insurance_plan": "ED (Unknown)", "vitals_summary": "Acute mental change, HR 112, BP 160/95", "labs_summary": "Cr 1.14", "allergies": ["Unknown"] },
"p5_pa_blocker": { "patient_id": "P5 - Han, K. (45/M)", "procedure_display": "Fever Focus: Chest+APCT", "location": "ID Ward Room 1007", "insurance_plan": "HMO", "vitals_summary": "Persistent fever 39.1, HR 105", "labs_summary": "CRP 18.2, WBC 14K", "allergies": ["None"] }
};
createApp({
data() {
return {
patients: [], activePatient: null, userInput: '', isTyping: false, showFhirModal: false, fhirPayload: "", impactPopup: false,
gpuStats: { gpu_count: 0, avg_util: 0, mode: "vertex" }, // live GPU telemetry state
isRecording: false,
mediaRecorder: null,
audioChunks: []
}
},
computed: {
sortedPatients() { return [...this.patients].sort((a, b) => b.priority_score - a.priority_score); },
urgentCount() { return this.patients.filter(p => !p.processing && p.intent === 'emergent').length; },
blockedCount() { return this.patients.filter(p => !p.processing && p.is_blocked && !p.resolved).length; },
// Dynamic color based on GPU load (>=60% red, >=30% orange)
gpuLoadClass() {
if (this.gpuStats.avg_util >= 60) return 'high-load';
if (this.gpuStats.avg_util >= 30) return 'mid-load';
return '';
}
},
mounted() {
// Poll backend GPU usage every 2 seconds after mount
this.pollGpuStats();
setInterval(this.pollGpuStats, 2000);
},
methods: {
getReadHeaders() {
const token = window.localStorage.getItem('readToken') || '';
return token ? { 'X-Read-Token': token } : {};
},
getWriteHeaders() {
const token = window.localStorage.getItem('writeToken') || '';
return token ? { 'X-Write-Token': token } : {};
},
async pollGpuStats() {
try {
const res = await fetch('/api/system/gpu');
this.gpuStats = await res.json();
} catch(e) {
console.log("GPU telemetry polling error");
}
},
async generateFhirMockup() {
if(!this.activePatient) return;
try {
const res = await fetch('/api/fhir/draft', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...this.getReadHeaders() },
body: JSON.stringify({ patient_id: this.activePatient.patient_id })
});
if (!res.ok) throw new Error(await res.text());
const data = await res.json();
this.fhirPayload = JSON.stringify(data.bundle, null, 2);
this.showFhirModal = true;
} catch (e) {
this.activePatient.chatHistory.push({ role: 'ai', text: "Failed to generate FHIR draft: check read access or patient context." });
this.scrollToBottom();
}
},
async triggerEvent(scenario) {
if(this.patients.find(p => p.scenario === scenario)) return;
const tempId = "Loading_" + Date.now();
const ehr = PATIENT_DATA[scenario];
const newPatient = {
patient_id: tempId, scenario: scenario, priority_score: -1, processing: true,
chatHistory: [{ role: 'ai', text: "Starting multi-agent workflow..." }],
intent: 'routine', triage_level: '', procedure: '', location: '', blocker_msg: '', is_blocked: false, resolved: false,
loading_agent: "🚀 5 Agents Parallel Initializing...",
completed_agents: [],
ehr_data: ehr,
timeline: [{ time: getTimeStr(), desc: `[Order Placed] ${ehr.procedure_display}`, type: "order" }]
};
this.patients.push(newPatient);
this.selectPatient(newPatient);
try {
const res = await fetch('/api/flow/run_patient_stream?scenario=' + scenario, {
method: 'POST',
headers: this.getReadHeaders()
});
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while(true) {
const { done, value } = await reader.read();
if(done) break;
buffer += decoder.decode(value, {stream: true});
let parts = buffer.split('\\n\\n');
buffer = parts.pop();
for(let part of parts) {
if(part.startsWith('data: ')) {
const data = JSON.parse(part.substring(6));
const pToUpdate = this.patients.find(p => p.patient_id === tempId);
if(!pToUpdate) continue;
if(data.event === 'running') {
if (data.agent_name.includes("Concurrent")) {
pToUpdate.loading_agent = "Running parallel agents...";
}
} else if(data.event === 'agent_log') {
if (!pToUpdate.completed_agents) pToUpdate.completed_agents = [];
let shortName = data.agent_name.replace(' Agent', '');