| 1 | import queue |
| 2 | from openai import OpenAI |
| 3 | import concurrent.futures |
| 4 | from typing_extensions import AbstractSet |
| 5 | |
| 6 | from .prompts import * |
| 7 | from .template import TEMPLATE |
| 8 | from openai import OpenAI |
| 9 | from falkordb import FalkorDB |
| 10 | from .query_graph import query |
| 11 | from .schema.schema import Schema |
| 12 | from .source import Source, AbstractSource |
| 13 | from .schema.tools_gen import schema_to_tools |
| 14 | from .schema.functions_gen import schema_to_functions |
| 15 | |
| 16 | import logging |
| 17 | logger = logging.getLogger(__name__) |
| 18 | |
| 19 | class KnowledgeGraph(object): |
| 20 | """Knowledge Graph model data as a network of entities and relations |
| 21 | To create one it is best to provide a schema 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__(self, name:str, host:str="127.0.0.1", port:int=6379, username:str|None=None, password:str|None=None, |
| 26 | model:str="gpt-4-1106-preview", schema:Schema|None=None): |
| 27 | """ |
| 28 | Initialize Knowledge Graph |
| 29 | |
| 30 | Parameters: |
| 31 | name (str): Knowledge graph name. |
| 32 | host (str): FalkorDB hostname. |
| 33 | port (int): FalkorDB port number. |
| 34 | username (str|None): FalkorDB username. |
| 35 | password (str|None): FalkorDB password. |
| 36 | model (str): OpenAI model to use. |
| 37 | """ |
| 38 | |
| 39 | if not isinstance(name, str) or name == "": |
| 40 | raise Exception("name should be a non empty string") |
| 41 | |
| 42 | # connect to database |
| 43 | self.db = FalkorDB(host=host, port=port, username=username, password=password) |
| 44 | self.graph = self.db.select_graph(name) |
| 45 | |
| 46 | self.model = model |
| 47 | self._name = name |
| 48 | self._schema = schema |
| 49 | self.client = None # OpenAI client |
| 50 | self.sources = set([]) |
| 51 | self.ontolegy_ratio = 0.1 # Sampaling ratio for ontolegy detection |
| 52 | |
| 53 | # in case schema is None |
| 54 | # try to load schema from FalkorDB |
| 55 | if schema is None: |
| 56 | schema_name = self._schema_name() |
| 57 | if schema_name in self.db.list_graphs(): |
| 58 | schema_graph = self.db.select_graph(schema_name) |
| 59 | self._schema = Schema.from_graph(schema_graph) |
| 60 | |
| 61 | logger.info(f"Schema detected") |
| 62 | logger.debug(f"Schema: {self.schema.to_JSON()}") |
| 63 | |
| 64 | # Attributes |
| 65 | |
| 66 | @property |
| 67 | def name(self): |
| 68 | return self._name |
| 69 | |
| 70 | @name.setter |
| 71 | def name(self, value): |
| 72 | raise AttributeError("Cannot modify the 'name' attribute") |
| 73 | |
| 74 | @property |
| 75 | def schema(self): |
| 76 | return self._schema |
| 77 | |
| 78 | @schema.setter |
| 79 | def schame(self, value): |
| 80 | raise AttributeError("Cannot modify the 'schema' attribute") |
| 81 | |
| 82 | def list_sources(self) -> list[AbstractSource]: |
| 83 | """ |
| 84 | List of sources associated with knowledge graph |
| 85 | |
| 86 | Returns: |
| 87 | list[AbstractSource]: sources |
| 88 | """ |
| 89 | |
| 90 | return [s.source for s in self.sources] |
| 91 | |
| 92 | def process_sources(self, sources: list[AbstractSource]) -> None: |
| 93 | """ |
| 94 | Add entities and relations found in sources into the knowledge-graph |
| 95 | |
| 96 | Parameters: |
| 97 | sources (list[AbstractSource]): list of sources to extract knowledge from |
| 98 | """ |
| 99 | |
| 100 | # Make sure knowledge graph is created. |
| 101 | if not 'build_graph_from_sources' in globals() or self.client is None: |
| 102 | self._create() |
| 103 | |
| 104 | # Run assistant |
| 105 | result = build_graph_from_sources(self, self.client, sources) |
| 106 | |
| 107 | # Add processed sources |
| 108 | for src in sources: |
| 109 | self.sources.add(src) |
| 110 | |
| 111 | def _schema_name(self) -> str: |
| 112 | """ |
| 113 | Generate a name for the schema based on the Knowledge Graph name |
| 114 | """ |
| 115 | |
| 116 | return f"{self.name}_schema" |
| 117 | |
| 118 | def _createKGWithSchema(self): |
| 119 | # Save schema as an ontology graph |
| 120 | schema_graph = self.db.select_graph(self._schema_name()) |
| 121 | self.schema.save_graph(schema_graph) |
| 122 | |
| 123 | # Create Knowledge Graph construction assistant |
| 124 | |
| 125 | # Generate assistant's toolings |
| 126 | tools = schema_to_tools(self.schema) |
| 127 | |
| 128 | # Generate functions from schema |
| 129 | funcs = schema_to_functions(self.schema) |
| 130 | functions_names = [func[0] for func in funcs] |
| 131 | functions_impl = [func[1] for func in funcs] |
| 132 | |
| 133 | # Generate assistant |
| 134 | # Generate code from template |
| 135 | code = TEMPLATE |
| 136 | code = code.replace("<TOOLS>", ",\n".join([str(tool) for tool in tools])) |
| 137 | code = code.replace("<GRAPH_ID>", "\"" + self.name + "\"") |
| 138 | code = code.replace("<FUNCTIONS>", "\n".join(functions_impl)) |
| 139 | code = code.replace("<AVAILABLE_FUNCTIONS>", '{' + ",\n".join([f"'{f}': {f}" for f in functions_names]) +'}') |
| 140 | |
| 141 | # Execute the code string in the global namespace |
| 142 | # Introduces the 'build_graph_from_sources' function |
| 143 | # TODO: note multiple calls to _createKGWithSchema will overide one another. |
| 144 | exec(code, globals()) |
| 145 | |
| 146 | def _create(self) -> None: |
| 147 | """ |
| 148 | Create knowledge graph |
| 149 | Extract entities and relations from sources |
| 150 | """ |
| 151 | |
| 152 | if self.schema is None: |
| 153 | raise Exception("Can not create knowledge graph, schema missing") |
| 154 | |
| 155 | # Create OpenAI client |
| 156 | if self.client is None: |
| 157 | self.client = OpenAI() |
| 158 | |
| 159 | self._createKGWithSchema() |
| 160 | |
| 161 | def ask(self, question:str, history:list|None=None) -> tuple[str, list]: |
| 162 | """ |
| 163 | Query the knowledge graph using natural language |
| 164 | if the query is asked as part of a longer conversation make sure to |
| 165 | include past history. |
| 166 | |
| 167 | Returns: |
| 168 | tuple[str, list]: answer, conversation history |
| 169 | |
| 170 | Example: |
| 171 | >>> ans, history = kg.ask("Which actor has the most oscars") |
| 172 | >>> ans, history = kg.ask("List a few movies in which that actored played in", history) |
| 173 | """ |
| 174 | |
| 175 | if history is None: |
| 176 | history = [] |
| 177 | |
| 178 | answer = query(self, question, history, self.model) |
| 179 | return (answer, history) |
| 180 | |
| 181 | def delete(self) -> None: |
| 182 | """ |
| 183 | Deletes the knowledge graph and any other related resource |
| 184 | e.g. Schema, OpenAI assistant |
| 185 | """ |
| 186 | |
| 187 | # Delete OpenAI KnowledgeGraph creation assistant |
| 188 | client = OpenAI() |
| 189 | assistant_ids = [] |
| 190 | for assistant in client.beta.assistants.list(): |
| 191 | if assistant.name == self.name: |
| 192 | # Do not break, there might be multiple assistants with the same name. |
| 193 | assistant_ids.append(assistant.id) |
| 194 | |
| 195 | for assistant_id in assistant_ids: |
| 196 | # Delete assistant |
| 197 | client.beta.assistants.delete(assistant_id) |
| 198 | |
| 199 | # List available graphs |
| 200 | available_graphs = self.db.list_graphs() |
| 201 | |
| 202 | # Delete KnowledgeGraph |
| 203 | if self.name in available_graphs: |
| 204 | self.graph.delete() |
| 205 | |
| 206 | # Delete schema graph |
| 207 | if self._schema_name() in available_graphs: |
| 208 | schema_graph = self.db.select_graph(self._schema_name()) |
| 209 | schema_graph.delete() |
| 210 | |
| 211 | # Nullify all attributes |
| 212 | for key in self.__dict__.keys(): |
| 213 | setattr(self, key, None) |