Elffuss BraidHub

kikocis/GraphRAG-SDK public

423ab603a5a9 · 6.0 KiBRawPermalink
1from falkordb import Graph
2from rag_sdk.source import AbstractSource
3from .entity import Entity
4from .relation import Relation
5from .encoder import SchemaEncoder
6from .decoder import SchemaDecoder
7from .to_graph import schema_to_graph
8from .from_graph import schema_from_graph
9from .auto_detect import schema_auto_detect
10
11class Schema(object):
12 """
13 Knowledge Graph schema (ontology)
14 The schema captures entities types in addition to their attributes
15 and the relationship types between the them
16 """
17
18 def __init__(self):
19 """
20 Initialize Schema
21 """
22
23 self.entities = {}
24 self.relations = {}
25
26 def __eq__(self, other) -> bool:
27 if not isinstance(other, Schema):
28 return False
29
30 if self.entities != other.entities:
31 return False
32
33 if self.relations != other.relations:
34 return False
35
36 return True
37
38
39 def add_entity(self, name:str) -> Entity:
40 """
41 Add a new entity to schema
42
43 Parameters:
44 name (str): Entity name.
45
46 Returns:
47 entity
48 """
49
50 # Validate arguments
51 if not isinstance(name, str) or name == "":
52 raise Exception(f"Invalid name argument, expecting none empty string")
53 if name in self.entities:
54 raise Exception(f"Entity {name} already exists")
55
56 e = Entity(name)
57 self.entities[name] = e
58 return e
59
60 def get_entity(self, name:str) -> Entity | None:
61 """
62 Get an entity from schema
63
64 Returns:
65 entity
66 """
67
68 if not isinstance(name, str) or name == "":
69 raise Exception("Invalid argument, name should be a none empty string")
70
71 if name in self.entities:
72 return self.entities[name]
73 else:
74 return None
75
76 def add_relation(self, name:str, src:Entity, dest:Entity) -> Relation:
77 """
78 Add a relationship to schema
79
80 Returns:
81 relation
82 """
83
84 # Validate arguments
85 if not isinstance(src, Entity) and not isinstance(src, str):
86 raise Exception(f"Invalid argument, src is expected to be either a string or an Entity")
87 if not isinstance(dest, Entity) and not isinstance(dest, str):
88 raise Exception(f"Invalid argument, dest is expected to be either a string or an Entity")
89 if not isinstance(name, str) or name == "":
90 raise Exception(f"Invalid name argument, expecting none empty string")
91
92 if isinstance(src, str) and src == "":
93 raise Exception(f"Invalid src argument, expecting a non empty string")
94 if isinstance(dest, str) and dest == "":
95 raise Exception(f"Invalid dest argument, expecting a non empty string")
96
97 if name in self.relations:
98 raise Exception(f"Relation {name} already exists")
99
100 # fetch entities
101 if isinstance(src, str):
102 src = self.entities[src]
103 if isinstance(dest, str):
104 dest = self.entities[dest]
105
106 # Both src and dest must have at least one unique attribute
107 if len(src.unique_attributes()) == 0:
108 raise Exception(f"{src.name} must have at least one unique attribute")
109 if len(dest.unique_attributes()) == 0:
110 raise Exception(f"{dest.name} must have at least one unique attribute")
111
112 # Create relation and add it to schema
113 r = Relation(name, src, dest)
114 self.relations[name] = r
115
116 return r
117
118 def validate(self) -> bool:
119 """
120 Validate schema
121
122 Returns:
123 True if schema is valid
124 """
125
126 # Make sure each Relation reference existing Entities
127 # And each referenced entity has at least one unique attribute
128 for r in self.relations:
129 r = self.relations[r]
130 src = r.src.name
131 dest = r.dest.name
132 if src not in self.entities:
133 raise Exception(f"Relation {r.name} reference a none existing entity {src}")
134 if dest not in self.entities:
135 raise Exception(f"Relation {r.name} reference a none existing entity {dest}")
136
137 src = self.entities[src]
138 if len(src.unique_attributes()) == 0:
139 raise Exception(f"Relation {r.name} src endpoint {src.name} is missing a unique attribute")
140
141 dest = self.entities[dest]
142 if len(dest.unique_attributes()) == 0:
143 raise Exception(f"Relation {r.name} src endpoint {dest.name} is missing a unique attribute")
144
145 return True
146
147 def save_graph(self, g:Graph) -> None:
148 """
149 Save schema as an ontology graph
150
151 Parameters:
152 g (Graph): graph to create
153 """
154
155 schema_to_graph(self, g)
156
157 def to_JSON(self) -> str:
158 """
159 Encode schema to JSON string
160
161 Returns:
162 JSON representation of schema
163 """
164
165 encoder = SchemaEncoder()
166 return encoder.to_JSON(self)
167
168 @classmethod
169 def from_graph(cls, g:Graph) -> 'Schema':
170 """
171 Create a schema from an ontology graph
172
173 Parameters:
174 g (Graph): ontology graph to load
175
176 Returns:
177 Schema: schema
178 """
179
180 s = cls()
181 schema_from_graph(s, g)
182 return s
183
184 @classmethod
185 def auto_detect(cls, sources: list[AbstractSource], model="gpt-3.5-turbo-0125") -> 'Schema':
186 """
187 Auto detect schema from sources
188
189 Parameters:
190 sources (list[AbstractSource]): list of sources to extract schema from
191 model (str): OpenAI model to use
192
193 Returns:
194 Schema: schema
195 """
196
197 s = cls()
198 schema_auto_detect(s, sources, model)
199 return s
200
201 @classmethod
202 def from_JSON(cls, json:str) -> 'Schema':
203 """
204 Create a schema from JSON
205
206 Parameters:
207 json (str): the output from to_JSON
208
209 Returns:
210 Schema: schema
211 """
212
213 s = cls()
214 decoder = SchemaDecoder()
215 decoder.from_JSON(s, json)
216 return s