mgbam commited on
Commit
2782916
Β·
verified Β·
1 Parent(s): 8e4dca9

Create graph_tools.py

Browse files
Files changed (1) hide show
  1. genesis/utils/graph_tools.py +75 -0
genesis/utils/graph_tools.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # genesis/utils/graph_tools.py
2
+ """
3
+ Graph Utilities for GENESIS-AI
4
+ Handles writing research topics and papers into the Neo4j graph database.
5
+ """
6
+
7
+ import logging
8
+ from typing import List, Dict, Optional
9
+ from neo4j import GraphDatabase
10
+ import os
11
+
12
+ logging.basicConfig(level=logging.INFO)
13
+
14
+ # Optional Neo4j connection
15
+ NEO4J_URI = os.getenv("NEO4J_URI")
16
+ NEO4J_USER = os.getenv("NEO4J_USER")
17
+ NEO4J_PASSWORD = os.getenv("NEO4J_PASSWORD")
18
+
19
+ driver = None
20
+ if NEO4J_URI and NEO4J_USER and NEO4J_PASSWORD:
21
+ try:
22
+ driver = GraphDatabase.driver(NEO4J_URI, auth=(NEO4J_USER, NEO4J_PASSWORD))
23
+ logging.info("[Neo4j] Connected in graph_tools.")
24
+ except Exception as e:
25
+ logging.error(f"[Neo4j] Connection failed in graph_tools: {e}")
26
+ else:
27
+ logging.info("[Neo4j] No URI/user/password set β€” skipping graph_tools connection.")
28
+
29
+
30
+ def write_topic_and_papers(topic: str, papers: List[Dict], db_driver: Optional[GraphDatabase.driver] = None):
31
+ """
32
+ Store a topic node and its related papers in Neo4j.
33
+
34
+ Args:
35
+ topic (str): Research topic name
36
+ papers (List[Dict]): List of paper dicts with keys: title, authors, link
37
+ db_driver: Optional Neo4j driver instance
38
+ """
39
+ if not (db_driver or driver):
40
+ logging.warning("[GraphTools] Skipping write β€” no Neo4j connection.")
41
+ return
42
+
43
+ neo_driver = db_driver or driver
44
+
45
+ try:
46
+ with neo_driver.session() as session:
47
+ # Create topic node
48
+ session.run(
49
+ """
50
+ MERGE (t:Topic {name: $topic})
51
+ """,
52
+ topic=topic
53
+ )
54
+
55
+ # Create paper nodes and relationships
56
+ for paper in papers:
57
+ session.run(
58
+ """
59
+ MERGE (p:Paper {title: $title})
60
+ ON CREATE SET p.authors = $authors, p.link = $link
61
+ MERGE (t:Topic {name: $topic})
62
+ MERGE (t)-[:HAS_PAPER]->(p)
63
+ """,
64
+ title=paper.get("title", ""),
65
+ authors=paper.get("authors", []),
66
+ link=paper.get("link", ""),
67
+ topic=topic
68
+ )
69
+
70
+ logging.info(f"[GraphTools] Added topic '{topic}' and {len(papers)} papers.")
71
+ except Exception as e:
72
+ logging.error(f"[GraphTools] Error writing to Neo4j: {e}")
73
+
74
+
75
+ __all__ = ["write_topic_and_papers"]