forked from OHDSI/StudyAgent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdodo.py
More file actions
657 lines (596 loc) · 26 KB
/
dodo.py
File metadata and controls
657 lines (596 loc) · 26 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
from __future__ import annotations
import json
import os
import socket
import subprocess
import time
import urllib.request
from urllib.parse import urlparse
## NOTE: you also need LLM_API_KEY
DEFAULT_ENV = {
"PHENOTYPE_INDEX_DIR": os.getenv("PHENOTYPE_INDEX_DIR", "data/phenotype_index"),
"PHENOTYPE_DENSE_WEIGHT": os.getenv("PHENOTYPE_DENSE_WEIGHT", "0.9"),
"PHENOTYPE_SPARSE_WEIGHT": os.getenv("PHENOTYPE_SPARSE_WEIGHT", "0.1"),
"EMBED_URL": os.getenv("EMBED_URL", "http://localhost:3000/ollama/api/embed"),
"EMBED_MODEL": os.getenv("EMBED_MODEL", "qwen3-embedding:4b"),
"LLM_API_URL": os.getenv("LLM_API_URL", "http://localhost:3000/api/chat/completions"),
"LLM_MODEL": os.getenv("LLM_MODEL", "gemma3:4b"),
"LLM_TIMEOUT": os.getenv("LLM_TIMEOUT", "240"),
"LLM_LOG": os.getenv("LLM_LOG", "1"),
"LLM_LOG_PROMPT": os.getenv("LLM_LOG_PROMPT", "0"),
"LLM_LOG_RESPONSE": os.getenv("LLM_LOG_RESPONSE", "0"),
"LLM_LOG_JSON": os.getenv("LLM_LOG_JSON", "0"),
"LLM_DRY_RUN": os.getenv("LLM_DRY_RUN", "0"),
"LLM_USE_RESPONSES": os.getenv("LLM_USE_RESPONSES", "0"),
"LLM_CANDIDATE_LIMIT": os.getenv("LLM_CANDIDATE_LIMIT", "10"),
"ACP_TIMEOUT": os.getenv("ACP_TIMEOUT", "180"),
"STUDY_AGENT_HOST": os.getenv("STUDY_AGENT_HOST", "127.0.0.1"),
"STUDY_AGENT_PORT": os.getenv("STUDY_AGENT_PORT", "8765"),
}
def _pytest_cmd(marker: str | None = None) -> str:
opts = os.getenv("PYTEST_OPTS", "")
base = "pytest"
if marker:
base = f"{base} -m {marker}"
if opts:
return f"{base} {opts}"
return base
def _start_mcp_http_if_needed(env: dict) -> subprocess.Popen | None:
url = env.get("STUDY_AGENT_MCP_URL")
if not url:
return None
if env.get("STUDY_AGENT_MCP_MANAGED", "1") != "1":
return None
parsed = urlparse(url)
host = parsed.hostname or "127.0.0.1"
port = parsed.port or 8790
path = parsed.path or "/mcp"
env.setdefault("MCP_TRANSPORT", "http")
env.setdefault("MCP_HOST", host)
env.setdefault("MCP_PORT", str(port))
env.setdefault("MCP_PATH", path)
mcp_stdout = env.get("MCP_STDOUT", "/tmp/study_agent_mcp_stdout.log")
mcp_stderr = env.get("MCP_STDERR", "/tmp/study_agent_mcp_stderr.log")
print(f"Starting MCP over HTTP at {host}:{port}{path}...")
with open(mcp_stdout, "w", encoding="utf-8") as out, open(mcp_stderr, "w", encoding="utf-8") as err:
proc = subprocess.Popen(["study-agent-mcp"], env=env, stdout=out, stderr=err)
timeout_s = int(env.get("MCP_START_TIMEOUT", "10"))
deadline = time.time() + timeout_s
while time.time() < deadline:
try:
with socket.create_connection((host, port), timeout=1):
return proc
except OSError:
time.sleep(0.5)
print(f"Warning: MCP did not open {host}:{port} within {timeout_s}s")
return proc
def _wait_for_acp(url: str, timeout_s: int = 30, require_mcp: bool = False) -> None:
deadline = time.time() + timeout_s
while time.time() < deadline:
try:
with urllib.request.urlopen(url, timeout=2) as response:
if response.status == 200:
if not require_mcp:
return
body = json.loads(response.read().decode("utf-8"))
mcp_ok = isinstance(body.get("mcp"), dict) and body.get("mcp", {}).get("ok") is True
if mcp_ok:
return
except Exception:
time.sleep(0.5)
raise RuntimeError(f"ACP did not become ready at {url}")
def task_install():
return {
"actions": ["pip install -e ."],
"verbosity": 2,
}
def task_test_core():
return {
"actions": [_pytest_cmd("core")],
"verbosity": 2,
}
def task_test_acp():
return {
"actions": [_pytest_cmd("acp")],
"verbosity": 2,
}
def task_test_mcp():
return {
"actions": [_pytest_cmd("mcp")],
"verbosity": 2,
}
def task_test_unit():
return {
"actions": None,
"task_dep": ["test_core", "test_acp", "test_mcp"],
}
def task_test_all():
return {
"actions": [_pytest_cmd()],
"verbosity": 2,
}
def task_run_all():
return {
"actions": None,
"task_dep": ["test_all","smoke_phenotype_recommend_flow", "smoke_phenotype_intent_split_flow", "smoke_phenotype_recommendation_advice_flow", "smoke_phenotype_improvements_flow", "smoke_concept_sets_review_flow", "smoke_cohort_critique_flow"],
}
def task_check_llm_connectivity():
def _run_check() -> None:
env = os.environ.copy()
if not env.get("LLM_API_KEY"):
print("Missing LLM_API_KEY in environment. Set it before running this task.")
return
for key, value in DEFAULT_ENV.items():
env.setdefault(key, value)
url = env["LLM_API_URL"]
model = env["LLM_MODEL"]
use_responses = env.get("LLM_USE_RESPONSES", "0") == "1"
if use_responses:
payload = json.dumps(
{
"model": model,
"input": "What we have here is a failure to communicate!.",
"temperature": 0,
}
)
else:
payload = json.dumps(
{
"model": model,
"messages": [{"role": "user", "content": "Tau Ceti here we ."}],
"temperature": 0,
}
)
cmd = [
"curl",
"-sS",
"-X",
"POST",
url,
"-H",
"Content-Type: application/json",
"-H",
f"Authorization: Bearer {env['LLM_API_KEY']}",
"-d",
payload,
]
print("Running LLM connectivity check...")
subprocess.run(cmd, check=True)
return {
"actions": [_run_check],
"verbosity": 2,
}
def task_list_services():
def _run_list() -> None:
env = os.environ.copy()
host = env.get("STUDY_AGENT_HOST", DEFAULT_ENV["STUDY_AGENT_HOST"])
port = env.get("STUDY_AGENT_PORT", DEFAULT_ENV["STUDY_AGENT_PORT"])
url = env.get("ACP_BASE_URL", f"http://{host}:{port}")
if url.endswith("/"):
url = url[:-1]
acp_proc = None
mcp_proc = None
try:
try:
_wait_for_acp(f"{url}/health", timeout_s=3)
except Exception:
if not env.get("STUDY_AGENT_MCP_URL"):
env.setdefault("STUDY_AGENT_MCP_COMMAND", "study-agent-mcp")
env.setdefault("STUDY_AGENT_MCP_ARGS", "")
mcp_proc = _start_mcp_http_if_needed(env)
acp_stdout = env.get("ACP_STDOUT", "/tmp/study_agent_acp_stdout.log")
acp_stderr = env.get("ACP_STDERR", "/tmp/study_agent_acp_stderr.log")
print("Starting ACP to list services...")
with open(acp_stdout, "w", encoding="utf-8") as out, open(acp_stderr, "w", encoding="utf-8") as err:
acp_proc = subprocess.Popen(["study-agent-acp"], env=env, stdout=out, stderr=err)
require_mcp = bool(env.get("STUDY_AGENT_MCP_URL") or env.get("STUDY_AGENT_MCP_COMMAND"))
_wait_for_acp(f"{url}/health", timeout_s=15, require_mcp=require_mcp)
req = urllib.request.Request(f"{url}/services")
with urllib.request.urlopen(req, timeout=10) as response:
body = response.read().decode("utf-8")
print(body)
finally:
if acp_proc is not None:
print("Stopping ACP...")
acp_proc.terminate()
try:
acp_proc.wait(timeout=10)
except subprocess.TimeoutExpired:
acp_proc.kill()
if mcp_proc is not None:
print("Stopping MCP...")
mcp_proc.terminate()
try:
mcp_proc.wait(timeout=10)
except subprocess.TimeoutExpired:
mcp_proc.kill()
return {
"actions": [_run_list],
"verbosity": 2,
}
def task_smoke_phenotype_recommend_flow():
def _run_smoke() -> None:
env = os.environ.copy()
if not env.get("LLM_API_KEY"):
print("Missing LLM_API_KEY in environment. Set it before running this task.")
return
for key, value in DEFAULT_ENV.items():
env.setdefault(key, value)
if not env.get("STUDY_AGENT_MCP_URL"):
env.setdefault("STUDY_AGENT_MCP_COMMAND", "study-agent-mcp")
env.setdefault("STUDY_AGENT_MCP_ARGS", "")
env.setdefault("LLM_LOG", "1")
env.setdefault("LLM_LOG_PROMPT", "1")
env.setdefault("LLM_LOG_RESPONSE", "1")
env["ACP_URL"] = "http://127.0.0.1:8765/flows/phenotype_recommendation"
acp_stdout = env.get("ACP_STDOUT", "/tmp/study_agent_acp_stdout.log")
acp_stderr = env.get("ACP_STDERR", "/tmp/study_agent_acp_stderr.log")
mcp_proc = _start_mcp_http_if_needed(env)
print("Starting ACP...")
with open(acp_stdout, "w", encoding="utf-8") as out, open(acp_stderr, "w", encoding="utf-8") as err:
acp_proc = subprocess.Popen(["study-agent-acp"], env=env, stdout=out, stderr=err)
try:
print("Waiting for ACP health endpoint...")
require_mcp = bool(env.get("STUDY_AGENT_MCP_URL") or env.get("STUDY_AGENT_MCP_COMMAND"))
_wait_for_acp("http://127.0.0.1:8765/health", timeout_s=30, require_mcp=require_mcp)
print("Running phenotype flow smoke test...")
subprocess.run(["python", "tests/phenotype_flow_smoke_test.py"], check=True, env=env)
print(f"ACP logs: {acp_stdout} {acp_stderr}")
finally:
print("Stopping ACP...")
acp_proc.terminate()
try:
acp_proc.wait(timeout=10)
except subprocess.TimeoutExpired:
acp_proc.kill()
if mcp_proc is not None:
print("Stopping MCP...")
mcp_proc.terminate()
try:
mcp_proc.wait(timeout=10)
except subprocess.TimeoutExpired:
mcp_proc.kill()
return {
"actions": [_run_smoke],
"verbosity": 2,
}
def task_smoke_phenotype_intent_split_flow():
def _run_smoke() -> None:
env = os.environ.copy()
if not env.get("LLM_API_KEY"):
print("Missing LLM_API_KEY in environment. Set it before running this task.")
return
for key, value in DEFAULT_ENV.items():
env.setdefault(key, value)
if not env.get("STUDY_AGENT_MCP_URL"):
env.setdefault("STUDY_AGENT_MCP_COMMAND", "study-agent-mcp")
env.setdefault("STUDY_AGENT_MCP_ARGS", "")
env.setdefault("LLM_LOG", "1")
env.setdefault("LLM_LOG_PROMPT", "1")
env.setdefault("LLM_LOG_RESPONSE", "1")
env["ACP_URL"] = "http://127.0.0.1:8765/flows/phenotype_intent_split"
acp_stdout = env.get("ACP_STDOUT", "/tmp/study_agent_acp_stdout.log")
acp_stderr = env.get("ACP_STDERR", "/tmp/study_agent_acp_stderr.log")
mcp_proc = _start_mcp_http_if_needed(env)
print("Starting ACP...")
with open(acp_stdout, "w", encoding="utf-8") as out, open(acp_stderr, "w", encoding="utf-8") as err:
acp_proc = subprocess.Popen(["study-agent-acp"], env=env, stdout=out, stderr=err)
try:
print("Waiting for ACP health endpoint...")
require_mcp = bool(env.get("STUDY_AGENT_MCP_URL") or env.get("STUDY_AGENT_MCP_COMMAND"))
_wait_for_acp("http://127.0.0.1:8765/health", timeout_s=30, require_mcp=require_mcp)
print("Running phenotype intent split flow smoke test...")
subprocess.run(["python", "tests/phenotype_intent_split_smoke_test.py"], check=True, env=env)
print(f"ACP logs: {acp_stdout} {acp_stderr}")
finally:
print("Stopping ACP...")
acp_proc.terminate()
try:
acp_proc.wait(timeout=10)
except subprocess.TimeoutExpired:
acp_proc.kill()
if mcp_proc is not None:
print("Stopping MCP...")
mcp_proc.terminate()
try:
mcp_proc.wait(timeout=10)
except subprocess.TimeoutExpired:
mcp_proc.kill()
return {
"actions": [_run_smoke],
"verbosity": 2,
}
def task_smoke_phenotype_improvements_flow():
def _run_smoke() -> None:
env = os.environ.copy()
if not env.get("LLM_API_KEY"):
print("Missing LLM_API_KEY in environment. Set it before running this task.")
return
for key, value in DEFAULT_ENV.items():
env.setdefault(key, value)
if not env.get("STUDY_AGENT_MCP_URL"):
env.setdefault("STUDY_AGENT_MCP_COMMAND", "study-agent-mcp")
env.setdefault("STUDY_AGENT_MCP_ARGS", "")
acp_stdout = env.get("ACP_STDOUT", "/tmp/study_agent_acp_stdout.log")
acp_stderr = env.get("ACP_STDERR", "/tmp/study_agent_acp_stderr.log")
mcp_proc = _start_mcp_http_if_needed(env)
print("Starting ACP...")
with open(acp_stdout, "w", encoding="utf-8") as out, open(acp_stderr, "w", encoding="utf-8") as err:
acp_proc = subprocess.Popen(["study-agent-acp"], env=env, stdout=out, stderr=err)
try:
print("Waiting for ACP health endpoint...")
require_mcp = bool(env.get("STUDY_AGENT_MCP_URL") or env.get("STUDY_AGENT_MCP_COMMAND"))
_wait_for_acp("http://127.0.0.1:8765/health", timeout_s=30, require_mcp=require_mcp)
print("Running phenotype improvements flow smoke test...")
payload = json.dumps(
{
"protocol_path": "demo/protocol.md",
"cohort_paths": [
"demo/test_git_event_cohort.json"
],
}
).encode("utf-8")
req = urllib.request.Request(
"http://127.0.0.1:8765/flows/phenotype_improvements",
data=payload,
method="POST",
)
req.add_header("Content-Type", "application/json")
try:
with urllib.request.urlopen(req, timeout=int(env.get("ACP_TIMEOUT", "180"))) as response:
body = response.read().decode("utf-8")
print(body)
except urllib.error.HTTPError as exc:
body = exc.read().decode("utf-8")
print(body)
print(f"ACP logs: {acp_stdout} {acp_stderr}")
finally:
print("Stopping ACP...")
acp_proc.terminate()
try:
acp_proc.wait(timeout=10)
except subprocess.TimeoutExpired:
acp_proc.kill()
if mcp_proc is not None:
print("Stopping MCP...")
mcp_proc.terminate()
try:
mcp_proc.wait(timeout=10)
except subprocess.TimeoutExpired:
mcp_proc.kill()
return {
"actions": [_run_smoke],
"verbosity": 2,
}
def task_smoke_phenotype_recommendation_advice_flow():
def _run_smoke() -> None:
env = os.environ.copy()
if not env.get("LLM_API_KEY"):
print("Missing LLM_API_KEY in environment. Set it before running this task.")
return
for key, value in DEFAULT_ENV.items():
env.setdefault(key, value)
if not env.get("STUDY_AGENT_MCP_URL"):
env.setdefault("STUDY_AGENT_MCP_COMMAND", "study-agent-mcp")
env.setdefault("STUDY_AGENT_MCP_ARGS", "")
env.setdefault("LLM_LOG", "1")
acp_stdout = env.get("ACP_STDOUT", "/tmp/study_agent_acp_stdout.log")
acp_stderr = env.get("ACP_STDERR", "/tmp/study_agent_acp_stderr.log")
mcp_proc = _start_mcp_http_if_needed(env)
print("Starting ACP...")
with open(acp_stdout, "w", encoding="utf-8") as out, open(acp_stderr, "w", encoding="utf-8") as err:
acp_proc = subprocess.Popen(["study-agent-acp"], env=env, stdout=out, stderr=err)
try:
print("Waiting for ACP health endpoint...")
require_mcp = bool(env.get("STUDY_AGENT_MCP_URL") or env.get("STUDY_AGENT_MCP_COMMAND"))
_wait_for_acp("http://127.0.0.1:8765/health", timeout_s=30, require_mcp=require_mcp)
print("Running phenotype recommendation advice flow smoke test...")
subprocess.run(["python", "tests/phenotype_recommendation_advice_smoke_test.py"], check=True, env=env)
finally:
print("Stopping ACP...")
acp_proc.terminate()
try:
acp_proc.wait(timeout=10)
except subprocess.TimeoutExpired:
acp_proc.kill()
if mcp_proc is not None:
print("Stopping MCP...")
mcp_proc.terminate()
try:
mcp_proc.wait(timeout=10)
except subprocess.TimeoutExpired:
mcp_proc.kill()
return {
"actions": [_run_smoke],
"verbosity": 2,
}
def task_smoke_concept_sets_review_flow():
def _run_smoke() -> None:
env = os.environ.copy()
if not env.get("LLM_API_KEY"):
print("Missing LLM_API_KEY in environment. Set it before running this task.")
return
for key, value in DEFAULT_ENV.items():
env.setdefault(key, value)
if not env.get("STUDY_AGENT_MCP_URL"):
env.setdefault("STUDY_AGENT_MCP_COMMAND", "study-agent-mcp")
env.setdefault("STUDY_AGENT_MCP_ARGS", "")
env.setdefault("LLM_LOG", "1")
acp_stdout = env.get("ACP_STDOUT", "/tmp/study_agent_acp_stdout.log")
acp_stderr = env.get("ACP_STDERR", "/tmp/study_agent_acp_stderr.log")
mcp_proc = _start_mcp_http_if_needed(env)
print("Starting ACP...")
with open(acp_stdout, "w", encoding="utf-8") as out, open(acp_stderr, "w", encoding="utf-8") as err:
acp_proc = subprocess.Popen(["study-agent-acp"], env=env, stdout=out, stderr=err)
try:
print("Waiting for ACP health endpoint...")
require_mcp = bool(env.get("STUDY_AGENT_MCP_URL") or env.get("STUDY_AGENT_MCP_COMMAND"))
_wait_for_acp("http://127.0.0.1:8765/health", timeout_s=30, require_mcp=require_mcp)
print("Running concept sets review flow smoke test...")
payload = json.dumps(
{
"concept_set_path": "demo/concept_set.json",
"study_intent": "Identify clinical risk factors for older adult patients who experience an adverse event of acute gastro-intenstinal (GI) bleeding. The GI bleed has to be detected in the hospital setting. Risk factors can include concomitant medications or chronic and acute conditions.",
}
).encode("utf-8")
req = urllib.request.Request(
"http://127.0.0.1:8765/flows/concept_sets_review",
data=payload,
method="POST",
)
req.add_header("Content-Type", "application/json")
try:
with urllib.request.urlopen(req, timeout=int(env.get("ACP_TIMEOUT", "180"))) as response:
body = response.read().decode("utf-8")
print(body)
except urllib.error.HTTPError as exc:
body = exc.read().decode("utf-8")
print(body)
print(f"ACP logs: {acp_stdout} {acp_stderr}")
finally:
print("Stopping ACP...")
acp_proc.terminate()
try:
acp_proc.wait(timeout=10)
except subprocess.TimeoutExpired:
acp_proc.kill()
if mcp_proc is not None:
print("Stopping MCP...")
mcp_proc.terminate()
try:
mcp_proc.wait(timeout=10)
except subprocess.TimeoutExpired:
mcp_proc.kill()
return {
"actions": [_run_smoke],
"verbosity": 2,
}
def task_smoke_cohort_critique_flow():
def _run_smoke() -> None:
env = os.environ.copy()
if not env.get("LLM_API_KEY"):
print("Missing LLM_API_KEY in environment. Set it before running this task.")
return
for key, value in DEFAULT_ENV.items():
env.setdefault(key, value)
if not env.get("STUDY_AGENT_MCP_URL"):
env.setdefault("STUDY_AGENT_MCP_COMMAND", "study-agent-mcp")
env.setdefault("STUDY_AGENT_MCP_ARGS", "")
env.setdefault("LLM_LOG", "1")
acp_stdout = env.get("ACP_STDOUT", "/tmp/study_agent_acp_stdout.log")
acp_stderr = env.get("ACP_STDERR", "/tmp/study_agent_acp_stderr.log")
mcp_proc = _start_mcp_http_if_needed(env)
print("Starting ACP...")
with open(acp_stdout, "w", encoding="utf-8") as out, open(acp_stderr, "w", encoding="utf-8") as err:
acp_proc = subprocess.Popen(["study-agent-acp"], env=env, stdout=out, stderr=err)
try:
print("Waiting for ACP health endpoint...")
require_mcp = bool(env.get("STUDY_AGENT_MCP_URL") or env.get("STUDY_AGENT_MCP_COMMAND"))
_wait_for_acp("http://127.0.0.1:8765/health", timeout_s=30, require_mcp=require_mcp)
print("Running cohort critique flow smoke test...")
payload = json.dumps(
{
"cohort_path": "demo/cohort_definition.json",
}
).encode("utf-8")
req = urllib.request.Request(
"http://127.0.0.1:8765/flows/cohort_critique_general_design",
data=payload,
method="POST",
)
req.add_header("Content-Type", "application/json")
with urllib.request.urlopen(req, timeout=int(env.get("ACP_TIMEOUT", "180"))) as response:
body = response.read().decode("utf-8")
print(body)
print(f"ACP logs: {acp_stdout} {acp_stderr}")
finally:
print("Stopping ACP...")
acp_proc.terminate()
try:
acp_proc.wait(timeout=10)
except subprocess.TimeoutExpired:
acp_proc.kill()
if mcp_proc is not None:
print("Stopping MCP...")
mcp_proc.terminate()
try:
mcp_proc.wait(timeout=10)
except subprocess.TimeoutExpired:
mcp_proc.kill()
return {
"actions": [_run_smoke],
"verbosity": 2,
}
def task_smoke_phenotype_validation_review_flow():
def _run_smoke() -> None:
env = os.environ.copy()
if not env.get("LLM_API_KEY"):
print("Missing LLM_API_KEY in environment. Set it before running this task.")
return
for key, value in DEFAULT_ENV.items():
env.setdefault(key, value)
if not env.get("STUDY_AGENT_MCP_URL"):
env.setdefault("STUDY_AGENT_MCP_COMMAND", "study-agent-mcp")
env.setdefault("STUDY_AGENT_MCP_ARGS", "")
env.setdefault("LLM_LOG", "1")
acp_stdout = env.get("ACP_STDOUT", "/tmp/study_agent_acp_stdout.log")
acp_stderr = env.get("ACP_STDERR", "/tmp/study_agent_acp_stderr.log")
mcp_proc = _start_mcp_http_if_needed(env)
print("Starting ACP...")
with open(acp_stdout, "w", encoding="utf-8") as out, open(acp_stderr, "w", encoding="utf-8") as err:
acp_proc = subprocess.Popen(["study-agent-acp"], env=env, stdout=out, stderr=err)
try:
print("Waiting for ACP health endpoint...")
require_mcp = bool(env.get("STUDY_AGENT_MCP_URL") or env.get("STUDY_AGENT_MCP_COMMAND"))
_wait_for_acp("http://127.0.0.1:8765/health", timeout_s=30, require_mcp=require_mcp)
print("Running phenotype validation review flow smoke test...")
payload = json.dumps(
{
"disease_name": "Gastrointestinal bleeding",
"keeper_row": {
"age": 44,
"gender": "Male",
"visitContext": "Inpatient Visit",
"presentation": "Gastrointestinal hemorrhage",
"priorDisease": "Peptic ulcer",
"symptoms": "",
"comorbidities": "",
"priorDrugs": "celecoxib",
"priorTreatmentProcedures": "",
"diagnosticProcedures": "",
"measurements": "",
"alternativeDiagnosis": "",
"afterDisease": "",
"afterDrugs": "Naproxen",
"afterTreatmentProcedures": "",
},
}
).encode("utf-8")
req = urllib.request.Request(
"http://127.0.0.1:8765/flows/phenotype_validation_review",
data=payload,
method="POST",
)
req.add_header("Content-Type", "application/json")
with urllib.request.urlopen(req, timeout=int(env.get("ACP_TIMEOUT", "180"))) as response:
body = response.read().decode("utf-8")
print(body)
print(f"ACP logs: {acp_stdout} {acp_stderr}")
finally:
print("Stopping ACP...")
acp_proc.terminate()
try:
acp_proc.wait(timeout=10)
except subprocess.TimeoutExpired:
acp_proc.kill()
if mcp_proc is not None:
print("Stopping MCP...")
mcp_proc.terminate()
try:
mcp_proc.wait(timeout=10)
except subprocess.TimeoutExpired:
mcp_proc.kill()
return {
"actions": [_run_smoke],
"verbosity": 2,
}