kikocis/GraphRAG-SDK public
Changesets · Branches · Tags · Compare
| Changeset | 3034d86cfbbe9200f55f9be9fc3040b33603815ff0da47df66eadc5a8900ec0e |
|---|---|
| Author | Roi Lipman <roilipman@gmail.com> · 2024-06-08 00:04 +03:00 |
| Committer | Roi Lipman <roilipman@gmail.com> · 2024-06-08 00:04 +03:00 |
| Parents | b6ff0beb7359 |
17 files changed
added examples/github.py +105 −0
| @@ -0,0 +1,105 @@ | ||
| 1 | +from graphrag_sdk.schema import Schema | |
| 2 | +from graphrag_sdk import KnowledgeGraph, Source | |
| 3 | + | |
| 4 | +import logging | |
| 5 | +logger = logging.getLogger("graphrag_sdk") | |
| 6 | + | |
| 7 | +# Configure the root logger | |
| 8 | +handler = logging.StreamHandler() | |
| 9 | +handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')) | |
| 10 | +logger.addHandler(handler) | |
| 11 | +logger.setLevel(logging.INFO) | |
| 12 | + | |
| 13 | +def main(): | |
| 14 | + # Manually define schema | |
| 15 | + s = Schema() | |
| 16 | + | |
| 17 | + # Entities: | |
| 18 | + # 1. File | |
| 19 | + # 2. Directory | |
| 20 | + # 3. Commit | |
| 21 | + # 4. Branch | |
| 22 | + # 5. Repository | |
| 23 | + # 6. Organization | |
| 24 | + # 7. User | |
| 25 | + | |
| 26 | + file = s.add_entity('File') | |
| 27 | + file.add_attribute('Name', str, unique=True, mandatory=True) | |
| 28 | + file.add_attribute('Extension', str, unique=True, mandatory=True) | |
| 29 | + | |
| 30 | + dir = s.add_entity('Directory') | |
| 31 | + dir.add_attribute('Name', str, unique=True, mandatory=True) | |
| 32 | + | |
| 33 | + commit = s.add_entity('Commit') | |
| 34 | + commit.add_attribute('Message', str) | |
| 35 | + commit.add_attribute('Date', int, desc="Commit date as UNIX timestamp") | |
| 36 | + commit.add_attribute('Hash', str, unique=True, mandatory=True) | |
| 37 | + | |
| 38 | + branch = s.add_entity('Branch') | |
| 39 | + branch.add_attribute('Name', str, unique=True, mandatory=True) | |
| 40 | + | |
| 41 | + repo = s.add_entity('Repository') | |
| 42 | + repo.add_attribute('Name', str, unique=True, mandatory=True) | |
| 43 | + repo.add_attribute('Description', str) | |
| 44 | + repo.add_attribute('Issues', int, desc="Number of issues") | |
| 45 | + | |
| 46 | + organization = s.add_entity('Organization') | |
| 47 | + organization.add_attribute('Name', str, unique=True, mandatory=True) | |
| 48 | + | |
| 49 | + user = s.add_entity('User') | |
| 50 | + user.add_attribute('Name', str, unique=True, mandatory=True) | |
| 51 | + user.add_attribute('Location', str, desc="Where the user is from") | |
| 52 | + | |
| 53 | + # Relations: | |
| 54 | + # 1. (Repository)-[CONTAINS]->(File) | |
| 55 | + # 2. (Repository)-[CONTAINS]->(Directory) | |
| 56 | + # 3. (Repository)-[CONTAINS]->(Commit) | |
| 57 | + # 4. (Repository)-[CONTAINS]->(bracnh) | |
| 58 | + # 5. (Directory)-[CONTAINS]->(File) | |
| 59 | + # 6. (Organization)-[OWNS]->(Repository) | |
| 60 | + # 7. (Commit)-[MODIFIES]->(File) | |
| 61 | + # 8. (User)-[STAR]->(Repository) | |
| 62 | + # 0. (User)-[PART_OF]->(Organization) | |
| 63 | + | |
| 64 | + s.add_relation("CONTAINS", repo, file) | |
| 65 | + s.add_relation("CONTAINS", repo, dir) | |
| 66 | + s.add_relation("CONTAINS", repo, commit) | |
| 67 | + s.add_relation("CONTAINS", repo, branch) | |
| 68 | + s.add_relation("CONTAINS", dir, file) | |
| 69 | + s.add_relation("OWNS", organization, repo) | |
| 70 | + s.add_relation("MODIFIES", commit, file) | |
| 71 | + s.add_relation("STAR", user, repo) | |
| 72 | + s.add_relation("PART_OF", user, organization) | |
| 73 | + | |
| 74 | + # Print schema | |
| 75 | + # print(s.to_JSON()) | |
| 76 | + | |
| 77 | + # Create Knowledge Graph | |
| 78 | + g = KnowledgeGraph("Github", schema=s, model="gpt-3.5-turbo-0125") | |
| 79 | + | |
| 80 | + # Ingest | |
| 81 | + # Define sources from which knowledge will be extracted | |
| 82 | + sources = [ | |
| 83 | + Source("https://github.com/FalkorDB/FalkorDB", | |
| 84 | + instruction="Extract organization, repository, users, files and directories. make sure to form connections"), | |
| 85 | + Source("https://github.com/FalkorDB/FalkorDB/stargazers", | |
| 86 | + instruction="Extract users who've stared this repo, make sure to create each user and connect it via an edge to the repo node."), | |
| 87 | + Source("https://github.com/FalkorDB/FalkorDB/branches", instruction="Extract branches and connect them to the repository")] | |
| 88 | + | |
| 89 | + g.process_sources(sources) | |
| 90 | + | |
| 91 | + # Query the repo | |
| 92 | + msgs = [] | |
| 93 | + questions = ["List a few Stargazers", | |
| 94 | + "How many Markdown files are there in the FalkorDB repository?", | |
| 95 | + "Which organization owns the FalkorDB repository?", | |
| 96 | + "Any of the Stargazers are also associated with the repo's organization?", | |
| 97 | + "Does the FalkorDB repository has a 'main' or a 'master' branch?"] | |
| 98 | + | |
| 99 | + for q in questions: | |
| 100 | + print(f"Question: {q}") | |
| 101 | + ans, msgs = g.ask(q, history=msgs) | |
| 102 | + print(f"Answer: {ans}") | |
| 103 | + | |
| 104 | +if __name__ == "__main__": | |
| 105 | + main() |
modified graphrag_sdk/__init__.py +5 −0
| @@ -1,2 +1,7 @@ | ||
| 1 | 1 | from .kg import KnowledgeGraph |
| 2 | 2 | from .source import Source |
| 3 | + | |
| 4 | +# Setup Null handler | |
| 5 | +import logging | |
| 6 | +logger = logging.getLogger(__name__) | |
| 7 | +logger.addHandler(logging.NullHandler()) |
modified graphrag_sdk/kg.py +75 −12
| @@ -1,5 +1,6 @@ | ||
| 1 | 1 | import os |
| 2 | 2 | import queue |
| 3 | +from openai import OpenAI | |
| 3 | 4 | import concurrent.futures |
| 4 | 5 | from typing_extensions import AbstractSet |
| 5 | 6 | |
| @@ -13,6 +14,13 @@ | ||
| 13 | 14 | from .schema.tools_gen import schema_to_tools |
| 14 | 15 | from .schema.functions_gen import schema_to_functions |
| 15 | 16 | |
| 17 | +import logging | |
| 18 | +logger = logging.getLogger(__name__) | |
| 19 | + | |
| 20 | +# Make sure OpenAI API key is set. | |
| 21 | +if "OPENAI_API_KEY" not in os.environ: | |
| 22 | + raise Exception("Missing 'OPENAI_API_KEY' environment variable, please make sure to set it: 'export OPENAI_API_KEY=<YOUR_OPENAI_API_KEY>'") | |
| 23 | + | |
| 16 | 24 | class KnowledgeGraph(object): |
| 17 | 25 | """Knowledge Graph model data as a network of entities and relations |
| 18 | 26 | To create one it is best to provide a schema which will define the graph's ontology |
| @@ -40,9 +48,9 @@ | ||
| 40 | 48 | self.db = FalkorDB(host=host, port=port, username=username, password=password) |
| 41 | 49 | self.graph = self.db.select_graph(name) |
| 42 | 50 | |
| 43 | - self.name = name | |
| 44 | 51 | self.model = model |
| 45 | - self.schema = schema | |
| 52 | + self._name = name | |
| 53 | + self._schema = schema | |
| 46 | 54 | self.client = None # OpenAI client |
| 47 | 55 | self.sources = set([]) |
| 48 | 56 | self.ontolegy_ratio = 0.1 # Sampaling ratio for ontolegy detection |
| @@ -52,8 +60,29 @@ | ||
| 52 | 60 | if schema is None: |
| 53 | 61 | schema_name = self._schema_name() |
| 54 | 62 | if schema_name in self.db.list_graphs(): |
| 55 | - schema_graph = self.db.select_graph() | |
| 56 | - self.schema = self.schema.from_graph(schema_graph) | |
| 63 | + schema_graph = self.db.select_graph(schema_name) | |
| 64 | + self._schema = Schema.from_graph(schema_graph) | |
| 65 | + | |
| 66 | + logger.info(f"Schema detected") | |
| 67 | + logger.debug(f"Schema: {self.schema.to_JSON()}") | |
| 68 | + | |
| 69 | + # Attributes | |
| 70 | + | |
| 71 | + @property | |
| 72 | + def name(self): | |
| 73 | + return self._name | |
| 74 | + | |
| 75 | + @name.setter | |
| 76 | + def name(self, value): | |
| 77 | + raise AttributeError("Cannot modify the 'name' attribute") | |
| 78 | + | |
| 79 | + @property | |
| 80 | + def schema(self): | |
| 81 | + return self._schema | |
| 82 | + | |
| 83 | + @schema.setter | |
| 84 | + def schame(self, value): | |
| 85 | + raise AttributeError("Cannot modify the 'schema' attribute") | |
| 57 | 86 | |
| 58 | 87 | def list_sources(self) -> list[AbstractSource]: |
| 59 | 88 | """ |
| @@ -119,20 +148,20 @@ | ||
| 119 | 148 | # TODO: note multiple calls to _createKGWithSchema will overide one another. |
| 120 | 149 | exec(code, globals()) |
| 121 | 150 | |
| 122 | - def _createKGWithoutSchema(self): | |
| 123 | - raise Exception("Can not create knowledge graph, schema missing") | |
| 124 | - | |
| 125 | 151 | def _create(self) -> None: |
| 126 | 152 | """ |
| 127 | 153 | Create knowledge graph |
| 128 | 154 | Extract entities and relations from sources |
| 129 | 155 | """ |
| 130 | - self.client = OpenAI() | |
| 131 | 156 | |
| 132 | - if self.schema is not None: | |
| 133 | - self._createKGWithSchema() | |
| 134 | - else: | |
| 135 | - self._createKGWithoutSchema() | |
| 157 | + if self.schema is None: | |
| 158 | + raise Exception("Can not create knowledge graph, schema missing") | |
| 159 | + | |
| 160 | + # Create OpenAI client | |
| 161 | + if self.client is None: | |
| 162 | + self.client = OpenAI() | |
| 163 | + | |
| 164 | + self._createKGWithSchema() | |
| 136 | 165 | |
| 137 | 166 | def ask(self, question:str, history:list|None=None) -> tuple[str, list]: |
| 138 | 167 | """ |
| @@ -153,3 +182,37 @@ | ||
| 153 | 182 | |
| 154 | 183 | answer = query(self, question, history, self.model) |
| 155 | 184 | return (answer, history) |
| 185 | + | |
| 186 | + def delete(self) -> None: | |
| 187 | + """ | |
| 188 | + Deletes the knowledge graph and any other related resource | |
| 189 | + e.g. Schema, OpenAI assistant | |
| 190 | + """ | |
| 191 | + | |
| 192 | + # Delete OpenAI KnowledgeGraph creation assistant | |
| 193 | + client = OpenAI() | |
| 194 | + assistant_ids = [] | |
| 195 | + for assistant in client.beta.assistants.list(): | |
| 196 | + if assistant.name == self.name: | |
| 197 | + # Do not break, there might be multiple assistants with the same name. | |
| 198 | + assistant_ids.append(assistant.id) | |
| 199 | + | |
| 200 | + for assistant_id in assistant_ids: | |
| 201 | + # Delete assistant | |
| 202 | + client.beta.assistants.delete(assistant_id) | |
| 203 | + | |
| 204 | + # List available graphs | |
| 205 | + available_graphs = self.db.list_graphs() | |
| 206 | + | |
| 207 | + # Delete KnowledgeGraph | |
| 208 | + if self.name in available_graphs: | |
| 209 | + self.graph.delete() | |
| 210 | + | |
| 211 | + # Delete schema graph | |
| 212 | + if self._schema_name() in available_graphs: | |
| 213 | + schema_graph = self.db.select_graph(self._schema_name()) | |
| 214 | + schema_graph.delete() | |
| 215 | + | |
| 216 | + # Nullify all attributes | |
| 217 | + for key in self.__dict__.keys(): | |
| 218 | + setattr(self, key, None) |
modified graphrag_sdk/query_graph.py +6 −6
| @@ -1,6 +1,9 @@ | ||
| 1 | 1 | import json |
| 2 | 2 | from openai import OpenAI |
| 3 | 3 | |
| 4 | +import logging | |
| 5 | +logger = logging.getLogger(__name__) | |
| 6 | + | |
| 4 | 7 | # Equipet assistant with tools: |
| 5 | 8 | tools = [ |
| 6 | 9 | { |
| @@ -37,12 +40,10 @@ | ||
| 37 | 40 | # list labels |
| 38 | 41 | desc = desc + "The graph contains the following node labels:\n"; |
| 39 | 42 | for e in s.entities: |
| 40 | - desc += e + "\n" | |
| 43 | + desc += e.name + "\n" | |
| 41 | 44 | |
| 42 | 45 | # specify attributes associated with each entity |
| 43 | 46 | for e in s.entities: |
| 44 | - e = s.entities[e] | |
| 45 | - | |
| 46 | 47 | lbl_name = e.name |
| 47 | 48 | attributes = e.attributes |
| 48 | 49 | attr_count = len(attributes) |
| @@ -64,8 +65,6 @@ | ||
| 64 | 65 | |
| 65 | 66 | # list relations |
| 66 | 67 | for rel in s.relations: |
| 67 | - rel = s.relations[rel] | |
| 68 | - | |
| 69 | 68 | src = rel.src.name |
| 70 | 69 | relationship_type = rel.name |
| 71 | 70 | dest = rel.dest.name |
| @@ -107,7 +106,8 @@ | ||
| 107 | 106 | function_to_call = available_functions[function_name] |
| 108 | 107 | function_args = json.loads(tool_call.function.arguments) |
| 109 | 108 | q = function_args.get("query") |
| 110 | - print(f"OpenAI suggested query: {q}") | |
| 109 | + logger.debug(f"Model suggested query: {q}") | |
| 110 | + | |
| 111 | 111 | function_response = function_to_call(g, q) |
| 112 | 112 | messages.append( |
| 113 | 113 | { |
modified graphrag_sdk/schema/__init__.py +5 −0
| @@ -1,1 +1,6 @@ | ||
| 1 | 1 | from .schema import Schema |
| 2 | + | |
| 3 | +# Setup Null handler | |
| 4 | +import logging | |
| 5 | +logger = logging.getLogger(__name__) | |
| 6 | +logger.addHandler(logging.NullHandler()) |
modified graphrag_sdk/schema/auto_detect.py +16 −21
| @@ -10,6 +10,9 @@ | ||
| 10 | 10 | from sqlalchemy.orm import sessionmaker |
| 11 | 11 | from sqlalchemy import create_engine, inspect, MetaData, Table, types |
| 12 | 12 | |
| 13 | +import logging | |
| 14 | +logger = logging.getLogger(__name__) | |
| 15 | + | |
| 13 | 16 | # Convert from SQLAlchemy type to Python type |
| 14 | 17 | def sqlalchemy_to_python_type(sqlalchemy_type): |
| 15 | 18 | if isinstance(sqlalchemy_type, types.Integer): |
| @@ -143,7 +146,7 @@ | ||
| 143 | 146 | pass |
| 144 | 147 | create_relation(s, tbl, foreign_keys) |
| 145 | 148 | else: |
| 146 | - print("can't process table with more then 2 forigen keys") | |
| 149 | + logger.error("can't process table with more then 2 forigen keys") | |
| 147 | 150 | |
| 148 | 151 | def convert_tables(s, client, model, inspector, table_names): |
| 149 | 152 | # Start by converting tabels without foreign keys |
| @@ -212,7 +215,7 @@ | ||
| 212 | 215 | # queue sql statment |
| 213 | 216 | def run_sql(arg, queue): |
| 214 | 217 | sql = arg["sql"] |
| 215 | - print(f"SQL: {sql}") | |
| 218 | + logger.debug(f"SQL: {sql}") | |
| 216 | 219 | |
| 217 | 220 | queue.put(sql) |
| 218 | 221 | |
| @@ -224,13 +227,9 @@ | ||
| 224 | 227 | # Get OpenAI ontology detection assistant |
| 225 | 228 | def get_assistant(client, assistant_name, model): |
| 226 | 229 | # Try reusing existing assistant |
| 227 | - if os.path.exists("./ONTOLOGY_ASSISTANT_ID"): | |
| 228 | - with open("./ONTOLOGY_ASSISTANT_ID", 'r') as f: | |
| 229 | - ASSISTANT_ID = f.read() | |
| 230 | - try: | |
| 231 | - return client.beta.assistants.retrieve(ASSISTANT_ID) | |
| 232 | - except: | |
| 233 | - pass | |
| 230 | + for assistant in client.beta.assistants.list(): | |
| 231 | + if assistant.name == assistant_name: | |
| 232 | + return client.beta.assistants.retrieve(assistant.id) | |
| 234 | 233 | |
| 235 | 234 | # Create OpenAI assistant |
| 236 | 235 | assistant = client.beta.assistants.create( |
| @@ -253,10 +252,6 @@ | ||
| 253 | 252 | }] |
| 254 | 253 | ) |
| 255 | 254 | |
| 256 | - # Save assistant ID to local file | |
| 257 | - with open("./ONTOLOGY_ASSISTANT_ID", 'w') as f: | |
| 258 | - f.write(assistant.id) | |
| 259 | - | |
| 260 | 255 | return assistant |
| 261 | 256 | |
| 262 | 257 | # Start an interaction with OpenAI assistant |
| @@ -274,15 +269,15 @@ | ||
| 274 | 269 | run = client.beta.threads.runs.retrieve(thread_id=run.thread_id, run_id=run.id) |
| 275 | 270 | |
| 276 | 271 | if run.status == "completed": |
| 277 | - print("Done processing document") | |
| 272 | + logger.debug("Done processing document") | |
| 278 | 273 | return |
| 279 | 274 | |
| 280 | 275 | if run.status == "expired": |
| 281 | - print(f"Processing expired") | |
| 276 | + logger.debug(f"Processing expired") | |
| 282 | 277 | return |
| 283 | 278 | |
| 284 | 279 | if run.status == "cancelling" or run.status == "cancelled" or run.status == "failed": |
| 285 | - print(f"Processing failed") | |
| 280 | + logger.debug(f"Processing failed") | |
| 286 | 281 | return |
| 287 | 282 | |
| 288 | 283 | # wait for run to complete |
| @@ -309,7 +304,7 @@ | ||
| 309 | 304 | f = available_functions[func_name] |
| 310 | 305 | f(args, queue) |
| 311 | 306 | except: |
| 312 | - print(f"tool_call: {tool_call}") | |
| 307 | + logger.debug(f"tool_call: {tool_call}") | |
| 313 | 308 | pass |
| 314 | 309 | |
| 315 | 310 | last_step_id = run_steps.last_id |
| @@ -384,14 +379,14 @@ | ||
| 384 | 379 | tables = {} |
| 385 | 380 | for i in range(n): |
| 386 | 381 | stmt = q.get() |
| 387 | - print(f"sql: {stmt}") | |
| 382 | + logger.debug(f"sql: {stmt}") | |
| 388 | 383 | |
| 389 | 384 | # group by table name |
| 390 | 385 | # CREATE TABLE MoviePersonnel ( |
| 391 | 386 | s = stmt.index("CREATE TABLE ") + len("CREATE TABLE ") |
| 392 | 387 | e = stmt.index("(") - 1 |
| 393 | 388 | tbl = stmt[s:e] |
| 394 | - print(f"tbl: {tbl}") | |
| 389 | + logger.debug(f"tbl: {tbl}") | |
| 395 | 390 | |
| 396 | 391 | if tbl not in tables: |
| 397 | 392 | tables[tbl] = [] |
| @@ -414,7 +409,7 @@ | ||
| 414 | 409 | ) |
| 415 | 410 | |
| 416 | 411 | merged_stmt = response.choices[0].message.content |
| 417 | - print(f"merged_stmt: {merged_stmt}") | |
| 412 | + logger.debug(f"merged_stmt: {merged_stmt}") | |
| 418 | 413 | tables[k].append(merged_stmt) |
| 419 | 414 | |
| 420 | 415 | # Switch back from dict to array |
| @@ -425,7 +420,7 @@ | ||
| 425 | 420 | cur = con.cursor() |
| 426 | 421 | |
| 427 | 422 | for stmt in tables: |
| 428 | - print(f"Executing: {stmt}") | |
| 423 | + logger.debug(f"Executing: {stmt}") | |
| 429 | 424 | cur.execute(stmt) |
| 430 | 425 | con.commit() |
| 431 | 426 |
modified graphrag_sdk/schema/encoder.py +2 −4
| @@ -1,10 +1,10 @@ | ||
| 1 | -from json import JSONEncoder | |
| 1 | +import json | |
| 2 | 2 | |
| 3 | 3 | # Encode Schema into JSON |
| 4 | 4 | class SchemaEncoder(): |
| 5 | 5 | # encode schema to JSON string |
| 6 | 6 | def to_JSON(self, schema) -> str: |
| 7 | - return JSONEncoder().encode(self.encode(schema)) | |
| 7 | + return json.dumps(self.encode(schema), indent=4) | |
| 8 | 8 | |
| 9 | 9 | # encode schema as dict |
| 10 | 10 | def encode(self, schema) -> dict: |
| @@ -14,11 +14,9 @@ | ||
| 14 | 14 | dict = {'entities': [], 'relations': []} |
| 15 | 15 | |
| 16 | 16 | for e in schema.entities: |
| 17 | - e = schema.entities[e] | |
| 18 | 17 | dict['entities'].append(self._encode_entity(e)) |
| 19 | 18 | |
| 20 | 19 | for r in schema.relations: |
| 21 | - r = schema.relations[r] | |
| 22 | 20 | dict['relations'].append(self._encode_relation(r)) |
| 23 | 21 | |
| 24 | 22 | return dict |
modified graphrag_sdk/schema/entity.py +19 −3
| @@ -47,7 +47,13 @@ | ||
| 47 | 47 | |
| 48 | 48 | return (self.name == other.name and self.attributes == other.attributes) |
| 49 | 49 | |
| 50 | - def add_attribute(self, name:str, type:type, desc:str|None=None, unique:bool=False, mandatory:bool=False) -> None: | |
| 50 | + def __hash__(self): | |
| 51 | + return hash(self.name) | |
| 52 | + | |
| 53 | + def __str__(self): | |
| 54 | + return f"(:{self.name})" | |
| 55 | + | |
| 56 | + def add_attribute(self, name:str, type:type, desc:str|None=None, unique:bool=False, mandatory:bool=False) -> 'Entity': | |
| 51 | 57 | """ |
| 52 | 58 | Add attribute to entity |
| 53 | 59 | |
| @@ -57,6 +63,9 @@ | ||
| 57 | 63 | desc (str): short description for attribute |
| 58 | 64 | unique (bool): is the attribute value unique |
| 59 | 65 | mandatory (bool): is the attribute mandatory |
| 66 | + | |
| 67 | + Returns: | |
| 68 | + Entity | |
| 60 | 69 | """ |
| 61 | 70 | |
| 62 | 71 | # Validate arguments |
| @@ -75,12 +84,17 @@ | ||
| 75 | 84 | desc = f"{self.name}'s {name}" if desc is None else desc |
| 76 | 85 | self.attributes.add(Attribute(name, type, desc, unique, mandatory)) |
| 77 | 86 | |
| 78 | - def remove_attribute(self, name:str) ->None: | |
| 87 | + return self | |
| 88 | + | |
| 89 | + def remove_attribute(self, name:str) -> 'Entity': | |
| 79 | 90 | """ |
| 80 | 91 | Remove attribute from entity |
| 81 | 92 | |
| 82 | 93 | Parameters: |
| 83 | 94 | name (str): name of attribute to remove |
| 95 | + | |
| 96 | + Returns: | |
| 97 | + Entity | |
| 84 | 98 | """ |
| 85 | 99 | |
| 86 | 100 | # Validate argument |
| @@ -90,7 +104,9 @@ | ||
| 90 | 104 | for attr in self.attributes: |
| 91 | 105 | if attr.name == name: |
| 92 | 106 | self.attributes.remove(attr) |
| 93 | - return | |
| 107 | + break | |
| 108 | + | |
| 109 | + return self | |
| 94 | 110 | |
| 95 | 111 | def get_attribute(self, name:str) -> Attribute|None: |
| 96 | 112 | """ |
modified graphrag_sdk/schema/functions_gen.py +11 −10
| @@ -5,33 +5,34 @@ | ||
| 5 | 5 | def relation_to_create_func(r:Relation): |
| 6 | 6 | src_lbl = r.src.name |
| 7 | 7 | dest_lbl = r.dest.name |
| 8 | - func_name = r.name | |
| 8 | + #func_name = r.name | |
| 9 | + func_name = f"{src_lbl}_{r.name}_{dest_lbl}" | |
| 9 | 10 | |
| 10 | - func = f"def {r.name}(args):\n" # def MovieStream(args): | |
| 11 | + func = f"def {func_name}(args):\n" # def MovieStream(args): | |
| 11 | 12 | func += "\targs = remove_none_values(args)\n" # args = remove_none_values(args) |
| 12 | 13 | |
| 13 | 14 | # extract required src arguments |
| 14 | 15 | src_attrs = r.src.unique_attributes() |
| 15 | 16 | |
| 16 | - # extract required dest arguments | |
| 17 | + # extract required src arguments | |
| 17 | 18 | func += "\tq = \"MERGE (s:" + src_lbl + " {" |
| 18 | - func += ", ".join([f"{attr.name}: " + f"${attr.name}" for attr in src_attrs]) | |
| 19 | + func += ", ".join([f"{attr.name}: " + f"${src_lbl}_{attr.name}" for attr in src_attrs]) | |
| 19 | 20 | func += "}) " |
| 20 | 21 | |
| 21 | - # extract required src arguments | |
| 22 | + # extract required dest arguments | |
| 22 | 23 | dest_attrs = r.dest.unique_attributes() |
| 23 | 24 | |
| 24 | 25 | func += "MERGE (d:" + dest_lbl + " {" |
| 25 | - func += ", ".join([f"{attr.name}: " + f"${attr.name}" for attr in dest_attrs]) | |
| 26 | + func += ", ".join([f"{attr.name}: " + f"${dest_lbl}_{attr.name}" for attr in dest_attrs]) | |
| 26 | 27 | func += "}) " |
| 27 | 28 | |
| 28 | 29 | func += "MERGE (s)-[r:" + r.name + "]->(d)\"\n" |
| 29 | 30 | |
| 30 | 31 | # construct query params |
| 31 | 32 | func += "\tparams = {" |
| 32 | - func += ", ".join([f"'{attr.name}': args['{attr.name}']" for attr in src_attrs]) | |
| 33 | + func += ", ".join([f"'{src_lbl}_{attr.name}': args['{src_lbl}_{attr.name}']" for attr in src_attrs]) | |
| 33 | 34 | func += ", " |
| 34 | - func += ", ".join([f"'{attr.name}': args['{attr.name}']" for attr in dest_attrs]) | |
| 35 | + func += ", ".join([f"'{dest_lbl}_{attr.name}': args['{dest_lbl}_{attr.name}']" for attr in dest_attrs]) | |
| 35 | 36 | func += "}\n" |
| 36 | 37 | |
| 37 | 38 | func += "\tg.query(q, params)\n" |
| @@ -64,11 +65,11 @@ | ||
| 64 | 65 | |
| 65 | 66 | functions = [] |
| 66 | 67 | for e in s.entities: |
| 67 | - func = entity_to_create_func(s.entities[e]) | |
| 68 | + func = entity_to_create_func(e) | |
| 68 | 69 | functions.append(func) |
| 69 | 70 | |
| 70 | 71 | for r in s.relations: |
| 71 | - func = relation_to_create_func(s.relations[r]) | |
| 72 | + func = relation_to_create_func(r) | |
| 72 | 73 | functions.append(func) |
| 73 | 74 | |
| 74 | 75 | return functions |
modified graphrag_sdk/schema/relation.py +9 −0
| @@ -19,6 +19,9 @@ | ||
| 19 | 19 | self.dest = dest |
| 20 | 20 | self.name = name |
| 21 | 21 | |
| 22 | + def __str__(self) -> str: | |
| 23 | + return f"(:{self.src.name})-[:{self.name}]->(:{self.dest.name})" | |
| 24 | + | |
| 22 | 25 | def __eq__(self, other) -> bool: |
| 23 | 26 | if not isinstance(other, Relation): |
| 24 | 27 | return False |
| @@ -26,3 +29,9 @@ | ||
| 26 | 29 | return (self.src == other.src and |
| 27 | 30 | self.dest == other.dest and |
| 28 | 31 | self.name == other.name) |
| 32 | + | |
| 33 | + def __lt__(self, other): | |
| 34 | + return (self.src, self.name, self.dest) < (other.src, other.name, other.dest) | |
| 35 | + | |
| 36 | + def __hash__(self) -> int: | |
| 37 | + return hash((self.src, self.name, self.dest)) |
modified graphrag_sdk/schema/schema.py +13 −21
| @@ -20,8 +20,8 @@ | ||
| 20 | 20 | Initialize Schema |
| 21 | 21 | """ |
| 22 | 22 | |
| 23 | - self.entities = {} | |
| 24 | - self.relations = {} | |
| 23 | + self.entities = set([]) | |
| 24 | + self.relations = set([]) | |
| 25 | 25 | |
| 26 | 26 | def __eq__(self, other) -> bool: |
| 27 | 27 | if not isinstance(other, Schema): |
| @@ -54,7 +54,8 @@ | ||
| 54 | 54 | raise Exception(f"Entity {name} already exists") |
| 55 | 55 | |
| 56 | 56 | e = Entity(name) |
| 57 | - self.entities[name] = e | |
| 57 | + self.entities.add(e) | |
| 58 | + | |
| 58 | 59 | return e |
| 59 | 60 | |
| 60 | 61 | def get_entity(self, name:str) -> Entity | None: |
| @@ -68,10 +69,11 @@ | ||
| 68 | 69 | if not isinstance(name, str) or name == "": |
| 69 | 70 | raise Exception("Invalid argument, name should be a none empty string") |
| 70 | 71 | |
| 71 | - if name in self.entities: | |
| 72 | - return self.entities[name] | |
| 73 | - else: | |
| 74 | - return None | |
| 72 | + for e in self.entities: | |
| 73 | + if e.name == name: | |
| 74 | + return e | |
| 75 | + | |
| 76 | + return None | |
| 75 | 77 | |
| 76 | 78 | def add_relation(self, name:str, src:Entity, dest:Entity) -> Relation: |
| 77 | 79 | """ |
| @@ -97,12 +99,6 @@ | ||
| 97 | 99 | if name in self.relations: |
| 98 | 100 | raise Exception(f"Relation {name} already exists") |
| 99 | 101 | |
| 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 | 102 | # Both src and dest must have at least one unique attribute |
| 107 | 103 | if len(src.unique_attributes()) == 0: |
| 108 | 104 | raise Exception(f"{src.name} must have at least one unique attribute") |
| @@ -111,7 +107,7 @@ | ||
| 111 | 107 | |
| 112 | 108 | # Create relation and add it to schema |
| 113 | 109 | r = Relation(name, src, dest) |
| 114 | - self.relations[name] = r | |
| 110 | + self.relations.add(r) | |
| 115 | 111 | |
| 116 | 112 | return r |
| 117 | 113 | |
| @@ -126,19 +122,15 @@ | ||
| 126 | 122 | # Make sure each Relation reference existing Entities |
| 127 | 123 | # And each referenced entity has at least one unique attribute |
| 128 | 124 | for r in self.relations: |
| 129 | - r = self.relations[r] | |
| 130 | - src = r.src.name | |
| 131 | - dest = r.dest.name | |
| 125 | + src = r.src | |
| 126 | + dest = r.dest | |
| 127 | + | |
| 132 | 128 | if src not in self.entities: |
| 133 | 129 | raise Exception(f"Relation {r.name} reference a none existing entity {src}") |
| 134 | 130 | if dest not in self.entities: |
| 135 | 131 | raise Exception(f"Relation {r.name} reference a none existing entity {dest}") |
| 136 | - | |
| 137 | - src = self.entities[src] | |
| 138 | 132 | if len(src.unique_attributes()) == 0: |
| 139 | 133 | raise Exception(f"Relation {r.name} src endpoint {src.name} is missing a unique attribute") |
| 140 | - | |
| 141 | - dest = self.entities[dest] | |
| 142 | 134 | if len(dest.unique_attributes()) == 0: |
| 143 | 135 | raise Exception(f"Relation {r.name} src endpoint {dest.name} is missing a unique attribute") |
| 144 | 136 |
modified graphrag_sdk/schema/to_graph.py +0 −4
| @@ -20,8 +20,6 @@ | ||
| 20 | 20 | # Create graph entities |
| 21 | 21 | entity_ids = {} |
| 22 | 22 | for e in s.entities: |
| 23 | - e = s.entities[e] | |
| 24 | - | |
| 25 | 23 | # Construct entity creation query |
| 26 | 24 | q = f"""CREATE (n:{e.name}) |
| 27 | 25 | SET n = $args |
| @@ -40,8 +38,6 @@ | ||
| 40 | 38 | |
| 41 | 39 | # Create graph relations |
| 42 | 40 | for r in s.relations: |
| 43 | - r = s.relations[r] | |
| 44 | - | |
| 45 | 41 | # Construct relationship creation query |
| 46 | 42 | q = f"""MATCH (src), (dest) |
| 47 | 43 | WHERE ID(src) = $src AND ID(dest) = $dest |
modified graphrag_sdk/schema/tools_gen.py +16 −14
| @@ -36,8 +36,8 @@ | ||
| 36 | 36 | tool = {} |
| 37 | 37 | tool['type'] = "function" |
| 38 | 38 | tool['function'] = {} |
| 39 | - tool['function']['name'] = r.name | |
| 40 | - tool['function']['description'] = "Form a connection between " + src.name + " and " + dest.name | |
| 39 | + tool['function']['name'] = f"{src.name}_{r.name}_{dest.name}" | |
| 40 | + tool['function']['description'] = f"Form a connection of type {r.name} between {src.name} and {dest.name}" | |
| 41 | 41 | |
| 42 | 42 | tool['function']['parameters'] = {} |
| 43 | 43 | tool['function']['parameters']['type'] = "object" |
| @@ -49,25 +49,27 @@ | ||
| 49 | 49 | # see if src node has a unique attribute |
| 50 | 50 | attrs = src.unique_attributes() |
| 51 | 51 | for attr in attrs: |
| 52 | - tool['function']['parameters']['properties'][attr.name] = {} | |
| 53 | - tool['function']['parameters']['properties'][attr.name]['type'] = type_mapping(attr.type) | |
| 52 | + property_name = f"{src.name}_{attr.name}" | |
| 53 | + tool['function']['parameters']['properties'][property_name] = {} | |
| 54 | + tool['function']['parameters']['properties'][property_name]['type'] = type_mapping(attr.type) | |
| 54 | 55 | if attr.desc is not None: |
| 55 | - tool['function']['parameters']['properties'][attr.name]['description'] = attr.desc | |
| 56 | + tool['function']['parameters']['properties'][property_name]['description'] = attr.desc | |
| 56 | 57 | else: |
| 57 | - tool['function']['parameters']['properties'][attr.name]['description'] = src.name + "'s " + attr.name | |
| 58 | - required.append(attr.name) | |
| 58 | + tool['function']['parameters']['properties'][property_name]['description'] = src.name + "'s " + attr.name | |
| 59 | + required.append(property_name) | |
| 59 | 60 | |
| 60 | 61 | # process edge's destination |
| 61 | 62 | # see if dest node has a unique attribute |
| 62 | 63 | attrs = dest.unique_attributes() |
| 63 | 64 | for attr in attrs: |
| 64 | - tool['function']['parameters']['properties'][attr.name] = {} | |
| 65 | - tool['function']['parameters']['properties'][attr.name]['type'] = type_mapping(attr.type) | |
| 65 | + property_name = f"{dest.name}_{attr.name}" | |
| 66 | + tool['function']['parameters']['properties'][property_name] = {} | |
| 67 | + tool['function']['parameters']['properties'][property_name]['type'] = type_mapping(attr.type) | |
| 66 | 68 | if attr.desc is not None: |
| 67 | - tool['function']['parameters']['properties'][attr.name]['description'] = attr.desc | |
| 69 | + tool['function']['parameters']['properties'][property_name]['description'] = attr.desc | |
| 68 | 70 | else: |
| 69 | - tool['function']['parameters']['properties'][attr.name]['description'] = dest.name + "'s " + attr.name | |
| 70 | - required.append(attr.name) | |
| 71 | + tool['function']['parameters']['properties'][property_name]['description'] = dest.name + "'s " + attr.name | |
| 72 | + required.append(property_name) | |
| 71 | 73 | |
| 72 | 74 | tool['function']['parameters']['required'] = required |
| 73 | 75 | |
| @@ -128,11 +130,11 @@ | ||
| 128 | 130 | |
| 129 | 131 | tools = [] |
| 130 | 132 | for e in s.entities: |
| 131 | - tool = entity_to_tool(s.entities[e]) | |
| 133 | + tool = entity_to_tool(e) | |
| 132 | 134 | tools.append(tool) |
| 133 | 135 | |
| 134 | 136 | for r in s.relations: |
| 135 | - tool = relation_to_tool(s.relations[r]) | |
| 137 | + tool = relation_to_tool(r) | |
| 136 | 138 | tools.append(tool) |
| 137 | 139 | |
| 138 | 140 | return tools |
modified graphrag_sdk/source.py +25 −7
| @@ -3,12 +3,13 @@ | ||
| 3 | 3 | from bs4 import BeautifulSoup |
| 4 | 4 | from abc import ABC, abstractmethod |
| 5 | 5 | |
| 6 | -def Source(source:str) ->'AbstractSource': | |
| 6 | +def Source(source:str, instruction:str|None=None) ->'AbstractSource': | |
| 7 | 7 | """ |
| 8 | 8 | Creates a source object |
| 9 | 9 | |
| 10 | 10 | Parameters: |
| 11 | 11 | source (str): path to source |
| 12 | + instruction (str): source specific instruction for the LLM | |
| 12 | 13 | |
| 13 | 14 | Returns: |
| 14 | 15 | AbstractSource: source |
| @@ -17,12 +18,19 @@ | ||
| 17 | 18 | if not isinstance(source, str) or source == "": |
| 18 | 19 | raise Exception("Invalid argument, source should be a none empty string.") |
| 19 | 20 | |
| 21 | + s = None | |
| 22 | + | |
| 20 | 23 | if ".pdf" in source.lower(): |
| 21 | - return PDF(source) | |
| 22 | - elif ".html" in source.lower(): | |
| 23 | - return HTML(source) | |
| 24 | + s = PDF(source) | |
| 25 | + elif ".html" in source.lower() or "http" in source.lower(): | |
| 26 | + s = HTML(source) | |
| 24 | 27 | else: |
| 25 | - return TEXT(source) | |
| 28 | + s = TEXT(source) | |
| 29 | + | |
| 30 | + # Set source instructions | |
| 31 | + s.instruction = instruction | |
| 32 | + | |
| 33 | + return s | |
| 26 | 34 | |
| 27 | 35 | class AbstractSource(ABC): |
| 28 | 36 | """ |
| @@ -83,9 +91,17 @@ | ||
| 83 | 91 | def __init__(self, source): |
| 84 | 92 | super().__init__(source) |
| 85 | 93 | |
| 94 | + def _download(self): | |
| 95 | + try: | |
| 96 | + response = requests.get(self.source) | |
| 97 | + response.raise_for_status() # Raise an HTTPError for bad responses (4xx and 5xx) | |
| 98 | + self.content = response.text | |
| 99 | + except requests.exceptions.RequestException as e: | |
| 100 | + print(f"An error occurred: {e}") | |
| 101 | + | |
| 86 | 102 | def load(self): |
| 87 | - with open(self.source, 'r') as f: | |
| 88 | - self.content = f.read() | |
| 103 | + # Download URL | |
| 104 | + self._download() | |
| 89 | 105 | |
| 90 | 106 | # extract text from HTML, populate self.content |
| 91 | 107 | soup = BeautifulSoup(self.content, 'html.parser') |
| @@ -95,3 +111,5 @@ | ||
| 95 | 111 | |
| 96 | 112 | # Remove extra newlines |
| 97 | 113 | self.content = re.sub(r'\n{2,}', '\n', self.content) |
| 114 | + | |
| 115 | + return f"{self.source}\n{self.content}" |
modified graphrag_sdk/template.py +26 −12
| @@ -9,6 +9,9 @@ | ||
| 9 | 9 | from .prompts import KNOWLEDGE_EXTRACTION_SYSTEM_PROMPT |
| 10 | 10 | from falkordb import FalkorDB |
| 11 | 11 | |
| 12 | +import logging | |
| 13 | +logger = logging.getLogger(__name__) | |
| 14 | + | |
| 12 | 15 | g = None # graph |
| 13 | 16 | client = None # OpenAI client |
| 14 | 17 | |
| @@ -21,7 +24,14 @@ | ||
| 21 | 24 | def remove_none_values(args): |
| 22 | 25 | return {key: value for key, value in args.items() if value is not None} |
| 23 | 26 | |
| 24 | -def create_assistant(client, assistant_name, instructions, model): | |
| 27 | +def get_assistant(client, assistant_name, instructions, model): | |
| 28 | + for assistant in client.beta.assistants.list(): | |
| 29 | + if assistant.name == assistant_name: | |
| 30 | + return client.beta.assistants.retrieve(assistant.id) | |
| 31 | + | |
| 32 | + return _create_assistant(client, assistant_name, instructions, model) | |
| 33 | + | |
| 34 | +def _create_assistant(client, assistant_name, instructions, model): | |
| 25 | 35 | assistant = client.beta.assistants.create( |
| 26 | 36 | name = assistant_name, |
| 27 | 37 | instructions = instructions, |
| @@ -44,26 +54,26 @@ | ||
| 44 | 54 | run = client.beta.threads.runs.retrieve(thread_id=run.thread_id, run_id=run.id) |
| 45 | 55 | |
| 46 | 56 | if run.status == "completed": |
| 47 | - print("Run completed") | |
| 57 | + logger.debug("Run completed") | |
| 48 | 58 | return |
| 49 | 59 | |
| 50 | 60 | if run.status == "expired": |
| 51 | - print(f"Run expired") | |
| 61 | + logger.debug(f"Run expired") | |
| 52 | 62 | return |
| 53 | 63 | |
| 54 | 64 | if run.status == "cancelling" or run.status == "cancelled" or run.status == "failed": |
| 55 | - print(f"Run failed") | |
| 65 | + logger.debug(f"Run failed") | |
| 56 | 66 | return |
| 57 | 67 | |
| 58 | 68 | # wait for run to complete |
| 59 | 69 | if run.status == "queued": |
| 60 | - print("Run queued") | |
| 70 | + logger.debug("Run queued") | |
| 61 | 71 | time.sleep(1) |
| 62 | 72 | continue |
| 63 | 73 | |
| 64 | 74 | if run.status == "in_progress": |
| 65 | 75 | last_step_id = None |
| 66 | - print("Run in progress") | |
| 76 | + logger.debug("Run in progress") | |
| 67 | 77 | run_steps = [] |
| 68 | 78 | # if last_step_id is None: |
| 69 | 79 | # run_steps = client.beta.threads.runs.steps.list(thread_id=run.thread_id, run_id=run.id) |
| @@ -82,11 +92,11 @@ | ||
| 82 | 92 | func_name = func.name |
| 83 | 93 | args = func.arguments |
| 84 | 94 | args = json.loads(args) |
| 85 | - print(f"Function: {func_name}, {args}") | |
| 95 | + logger.debug(f"Function: {func_name}, {args}") | |
| 86 | 96 | f = available_functions[func_name] |
| 87 | 97 | f(args) |
| 88 | 98 | except: |
| 89 | - print(f"tool_call: {tool_call}") | |
| 99 | + logger.debug(f"tool_call: {tool_call}") | |
| 90 | 100 | pass |
| 91 | 101 | |
| 92 | 102 | last_step_id = run_steps.last_id |
| @@ -95,7 +105,7 @@ | ||
| 95 | 105 | continue |
| 96 | 106 | |
| 97 | 107 | if run.status == "requires_action": |
| 98 | - print(f"Run requires action") | |
| 108 | + logger.debug(f"Run requires action") | |
| 99 | 109 | action = run.required_action |
| 100 | 110 | if action.type == "submit_tool_outputs": |
| 101 | 111 | tool_outputs = action.submit_tool_outputs |
| @@ -107,7 +117,7 @@ | ||
| 107 | 117 | func_name = func.name |
| 108 | 118 | args = func.arguments |
| 109 | 119 | args = json.loads(args) |
| 110 | - print(f"Function: {func_name}, {args}") | |
| 120 | + logger.debug(f"Function: {func_name}, {args}") | |
| 111 | 121 | |
| 112 | 122 | f = available_functions[func_name] |
| 113 | 123 | f(args) |
| @@ -126,18 +136,21 @@ | ||
| 126 | 136 | def process_source(client, assistant, src): |
| 127 | 137 | text = src.load()[:32000] |
| 128 | 138 | user_message = f"Extracts entities and relations from the following text: {text}" |
| 139 | + if src.instruction is not None: | |
| 140 | + user_message = f"{src.instruction}\\n{user_message}" | |
| 129 | 141 | |
| 130 | 142 | run = initiate_interaction(client, assistant, user_message) |
| 131 | 143 | |
| 132 | 144 | handle_run(client, run) |
| 133 | 145 | |
| 134 | 146 | client.beta.threads.delete(run.thread_id) |
| 147 | + logger.debug(f"Done processing {src.source}") | |
| 135 | 148 | |
| 136 | 149 | def build_graph_from_sources(kg, client, srcs:set): |
| 137 | 150 | global g |
| 138 | 151 | g = kg.graph |
| 139 | 152 | |
| 140 | - assistant = create_assistant(client, kg.name, KNOWLEDGE_EXTRACTION_SYSTEM_PROMPT, model=kg.model) | |
| 153 | + assistant = get_assistant(client, kg.name, KNOWLEDGE_EXTRACTION_SYSTEM_PROMPT, model=kg.model) | |
| 141 | 154 | |
| 142 | 155 | # Create thread pool |
| 143 | 156 | with concurrent.futures.ThreadPoolExecutor(max_workers=16) as executor: |
| @@ -145,9 +158,10 @@ | ||
| 145 | 158 | # extract entities and relationships from each page |
| 146 | 159 | for src in srcs: |
| 147 | 160 | task = executor.submit(process_source, client, assistant, src) |
| 161 | + tasks.append(task) | |
| 148 | 162 | |
| 149 | 163 | # Wait for all tasks to complete |
| 150 | 164 | concurrent.futures.wait(tasks) |
| 151 | 165 | |
| 152 | - print("Done") | |
| 166 | + logger.debug("Done") | |
| 153 | 167 | ''' |
deleted template.py +0 −148
| @@ -1,148 +0,0 @@ | ||
| 1 | -import json | |
| 2 | -import time | |
| 3 | -import concurrent.futures | |
| 4 | -from openai import OpenAI | |
| 5 | -from graphrag_sdk.prompts import KNOWLEDGE_EXTRACTION_SYSTEM_PROMPT | |
| 6 | -from falkordb import FalkorDB | |
| 7 | - | |
| 8 | -g = None # graph | |
| 9 | -client = None # OpenAI client | |
| 10 | - | |
| 11 | -tools = [<TOOLS>] | |
| 12 | - | |
| 13 | -<FUNCTIONS> | |
| 14 | - | |
| 15 | -available_functions = <AVAILABLE_FUNCTIONS> | |
| 16 | - | |
| 17 | -def remove_none_values(args): | |
| 18 | - return {key: value for key, value in args.items() if value is not None} | |
| 19 | - | |
| 20 | -def create_assistant(client, assistant_name, instructions, model): | |
| 21 | - assistant = client.beta.assistants.create( | |
| 22 | - name = assistant_name, | |
| 23 | - instructions = instructions, | |
| 24 | - model = model, | |
| 25 | - tools = tools | |
| 26 | - ) | |
| 27 | - | |
| 28 | - return assistant | |
| 29 | - | |
| 30 | -def initiate_interaction(client, assistant, user_message): | |
| 31 | - run = client.beta.threads.create_and_run( | |
| 32 | - assistant_id=assistant.id, | |
| 33 | - thread={ "messages": [ {"role": "user", "content": user_message} ] } | |
| 34 | - ) | |
| 35 | - | |
| 36 | - return run | |
| 37 | - | |
| 38 | -def handle_run(client, run): | |
| 39 | - while True: | |
| 40 | - run = client.beta.threads.runs.retrieve(thread_id=run.thread_id, run_id=run.id) | |
| 41 | - | |
| 42 | - if run.status == "completed": | |
| 43 | - print("Run completed") | |
| 44 | - return | |
| 45 | - | |
| 46 | - if run.status == "expired": | |
| 47 | - print(f"Run expired") | |
| 48 | - return | |
| 49 | - | |
| 50 | - if run.status == "cancelling" or run.status == "cancelled" or run.status == "failed": | |
| 51 | - print(f"Run failed") | |
| 52 | - return | |
| 53 | - | |
| 54 | - # wait for run to complete | |
| 55 | - if run.status == "queued": | |
| 56 | - print("Run queued") | |
| 57 | - time.sleep(1) | |
| 58 | - continue | |
| 59 | - | |
| 60 | - if run.status == "in_progress": | |
| 61 | - last_step_id = None | |
| 62 | - print("Run in progress") | |
| 63 | - run_steps = [] | |
| 64 | - # if last_step_id is None: | |
| 65 | - # run_steps = client.beta.threads.runs.steps.list(thread_id=run.thread_id, run_id=run.id) | |
| 66 | - # else: | |
| 67 | - # run_steps = client.beta.threads.runs.steps.list(thread_id=run.thread_id, run_id=run.id, after=last_step_id) | |
| 68 | - run_steps = client.beta.threads.runs.steps.list(thread_id=run.thread_id, run_id=run.id) | |
| 69 | - | |
| 70 | - for step in run_steps.data: | |
| 71 | - if step.status == "in_progress": | |
| 72 | - step_details = step.step_details | |
| 73 | - if step_details.type == "tool_calls": | |
| 74 | - for tool_call in step_details.tool_calls: | |
| 75 | - try: | |
| 76 | - if tool_call.type == "function": | |
| 77 | - func = tool_call.function | |
| 78 | - func_name = func.name | |
| 79 | - args = func.arguments | |
| 80 | - args = json.loads(args) | |
| 81 | - print(f"Function: {func_name}, {args}") | |
| 82 | - f = available_functions[func_name] | |
| 83 | - f(args) | |
| 84 | - except: | |
| 85 | - print(f"tool_call: {tool_call}") | |
| 86 | - pass | |
| 87 | - | |
| 88 | - last_step_id = run_steps.last_id | |
| 89 | - | |
| 90 | - time.sleep(1) | |
| 91 | - continue | |
| 92 | - | |
| 93 | - if run.status == "requires_action": | |
| 94 | - print(f"Run requires action") | |
| 95 | - action = run.required_action | |
| 96 | - if action.type == "submit_tool_outputs": | |
| 97 | - tool_outputs = action.submit_tool_outputs | |
| 98 | - outputs = [] | |
| 99 | - for tool in tool_outputs.tool_calls: | |
| 100 | - tool_call_id = tool.id | |
| 101 | - tool_type = tool.type | |
| 102 | - func = tool.function | |
| 103 | - func_name = func.name | |
| 104 | - args = func.arguments | |
| 105 | - args = json.loads(args) | |
| 106 | - print(f"Function: {func_name}, {args}") | |
| 107 | - | |
| 108 | - f = available_functions[func_name] | |
| 109 | - f(args) | |
| 110 | - | |
| 111 | - outputs.append({ "tool_call_id": tool_call_id, "output": "OK" }) | |
| 112 | - | |
| 113 | - # respond to action | |
| 114 | - run = client.beta.threads.runs.submit_tool_outputs( | |
| 115 | - thread_id=run.thread_id, | |
| 116 | - run_id=run.id, | |
| 117 | - tool_outputs=outputs | |
| 118 | - ) | |
| 119 | - | |
| 120 | - continue | |
| 121 | - | |
| 122 | -def process_source(client, assistant, src): | |
| 123 | - text = src.load()[:32000] | |
| 124 | - user_message = f"Extracts entities and relations from the following text:\n {text}" | |
| 125 | - | |
| 126 | - run = initiate_interaction(client, assistant, user_message) | |
| 127 | - | |
| 128 | - handle_run(client, run) | |
| 129 | - | |
| 130 | - client.beta.threads.delete(run.thread_id) | |
| 131 | - | |
| 132 | -def build_graph_from_sources(kg, client, srcs:set): | |
| 133 | - global g | |
| 134 | - g = kg.graph | |
| 135 | - | |
| 136 | - assistant = create_assistant(client, kg.name, KNOWLEDGE_EXTRACTION_SYSTEM_PROMPT, model=kg.model) | |
| 137 | - | |
| 138 | - # Create thread pool | |
| 139 | - with concurrent.futures.ThreadPoolExecutor(max_workers=16) as executor: | |
| 140 | - tasks = [] | |
| 141 | - # extract entities and relationships from each page | |
| 142 | - for src in srcs: | |
| 143 | - task = executor.submit(process_source, client, assistant, src) | |
| 144 | - | |
| 145 | - # Wait for all tasks to complete | |
| 146 | - concurrent.futures.wait(tasks) | |
| 147 | - | |
| 148 | - print("Done") |
modified tests/test_kg.py +30 −6
| @@ -1,4 +1,6 @@ | ||
| 1 | 1 | import unittest |
| 2 | +from openai import OpenAI | |
| 3 | +from falkordb import FalkorDB | |
| 2 | 4 | from graphrag_sdk import KnowledgeGraph, Source |
| 3 | 5 | from graphrag_sdk.schema import Schema |
| 4 | 6 | |
| @@ -6,12 +8,8 @@ | ||
| 6 | 8 | def test_kg_creation(self): |
| 7 | 9 | # Create schema |
| 8 | 10 | s = Schema() |
| 9 | - actor = s.add_entity('Actor') | |
| 10 | - actor.add_attribute('name', str, unique=True) | |
| 11 | - | |
| 12 | - movie = s.add_entity('Movie') | |
| 13 | - movie.add_attribute('title', str, unique=True) | |
| 14 | - | |
| 11 | + actor = s.add_entity('Actor').add_attribute('name', str, unique=True) | |
| 12 | + movie = s.add_entity('Movie').add_attribute('title', str, unique=True) | |
| 15 | 13 | s.add_relation("ACTED", actor, movie) |
| 16 | 14 | |
| 17 | 15 | g = KnowledgeGraph("IMDB", schema=s) |
| @@ -23,5 +21,31 @@ | ||
| 23 | 21 | answer, messages = g.ask("list additional actors", messages) |
| 24 | 22 | print(f"answer: {answer}") |
| 25 | 23 | |
| 24 | + def test_kg_delete(self): | |
| 25 | + s = Schema() | |
| 26 | + actor = s.add_entity('Actor').add_attribute('name', str, unique=True) | |
| 27 | + movie = s.add_entity('Movie').add_attribute('title', str, unique=True) | |
| 28 | + s.add_relation("ACTED", actor, movie) | |
| 29 | + | |
| 30 | + g = KnowledgeGraph("IMDB", schema=s) | |
| 31 | + g.process_sources([Source("./data/madoff.txt")]) | |
| 32 | + | |
| 33 | + g.delete() | |
| 34 | + | |
| 35 | + # Check that: | |
| 36 | + # 1. KnowledgeGraph has been removed from FalkorDB. | |
| 37 | + # 2. SchemaGraph has been removed from FalkorDB. | |
| 38 | + # 3. OpenAI assistant has been deleted. | |
| 39 | + | |
| 40 | + db = FalkorDB() | |
| 41 | + graphs = db.list_graphs() | |
| 42 | + self.assertNotIn("IMDB", graphs) | |
| 43 | + self.assertNotIn("IMDB_schema", graphs) | |
| 44 | + | |
| 45 | + client = OpenAI() | |
| 46 | + assistant_id = None | |
| 47 | + for assistant in client.beta.assistants.list(): | |
| 48 | + self.assertNotEqual(assistant.name, "IMDB") | |
| 49 | + | |
| 26 | 50 | if __name__ == '__main__': |
| 27 | 51 | unittest.main() |