-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcgex.py
More file actions
2100 lines (1725 loc) · 76.8 KB
/
cgex.py
File metadata and controls
2100 lines (1725 loc) · 76.8 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
import dash
from dash import dcc, html, Input, Output, State
import dash_bootstrap_components as dbc
import json
import re
import io
from contextlib import redirect_stdout
from langchain_openai import ChatOpenAI
from langchain_community.graphs import Neo4jGraph
from langchain_classic.chains import GraphCypherQAChain
from langchain_classic.prompts import PromptTemplate, FewShotPromptTemplate
from neo4j import GraphDatabase
import dotenv
import certifi
import os
import dash_cytoscape as cyto
import requests
from requests.auth import HTTPBasicAuth
import neo4j as neo4j_mod
# Load examples from the JSON file
def load_examples(file_path):
try:
with open(file_path, 'r') as file:
examples_data = json.load(file)
examples = examples_data.get('examples', [])
updated_examples = [{"example question": ex.get("question", "No question found"), "example cypher": ex.get("cypher", "No cypher found")} for ex in examples]
return updated_examples
except FileNotFoundError:
return []
# Save examples to the JSON file
def save_example(file_path, question, cypher):
try:
with open(file_path, 'r') as file:
examples_data = json.load(file)
except FileNotFoundError:
examples_data = {"examples": []}
examples_data['examples'].append({"question": question, "cypher": cypher})
with open(file_path, 'w') as file:
json.dump(examples_data, file, indent=4)
# Define the path to the examples JSON file
EXAMPLES_FILE_PATH = 'cypher_examples.json'
# Load environment variables
dotenv.load_dotenv()
# Load API key and Neo4j credentials
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
# KG 1
NEO4J_URI = os.getenv("NEO4J_URI")
NEO4J_USERNAME = os.getenv("NEO4J_USERNAME")
NEO4J_PASSWORD = os.getenv("NEO4J_PASSWORD")
NEO4J_HTTP_URI = os.getenv("NEO4J_HTTP_URI", "http://localhost:7474")
# KG 2
NEO4J_URI_2 = os.getenv("NEO4J_URI_2")
NEO4J_USERNAME_2 = os.getenv("NEO4J_USERNAME_2")
NEO4J_PASSWORD_2 = os.getenv("NEO4J_PASSWORD_2")
NEO4J_HTTP_URI_2 = os.getenv("NEO4J_HTTP_URI_2", "http://localhost:7474")
# Function to retrieve relationship details
#def extract_schema():
def extract_schema(uri, username, password):
try:
#driver = GraphDatabase.driver(NEO4J_URI, auth=(NEO4J_USERNAME, NEO4J_PASSWORD))
driver = GraphDatabase.driver(uri, auth=(username, password))
with driver.session() as session:
# Extract Nodes & Properties
node_query = """
CALL db.schema.nodeTypeProperties()
YIELD nodeType, propertyName
WITH nodeType,
CASE
WHEN nodeType CONTAINS 'ProteinModification' THEN
COLLECT(CASE WHEN propertyName IN ['name', 'amino_acid', 'position'] THEN propertyName END)
ELSE
COLLECT(CASE WHEN propertyName = 'name' THEN propertyName END)
END AS Properties
RETURN nodeType AS NodeLabel, Properties
ORDER BY NodeLabel;
"""
node_schema = session.run(node_query).data()
# Extract Relationships
rel_query = """
MATCH ()-[r]->()
WITH DISTINCT type(r) AS relType, keys(r) AS properties
UNWIND properties AS property
WITH relType, COLLECT(DISTINCT property) AS uniqueProps
WITH relType, [p IN uniqueProps WHERE p IN ["source", "citationType", "pmid", "citationRef", "evidence"]] AS filteredProps
RETURN relType, filteredProps
ORDER BY relType;
"""
rel_schema = session.run(rel_query).data()
# Directionality
# dir_query = """
# MATCH (a)-[r]->(b)
# RETURN DISTINCT type(r) AS RelationshipType, labels(a)[0] AS StartNode, labels(b)[0] AS EndNode
# ORDER BY RelationshipType;
# """
# dir_schema = session.run(dir_query).data()
driver.close()
print("\n🔹 Extracted Nodes Schema:")
for node in node_schema:
print(f" - {node['NodeLabel']} → Properties: {', '.join(node['Properties'])}")
print("\n🔹 Extracted Relationships Schema:")
for rel in rel_schema:
print(f" - {rel['relType']} → Properties: {', '.join(rel['filteredProps'])}")
# print("\n🔹 Extracted Relationship Directionality:")
# for dir in dir_schema:
# print(f" - {dir['RelationshipType']} → Direction: {dir['StartNode']} → {dir['EndNode']}")
return {
"nodes": node_schema,
"relationships": rel_schema
# "directionality": dir_schema
}
except Exception as e:
print(f"⚠️ Error extracting schema: {e}")
return {"nodes": [], "relationships": [], "directionality": []} # Fallback to avoid crashes
#def build_prompt_template(node_schema, rel_schema):
def build_prompt_template(node_schema, rel_schema, kg_name="Selected KG"):
nodes_schema_str = "\n".join(
[f" - {item['NodeLabel']}\n Properties: {', '.join(item['Properties'])}"
for item in node_schema]
)
relationships_schema_str = "\n".join(
[f" - {item['relType']}\n Properties: {', '.join(item['filteredProps'])}"
for item in rel_schema]
)
template = f"""
You are an expert at translating user questions into Cypher Queries.
These Cypher queries are then run on a knowledge graph about COVID-19 and NDDs (Neurodegenerative diseases).
Your task is to **think step-by-step** before generating the Cypher query.
---
## **Graph in Use**
Currently using: **{kg_name}**
## **Graph Schema**
- Nodes:
{nodes_schema_str}
- Relationships:
{relationships_schema_str}
---
## **Instructions for Query Generation**
### **MANDATORY: USE THE GRAPH SCHEMA PROVIDED**
- You must refer to the graph schema when constructing Cypher queries.
- STRICTLY follow the node labels, relationship types, and property names as provided in the schemas.
- DO NOT invent node labels, properties, or relationships not present in the schema.
---
## **Node Matching Rules**
- Do NOT specify any node labels, use name filtering:
MATCH (n) WHERE toLower(n.name) CONTAINS "covid"
- Do NOT apply conflicting conditions on the same entity. Use `OR` instead of `AND` for multiple concepts.
- If the question mentions "neurological impact", "nervous system", "neurodegeneration", etc.,
match nodes using `"neuro"`.
---
## **Relationship Matching Rules**
- First check for a direct relationship (`MATCH (a)-[r]-(b)`).
- If no direct relationship exists, use multi-hop traversal (`MATCH (a)-[*..3]-(b)`).
- Do NOT specify any relationship types. Allow general connections.
- DO NOT filter relationships using `r.name`.
---
## **ALWAYS Include `LIMIT 5` in RETURN.**
---
## **EXAMPLES (Few-Shot Reasoning + Query)**
### Example 1:
**User Question**:
*How do cytokine levels correlate with neurodegenerative outcomes in COVID-19 patients?*
**Step-by-Step Reasoning**:
1. Identify key entities: "cytokine", "COVID", and "neurodegenerative".
2. For "cytokine", match nodes where the entity name includes "cytokine".
3. "COVID" can be matched using `toLower(d.name) CONTAINS "covid"`.
4. Neurodegenerative examples include Alzheimers, Parkinsons, or general neurodegeneration; use:
toLower(d.name) CONTAINS "alzheimer" OR toLower(d.name) CONTAINS "parkinson" OR toLower(d.name)
CONTAINS "neuro"
5. No specific relationship types are required. Use `-[r]-`.
6. Add `LIMIT 5`.
**Cypher Query**:
```cypher
MATCH (c)-[r]-(d)-[r2]-(e)
WHERE toLower(c.name) CONTAINS "cytokine" AND
(toLower(d.name) CONTAINS "parkinson" OR
toLower(d.name) CONTAINS "alzheimer" OR
toLower(d.name) CONTAINS "neuro") AND
toLower(e.name) CONTAINS "covid"
RETURN c, r, d, r2, e LIMIT 5
```
Do NOT add extra text like "Example:", "Cypher:", "---", etc., to the actual Cypher query.
Now generate a Cypher query for this question:
{{question}}
"""
return PromptTemplate(template=template, input_variables=["question"])
# Extract schema dynamically
# try:
# dynamic_schema = extract_schema()
# except Exception as e:
# print(f"⚠️ Failed to extract schema from Neo4j: {e}")
# dynamic_schema = {"nodes": [], "relationships": [], "directionality": []}
# nodes_schema = "\n".join(
# [f" - {item['NodeLabel']}\n Properties: {', '.join(item['Properties'])}"
# for item in dynamic_schema['nodes']]
# )
# relationships_schema = "\n".join(
# [f" - {item['relType']}\n Properties: {', '.join(item['filteredProps'])}"
# for item in dynamic_schema['relationships']]
# )
# PROMPT ENGINE
# CYPHER_GENERATION_TEMPLATE = f"""
# You are an expert at translating user questions into Cypher Queries.
# These Cypher queries are then run on a knowledge graph about COVID-19 and NDDs (Neurodegenerative diseases).
# Your task is to **think step-by-step** before generating the Cypher query.
# ---
# ## **Graph Schema**
# - Nodes:
# {nodes_schema}
# - Relationships:
# {relationships_schema}
# ---
# ## **Instructions for Query Generation**
# ### **MANDATORY: USE THE GRAPH SCHEMA PROVIDED**
# - You must refer to the graph schema when constructing Cypher queries.
# - STRICTLY follow the node labels, relationship types, and property names as provided in the schemas.
# - DO NOT invent node labels, properties, or relationships not present in the schema.
# ---
# ## **Node Matching Rules**
# - Do NOT specify any node labels, use name filtering:
# MATCH (n) WHERE toLower(n.name) CONTAINS "covid"
# - Do NOT apply conflicting conditions on the same entity. Use `OR` instead of `AND` for multiple concepts.
# - If the question mentions "neurological impact", "nervous system", "neurodegeneration", etc.,
# match nodes using `"neuro"`.
# ---
# ## **Relationship Matching Rules**
# - First check for a direct relationship (`MATCH (a)-[r]-(b)`).
# - If no direct relationship exists, use multi-hop traversal (`MATCH (a)-[*..3]-(b)`).
# - Do NOT specify any relationship types. Allow general connections.
# - DO NOT filter relationships using `r.name`.
# ---
# ## **ALWAYS Include `LIMIT 5` in RETURN.**
# ---
# ## **EXAMPLES (Few-Shot Reasoning + Query)**
# ### Example 1:
# **User Question**:
# *How do cytokine levels correlate with neurodegenerative outcomes in COVID-19 patients?*
# **Step-by-Step Reasoning**:
# 1. Identify key entities: "cytokine", "COVID", and "neurodegenerative".
# 2. For "cytokine", match nodes where the entity name includes "cytokine".
# 3. "COVID" can be matched using `toLower(d.name) CONTAINS "covid"`.
# 4. Neurodegenerative examples include Alzheimers, Parkinsons, or general neurodegeneration; use:
# toLower(d.name) CONTAINS "alzheimer" OR toLower(d.name) CONTAINS "parkinson" OR toLower(d.name)
# CONTAINS "neuro"
# 5. No specific relationship types are required. Use `-[r]-`.
# 6. Add `LIMIT 5`.
# **Cypher Query**:
# ```cypher
# MATCH (c)-[r]-(d)-[r2]-(e)
# WHERE toLower(c.name) CONTAINS "cytokine" AND
# (toLower(d.name) CONTAINS "parkinson" OR
# toLower(d.name) CONTAINS "alzheimer" OR
# toLower(d.name) CONTAINS "neuro") AND
# toLower(e.name) CONTAINS "covid"
# RETURN c, r, d, r2, e LIMIT 5
# ```
# Do NOT add extra text like "Example:", "Cypher:", "---", etc., to the actual Cypher query.
# Now generate a Cypher query for this question:
# {{question}}
# """
# Initialize the OpenAI API
# llm = OpenAI(openai_api_key=OPENAI_API_KEY)
llm = ChatOpenAI(
model="gpt-5",
openai_api_key=OPENAI_API_KEY,
model_kwargs={"response_format": {"type": "text"}} # force text
)
# cypher_generation_prompt = PromptTemplate(
# template=CYPHER_GENERATION_TEMPLATE,
# input_variables=["question"],
# )
# Create a prompt template with dynamic schema details
# cypher_generation_prompt = PromptTemplate(
# template=CYPHER_GENERATION_TEMPLATE,
# input_variables=["question"],
# )
# Set the SSL_CERT_FILE environment variable
os.environ["SSL_CERT_FILE"] = certifi.where()
# Connect to both graphs
graph_1 = Neo4jGraph(url=NEO4J_URI, username=NEO4J_USERNAME, password=NEO4J_PASSWORD)
graph_2 = Neo4jGraph(url=NEO4J_URI_2, username=NEO4J_USERNAME_2, password=NEO4J_PASSWORD_2)
# Chains for each KG
# cypher_chain_1 = GraphCypherQAChain.from_llm(
# llm, graph=graph_1, cypher_prompt=cypher_generation_prompt,
# verbose=True, allow_dangerous_requests=True
# )
# cypher_chain_2 = GraphCypherQAChain.from_llm(
# llm, graph=graph_2, cypher_prompt=cypher_generation_prompt,
# verbose=True, allow_dangerous_requests=True
# )
def generate_cypher_fallback(llm, prompt_like, question):
"""Ask the LLM directly for a Cypher and extract it robustly."""
# Accept either a PromptTemplate or a pre-formatted string
if hasattr(prompt_like, "format"):
prompt_txt = prompt_like.format(question=question)
else:
prompt_txt = str(prompt_like)
prompt_txt += "\n\nReturn only the Cypher query. Do not add any explanation."
txt = llm.invoke(prompt_txt).content # get the string to regex
m = re.search(r"```cypher\s*(.*?)```", txt, re.DOTALL | re.IGNORECASE)
if not m:
m = re.search(r"(MATCH[\s\S]*?RETURN[\s\S]*?)(?:$|\n\n|```)", txt, re.IGNORECASE)
if m:
cy = m.group(1).strip().replace("\\", " ")
cy = re.sub(r"\s+", " ", cy)
return cy
return None
# Function to query the KG using a natural language prompt
#def query_kg(prompt, graph, cypher_chain, use_few_shot=False):
def query_kg(prompt, graph, cypher_chain, use_few_shot=False, prompt_str=None):
try:
inputs = {"question": prompt, "query": prompt}
# if use_few_shot:
# examples = load_examples(EXAMPLES_FILE_PATH)
# if examples:
# # example_prompt_template = FewShotPromptTemplate(
# # examples=examples,
# # example_prompt=PromptTemplate(
# # template="Example Question: {example question}\nExample Cypher: {example cypher}\n",
# # input_variables=["example question", "example cypher"]
# # ),
# # prefix=CYPHER_GENERATION_TEMPLATE,
# # suffix="Generate cypher for this Question: {question}",
# # input_variables=["question"],
# # example_separator="\n\n"
# # )
# # Rebuild schema and prompt for few-shot as well
# if graph == graph_1:
# uri, username, password = NEO4J_URI, NEO4J_USERNAME, NEO4J_PASSWORD
# else:
# uri, username, password = NEO4J_URI_2, NEO4J_USERNAME_2, NEO4J_PASSWORD_2
# schema = extract_schema(uri, username, password)
# base_prompt = build_prompt_template(schema["nodes"], schema["relationships"])
# example_prompt_template = FewShotPromptTemplate(
# examples=examples,
# example_prompt=PromptTemplate(
# template="Example Question: {example question}\nExample Cypher: {example cypher}\n",
# input_variables=["example question", "example cypher"]
# ),
# prefix=base_prompt.template,
# suffix="Generate cypher for this Question: {question}",
# input_variables=["question"],
# example_separator="\n\n"
# )
# cypher_chain_instance = GraphCypherQAChain.from_llm(
# llm,
# graph=graph,
# cypher_prompt=example_prompt_template,
# verbose=True,
# allow_dangerous_requests=True
# )
# formatted_prompt = example_prompt_template.format_prompt(question=prompt)
# with io.StringIO() as buf, redirect_stdout(buf):
# response = cypher_chain_instance(inputs)
# output = buf.getvalue()
# else:
# with io.StringIO() as buf, redirect_stdout(buf):
# response = cypher_chain(inputs)
# output = buf.getvalue()
# else:
# with io.StringIO() as buf, redirect_stdout(buf):
# response = cypher_chain(inputs)
# output = buf.getvalue()
# cypher_match = re.search(r'MATCH.*?RETURN.*?(?=\n|$)', output, re.DOTALL)
# if cypher_match:
# generated_cypher = cypher_match.group(0).strip()
# generated_cypher = re.sub(r'\u001b\[0m', '', generated_cypher) # Remove escape sequence
# generated_cypher = generated_cypher.replace("\n", " ") # Replace new line with space
# generated_cypher = generated_cypher.replace("\\", "") # Remove backslashes
# generated_cypher = re.sub(r'\s+', ' ', generated_cypher).strip() # Remove extra spaces
# else:
# generated_cypher = None
if use_few_shot:
if graph == graph_1:
uri, username, password = NEO4J_URI, NEO4J_USERNAME, NEO4J_PASSWORD
else:
uri, username, password = NEO4J_URI_2, NEO4J_USERNAME_2, NEO4J_PASSWORD_2
schema = extract_schema(uri, username, password)
base_prompt = build_prompt_template(schema["nodes"], schema["relationships"])
examples = load_examples(EXAMPLES_FILE_PATH)
example_prompt_template = FewShotPromptTemplate(
examples=examples,
example_prompt=PromptTemplate(
template="Example Question: {example question}\nExample Cypher: {example cypher}\n",
input_variables=["example question", "example cypher"]
),
prefix=base_prompt.template,
suffix="Generate cypher for this Question: {question}",
input_variables=["question"],
example_separator="\n\n"
)
cypher_chain_instance = GraphCypherQAChain.from_llm(
llm, graph=graph, cypher_prompt=example_prompt_template,
verbose=True, allow_dangerous_requests=True, return_intermediate_steps=True
)
response = cypher_chain_instance.invoke(inputs)
formatted_prompt = example_prompt_template.format_prompt(question=prompt)
else:
response = cypher_chain.invoke(inputs)
#formatted_prompt = None
# --- Robust Cypher extraction ---
generated_cypher = None
if isinstance(response, dict):
# try direct field
cy = response.get("cypher")
if isinstance(cy, str) and "MATCH" in cy.upper():
generated_cypher = cy
# try intermediate_steps (common)
if not generated_cypher:
steps = response.get("intermediate_steps") or []
# steps may be a list of dicts or list/tuple; scan from the end
for step in reversed(steps):
q = None
if isinstance(step, dict):
q = step.get("query") or step.get("cypher") or step.get("tool_input")
elif isinstance(step, (list, tuple)) and step:
last = step[-1]
if isinstance(last, dict):
q = last.get("query") or last.get("cypher") or last.get("tool_input")
if isinstance(q, str) and "MATCH" in q.upper():
generated_cypher = q
break
# try fenced code inside 'result'
if not generated_cypher and isinstance(response.get("result"), str):
m = re.search(r"```cypher\s*(.*?)```", response["result"], re.DOTALL | re.IGNORECASE)
if not m:
m = re.search(r"(MATCH[\s\S]*?RETURN[\s\S]*?)(?:$|\n\n|```)", response["result"], re.IGNORECASE)
if m:
generated_cypher = m.group(1).strip()
# sanitize
if generated_cypher:
generated_cypher = generated_cypher.replace("\n", " ")
generated_cypher = generated_cypher.replace("\\", "")
generated_cypher = re.sub(r"\s+", " ", generated_cypher).strip()
if not generated_cypher:
prompt_for_chain = example_prompt_template if use_few_shot else (prompt_str or "")
generated_cypher = generate_cypher_fallback(llm, prompt_for_chain, prompt)
if generated_cypher:
generated_cypher = re.sub(r"\s+", " ", generated_cypher.replace("\n", " ")).strip()
# Try direct LLM fallback using the same prompt
# decide which prompt the chain actually used
#cypher_prompt = formatted_prompt if use_few_shot else cypher_generation_prompt.format(question=prompt)
#cypher_prompt = str(formatted_prompt) if use_few_shot else prompt
#cypher_prompt = str(formatted_prompt) if use_few_shot else cypher_chain.cypher_prompt.format(question=prompt)
cypher_prompt = str(formatted_prompt) if use_few_shot else prompt_str
if generated_cypher:
# Dynamically choose the right credentials
if graph == graph_1:
uri, username, password = NEO4J_URI, NEO4J_USERNAME, NEO4J_PASSWORD
else:
uri, username, password = NEO4J_URI_2, NEO4J_USERNAME_2, NEO4J_PASSWORD_2
results = execute_cypher(generated_cypher, uri, username, password)
detailed_response = generate_detailed_response(results)
return str(cypher_prompt), generated_cypher, json.dumps(results, indent=2), detailed_response
return str(cypher_prompt), generated_cypher, None, None
except Exception as e:
return str(e), None, None, None
# Function to execute Cypher query on Neo4j and retrieve results
def execute_cypher(cypher_query, uri, username, password):
driver = GraphDatabase.driver(uri, auth=(username, password))
with driver.session() as session:
result = session.run(cypher_query)
return [record.data() for record in result]
# Function to generate detailed response using LLM
def generate_detailed_response(kg_results, max_tokens=550):
response_prompt = f"""
You are a medical expert in COVID-19 and NDD (Neurodegenerative Diseases) knowledge.
Make sure you give complete response. It can be concise but should not be incomplete.
Ensure that your response ends with a complete thought and does not stop abruptly.
CRITICAL RULES:
- Do NOT assume causality or direction not present.
- If a relationship in the JSON came from an undirected pattern (e.g., '-[r]-'),
write "connected to" rather than directional verbs.
- If a Relationship object includes start/end nodes, respect that direction in the wording.
- Quote the relationship type verbatim (e.g., 'INVOLVED_IN_PATHWAY', 'INCREASES').
Based on the following knowledge graph results, provide a detailed and structured response:
{json.dumps(kg_results, indent=2)}
Detailed Response:
"""
return llm.invoke(response_prompt).content
# CSS for background image and styling
external_stylesheets = [dbc.themes.BOOTSTRAP]
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
# Add this 👇
app.index_string = '''
<!DOCTYPE html>
<html lang="en">
<head>
{%metas%}
<title>CGEx: Cypher Generating Expert</title>
{%favicon%}
{%css%}
<link href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@500&family=Inter:wght@400;600&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" integrity="sha512-Fo3rlrZj/k7ujTTX+2n9Xl+ZlRNHl0wq35KOEqzZ19aF3b0Ql0KwUsxxW+WUcgcMEwIlWzM8qfRhYFFM2eYVFg==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<style>
body {
margin: 0;
font-family: 'Inter', sans-serif;
background: linear-gradient(to right, #e8faff, #c6ebf2);
color: #002b36;
}
.topnav {
background: rgba(0, 18, 32, 0.85);
padding: 14px 40px;
display: flex;
justify-content: space-between;
align-items: center;
position: sticky;
top: 0;
z-index: 10;
}
.topnav h2 {
margin: 0;
font-size: 1.4rem;
font-weight: 600;
color: #ffffff;
}
.topnav a {
color: #c5e5f2;
margin-left: 20px;
text-decoration: none;
font-weight: 500;
}
.hero {
background-image: url('https://i0.wp.com/asiatimes.com/wp-content/uploads/2022/05/Artificial-Intelligence-AI-Quantum-Computing.jpg?fit=1200%2C794&quality=89&ssl=1');
background-size: cover;
background-position: center;
height: 100vh;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
text-align: center;
padding: 0 20px;
background-blend-mode: overlay;
background-color: rgba(0, 18, 32, 0.7);
}
.hero h1 {
font-family: 'Playfair Display', serif;
font-size: 3.5rem;
font-weight: 700;
margin-bottom: 10px;
color: #f2faff;
}
.hero p {
font-size: 1.2rem;
font-weight: 500; /* Slightly bolder */
max-width: 700px;
margin-bottom: 30px;
color: #f0f6fa; /* Brighter text */
text-shadow: 0 1px 3px rgba(0, 0, 0, 0.6); /* Soft glow */
}
.hero .cta-button {
background: linear-gradient(to right, #00c1e0, #00527a);
border: none;
color: white;
padding: 14px 32px;
font-size: 1rem;
font-weight: 600;
border-radius: 14px;
cursor: pointer;
box-shadow: 0 3px 10px rgba(0, 0, 0, 0.25);
transition: all 0.3s ease;
}
.hero .cta-button:hover {
background: linear-gradient(to right, #00a6c3, #004060);
}
.main-content {
max-width: 960px;
margin: 40px auto;
padding: 40px 30px;
background: transparent;
border-radius: 0;
box-shadow: none;
}
.section {
margin-bottom: 40px;
}
.section h5 {
font-weight: 700;
margin-bottom: 10px;
color: #003344;
}
.form-control {
width: 100%;
border-radius: 12px;
padding: 12px;
border: 1px solid #005f87;
background-color: rgba(0, 24, 36, 0.6);
color: #e6f7ff;
font-size: 1rem;
box-shadow: 0 0 5px rgba(0, 193, 224, 0);
transition: box-shadow 0.3s ease;
}
.form-control:focus {
outline: none;
box-shadow: 0 0 10px rgba(0, 193, 224, 0.6);
}
.btn-primary, .btn-success, .btn-danger {
background-color: #00a6c3 !important;
border: none;
color: white !important;
padding: 10px 20px;
border-radius: 10px;
font-weight: 600;
font-size: 0.95rem;
cursor: pointer;
margin: 5px 10px 15px 0;
transition: background-color 0.2s ease;
}
.btn-primary:hover, .btn-success:hover, .btn-danger:hover {
background-color: #0088a0 !important;
}
.btn-success i, .btn-danger i {
margin-right: 6px;
}
pre {
background: rgba(0, 18, 32, 0.8);
padding: 15px;
border-radius: 12px;
font-size: 0.95rem;
white-space: pre-wrap;
color: #d0e8f0;
border: 1px solid #004b6b;
}
</style>
</head>
<body>
<div class="topnav">
<h2>CGEx</h2>
<div>
<a href="#">Home</a>
<a href="#">About</a>
<a href="#">Use Cases</a>
<a href="#">Contact</a>
</div>
</div>
<div class="hero">
<h1>Translate Biomedical Questions into Cypher</h1>
<p>Built for COVID-NDD Comorbidities research. Powered by explainable AI and knowledge graphs.</p>
<button class="cta-button" onclick="document.querySelector('.main-content').scrollIntoView({ behavior: 'smooth' });">Try It Now</button>
</div>
<div class="main-content">
{%app_entry%}
</div>
<footer>
{%config%}
{%scripts%}
{%renderer%}
</footer>
</body>
</html>
'''
# 1. Add dropdown to select KG in layout
# 2. Update callback to include kg selection from dropdown
# 🧠 In app.layout:
app.layout = dbc.Container([
dbc.Row([
dbc.Col(html.H1("Cypher Generating System with XAI"), className="mb-2")
]),
dbc.Row([
dbc.Col(html.Div("Enter your question:"), width=2),
dbc.Col(dcc.Input(id='user-question', type='text', value='', style={'width': '100%'}), width=6),
dbc.Col(
dcc.Dropdown(
id='kg-selector',
options=[
{'label': 'COVID–NDD CBM', 'value': 'kg1'},
{'label': 'COVID–NDD Negin', 'value': 'kg2'}
],
value='kg1',
clearable=False,
style={
'color': '#000000',
'backgroundColor': '#ffffff',
'fontSize': '15px'
}
),
width=2,
style={'minWidth': '180px'}
),
dbc.Col(dbc.Button("Submit", id='submit-question', color='primary'), width=2)
], className="mb-4"),
dbc.Row([
dbc.Col(html.H5("Generated Cypher Query:"), width=12),
dbc.Col(html.Pre(id='generated-cypher', style={'whiteSpace': 'pre-wrap', 'margin-top': '10px'}), width=12)
], className="mb-4"),
dbc.Row([
dbc.Col(html.H5("Cypher Query Results:"), width=12),
dbc.Col(html.Pre(id='cypher-results', style={'whiteSpace': 'pre-wrap', 'margin-top': '10px'}), width=12)
], className="mb-4"),
dbc.Row([
dbc.Col(html.H5("Detailed Response:"), width=12),
dbc.Col(html.Pre(id='detailed-response', style={'whiteSpace': 'pre-wrap', 'margin-top': '10px'}), width=12)
], className="mb-4"),
dbc.Row([
dbc.Col(html.H5("Solution Graph (Query Result Subgraph):"), width=12),
dbc.Col(
cyto.Cytoscape(
id='solution-graph',
layout={'name': 'cose'}, # good default force-directed layout
style={'width': '100%', 'height': '600px', 'backgroundColor': 'white'},
elements=[],
stylesheet = [
{"selector": "node", "style": {
"label": "data(label)",
"font-size": "12px",
"text-wrap": "wrap",
"text-max-width": "1000px",
"width": 28, "height": 28,
"background-color": "#9aa0a6" # default grey
}},
# Exact labels (when real Neo4j nodes are returned)
{"selector": 'node[labels_str *= "Protein"]', "style": {"background-color": "#66ccff"}}, # blue
{"selector": 'node[labels_str *= "Rna"]', "style": {"background-color": "#4fc3f7"}}, # light blue
{"selector": 'node[labels_str *= "GeneticFlow"]', "style": {"background-color": "#29b6f6"}}, # mid blue
{"selector": 'node[labels_str *= "BiologicalProcess"]', "style": {"background-color": "#ffcc80"}}, # orange
{"selector": 'node[labels_str *= "Complex"]', "style": {"background-color": "#ffd180"}}, # light orange
{"selector": 'node[labels_str *= "BioConcept"]', "style": {"background-color": "#f48fb1"}}, # pink
{"selector": 'node[labels_str *= "Pathology"]', "style": {"background-color": "#b39ddb"}}, # purple
{"selector": 'node[labels_str *= "Abundance"]', "style": {"background-color": "#a5d6a7"}}, # green
# New KG-1 labels (add just these)
{"selector": 'node[labels_str *= "Activity"]', "style": {"background-color": "#4db6ac"}}, # teal
{"selector": 'node[labels_str *= "ProteinModification"]',"style": {"background-color": "#ba68c8"}}, # purple-ish
{"selector": 'node[labels_str *= "Reactants"]', "style": {"background-color": "#81d4fa"}}, # light blue
{"selector": 'node[labels_str *= "Products"]', "style": {"background-color": "#ffe082"}}, # warm yellow
# KG-2: only new labels
{"selector": 'node[labels_str *= "Anatomical_Structure"]', "style": {"background-color": "#ffd54f"}}, # amber
{"selector": 'node[labels_str *= "Pathogen"]', "style": {"background-color": "#ef9a9a"}}, # soft red
{"selector": 'node[labels_str *= "Pathway"]', "style": {"background-color": "#90caf9"}}, # light blue
{"selector": 'node[labels_str *= "Phenotype"]', "style": {"background-color": "#d39b7d"}}, # brown (matches BioConcept vibe)
{"selector": 'node[labels_str *= "SNP"]', "style": {"background-color": "#a5d6a7"}}, # green
{"selector": 'node[labels_str *= "Symptom"]', "style": {"background-color": "#ce93d8"}}, # lavender
{"selector": 'node[labels_str *= "BioConceptLike"]', "style": {"background-color": "#f48fb1"}}, # match BioConcept pink
{"selector": 'node[labels_str *= "BiologicalProcessLike"]', "style": {"background-color": "#ffcc80"}}, # orange
{"selector": 'node[labels_str *= "Biological_Process"]', "style": {"background-color": "#ffcc80"}}, # orange like BiologicalProcess
# Namespace buckets (kick in when we only have dict projections)
{"selector": 'node[labels_str *= "ProteinLike"]', "style": {"background-color": "#66ccff"}}, # HGNC
{"selector": 'node[labels_str *= "BiologicalProcessLike"]', "style": {"background-color": "#ffcc80"}}, # GO
{"selector": 'node[labels_str *= "AbundanceLike"]', "style": {"background-color": "#a5d6a7"}}, # MESH
# DO falls back to 'Pathology' above
{"selector": "edge", "style": {
"label": "data(shortLabel)",
"font-size": "10px",
"curve-style": "bezier",
"target-arrow-shape": "triangle",
"text-rotation": "autorotate",
"text-background-color": "white",
"text-background-opacity": 0.8,
"text-background-padding": 2
}},
]
),
width=12
)
], className="mb-4"),
dbc.Row([
dbc.Col(html.H5("Selected Edge Evidence:"), width=12),
dbc.Col(
html.Pre(
id="edge-evidence",
style={"whiteSpace": "pre-wrap", "marginTop": "10px"}
),
width=12
)
], className="mb-4"),
dbc.Row([
dbc.Col(dbc.Button("Approve Query", id='approve-cypher', color='success', className="mt-2"), width=2),
dbc.Col(dbc.Button("Disapprove Query", id='disapprove-cypher', color='danger', className="mt-2"), width=2)
], className="button-row"),
dbc.Row([
dbc.Col(html.H3("Explainability"), width=12),
dbc.Col(html.H5("Prompt sent to the LLM:"), width=12),
dbc.Col(html.Pre(id='cypher-prompt', style={'whiteSpace': 'pre-wrap', 'margin-top': '10px', 'text-align': 'left'}), width=12)
], className="mb-4")
], className="container")
# ---- helpers (place these well above the callback) ----
def format_prompt_with_examples(prompt_template, question, examples=None):
base = prompt_template.format(question=question)
if not examples:
final = base
else:
shots = []
for ex in examples:
q = ex.get("example question") or ex.get("question")
c = ex.get("example cypher") or ex.get("cypher")
if q and c:
shots.append(f"Example Question: {q}\nExample Cypher:\n```cypher\n{c}\n```")
final = ("\n\n".join(shots) + "\n\n" + base) if shots else base
# 👇 add this strict ending
final += "\n\nReturn only the Cypher query enclosed in a ```cypher``` code block. Do not add any explanation."
return final
CY_CODE_BLOCK = re.compile(r"```cypher\s*(.*?)```", re.DOTALL | re.IGNORECASE)
CY_FALLBACK = re.compile(r"(MATCH[\s\S]*?RETURN[\s\S]*?)(?:$|\n\n|```)", re.IGNORECASE)
def fetch_graph_via_http(cypher_query, http_base_url, username, password, db="neo4j"):
"""
Use Neo4j transactional HTTP endpoint to get the result as a graph
(nodes + relationships), similar to Neo4j Browser's 'Graph' tab.
"""
url = f"{http_base_url}/db/{db}/tx/commit"
payload = {
"statements": [
{
"statement": cypher_query,
"resultDataContents": ["graph"]
}
]
}
resp = requests.post(
url,
json=payload,
auth=HTTPBasicAuth(username, password)
)
resp.raise_for_status()
data = resp.json()
nodes_by_id = {}
rels_by_id = {}
for res in data.get("results", []):
for row in res.get("data", []):
g = row.get("graph") or {}