Elffuss BraidHub

kikocis/GraphRAG-SDK public

423ab603a5a9 · 2.3 KiBRawPermalink
1from .schema import Schema
2from .entity import Entity
3from .relation import Relation
4
5def relation_to_create_func(r:Relation):
6 src_lbl = r.src.name
7 dest_lbl = r.dest.name
8 func_name = r.name
9
10 func = f"def {r.name}(args):\n" # def MovieStream(args):
11 func += "\targs = remove_none_values(args)\n" # args = remove_none_values(args)
12
13 # extract required src arguments
14 src_attrs = r.src.unique_attributes()
15
16 # extract required dest arguments
17 func += "\tq = \"MERGE (s:" + src_lbl + " {"
18 func += ", ".join([f"{attr.name}: " + f"${attr.name}" for attr in src_attrs])
19 func += "}) "
20
21 # extract required src arguments
22 dest_attrs = r.dest.unique_attributes()
23
24 func += "MERGE (d:" + dest_lbl + " {"
25 func += ", ".join([f"{attr.name}: " + f"${attr.name}" for attr in dest_attrs])
26 func += "}) "
27
28 func += "MERGE (s)-[r:" + r.name + "]->(d)\"\n"
29
30 # construct query params
31 func += "\tparams = {"
32 func += ", ".join([f"'{attr.name}': args['{attr.name}']" for attr in src_attrs])
33 func += ", "
34 func += ", ".join([f"'{attr.name}': args['{attr.name}']" for attr in dest_attrs])
35 func += "}\n"
36
37 func += "\tg.query(q, params)\n"
38
39 return (func_name, func)
40
41def entity_to_create_func(e:Entity):
42 func_name = f"Create_{e.name}" # Create_Actor
43 func = f"def {func_name}(args):\n" # def Create_Actor(args):
44
45 func += "\targs = remove_none_values(args)\n"
46 func += "\tquery = \"MERGE (n:" + e.name + " {" # query = "MERGE (n:Actor {
47
48 unique_attributes = e.unique_attributes()
49
50 func += ", ".join([f"{attr.name}: ${attr.name}" for attr in unique_attributes]) + "})"
51 func += " SET n += $args\"\n"
52
53 func += "\tparams = {"
54 func += ", ".join([f"'{attr.name}': args['{attr.name}']" for attr in unique_attributes])
55 func += ", 'args': args}\n"
56
57 func += "\tg.query(query, params)\n"
58
59 return (func_name, func)
60
61def schema_to_functions(s:Schema):
62 if not isinstance(s, Schema):
63 raise Exception("Invalid argument, expecting a Schema object")
64
65 functions = []
66 for e in s.entities:
67 func = entity_to_create_func(s.entities[e])
68 functions.append(func)
69
70 for r in s.relations:
71 func = relation_to_create_func(s.relations[r])
72 functions.append(func)
73
74 return functions