| 1 | from falkordb import Graph |
| 2 | from graphrag_sdk.source import AbstractSource |
| 3 | from .entity import Entity |
| 4 | from .relation import Relation |
| 5 | from .encoder import SchemaEncoder |
| 6 | from .decoder import SchemaDecoder |
| 7 | from .to_graph import schema_to_graph |
| 8 | from .from_graph import schema_from_graph |
| 9 | from .auto_detect import schema_auto_detect |
| 10 | |
| 11 | class 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 = set([]) |
| 24 | self.relations = set([]) |
| 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.add(e) |
| 58 | |
| 59 | return e |
| 60 | |
| 61 | def get_entity(self, name:str) -> Entity | None: |
| 62 | """ |
| 63 | Get an entity from schema |
| 64 | |
| 65 | Returns: |
| 66 | entity |
| 67 | """ |
| 68 | |
| 69 | if not isinstance(name, str) or name == "": |
| 70 | raise Exception("Invalid argument, name should be a none empty string") |
| 71 | |
| 72 | for e in self.entities: |
| 73 | if e.name == name: |
| 74 | return e |
| 75 | |
| 76 | return None |
| 77 | |
| 78 | def add_relation(self, name:str, src:Entity, dest:Entity) -> Relation: |
| 79 | """ |
| 80 | Add a relationship to schema |
| 81 | |
| 82 | Returns: |
| 83 | relation |
| 84 | """ |
| 85 | |
| 86 | # Validate arguments |
| 87 | if not isinstance(src, Entity) and not isinstance(src, str): |
| 88 | raise Exception(f"Invalid argument, src is expected to be either a string or an Entity") |
| 89 | if not isinstance(dest, Entity) and not isinstance(dest, str): |
| 90 | raise Exception(f"Invalid argument, dest is expected to be either a string or an Entity") |
| 91 | if not isinstance(name, str) or name == "": |
| 92 | raise Exception(f"Invalid name argument, expecting none empty string") |
| 93 | |
| 94 | if isinstance(src, str) and src == "": |
| 95 | raise Exception(f"Invalid src argument, expecting a non empty string") |
| 96 | if isinstance(dest, str) and dest == "": |
| 97 | raise Exception(f"Invalid dest argument, expecting a non empty string") |
| 98 | |
| 99 | if name in self.relations: |
| 100 | raise Exception(f"Relation {name} already exists") |
| 101 | |
| 102 | # Both src and dest must have at least one unique attribute |
| 103 | if len(src.unique_attributes()) == 0: |
| 104 | raise Exception(f"{src.name} must have at least one unique attribute") |
| 105 | if len(dest.unique_attributes()) == 0: |
| 106 | raise Exception(f"{dest.name} must have at least one unique attribute") |
| 107 | |
| 108 | # Create relation and add it to schema |
| 109 | r = Relation(name, src, dest) |
| 110 | self.relations.add(r) |
| 111 | |
| 112 | return r |
| 113 | |
| 114 | def validate(self) -> bool: |
| 115 | """ |
| 116 | Validate schema |
| 117 | |
| 118 | Returns: |
| 119 | True if schema is valid |
| 120 | """ |
| 121 | |
| 122 | # Make sure each Relation reference existing Entities |
| 123 | # And each referenced entity has at least one unique attribute |
| 124 | for r in self.relations: |
| 125 | src = r.src |
| 126 | dest = r.dest |
| 127 | |
| 128 | if src not in self.entities: |
| 129 | raise Exception(f"Relation {r.name} reference a none existing entity {src}") |
| 130 | if dest not in self.entities: |
| 131 | raise Exception(f"Relation {r.name} reference a none existing entity {dest}") |
| 132 | if len(src.unique_attributes()) == 0: |
| 133 | raise Exception(f"Relation {r.name} src endpoint {src.name} is missing a unique attribute") |
| 134 | if len(dest.unique_attributes()) == 0: |
| 135 | raise Exception(f"Relation {r.name} src endpoint {dest.name} is missing a unique attribute") |
| 136 | |
| 137 | return True |
| 138 | |
| 139 | def save_graph(self, g:Graph) -> None: |
| 140 | """ |
| 141 | Save schema as an ontology graph |
| 142 | |
| 143 | Parameters: |
| 144 | g (Graph): graph to create |
| 145 | """ |
| 146 | |
| 147 | schema_to_graph(self, g) |
| 148 | |
| 149 | def to_JSON(self) -> str: |
| 150 | """ |
| 151 | Encode schema to JSON string |
| 152 | |
| 153 | Returns: |
| 154 | JSON representation of schema |
| 155 | """ |
| 156 | |
| 157 | encoder = SchemaEncoder() |
| 158 | return encoder.to_JSON(self) |
| 159 | |
| 160 | @classmethod |
| 161 | def from_graph(cls, g:Graph) -> 'Schema': |
| 162 | """ |
| 163 | Create a schema from an ontology graph |
| 164 | |
| 165 | Parameters: |
| 166 | g (Graph): ontology graph to load |
| 167 | |
| 168 | Returns: |
| 169 | Schema: schema |
| 170 | """ |
| 171 | |
| 172 | s = cls() |
| 173 | schema_from_graph(s, g) |
| 174 | return s |
| 175 | |
| 176 | @classmethod |
| 177 | def auto_detect(cls, sources: list[AbstractSource], model="gpt-3.5-turbo-0125") -> 'Schema': |
| 178 | """ |
| 179 | Auto detect schema from sources |
| 180 | |
| 181 | Parameters: |
| 182 | sources (list[AbstractSource]): list of sources to extract schema from |
| 183 | model (str): OpenAI model to use |
| 184 | |
| 185 | Returns: |
| 186 | Schema: schema |
| 187 | """ |
| 188 | |
| 189 | s = cls() |
| 190 | schema_auto_detect(s, sources, model) |
| 191 | return s |
| 192 | |
| 193 | @classmethod |
| 194 | def from_JSON(cls, json:str) -> 'Schema': |
| 195 | """ |
| 196 | Create a schema from JSON |
| 197 | |
| 198 | Parameters: |
| 199 | json (str): the output from to_JSON |
| 200 | |
| 201 | Returns: |
| 202 | Schema: schema |
| 203 | """ |
| 204 | |
| 205 | s = cls() |
| 206 | decoder = SchemaDecoder() |
| 207 | decoder.from_JSON(s, json) |
| 208 | return s |