Elffuss BraidHub

kikocis/GraphRAG-SDK public

support logging, wait for all concurrent tasks, github example
Changeset3034d86cfbbe9200f55f9be9fc3040b33603815ff0da47df66eadc5a8900ec0e
AuthorRoi Lipman <roilipman@gmail.com> · 2024-06-08 00:04 +03:00
CommitterRoi Lipman <roilipman@gmail.com> · 2024-06-08 00:04 +03:00
Parentsb6ff0beb7359

Browse the files at this changeset

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 @@
11 from .kg import KnowledgeGraph
22 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 @@
11 import os
22 import queue
3+from openai import OpenAI
34 import concurrent.futures
45 from typing_extensions import AbstractSet
56
@@ -13,6 +14,13 @@
1314 from .schema.tools_gen import schema_to_tools
1415 from .schema.functions_gen import schema_to_functions
1516
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+
1624 class KnowledgeGraph(object):
1725 """Knowledge Graph model data as a network of entities and relations
1826 To create one it is best to provide a schema which will define the graph's ontology
@@ -40,9 +48,9 @@
4048 self.db = FalkorDB(host=host, port=port, username=username, password=password)
4149 self.graph = self.db.select_graph(name)
4250
43- self.name = name
4451 self.model = model
45- self.schema = schema
52+ self._name = name
53+ self._schema = schema
4654 self.client = None # OpenAI client
4755 self.sources = set([])
4856 self.ontolegy_ratio = 0.1 # Sampaling ratio for ontolegy detection
@@ -52,8 +60,29 @@
5260 if schema is None:
5361 schema_name = self._schema_name()
5462 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")
5786
5887 def list_sources(self) -> list[AbstractSource]:
5988 """
@@ -119,20 +148,20 @@
119148 # TODO: note multiple calls to _createKGWithSchema will overide one another.
120149 exec(code, globals())
121150
122- def _createKGWithoutSchema(self):
123- raise Exception("Can not create knowledge graph, schema missing")
124-
125151 def _create(self) -> None:
126152 """
127153 Create knowledge graph
128154 Extract entities and relations from sources
129155 """
130- self.client = OpenAI()
131156
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()
136165
137166 def ask(self, question:str, history:list|None=None) -> tuple[str, list]:
138167 """
@@ -153,3 +182,37 @@
153182
154183 answer = query(self, question, history, self.model)
155184 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 @@
11 import json
22 from openai import OpenAI
33
4+import logging
5+logger = logging.getLogger(__name__)
6+
47 # Equipet assistant with tools:
58 tools = [
69 {
@@ -37,12 +40,10 @@
3740 # list labels
3841 desc = desc + "The graph contains the following node labels:\n";
3942 for e in s.entities:
40- desc += e + "\n"
43+ desc += e.name + "\n"
4144
4245 # specify attributes associated with each entity
4346 for e in s.entities:
44- e = s.entities[e]
45-
4647 lbl_name = e.name
4748 attributes = e.attributes
4849 attr_count = len(attributes)
@@ -64,8 +65,6 @@
6465
6566 # list relations
6667 for rel in s.relations:
67- rel = s.relations[rel]
68-
6968 src = rel.src.name
7069 relationship_type = rel.name
7170 dest = rel.dest.name
@@ -107,7 +106,8 @@
107106 function_to_call = available_functions[function_name]
108107 function_args = json.loads(tool_call.function.arguments)
109108 q = function_args.get("query")
110- print(f"OpenAI suggested query: {q}")
109+ logger.debug(f"Model suggested query: {q}")
110+
111111 function_response = function_to_call(g, q)
112112 messages.append(
113113 {
modified graphrag_sdk/schema/__init__.py +5 −0
@@ -1,1 +1,6 @@
11 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 @@
1010 from sqlalchemy.orm import sessionmaker
1111 from sqlalchemy import create_engine, inspect, MetaData, Table, types
1212
13+import logging
14+logger = logging.getLogger(__name__)
15+
1316 # Convert from SQLAlchemy type to Python type
1417 def sqlalchemy_to_python_type(sqlalchemy_type):
1518 if isinstance(sqlalchemy_type, types.Integer):
@@ -143,7 +146,7 @@
143146 pass
144147 create_relation(s, tbl, foreign_keys)
145148 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")
147150
148151 def convert_tables(s, client, model, inspector, table_names):
149152 # Start by converting tabels without foreign keys
@@ -212,7 +215,7 @@
212215 # queue sql statment
213216 def run_sql(arg, queue):
214217 sql = arg["sql"]
215- print(f"SQL: {sql}")
218+ logger.debug(f"SQL: {sql}")
216219
217220 queue.put(sql)
218221
@@ -224,13 +227,9 @@
224227 # Get OpenAI ontology detection assistant
225228 def get_assistant(client, assistant_name, model):
226229 # 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)
234233
235234 # Create OpenAI assistant
236235 assistant = client.beta.assistants.create(
@@ -253,10 +252,6 @@
253252 }]
254253 )
255254
256- # Save assistant ID to local file
257- with open("./ONTOLOGY_ASSISTANT_ID", 'w') as f:
258- f.write(assistant.id)
259-
260255 return assistant
261256
262257 # Start an interaction with OpenAI assistant
@@ -274,15 +269,15 @@
274269 run = client.beta.threads.runs.retrieve(thread_id=run.thread_id, run_id=run.id)
275270
276271 if run.status == "completed":
277- print("Done processing document")
272+ logger.debug("Done processing document")
278273 return
279274
280275 if run.status == "expired":
281- print(f"Processing expired")
276+ logger.debug(f"Processing expired")
282277 return
283278
284279 if run.status == "cancelling" or run.status == "cancelled" or run.status == "failed":
285- print(f"Processing failed")
280+ logger.debug(f"Processing failed")
286281 return
287282
288283 # wait for run to complete
@@ -309,7 +304,7 @@
309304 f = available_functions[func_name]
310305 f(args, queue)
311306 except:
312- print(f"tool_call: {tool_call}")
307+ logger.debug(f"tool_call: {tool_call}")
313308 pass
314309
315310 last_step_id = run_steps.last_id
@@ -384,14 +379,14 @@
384379 tables = {}
385380 for i in range(n):
386381 stmt = q.get()
387- print(f"sql: {stmt}")
382+ logger.debug(f"sql: {stmt}")
388383
389384 # group by table name
390385 # CREATE TABLE MoviePersonnel (
391386 s = stmt.index("CREATE TABLE ") + len("CREATE TABLE ")
392387 e = stmt.index("(") - 1
393388 tbl = stmt[s:e]
394- print(f"tbl: {tbl}")
389+ logger.debug(f"tbl: {tbl}")
395390
396391 if tbl not in tables:
397392 tables[tbl] = []
@@ -414,7 +409,7 @@
414409 )
415410
416411 merged_stmt = response.choices[0].message.content
417- print(f"merged_stmt: {merged_stmt}")
412+ logger.debug(f"merged_stmt: {merged_stmt}")
418413 tables[k].append(merged_stmt)
419414
420415 # Switch back from dict to array
@@ -425,7 +420,7 @@
425420 cur = con.cursor()
426421
427422 for stmt in tables:
428- print(f"Executing: {stmt}")
423+ logger.debug(f"Executing: {stmt}")
429424 cur.execute(stmt)
430425 con.commit()
431426
modified graphrag_sdk/schema/encoder.py +2 −4
@@ -1,10 +1,10 @@
1-from json import JSONEncoder
1+import json
22
33 # Encode Schema into JSON
44 class SchemaEncoder():
55 # encode schema to JSON string
66 def to_JSON(self, schema) -> str:
7- return JSONEncoder().encode(self.encode(schema))
7+ return json.dumps(self.encode(schema), indent=4)
88
99 # encode schema as dict
1010 def encode(self, schema) -> dict:
@@ -14,11 +14,9 @@
1414 dict = {'entities': [], 'relations': []}
1515
1616 for e in schema.entities:
17- e = schema.entities[e]
1817 dict['entities'].append(self._encode_entity(e))
1918
2019 for r in schema.relations:
21- r = schema.relations[r]
2220 dict['relations'].append(self._encode_relation(r))
2321
2422 return dict
modified graphrag_sdk/schema/entity.py +19 −3
@@ -47,7 +47,13 @@
4747
4848 return (self.name == other.name and self.attributes == other.attributes)
4949
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':
5157 """
5258 Add attribute to entity
5359
@@ -57,6 +63,9 @@
5763 desc (str): short description for attribute
5864 unique (bool): is the attribute value unique
5965 mandatory (bool): is the attribute mandatory
66+
67+ Returns:
68+ Entity
6069 """
6170
6271 # Validate arguments
@@ -75,12 +84,17 @@
7584 desc = f"{self.name}'s {name}" if desc is None else desc
7685 self.attributes.add(Attribute(name, type, desc, unique, mandatory))
7786
78- def remove_attribute(self, name:str) ->None:
87+ return self
88+
89+ def remove_attribute(self, name:str) -> 'Entity':
7990 """
8091 Remove attribute from entity
8192
8293 Parameters:
8394 name (str): name of attribute to remove
95+
96+ Returns:
97+ Entity
8498 """
8599
86100 # Validate argument
@@ -90,7 +104,9 @@
90104 for attr in self.attributes:
91105 if attr.name == name:
92106 self.attributes.remove(attr)
93- return
107+ break
108+
109+ return self
94110
95111 def get_attribute(self, name:str) -> Attribute|None:
96112 """
modified graphrag_sdk/schema/functions_gen.py +11 −10
@@ -5,33 +5,34 @@
55 def relation_to_create_func(r:Relation):
66 src_lbl = r.src.name
77 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}"
910
10- func = f"def {r.name}(args):\n" # def MovieStream(args):
11+ func = f"def {func_name}(args):\n" # def MovieStream(args):
1112 func += "\targs = remove_none_values(args)\n" # args = remove_none_values(args)
1213
1314 # extract required src arguments
1415 src_attrs = r.src.unique_attributes()
1516
16- # extract required dest arguments
17+ # extract required src arguments
1718 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])
1920 func += "}) "
2021
21- # extract required src arguments
22+ # extract required dest arguments
2223 dest_attrs = r.dest.unique_attributes()
2324
2425 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])
2627 func += "}) "
2728
2829 func += "MERGE (s)-[r:" + r.name + "]->(d)\"\n"
2930
3031 # construct query params
3132 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])
3334 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])
3536 func += "}\n"
3637
3738 func += "\tg.query(q, params)\n"
@@ -64,11 +65,11 @@
6465
6566 functions = []
6667 for e in s.entities:
67- func = entity_to_create_func(s.entities[e])
68+ func = entity_to_create_func(e)
6869 functions.append(func)
6970
7071 for r in s.relations:
71- func = relation_to_create_func(s.relations[r])
72+ func = relation_to_create_func(r)
7273 functions.append(func)
7374
7475 return functions
modified graphrag_sdk/schema/relation.py +9 −0
@@ -19,6 +19,9 @@
1919 self.dest = dest
2020 self.name = name
2121
22+ def __str__(self) -> str:
23+ return f"(:{self.src.name})-[:{self.name}]->(:{self.dest.name})"
24+
2225 def __eq__(self, other) -> bool:
2326 if not isinstance(other, Relation):
2427 return False
@@ -26,3 +29,9 @@
2629 return (self.src == other.src and
2730 self.dest == other.dest and
2831 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 @@
2020 Initialize Schema
2121 """
2222
23- self.entities = {}
24- self.relations = {}
23+ self.entities = set([])
24+ self.relations = set([])
2525
2626 def __eq__(self, other) -> bool:
2727 if not isinstance(other, Schema):
@@ -54,7 +54,8 @@
5454 raise Exception(f"Entity {name} already exists")
5555
5656 e = Entity(name)
57- self.entities[name] = e
57+ self.entities.add(e)
58+
5859 return e
5960
6061 def get_entity(self, name:str) -> Entity | None:
@@ -68,10 +69,11 @@
6869 if not isinstance(name, str) or name == "":
6970 raise Exception("Invalid argument, name should be a none empty string")
7071
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
7577
7678 def add_relation(self, name:str, src:Entity, dest:Entity) -> Relation:
7779 """
@@ -97,12 +99,6 @@
9799 if name in self.relations:
98100 raise Exception(f"Relation {name} already exists")
99101
100- # fetch entities
101- if isinstance(src, str):
102- src = self.entities[src]
103- if isinstance(dest, str):
104- dest = self.entities[dest]
105-
106102 # Both src and dest must have at least one unique attribute
107103 if len(src.unique_attributes()) == 0:
108104 raise Exception(f"{src.name} must have at least one unique attribute")
@@ -111,7 +107,7 @@
111107
112108 # Create relation and add it to schema
113109 r = Relation(name, src, dest)
114- self.relations[name] = r
110+ self.relations.add(r)
115111
116112 return r
117113
@@ -126,19 +122,15 @@
126122 # Make sure each Relation reference existing Entities
127123 # And each referenced entity has at least one unique attribute
128124 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+
132128 if src not in self.entities:
133129 raise Exception(f"Relation {r.name} reference a none existing entity {src}")
134130 if dest not in self.entities:
135131 raise Exception(f"Relation {r.name} reference a none existing entity {dest}")
136-
137- src = self.entities[src]
138132 if len(src.unique_attributes()) == 0:
139133 raise Exception(f"Relation {r.name} src endpoint {src.name} is missing a unique attribute")
140-
141- dest = self.entities[dest]
142134 if len(dest.unique_attributes()) == 0:
143135 raise Exception(f"Relation {r.name} src endpoint {dest.name} is missing a unique attribute")
144136
modified graphrag_sdk/schema/to_graph.py +0 −4
@@ -20,8 +20,6 @@
2020 # Create graph entities
2121 entity_ids = {}
2222 for e in s.entities:
23- e = s.entities[e]
24-
2523 # Construct entity creation query
2624 q = f"""CREATE (n:{e.name})
2725 SET n = $args
@@ -40,8 +38,6 @@
4038
4139 # Create graph relations
4240 for r in s.relations:
43- r = s.relations[r]
44-
4541 # Construct relationship creation query
4642 q = f"""MATCH (src), (dest)
4743 WHERE ID(src) = $src AND ID(dest) = $dest
modified graphrag_sdk/schema/tools_gen.py +16 −14
@@ -36,8 +36,8 @@
3636 tool = {}
3737 tool['type'] = "function"
3838 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}"
4141
4242 tool['function']['parameters'] = {}
4343 tool['function']['parameters']['type'] = "object"
@@ -49,25 +49,27 @@
4949 # see if src node has a unique attribute
5050 attrs = src.unique_attributes()
5151 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)
5455 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
5657 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)
5960
6061 # process edge's destination
6162 # see if dest node has a unique attribute
6263 attrs = dest.unique_attributes()
6364 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)
6668 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
6870 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)
7173
7274 tool['function']['parameters']['required'] = required
7375
@@ -128,11 +130,11 @@
128130
129131 tools = []
130132 for e in s.entities:
131- tool = entity_to_tool(s.entities[e])
133+ tool = entity_to_tool(e)
132134 tools.append(tool)
133135
134136 for r in s.relations:
135- tool = relation_to_tool(s.relations[r])
137+ tool = relation_to_tool(r)
136138 tools.append(tool)
137139
138140 return tools
modified graphrag_sdk/source.py +25 −7
@@ -3,12 +3,13 @@
33 from bs4 import BeautifulSoup
44 from abc import ABC, abstractmethod
55
6-def Source(source:str) ->'AbstractSource':
6+def Source(source:str, instruction:str|None=None) ->'AbstractSource':
77 """
88 Creates a source object
99
1010 Parameters:
1111 source (str): path to source
12+ instruction (str): source specific instruction for the LLM
1213
1314 Returns:
1415 AbstractSource: source
@@ -17,12 +18,19 @@
1718 if not isinstance(source, str) or source == "":
1819 raise Exception("Invalid argument, source should be a none empty string.")
1920
21+ s = None
22+
2023 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)
2427 else:
25- return TEXT(source)
28+ s = TEXT(source)
29+
30+ # Set source instructions
31+ s.instruction = instruction
32+
33+ return s
2634
2735 class AbstractSource(ABC):
2836 """
@@ -83,9 +91,17 @@
8391 def __init__(self, source):
8492 super().__init__(source)
8593
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+
86102 def load(self):
87- with open(self.source, 'r') as f:
88- self.content = f.read()
103+ # Download URL
104+ self._download()
89105
90106 # extract text from HTML, populate self.content
91107 soup = BeautifulSoup(self.content, 'html.parser')
@@ -95,3 +111,5 @@
95111
96112 # Remove extra newlines
97113 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 @@
99 from .prompts import KNOWLEDGE_EXTRACTION_SYSTEM_PROMPT
1010 from falkordb import FalkorDB
1111
12+import logging
13+logger = logging.getLogger(__name__)
14+
1215 g = None # graph
1316 client = None # OpenAI client
1417
@@ -21,7 +24,14 @@
2124 def remove_none_values(args):
2225 return {key: value for key, value in args.items() if value is not None}
2326
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):
2535 assistant = client.beta.assistants.create(
2636 name = assistant_name,
2737 instructions = instructions,
@@ -44,26 +54,26 @@
4454 run = client.beta.threads.runs.retrieve(thread_id=run.thread_id, run_id=run.id)
4555
4656 if run.status == "completed":
47- print("Run completed")
57+ logger.debug("Run completed")
4858 return
4959
5060 if run.status == "expired":
51- print(f"Run expired")
61+ logger.debug(f"Run expired")
5262 return
5363
5464 if run.status == "cancelling" or run.status == "cancelled" or run.status == "failed":
55- print(f"Run failed")
65+ logger.debug(f"Run failed")
5666 return
5767
5868 # wait for run to complete
5969 if run.status == "queued":
60- print("Run queued")
70+ logger.debug("Run queued")
6171 time.sleep(1)
6272 continue
6373
6474 if run.status == "in_progress":
6575 last_step_id = None
66- print("Run in progress")
76+ logger.debug("Run in progress")
6777 run_steps = []
6878 # if last_step_id is None:
6979 # run_steps = client.beta.threads.runs.steps.list(thread_id=run.thread_id, run_id=run.id)
@@ -82,11 +92,11 @@
8292 func_name = func.name
8393 args = func.arguments
8494 args = json.loads(args)
85- print(f"Function: {func_name}, {args}")
95+ logger.debug(f"Function: {func_name}, {args}")
8696 f = available_functions[func_name]
8797 f(args)
8898 except:
89- print(f"tool_call: {tool_call}")
99+ logger.debug(f"tool_call: {tool_call}")
90100 pass
91101
92102 last_step_id = run_steps.last_id
@@ -95,7 +105,7 @@
95105 continue
96106
97107 if run.status == "requires_action":
98- print(f"Run requires action")
108+ logger.debug(f"Run requires action")
99109 action = run.required_action
100110 if action.type == "submit_tool_outputs":
101111 tool_outputs = action.submit_tool_outputs
@@ -107,7 +117,7 @@
107117 func_name = func.name
108118 args = func.arguments
109119 args = json.loads(args)
110- print(f"Function: {func_name}, {args}")
120+ logger.debug(f"Function: {func_name}, {args}")
111121
112122 f = available_functions[func_name]
113123 f(args)
@@ -126,18 +136,21 @@
126136 def process_source(client, assistant, src):
127137 text = src.load()[:32000]
128138 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}"
129141
130142 run = initiate_interaction(client, assistant, user_message)
131143
132144 handle_run(client, run)
133145
134146 client.beta.threads.delete(run.thread_id)
147+ logger.debug(f"Done processing {src.source}")
135148
136149 def build_graph_from_sources(kg, client, srcs:set):
137150 global g
138151 g = kg.graph
139152
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)
141154
142155 # Create thread pool
143156 with concurrent.futures.ThreadPoolExecutor(max_workers=16) as executor:
@@ -145,9 +158,10 @@
145158 # extract entities and relationships from each page
146159 for src in srcs:
147160 task = executor.submit(process_source, client, assistant, src)
161+ tasks.append(task)
148162
149163 # Wait for all tasks to complete
150164 concurrent.futures.wait(tasks)
151165
152- print("Done")
166+ logger.debug("Done")
153167 '''
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 @@
11 import unittest
2+from openai import OpenAI
3+from falkordb import FalkorDB
24 from graphrag_sdk import KnowledgeGraph, Source
35 from graphrag_sdk.schema import Schema
46
@@ -6,12 +8,8 @@
68 def test_kg_creation(self):
79 # Create schema
810 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)
1513 s.add_relation("ACTED", actor, movie)
1614
1715 g = KnowledgeGraph("IMDB", schema=s)
@@ -23,5 +21,31 @@
2321 answer, messages = g.ask("list additional actors", messages)
2422 print(f"answer: {answer}")
2523
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+
2650 if __name__ == '__main__':
2751 unittest.main()