Elffuss BraidHub

kikocis/GraphRAG-SDK public

423ab603a5a9 · 14.2 KiBRawPermalink
1import os
2import json
3import time
4import queue
5import sqlite3
6import concurrent.futures
7
8from rag_sdk.prompts import *
9from openai import OpenAI
10from sqlalchemy.orm import sessionmaker
11from sqlalchemy import create_engine, inspect, MetaData, Table, types
12
13# Convert from SQLAlchemy type to Python type
14def 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
46def 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
81def 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
117def 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
130def 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
148def 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
164def 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
213def run_sql(arg, queue):
214 sql = arg["sql"]
215 print(f"SQL: {sql}")
216
217 queue.put(sql)
218
219# OpenAI available functions
220available_functions = {
221 "run_sql": run_sql
222}
223
224# Get OpenAI ontology detection assistant
225def 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
263def 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
272def 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
349def 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
360def 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)