Elffuss BraidHub

kikocis/GraphRAG-SDK public

installable
Changesetacbde8a169514183f7b4826571f36a5a953041917fb0740a2bbde5e4b5333fdc
AuthorRoi Lipman <roilipman@gmail.com> · 2024-06-05 15:21 +03:00
CommitterRoi Lipman <roilipman@gmail.com> · 2024-06-05 15:21 +03:00
Parents0ba6be3f19c9

Browse the files at this changeset

39 files changed

modified README.md +2 −2
@@ -16,8 +16,8 @@
1616 ```
1717
1818 ```python
19-from rag_sdk.Schema import Schema
20-from rag_sdk import KnowledgeGraph, Source
19+from graphrag_sdk.schema import Schema
20+from graphrag_sdk import KnowledgeGraph, Source
2121
2222 # Auto generate graph schema from unstructured data
2323 sources = [Source("./data/the_matrix.txt")]
added graphrag_sdk/__init__.py +2 −0
@@ -0,0 +1,2 @@
1+from .kg import KnowledgeGraph
2+from .source import Source
added graphrag_sdk/kg.py +155 −0
@@ -0,0 +1,155 @@
1+import os
2+import queue
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+class KnowledgeGraph(object):
17+ """Knowledge Graph model data as a network of entities and relations
18+ To create one it is best to provide a schema which will define the graph's ontology
19+ In addition to a set of sources from which entities and relations will be extracted.
20+ """
21+
22+ def __init__(self, name:str, host:str="127.0.0.1", port:int=6379, username:str|None=None, password:str|None=None,
23+ model:str="gpt-4-1106-preview", schema:Schema|None=None):
24+ """
25+ Initialize Knowledge Graph
26+
27+ Parameters:
28+ name (str): Knowledge graph name.
29+ host (str): FalkorDB hostname.
30+ port (int): FalkorDB port number.
31+ username (str|None): FalkorDB username.
32+ password (str|None): FalkorDB password.
33+ model (str): OpenAI model to use.
34+ """
35+
36+ if not isinstance(name, str) or name == "":
37+ raise Exception("name should be a non empty string")
38+
39+ # connect to database
40+ self.db = FalkorDB(host=host, port=port, username=username, password=password)
41+ self.graph = self.db.select_graph(name)
42+
43+ self.name = name
44+ self.model = model
45+ self.schema = schema
46+ self.client = None # OpenAI client
47+ self.sources = set([])
48+ self.ontolegy_ratio = 0.1 # Sampaling ratio for ontolegy detection
49+
50+ # in case schema is None
51+ # try to load schema from FalkorDB
52+ if schema is None:
53+ schema_name = self._schema_name()
54+ if schema_name in self.db.list_graphs():
55+ schema_graph = self.db.select_graph()
56+ self.schema = self.schema.from_graph(schema_graph)
57+
58+ def list_sources(self) -> list[AbstractSource]:
59+ """
60+ List of sources associated with knowledge graph
61+
62+ Returns:
63+ list[AbstractSource]: sources
64+ """
65+
66+ return [s.source for s in self.sources]
67+
68+ def process_sources(self, sources: list[AbstractSource]) -> None:
69+ """
70+ Add entities and relations found in sources into the knowledge-graph
71+
72+ Parameters:
73+ sources (list[AbstractSource]): list of sources to extract knowledge from
74+ """
75+
76+ # Make sure knowledge graph is created.
77+ if not 'build_graph_from_sources' in globals() or self.client is None:
78+ self._create()
79+
80+ # Run assistant
81+ result = build_graph_from_sources(self, self.client, sources)
82+
83+ # Add processed sources
84+ for src in sources:
85+ self.sources.add(src)
86+
87+ def _schema_name(self) -> str:
88+ """
89+ Generate a name for the schema based on the Knowledge Graph name
90+ """
91+
92+ return f"{self.name}_schema"
93+
94+ def _createKGWithSchema(self):
95+ # Save schema as an ontology graph
96+ schema_graph = self.db.select_graph(self._schema_name())
97+ self.schema.save_graph(schema_graph)
98+
99+ # Create Knowledge Graph construction assistant
100+
101+ # Generate assistant's toolings
102+ tools = schema_to_tools(self.schema)
103+
104+ # Generate functions from schema
105+ funcs = schema_to_functions(self.schema)
106+ functions_names = [func[0] for func in funcs]
107+ functions_impl = [func[1] for func in funcs]
108+
109+ # Generate assistant
110+ # Generate code from template
111+ code = TEMPLATE
112+ code = code.replace("<TOOLS>", ",\n".join([str(tool) for tool in tools]))
113+ code = code.replace("<GRAPH_ID>", "\"" + self.name + "\"")
114+ code = code.replace("<FUNCTIONS>", "\n".join(functions_impl))
115+ code = code.replace("<AVAILABLE_FUNCTIONS>", '{' + ",\n".join([f"'{f}': {f}" for f in functions_names]) +'}')
116+
117+ # Execute the code string in the global namespace
118+ # Introduces the 'build_graph_from_sources' function
119+ # TODO: note multiple calls to _createKGWithSchema will overide one another.
120+ exec(code, globals())
121+
122+ def _createKGWithoutSchema(self):
123+ raise Exception("Can not create knowledge graph, schema missing")
124+
125+ def _create(self) -> None:
126+ """
127+ Create knowledge graph
128+ Extract entities and relations from sources
129+ """
130+ self.client = OpenAI()
131+
132+ if self.schema is not None:
133+ self._createKGWithSchema()
134+ else:
135+ self._createKGWithoutSchema()
136+
137+ def ask(self, question:str, history:list|None=None) -> tuple[str, list]:
138+ """
139+ Query the knowledge graph using natural language
140+ if the query is asked as part of a longer conversation make sure to
141+ include past history.
142+
143+ Rreturns:
144+ tuple[str, list]: answer, conversation history
145+
146+ Example:
147+ >>> ans, history = kg.ask("Which actor has the most oscars")
148+ >>> ans, history = kg.ask("List a few movies in which that actored played in", history)
149+ """
150+
151+ if history is None:
152+ history = []
153+
154+ answer = query(self, question, history, self.model)
155+ return (answer, history)
added graphrag_sdk/prompts.py +76 −0
@@ -0,0 +1,76 @@
1+ONTOLOGY_DETECTION_SYSTEM_PROMPT = """Create SQL statement which will capture the different entities and the relations between them in the provided text.
2+Each table should represent either a single entity type with the entity's attributes as the table columns or a relation between two entities, using foreign keys.
3+For example an IMDB document is likely to produce 5 tables: Movie, Actor and Director each with its own columns and ACTED and DIRECTED tables.
4+Do not create an ID primary key column but set the most compelling attribute as the entity's primary key
5+Make sure to call the run_sql function provided in your tools set for each sql statement generated."""
6+
7+KNOWLEDGE_EXTRACTION_SYSTEM_PROMPT = """You are a helpful assistant with the goal of extracting
8+entities and relationships from text"""
9+
10+SQL_FOLDING_PROMPT = """The following two CREATE TABLE SQL statments are
11+creating the same table name, consolidate the two into a single
12+CREATE TABLE SQL statment.
13+Remove all duplicated columns.
14+Make sure the number of PRIMARY KEYs and FOREIGN KEYs is maintained.
15+Reply only with the result SQL statment, the reply should start with:
16+CREATE TABLE and end with );
17+For example: given the two CREATE TABLE SQL:
18+CREATE TABLE Person (FirstName string, LastName string, Age int);
19+CREATE TABLE Person (SurName string, ForeName string, Height int);
20+The response should be:
21+CREATE TABLE Person (FirstName string, LastName string, Age int, Height int);
22+"""
23+
24+SQL_FOCUS_PROMPT = """Given a CREATE TABLE SQL statment the table name
25+ represents some entity, in case the number of columns in the table is
26+ greater than 5, remove columns which are less descriptive of the entity.
27+ Do NOT remove columns which are either a PRIMARY KEY or a FOREIGN KEY.
28+ Make sure to leave at least 5 columns.
29+ Do NOT rename the table name.
30+ Reply only with the result SQL statment, the reply should start with:
31+ CREATE TABLE and end with );
32+ For example: given the CREATE TABLE SQL:
33+ CREATE TABLE Movie (
34+ Title string PRIMARY KEY,
35+ Genre string,
36+ ReleaseYear int,
37+ Rating string,
38+ Language string,
39+ BoxOffice string,
40+ streaming_date STRING,
41+ runtime STRING
42+ );
43+ The response should be:
44+ CREATE TABLE Movie (
45+ Title string PRIMARY KEY,
46+ Genre string,
47+ ReleaseYear int,
48+ Rating string,
49+ runtime STRING
50+ );
51+ Another example: given the CREATE TABLE SQL:
52+ CREATE TABLE Episode (
53+ show_title VARCHAR(255),
54+ show_year VARCHAR(4),
55+ season INT,
56+ episode_number INT,
57+ episode_title VARCHAR(255),
58+ air_date DATE,
59+ episode_rating DECIMAL(2, 1),
60+ FOREIGN KEY (show_title, show_year) REFERENCES TVShow(title, year)
61+ );
62+ You are not allowed to remove either show_title or show_year as these are part of the table's
63+ foreign key.
64+ """
65+
66+RELATIONSHIP_NAMING_PROMPT = """"You are a Cypher expert, help suggest names for
67+relationship types connecting source node to destination node.
68+Respond only with the suggested name.
69+For example given source node of type 'Actor' and destination node of type 'Movie'
70+Replay with: ACTED"""
71+
72+FIND_UNIQUE_ATTRIBUTE_PROMPT = """From the list of attributes describing a graph node
73+pick the most suitble attribute to act as a unique identifier of the node.
74+Respond only with the suggested attribute name
75+For example given a list of attributes: series_title, air_date, season_number, episode_number, title
76+Describing the graph entity "Episode" Reply with: title"""
added graphrag_sdk/query_graph.py +144 −0
@@ -0,0 +1,144 @@
1+import json
2+from openai import OpenAI
3+
4+# Equipet assistant with tools:
5+tools = [
6+ {
7+ "type": "function",
8+ "function": {
9+ "name": "run_cypher_query",
10+ "description": "Run a Cypher query against the graph",
11+ "parameters": {
12+ "type": "object",
13+ "properties": {
14+ "query": {
15+ "type": "string",
16+ "description": "query to execute",
17+ },
18+ },
19+ "required": ["query"],
20+ },
21+ },
22+ }
23+]
24+
25+def run_cypher_query(g, q):
26+ return g.query(q).result_set
27+
28+# convert a schema into a string representation
29+def _graph_schema_to_prompt(s) -> str:
30+ # Build a string description of graph schema
31+ desc = "The knowladge graph schema is as follows:\n"
32+
33+ #--------------------------------------------------------------------------
34+ # Describe labels
35+ #--------------------------------------------------------------------------
36+
37+ # list labels
38+ desc = desc + "The graph contains the following node labels:\n";
39+ for e in s.entities:
40+ desc += e + "\n"
41+
42+ # specify attributes associated with each entity
43+ for e in s.entities:
44+ e = s.entities[e]
45+
46+ lbl_name = e.name
47+ attributes = e.attributes
48+ attr_count = len(attributes)
49+
50+ if (attr_count == 0):
51+ desc += f"The {lbl_name} label has no attributes\n"
52+ else:
53+ desc += f"The {lbl_name} label is associated with the following attribute(s):\n"
54+ for attr in attributes:
55+ attr_name = attr.name
56+ attr_type = attr.type.__name__
57+ desc += f"{attr_name} which is of type {attr_type}\n"
58+
59+ desc += "The graph contains the following relationship types:\n"
60+
61+ #--------------------------------------------------------------------------
62+ # Describe relationships
63+ #--------------------------------------------------------------------------
64+
65+ # list relations
66+ for rel in s.relations:
67+ rel = s.relations[rel]
68+
69+ src = rel.src.name
70+ relationship_type = rel.name
71+ dest = rel.dest.name
72+ desc += f"{relationship_type}\n"
73+ desc += f"The {relationship_type} relationship connects the following labels:\n"
74+ desc += f"{src} is connected via {relationship_type} to {dest}\n"
75+
76+ desc += "This is the end of the knowladge graph schema description.\n"
77+
78+ return desc;
79+
80+def run_conversation(g, question, messages, model) -> str:
81+ client = OpenAI()
82+
83+ # Step 1: send the conversation and available functions to the model
84+ messages.append({"role": "user", "content": question})
85+
86+ response = client.chat.completions.create(
87+ model=model,
88+ messages=messages,
89+ tools=tools,
90+ tool_choice="auto", # auto is default, but we'll be explicit
91+ )
92+
93+ response_message = response.choices[0].message
94+ tool_calls = response_message.tool_calls
95+
96+ # Step 2: check if the model wanted to call a function
97+ if tool_calls:
98+ # Step 3: call the function
99+ # Note: the JSON response may not always be valid; be sure to handle errors
100+ available_functions = {
101+ "run_cypher_query": run_cypher_query,
102+ } # only one function in this example, but you can have multiple
103+ messages.append(response_message) # extend conversation with assistant's reply
104+ # Step 4: send the info for each function call and function response to the model
105+ for tool_call in tool_calls:
106+ function_name = tool_call.function.name
107+ function_to_call = available_functions[function_name]
108+ function_args = json.loads(tool_call.function.arguments)
109+ q = function_args.get("query")
110+ print(f"OpenAI suggested query: {q}")
111+ function_response = function_to_call(g, q)
112+ messages.append(
113+ {
114+ "tool_call_id": tool_call.id,
115+ "role": "tool",
116+ "name": function_name,
117+ "content": str(function_response),
118+ }
119+ ) # extend conversation with function response
120+ second_response = client.chat.completions.create(
121+ model=model,
122+ messages=messages,
123+ ) # get a new response from the model where it can see the function response
124+
125+ return second_response.choices[0].message.content
126+
127+ return None
128+
129+def query(kg, question:str, messages:list, model="gpt-4-1106-preview") -> str:
130+ # Build system message
131+ if len(messages) == 0:
132+ # graph schema
133+ schema_desc = _graph_schema_to_prompt(kg.schema)
134+ messages.append(
135+ {"role": "system", "content": f"""You are a graph database expert fluent in the Cypher query language
136+ with access to the following knowledge graph: {schema_desc}"""})
137+
138+ # Get an answer
139+ answer = run_conversation(kg.graph, question, messages, model)
140+
141+ # Append answer to conversation
142+ messages.append({"role": "assistant", "content": answer})
143+
144+ return answer
added graphrag_sdk/schema/__init__.py +1 −0
@@ -0,0 +1,1 @@
1+from .schema import Schema
added graphrag_sdk/schema/auto_detect.py +456 −0
@@ -0,0 +1,456 @@
1+import os
2+import json
3+import time
4+import queue
5+import sqlite3
6+import concurrent.futures
7+
8+from graphrag_sdk.prompts import *
9+from openai import OpenAI
10+from sqlalchemy.orm import sessionmaker
11+from sqlalchemy import create_engine, inspect, MetaData, Table, types
12+
13+# Convert from SQLAlchemy type to Python type
14+def sqlalchemy_to_python_type(sqlalchemy_type):
15+ if isinstance(sqlalchemy_type, types.Integer):
16+ return int
17+ elif isinstance(sqlalchemy_type, types.Numeric):
18+ return float
19+ elif isinstance(sqlalchemy_type, types.Float):
20+ return float
21+ elif isinstance(sqlalchemy_type, types.String):
22+ return str
23+ elif isinstance(sqlalchemy_type, types.Text):
24+ return str
25+ elif isinstance(sqlalchemy_type, types.Boolean):
26+ return bool
27+ elif isinstance(sqlalchemy_type, types.Date):
28+ #return 'date'
29+ return str
30+ elif isinstance(sqlalchemy_type, types.DateTime):
31+ #return 'datetime'
32+ return str
33+ elif isinstance(sqlalchemy_type, types.Time):
34+ #return 'time'
35+ return str
36+ elif isinstance(sqlalchemy_type, types.LargeBinary):
37+ #return bytes
38+ return str
39+ elif isinstance(sqlalchemy_type, types.JSON):
40+ #return dict
41+ return str
42+ else:
43+ return 'Unknown Type'
44+
45+# create entity node
46+def create_entity(s, client, model, name:str, columns) -> None:
47+ e = s.add_entity(name)
48+
49+ has_pk = False
50+ for col in columns:
51+ t = sqlalchemy_to_python_type(col['type'])
52+ pk = bool(col['primary_key'])
53+ name = col['name']
54+
55+ if pk:
56+ has_pk = True
57+
58+ e.add_attribute(name, t, unique=pk, mandatory=pk)
59+
60+ # Require each entity to have at least one unique attribute
61+ if has_pk is False:
62+ user_msg = f"""Which of the following attributes is most suitble to identify
63+ a graph node of type: {name} ?
64+ List of attributes: {','.join([col['name'] for col in columns])}
65+ """
66+
67+ response = client.chat.completions.create(
68+ model=model,
69+ messages=[
70+ {"role": "system", "content": FIND_UNIQUE_ATTRIBUTE_PROMPT},
71+ {"role": "user", "content": user_msg}
72+ ]
73+ )
74+
75+ attr = response.choices[0].message.content
76+ attr = e.get_attribute(attr)
77+ attr.unique = True
78+ attr.mandatory = True
79+
80+# Create entity node in addition to a single relation
81+def create_entity_with_relation(s, client, model, name:str, columns, foreign_keys) -> None:
82+ # Remove foreign_keys from columns
83+ for foreign_key in foreign_keys:
84+ for constrained_column in foreign_key['constrained_columns']:
85+ for idx, col in enumerate(columns):
86+ if col['name'] == constrained_column:
87+ del columns[idx]
88+ break
89+
90+ # create entity
91+ create_entity(s, client, model, name, columns)
92+
93+ # Determine relation destination node type
94+ dest = foreign_keys[0]['referred_table']
95+
96+ src = s.get_entity(name)
97+ dest = s.get_entity(dest)
98+
99+ # Get relationship name
100+ user_msg = f"""Suggest a name for a relationship-type connecting
101+ source node of type {src.name} to destination node of type {dest.name}"""
102+
103+ response = client.chat.completions.create(
104+ model=model,
105+ messages=[
106+ {"role": "system", "content": RELATIONSHIP_NAMING_PROMPT},
107+ {"role": "user", "content": user_msg}
108+ ]
109+ )
110+
111+ relatoin_name = response.choices[0].message.content.upper()
112+
113+ # Create relation
114+ s.add_relation(relatoin_name, src, dest)
115+
116+# Create relation between two entities
117+def create_relation(s, name:str, foreign_keys):
118+ src = foreign_keys[0]['referred_table']
119+ dest = foreign_keys[1]['referred_table']
120+
121+ # Get source and destination entities
122+ # (src)-[]->(dest)
123+ src = s.get_entity(src)
124+ dest = s.get_entity(dest)
125+
126+ # Create relation
127+ s.add_relation(name.upper(), src, dest)
128+
129+# Convert SQL table into a node type or a relation
130+def convert_table(s, client, model, tbl, columns, foreign_keys):
131+ # Depending on the number of foreign keys in table
132+ # 0 -> Entity
133+ # 1 -> Entity & Relation
134+ # 2 -> Relation
135+ l = len(foreign_keys)
136+
137+ if l == 0:
138+ create_entity(s, client, model, tbl, columns)
139+ elif l == 1:
140+ pass
141+ create_entity_with_relation(s, client, model, tbl, columns, foreign_keys)
142+ elif l == 2:
143+ pass
144+ create_relation(s, tbl, foreign_keys)
145+ else:
146+ print("can't process table with more then 2 forigen keys")
147+
148+def convert_tables(s, client, model, inspector, table_names):
149+ # Start by converting tabels without foreign keys
150+ for table_name in table_names:
151+ columns = inspector.get_columns(table_name)
152+ foreign_keys = inspector.get_foreign_keys(table_name)
153+ if len(foreign_keys) == 0:
154+ convert_table(s, client, model, table_name, columns, foreign_keys)
155+
156+ # Continue on processing the rest of the tables
157+ for table_name in table_names:
158+ columns = inspector.get_columns(table_name)
159+ foreign_keys = inspector.get_foreign_keys(table_name)
160+ if len(foreign_keys) > 0:
161+ convert_table(s, client, model, table_name, columns, foreign_keys)
162+
163+# Create graph ontology from a set of SQL tables
164+def generate_graph_schema(s, client, model):
165+ # Connect to local SQLite DB
166+ database_file = 'ontology.db'
167+ connection_string = f'sqlite:///{database_file}'
168+
169+ # Create an engine
170+ engine = create_engine(connection_string)
171+
172+ # Verify the connection by connecting to the database
173+ connection = engine.connect()
174+
175+ # Create a configured "Session" class
176+ Session = sessionmaker(bind=engine)
177+
178+ # Create a Session
179+ session = Session()
180+
181+ inspector = inspect(engine)
182+ table_names = inspector.get_table_names()
183+
184+ # Process tabels into schema
185+ convert_tables(s, client, model, inspector, table_names)
186+
187+ # Close the session when done
188+ session.close()
189+
190+ # Close the connection
191+ connection.close()
192+
193+ # Improve relations nameing
194+ #for rel in s.relations:
195+ # r = s.relations[rel]
196+ # user_msg = f"""Suggest a name for a relationship-type connecting
197+ # source node of type {r.src.name} to destination node of type {r.dest.name}"""
198+
199+ # response = client.chat.completions.create(
200+ # model=model,
201+ # messages=[
202+ # {"role": "system", "content": RELATIONSHIP_NAMING_PROMPT},
203+ # {"role": "user", "content": user_msg}
204+ # ]
205+ # )
206+
207+ # old = r.name
208+ # r.name = response.choices[0].message.content.upper()
209+ # print(f"Renamed from {old} to: {r.name}")
210+
211+# OpenAI assistant tool
212+# queue sql statment
213+def run_sql(arg, queue):
214+ sql = arg["sql"]
215+ print(f"SQL: {sql}")
216+
217+ queue.put(sql)
218+
219+# OpenAI available functions
220+available_functions = {
221+ "run_sql": run_sql
222+}
223+
224+# Get OpenAI ontology detection assistant
225+def get_assistant(client, assistant_name, model):
226+ # 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
234+
235+ # Create OpenAI assistant
236+ assistant = client.beta.assistants.create(
237+ name = assistant_name,
238+ instructions = ONTOLOGY_DETECTION_SYSTEM_PROMPT,
239+ model = model,
240+ tools=[{
241+ "type": "function",
242+ "function": {
243+ "name": "run_sql",
244+ "description": "Run SQL statement",
245+ "parameters": {
246+ "type": "object",
247+ "properties": {
248+ "sql": {"type": "string", "description": "SQL statement"}
249+ },
250+ "required": ["sql"]
251+ }
252+ }
253+ }]
254+ )
255+
256+ # Save assistant ID to local file
257+ with open("./ONTOLOGY_ASSISTANT_ID", 'w') as f:
258+ f.write(assistant.id)
259+
260+ return assistant
261+
262+# Start an interaction with OpenAI assistant
263+def initiate_interaction(client, assistant, user_message):
264+ run = client.beta.threads.create_and_run(
265+ assistant_id=assistant.id,
266+ thread={ "messages": [ {"role": "user", "content": user_message} ] }
267+ )
268+
269+ return run
270+
271+# OpenAI run handler
272+def handle_run(client, run, queue):
273+ while True:
274+ run = client.beta.threads.runs.retrieve(thread_id=run.thread_id, run_id=run.id)
275+
276+ if run.status == "completed":
277+ print("Done processing document")
278+ return
279+
280+ if run.status == "expired":
281+ print(f"Processing expired")
282+ return
283+
284+ if run.status == "cancelling" or run.status == "cancelled" or run.status == "failed":
285+ print(f"Processing failed")
286+ return
287+
288+ # wait for run to complete
289+ if run.status == "queued":
290+ time.sleep(1)
291+ continue
292+
293+ if run.status == "in_progress":
294+ last_step_id = None
295+ run_steps = []
296+ run_steps = client.beta.threads.runs.steps.list(thread_id=run.thread_id, run_id=run.id)
297+
298+ for step in run_steps.data:
299+ if step.status == "in_progress":
300+ step_details = step.step_details
301+ if step_details.type == "tool_calls":
302+ for tool_call in step_details.tool_calls:
303+ try:
304+ if tool_call.type == "function":
305+ func = tool_call.function
306+ func_name = func.name
307+ args = func.arguments
308+ args = json.loads(args)
309+ f = available_functions[func_name]
310+ f(args, queue)
311+ except:
312+ print(f"tool_call: {tool_call}")
313+ pass
314+
315+ last_step_id = run_steps.last_id
316+
317+ time.sleep(1)
318+ continue
319+
320+ if run.status == "requires_action":
321+ action = run.required_action
322+ if action.type == "submit_tool_outputs":
323+ tool_outputs = action.submit_tool_outputs
324+ outputs = []
325+ for tool in tool_outputs.tool_calls:
326+ tool_call_id = tool.id
327+ tool_type = tool.type
328+ func = tool.function
329+ func_name = func.name
330+ args = func.arguments
331+ args = json.loads(args)
332+
333+ f = available_functions[func_name]
334+ f(args, queue)
335+
336+ outputs.append({ "tool_call_id": tool_call_id, "output": "OK" })
337+
338+ # respond to action
339+ run = client.beta.threads.runs.submit_tool_outputs(
340+ thread_id=run.thread_id,
341+ run_id=run.id,
342+ tool_outputs=outputs
343+ )
344+
345+ continue
346+
347+# process source
348+# present content to LLM for graph ontology detection
349+def process_source(client, assistant, src, queue):
350+ text = src.load()[:32000]
351+ user_message = "Extract schema from following text:" + text
352+
353+ run = initiate_interaction(client, assistant, user_message)
354+
355+ handle_run(client, run, queue)
356+
357+ client.beta.threads.delete(run.thread_id)
358+
359+# Detect graph ontology from a set of sources
360+def schema_auto_detect(schema, sources, model="gpt-3.5-turbo-0125"):
361+ client = OpenAI()
362+
363+ # Get assistant
364+ assistant = get_assistant(client, "ontology detection", model)
365+
366+ # Create a new local SQLite DB
367+ db_file = "ontology.db"
368+ if os.path.exists(db_file):
369+ os.remove(db_file)
370+
371+ # Process sources
372+ q = queue.Queue()
373+ with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
374+ tasks = []
375+ # extract entities and relationships from each page
376+ for src in sources:
377+ task = executor.submit(process_source, client, assistant, src, q)
378+
379+ # Wait for all tasks to complete
380+ concurrent.futures.wait(tasks)
381+
382+ # Collect duplicated CREATE statments
383+ n = q.qsize()
384+ tables = {}
385+ for i in range(n):
386+ stmt = q.get()
387+ print(f"sql: {stmt}")
388+
389+ # group by table name
390+ # CREATE TABLE MoviePersonnel (
391+ s = stmt.index("CREATE TABLE ") + len("CREATE TABLE ")
392+ e = stmt.index("(") - 1
393+ tbl = stmt[s:e]
394+ print(f"tbl: {tbl}")
395+
396+ if tbl not in tables:
397+ tables[tbl] = []
398+ tables[tbl].append(stmt)
399+
400+ # Merge duplicated create table statments
401+ for k in tables:
402+ while len(tables[k]) > 1:
403+ user_msg = f"""Merge to following two SQL CREATE TABLE statments:
404+ 1. {tables[k].pop()}
405+ 2. {tables[k].pop()}
406+ """
407+
408+ response = client.chat.completions.create(
409+ model=model,
410+ messages=[
411+ {"role": "system", "content": SQL_FOLDING_PROMPT},
412+ {"role": "user", "content": user_msg}
413+ ]
414+ )
415+
416+ merged_stmt = response.choices[0].message.content
417+ print(f"merged_stmt: {merged_stmt}")
418+ tables[k].append(merged_stmt)
419+
420+ # Switch back from dict to array
421+ tables = [tables[x][0] for x in tables]
422+
423+ # execute SQL statments
424+ con = sqlite3.connect(db_file)
425+ cur = con.cursor()
426+
427+ for stmt in tables:
428+ print(f"Executing: {stmt}")
429+ cur.execute(stmt)
430+ con.commit()
431+
432+ # Remove esoteric columns
433+ #for i, stmt in enumerate(tables):
434+ # user_msg = f"""Remove less descriptive columns from the following
435+ # CREATE TABLE SQL statment: {stmt}"""
436+
437+ # response = client.chat.completions.create(
438+ # model=model,
439+ # messages=[
440+ # {"role": "system", "content": SQL_FOCUS_PROMPT},
441+ # {"role": "user", "content": user_msg}
442+ # ]
443+ # )
444+
445+ # refined_stmt = response.choices[0].message.content
446+ # if not refined_stmt.startswith("CREATE TABLE"):
447+ # refined_stmt = stmt
448+
449+ # print(f"refined_stmt: {refined_stmt}")
450+ # tables[i] = refined_stmt
451+
452+ cur.close()
453+ con.close()
454+
455+ # generate schema
456+ generate_graph_schema(schema, client, model)
added graphrag_sdk/schema/decoder.py +80 −0
@@ -0,0 +1,80 @@
1+import builtins
2+from .entity import Entity
3+from json import JSONDecoder
4+
5+# Decode Schema from JSON
6+class SchemaDecoder():
7+ def from_JSON(self, schema, json:str):
8+ # Validate argument
9+ if not isinstance(json, str) or json == "":
10+ raise Exception("Unable to decode schema, make sure data is a none empty string")
11+
12+ return self.decode(schema, JSONDecoder().decode(json))
13+
14+ # Create Schema from dict
15+ def decode(self, schema, data:dict):
16+ if not isinstance(data, dict):
17+ raise Exception("Unable to decode schema, make sure data is a dict")
18+
19+ # Validate JSON schema structure
20+ if 'entities' not in data or 'relations' not in data:
21+ raise Exception("Invalid schema format")
22+
23+ entities = data['entities']
24+ relations = data['relations']
25+
26+ # Decode entities
27+ for e in entities:
28+ name, attributes = self._entity_decode(e)
29+ e = schema.add_entity(name)
30+ for attr in attributes:
31+ e.add_attribute(attr['name'], attr['type'], attr['desc'], attr['unique'], attr['mandatory'])
32+
33+ # Decode relations
34+ for r in relations:
35+ # Validate relation
36+ if not isinstance(r, dict):
37+ raise Exception("Invalid argument, expecting dict")
38+ if 'name' not in r:
39+ raise Exception("Invalid Relation format, missing 'name'")
40+ if 'src' not in r:
41+ raise Exception("Invalid Relation format, missing 'src'")
42+ if 'dest' not in r:
43+ raise Exception("Invalid Relation format, missing 'dest'")
44+
45+ src = r['src']
46+ dest = r['dest']
47+ name = r['name']
48+
49+ src = schema.get_entity(src)
50+ dest = schema.get_entity(dest)
51+
52+ if src is None:
53+ raise Exception(f"Missing src entity {r['src']}")
54+ if dest is None:
55+ raise Exception(f"Missing dest entity {r['dest']}")
56+
57+ schema.add_relation(name, src, dest)
58+
59+ return schema
60+
61+ # Load Entity from dict
62+ # see entityEncode generated structure
63+ def _entity_decode(self, raw: dict):
64+ if not isinstance(raw, dict):
65+ raise Exception("Invalid argument, expecting dict")
66+ if 'name' not in raw:
67+ raise Exception("Invalid format, missing 'name'")
68+ if 'attributes' not in raw:
69+ raise Exception("Invalid format, missing 'attributes'")
70+
71+ name = raw['name']
72+ attributes = raw['attributes']
73+
74+ for attr in attributes:
75+ if 'name' not in attr or 'type' not in attr or 'unique' not in attr:
76+ raise Exception("Invalid format, attribute must include a 'name', 'type' and 'unique' fields")
77+
78+ attr['type'] = getattr(builtins, attr['type'])
79+
80+ return name, attributes
added graphrag_sdk/schema/encoder.py +45 −0
@@ -0,0 +1,45 @@
1+from json import JSONEncoder
2+
3+# Encode Schema into JSON
4+class SchemaEncoder():
5+ # encode schema to JSON string
6+ def to_JSON(self, schema) -> str:
7+ return JSONEncoder().encode(self.encode(schema))
8+
9+ # encode schema as dict
10+ def encode(self, schema) -> dict:
11+ # Make sure schema is valid
12+ schema.validate()
13+
14+ dict = {'entities': [], 'relations': []}
15+
16+ for e in schema.entities:
17+ e = schema.entities[e]
18+ dict['entities'].append(self._encode_entity(e))
19+
20+ for r in schema.relations:
21+ r = schema.relations[r]
22+ dict['relations'].append(self._encode_relation(r))
23+
24+ return dict
25+
26+ # Dump Entity into a dict
27+ # format:
28+ # {'name': name,
29+ # 'attributes': [
30+ # {'name': attr_name,
31+ # 'type': attr_type,
32+ # 'unique': attr_unique},...
33+ # ]
34+ # }
35+ def _encode_entity(self, e):
36+ dict = {'name': e.name, 'attributes': []}
37+
38+ for attr in e.attributes:
39+ dict['attributes'].append({'name': attr.name, 'type': attr.type.__name__, 'desc': attr.desc, 'unique': attr.unique, 'mandatory': attr.mandatory})
40+
41+ return dict
42+
43+ # Dump Relation into dict
44+ def _encode_relation(self, r):
45+ return {'name': r.name, 'src': r.src.name, 'dest': r.dest.name}
added graphrag_sdk/schema/entity.py +129 −0
@@ -0,0 +1,129 @@
1+class Attribute(object):
2+ def __init__(self, name:str, type:type, desc=None, unique=False, mandatory=False):
3+ self.name = name
4+ self.type = type
5+ self.desc = desc
6+ self.unique = unique
7+ self.mandatory = mandatory
8+
9+ def __eq__(self, other) -> bool:
10+ if not isinstance(other, Attribute):
11+ return False
12+
13+ return (self.name == other.name and
14+ self.type == other.type and
15+ self.desc == other.desc and
16+ self.unique == other.unique and
17+ self.mandatory == other.mandatory)
18+
19+ def __lt__(self, other):
20+ return self.name < other.name
21+
22+ def __hash__(self) -> int:
23+ return hash(self.name)
24+
25+class Entity(object):
26+ """
27+ Represents an ontolegy entity
28+ """
29+
30+ def __init__(self, name:str):
31+ """
32+ Initialize Entity
33+
34+ Parameters:
35+ name (str): name of entity
36+ """
37+
38+ if not isinstance(name, str) or name == "":
39+ raise Exception("Entity name must be a none empty string")
40+
41+ self.name = name
42+ self.attributes = set([])
43+
44+ def __eq__(self, other) -> bool:
45+ if not isinstance(other, Entity):
46+ return False
47+
48+ return (self.name == other.name and self.attributes == other.attributes)
49+
50+ def add_attribute(self, name:str, type:type, desc:str|None=None, unique:bool=False, mandatory:bool=False) -> None:
51+ """
52+ Add attribute to entity
53+
54+ Parameters:
55+ name (str): attribute name
56+ type (type): attribute type
57+ desc (str): short description for attribute
58+ unique (bool): is the attribute value unique
59+ mandatory (bool): is the attribute mandatory
60+ """
61+
62+ # Validate arguments
63+ if not isinstance(name, str) or name == "":
64+ raise Exception("Attribute name must be a none empty string")
65+ #if not isinstance(type, type) or type not in [int, str, bool]:
66+ if type not in [int, float, str, bool]:
67+ raise Exception("Attribute type must be one of the supported types")
68+ if not isinstance(unique, bool):
69+ raise Exception("primary_key must be of type bool")
70+ if name in self.attributes:
71+ raise Exception(f"Entity already contains attribute: {name}")
72+ if isinstance(desc, str) and desc == "":
73+ raise Exception(f"Invalid argument, desc should be a non empty string")
74+
75+ desc = f"{self.name}'s {name}" if desc is None else desc
76+ self.attributes.add(Attribute(name, type, desc, unique, mandatory))
77+
78+ def remove_attribute(self, name:str) ->None:
79+ """
80+ Remove attribute from entity
81+
82+ Parameters:
83+ name (str): name of attribute to remove
84+ """
85+
86+ # Validate argument
87+ if not isinstance(name, str) or name == "":
88+ raise Exception("Attribute name must be a none empty string")
89+
90+ for attr in self.attributes:
91+ if attr.name == name:
92+ self.attributes.remove(attr)
93+ return
94+
95+ def get_attribute(self, name:str) -> Attribute|None:
96+ """
97+ Get attribute
98+
99+ Parameters:
100+ name (str): name of attribute to get
101+
102+ Returns:
103+ attribute
104+ """
105+
106+ # Validate argument
107+ if not isinstance(name, str) or name == "":
108+ raise Exception("Attribute name must be a none empty string")
109+
110+ for attr in self.attributes:
111+ if attr.name == name:
112+ return attr
113+
114+ return None
115+
116+ def unique_attributes(self) -> list[Attribute]:
117+ """
118+ Get a list of Entity's unique attributes
119+
120+ Returns:
121+ list of unique attributes
122+ """
123+
124+ unique_attrs = []
125+ for attr in self.attributes:
126+ if attr.unique:
127+ unique_attrs.append(attr)
128+
129+ return sorted(unique_attrs)
added graphrag_sdk/schema/from_graph.py +48 −0
@@ -0,0 +1,48 @@
1+from falkordb import Graph
2+from .entity import Entity
3+from .relation import Relation
4+
5+import builtins
6+
7+# Create a schema from an ontology graph
8+def schema_from_graph(s, g:Graph):
9+ # Validate arguments
10+ if not isinstance(g, Graph):
11+ raise Exception("Invalid argument, g is expected to be a Graph")
12+
13+ # Fetch entities
14+ q = "MATCH (n) RETURN n"
15+ res = g.query(q).result_set
16+
17+ for row in res:
18+ n = row[0]
19+ name = n.labels[0]
20+
21+ e = s.add_entity(name)
22+ for prop in n.properties:
23+ name = prop
24+ prop = n.properties[prop]
25+
26+ type = getattr(builtins, prop[0])
27+ desc = prop[1]
28+ unique = prop[2]
29+ mandatory = prop[3]
30+
31+ e.add_attribute(name, type, desc, unique, mandatory)
32+
33+ # Fetch relations
34+ q = "MATCH (src)-[e]->(dest) RETURN src, e, dest"
35+ res = g.query(q).result_set
36+
37+ for row in res:
38+ src = row[0].labels[0]
39+ r = row[1].relation
40+ dest = row[2].labels[0]
41+
42+ src = s.get_entity(src)
43+ dest = s.get_entity(dest)
44+
45+ s.add_relation(r, src, dest)
46+
47+ # Make sure schema is valid
48+ s.validate()
added graphrag_sdk/schema/functions_gen.py +74 −0
@@ -0,0 +1,74 @@
1+from .schema import Schema
2+from .entity import Entity
3+from .relation import Relation
4+
5+def relation_to_create_func(r:Relation):
6+ src_lbl = r.src.name
7+ dest_lbl = r.dest.name
8+ func_name = r.name
9+
10+ func = f"def {r.name}(args):\n" # def MovieStream(args):
11+ func += "\targs = remove_none_values(args)\n" # args = remove_none_values(args)
12+
13+ # extract required src arguments
14+ src_attrs = r.src.unique_attributes()
15+
16+ # extract required dest arguments
17+ func += "\tq = \"MERGE (s:" + src_lbl + " {"
18+ func += ", ".join([f"{attr.name}: " + f"${attr.name}" for attr in src_attrs])
19+ func += "}) "
20+
21+ # extract required src arguments
22+ dest_attrs = r.dest.unique_attributes()
23+
24+ func += "MERGE (d:" + dest_lbl + " {"
25+ func += ", ".join([f"{attr.name}: " + f"${attr.name}" for attr in dest_attrs])
26+ func += "}) "
27+
28+ func += "MERGE (s)-[r:" + r.name + "]->(d)\"\n"
29+
30+ # construct query params
31+ func += "\tparams = {"
32+ func += ", ".join([f"'{attr.name}': args['{attr.name}']" for attr in src_attrs])
33+ func += ", "
34+ func += ", ".join([f"'{attr.name}': args['{attr.name}']" for attr in dest_attrs])
35+ func += "}\n"
36+
37+ func += "\tg.query(q, params)\n"
38+
39+ return (func_name, func)
40+
41+def entity_to_create_func(e:Entity):
42+ func_name = f"Create_{e.name}" # Create_Actor
43+ func = f"def {func_name}(args):\n" # def Create_Actor(args):
44+
45+ func += "\targs = remove_none_values(args)\n"
46+ func += "\tquery = \"MERGE (n:" + e.name + " {" # query = "MERGE (n:Actor {
47+
48+ unique_attributes = e.unique_attributes()
49+
50+ func += ", ".join([f"{attr.name}: ${attr.name}" for attr in unique_attributes]) + "})"
51+ func += " SET n += $args\"\n"
52+
53+ func += "\tparams = {"
54+ func += ", ".join([f"'{attr.name}': args['{attr.name}']" for attr in unique_attributes])
55+ func += ", 'args': args}\n"
56+
57+ func += "\tg.query(query, params)\n"
58+
59+ return (func_name, func)
60+
61+def schema_to_functions(s:Schema):
62+ if not isinstance(s, Schema):
63+ raise Exception("Invalid argument, expecting a Schema object")
64+
65+ functions = []
66+ for e in s.entities:
67+ func = entity_to_create_func(s.entities[e])
68+ functions.append(func)
69+
70+ for r in s.relations:
71+ func = relation_to_create_func(s.relations[r])
72+ functions.append(func)
73+
74+ return functions
added graphrag_sdk/schema/relation.py +28 −0
@@ -0,0 +1,28 @@
1+from .entity import Entity
2+
3+# Represents an ontolegy relation
4+# A relation is composed of:
5+# 1. name
6+# 2. src entity
7+# 3. destination entity
8+class Relation(object):
9+ def __init__(self, name:str, src:Entity, dest:Entity):
10+ # Validate arguments
11+ if not isinstance(name, str) or name == "":
12+ raise Exception("Relation name must be a none empty string")
13+ if not isinstance(src, Entity):
14+ raise Exception("src must be am entity")
15+ if not isinstance(dest, Entity):
16+ raise Exception("dest must be am entity")
17+
18+ self.src = src
19+ self.dest = dest
20+ self.name = name
21+
22+ def __eq__(self, other) -> bool:
23+ if not isinstance(other, Relation):
24+ return False
25+
26+ return (self.src == other.src and
27+ self.dest == other.dest and
28+ self.name == other.name)
added graphrag_sdk/schema/schema.py +216 −0
@@ -0,0 +1,216 @@
1+from falkordb import Graph
2+from graphrag_sdk.source import AbstractSource
3+from .entity import Entity
4+from .relation import Relation
5+from .encoder import SchemaEncoder
6+from .decoder import SchemaDecoder
7+from .to_graph import schema_to_graph
8+from .from_graph import schema_from_graph
9+from .auto_detect import schema_auto_detect
10+
11+class Schema(object):
12+ """
13+ Knowledge Graph schema (ontology)
14+ The schema captures entities types in addition to their attributes
15+ and the relationship types between the them
16+ """
17+
18+ def __init__(self):
19+ """
20+ Initialize Schema
21+ """
22+
23+ self.entities = {}
24+ self.relations = {}
25+
26+ def __eq__(self, other) -> bool:
27+ if not isinstance(other, Schema):
28+ return False
29+
30+ if self.entities != other.entities:
31+ return False
32+
33+ if self.relations != other.relations:
34+ return False
35+
36+ return True
37+
38+
39+ def add_entity(self, name:str) -> Entity:
40+ """
41+ Add a new entity to schema
42+
43+ Parameters:
44+ name (str): Entity name.
45+
46+ Returns:
47+ entity
48+ """
49+
50+ # Validate arguments
51+ if not isinstance(name, str) or name == "":
52+ raise Exception(f"Invalid name argument, expecting none empty string")
53+ if name in self.entities:
54+ raise Exception(f"Entity {name} already exists")
55+
56+ e = Entity(name)
57+ self.entities[name] = e
58+ return e
59+
60+ def get_entity(self, name:str) -> Entity | None:
61+ """
62+ Get an entity from schema
63+
64+ Returns:
65+ entity
66+ """
67+
68+ if not isinstance(name, str) or name == "":
69+ raise Exception("Invalid argument, name should be a none empty string")
70+
71+ if name in self.entities:
72+ return self.entities[name]
73+ else:
74+ return None
75+
76+ def add_relation(self, name:str, src:Entity, dest:Entity) -> Relation:
77+ """
78+ Add a relationship to schema
79+
80+ Returns:
81+ relation
82+ """
83+
84+ # Validate arguments
85+ if not isinstance(src, Entity) and not isinstance(src, str):
86+ raise Exception(f"Invalid argument, src is expected to be either a string or an Entity")
87+ if not isinstance(dest, Entity) and not isinstance(dest, str):
88+ raise Exception(f"Invalid argument, dest is expected to be either a string or an Entity")
89+ if not isinstance(name, str) or name == "":
90+ raise Exception(f"Invalid name argument, expecting none empty string")
91+
92+ if isinstance(src, str) and src == "":
93+ raise Exception(f"Invalid src argument, expecting a non empty string")
94+ if isinstance(dest, str) and dest == "":
95+ raise Exception(f"Invalid dest argument, expecting a non empty string")
96+
97+ if name in self.relations:
98+ raise Exception(f"Relation {name} already exists")
99+
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+ # Both src and dest must have at least one unique attribute
107+ if len(src.unique_attributes()) == 0:
108+ raise Exception(f"{src.name} must have at least one unique attribute")
109+ if len(dest.unique_attributes()) == 0:
110+ raise Exception(f"{dest.name} must have at least one unique attribute")
111+
112+ # Create relation and add it to schema
113+ r = Relation(name, src, dest)
114+ self.relations[name] = r
115+
116+ return r
117+
118+ def validate(self) -> bool:
119+ """
120+ Validate schema
121+
122+ Returns:
123+ True if schema is valid
124+ """
125+
126+ # Make sure each Relation reference existing Entities
127+ # And each referenced entity has at least one unique attribute
128+ for r in self.relations:
129+ r = self.relations[r]
130+ src = r.src.name
131+ dest = r.dest.name
132+ if src not in self.entities:
133+ raise Exception(f"Relation {r.name} reference a none existing entity {src}")
134+ if dest not in self.entities:
135+ raise Exception(f"Relation {r.name} reference a none existing entity {dest}")
136+
137+ src = self.entities[src]
138+ if len(src.unique_attributes()) == 0:
139+ raise Exception(f"Relation {r.name} src endpoint {src.name} is missing a unique attribute")
140+
141+ dest = self.entities[dest]
142+ if len(dest.unique_attributes()) == 0:
143+ raise Exception(f"Relation {r.name} src endpoint {dest.name} is missing a unique attribute")
144+
145+ return True
146+
147+ def save_graph(self, g:Graph) -> None:
148+ """
149+ Save schema as an ontology graph
150+
151+ Parameters:
152+ g (Graph): graph to create
153+ """
154+
155+ schema_to_graph(self, g)
156+
157+ def to_JSON(self) -> str:
158+ """
159+ Encode schema to JSON string
160+
161+ Returns:
162+ JSON representation of schema
163+ """
164+
165+ encoder = SchemaEncoder()
166+ return encoder.to_JSON(self)
167+
168+ @classmethod
169+ def from_graph(cls, g:Graph) -> 'Schema':
170+ """
171+ Create a schema from an ontology graph
172+
173+ Parameters:
174+ g (Graph): ontology graph to load
175+
176+ Returns:
177+ Schema: schema
178+ """
179+
180+ s = cls()
181+ schema_from_graph(s, g)
182+ return s
183+
184+ @classmethod
185+ def auto_detect(cls, sources: list[AbstractSource], model="gpt-3.5-turbo-0125") -> 'Schema':
186+ """
187+ Auto detect schema from sources
188+
189+ Parameters:
190+ sources (list[AbstractSource]): list of sources to extract schema from
191+ model (str): OpenAI model to use
192+
193+ Returns:
194+ Schema: schema
195+ """
196+
197+ s = cls()
198+ schema_auto_detect(s, sources, model)
199+ return s
200+
201+ @classmethod
202+ def from_JSON(cls, json:str) -> 'Schema':
203+ """
204+ Create a schema from JSON
205+
206+ Parameters:
207+ json (str): the output from to_JSON
208+
209+ Returns:
210+ Schema: schema
211+ """
212+
213+ s = cls()
214+ decoder = SchemaDecoder()
215+ decoder.from_JSON(s, json)
216+ return s
added graphrag_sdk/schema/to_graph.py +54 −0
@@ -0,0 +1,54 @@
1+from falkordb import Graph
2+from .entity import Entity
3+from .relation import Relation
4+
5+# Save schema as graph
6+def schema_to_graph(s, g:Graph) -> None:
7+ # Validate arguments
8+ if not isinstance(g, Graph):
9+ raise Exception("Invalid argument, g is expected to be a Graph")
10+
11+ # Make sure schema is valid
12+ s.validate()
13+
14+ # Clear graph
15+ try:
16+ g.delete()
17+ except:
18+ pass
19+
20+ # Create graph entities
21+ entity_ids = {}
22+ for e in s.entities:
23+ e = s.entities[e]
24+
25+ # Construct entity creation query
26+ q = f"""CREATE (n:{e.name})
27+ SET n = $args
28+ RETURN ID(n)"""
29+
30+ # Build query arguments
31+ args = {}
32+ for attr in e.attributes:
33+ args[attr.name] = [attr.type.__name__, attr.desc, attr.unique, attr.mandatory]
34+
35+ # Run query and get entity id
36+ id = g.query(q, params={'args': args}).result_set[0][0]
37+
38+ # Save
39+ entity_ids[e.name] = id
40+
41+ # Create graph relations
42+ for r in s.relations:
43+ r = s.relations[r]
44+
45+ # Construct relationship creation query
46+ q = f"""MATCH (src), (dest)
47+ WHERE ID(src) = $src AND ID(dest) = $dest
48+ CREATE (src)-[:{r.name}]->(dest)"""
49+
50+ # Build query arguments
51+ args = {'src': entity_ids[r.src.name], 'dest':entity_ids[r.dest.name]}
52+
53+ # Run query and get entity id
54+ g.query(q, params=args)
added graphrag_sdk/schema/tools_gen.py +138 −0
@@ -0,0 +1,138 @@
1+from .entity import Entity
2+from .schema import Schema
3+from .relation import Relation
4+
5+def type_mapping(t) -> str:
6+ if t not in [str, int, float, bool]:
7+ raise Exception(f"Unsupported type: {t.__name__}")
8+
9+ if t == str:
10+ return "string"
11+ elif t == bool:
12+ return "boolean"
13+ else:
14+ return "number"
15+
16+def relation_to_tool(r:Relation):
17+ # {
18+ # "type": "function",
19+ # "function": {
20+ # "name": "directed",
21+ # "description": "Form a connection between a director and a movie",
22+ # "parameters": {
23+ # "type": "object",
24+ # "properties": {
25+ # "src": {"type": "string", "description": "director's name"},
26+ # "dest": {"type": "string", "description": "movie's title"}
27+ # },
28+ # "required": ["src", "dest"]
29+ # }
30+ # }
31+ # }
32+
33+ src = r.src
34+ dest = r.dest
35+
36+ tool = {}
37+ tool['type'] = "function"
38+ tool['function'] = {}
39+ tool['function']['name'] = r.name
40+ tool['function']['description'] = "Form a connection between " + src.name + " and " + dest.name
41+
42+ tool['function']['parameters'] = {}
43+ tool['function']['parameters']['type'] = "object"
44+ tool['function']['parameters']['properties'] = {}
45+
46+ required = []
47+
48+ # process edge's src
49+ # see if src node has a unique attribute
50+ attrs = src.unique_attributes()
51+ for attr in attrs:
52+ tool['function']['parameters']['properties'][attr.name] = {}
53+ tool['function']['parameters']['properties'][attr.name]['type'] = type_mapping(attr.type)
54+ if attr.desc is not None:
55+ tool['function']['parameters']['properties'][attr.name]['description'] = attr.desc
56+ else:
57+ tool['function']['parameters']['properties'][attr.name]['description'] = src.name + "'s " + attr.name
58+ required.append(attr.name)
59+
60+ # process edge's destination
61+ # see if dest node has a unique attribute
62+ attrs = dest.unique_attributes()
63+ for attr in attrs:
64+ tool['function']['parameters']['properties'][attr.name] = {}
65+ tool['function']['parameters']['properties'][attr.name]['type'] = type_mapping(attr.type)
66+ if attr.desc is not None:
67+ tool['function']['parameters']['properties'][attr.name]['description'] = attr.desc
68+ else:
69+ tool['function']['parameters']['properties'][attr.name]['description'] = dest.name + "'s " + attr.name
70+ required.append(attr.name)
71+
72+ tool['function']['parameters']['required'] = required
73+
74+ return tool
75+
76+def entity_to_tool(e:Entity):
77+ # {
78+ # "type": "function",
79+ # "function": {
80+ # "name": "directed",
81+ # "description": "Form a connection between a director and a movie",
82+ # "parameters": {
83+ # "type": "object",
84+ # "properties": {
85+ # "src": {"type": "string", "description": "director's name"},
86+ # "dest": {"type": "string", "description": "movie's title"}
87+ # },
88+ # "required": ["src", "dest"]
89+ # }
90+ # }
91+ # }
92+
93+ tool = {}
94+ tool['type'] = "function"
95+ tool['function'] = {}
96+
97+ tool['function']['name'] = "Create_" + e.name
98+ tool['function']['description'] = "Create a new " + e.name
99+
100+ tool['function']['parameters'] = {}
101+ tool['function']['parameters']['type'] = "object"
102+ tool['function']['parameters']['properties'] = {}
103+
104+ unique_attributes = []
105+ for attr in e.attributes:
106+ attribute_name = attr.name
107+ attribute_type = type_mapping(attr.type)
108+ attribute_unique = attr.unique
109+
110+ tool['function']['parameters']['properties'][attribute_name] = {}
111+ tool['function']['parameters']['properties'][attribute_name]['type'] = attribute_type
112+ if attr.desc is None:
113+ tool['function']['parameters']['properties'][attribute_name]['description'] = f"{e.name}'s {attr.name}"
114+ else:
115+ tool['function']['parameters']['properties'][attribute_name]['description'] = attr.desc
116+
117+ if attribute_unique:
118+ unique_attributes.append(attribute_name)
119+
120+ tool['function']['parameters']['required'] = unique_attributes
121+
122+ return tool
123+
124+# Create OpenAI tools from schema
125+def schema_to_tools(s:Schema):
126+ if not isinstance(s, Schema):
127+ raise Exception("Invalid argument, expecting a Schema object")
128+
129+ tools = []
130+ for e in s.entities:
131+ tool = entity_to_tool(s.entities[e])
132+ tools.append(tool)
133+
134+ for r in s.relations:
135+ tool = relation_to_tool(s.relations[r])
136+ tools.append(tool)
137+
138+ return tools
added graphrag_sdk/source.py +97 −0
@@ -0,0 +1,97 @@
1+import re
2+import requests
3+from bs4 import BeautifulSoup
4+from abc import ABC, abstractmethod
5+
6+def Source(source:str) ->'AbstractSource':
7+ """
8+ Creates a source object
9+
10+ Parameters:
11+ source (str): path to source
12+
13+ Returns:
14+ AbstractSource: source
15+ """
16+
17+ if not isinstance(source, str) or source == "":
18+ raise Exception("Invalid argument, source should be a none empty string.")
19+
20+ if ".pdf" in source.lower():
21+ return PDF(source)
22+ elif ".html" in source.lower():
23+ return HTML(source)
24+ else:
25+ return TEXT(source)
26+
27+class AbstractSource(ABC):
28+ """
29+ Abstract class representing a source file
30+ """
31+
32+ def __init__(self, source:str):
33+ self.source = source
34+ self.content = None
35+
36+ @abstractmethod
37+ def load(self) -> str:
38+ pass
39+
40+ def __eq__(self, other) -> bool:
41+ if not isinstance(other, AbstractSource):
42+ return False
43+
44+ return self.source == other.source
45+
46+ def __hash__(self):
47+ return hash(self.source)
48+
49+class PDF(AbstractSource):
50+ """
51+ PDF resource
52+ """
53+
54+ def __init__(self, source):
55+ super().__init__(source)
56+
57+ def load(self):
58+ raise Exception("Not implemented")
59+ # extract text from PDF, populate self.content
60+ self.content = None
61+
62+class TEXT(AbstractSource):
63+ """
64+ TEXT resource
65+ """
66+
67+ def __init__(self, source):
68+ super().__init__(source)
69+
70+ def load(self):
71+ if self.content is None:
72+ # populate self.content
73+ with open(self.source, 'r') as f:
74+ self.content = f.read()
75+
76+ return self.content
77+
78+class HTML(AbstractSource):
79+ """
80+ HTML resource
81+ """
82+
83+ def __init__(self, source):
84+ super().__init__(source)
85+
86+ def load(self):
87+ with open(self.source, 'r') as f:
88+ self.content = f.read()
89+
90+ # extract text from HTML, populate self.content
91+ soup = BeautifulSoup(self.content, 'html.parser')
92+
93+ # Extract text from the HTML
94+ self.content = soup.get_text()
95+
96+ # Remove extra newlines
97+ self.content = re.sub(r'\n{2,}', '\n', self.content)
added graphrag_sdk/template.py +153 −0
@@ -0,0 +1,153 @@
1+# template file for entities and relationships extraction using OpenAI assistant
2+# The assistant is equipped with a set of auto generated tools
3+# e.g. Create_Actor, Create_Movie and CAST functions.
4+
5+TEMPLATE = '''import json
6+import time
7+import concurrent.futures
8+from openai import OpenAI
9+from .prompts import KNOWLEDGE_EXTRACTION_SYSTEM_PROMPT
10+from falkordb import FalkorDB
11+
12+g = None # graph
13+client = None # OpenAI client
14+
15+tools = [<TOOLS>]
16+
17+<FUNCTIONS>
18+
19+available_functions = <AVAILABLE_FUNCTIONS>
20+
21+def remove_none_values(args):
22+ return {key: value for key, value in args.items() if value is not None}
23+
24+def create_assistant(client, assistant_name, instructions, model):
25+ assistant = client.beta.assistants.create(
26+ name = assistant_name,
27+ instructions = instructions,
28+ model = model,
29+ tools = tools
30+ )
31+
32+ return assistant
33+
34+def initiate_interaction(client, assistant, user_message):
35+ run = client.beta.threads.create_and_run(
36+ assistant_id=assistant.id,
37+ thread={ "messages": [ {"role": "user", "content": user_message} ] }
38+ )
39+
40+ return run
41+
42+def handle_run(client, run):
43+ while True:
44+ run = client.beta.threads.runs.retrieve(thread_id=run.thread_id, run_id=run.id)
45+
46+ if run.status == "completed":
47+ print("Run completed")
48+ return
49+
50+ if run.status == "expired":
51+ print(f"Run expired")
52+ return
53+
54+ if run.status == "cancelling" or run.status == "cancelled" or run.status == "failed":
55+ print(f"Run failed")
56+ return
57+
58+ # wait for run to complete
59+ if run.status == "queued":
60+ print("Run queued")
61+ time.sleep(1)
62+ continue
63+
64+ if run.status == "in_progress":
65+ last_step_id = None
66+ print("Run in progress")
67+ run_steps = []
68+ # if last_step_id is None:
69+ # run_steps = client.beta.threads.runs.steps.list(thread_id=run.thread_id, run_id=run.id)
70+ # else:
71+ # run_steps = client.beta.threads.runs.steps.list(thread_id=run.thread_id, run_id=run.id, after=last_step_id)
72+ run_steps = client.beta.threads.runs.steps.list(thread_id=run.thread_id, run_id=run.id)
73+
74+ for step in run_steps.data:
75+ if step.status == "in_progress":
76+ step_details = step.step_details
77+ if step_details.type == "tool_calls":
78+ for tool_call in step_details.tool_calls:
79+ try:
80+ if tool_call.type == "function":
81+ func = tool_call.function
82+ func_name = func.name
83+ args = func.arguments
84+ args = json.loads(args)
85+ print(f"Function: {func_name}, {args}")
86+ f = available_functions[func_name]
87+ f(args)
88+ except:
89+ print(f"tool_call: {tool_call}")
90+ pass
91+
92+ last_step_id = run_steps.last_id
93+
94+ time.sleep(1)
95+ continue
96+
97+ if run.status == "requires_action":
98+ print(f"Run requires action")
99+ action = run.required_action
100+ if action.type == "submit_tool_outputs":
101+ tool_outputs = action.submit_tool_outputs
102+ outputs = []
103+ for tool in tool_outputs.tool_calls:
104+ tool_call_id = tool.id
105+ tool_type = tool.type
106+ func = tool.function
107+ func_name = func.name
108+ args = func.arguments
109+ args = json.loads(args)
110+ print(f"Function: {func_name}, {args}")
111+
112+ f = available_functions[func_name]
113+ f(args)
114+
115+ outputs.append({ "tool_call_id": tool_call_id, "output": "OK" })
116+
117+ # respond to action
118+ run = client.beta.threads.runs.submit_tool_outputs(
119+ thread_id=run.thread_id,
120+ run_id=run.id,
121+ tool_outputs=outputs
122+ )
123+
124+ continue
125+
126+def process_source(client, assistant, src):
127+ text = src.load()[:32000]
128+ user_message = f"Extracts entities and relations from the following text: {text}"
129+
130+ run = initiate_interaction(client, assistant, user_message)
131+
132+ handle_run(client, run)
133+
134+ client.beta.threads.delete(run.thread_id)
135+
136+def build_graph_from_sources(kg, client, srcs:set):
137+ global g
138+ g = kg.graph
139+
140+ assistant = create_assistant(client, kg.name, KNOWLEDGE_EXTRACTION_SYSTEM_PROMPT, model=kg.model)
141+
142+ # Create thread pool
143+ with concurrent.futures.ThreadPoolExecutor(max_workers=16) as executor:
144+ tasks = []
145+ # extract entities and relationships from each page
146+ for src in srcs:
147+ task = executor.submit(process_source, client, assistant, src)
148+
149+ # Wait for all tasks to complete
150+ concurrent.futures.wait(tasks)
151+
152+ print("Done")
153+'''
modified pyproject.toml +3 −2
@@ -1,8 +1,9 @@
11 [tool.poetry]
2-name = "GraphRAG-SDK"
2+name = "graphrag_sdk"
33 version = "0.1.0"
4+license = "MIT"
45 description = ""
5-authors = ["Roi Lipman <roi.lipman@falkordb.com>"]
6+authors = ["FalkorDB <info@falkordb.com>"]
67 readme = "README.md"
78 repository = "https://github.com/FalkorDB/GraphRAG-SDK"
89 homepage = "http://RAG-SDK.readthedocs.io"
deleted rag_sdk/Schema/__init__.py +0 −1
@@ -1,1 +0,0 @@
1-from .schema import Schema
deleted rag_sdk/Schema/auto_detect.py +0 −456
@@ -1,456 +0,0 @@
1-import os
2-import json
3-import time
4-import queue
5-import sqlite3
6-import concurrent.futures
7-
8-from rag_sdk.prompts import *
9-from openai import OpenAI
10-from sqlalchemy.orm import sessionmaker
11-from sqlalchemy import create_engine, inspect, MetaData, Table, types
12-
13-# Convert from SQLAlchemy type to Python type
14-def sqlalchemy_to_python_type(sqlalchemy_type):
15- if isinstance(sqlalchemy_type, types.Integer):
16- return int
17- elif isinstance(sqlalchemy_type, types.Numeric):
18- return float
19- elif isinstance(sqlalchemy_type, types.Float):
20- return float
21- elif isinstance(sqlalchemy_type, types.String):
22- return str
23- elif isinstance(sqlalchemy_type, types.Text):
24- return str
25- elif isinstance(sqlalchemy_type, types.Boolean):
26- return bool
27- elif isinstance(sqlalchemy_type, types.Date):
28- #return 'date'
29- return str
30- elif isinstance(sqlalchemy_type, types.DateTime):
31- #return 'datetime'
32- return str
33- elif isinstance(sqlalchemy_type, types.Time):
34- #return 'time'
35- return str
36- elif isinstance(sqlalchemy_type, types.LargeBinary):
37- #return bytes
38- return str
39- elif isinstance(sqlalchemy_type, types.JSON):
40- #return dict
41- return str
42- else:
43- return 'Unknown Type'
44-
45-# create entity node
46-def create_entity(s, client, model, name:str, columns) -> None:
47- e = s.add_entity(name)
48-
49- has_pk = False
50- for col in columns:
51- t = sqlalchemy_to_python_type(col['type'])
52- pk = bool(col['primary_key'])
53- name = col['name']
54-
55- if pk:
56- has_pk = True
57-
58- e.add_attribute(name, t, unique=pk, mandatory=pk)
59-
60- # Require each entity to have at least one unique attribute
61- if has_pk is False:
62- user_msg = f"""Which of the following attributes is most suitble to identify
63- a graph node of type: {name} ?
64- List of attributes: {','.join([col['name'] for col in columns])}
65- """
66-
67- response = client.chat.completions.create(
68- model=model,
69- messages=[
70- {"role": "system", "content": FIND_UNIQUE_ATTRIBUTE_PROMPT},
71- {"role": "user", "content": user_msg}
72- ]
73- )
74-
75- attr = response.choices[0].message.content
76- attr = e.get_attribute(attr)
77- attr.unique = True
78- attr.mandatory = True
79-
80-# Create entity node in addition to a single relation
81-def create_entity_with_relation(s, client, model, name:str, columns, foreign_keys) -> None:
82- # Remove foreign_keys from columns
83- for foreign_key in foreign_keys:
84- for constrained_column in foreign_key['constrained_columns']:
85- for idx, col in enumerate(columns):
86- if col['name'] == constrained_column:
87- del columns[idx]
88- break
89-
90- # create entity
91- create_entity(s, client, model, name, columns)
92-
93- # Determine relation destination node type
94- dest = foreign_keys[0]['referred_table']
95-
96- src = s.get_entity(name)
97- dest = s.get_entity(dest)
98-
99- # Get relationship name
100- user_msg = f"""Suggest a name for a relationship-type connecting
101- source node of type {src.name} to destination node of type {dest.name}"""
102-
103- response = client.chat.completions.create(
104- model=model,
105- messages=[
106- {"role": "system", "content": RELATIONSHIP_NAMING_PROMPT},
107- {"role": "user", "content": user_msg}
108- ]
109- )
110-
111- relatoin_name = response.choices[0].message.content.upper()
112-
113- # Create relation
114- s.add_relation(relatoin_name, src, dest)
115-
116-# Create relation between two entities
117-def create_relation(s, name:str, foreign_keys):
118- src = foreign_keys[0]['referred_table']
119- dest = foreign_keys[1]['referred_table']
120-
121- # Get source and destination entities
122- # (src)-[]->(dest)
123- src = s.get_entity(src)
124- dest = s.get_entity(dest)
125-
126- # Create relation
127- s.add_relation(name.upper(), src, dest)
128-
129-# Convert SQL table into a node type or a relation
130-def convert_table(s, client, model, tbl, columns, foreign_keys):
131- # Depending on the number of foreign keys in table
132- # 0 -> Entity
133- # 1 -> Entity & Relation
134- # 2 -> Relation
135- l = len(foreign_keys)
136-
137- if l == 0:
138- create_entity(s, client, model, tbl, columns)
139- elif l == 1:
140- pass
141- create_entity_with_relation(s, client, model, tbl, columns, foreign_keys)
142- elif l == 2:
143- pass
144- create_relation(s, tbl, foreign_keys)
145- else:
146- print("can't process table with more then 2 forigen keys")
147-
148-def convert_tables(s, client, model, inspector, table_names):
149- # Start by converting tabels without foreign keys
150- for table_name in table_names:
151- columns = inspector.get_columns(table_name)
152- foreign_keys = inspector.get_foreign_keys(table_name)
153- if len(foreign_keys) == 0:
154- convert_table(s, client, model, table_name, columns, foreign_keys)
155-
156- # Continue on processing the rest of the tables
157- for table_name in table_names:
158- columns = inspector.get_columns(table_name)
159- foreign_keys = inspector.get_foreign_keys(table_name)
160- if len(foreign_keys) > 0:
161- convert_table(s, client, model, table_name, columns, foreign_keys)
162-
163-# Create graph ontology from a set of SQL tables
164-def generate_graph_schema(s, client, model):
165- # Connect to local SQLite DB
166- database_file = 'ontology.db'
167- connection_string = f'sqlite:///{database_file}'
168-
169- # Create an engine
170- engine = create_engine(connection_string)
171-
172- # Verify the connection by connecting to the database
173- connection = engine.connect()
174-
175- # Create a configured "Session" class
176- Session = sessionmaker(bind=engine)
177-
178- # Create a Session
179- session = Session()
180-
181- inspector = inspect(engine)
182- table_names = inspector.get_table_names()
183-
184- # Process tabels into schema
185- convert_tables(s, client, model, inspector, table_names)
186-
187- # Close the session when done
188- session.close()
189-
190- # Close the connection
191- connection.close()
192-
193- # Improve relations nameing
194- #for rel in s.relations:
195- # r = s.relations[rel]
196- # user_msg = f"""Suggest a name for a relationship-type connecting
197- # source node of type {r.src.name} to destination node of type {r.dest.name}"""
198-
199- # response = client.chat.completions.create(
200- # model=model,
201- # messages=[
202- # {"role": "system", "content": RELATIONSHIP_NAMING_PROMPT},
203- # {"role": "user", "content": user_msg}
204- # ]
205- # )
206-
207- # old = r.name
208- # r.name = response.choices[0].message.content.upper()
209- # print(f"Renamed from {old} to: {r.name}")
210-
211-# OpenAI assistant tool
212-# queue sql statment
213-def run_sql(arg, queue):
214- sql = arg["sql"]
215- print(f"SQL: {sql}")
216-
217- queue.put(sql)
218-
219-# OpenAI available functions
220-available_functions = {
221- "run_sql": run_sql
222-}
223-
224-# Get OpenAI ontology detection assistant
225-def get_assistant(client, assistant_name, model):
226- # 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
234-
235- # Create OpenAI assistant
236- assistant = client.beta.assistants.create(
237- name = assistant_name,
238- instructions = ONTOLOGY_DETECTION_SYSTEM_PROMPT,
239- model = model,
240- tools=[{
241- "type": "function",
242- "function": {
243- "name": "run_sql",
244- "description": "Run SQL statement",
245- "parameters": {
246- "type": "object",
247- "properties": {
248- "sql": {"type": "string", "description": "SQL statement"}
249- },
250- "required": ["sql"]
251- }
252- }
253- }]
254- )
255-
256- # Save assistant ID to local file
257- with open("./ONTOLOGY_ASSISTANT_ID", 'w') as f:
258- f.write(assistant.id)
259-
260- return assistant
261-
262-# Start an interaction with OpenAI assistant
263-def initiate_interaction(client, assistant, user_message):
264- run = client.beta.threads.create_and_run(
265- assistant_id=assistant.id,
266- thread={ "messages": [ {"role": "user", "content": user_message} ] }
267- )
268-
269- return run
270-
271-# OpenAI run handler
272-def handle_run(client, run, queue):
273- while True:
274- run = client.beta.threads.runs.retrieve(thread_id=run.thread_id, run_id=run.id)
275-
276- if run.status == "completed":
277- print("Done processing document")
278- return
279-
280- if run.status == "expired":
281- print(f"Processing expired")
282- return
283-
284- if run.status == "cancelling" or run.status == "cancelled" or run.status == "failed":
285- print(f"Processing failed")
286- return
287-
288- # wait for run to complete
289- if run.status == "queued":
290- time.sleep(1)
291- continue
292-
293- if run.status == "in_progress":
294- last_step_id = None
295- run_steps = []
296- run_steps = client.beta.threads.runs.steps.list(thread_id=run.thread_id, run_id=run.id)
297-
298- for step in run_steps.data:
299- if step.status == "in_progress":
300- step_details = step.step_details
301- if step_details.type == "tool_calls":
302- for tool_call in step_details.tool_calls:
303- try:
304- if tool_call.type == "function":
305- func = tool_call.function
306- func_name = func.name
307- args = func.arguments
308- args = json.loads(args)
309- f = available_functions[func_name]
310- f(args, queue)
311- except:
312- print(f"tool_call: {tool_call}")
313- pass
314-
315- last_step_id = run_steps.last_id
316-
317- time.sleep(1)
318- continue
319-
320- if run.status == "requires_action":
321- action = run.required_action
322- if action.type == "submit_tool_outputs":
323- tool_outputs = action.submit_tool_outputs
324- outputs = []
325- for tool in tool_outputs.tool_calls:
326- tool_call_id = tool.id
327- tool_type = tool.type
328- func = tool.function
329- func_name = func.name
330- args = func.arguments
331- args = json.loads(args)
332-
333- f = available_functions[func_name]
334- f(args, queue)
335-
336- outputs.append({ "tool_call_id": tool_call_id, "output": "OK" })
337-
338- # respond to action
339- run = client.beta.threads.runs.submit_tool_outputs(
340- thread_id=run.thread_id,
341- run_id=run.id,
342- tool_outputs=outputs
343- )
344-
345- continue
346-
347-# process source
348-# present content to LLM for graph ontology detection
349-def process_source(client, assistant, src, queue):
350- text = src.load()[:32000]
351- user_message = "Extract schema from following text:" + text
352-
353- run = initiate_interaction(client, assistant, user_message)
354-
355- handle_run(client, run, queue)
356-
357- client.beta.threads.delete(run.thread_id)
358-
359-# Detect graph ontology from a set of sources
360-def schema_auto_detect(schema, sources, model="gpt-3.5-turbo-0125"):
361- client = OpenAI()
362-
363- # Get assistant
364- assistant = get_assistant(client, "ontology detection", model)
365-
366- # Create a new local SQLite DB
367- db_file = "ontology.db"
368- if os.path.exists(db_file):
369- os.remove(db_file)
370-
371- # Process sources
372- q = queue.Queue()
373- with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
374- tasks = []
375- # extract entities and relationships from each page
376- for src in sources:
377- task = executor.submit(process_source, client, assistant, src, q)
378-
379- # Wait for all tasks to complete
380- concurrent.futures.wait(tasks)
381-
382- # Collect duplicated CREATE statments
383- n = q.qsize()
384- tables = {}
385- for i in range(n):
386- stmt = q.get()
387- print(f"sql: {stmt}")
388-
389- # group by table name
390- # CREATE TABLE MoviePersonnel (
391- s = stmt.index("CREATE TABLE ") + len("CREATE TABLE ")
392- e = stmt.index("(") - 1
393- tbl = stmt[s:e]
394- print(f"tbl: {tbl}")
395-
396- if tbl not in tables:
397- tables[tbl] = []
398- tables[tbl].append(stmt)
399-
400- # Merge duplicated create table statments
401- for k in tables:
402- while len(tables[k]) > 1:
403- user_msg = f"""Merge to following two SQL CREATE TABLE statments:
404- 1. {tables[k].pop()}
405- 2. {tables[k].pop()}
406- """
407-
408- response = client.chat.completions.create(
409- model=model,
410- messages=[
411- {"role": "system", "content": SQL_FOLDING_PROMPT},
412- {"role": "user", "content": user_msg}
413- ]
414- )
415-
416- merged_stmt = response.choices[0].message.content
417- print(f"merged_stmt: {merged_stmt}")
418- tables[k].append(merged_stmt)
419-
420- # Switch back from dict to array
421- tables = [tables[x][0] for x in tables]
422-
423- # execute SQL statments
424- con = sqlite3.connect(db_file)
425- cur = con.cursor()
426-
427- for stmt in tables:
428- print(f"Executing: {stmt}")
429- cur.execute(stmt)
430- con.commit()
431-
432- # Remove esoteric columns
433- #for i, stmt in enumerate(tables):
434- # user_msg = f"""Remove less descriptive columns from the following
435- # CREATE TABLE SQL statment: {stmt}"""
436-
437- # response = client.chat.completions.create(
438- # model=model,
439- # messages=[
440- # {"role": "system", "content": SQL_FOCUS_PROMPT},
441- # {"role": "user", "content": user_msg}
442- # ]
443- # )
444-
445- # refined_stmt = response.choices[0].message.content
446- # if not refined_stmt.startswith("CREATE TABLE"):
447- # refined_stmt = stmt
448-
449- # print(f"refined_stmt: {refined_stmt}")
450- # tables[i] = refined_stmt
451-
452- cur.close()
453- con.close()
454-
455- # generate schema
456- generate_graph_schema(schema, client, model)
deleted rag_sdk/Schema/decoder.py +0 −80
@@ -1,80 +0,0 @@
1-import builtins
2-from .entity import Entity
3-from json import JSONDecoder
4-
5-# Decode Schema from JSON
6-class SchemaDecoder():
7- def from_JSON(self, schema, json:str):
8- # Validate argument
9- if not isinstance(json, str) or json == "":
10- raise Exception("Unable to decode schema, make sure data is a none empty string")
11-
12- return self.decode(schema, JSONDecoder().decode(json))
13-
14- # Create Schema from dict
15- def decode(self, schema, data:dict):
16- if not isinstance(data, dict):
17- raise Exception("Unable to decode schema, make sure data is a dict")
18-
19- # Validate JSON schema structure
20- if 'entities' not in data or 'relations' not in data:
21- raise Exception("Invalid schema format")
22-
23- entities = data['entities']
24- relations = data['relations']
25-
26- # Decode entities
27- for e in entities:
28- name, attributes = self._entity_decode(e)
29- e = schema.add_entity(name)
30- for attr in attributes:
31- e.add_attribute(attr['name'], attr['type'], attr['desc'], attr['unique'], attr['mandatory'])
32-
33- # Decode relations
34- for r in relations:
35- # Validate relation
36- if not isinstance(r, dict):
37- raise Exception("Invalid argument, expecting dict")
38- if 'name' not in r:
39- raise Exception("Invalid Relation format, missing 'name'")
40- if 'src' not in r:
41- raise Exception("Invalid Relation format, missing 'src'")
42- if 'dest' not in r:
43- raise Exception("Invalid Relation format, missing 'dest'")
44-
45- src = r['src']
46- dest = r['dest']
47- name = r['name']
48-
49- src = schema.get_entity(src)
50- dest = schema.get_entity(dest)
51-
52- if src is None:
53- raise Exception(f"Missing src entity {r['src']}")
54- if dest is None:
55- raise Exception(f"Missing dest entity {r['dest']}")
56-
57- schema.add_relation(name, src, dest)
58-
59- return schema
60-
61- # Load Entity from dict
62- # see entityEncode generated structure
63- def _entity_decode(self, raw: dict):
64- if not isinstance(raw, dict):
65- raise Exception("Invalid argument, expecting dict")
66- if 'name' not in raw:
67- raise Exception("Invalid format, missing 'name'")
68- if 'attributes' not in raw:
69- raise Exception("Invalid format, missing 'attributes'")
70-
71- name = raw['name']
72- attributes = raw['attributes']
73-
74- for attr in attributes:
75- if 'name' not in attr or 'type' not in attr or 'unique' not in attr:
76- raise Exception("Invalid format, attribute must include a 'name', 'type' and 'unique' fields")
77-
78- attr['type'] = getattr(builtins, attr['type'])
79-
80- return name, attributes
deleted rag_sdk/Schema/encoder.py +0 −45
@@ -1,45 +0,0 @@
1-from json import JSONEncoder
2-
3-# Encode Schema into JSON
4-class SchemaEncoder():
5- # encode schema to JSON string
6- def to_JSON(self, schema) -> str:
7- return JSONEncoder().encode(self.encode(schema))
8-
9- # encode schema as dict
10- def encode(self, schema) -> dict:
11- # Make sure schema is valid
12- schema.validate()
13-
14- dict = {'entities': [], 'relations': []}
15-
16- for e in schema.entities:
17- e = schema.entities[e]
18- dict['entities'].append(self._encode_entity(e))
19-
20- for r in schema.relations:
21- r = schema.relations[r]
22- dict['relations'].append(self._encode_relation(r))
23-
24- return dict
25-
26- # Dump Entity into a dict
27- # format:
28- # {'name': name,
29- # 'attributes': [
30- # {'name': attr_name,
31- # 'type': attr_type,
32- # 'unique': attr_unique},...
33- # ]
34- # }
35- def _encode_entity(self, e):
36- dict = {'name': e.name, 'attributes': []}
37-
38- for attr in e.attributes:
39- dict['attributes'].append({'name': attr.name, 'type': attr.type.__name__, 'desc': attr.desc, 'unique': attr.unique, 'mandatory': attr.mandatory})
40-
41- return dict
42-
43- # Dump Relation into dict
44- def _encode_relation(self, r):
45- return {'name': r.name, 'src': r.src.name, 'dest': r.dest.name}
deleted rag_sdk/Schema/entity.py +0 −129
@@ -1,129 +0,0 @@
1-class Attribute(object):
2- def __init__(self, name:str, type:type, desc=None, unique=False, mandatory=False):
3- self.name = name
4- self.type = type
5- self.desc = desc
6- self.unique = unique
7- self.mandatory = mandatory
8-
9- def __eq__(self, other) -> bool:
10- if not isinstance(other, Attribute):
11- return False
12-
13- return (self.name == other.name and
14- self.type == other.type and
15- self.desc == other.desc and
16- self.unique == other.unique and
17- self.mandatory == other.mandatory)
18-
19- def __lt__(self, other):
20- return self.name < other.name
21-
22- def __hash__(self) -> int:
23- return hash(self.name)
24-
25-class Entity(object):
26- """
27- Represents an ontolegy entity
28- """
29-
30- def __init__(self, name:str):
31- """
32- Initialize Entity
33-
34- Parameters:
35- name (str): name of entity
36- """
37-
38- if not isinstance(name, str) or name == "":
39- raise Exception("Entity name must be a none empty string")
40-
41- self.name = name
42- self.attributes = set([])
43-
44- def __eq__(self, other) -> bool:
45- if not isinstance(other, Entity):
46- return False
47-
48- return (self.name == other.name and self.attributes == other.attributes)
49-
50- def add_attribute(self, name:str, type:type, desc:str|None=None, unique:bool=False, mandatory:bool=False) -> None:
51- """
52- Add attribute to entity
53-
54- Parameters:
55- name (str): attribute name
56- type (type): attribute type
57- desc (str): short description for attribute
58- unique (bool): is the attribute value unique
59- mandatory (bool): is the attribute mandatory
60- """
61-
62- # Validate arguments
63- if not isinstance(name, str) or name == "":
64- raise Exception("Attribute name must be a none empty string")
65- #if not isinstance(type, type) or type not in [int, str, bool]:
66- if type not in [int, float, str, bool]:
67- raise Exception("Attribute type must be one of the supported types")
68- if not isinstance(unique, bool):
69- raise Exception("primary_key must be of type bool")
70- if name in self.attributes:
71- raise Exception(f"Entity already contains attribute: {name}")
72- if isinstance(desc, str) and desc == "":
73- raise Exception(f"Invalid argument, desc should be a non empty string")
74-
75- desc = f"{self.name}'s {name}" if desc is None else desc
76- self.attributes.add(Attribute(name, type, desc, unique, mandatory))
77-
78- def remove_attribute(self, name:str) ->None:
79- """
80- Remove attribute from entity
81-
82- Parameters:
83- name (str): name of attribute to remove
84- """
85-
86- # Validate argument
87- if not isinstance(name, str) or name == "":
88- raise Exception("Attribute name must be a none empty string")
89-
90- for attr in self.attributes:
91- if attr.name == name:
92- self.attributes.remove(attr)
93- return
94-
95- def get_attribute(self, name:str) -> Attribute|None:
96- """
97- Get attribute
98-
99- Parameters:
100- name (str): name of attribute to get
101-
102- Returns:
103- attribute
104- """
105-
106- # Validate argument
107- if not isinstance(name, str) or name == "":
108- raise Exception("Attribute name must be a none empty string")
109-
110- for attr in self.attributes:
111- if attr.name == name:
112- return attr
113-
114- return None
115-
116- def unique_attributes(self) -> list[Attribute]:
117- """
118- Get a list of Entity's unique attributes
119-
120- Returns:
121- list of unique attributes
122- """
123-
124- unique_attrs = []
125- for attr in self.attributes:
126- if attr.unique:
127- unique_attrs.append(attr)
128-
129- return sorted(unique_attrs)
deleted rag_sdk/Schema/from_graph.py +0 −48
@@ -1,48 +0,0 @@
1-from falkordb import Graph
2-from .entity import Entity
3-from .relation import Relation
4-
5-import builtins
6-
7-# Create a schema from an ontology graph
8-def schema_from_graph(s, g:Graph):
9- # Validate arguments
10- if not isinstance(g, Graph):
11- raise Exception("Invalid argument, g is expected to be a Graph")
12-
13- # Fetch entities
14- q = "MATCH (n) RETURN n"
15- res = g.query(q).result_set
16-
17- for row in res:
18- n = row[0]
19- name = n.labels[0]
20-
21- e = s.add_entity(name)
22- for prop in n.properties:
23- name = prop
24- prop = n.properties[prop]
25-
26- type = getattr(builtins, prop[0])
27- desc = prop[1]
28- unique = prop[2]
29- mandatory = prop[3]
30-
31- e.add_attribute(name, type, desc, unique, mandatory)
32-
33- # Fetch relations
34- q = "MATCH (src)-[e]->(dest) RETURN src, e, dest"
35- res = g.query(q).result_set
36-
37- for row in res:
38- src = row[0].labels[0]
39- r = row[1].relation
40- dest = row[2].labels[0]
41-
42- src = s.get_entity(src)
43- dest = s.get_entity(dest)
44-
45- s.add_relation(r, src, dest)
46-
47- # Make sure schema is valid
48- s.validate()
deleted rag_sdk/Schema/functions_gen.py +0 −74
@@ -1,74 +0,0 @@
1-from .schema import Schema
2-from .entity import Entity
3-from .relation import Relation
4-
5-def relation_to_create_func(r:Relation):
6- src_lbl = r.src.name
7- dest_lbl = r.dest.name
8- func_name = r.name
9-
10- func = f"def {r.name}(args):\n" # def MovieStream(args):
11- func += "\targs = remove_none_values(args)\n" # args = remove_none_values(args)
12-
13- # extract required src arguments
14- src_attrs = r.src.unique_attributes()
15-
16- # extract required dest arguments
17- func += "\tq = \"MERGE (s:" + src_lbl + " {"
18- func += ", ".join([f"{attr.name}: " + f"${attr.name}" for attr in src_attrs])
19- func += "}) "
20-
21- # extract required src arguments
22- dest_attrs = r.dest.unique_attributes()
23-
24- func += "MERGE (d:" + dest_lbl + " {"
25- func += ", ".join([f"{attr.name}: " + f"${attr.name}" for attr in dest_attrs])
26- func += "}) "
27-
28- func += "MERGE (s)-[r:" + r.name + "]->(d)\"\n"
29-
30- # construct query params
31- func += "\tparams = {"
32- func += ", ".join([f"'{attr.name}': args['{attr.name}']" for attr in src_attrs])
33- func += ", "
34- func += ", ".join([f"'{attr.name}': args['{attr.name}']" for attr in dest_attrs])
35- func += "}\n"
36-
37- func += "\tg.query(q, params)\n"
38-
39- return (func_name, func)
40-
41-def entity_to_create_func(e:Entity):
42- func_name = f"Create_{e.name}" # Create_Actor
43- func = f"def {func_name}(args):\n" # def Create_Actor(args):
44-
45- func += "\targs = remove_none_values(args)\n"
46- func += "\tquery = \"MERGE (n:" + e.name + " {" # query = "MERGE (n:Actor {
47-
48- unique_attributes = e.unique_attributes()
49-
50- func += ", ".join([f"{attr.name}: ${attr.name}" for attr in unique_attributes]) + "})"
51- func += " SET n += $args\"\n"
52-
53- func += "\tparams = {"
54- func += ", ".join([f"'{attr.name}': args['{attr.name}']" for attr in unique_attributes])
55- func += ", 'args': args}\n"
56-
57- func += "\tg.query(query, params)\n"
58-
59- return (func_name, func)
60-
61-def schema_to_functions(s:Schema):
62- if not isinstance(s, Schema):
63- raise Exception("Invalid argument, expecting a Schema object")
64-
65- functions = []
66- for e in s.entities:
67- func = entity_to_create_func(s.entities[e])
68- functions.append(func)
69-
70- for r in s.relations:
71- func = relation_to_create_func(s.relations[r])
72- functions.append(func)
73-
74- return functions
deleted rag_sdk/Schema/relation.py +0 −28
@@ -1,28 +0,0 @@
1-from .entity import Entity
2-
3-# Represents an ontolegy relation
4-# A relation is composed of:
5-# 1. name
6-# 2. src entity
7-# 3. destination entity
8-class Relation(object):
9- def __init__(self, name:str, src:Entity, dest:Entity):
10- # Validate arguments
11- if not isinstance(name, str) or name == "":
12- raise Exception("Relation name must be a none empty string")
13- if not isinstance(src, Entity):
14- raise Exception("src must be am entity")
15- if not isinstance(dest, Entity):
16- raise Exception("dest must be am entity")
17-
18- self.src = src
19- self.dest = dest
20- self.name = name
21-
22- def __eq__(self, other) -> bool:
23- if not isinstance(other, Relation):
24- return False
25-
26- return (self.src == other.src and
27- self.dest == other.dest and
28- self.name == other.name)
deleted rag_sdk/Schema/schema.py +0 −216
@@ -1,216 +0,0 @@
1-from falkordb import Graph
2-from rag_sdk.source import AbstractSource
3-from .entity import Entity
4-from .relation import Relation
5-from .encoder import SchemaEncoder
6-from .decoder import SchemaDecoder
7-from .to_graph import schema_to_graph
8-from .from_graph import schema_from_graph
9-from .auto_detect import schema_auto_detect
10-
11-class Schema(object):
12- """
13- Knowledge Graph schema (ontology)
14- The schema captures entities types in addition to their attributes
15- and the relationship types between the them
16- """
17-
18- def __init__(self):
19- """
20- Initialize Schema
21- """
22-
23- self.entities = {}
24- self.relations = {}
25-
26- def __eq__(self, other) -> bool:
27- if not isinstance(other, Schema):
28- return False
29-
30- if self.entities != other.entities:
31- return False
32-
33- if self.relations != other.relations:
34- return False
35-
36- return True
37-
38-
39- def add_entity(self, name:str) -> Entity:
40- """
41- Add a new entity to schema
42-
43- Parameters:
44- name (str): Entity name.
45-
46- Returns:
47- entity
48- """
49-
50- # Validate arguments
51- if not isinstance(name, str) or name == "":
52- raise Exception(f"Invalid name argument, expecting none empty string")
53- if name in self.entities:
54- raise Exception(f"Entity {name} already exists")
55-
56- e = Entity(name)
57- self.entities[name] = e
58- return e
59-
60- def get_entity(self, name:str) -> Entity | None:
61- """
62- Get an entity from schema
63-
64- Returns:
65- entity
66- """
67-
68- if not isinstance(name, str) or name == "":
69- raise Exception("Invalid argument, name should be a none empty string")
70-
71- if name in self.entities:
72- return self.entities[name]
73- else:
74- return None
75-
76- def add_relation(self, name:str, src:Entity, dest:Entity) -> Relation:
77- """
78- Add a relationship to schema
79-
80- Returns:
81- relation
82- """
83-
84- # Validate arguments
85- if not isinstance(src, Entity) and not isinstance(src, str):
86- raise Exception(f"Invalid argument, src is expected to be either a string or an Entity")
87- if not isinstance(dest, Entity) and not isinstance(dest, str):
88- raise Exception(f"Invalid argument, dest is expected to be either a string or an Entity")
89- if not isinstance(name, str) or name == "":
90- raise Exception(f"Invalid name argument, expecting none empty string")
91-
92- if isinstance(src, str) and src == "":
93- raise Exception(f"Invalid src argument, expecting a non empty string")
94- if isinstance(dest, str) and dest == "":
95- raise Exception(f"Invalid dest argument, expecting a non empty string")
96-
97- if name in self.relations:
98- raise Exception(f"Relation {name} already exists")
99-
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- # Both src and dest must have at least one unique attribute
107- if len(src.unique_attributes()) == 0:
108- raise Exception(f"{src.name} must have at least one unique attribute")
109- if len(dest.unique_attributes()) == 0:
110- raise Exception(f"{dest.name} must have at least one unique attribute")
111-
112- # Create relation and add it to schema
113- r = Relation(name, src, dest)
114- self.relations[name] = r
115-
116- return r
117-
118- def validate(self) -> bool:
119- """
120- Validate schema
121-
122- Returns:
123- True if schema is valid
124- """
125-
126- # Make sure each Relation reference existing Entities
127- # And each referenced entity has at least one unique attribute
128- for r in self.relations:
129- r = self.relations[r]
130- src = r.src.name
131- dest = r.dest.name
132- if src not in self.entities:
133- raise Exception(f"Relation {r.name} reference a none existing entity {src}")
134- if dest not in self.entities:
135- raise Exception(f"Relation {r.name} reference a none existing entity {dest}")
136-
137- src = self.entities[src]
138- if len(src.unique_attributes()) == 0:
139- raise Exception(f"Relation {r.name} src endpoint {src.name} is missing a unique attribute")
140-
141- dest = self.entities[dest]
142- if len(dest.unique_attributes()) == 0:
143- raise Exception(f"Relation {r.name} src endpoint {dest.name} is missing a unique attribute")
144-
145- return True
146-
147- def save_graph(self, g:Graph) -> None:
148- """
149- Save schema as an ontology graph
150-
151- Parameters:
152- g (Graph): graph to create
153- """
154-
155- schema_to_graph(self, g)
156-
157- def to_JSON(self) -> str:
158- """
159- Encode schema to JSON string
160-
161- Returns:
162- JSON representation of schema
163- """
164-
165- encoder = SchemaEncoder()
166- return encoder.to_JSON(self)
167-
168- @classmethod
169- def from_graph(cls, g:Graph) -> 'Schema':
170- """
171- Create a schema from an ontology graph
172-
173- Parameters:
174- g (Graph): ontology graph to load
175-
176- Returns:
177- Schema: schema
178- """
179-
180- s = cls()
181- schema_from_graph(s, g)
182- return s
183-
184- @classmethod
185- def auto_detect(cls, sources: list[AbstractSource], model="gpt-3.5-turbo-0125") -> 'Schema':
186- """
187- Auto detect schema from sources
188-
189- Parameters:
190- sources (list[AbstractSource]): list of sources to extract schema from
191- model (str): OpenAI model to use
192-
193- Returns:
194- Schema: schema
195- """
196-
197- s = cls()
198- schema_auto_detect(s, sources, model)
199- return s
200-
201- @classmethod
202- def from_JSON(cls, json:str) -> 'Schema':
203- """
204- Create a schema from JSON
205-
206- Parameters:
207- json (str): the output from to_JSON
208-
209- Returns:
210- Schema: schema
211- """
212-
213- s = cls()
214- decoder = SchemaDecoder()
215- decoder.from_JSON(s, json)
216- return s
deleted rag_sdk/Schema/to_graph.py +0 −54
@@ -1,54 +0,0 @@
1-from falkordb import Graph
2-from .entity import Entity
3-from .relation import Relation
4-
5-# Save schema as graph
6-def schema_to_graph(s, g:Graph) -> None:
7- # Validate arguments
8- if not isinstance(g, Graph):
9- raise Exception("Invalid argument, g is expected to be a Graph")
10-
11- # Make sure schema is valid
12- s.validate()
13-
14- # Clear graph
15- try:
16- g.delete()
17- except:
18- pass
19-
20- # Create graph entities
21- entity_ids = {}
22- for e in s.entities:
23- e = s.entities[e]
24-
25- # Construct entity creation query
26- q = f"""CREATE (n:{e.name})
27- SET n = $args
28- RETURN ID(n)"""
29-
30- # Build query arguments
31- args = {}
32- for attr in e.attributes:
33- args[attr.name] = [attr.type.__name__, attr.desc, attr.unique, attr.mandatory]
34-
35- # Run query and get entity id
36- id = g.query(q, params={'args': args}).result_set[0][0]
37-
38- # Save
39- entity_ids[e.name] = id
40-
41- # Create graph relations
42- for r in s.relations:
43- r = s.relations[r]
44-
45- # Construct relationship creation query
46- q = f"""MATCH (src), (dest)
47- WHERE ID(src) = $src AND ID(dest) = $dest
48- CREATE (src)-[:{r.name}]->(dest)"""
49-
50- # Build query arguments
51- args = {'src': entity_ids[r.src.name], 'dest':entity_ids[r.dest.name]}
52-
53- # Run query and get entity id
54- g.query(q, params=args)
deleted rag_sdk/Schema/tools_gen.py +0 −138
@@ -1,138 +0,0 @@
1-from .entity import Entity
2-from .schema import Schema
3-from .relation import Relation
4-
5-def type_mapping(t) -> str:
6- if t not in [str, int, float, bool]:
7- raise Exception(f"Unsupported type: {t.__name__}")
8-
9- if t == str:
10- return "string"
11- elif t == bool:
12- return "boolean"
13- else:
14- return "number"
15-
16-def relation_to_tool(r:Relation):
17- # {
18- # "type": "function",
19- # "function": {
20- # "name": "directed",
21- # "description": "Form a connection between a director and a movie",
22- # "parameters": {
23- # "type": "object",
24- # "properties": {
25- # "src": {"type": "string", "description": "director's name"},
26- # "dest": {"type": "string", "description": "movie's title"}
27- # },
28- # "required": ["src", "dest"]
29- # }
30- # }
31- # }
32-
33- src = r.src
34- dest = r.dest
35-
36- tool = {}
37- tool['type'] = "function"
38- tool['function'] = {}
39- tool['function']['name'] = r.name
40- tool['function']['description'] = "Form a connection between " + src.name + " and " + dest.name
41-
42- tool['function']['parameters'] = {}
43- tool['function']['parameters']['type'] = "object"
44- tool['function']['parameters']['properties'] = {}
45-
46- required = []
47-
48- # process edge's src
49- # see if src node has a unique attribute
50- attrs = src.unique_attributes()
51- for attr in attrs:
52- tool['function']['parameters']['properties'][attr.name] = {}
53- tool['function']['parameters']['properties'][attr.name]['type'] = type_mapping(attr.type)
54- if attr.desc is not None:
55- tool['function']['parameters']['properties'][attr.name]['description'] = attr.desc
56- else:
57- tool['function']['parameters']['properties'][attr.name]['description'] = src.name + "'s " + attr.name
58- required.append(attr.name)
59-
60- # process edge's destination
61- # see if dest node has a unique attribute
62- attrs = dest.unique_attributes()
63- for attr in attrs:
64- tool['function']['parameters']['properties'][attr.name] = {}
65- tool['function']['parameters']['properties'][attr.name]['type'] = type_mapping(attr.type)
66- if attr.desc is not None:
67- tool['function']['parameters']['properties'][attr.name]['description'] = attr.desc
68- else:
69- tool['function']['parameters']['properties'][attr.name]['description'] = dest.name + "'s " + attr.name
70- required.append(attr.name)
71-
72- tool['function']['parameters']['required'] = required
73-
74- return tool
75-
76-def entity_to_tool(e:Entity):
77- # {
78- # "type": "function",
79- # "function": {
80- # "name": "directed",
81- # "description": "Form a connection between a director and a movie",
82- # "parameters": {
83- # "type": "object",
84- # "properties": {
85- # "src": {"type": "string", "description": "director's name"},
86- # "dest": {"type": "string", "description": "movie's title"}
87- # },
88- # "required": ["src", "dest"]
89- # }
90- # }
91- # }
92-
93- tool = {}
94- tool['type'] = "function"
95- tool['function'] = {}
96-
97- tool['function']['name'] = "Create_" + e.name
98- tool['function']['description'] = "Create a new " + e.name
99-
100- tool['function']['parameters'] = {}
101- tool['function']['parameters']['type'] = "object"
102- tool['function']['parameters']['properties'] = {}
103-
104- unique_attributes = []
105- for attr in e.attributes:
106- attribute_name = attr.name
107- attribute_type = type_mapping(attr.type)
108- attribute_unique = attr.unique
109-
110- tool['function']['parameters']['properties'][attribute_name] = {}
111- tool['function']['parameters']['properties'][attribute_name]['type'] = attribute_type
112- if attr.desc is None:
113- tool['function']['parameters']['properties'][attribute_name]['description'] = f"{e.name}'s {attr.name}"
114- else:
115- tool['function']['parameters']['properties'][attribute_name]['description'] = attr.desc
116-
117- if attribute_unique:
118- unique_attributes.append(attribute_name)
119-
120- tool['function']['parameters']['required'] = unique_attributes
121-
122- return tool
123-
124-# Create OpenAI tools from schema
125-def schema_to_tools(s:Schema):
126- if not isinstance(s, Schema):
127- raise Exception("Invalid argument, expecting a Schema object")
128-
129- tools = []
130- for e in s.entities:
131- tool = entity_to_tool(s.entities[e])
132- tools.append(tool)
133-
134- for r in s.relations:
135- tool = relation_to_tool(s.relations[r])
136- tools.append(tool)
137-
138- return tools
deleted rag_sdk/__init__.py +0 −2
@@ -1,2 +0,0 @@
1-from .kg import KnowledgeGraph
2-from .source import Source
deleted rag_sdk/kg.py +0 −155
@@ -1,155 +0,0 @@
1-import os
2-import queue
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-class KnowledgeGraph(object):
17- """Knowledge Graph model data as a network of entities and relations
18- To create one it is best to provide a schema which will define the graph's ontology
19- In addition to a set of sources from which entities and relations will be extracted.
20- """
21-
22- def __init__(self, name:str, host:str="127.0.0.1", port:int=6379, username:str|None=None, password:str|None=None,
23- model:str="gpt-4-1106-preview", schema:Schema|None=None):
24- """
25- Initialize Knowledge Graph
26-
27- Parameters:
28- name (str): Knowledge graph name.
29- host (str): FalkorDB hostname.
30- port (int): FalkorDB port number.
31- username (str|None): FalkorDB username.
32- password (str|None): FalkorDB password.
33- model (str): OpenAI model to use.
34- """
35-
36- if not isinstance(name, str) or name == "":
37- raise Exception("name should be a non empty string")
38-
39- # connect to database
40- self.db = FalkorDB(host=host, port=port, username=username, password=password)
41- self.graph = self.db.select_graph(name)
42-
43- self.name = name
44- self.model = model
45- self.schema = schema
46- self.client = None # OpenAI client
47- self.sources = set([])
48- self.ontolegy_ratio = 0.1 # Sampaling ratio for ontolegy detection
49-
50- # in case schema is None
51- # try to load schema from FalkorDB
52- if schema is None:
53- schema_name = self._schema_name()
54- if schema_name in self.db.list_graphs():
55- schema_graph = self.db.select_graph()
56- self.schema = self.schema.from_graph(schema_graph)
57-
58- def list_sources(self) -> list[AbstractSource]:
59- """
60- List of sources associated with knowledge graph
61-
62- Returns:
63- list[AbstractSource]: sources
64- """
65-
66- return [s.source for s in self.sources]
67-
68- def process_sources(self, sources: list[AbstractSource]) -> None:
69- """
70- Add entities and relations found in sources into the knowledge-graph
71-
72- Parameters:
73- sources (list[AbstractSource]): list of sources to extract knowledge from
74- """
75-
76- # Make sure knowledge graph is created.
77- if not 'build_graph_from_sources' in globals() or self.client is None:
78- self._create()
79-
80- # Run assistant
81- result = build_graph_from_sources(self, self.client, sources)
82-
83- # Add processed sources
84- for src in sources:
85- self.sources.add(src)
86-
87- def _schema_name(self) -> str:
88- """
89- Generate a name for the schema based on the Knowledge Graph name
90- """
91-
92- return f"{self.name}_schema"
93-
94- def _createKGWithSchema(self):
95- # Save schema as an ontology graph
96- schema_graph = self.db.select_graph(self._schema_name())
97- self.schema.save_graph(schema_graph)
98-
99- # Create Knowledge Graph construction assistant
100-
101- # Generate assistant's toolings
102- tools = schema_to_tools(self.schema)
103-
104- # Generate functions from schema
105- funcs = schema_to_functions(self.schema)
106- functions_names = [func[0] for func in funcs]
107- functions_impl = [func[1] for func in funcs]
108-
109- # Generate assistant
110- # Generate code from template
111- code = TEMPLATE
112- code = code.replace("<TOOLS>", ",\n".join([str(tool) for tool in tools]))
113- code = code.replace("<GRAPH_ID>", "\"" + self.name + "\"")
114- code = code.replace("<FUNCTIONS>", "\n".join(functions_impl))
115- code = code.replace("<AVAILABLE_FUNCTIONS>", '{' + ",\n".join([f"'{f}': {f}" for f in functions_names]) +'}')
116-
117- # Execute the code string in the global namespace
118- # Introduces the 'build_graph_from_sources' function
119- # TODO: note multiple calls to _createKGWithSchema will overide one another.
120- exec(code, globals())
121-
122- def _createKGWithoutSchema(self):
123- raise Exception("Can not create knowledge graph, schema missing")
124-
125- def _create(self) -> None:
126- """
127- Create knowledge graph
128- Extract entities and relations from sources
129- """
130- self.client = OpenAI()
131-
132- if self.schema is not None:
133- self._createKGWithSchema()
134- else:
135- self._createKGWithoutSchema()
136-
137- def ask(self, question:str, history:list|None=None) -> tuple[str, list]:
138- """
139- Query the knowledge graph using natural language
140- if the query is asked as part of a longer conversation make sure to
141- include past history.
142-
143- Rreturns:
144- tuple[str, list]: answer, conversation history
145-
146- Example:
147- >>> ans, history = kg.ask("Which actor has the most oscars")
148- >>> ans, history = kg.ask("List a few movies in which that actored played in", history)
149- """
150-
151- if history is None:
152- history = []
153-
154- answer = query(self, question, history, self.model)
155- return (answer, history)
deleted rag_sdk/prompts.py +0 −76
@@ -1,76 +0,0 @@
1-ONTOLOGY_DETECTION_SYSTEM_PROMPT = """Create SQL statement which will capture the different entities and the relations between them in the provided text.
2-Each table should represent either a single entity type with the entity's attributes as the table columns or a relation between two entities, using foreign keys.
3-For example an IMDB document is likely to produce 5 tables: Movie, Actor and Director each with its own columns and ACTED and DIRECTED tables.
4-Do not create an ID primary key column but set the most compelling attribute as the entity's primary key
5-Make sure to call the run_sql function provided in your tools set for each sql statement generated."""
6-
7-KNOWLEDGE_EXTRACTION_SYSTEM_PROMPT = """You are a helpful assistant with the goal of extracting
8-entities and relationships from text"""
9-
10-SQL_FOLDING_PROMPT = """The following two CREATE TABLE SQL statments are
11-creating the same table name, consolidate the two into a single
12-CREATE TABLE SQL statment.
13-Remove all duplicated columns.
14-Make sure the number of PRIMARY KEYs and FOREIGN KEYs is maintained.
15-Reply only with the result SQL statment, the reply should start with:
16-CREATE TABLE and end with );
17-For example: given the two CREATE TABLE SQL:
18-CREATE TABLE Person (FirstName string, LastName string, Age int);
19-CREATE TABLE Person (SurName string, ForeName string, Height int);
20-The response should be:
21-CREATE TABLE Person (FirstName string, LastName string, Age int, Height int);
22-"""
23-
24-SQL_FOCUS_PROMPT = """Given a CREATE TABLE SQL statment the table name
25- represents some entity, in case the number of columns in the table is
26- greater than 5, remove columns which are less descriptive of the entity.
27- Do NOT remove columns which are either a PRIMARY KEY or a FOREIGN KEY.
28- Make sure to leave at least 5 columns.
29- Do NOT rename the table name.
30- Reply only with the result SQL statment, the reply should start with:
31- CREATE TABLE and end with );
32- For example: given the CREATE TABLE SQL:
33- CREATE TABLE Movie (
34- Title string PRIMARY KEY,
35- Genre string,
36- ReleaseYear int,
37- Rating string,
38- Language string,
39- BoxOffice string,
40- streaming_date STRING,
41- runtime STRING
42- );
43- The response should be:
44- CREATE TABLE Movie (
45- Title string PRIMARY KEY,
46- Genre string,
47- ReleaseYear int,
48- Rating string,
49- runtime STRING
50- );
51- Another example: given the CREATE TABLE SQL:
52- CREATE TABLE Episode (
53- show_title VARCHAR(255),
54- show_year VARCHAR(4),
55- season INT,
56- episode_number INT,
57- episode_title VARCHAR(255),
58- air_date DATE,
59- episode_rating DECIMAL(2, 1),
60- FOREIGN KEY (show_title, show_year) REFERENCES TVShow(title, year)
61- );
62- You are not allowed to remove either show_title or show_year as these are part of the table's
63- foreign key.
64- """
65-
66-RELATIONSHIP_NAMING_PROMPT = """"You are a Cypher expert, help suggest names for
67-relationship types connecting source node to destination node.
68-Respond only with the suggested name.
69-For example given source node of type 'Actor' and destination node of type 'Movie'
70-Replay with: ACTED"""
71-
72-FIND_UNIQUE_ATTRIBUTE_PROMPT = """From the list of attributes describing a graph node
73-pick the most suitble attribute to act as a unique identifier of the node.
74-Respond only with the suggested attribute name
75-For example given a list of attributes: series_title, air_date, season_number, episode_number, title
76-Describing the graph entity "Episode" Reply with: title"""
deleted rag_sdk/query_graph.py +0 −144
@@ -1,144 +0,0 @@
1-import json
2-from openai import OpenAI
3-
4-# Equipet assistant with tools:
5-tools = [
6- {
7- "type": "function",
8- "function": {
9- "name": "run_cypher_query",
10- "description": "Run a Cypher query against the graph",
11- "parameters": {
12- "type": "object",
13- "properties": {
14- "query": {
15- "type": "string",
16- "description": "query to execute",
17- },
18- },
19- "required": ["query"],
20- },
21- },
22- }
23-]
24-
25-def run_cypher_query(g, q):
26- return g.query(q).result_set
27-
28-# convert a schema into a string representation
29-def _graph_schema_to_prompt(s) -> str:
30- # Build a string description of graph schema
31- desc = "The knowladge graph schema is as follows:\n"
32-
33- #--------------------------------------------------------------------------
34- # Describe labels
35- #--------------------------------------------------------------------------
36-
37- # list labels
38- desc = desc + "The graph contains the following node labels:\n";
39- for e in s.entities:
40- desc += e + "\n"
41-
42- # specify attributes associated with each entity
43- for e in s.entities:
44- e = s.entities[e]
45-
46- lbl_name = e.name
47- attributes = e.attributes
48- attr_count = len(attributes)
49-
50- if (attr_count == 0):
51- desc += f"The {lbl_name} label has no attributes\n"
52- else:
53- desc += f"The {lbl_name} label is associated with the following attribute(s):\n"
54- for attr in attributes:
55- attr_name = attr.name
56- attr_type = attr.type.__name__
57- desc += f"{attr_name} which is of type {attr_type}\n"
58-
59- desc += "The graph contains the following relationship types:\n"
60-
61- #--------------------------------------------------------------------------
62- # Describe relationships
63- #--------------------------------------------------------------------------
64-
65- # list relations
66- for rel in s.relations:
67- rel = s.relations[rel]
68-
69- src = rel.src.name
70- relationship_type = rel.name
71- dest = rel.dest.name
72- desc += f"{relationship_type}\n"
73- desc += f"The {relationship_type} relationship connects the following labels:\n"
74- desc += f"{src} is connected via {relationship_type} to {dest}\n"
75-
76- desc += "This is the end of the knowladge graph schema description.\n"
77-
78- return desc;
79-
80-def run_conversation(g, question, messages, model) -> str:
81- client = OpenAI()
82-
83- # Step 1: send the conversation and available functions to the model
84- messages.append({"role": "user", "content": question})
85-
86- response = client.chat.completions.create(
87- model=model,
88- messages=messages,
89- tools=tools,
90- tool_choice="auto", # auto is default, but we'll be explicit
91- )
92-
93- response_message = response.choices[0].message
94- tool_calls = response_message.tool_calls
95-
96- # Step 2: check if the model wanted to call a function
97- if tool_calls:
98- # Step 3: call the function
99- # Note: the JSON response may not always be valid; be sure to handle errors
100- available_functions = {
101- "run_cypher_query": run_cypher_query,
102- } # only one function in this example, but you can have multiple
103- messages.append(response_message) # extend conversation with assistant's reply
104- # Step 4: send the info for each function call and function response to the model
105- for tool_call in tool_calls:
106- function_name = tool_call.function.name
107- function_to_call = available_functions[function_name]
108- function_args = json.loads(tool_call.function.arguments)
109- q = function_args.get("query")
110- print(f"OpenAI suggested query: {q}")
111- function_response = function_to_call(g, q)
112- messages.append(
113- {
114- "tool_call_id": tool_call.id,
115- "role": "tool",
116- "name": function_name,
117- "content": str(function_response),
118- }
119- ) # extend conversation with function response
120- second_response = client.chat.completions.create(
121- model=model,
122- messages=messages,
123- ) # get a new response from the model where it can see the function response
124-
125- return second_response.choices[0].message.content
126-
127- return None
128-
129-def query(kg, question:str, messages:list, model="gpt-4-1106-preview") -> str:
130- # Build system message
131- if len(messages) == 0:
132- # graph schema
133- schema_desc = _graph_schema_to_prompt(kg.schema)
134- messages.append(
135- {"role": "system", "content": f"""You are a graph database expert fluent in the Cypher query language
136- with access to the following knowledge graph: {schema_desc}"""})
137-
138- # Get an answer
139- answer = run_conversation(kg.graph, question, messages, model)
140-
141- # Append answer to conversation
142- messages.append({"role": "assistant", "content": answer})
143-
144- return answer
deleted rag_sdk/source.py +0 −97
@@ -1,97 +0,0 @@
1-import re
2-import requests
3-from bs4 import BeautifulSoup
4-from abc import ABC, abstractmethod
5-
6-def Source(source:str) ->'AbstractSource':
7- """
8- Creates a source object
9-
10- Parameters:
11- source (str): path to source
12-
13- Returns:
14- AbstractSource: source
15- """
16-
17- if not isinstance(source, str) or source == "":
18- raise Exception("Invalid argument, source should be a none empty string.")
19-
20- if ".pdf" in source.lower():
21- return PDF(source)
22- elif ".html" in source.lower():
23- return HTML(source)
24- else:
25- return TEXT(source)
26-
27-class AbstractSource(ABC):
28- """
29- Abstract class representing a source file
30- """
31-
32- def __init__(self, source:str):
33- self.source = source
34- self.content = None
35-
36- @abstractmethod
37- def load(self) -> str:
38- pass
39-
40- def __eq__(self, other) -> bool:
41- if not isinstance(other, AbstractSource):
42- return False
43-
44- return self.source == other.source
45-
46- def __hash__(self):
47- return hash(self.source)
48-
49-class PDF(AbstractSource):
50- """
51- PDF resource
52- """
53-
54- def __init__(self, source):
55- super().__init__(source)
56-
57- def load(self):
58- raise Exception("Not implemented")
59- # extract text from PDF, populate self.content
60- self.content = None
61-
62-class TEXT(AbstractSource):
63- """
64- TEXT resource
65- """
66-
67- def __init__(self, source):
68- super().__init__(source)
69-
70- def load(self):
71- if self.content is None:
72- # populate self.content
73- with open(self.source, 'r') as f:
74- self.content = f.read()
75-
76- return self.content
77-
78-class HTML(AbstractSource):
79- """
80- HTML resource
81- """
82-
83- def __init__(self, source):
84- super().__init__(source)
85-
86- def load(self):
87- with open(self.source, 'r') as f:
88- self.content = f.read()
89-
90- # extract text from HTML, populate self.content
91- soup = BeautifulSoup(self.content, 'html.parser')
92-
93- # Extract text from the HTML
94- self.content = soup.get_text()
95-
96- # Remove extra newlines
97- self.content = re.sub(r'\n{2,}', '\n', self.content)
deleted rag_sdk/template.py +0 −153
@@ -1,153 +0,0 @@
1-# template file for entities and relationships extraction using OpenAI assistant
2-# The assistant is equipped with a set of auto generated tools
3-# e.g. Create_Actor, Create_Movie and CAST functions.
4-
5-TEMPLATE = '''import json
6-import time
7-import concurrent.futures
8-from openai import OpenAI
9-from .prompts import KNOWLEDGE_EXTRACTION_SYSTEM_PROMPT
10-from falkordb import FalkorDB
11-
12-g = None # graph
13-client = None # OpenAI client
14-
15-tools = [<TOOLS>]
16-
17-<FUNCTIONS>
18-
19-available_functions = <AVAILABLE_FUNCTIONS>
20-
21-def remove_none_values(args):
22- return {key: value for key, value in args.items() if value is not None}
23-
24-def create_assistant(client, assistant_name, instructions, model):
25- assistant = client.beta.assistants.create(
26- name = assistant_name,
27- instructions = instructions,
28- model = model,
29- tools = tools
30- )
31-
32- return assistant
33-
34-def initiate_interaction(client, assistant, user_message):
35- run = client.beta.threads.create_and_run(
36- assistant_id=assistant.id,
37- thread={ "messages": [ {"role": "user", "content": user_message} ] }
38- )
39-
40- return run
41-
42-def handle_run(client, run):
43- while True:
44- run = client.beta.threads.runs.retrieve(thread_id=run.thread_id, run_id=run.id)
45-
46- if run.status == "completed":
47- print("Run completed")
48- return
49-
50- if run.status == "expired":
51- print(f"Run expired")
52- return
53-
54- if run.status == "cancelling" or run.status == "cancelled" or run.status == "failed":
55- print(f"Run failed")
56- return
57-
58- # wait for run to complete
59- if run.status == "queued":
60- print("Run queued")
61- time.sleep(1)
62- continue
63-
64- if run.status == "in_progress":
65- last_step_id = None
66- print("Run in progress")
67- run_steps = []
68- # if last_step_id is None:
69- # run_steps = client.beta.threads.runs.steps.list(thread_id=run.thread_id, run_id=run.id)
70- # else:
71- # run_steps = client.beta.threads.runs.steps.list(thread_id=run.thread_id, run_id=run.id, after=last_step_id)
72- run_steps = client.beta.threads.runs.steps.list(thread_id=run.thread_id, run_id=run.id)
73-
74- for step in run_steps.data:
75- if step.status == "in_progress":
76- step_details = step.step_details
77- if step_details.type == "tool_calls":
78- for tool_call in step_details.tool_calls:
79- try:
80- if tool_call.type == "function":
81- func = tool_call.function
82- func_name = func.name
83- args = func.arguments
84- args = json.loads(args)
85- print(f"Function: {func_name}, {args}")
86- f = available_functions[func_name]
87- f(args)
88- except:
89- print(f"tool_call: {tool_call}")
90- pass
91-
92- last_step_id = run_steps.last_id
93-
94- time.sleep(1)
95- continue
96-
97- if run.status == "requires_action":
98- print(f"Run requires action")
99- action = run.required_action
100- if action.type == "submit_tool_outputs":
101- tool_outputs = action.submit_tool_outputs
102- outputs = []
103- for tool in tool_outputs.tool_calls:
104- tool_call_id = tool.id
105- tool_type = tool.type
106- func = tool.function
107- func_name = func.name
108- args = func.arguments
109- args = json.loads(args)
110- print(f"Function: {func_name}, {args}")
111-
112- f = available_functions[func_name]
113- f(args)
114-
115- outputs.append({ "tool_call_id": tool_call_id, "output": "OK" })
116-
117- # respond to action
118- run = client.beta.threads.runs.submit_tool_outputs(
119- thread_id=run.thread_id,
120- run_id=run.id,
121- tool_outputs=outputs
122- )
123-
124- continue
125-
126-def process_source(client, assistant, src):
127- text = src.load()[:32000]
128- user_message = f"Extracts entities and relations from the following text: {text}"
129-
130- run = initiate_interaction(client, assistant, user_message)
131-
132- handle_run(client, run)
133-
134- client.beta.threads.delete(run.thread_id)
135-
136-def build_graph_from_sources(kg, client, srcs:set):
137- global g
138- g = kg.graph
139-
140- assistant = create_assistant(client, kg.name, KNOWLEDGE_EXTRACTION_SYSTEM_PROMPT, model=kg.model)
141-
142- # Create thread pool
143- with concurrent.futures.ThreadPoolExecutor(max_workers=16) as executor:
144- tasks = []
145- # extract entities and relationships from each page
146- for src in srcs:
147- task = executor.submit(process_source, client, assistant, src)
148-
149- # Wait for all tasks to complete
150- concurrent.futures.wait(tasks)
151-
152- print("Done")
153-'''
modified tests/test_auto_detect.py +2 −2
@@ -1,6 +1,6 @@
11 import unittest
2-from rag_sdk import Source
3-from rag_sdk.Schema import Schema
2+from graphrag_sdk import Source
3+from graphrag_sdk.schema import Schema
44
55 class TestSchemaAutoDetect(unittest.TestCase):
66 def test_schema(self):
modified tests/test_kg.py +2 −2
@@ -1,6 +1,6 @@
11 import unittest
2-from rag_sdk import KnowledgeGraph, Source
3-from rag_sdk.Schema import Schema
2+from graphrag_sdk import KnowledgeGraph, Source
3+from graphrag_sdk.schema import Schema
44
55 class TestKG(unittest.TestCase):
66 def test_kg_creation(self):
modified tests/test_schema.py +4 −4
@@ -1,9 +1,9 @@
11 import unittest
22 from falkordb import FalkorDB
3-from rag_sdk import Source
4-from rag_sdk.Schema import Schema
5-from rag_sdk.Schema.tools_gen import schema_to_tools
6-from rag_sdk.Schema.functions_gen import schema_to_functions
3+from graphrag_sdk import Source
4+from graphrag_sdk.schema import Schema
5+from graphrag_sdk.schema.tools_gen import schema_to_tools
6+from graphrag_sdk.schema.functions_gen import schema_to_functions
77
88 class TestSchema(unittest.TestCase):
99 def test_schema(self):