Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
2708 lines (2470 loc) · 112 KB
/
Copy pathmain.py
File metadata and controls
2708 lines (2470 loc) · 112 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
#!/usr/bin/env python3
"""
COMPASS Multi-Agent System
Clinical Ontology-driven Multi-modal Predictive Agentic Support System
Main entry point for running the COMPASS pipeline on participant data.
"""
import argparse
import json
import sys
import threading
import time
from pathlib import Path
from datetime import datetime
from typing import Optional, Dict, Any, List, Tuple
import logging
logger = logging.getLogger(__name__)
# Default control condition (non-target comparator)
DEFAULT_CONTROL_CONDITION = "non-target comparator phenotype profile"
AGENT_INSTRUCTION_KEYS = (
"global",
"orchestrator",
"executor",
"tools",
"integrator",
"predictor",
"critic",
"communicator",
)
# Add parent to path for imports
sys.path.insert(0, str(Path(__file__).parent.parent))
from multi_agent_system.config.settings import get_settings, LLMBackend
from multi_agent_system.utils.core.data_loader import DataLoader
from multi_agent_system.utils.core.token_manager import TokenManager
from multi_agent_system.utils.llm_client import get_llm_client, reset_llm_client
from multi_agent_system.utils.core.fusion_layer import FusionLayer, FusionResult
from multi_agent_system.utils.core.predictor_input_assembler import PredictorInputAssembler
from multi_agent_system.utils.core.explainability_feature_space import build_feature_space
from multi_agent_system.utils.core.explainability_runner import run_explainability_methods
from multi_agent_system.utils.token_packer import count_tokens
from multi_agent_system.agents.orchestrator import Orchestrator
from multi_agent_system.agents.executor import Executor
from multi_agent_system.agents.predictor import Predictor
from multi_agent_system.agents.critic import Critic
from multi_agent_system.agents.communicator import Communicator
from multi_agent_system.utils.compass_logging.execution_logger import ExecutionLogger
from multi_agent_system.utils.compass_logging.decision_trace import DecisionTrace
from multi_agent_system.utils.compass_logging.patient_report import PatientReportGenerator
from multi_agent_system.data.models.prediction_result import Verdict
from multi_agent_system.data.models.prediction_task import (
PredictionTaskSpec,
PredictionMode,
build_binary_task_spec,
build_task_spec_from_flat_args,
parse_csv_list,
)
from multi_agent_system.frontend.compass_ui import get_ui, reset_ui, start_ui_loop
from multi_agent_system.utils.participant_resolver import resolve_participant_dir
def _resolve_output_dir(participant_dir: Path, participant_id: str, settings) -> Path:
pseudo_inputs = settings.paths.base_dir / "data" / "pseudo_data" / "inputs"
pseudo_outputs = settings.paths.base_dir / "data" / "pseudo_data" / "outputs"
try:
if pseudo_inputs in participant_dir.resolve().parents:
return pseudo_outputs / f"participant_{participant_id}"
except Exception:
pass
return settings.paths.output_dir / f"participant_{participant_id}"
def _build_report_context_note(final_evaluation, selected_iteration: int, selection_reason: str) -> str:
if not final_evaluation or final_evaluation.verdict == Verdict.SATISFACTORY:
return ""
return (
"WARNING: Selected final verdict remains UNSATISFACTORY. "
f"Selected iteration: {selected_iteration}. "
f"Selection basis: {selection_reason}. "
"Interpret deep phenotype content as exploratory and not production-final."
)
def _append_execution_log_entry(output_dir: Path, participant_id: str, entry: Dict[str, Any]) -> None:
log_path = output_dir / f"execution_log_{participant_id}.json"
payload = []
if log_path.exists():
try:
with open(log_path, "r") as f:
loaded = json.load(f)
if isinstance(loaded, list):
payload = loaded
except Exception:
payload = []
payload.append(entry)
with open(log_path, "w") as f:
json.dump(payload, f, indent=2)
def _clamp_role_token_limits(settings) -> None:
role_names = ("orchestrator", "critic", "integrator", "predictor", "communicator", "tool")
for role in role_names:
model_attr = f"{role}_model"
max_attr = f"{role}_max_tokens"
model_name = getattr(settings.models, model_attr, "")
configured = int(getattr(settings.models, max_attr, 0) or 0)
safe_cap = int(settings.auto_output_token_limit(model_name=model_name))
if configured <= 0:
setattr(settings.models, max_attr, safe_cap)
else:
setattr(settings.models, max_attr, min(configured, safe_cap))
def _is_openai_model_name(model_name: str) -> bool:
value = str(model_name or "").strip().lower()
if not value:
return False
return value.startswith(("gpt-", "o1", "o3", "o4", "text-embedding-"))
def _to_openai_model_name(model_name: str) -> str:
value = str(model_name or "").strip()
if not value:
return ""
if "/" in value:
provider, name = value.split("/", 1)
if provider.strip().lower() != "openai":
return ""
candidate = name.strip()
return candidate if _is_openai_model_name(candidate) else ""
return value if _is_openai_model_name(value) else ""
def _activate_openai_fallback(settings, reason: str, ui=None) -> None:
settings.models.backend = LLMBackend.OPENAI
role_names = ("orchestrator", "critic", "integrator", "predictor", "communicator", "tool")
public_default = _to_openai_model_name(settings.models.public_model_name) or "gpt-5-nano"
settings.models.public_model_name = public_default
for role in role_names:
role_attr = f"{role}_model"
current = getattr(settings.models, role_attr, "")
setattr(settings.models, role_attr, _to_openai_model_name(current) or public_default)
reset_llm_client()
msg = f"OpenRouter unavailable. Falling back to OpenAI backend ({reason})."
logger.warning(msg)
print(f"[Init] {msg}")
if ui is not None:
try:
ui.set_status("OpenRouter unavailable. Fallback to OpenAI backend.", stage=0)
except Exception:
pass
def _apply_role_model_overrides(settings, role_models: Dict[str, Any]) -> None:
if not isinstance(role_models, dict):
return
role_names = ("orchestrator", "critic", "integrator", "predictor", "communicator", "tool")
for role in role_names:
value = role_models.get(role)
if value:
setattr(settings.models, f"{role}_model", str(value))
def _apply_role_max_token_overrides(settings, role_max_tokens: Dict[str, Any]) -> None:
if not isinstance(role_max_tokens, dict):
return
role_names = ("orchestrator", "critic", "integrator", "predictor", "communicator", "tool")
for role in role_names:
value = role_max_tokens.get(role)
if value in (None, ""):
continue
setattr(settings.models, f"{role}_max_tokens", int(value))
def _sync_role_token_limits_with_budgets(settings, role_max_tokens: Optional[Dict[str, Any]] = None) -> None:
"""
Keep per-role generation caps aligned with global budget controls.
Precedence:
1) Explicit per-role max token overrides (if provided by UI)
2) Global `max_agent_output_tokens` / `max_tool_output_tokens`
3) Model-safe cap via `_clamp_role_token_limits`
"""
role_names = ("orchestrator", "critic", "integrator", "predictor", "communicator", "tool")
explicit_roles = set()
if isinstance(role_max_tokens, dict):
for role in role_names:
value = role_max_tokens.get(role)
if value in (None, "", 0, "0"):
continue
explicit_roles.add(role)
setattr(settings.models, f"{role}_max_tokens", int(value))
max_agent_output = max(1, int(getattr(settings.token_budget, "max_agent_output_tokens", 16000) or 16000))
max_tool_output = max(1, int(getattr(settings.token_budget, "max_tool_output_tokens", 8000) or 8000))
for role in ("orchestrator", "critic", "integrator", "predictor", "communicator"):
if role not in explicit_roles:
setattr(settings.models, f"{role}_max_tokens", max_agent_output)
if "tool" not in explicit_roles:
settings.models.tool_max_tokens = max_tool_output
_clamp_role_token_limits(settings)
def _compute_token_budget_defaults(settings, context_window: int) -> Dict[str, int]:
ctx = max(1, int(context_window or 0))
backend_value = getattr(settings.models.backend, "value", settings.models.backend)
is_local = (
settings.models.backend == LLMBackend.LOCAL
or str(backend_value).lower() == "local"
)
if is_local:
# Local-hosting profile:
# - fixed output caps (agent=16K, tool=8K)
# - tool input defaults to the same as agent input (capped for safety).
agent_output = 16000
tool_output = 8000
headroom = 2048
agent_input_cap = max(4096, ctx - agent_output - headroom)
tool_input_cap = max(4096, ctx - tool_output - headroom)
agent_input = max(4096, min(int(ctx * 0.75), agent_input_cap))
tool_input = max(4096, min(agent_input, tool_input_cap))
return {
"max_agent_input": agent_input,
"max_agent_output": agent_output,
"max_tool_input": tool_input,
"max_tool_output": tool_output,
}
return {
"max_agent_input": int(ctx * 0.95),
"max_agent_output": int(ctx * 0.25),
"max_tool_input": int(ctx * 0.40),
"max_tool_output": int(ctx * 0.25),
}
def _apply_token_budget_defaults(settings, overrides: Dict[str, Any]) -> None:
defaults = _compute_token_budget_defaults(settings, settings.effective_context_window())
if overrides.get("max_agent_input") in (None, "", 0):
settings.token_budget.max_agent_input_tokens = defaults["max_agent_input"]
if overrides.get("max_agent_output") in (None, "", 0):
settings.token_budget.max_agent_output_tokens = defaults["max_agent_output"]
if overrides.get("max_tool_input") in (None, "", 0):
settings.token_budget.max_tool_input_tokens = defaults["max_tool_input"]
if overrides.get("max_tool_output") in (None, "", 0):
settings.token_budget.max_tool_output_tokens = defaults["max_tool_output"]
def _sync_component_token_budgets(settings) -> None:
"""
Synchronize per-component budgets with dynamic token limits.
Why: component budgets were historically static (e.g., critic_budget=50k), which
can produce misleading CRITICAL percentages when users select large-context models.
"""
max_agent_input = int(getattr(settings.token_budget, "max_agent_input_tokens", 30000) or 30000)
max_agent_output = int(getattr(settings.token_budget, "max_agent_output_tokens", 16000) or 16000)
max_tool_input = int(getattr(settings.token_budget, "max_tool_input_tokens", 30000) or 30000)
max_tool_output = int(getattr(settings.token_budget, "max_tool_output_tokens", 8000) or 8000)
# Agent-level budgets scale with agent context + generation capacity.
settings.token_budget.orchestrator_budget = max(50000, int(max_agent_input * 0.80) + max_agent_output)
settings.token_budget.predictor_budget = max(100000, int(max_agent_input * 0.95) + max_agent_output)
settings.token_budget.critic_budget = max(50000, int(max_agent_input * 0.95) + max_agent_output)
settings.token_budget.communicator_budget = max(50000, int(max_agent_input * 0.75) + max_agent_output)
# Integration/execution budgets scale with tool payload sizes.
tool_fusion_floor = int(max(max_agent_input * 0.85, max_tool_input + max_tool_output))
settings.token_budget.fusion_budget = max(90000, tool_fusion_floor)
settings.token_budget.integrator_budget = max(90000, tool_fusion_floor)
settings.token_budget.executor_budget_per_step = max(30000, max_tool_input + max_tool_output)
def _parse_xai_methods(raw_methods: Optional[str]) -> List[str]:
"""Parse comma-separated XAI methods with support for `all` alias."""
if raw_methods is None:
return []
text = str(raw_methods).strip().lower()
if not text:
return []
parts = [p.strip().lower() for p in text.split(",") if p.strip()]
if not parts:
return []
valid = {"external", "internal", "hybrid"}
if "all" in parts:
parts = ["external", "internal", "hybrid"]
invalid = sorted([p for p in parts if p not in valid])
if invalid:
raise ValueError(f"Invalid --xai_methods entries: {', '.join(invalid)}")
# preserve order, remove duplicates
dedup: List[str] = []
for p in parts:
if p not in dedup:
dedup.append(p)
return dedup
def _apply_explainability_overrides(settings, args: argparse.Namespace) -> None:
methods = _parse_xai_methods(getattr(args, "xai_methods", None))
settings.explainability.methods = methods
settings.explainability.enabled = bool(methods)
settings.explainability.run_full_validation = bool(getattr(args, "xai_full_validation", False))
if getattr(args, "xai_external_k", None) is not None:
settings.explainability.external_k = max(1, int(args.xai_external_k))
if getattr(args, "xai_external_runs", None) is not None:
settings.explainability.external_runs = max(1, int(args.xai_external_runs))
if getattr(args, "xai_external_adaptive", None) is not None:
settings.explainability.external_adaptive = bool(args.xai_external_adaptive)
if getattr(args, "xai_internal_model", None):
settings.explainability.internal_model = str(args.xai_internal_model)
if getattr(args, "xai_internal_steps", None) is not None:
settings.explainability.internal_steps = max(1, int(args.xai_internal_steps))
if getattr(args, "xai_internal_baseline", None):
settings.explainability.internal_baseline_mode = str(args.xai_internal_baseline)
if getattr(args, "xai_internal_span_mode", None):
settings.explainability.internal_span_mode = str(args.xai_internal_span_mode)
if getattr(args, "xai_hybrid_model", None):
settings.explainability.hybrid_model = str(args.xai_hybrid_model)
if getattr(args, "xai_hybrid_repeats", None) is not None:
settings.explainability.hybrid_repeats = max(1, int(args.xai_hybrid_repeats))
if getattr(args, "xai_hybrid_temperature", None) is not None:
settings.explainability.hybrid_temperature = float(args.xai_hybrid_temperature)
def _parse_task_spec_payload(raw_payload: Any) -> PredictionTaskSpec:
if isinstance(raw_payload, PredictionTaskSpec):
return raw_payload
if isinstance(raw_payload, dict):
return PredictionTaskSpec(**raw_payload)
if isinstance(raw_payload, str):
text = raw_payload.strip()
if not text:
raise ValueError("prediction task spec payload is empty")
return PredictionTaskSpec(**json.loads(text))
raise ValueError(f"Unsupported prediction task spec payload type: {type(raw_payload).__name__}")
def _resolve_prediction_task_spec(
*,
prediction_type: Optional[str],
target_label: str,
control_label: str,
class_labels: Optional[List[str]] = None,
regression_outputs: Optional[List[str]] = None,
task_spec_json: Optional[str] = None,
task_spec_file: Optional[str] = None,
task_spec_payload: Optional[Dict[str, Any]] = None,
) -> PredictionTaskSpec:
if task_spec_payload is not None:
return _parse_task_spec_payload(task_spec_payload)
if task_spec_json and str(task_spec_json).strip():
return _parse_task_spec_payload(task_spec_json)
if task_spec_file and str(task_spec_file).strip():
path = Path(str(task_spec_file)).expanduser().resolve()
if not path.exists():
raise FileNotFoundError(f"Task spec file not found: {path}")
with open(path, "r") as f:
payload = json.load(f)
return PredictionTaskSpec(**payload)
mode = str(prediction_type or "binary").strip().lower()
if mode == "hierarchical":
raise ValueError("prediction_type=hierarchical requires --task_spec_json or --task_spec_file")
return build_task_spec_from_flat_args(
prediction_type=mode,
target_label=target_label,
control_label=control_label,
class_labels=list(class_labels or []),
regression_outputs=list(regression_outputs or []),
)
def _task_spec_to_legacy_labels(task_spec: PredictionTaskSpec) -> Tuple[str, str]:
target_label, control_label = task_spec.legacy_target_control()
target = str(target_label or "Target Phenotype").strip() or "Target Phenotype"
root_mode = task_spec.root.mode
if root_mode == PredictionMode.BINARY_CLASSIFICATION:
control = str(control_label or DEFAULT_CONTROL_CONDITION).strip() or DEFAULT_CONTROL_CONDITION
else:
control = str(control_label or "").strip()
return target, control
def _align_binary_task_spec_labels(
task_spec: PredictionTaskSpec,
*,
target_label: str,
control_label: str,
) -> PredictionTaskSpec:
"""
Keep binary class labels aligned with explicit runtime labels.
This prevents stale UI payload defaults (e.g., CASE/CONTROL from cached JS)
from overriding user-entered binary labels.
"""
if task_spec.root.mode != PredictionMode.BINARY_CLASSIFICATION:
return task_spec
target = str(target_label or "").strip()
control = str(control_label or "").strip()
if not target or not control:
return task_spec
current = list(task_spec.root.class_labels or [])
if len(current) == 2 and current[0] == target and current[1] == control:
return task_spec
payload = task_spec.model_dump() if hasattr(task_spec, "model_dump") else task_spec.dict()
payload.setdefault("root", {})
payload["root"]["display_name"] = target
payload["root"]["class_labels"] = [target, control]
return PredictionTaskSpec(**payload)
def _normalize_agent_instructions(raw: Optional[Dict[str, Any]]) -> Dict[str, str]:
out = {key: "" for key in AGENT_INSTRUCTION_KEYS}
if not isinstance(raw, dict):
return out
for key in AGENT_INSTRUCTION_KEYS:
out[key] = str(raw.get(key) or "").strip()
return out
def _combine_instruction(global_instruction: str, scoped_instruction: str) -> str:
global_text = str(global_instruction or "").strip()
scoped_text = str(scoped_instruction or "").strip()
if global_text and scoped_text:
return f"{global_text}\n\n{scoped_text}"
return scoped_text or global_text
def _describe_task_spec_for_launch(task_spec: PredictionTaskSpec) -> str:
root = task_spec.root
mode = root.mode
if mode == PredictionMode.BINARY_CLASSIFICATION:
labels = list(root.class_labels or [])
if len(labels) == 2:
return f"{labels[0]} vs {labels[1]}"
return str(root.display_name or root.node_id)
if mode == PredictionMode.MULTICLASS_CLASSIFICATION:
labels = ", ".join(list(root.class_labels or [])[:6])
return f"{root.display_name}: classes=[{labels}]"
outputs = list(root.regression_outputs or [])
if not outputs:
return str(root.display_name or root.node_id)
if len(outputs) == 1:
return f"{root.display_name}: {outputs[0]}"
preview = ", ".join(outputs[:4])
if len(outputs) > 4:
preview = f"{preview}, +{len(outputs) - 4} more"
return f"{root.display_name}: {preview}"
def _prediction_primary_label(prediction: Any) -> str:
root = getattr(prediction, "root_prediction", None)
if root is not None:
mode = getattr(root, "mode", None)
if mode in (PredictionMode.BINARY_CLASSIFICATION, PredictionMode.MULTICLASS_CLASSIFICATION):
cls = getattr(root, "classification", None)
label = str(getattr(cls, "predicted_label", "") or "").strip()
if label:
return label
return str(getattr(root, "node_id", "classification_output"))
reg = getattr(root, "regression", None)
values = getattr(reg, "values", {}) if reg is not None else {}
if isinstance(values, dict) and values:
if len(values) == 1:
key, value = next(iter(values.items()))
try:
return f"{key}: {float(value):.3f}"
except Exception:
return f"{key}: {value}"
rows = []
for key, value in list(values.items())[:3]:
try:
rows.append(f"{key}: {float(value):.3f}")
except Exception:
rows.append(f"{key}: {value}")
if len(values) > 3:
rows.append(f"+{len(values) - 3} more")
return "; ".join(rows)
return str(getattr(root, "node_id", "regression_output"))
if getattr(prediction, "binary_classification", None) is not None:
return str(prediction.binary_classification.value)
return "NON_BINARY"
def _prediction_display_probability(prediction: Any) -> Optional[float]:
root = getattr(prediction, "root_prediction", None)
if root is not None:
mode = getattr(root, "mode", None)
if mode in (PredictionMode.BINARY_CLASSIFICATION, PredictionMode.MULTICLASS_CLASSIFICATION):
cls = getattr(root, "classification", None)
probs = getattr(cls, "probabilities", {}) if cls is not None else {}
predicted_label = str(getattr(cls, "predicted_label", "") or "").strip()
if isinstance(probs, dict) and probs:
if predicted_label in probs:
try:
return max(0.0, min(1.0, float(probs[predicted_label])))
except Exception:
pass
try:
top_prob = max(float(v) for v in probs.values())
return max(0.0, min(1.0, top_prob))
except Exception:
pass
score = getattr(prediction, "probability_score", None)
if isinstance(score, (int, float)):
return float(score)
if root is None:
return None
confidence_score = getattr(root, "confidence_score", None)
if isinstance(confidence_score, (int, float)):
return max(0.0, min(1.0, float(confidence_score)))
return None
def _generate_deep_phenotype_report(
*,
communicator: Communicator,
prediction: Any,
evaluation: Any,
executor_output: Dict[str, Any],
data_overview: Dict[str, Any],
execution_summary: Dict[str, Any],
control_condition: str,
report_context_note: str,
base_output_dir: Path,
participant_id: str,
user_focus_modalities: str = "",
user_general_instruction: str = "",
trigger_source: str = "manual",
ui_step_id: Optional[int] = None,
interactive_ui: bool = False,
) -> Dict[str, Any]:
ui = get_ui()
if interactive_ui:
ui.set_status("Generating deep phenotype report...", stage=6)
ui.on_step_start(
step_id=ui_step_id or 930,
tool_name="Communicator Agent",
description="Generating deep phenotype report...",
stage=6,
)
try:
deep_report = communicator.execute(
prediction=prediction,
evaluation=evaluation,
executor_output=executor_output,
data_overview=data_overview,
execution_summary=execution_summary,
report_context_note=report_context_note,
control_condition=control_condition,
user_focus_modalities=user_focus_modalities,
user_general_instruction=user_general_instruction,
status_callback=(lambda msg: ui.set_status(msg, stage=6)) if interactive_ui else None,
)
deep_path = base_output_dir / "deep_phenotype.md"
with open(deep_path, "w") as f:
f.write(deep_report)
metadata = dict(getattr(communicator, "last_run_metadata", {}) or {})
metadata.update(
{
"trigger_source": trigger_source,
"user_focus_modalities_present": bool(str(user_focus_modalities or "").strip()),
"user_general_instruction_present": bool(str(user_general_instruction or "").strip()),
"output_path": str(deep_path),
}
)
_append_execution_log_entry(
base_output_dir,
participant_id,
{
"type": "COMMUNICATOR",
"timestamp": datetime.now().isoformat(),
"data": metadata,
},
)
perf_path = base_output_dir / f"performance_report_{participant_id}.json"
if perf_path.exists():
try:
with open(perf_path, "r") as f:
perf = json.load(f)
perf["deep_phenotype"] = {
"generated": True,
"path": str(deep_path),
"trigger_source": trigger_source,
"metadata": metadata,
}
with open(perf_path, "w") as f:
json.dump(perf, f, indent=2)
except Exception:
pass
if interactive_ui:
ui.on_step_complete(
step_id=ui_step_id or 930,
tokens=0,
duration_ms=0,
preview="Deep phenotype report generated.",
)
print(f"[Communicator] Saved to: {deep_path}")
return {"success": True, "path": str(deep_path), "metadata": metadata}
except Exception as e:
_append_execution_log_entry(
base_output_dir,
participant_id,
{
"type": "COMMUNICATOR",
"timestamp": datetime.now().isoformat(),
"data": {
"trigger_source": trigger_source,
"success": False,
"error": str(e),
"user_focus_modalities_present": bool(str(user_focus_modalities or "").strip()),
"user_general_instruction_present": bool(str(user_general_instruction or "").strip()),
},
},
)
if interactive_ui:
ui.on_step_failed(step_id=ui_step_id or 930, error=str(e))
return {"success": False, "error": str(e), "metadata": {}}
def _generate_xai_explainability_report(
*,
communicator: Communicator,
xai_result: Dict[str, Any],
prediction: Any,
evaluation: Any,
execution_summary: Dict[str, Any],
target_condition: str,
control_condition: str,
base_output_dir: Path,
participant_id: str,
trigger_source: str = "cli",
ui_step_id: Optional[int] = None,
interactive_ui: bool = False,
) -> Dict[str, Any]:
ui = get_ui()
methods = dict((xai_result or {}).get("methods") or {})
successful_methods = sorted(
[name for name, payload in methods.items() if (payload or {}).get("status") == "success"]
)
if not successful_methods:
reason = "No successful explainability method outputs available; skipping XAI report."
_append_execution_log_entry(
base_output_dir,
participant_id,
{
"type": "XAI_REPORT",
"timestamp": datetime.now().isoformat(),
"data": {
"trigger_source": trigger_source,
"success": False,
"skipped": True,
"reason": reason,
"methods_requested": list((xai_result or {}).get("methods_requested") or []),
},
},
)
return {"success": False, "skipped": True, "reason": reason, "metadata": {}}
if interactive_ui:
ui.set_status("Generating explainability report...", stage=6)
ui.on_step_start(
step_id=ui_step_id or 995,
tool_name="Communicator Agent",
description="Generating explainability report...",
stage=6,
)
try:
xai_report = communicator.execute_xai_report(
xai_result=xai_result,
prediction=prediction,
evaluation=evaluation,
execution_summary=execution_summary,
target_condition=target_condition,
control_condition=control_condition,
status_callback=(lambda msg: ui.set_status(msg, stage=6)) if interactive_ui else None,
)
xai_path = base_output_dir / "xai_explainability_report.md"
with open(xai_path, "w") as f:
f.write(xai_report)
metadata = dict(getattr(communicator, "last_run_metadata", {}) or {})
metadata.update(
{
"trigger_source": trigger_source,
"output_path": str(xai_path),
"methods_requested": list((xai_result or {}).get("methods_requested") or []),
"methods_successful": successful_methods,
}
)
_append_execution_log_entry(
base_output_dir,
participant_id,
{
"type": "XAI_REPORT",
"timestamp": datetime.now().isoformat(),
"data": metadata,
},
)
if interactive_ui:
ui.on_step_complete(
step_id=ui_step_id or 995,
tokens=0,
duration_ms=0,
preview="XAI explainability report generated.",
)
print(f"[Communicator] XAI report saved to: {xai_path}")
return {"success": True, "path": str(xai_path), "metadata": metadata}
except Exception as e:
_append_execution_log_entry(
base_output_dir,
participant_id,
{
"type": "XAI_REPORT",
"timestamp": datetime.now().isoformat(),
"data": {
"trigger_source": trigger_source,
"success": False,
"error": str(e),
"methods_requested": list((xai_result or {}).get("methods_requested") or []),
"methods_successful": successful_methods,
},
},
)
if interactive_ui:
ui.on_step_failed(step_id=ui_step_id or 995, error=str(e))
return {"success": False, "error": str(e), "metadata": {}}
def run_compass_pipeline(
participant_dir: Path,
target_condition: str,
control_condition: str = DEFAULT_CONTROL_CONDITION,
prediction_task_spec: Optional[PredictionTaskSpec] = None,
agent_instructions: Optional[Dict[str, str]] = None,
max_iterations: int = 3,
verbose: bool = True,
interactive_ui: bool = False,
generate_deep_phenotype: bool = False,
generate_xai_report: bool = False,
deep_report_focus_modalities: str = "",
deep_report_general_instruction: str = "",
) -> dict:
"""
Run the complete COMPASS pipeline for a participant.
Args:
participant_dir: Path to participant data directory
target_condition: Target phenotype string (legacy compatibility)
control_condition: Control comparator string (legacy compatibility)
prediction_task_spec: Canonical task specification (hierarchical/mixed)
max_iterations: Maximum orchestration iterations
verbose: Enable verbose output
Returns:
Dictionary with prediction result and metadata
"""
settings = get_settings()
_sync_component_token_budgets(settings)
_sync_role_token_limits_with_budgets(settings)
start_time = datetime.now()
if prediction_task_spec is None:
prediction_task_spec = build_binary_task_spec(
target_label=target_condition,
control_label=control_condition,
)
target_condition, control_condition = _task_spec_to_legacy_labels(prediction_task_spec)
runtime_agent_instructions = _normalize_agent_instructions(agent_instructions)
# Initialize UI
ui = get_ui(enabled=interactive_ui)
# Initialize components
if interactive_ui:
ui.on_pipeline_start(
participant_id=participant_dir.name,
target=target_condition,
control=control_condition,
prediction_spec=(
prediction_task_spec.model_dump()
if hasattr(prediction_task_spec, "model_dump")
else prediction_task_spec.dict()
),
participant_dir=str(participant_dir),
max_iterations=max_iterations
)
else:
print("\n" + "=" * 70)
print(" COMPASS - Clinical Ontology-driven Multi-modal Predictive Agentic Support System")
print("=" * 70)
# Load participant data
if interactive_ui: ui.set_status("Loading Participant Data...", stage=0)
print(f"\n[1/5] Loading participant data from: {participant_dir}")
data_loader = DataLoader()
participant_data = data_loader.load(participant_dir)
participant_id_raw = str(getattr(participant_data, "participant_id", "") or "").strip()
if not participant_id_raw or participant_id_raw.lower() == "unknown":
participant_id = participant_dir.name
try:
participant_data.participant_id = participant_id
except Exception:
pass
else:
participant_id = participant_id_raw
# Build explainability feature space once from loaded artifacts.
multimodal_for_xai = getattr(participant_data.multimodal_data, "features", {}) or {}
try:
raw_multimodal_path = (participant_data.raw_files or {}).get("multimodal_data")
if raw_multimodal_path and Path(raw_multimodal_path).exists():
with open(raw_multimodal_path, "r") as f:
multimodal_for_xai = json.load(f)
except Exception:
multimodal_for_xai = getattr(participant_data.multimodal_data, "features", {}) or {}
non_numerical_for_xai = str(
getattr(participant_data.non_numerical_data, "raw_text", "") or ""
)
feature_space = build_feature_space(
multimodal_for_xai,
non_numerical_text=non_numerical_for_xai,
)
# Initialize logging
exec_logger = ExecutionLogger(participant_id, verbose=verbose)
decision_trace = DecisionTrace(participant_id)
exec_logger.log_pipeline_start(
target_condition=target_condition,
control_condition=control_condition,
prediction_task_mode=prediction_task_spec.root.mode.value if prediction_task_spec is not None else None,
)
# Initialize token manager
token_manager = TokenManager()
# Preflight connectivity check (public API backend)
if settings.models.backend in (LLMBackend.OPENAI, LLMBackend.OPENROUTER):
provider_label = "OpenRouter" if settings.models.backend == LLMBackend.OPENROUTER else "OpenAI"
if interactive_ui:
ui.set_status(f"Checking {provider_label} connectivity...", stage=0)
llm_client = get_llm_client()
try:
llm_client.ping()
except Exception as e:
can_openai_fallback = False
if settings.models.backend == LLMBackend.OPENROUTER:
try:
can_openai_fallback = bool(
llm_client._can_fallback_to_openai(
e,
requested_model=settings.models.public_model_name,
)
)
except Exception:
can_openai_fallback = False
if settings.models.backend == LLMBackend.OPENROUTER and can_openai_fallback:
_activate_openai_fallback(settings, str(e), ui=ui if interactive_ui else None)
if interactive_ui:
ui.set_status("Checking OpenAI fallback connectivity...", stage=0)
try:
get_llm_client().ping()
except Exception as fallback_error:
raise RuntimeError(
"OpenRouter connectivity failed and OpenAI fallback also failed. "
"Verify network access and API keys."
) from fallback_error
else:
key_name = "OPENROUTER_API_KEY" if settings.models.backend == LLMBackend.OPENROUTER else "OPENAI_API_KEY"
raise RuntimeError(
f"{provider_label} connectivity check failed. Verify network access and {key_name}."
) from e
elif settings.models.backend == LLMBackend.LOCAL:
if interactive_ui:
ui.set_status("Initializing local model...", stage=0)
try:
get_llm_client()
except Exception as e:
print(f"[Init][Local] Initialization failed: {type(e).__name__}: {e}")
raise RuntimeError(
f"Local backend initialization failed: {e}"
) from e
# Initialize agents
if interactive_ui: ui.set_status("Initializing Agents...", stage=0)
print(f"\n[2/5] Initializing COMPASS agents...")
orchestrator = Orchestrator(token_manager=token_manager)
executor = Executor(token_manager=token_manager)
predictor = Predictor(token_manager=token_manager)
critic = Critic(token_manager=token_manager)
communicator = Communicator(token_manager=token_manager)
orchestrator.set_runtime_instruction(
_combine_instruction(runtime_agent_instructions.get("global", ""), runtime_agent_instructions.get("orchestrator", ""))
)
predictor.set_runtime_instruction(
_combine_instruction(runtime_agent_instructions.get("global", ""), runtime_agent_instructions.get("predictor", ""))
)
critic.set_runtime_instruction(
_combine_instruction(runtime_agent_instructions.get("global", ""), runtime_agent_instructions.get("critic", ""))
)
communicator.set_runtime_instruction(
_combine_instruction(runtime_agent_instructions.get("global", ""), runtime_agent_instructions.get("communicator", ""))
)
executor.integrator.set_runtime_instruction(
_combine_instruction(runtime_agent_instructions.get("global", ""), runtime_agent_instructions.get("integrator", ""))
)
# Main loop: Orchestrator -> Executor -> Predictor -> Critic
iteration = 1
previous_feedback = None
final_prediction = None
final_evaluation = None
final_executor_output = None
final_plan = None
attempts: List[Dict[str, Any]] = []
while iteration <= max_iterations:
print(f"\n{'='*70}")
print(f" ITERATION {iteration}/{max_iterations}")
print(f"{'='*70}")
# Step 3: Orchestrator creates plan
if interactive_ui:
ui.set_status("Orchestrator creating execution plan...", stage=1, iteration=iteration)
print(f"\n[3/5] Orchestrator creating execution plan...")
print(
f"[Orchestrator] Runtime config: model={settings.models.orchestrator_model}, "
f"max_tokens={settings.models.orchestrator_max_tokens}, temp={settings.models.orchestrator_temperature}, "
f"agent_in={settings.token_budget.max_agent_input_tokens}, "
f"agent_out={settings.token_budget.max_agent_output_tokens}, "
f"tool_in={settings.token_budget.max_tool_input_tokens}, "
f"tool_out={settings.token_budget.max_tool_output_tokens}"
)
orchestrator_started = time.time()
plan = orchestrator.execute(
participant_data=participant_data,
target_condition=target_condition,
control_condition=control_condition,
prediction_task_spec=prediction_task_spec,
previous_feedback=previous_feedback,
iteration=iteration
)
orchestrator_elapsed = int((time.time() - orchestrator_started) * 1000)
print(
f"[Orchestrator] Plan created in {orchestrator_elapsed}ms "
f"(steps={plan.total_steps}, est_tokens={plan.total_estimated_tokens})"
)
exec_logger.log_orchestrator({
"plan_id": plan.plan_id,
"total_steps": plan.total_steps,
"priority_domains": plan.priority_domains
})
decision_trace.record_orchestrator_plan(
domains=plan.priority_domains,
num_steps=plan.total_steps,
reasoning=plan.reasoning[:500]
)
# Step 4: Executor runs plan
print(f"\n[4/5] Executor processing plan...")
executor_started = time.time()
executor_output = executor.execute(
plan=plan,
participant_data=participant_data,
target_condition=target_condition,
control_condition=control_condition,
prediction_task_spec=prediction_task_spec,
agent_instructions=runtime_agent_instructions,
)
print(f"[Executor] Completed in {int((time.time() - executor_started) * 1000)}ms")
final_executor_output = executor_output
final_plan = plan
# Log each step
exec_result = executor_output.get("execution_result")
if exec_result and hasattr(exec_result, 'step_statuses'):
for step_id, status in exec_result.step_statuses.items():