| 1 | import logging |
| 2 | from graphrag_sdk.ontology import Ontology |
| 3 | from falkordb import FalkorDB |
| 4 | from graphrag_sdk.source import AbstractSource |
| 5 | from graphrag_sdk.model_config import KnowledgeGraphModelConfig |
| 6 | from graphrag_sdk.steps.extract_data_step import ExtractDataStep |
| 7 | from graphrag_sdk.steps.graph_query_step import GraphQueryGenerationStep |
| 8 | from graphrag_sdk.fixtures.prompts import GRAPH_QA_SYSTEM, CYPHER_GEN_SYSTEM |
| 9 | from graphrag_sdk.steps.qa_step import QAStep |
| 10 | from graphrag_sdk.chat_session import ChatSession |
| 11 | from graphrag_sdk.helpers import map_dict_to_cypher_properties |
| 12 | from graphrag_sdk.attribute import AttributeType, Attribute |
| 13 | from graphrag_sdk.models import GenerativeModelChatSession |
| 14 | |
| 15 | logger = logging.getLogger(__name__) |
| 16 | logger.setLevel(logging.DEBUG) |
| 17 | |
| 18 | |
| 19 | class KnowledgeGraph: |
| 20 | """Knowledge Graph model data as a network of entities and relations |
| 21 | To create one it is best to provide a ontology which will define the graph's ontology |
| 22 | In addition to a set of sources from which entities and relations will be extracted. |
| 23 | """ |
| 24 | |
| 25 | def __init__( |
| 26 | self, |
| 27 | name: str, |
| 28 | model_config: KnowledgeGraphModelConfig, |
| 29 | ontology: Ontology, |
| 30 | host: str = "127.0.0.1", |
| 31 | port: int = 6379, |
| 32 | username: str | None = None, |
| 33 | password: str | None = None, |
| 34 | ): |
| 35 | """ |
| 36 | Initialize Knowledge Graph |
| 37 | |
| 38 | Parameters: |
| 39 | name (str): Knowledge graph name. |
| 40 | model (GenerativeModel): The Google GenerativeModel to use. |
| 41 | host (str): FalkorDB hostname. |
| 42 | port (int): FalkorDB port number. |
| 43 | username (str|None): FalkorDB username. |
| 44 | password (str|None): FalkorDB password. |
| 45 | ontology (Ontology|None): Ontology to use. |
| 46 | """ |
| 47 | |
| 48 | if not isinstance(name, str) or name == "": |
| 49 | raise Exception("name should be a non empty string") |
| 50 | |
| 51 | # connect to database |
| 52 | self.db = FalkorDB(host=host, port=port, username=username, password=password) |
| 53 | self.graph = self.db.select_graph(name) |
| 54 | |
| 55 | self._name = name |
| 56 | self._ontology = ontology |
| 57 | self._model_config = model_config |
| 58 | self.sources = set([]) |
| 59 | |
| 60 | # Attributes |
| 61 | |
| 62 | @property |
| 63 | def name(self): |
| 64 | return self._name |
| 65 | |
| 66 | @name.setter |
| 67 | def name(self, value): |
| 68 | raise AttributeError("Cannot modify the 'name' attribute") |
| 69 | |
| 70 | @property |
| 71 | def ontology(self): |
| 72 | return self._ontology |
| 73 | |
| 74 | @ontology.setter |
| 75 | def ontology(self, value): |
| 76 | self._ontology = value |
| 77 | |
| 78 | def list_sources(self) -> list[AbstractSource]: |
| 79 | """ |
| 80 | List of sources associated with knowledge graph |
| 81 | |
| 82 | Returns: |
| 83 | list[AbstractSource]: sources |
| 84 | """ |
| 85 | |
| 86 | return [s.source for s in self.sources] |
| 87 | |
| 88 | def process_sources( |
| 89 | self, sources: list[AbstractSource], instructions: str = None |
| 90 | ) -> None: |
| 91 | """ |
| 92 | Add entities and relations found in sources into the knowledge-graph |
| 93 | |
| 94 | Parameters: |
| 95 | sources (list[AbstractSource]): list of sources to extract knowledge from |
| 96 | """ |
| 97 | |
| 98 | if self.ontology is None: |
| 99 | raise Exception("Ontology is not defined") |
| 100 | |
| 101 | # Create graph with sources |
| 102 | self._create_graph_with_sources(sources, instructions) |
| 103 | |
| 104 | # Add processed sources |
| 105 | for src in sources: |
| 106 | self.sources.add(src) |
| 107 | |
| 108 | def _create_graph_with_sources( |
| 109 | self, sources: list[AbstractSource] | None = None, instructions: str = None |
| 110 | ): |
| 111 | |
| 112 | step = ExtractDataStep( |
| 113 | sources=list(sources), |
| 114 | ontology=self.ontology, |
| 115 | model=self._model_config.extract_data, |
| 116 | graph=self.graph, |
| 117 | ) |
| 118 | |
| 119 | step.run(instructions) |
| 120 | |
| 121 | def ask( |
| 122 | self, question: str, qa_chat_session: GenerativeModelChatSession | None = None |
| 123 | ) -> tuple[str, GenerativeModelChatSession]: |
| 124 | """ |
| 125 | Query the knowledge graph using natural language. |
| 126 | Optionally, you can provide a qa_chat_session to use for the query. |
| 127 | |
| 128 | Parameters: |
| 129 | question (str): question to ask the knowledge graph |
| 130 | qa_chat_session (GenerativeModelChatSession|None): qa_chat_session to use for the query |
| 131 | |
| 132 | Returns: |
| 133 | tuple[str, GenerativeModelChatSession]: answer, qa_chat_session |
| 134 | |
| 135 | Example: |
| 136 | >>> (ans, qa_chat_session) = kg.ask("List a few movies in which that actor played in") |
| 137 | >>> print(ans) |
| 138 | """ |
| 139 | |
| 140 | cypher_chat_session = ( |
| 141 | self._model_config.cypher_generation.with_system_instruction( |
| 142 | CYPHER_GEN_SYSTEM.replace("#ONTOLOGY", str(self.ontology.to_json())), |
| 143 | ).start_chat() |
| 144 | ) |
| 145 | cypher_step = GraphQueryGenerationStep( |
| 146 | ontology=self.ontology, |
| 147 | chat_session=cypher_chat_session, |
| 148 | graph=self.graph, |
| 149 | ) |
| 150 | |
| 151 | (context, cypher) = cypher_step.run(question) |
| 152 | |
| 153 | if not cypher or len(cypher) == 0: |
| 154 | return "I am sorry, I could not find the answer to your question" |
| 155 | |
| 156 | qa_chat_session = ( |
| 157 | qa_chat_session |
| 158 | or self._model_config.qa.with_system_instruction( |
| 159 | GRAPH_QA_SYSTEM |
| 160 | ).start_chat() |
| 161 | ) |
| 162 | qa_step = QAStep( |
| 163 | chat_session=qa_chat_session, |
| 164 | ) |
| 165 | |
| 166 | answer = qa_step.run(question, cypher, context) |
| 167 | |
| 168 | return (answer, qa_chat_session) |
| 169 | |
| 170 | def delete(self) -> None: |
| 171 | """ |
| 172 | Deletes the knowledge graph and any other related resource |
| 173 | e.g. Ontology, data graphs |
| 174 | """ |
| 175 | # List available graphs |
| 176 | available_graphs = self.db.list_graphs() |
| 177 | |
| 178 | # Delete KnowledgeGraph |
| 179 | if self.name in available_graphs: |
| 180 | self.graph.delete() |
| 181 | |
| 182 | # Nullify all attributes |
| 183 | for key in self.__dict__.keys(): |
| 184 | setattr(self, key, None) |
| 185 | |
| 186 | def chat_session(self) -> ChatSession: |
| 187 | return ChatSession(self._model_config, self.ontology, self.graph) |
| 188 | |
| 189 | def add_node(self, entity: str, attributes: dict): |
| 190 | """ |
| 191 | Add a node to the knowledge graph, checking if it matches the ontology |
| 192 | |
| 193 | Parameters: |
| 194 | label (str): label of the node |
| 195 | attributes (dict): node attributes |
| 196 | """ |
| 197 | |
| 198 | self._validate_entity(entity, attributes) |
| 199 | |
| 200 | # Add node to graph |
| 201 | self.graph.query( |
| 202 | f"MERGE (n:{entity} {map_dict_to_cypher_properties(attributes)})" |
| 203 | ) |
| 204 | |
| 205 | def add_edge( |
| 206 | self, |
| 207 | relation: str, |
| 208 | source: str, |
| 209 | target: str, |
| 210 | source_attr: dict = None, |
| 211 | target_attr: dict = None, |
| 212 | attributes: dict = None, |
| 213 | ): |
| 214 | """ |
| 215 | Add an edge to the knowledge graph, checking if it matches the ontology |
| 216 | |
| 217 | Parameters: |
| 218 | relation (str): relation label |
| 219 | source (str): source entity label |
| 220 | target (str): target entity label |
| 221 | source_attr (dict): source entity attributes |
| 222 | target_attr (dict): target entity attributes |
| 223 | attributes (dict): relation attributes |
| 224 | """ |
| 225 | |
| 226 | source_attr = source_attr or {} |
| 227 | target_attr = target_attr or {} |
| 228 | attributes = attributes or {} |
| 229 | |
| 230 | self._validate_relation( |
| 231 | relation, source, target, source_attr, target_attr, attributes |
| 232 | ) |
| 233 | |
| 234 | # Add relation to graph |
| 235 | self.graph.query( |
| 236 | f"MATCH (s:{source} {map_dict_to_cypher_properties(source_attr)}) MATCH (t:{target} {map_dict_to_cypher_properties(target_attr)}) MERGE (s)-[r:{relation} {map_dict_to_cypher_properties(attributes)}]->(t)" |
| 237 | ) |
| 238 | |
| 239 | def _validate_entity(self, entity: str, attributes: str): |
| 240 | ontology_entity = self.ontology.get_entity_with_label(entity) |
| 241 | |
| 242 | if ontology_entity is None: |
| 243 | raise Exception(f"Entity {entity} not found in ontology") |
| 244 | |
| 245 | self._validate_attributes_dict(attributes, ontology_entity.attributes) |
| 246 | |
| 247 | def _validate_relation( |
| 248 | self, |
| 249 | relation: str, |
| 250 | source: str, |
| 251 | target: str, |
| 252 | source_attr: dict, |
| 253 | target_attr: dict, |
| 254 | attributes: dict, |
| 255 | ): |
| 256 | ontology_relations = self.ontology.get_relations_with_label(relation) |
| 257 | |
| 258 | found_relation = [ |
| 259 | relation |
| 260 | for relation in ontology_relations |
| 261 | if relation.source.label == source and relation.target.label == target |
| 262 | ] |
| 263 | if len(ontology_relations) == 0 or len(found_relation) == 0: |
| 264 | raise Exception(f"Relation {relation} not found in ontology") |
| 265 | |
| 266 | self._validate_attributes_dict(attributes, found_relation[0].attributes) |
| 267 | |
| 268 | self._validate_entity(source, source_attr) |
| 269 | self._validate_entity(target, target_attr) |
| 270 | |
| 271 | def _validate_attributes_dict( |
| 272 | self, attr_dict: dict, attributes_list: list[Attribute] |
| 273 | ): |
| 274 | # validate attributes |
| 275 | for attr in attributes_list: |
| 276 | if attr.name not in attr_dict: |
| 277 | if attr.required or attr.unique: |
| 278 | raise Exception(f"Attribute {attr.name} is required") |
| 279 | |
| 280 | for attr in attr_dict.keys(): |
| 281 | valid_attr = [a for a in attributes_list if a.name == attr] |
| 282 | if len(valid_attr) == 0: |
| 283 | raise Exception(f"Invalid attribute {attr}") |
| 284 | valid_attr = valid_attr[0] |
| 285 | |
| 286 | if valid_attr.type == AttributeType.STRING: |
| 287 | if not isinstance(attr_dict[attr], str): |
| 288 | raise Exception(f"Attribute {attr} should be a string") |
| 289 | elif valid_attr.type == AttributeType.NUMBER: |
| 290 | if not isinstance(attr_dict[attr], int) and not isinstance( |
| 291 | attr_dict[attr], float |
| 292 | ): |
| 293 | raise Exception(f"Attribute {attr} should be an number") |
| 294 | elif valid_attr.type == AttributeType.BOOLEAN: |
| 295 | if not isinstance(attr_dict[attr], bool): |
| 296 | raise Exception(f"Attribute {attr} should be a boolean") |