-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2382 lines (2103 loc) · 110 KB
/
Copy pathapp.py
File metadata and controls
2382 lines (2103 loc) · 110 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
"""
Critical Minerals Causal Engine - Full inference engine UI.
Integrates: LLM query, RAG document search, causal DAG/identifiability,
scenario run, RAG validation, synthetic control, and POMDP (sensor maintenance).
"""
# Use non-interactive backend so matplotlib works in Gradio/server (no display)
import matplotlib
matplotlib.use("Agg")
import gradio as gr
import os
import subprocess
import sys
from pathlib import Path
PROJECT_ROOT = Path(__file__).resolve().parent
if str(PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(PROJECT_ROOT))
# ---------------------------------------------------------------------------
# Shared RAGPipeline singleton — persists episodic memory within a session.
# Memory is loaded from / saved to data/memory/ across restarts automatically.
# ---------------------------------------------------------------------------
_MEMORY_DIR = PROJECT_ROOT / "data" / "memory"
_pipeline = None # lazy-init on first use
def _get_pipeline():
global _pipeline
if _pipeline is None:
from src.minerals.rag_pipeline import RAGPipeline
_MEMORY_DIR.mkdir(parents=True, exist_ok=True)
_pipeline = RAGPipeline(backend="auto", memory_dir=str(_MEMORY_DIR))
return _pipeline
# ----- Subprocess helpers -----
def _run(cmd: list, timeout: int = 120, capture_stdout_stderr: bool = True) -> tuple[str, str, int]:
result = subprocess.run(
cmd,
capture_output=capture_stdout_stderr,
text=True,
timeout=timeout,
cwd=str(PROJECT_ROOT),
)
return (result.stdout or "", result.stderr or "", result.returncode)
# ----- Tab: Query Model -----
def query_model(natural_language_query: str) -> str:
try:
out, err, code = _run(
[sys.executable, "-m", "scripts.llm_query", natural_language_query],
timeout=60,
)
if code != 0:
return f"❌ Error:\n\n{err}\n\nOutput:\n{out}"
return f"```\n{out}\n```"
except subprocess.TimeoutExpired:
return "❌ Query timed out (>60s). Try a simpler question."
except Exception as e:
return f"❌ Error: {str(e)}"
# ----- Tab: RAG - Search Documents -----
DOCUMENTS_DIR = PROJECT_ROOT / "data" / "documents"
UPLOAD_SUBDIR = DOCUMENTS_DIR / "uploaded" # Your uploaded .txt/.md go here (any scenario, incl. non-mineral)
def save_uploaded_documents(files: list | None) -> str:
"""Save uploaded .txt/.md files to data/documents/uploaded/. Returns status message."""
if not files:
return "No files selected. Choose one or more .txt or .md files."
UPLOAD_SUBDIR.mkdir(parents=True, exist_ok=True)
allowed = {".txt", ".md"}
saved = []
import shutil
for f in files:
if f is None:
continue
path = (f.get("name") if isinstance(f, dict) else f) or f
path = Path(str(path))
if not path.suffix or path.suffix.lower() not in allowed:
continue
dest = UPLOAD_SUBDIR / path.name
try:
shutil.copy2(str(path), str(dest))
saved.append(path.name)
except Exception as e:
return f"❌ Error saving {path.name}: {e}"
if not saved:
return "No .txt or .md files to save. Only .txt and .md are indexed."
return f"✅ Saved {len(saved)} file(s) to `data/documents/uploaded/`: {', '.join(saved)}\n\nClick **Rebuild search index** to include them in search."
def reindex_rag() -> str:
"""Rebuild the RAG document index after adding/uploading files."""
script = PROJECT_ROOT / "scripts" / "index_rag_documents.py"
if not script.exists():
return f"❌ Index script not found: {script}"
try:
out, err, code = _run(
[sys.executable, str(script)],
timeout=120,
)
if code != 0:
return f"❌ Index failed:\n\n{err}\n{out}"
return f"✅ Index rebuilt.\n\n{out or 'Done.'}"
except subprocess.TimeoutExpired:
return "❌ Reindex timed out."
except Exception as e:
return f"❌ Error: {str(e)}"
def build_hipporag_index() -> str:
"""Build HippoRAG graph index from data/documents. Requires hipporag + OPENAI or vLLM."""
try:
from src.minerals.hipporag_retrieval import HippoRAGRetriever, hipporag_available
if not hipporag_available():
return "❌ HippoRAG not installed. Run: python3 -m pip install hipporag or pip install -e \".[hipporag]\""
docs_dir = PROJECT_ROOT / "data" / "documents"
save_dir = docs_dir / "hipporag_index"
retriever = HippoRAGRetriever(documents_dir=str(docs_dir), save_dir=str(save_dir))
return retriever.index()
except Exception as e:
return f"❌ HippoRAG index failed: {e}"
def rag_search(query: str, top_k: int = 5, use_kg_context: bool = False, use_classic_search_only: bool = False) -> str:
"""Retrieve document chunks via RAGPipeline (memory-boosted) and return formatted markdown."""
try:
pipeline = _get_pipeline()
q = query.strip() or "graphite supply trade"
backend_override = "simple" if use_classic_search_only else None
if backend_override:
# Bypass pipeline for explicit classic-only request
from src.minerals.rag_retrieval import SimpleRAGRetriever
docs_dir = PROJECT_ROOT / "data" / "documents"
retriever = SimpleRAGRetriever(str(docs_dir), str(docs_dir / "index.json"))
if not retriever.chunks:
return "⚠️ No documents indexed. Run `python scripts/index_rag_documents.py` first."
chunks = retriever.retrieve(query=q, top_k=max(1, min(20, top_k)))
else:
chunks = pipeline.retrieve(query=q, top_k=max(1, min(20, top_k)))
if not chunks:
return "⚠️ No documents indexed. Run `python scripts/index_rag_documents.py` first."
lines = []
if use_kg_context:
kg_ctx = get_kg_context_for_rag()
if kg_ctx:
lines.append(kg_ctx)
lines.append("---\n")
backend_label = f"({pipeline.backend_name})" if not backend_override else "(classic)"
lines.append(f"**Retrieved {len(chunks)} chunks** {backend_label}\n")
for i, c in enumerate(chunks, 1):
meta = c.get("metadata", {}) if isinstance(c.get("metadata"), dict) else {}
src = meta.get("source_file", c.get("source", "?"))
sim = c.get("similarity", 0.0)
text = (c.get("text") or "")[:1500]
if len(c.get("text") or "") > 1500:
text += "..."
lines.append(f"### {i}. `{src}` (score: {sim:.3f})\n{text}\n")
return "\n".join(lines)
except Exception as e:
return f"❌ RAG error: {e}"
def rag_ask(query: str, top_k: int = 5) -> tuple[str, str]:
"""Full Q&A with memory: retrieve → few-shot inject → LLM answer → store episode.
Returns (answer_markdown, episode_id) for subsequent feedback.
"""
if not query.strip():
return ("Enter a question first.", "")
try:
from src.llm.chat import is_chat_available
if not is_chat_available():
return ("❌ No LLM backend configured. Set ANTHROPIC_API_KEY or OPENAI_API_KEY in your `.env`.", "")
pipeline = _get_pipeline()
result = pipeline.ask(query.strip(), top_k=max(1, min(20, top_k)), use_memory=True)
answer = result.get("answer", "(no answer)")
episode_id = result.get("episode_id", "")
sources = result.get("sources", [])
lines = [f"### Answer\n{answer}\n"]
if sources:
lines.append(f"**Sources ({len(sources)}):**")
for s in sources[:5]:
meta = s.get("metadata", {}) if isinstance(s.get("metadata"), dict) else {}
src = meta.get("source_file", s.get("source", "?"))
sim = s.get("similarity", 0.0)
lines.append(f"- `{src}` (score: {sim:.3f})")
lines.append(f"\n*Episode ID: `{episode_id}` — use thumbs to rate this answer.*")
return ("\n".join(lines), episode_id)
except Exception as e:
return (f"❌ Ask error: {e}", "")
def rag_feedback(episode_id: str, rating: float) -> str:
"""Store user rating for the last episode."""
if not episode_id:
return "No episode to rate — run Ask first."
try:
pipeline = _get_pipeline()
pipeline.feedback(episode_id, rating=rating)
label = "👍 positive" if rating > 0 else "👎 negative"
return f"Feedback recorded ({label}) for episode `{episode_id}`."
except Exception as e:
return f"❌ Feedback error: {e}"
def run_rag_eval(n_questions: int = 10, top_k: int = 5) -> str:
"""Generate synthetic questions, evaluate retrieval + answer quality, and trigger self-learning."""
try:
from src.llm.chat import is_chat_available
if not is_chat_available():
return "❌ No LLM configured — set ANTHROPIC_API_KEY or OPENAI_API_KEY."
from src.minerals.rag_eval import RAGEvaluator
pipeline = _get_pipeline()
ev = RAGEvaluator(pipeline)
n = max(3, int(n_questions))
questions = ev.generate_questions(n_chunks=n, questions_per_chunk=1)
if not questions:
return "⚠️ No questions generated — check that documents are indexed."
ret_report = ev.evaluate_retrieval(questions, top_k=int(top_k))
ans_n = min(5, len(questions))
ans_report = ev.evaluate_answers(questions[:ans_n], top_k=int(top_k))
learn_stats = ev.learn(ret_report, ans_report)
lines = [
"### RAG Evaluation",
f"**Questions generated:** {len(questions)}",
"",
"**Retrieval quality:**",
f"- Hit@{int(top_k)}: **{ret_report.get('hit_at_k', 0)*100:.1f}%**",
f"- MRR@{int(top_k)}: **{ret_report.get('mrr', 0):.3f}**",
"",
f"**Answer quality** (n={ans_n}):",
f"- Avg faithfulness: **{ans_report.get('faithfulness_mean', ans_report.get('avg_faithfulness', 0)):.2f}**",
f"- Avg relevance: **{ans_report.get('relevance_mean', ans_report.get('avg_relevance', 0)):.2f}**",
"",
"**Self-learning:**",
f"- Episodes stored as few-shot examples: **{learn_stats.get('stored', 0)}**",
f"- Knowledge gaps logged: **{learn_stats.get('gaps', 0)}**",
]
return "\n".join(lines)
except Exception as e:
return f"❌ Eval error: {e}"
def rag_memory_stats() -> str:
"""Return human-readable memory statistics."""
try:
pipeline = _get_pipeline()
s = pipeline.stats()
mem = s.get("memory") or {}
if not mem:
return "Memory not initialised."
lines = [
f"**Memory** (`{mem.get('memory_dir', '')}`):",
f"- Episodes stored: **{mem.get('n_episodes', 0)}**",
f"- Avg quality score: **{mem.get('avg_quality', 0):.2f}**",
f"- Boosted chunks: **{mem.get('n_boosted_chunks', 0)}**",
f"- Knowledge gaps: **{mem.get('n_gaps', 0)}**",
f"- Backend: **{s.get('backend', '?')}**",
]
return "\n".join(lines)
except Exception as e:
return f"❌ Stats error: {e}"
# ----- Knowledge Graph (shared helpers for KG tab, RAG, Causal) -----
_kg = None # singleton — persists enrichment within session
_KG_SAVE_PATH = PROJECT_ROOT / "data" / "knowledge_graph.json"
def _get_kg():
"""Return the KG singleton. Loads from disk if a saved copy exists; otherwise builds fresh."""
global _kg
if _kg is None:
from src.minerals.knowledge_graph import build_critical_minerals_kg, CausalKnowledgeGraph
if _KG_SAVE_PATH.exists():
try:
_kg = CausalKnowledgeGraph.load(str(_KG_SAVE_PATH))
except Exception:
_kg = build_critical_minerals_kg()
else:
_kg = build_critical_minerals_kg()
return _kg
_CRITICAL_MINERALS = [
"graphite", "lithium", "cobalt", "copper", "nickel",
"antimony", "beryllium", "cesium", "gallium", "germanium",
"indium", "niobium", "platinum", "tantalum", "tellurium",
"titanium", "tungsten", "vanadium", "yttrium", "rare-earths",
]
def kg_batch_enrich(top_k: int = 3) -> str:
"""Enrich the KG with supply chain knowledge for every critical mineral in the corpus."""
try:
from src.minerals.kg_extractor import KGExtractor
from src.llm.chat import is_chat_available
if not is_chat_available():
return "❌ No LLM configured — set ANTHROPIC_API_KEY or OPENAI_API_KEY."
pipeline = _get_pipeline()
kg = _get_kg()
extractor = KGExtractor(pipeline)
before_rels = kg.num_relationships
before_ents = kg.num_entities
_KG_SAVE_PATH.parent.mkdir(parents=True, exist_ok=True)
per_mineral: list[str] = []
for mineral in _CRITICAL_MINERALS:
query = f"{mineral} supply chain production trade export restrictions"
try:
n = extractor.enrich(kg, query, top_k=max(1, int(top_k)))
per_mineral.append(f"- {mineral}: +{n} triples")
except Exception as e:
per_mineral.append(f"- {mineral}: ⚠️ {e}")
kg.save(str(_KG_SAVE_PATH))
added_rels = kg.num_relationships - before_rels
added_ents = kg.num_entities - before_ents
lines = [
f"**Batch enrichment complete** ({len(_CRITICAL_MINERALS)} minerals)",
f"- New relationships: **+{added_rels}** (total: {kg.num_relationships})",
f"- New entities: **+{added_ents}** (total: {kg.num_entities})",
f"- Saved to `{_KG_SAVE_PATH.name}`",
"",
"**Per-mineral:**",
] + per_mineral
return "\n".join(lines)
except Exception as e:
return f"❌ Batch enrich failed: {e}"
def kg_enrich_from_corpus(query: str, top_k: int = 5) -> str:
"""Retrieve corpus chunks for *query*, extract triples, merge into the live KG, and save."""
if not query.strip():
return "Enter a query to enrich the KG with."
try:
from src.minerals.kg_extractor import KGExtractor
pipeline = _get_pipeline()
kg = _get_kg()
extractor = KGExtractor(pipeline)
before_rels = kg.num_relationships
before_ents = kg.num_entities
_KG_SAVE_PATH.parent.mkdir(parents=True, exist_ok=True)
n = extractor.enrich(kg, query.strip(), top_k=max(1, min(20, top_k)),
save_path=str(_KG_SAVE_PATH))
added_rels = kg.num_relationships - before_rels
added_ents = kg.num_entities - before_ents
lines = [
f"**KG enriched** from query: `{query.strip()}`",
f"- Triples extracted: **{n}**",
f"- New relationships: **+{added_rels}** (total: {kg.num_relationships})",
f"- New entities: **+{added_ents}** (total: {kg.num_entities})",
f"- Saved to `{_KG_SAVE_PATH.relative_to(PROJECT_ROOT)}`",
]
return "\n".join(lines)
except Exception as e:
return f"❌ Enrich failed: {e}"
def get_kg_summary() -> str:
"""Return human-readable KG summary (entities, relationship counts)."""
try:
kg = _get_kg()
return kg.summary()
except Exception as e:
return f"❌ Failed to build KG: {e}"
def kg_rebuild() -> tuple[str, object]:
"""Reset the KG singleton and rebuild from disk / base, return (summary, shock_choices)."""
global _kg
_kg = None # clear singleton so _get_kg() rebuilds
try:
kg = _get_kg()
return kg.summary(), gr.update(choices=kg.get_shock_origin_candidates())
except Exception as e:
return f"❌ {e}", gr.update(choices=[])
def get_kg_shock_sources() -> list[str]:
"""Return entity IDs suitable as shock origins (have outgoing CAUSES)."""
try:
kg = _get_kg()
return kg.get_shock_origin_candidates()
except Exception:
return []
def run_kg_shock_propagation(origin_id: str) -> str:
"""Propagate shock from origin_id and return formatted trace."""
if not (origin_id or origin_id.strip()):
return "Select or enter a shock origin (e.g. china_export_controls)."
try:
kg = _get_kg()
trace = kg.propagate_shock(origin_id.strip(), initial_magnitude=1.0, decay=0.5, max_depth=5)
lines = [f"**Shock origin:** `{trace.origin}`", f"**Affected entities ({len(trace.affected)}):**", ""]
for eid, mag in sorted(trace.affected.items(), key=lambda x: -x[1]):
path = trace.paths.get(eid, [])
path_str = " → ".join(path) if path else eid
lines.append(f"- `{eid}` (impact {mag:.3f}): path `{path_str}`")
return "\n".join(lines)
except Exception as e:
return f"❌ Shock propagation failed: {e}"
def run_kg_identifiability() -> str:
"""Run identifiability analysis using the KG-derived causal DAG."""
try:
kg = _get_kg()
dag = kg.to_causal_dag()
queries = [
("china_export_controls", "graphite"),
("graphite", "ev_batteries"),
("china_export_controls", "ev_batteries"),
]
lines = [
"**Identifiability (KG-derived DAG)**",
"",
"**Do-calculus (Pearl):** Rule 1 — insertion/deletion of observations. Rule 2 — action/observation exchange. Rule 3 — insertion/deletion of actions.",
"",
f"Nodes: {len(dag.graph.nodes())}, Edges: {len(dag.graph.edges())}",
"",
]
for treatment, outcome in queries:
if treatment not in dag.graph or outcome not in dag.graph:
lines.append(f"- P({outcome}|do({treatment})): (skip — node not in DAG)")
continue
result = dag.is_identifiable(treatment, outcome)
yes_no = "✅ YES" if result.identifiable else "❌ NO"
lines.append(f"- **P({outcome}|do({treatment}))**: {yes_no}")
if result.identifiable:
lines.append(f" Formula: {result.formula}")
if result.strategy:
lines.append(f" Strategy: {result.strategy.value}")
if result.adjustment_set:
lines.append(f" Adjustment set: {result.adjustment_set}")
if result.derivation_steps:
lines.append(" *Do-calculus derivation:*")
for step in result.derivation_steps:
if step.strip():
lines.append(f" {step}")
lines.append("")
return "\n".join(lines)
except Exception as e:
return f"❌ KG identifiability failed: {e}"
def get_kg_dag_edges() -> str:
"""Return text listing of edges in the KG-derived causal DAG."""
try:
kg = _get_kg()
dag = kg.to_causal_dag()
edges = list(dag.graph.edges())
if not edges:
return "(No causal edges in KG-derived DAG.)"
return "Causal edges (cause → effect):\n" + "\n".join(f" {u} → {v}" for u, v in sorted(edges))
except Exception as e:
return f"❌ {e}"
def get_kg_dag_image(simplified=True):
"""Render KG-derived causal DAG to PNG. simplified=True caps nodes for legibility."""
try:
use_simplified = simplified if isinstance(simplified, bool) else (simplified != "Full graph")
import matplotlib.pyplot as plt
plt.close("all") # clear any previous figures
path = PROJECT_ROOT / "kg_causal_dag.png"
kg = _get_kg()
from scripts.run_knowledge_graph import visualize_kg_dag
max_nodes = 42 if use_simplified else None
visualize_kg_dag(kg, str(path), max_nodes=max_nodes)
plt.close("all")
return str(path)
except Exception as e:
# Return path to a simple error placeholder so user sees feedback
err_path = PROJECT_ROOT / "kg_dag_error.png"
try:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(8, 4))
ax.text(0.5, 0.5, f"Visualization failed:\n{str(e)}", ha="center", va="center",
fontsize=12, wrap=True)
ax.axis("off")
plt.savefig(str(err_path), bbox_inches="tight", dpi=150)
plt.close("all")
return str(err_path)
except Exception:
return None
def get_kg_dag_interactive_html(simplified=True):
"""Return HTML for an interactive DAG viewer with smooth zoom and pan (vis-network)."""
import json
try:
use_simplified = simplified if isinstance(simplified, bool) else (simplified != "Full graph")
kg = _get_kg()
from scripts.run_knowledge_graph import get_kg_dag_interactive_data
data = get_kg_dag_interactive_data(kg, max_nodes=42 if use_simplified else None)
if not data or not data.get("nodes"):
return "<p>No graph data to display. Build the KG first.</p>"
# Escape JSON for embedding in HTML
data_js = json.dumps(data).replace("</", "<\\/")
return _INTERACTIVE_DAG_HTML_TEMPLATE.format(data_js=data_js)
except Exception as e:
return f"<p>Interactive viewer failed: {e}</p>"
_INTERACTIVE_DAG_HTML_TEMPLATE = """
<div id="dag-container" style="width:100%; height:520px; background:#fafafa; border-radius:8px;"></div>
<script src="https://unpkg.com/vis-network/standalone/umd/vis-network.min.js"></script>
<script>
(function() {
var data = {data_js};
var nodes = new vis.DataSet(data.nodes.map(function(n) {
return {{ id: n.id, label: n.label, title: n.id, x: n.x, y: n.y, color: n.color, fixed: true }};
}));
var edges = new vis.DataSet(data.edges.map(function(e) {{ return {{ from: e.from, to: e.to, arrows: "to" }}; }}));
var container = document.getElementById("dag-container");
var net = new vis.Network(container, {{ nodes: nodes, edges: edges }}, {{
nodes: {{ shape: "box", font: {{ size: 14 }}, margin: 10, borderWidth: 2 }},
edges: {{ width: 1.5, smooth: {{ type: "cubicBezier", roundness: 0.2 }}}},
physics: false,
interaction: {{ zoomView: true, dragView: true, hover: true, tooltipDelay: 100 }},
layout: {{ randomSeed: 1 }}
}});
net.fit({{ animation: {{ duration: 300, easingFunction: "easeInOutQuad" }}}});
})();
</script>
<p style="margin-top:8px;color:#666;font-size:13px;">Scroll to zoom • Drag background to pan • Hover nodes for full name</p>
"""
def get_kg_context_for_rag() -> str:
"""Short KG context string for RAG augmentation (entities + key causal relations)."""
try:
kg = _get_kg()
summary = kg.summary()
dag = kg.to_causal_dag()
all_edges = list(dag.graph.edges())
edges = sorted(all_edges)[:30]
head = "**Knowledge Graph context**\n" + summary + "\n\n**Key causal relations:**\n"
suffix = "\n..." if len(all_edges) > 30 else ""
return head + "\n".join(f"{u} → {v}" for u, v in edges) + suffix
except Exception:
return ""
# ----- Tab: Query Model (unified chain) -----
_FALLBACK_CAUSAL_PAIRS = [
("china_export_controls", "graphite"),
("graphite", "ev_batteries"),
("china_export_controls", "ev_batteries"),
("china", "graphite"),
]
def _causal_candidates_for_question(question: str, dag) -> list[tuple[str, str]]:
"""Derive relevant (treatment, outcome) pairs by matching question tokens to DAG node IDs.
Each DAG node ID like ``china_export_controls`` is split into tokens and checked against
the question words. All matched-node pairs are returned (capped at 40 to bound runtime).
Falls back to the hardcoded graphite/China pairs if nothing matches.
"""
q_tokens = set(question.lower().replace("?", "").replace(",", "").replace("'", "").split())
nodes = list(dag.graph.nodes())
matched: list[str] = []
for node in nodes:
node_tokens = set(node.lower().replace("_", " ").replace("-", " ").split())
if node_tokens & q_tokens:
matched.append(node)
if not matched:
return _FALLBACK_CAUSAL_PAIRS
pairs = [(t, o) for t in matched for o in matched if t != o]
return pairs[:40]
def unified_query(question: str, top_k: int = 5) -> str:
"""Chain: RAG retrieve → KG causal ID → simulation do() + backdoor ATE → LLM synthesis."""
if not question.strip():
return "Enter a question."
from src.llm.chat import chat_completion, is_chat_available
sections: list[str] = []
causal_numeric_context = "" # numeric estimates for LLM prompt
# ── 1. RAG retrieve ──────────────────────────────────────────────────────
try:
pipeline = _get_pipeline()
chunks = pipeline.retrieve(question.strip(), top_k=max(1, min(20, top_k)))
rag_context = "\n\n".join(
f"[{i+1}] {(c.get('metadata') or {}).get('source_file', '?')}: "
f"{(c.get('text') or '')[:600]}"
for i, c in enumerate(chunks)
)
sections.append(
f"### 1. Retrieved {len(chunks)} documents\n"
+ "\n".join(
f"- [{i+1}] `{(c.get('metadata') or {}).get('source_file', '?')}`"
for i, c in enumerate(chunks)
)
)
except Exception as e:
rag_context = ""
sections.append(f"### 1. RAG retrieval\n⚠️ {e}")
# ── 2. Causal identification + numeric estimation ─────────────────────────
try:
from src.minerals.causal_inference import GraphiteSupplyChainDAG
from src.minerals.causal_engine import CausalInferenceEngine
# Use KG-derived DAG for identifiability, graphite SCM for estimation
kg = _get_kg()
kg_dag = kg.to_causal_dag()
candidates = _causal_candidates_for_question(question.strip(), kg_dag)
# Also always check graphite SCM pairs relevant to the question
scm_dag = GraphiteSupplyChainDAG()
_SCM_PAIRS = [
("ExportPolicy", "Price"),
("ExportPolicy", "TradeValue"),
("Demand", "Price"),
("GlobalDemand", "Price"),
]
q_lower = question.lower()
scm_candidates = [
(t, o) for t, o in _SCM_PAIRS
if any(kw in q_lower for kw in (t.lower(), o.lower(),
"export", "price", "demand", "trade", "restrict", "impact"))
] or [("ExportPolicy", "Price")] # always include main pair
id_lines: list[str] = []
numeric_lines: list[str] = []
# KG-DAG identifiability
for t, o in candidates:
if t in kg_dag.graph and o in kg_dag.graph:
result = kg_dag.is_identifiable(t, o)
if result.identifiable:
strategy = result.strategy.value if result.strategy else "adjustment"
id_lines.append(f"- P({o}|do({t})): ✅ via {strategy} — `{result.formula}`")
# Graphite SCM: simulation-based do() estimate using default scenario
try:
import yaml
from src.minerals.schema import ScenarioConfig
_default_scenario = PROJECT_ROOT / "scenarios" / "graphite_baseline_2000_2011.yaml"
if _default_scenario.exists():
cfg = ScenarioConfig(**yaml.safe_load(_default_scenario.read_text()))
engine = CausalInferenceEngine(scm_dag, cfg=cfg)
for t, o in scm_candidates:
try:
do_result = engine.do(t, 0.4) # do(treatment=40%)
delta = do_result.effect_on_outcome.get(
{"Price": "P", "TradeValue": "TradeValue", "Demand": "D"}.get(o, o), None
)
if delta is not None:
numeric_lines.append(
f"- **do({t}=0.4)** → Δ{o} = **{delta:+.3f}** "
f"(sim-based, 2000–2011 baseline)"
)
except Exception:
pass
except Exception:
pass
# Graphite SCM: backdoor ATE using cross-scenario data (shock vs baseline)
# Run a shocked version to get variation in ExportPolicy for ATE estimation
try:
from src.minerals.simulate import run_scenario
import yaml
from src.minerals.schema import ScenarioConfig
from src.minerals.schema import ShockConfig
if _default_scenario.exists():
cfg_base = ScenarioConfig(**yaml.safe_load(_default_scenario.read_text()))
cfg_shock = cfg_base.model_copy(deep=True)
cfg_shock.shocks = list(cfg_shock.shocks) + [
ShockConfig(type="export_restriction", start_year=cfg_base.time.start_year,
end_year=cfg_base.time.end_year, magnitude=0.4)
]
df_base, _ = run_scenario(cfg_base)
df_shock, _ = run_scenario(cfg_shock)
# Pool baseline (ExportPolicy=0) + shock (ExportPolicy=0.4) runs
df_base["ExportPolicy"] = 0.0
df_shock["ExportPolicy"] = 0.4
import pandas as pd
df_pooled = pd.concat([df_base, df_shock], ignore_index=True)
df_pooled = df_pooled.rename(columns={"P": "Price", "D": "Demand", "Q": "TradeValue"})
engine2 = CausalInferenceEngine(scm_dag)
for t, o in [("ExportPolicy", "Price"), ("Demand", "Price")]:
if t in df_pooled.columns and o in df_pooled.columns:
try:
est = engine2.backdoor_estimate(df_pooled, treatment=t, outcome=o)
numeric_lines.append(
f"- **Backdoor ATE** {t}→{o}: **{est.ate:+.3f}** "
f"95% CI [{est.ate_ci[0]:+.3f}, {est.ate_ci[1]:+.3f}]"
)
except Exception:
pass
except Exception:
pass
matched_nodes = sorted({n for pair in candidates for n in pair if n in kg_dag.graph})
node_note = (
f"*(matched KG nodes: {', '.join(f'`{n}`' for n in matched_nodes[:8])})*"
if matched_nodes else ""
)
causal_context = "\n".join(id_lines) if id_lines else "(no identifiable pairs in KG DAG for this question)"
numeric_context = "\n".join(numeric_lines) if numeric_lines else ""
causal_numeric_context = numeric_context
sec2 = f"### 2. Causal identification + estimation\n{node_note}\n{causal_context}"
if numeric_lines:
sec2 += f"\n\n**Numeric estimates (graphite SCM):**\n{numeric_context}"
sections.append(sec2)
except Exception as e:
causal_context = ""
sections.append(f"### 2. Causal identification\n⚠️ {e}")
# ── 3. LLM synthesis ─────────────────────────────────────────────────────
if not is_chat_available():
sections.append("### 3. Synthesis\n❌ No LLM configured — set ANTHROPIC_API_KEY or OPENAI_API_KEY.")
return "\n\n".join(sections)
prompt = (
f"You are a critical minerals supply chain analyst.\n\n"
f"QUESTION: {question.strip()}\n\n"
f"RETRIEVED DOCUMENTS:\n{rag_context or '(none)'}\n\n"
f"CAUSAL STRUCTURE:\n{causal_context or '(none)'}\n\n"
+ (f"NUMERIC CAUSAL ESTIMATES:\n{causal_numeric_context}\n\n" if causal_numeric_context else "")
+ "Write a concise, structured answer that:\n"
"1. Directly answers the question using the documents (cite [1], [2], …)\n"
"2. Explains the causal mechanism where relevant\n"
"3. Quantifies the expected impact using the numeric estimates above when available\n"
"4. Flags key uncertainties and model assumptions"
)
try:
answer = chat_completion([{"role": "user", "content": prompt}], max_tokens=900)
sections.append(f"### 3. Synthesis\n{answer}")
except Exception as e:
sections.append(f"### 3. Synthesis\n❌ LLM error: {e}")
return "\n\n".join(sections)
# ----- Report export -----
def export_report(content: str) -> str | None:
"""Save *content* to a timestamped file in runs/ and return the path for download."""
if not content or not content.strip():
return None
import datetime
ts = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
out_dir = PROJECT_ROOT / "runs" / "reports"
out_dir.mkdir(parents=True, exist_ok=True)
path = out_dir / f"report_{ts}.md"
path.write_text(content, encoding="utf-8")
return str(path)
# ----- Tab: Causal Analysis + DAG -----
def show_causal_analysis(scenario_name: str = "") -> str:
"""
Run identifiability analysis against the SELECTED scenario's shocks.
- If a scenario is selected: extracts its shocks, maps them to treatment
nodes, and runs identifiability for those specific (treatment, outcome)
pairs plus the standard ones.
- If no scenario: falls back to the standard graphite queries.
- Always uses the live GraphiteSupplyChainDAG (which includes the
TradeValue→Price and Demand→Price observed edges we added).
"""
import yaml
from src.minerals.causal_inference import GraphiteSupplyChainDAG
from src.minerals.do_calculus import (
id_algorithm, rule_1_statement, rule_2_statement, rule_3_statement,
)
dag = GraphiteSupplyChainDAG()
lines = [
"## Causal Identifiability Analysis (Pearl do-calculus)\n",
"**Do-calculus rules:**",
f"- {rule_1_statement()}",
f"- {rule_2_statement()}",
f"- {rule_3_statement()}",
"",
f"**DAG:** {len(dag.graph.nodes())} nodes "
f"({len(dag.observed_vars)} observed, {len(dag.unobserved_vars)} unobserved), "
f"{len(dag.graph.edges())} edges",
"",
]
# Build queries from selected scenario shocks + always-include standard queries
queries: list[tuple[str, str]] = []
scenario_label = "default graphite DAG"
if scenario_name:
path = PROJECT_ROOT / "scenarios" / scenario_name
if path.exists():
try:
cfg_raw = yaml.safe_load(path.read_text())
shocks = cfg_raw.get("shocks", [])
scenario_label = scenario_name
for s in shocks:
node = _SHOCK_TYPE_TO_CAUSAL.get(s.get("type", ""), ("ExportPolicy",))[0]
for outcome in ("Price", "TradeValue"):
if (node, outcome) not in queries and node != outcome:
queries.append((node, outcome))
except Exception:
pass
# Always include the core graphite queries
for pair in [("ExportPolicy", "Price"), ("ExportPolicy", "TradeValue"),
("Demand", "Price"), ("GlobalDemand", "Price")]:
if pair not in queries:
queries.append(pair)
lines.append(f"*Scenario: `{scenario_label}`*\n")
for treatment, outcome in queries:
if treatment not in dag.graph or outcome not in dag.graph:
lines.append(f"- P({outcome}|do({treatment})): (skip — node not in DAG)\n")
continue
result = dag.is_identifiable(treatment, outcome)
status = "✅ Identifiable" if result.identifiable else "❌ Not identifiable"
lines.append(f"### P({outcome} | do({treatment}))")
lines.append(f"**{status}**")
if result.identifiable:
lines.append(f"- Strategy: `{result.strategy.value if result.strategy else 'N/A'}`")
if result.adjustment_set:
lines.append(f"- Adjustment set Z: {sorted(result.adjustment_set)}")
lines.append(f"- Estimand: `{result.formula}`")
if result.assumptions:
lines.append("- Assumptions: " + "; ".join(result.assumptions))
# ID algorithm cross-check
id_res = id_algorithm(dag, treatment, outcome)
if id_res["derivation_steps"]:
deriv = "\n".join(s for s in id_res["derivation_steps"] if s.strip())
lines.append(f"\n<details><summary>ID algorithm derivation</summary>\n\n```\n{deriv}\n```\n\n</details>")
else:
lines.append(f"- Reason: {result.formula}")
lines.append("")
# Parameter identification strategies
lines.append("---\n### Parameter identification strategies")
for pid in dag.get_parameter_identifications():
lines.append(
f"- **{pid.parameter}** (`{pid.description}`): "
f"`{pid.estimand}` via {pid.strategy.value}"
)
return "\n".join(lines)
def get_dag_image_path():
"""Return the most up-to-date DAG image: KG-derived if it exists, else default."""
for p in ("kg_causal_dag.png", "graphite_causal_dag.png"):
path = PROJECT_ROOT / p
if path.exists():
return str(path)
return None
def generate_dag_image(scenario_name: str = "") -> str | None:
"""
Regenerate the DAG image.
- If the KG has been built/enriched, generates the KG-derived DAG
(which reflects LLM-extracted causal edges from the corpus).
- Falls back to the static GraphiteSupplyChainDAG.
The KG-derived DAG will be DIFFERENT from run to run as more documents
are indexed and the KG is enriched — it's live, not hardcoded.
"""
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
# Prefer KG-derived DAG (reflects enrichment)
try:
kg = _get_kg()
if kg is not None:
dag = kg.to_causal_dag()
if len(dag.graph.edges()) > 0:
path = PROJECT_ROOT / "kg_causal_dag.png"
dag.visualize(str(path))
plt.close("all")
return str(path)
except Exception:
pass
# Fallback: static GraphiteSupplyChainDAG (always has the correct structure)
try:
from src.minerals.causal_inference import GraphiteSupplyChainDAG
path = PROJECT_ROOT / "graphite_causal_dag.png"
dag = GraphiteSupplyChainDAG()
dag.visualize(str(path))
plt.close("all")
return str(path)
except Exception:
return None
# Keep old name as alias for any callers
def generate_default_dag_image():
return generate_dag_image()
# ----- Tab: Run Scenario -----
def list_scenarios() -> list[str]:
scenarios_dir = PROJECT_ROOT / "scenarios"
if not scenarios_dir.exists():
return []
return sorted(
f.name for f in scenarios_dir.iterdir()
if f.suffix.lower() in (".yaml", ".yml")
)
def _parse_run_dir_from_stdout(stdout: str) -> str:
"""Extract run directory from 'Outputs: <path>' in scenario script output."""
for line in reversed((stdout or "").strip().splitlines()):
line = line.strip()
if line.startswith("Outputs:") and len(line) > 8:
return line[8:].strip()
return ""
def run_scenario_tab(scenario_name: str) -> tuple[str, str]:
"""Run scenario and return (markdown_output, run_dir_to_prefill). Includes scenario YAML in output."""
empty = ("Select a scenario from the dropdown.", "")
if not scenario_name:
return empty
path = PROJECT_ROOT / "scenarios" / scenario_name
if not path.exists():
return (f"❌ File not found: {path}", "")
try:
# Read scenario YAML to show after run
yaml_section = ""
try:
yaml_text = path.read_text(encoding="utf-8")
yaml_section = "\n\n---\n**Scenario YAML** (`" + scenario_name + "`):\n\n```yaml\n" + yaml_text.strip() + "\n```\n"
except Exception:
yaml_section = "\n\n*(Could not read scenario file.)*"
out, err, code = _run(
[sys.executable, "-m", "scripts.run_scenario", "--scenario", str(path)],
timeout=120,
)
if code != 0:
return (f"❌ Run failed:\n\n{err}\n\n{out}", "")
run_dir = _parse_run_dir_from_stdout(out)
body = f"```\n{out}\n```" + yaml_section
return (body, run_dir)
except subprocess.TimeoutExpired:
return ("❌ Scenario run timed out.", "")
except Exception as e:
return (f"❌ Error: {str(e)}", "")
# ----- Causal Ask (unified entry point) -----
def causal_ask(question: str, scenario_name: str = "", top_k: int = 5) -> str:
"""
Natural-language causal question → complete analysis in one shot.
Combines every tool in the stack:
1. RAG retrieval (HippoRAG/SimpleRAG) — what the corpus says
2. KG causal identification — is the effect identifiable? what's the formula?
3. Simulation do() — numeric effect from graph surgery (needs scenario)
4. Backdoor ATE + bootstrap CI — observational causal estimate (needs scenario)
5. Counterfactual — what would have happened without the shock? (needs scenario)
6. Supply chain cascade — how the shock propagates through trade network
7. LLM synthesis — grounded answer citing all of the above
"""
import yaml