| 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 | import logging |
| 14 | logger = logging.getLogger(__name__) |
| 15 | |
| 16 | # Convert from SQLAlchemy type to Python type |
| 17 | def sqlalchemy_to_python_type(sqlalchemy_type): |
| 18 | if isinstance(sqlalchemy_type, types.Integer): |
| 19 | return int |
| 20 | elif isinstance(sqlalchemy_type, types.Numeric): |
| 21 | return float |
| 22 | elif isinstance(sqlalchemy_type, types.Float): |
| 23 | return float |
| 24 | elif isinstance(sqlalchemy_type, types.String): |
| 25 | return str |
| 26 | elif isinstance(sqlalchemy_type, types.Text): |
| 27 | return str |
| 28 | elif isinstance(sqlalchemy_type, types.Boolean): |
| 29 | return bool |
| 30 | elif isinstance(sqlalchemy_type, types.Date): |
| 31 | #return 'date' |
| 32 | return str |
| 33 | elif isinstance(sqlalchemy_type, types.DateTime): |
| 34 | #return 'datetime' |
| 35 | return str |
| 36 | elif isinstance(sqlalchemy_type, types.Time): |
| 37 | #return 'time' |
| 38 | return str |
| 39 | elif isinstance(sqlalchemy_type, types.LargeBinary): |
| 40 | #return bytes |
| 41 | return str |
| 42 | elif isinstance(sqlalchemy_type, types.JSON): |
| 43 | #return dict |
| 44 | return str |
| 45 | else: |
| 46 | return 'Unknown Type' |
| 47 | |
| 48 | # create entity node |
| 49 | def create_entity(s, client, model, name:str, columns) -> None: |
| 50 | e = s.add_entity(name) |
| 51 | |
| 52 | has_pk = False |
| 53 | for col in columns: |
| 54 | t = sqlalchemy_to_python_type(col['type']) |
| 55 | pk = bool(col['primary_key']) |
| 56 | name = col['name'] |
| 57 | |
| 58 | if pk: |
| 59 | has_pk = True |
| 60 | |
| 61 | e.add_attribute(name, t, unique=pk, mandatory=pk) |
| 62 | |
| 63 | # Require each entity to have at least one unique attribute |
| 64 | if has_pk is False: |
| 65 | user_msg = f"""Which of the following attributes is most suitble to identify |
| 66 | a graph node of type: {name} ? |
| 67 | List of attributes: {','.join([col['name'] for col in columns])} |
| 68 | """ |
| 69 | |
| 70 | response = client.chat.completions.create( |
| 71 | model=model, |
| 72 | messages=[ |
| 73 | {"role": "system", "content": FIND_UNIQUE_ATTRIBUTE_PROMPT}, |
| 74 | {"role": "user", "content": user_msg} |
| 75 | ] |
| 76 | ) |
| 77 | |
| 78 | attr = response.choices[0].message.content |
| 79 | attr = e.get_attribute(attr) |
| 80 | attr.unique = True |
| 81 | attr.mandatory = True |
| 82 | |
| 83 | # Create entity node in addition to a single relation |
| 84 | def create_entity_with_relation(s, client, model, name:str, columns, foreign_keys) -> None: |
| 85 | # Remove foreign_keys from columns |
| 86 | for foreign_key in foreign_keys: |
| 87 | for constrained_column in foreign_key['constrained_columns']: |
| 88 | for idx, col in enumerate(columns): |
| 89 | if col['name'] == constrained_column: |
| 90 | del columns[idx] |
| 91 | break |
| 92 | |
| 93 | # create entity |
| 94 | create_entity(s, client, model, name, columns) |
| 95 | |
| 96 | # Determine relation destination node type |
| 97 | dest = foreign_keys[0]['referred_table'] |
| 98 | |
| 99 | src = s.get_entity(name) |
| 100 | dest = s.get_entity(dest) |
| 101 | |
| 102 | # Get relationship name |
| 103 | user_msg = f"""Suggest a name for a relationship-type connecting |
| 104 | source node of type {src.name} to destination node of type {dest.name}""" |
| 105 | |
| 106 | response = client.chat.completions.create( |
| 107 | model=model, |
| 108 | messages=[ |
| 109 | {"role": "system", "content": RELATIONSHIP_NAMING_PROMPT}, |
| 110 | {"role": "user", "content": user_msg} |
| 111 | ] |
| 112 | ) |
| 113 | |
| 114 | relatoin_name = response.choices[0].message.content.upper() |
| 115 | |
| 116 | # Create relation |
| 117 | s.add_relation(relatoin_name, src, dest) |
| 118 | |
| 119 | # Create relation between two entities |
| 120 | def create_relation(s, name:str, foreign_keys): |
| 121 | src = foreign_keys[0]['referred_table'] |
| 122 | dest = foreign_keys[1]['referred_table'] |
| 123 | |
| 124 | # Get source and destination entities |
| 125 | # (src)-[]->(dest) |
| 126 | src = s.get_entity(src) |
| 127 | dest = s.get_entity(dest) |
| 128 | |
| 129 | # Create relation |
| 130 | s.add_relation(name.upper(), src, dest) |
| 131 | |
| 132 | # Convert SQL table into a node type or a relation |
| 133 | def convert_table(s, client, model, tbl, columns, foreign_keys): |
| 134 | # Depending on the number of foreign keys in table |
| 135 | # 0 -> Entity |
| 136 | # 1 -> Entity & Relation |
| 137 | # 2 -> Relation |
| 138 | l = len(foreign_keys) |
| 139 | |
| 140 | if l == 0: |
| 141 | create_entity(s, client, model, tbl, columns) |
| 142 | elif l == 1: |
| 143 | pass |
| 144 | create_entity_with_relation(s, client, model, tbl, columns, foreign_keys) |
| 145 | elif l == 2: |
| 146 | pass |
| 147 | create_relation(s, tbl, foreign_keys) |
| 148 | else: |
| 149 | logger.error("can't process table with more then 2 forigen keys") |
| 150 | |
| 151 | def convert_tables(s, client, model, inspector, table_names): |
| 152 | # Start by converting tabels without foreign keys |
| 153 | for table_name in table_names: |
| 154 | columns = inspector.get_columns(table_name) |
| 155 | foreign_keys = inspector.get_foreign_keys(table_name) |
| 156 | if len(foreign_keys) == 0: |
| 157 | convert_table(s, client, model, table_name, columns, foreign_keys) |
| 158 | |
| 159 | # Continue on processing the rest of the tables |
| 160 | for table_name in table_names: |
| 161 | columns = inspector.get_columns(table_name) |
| 162 | foreign_keys = inspector.get_foreign_keys(table_name) |
| 163 | if len(foreign_keys) > 0: |
| 164 | convert_table(s, client, model, table_name, columns, foreign_keys) |
| 165 | |
| 166 | # Create graph ontology from a set of SQL tables |
| 167 | def generate_graph_schema(s, client, model): |
| 168 | # Connect to local SQLite DB |
| 169 | database_file = 'ontology.db' |
| 170 | connection_string = f'sqlite:///{database_file}' |
| 171 | |
| 172 | # Create an engine |
| 173 | engine = create_engine(connection_string) |
| 174 | |
| 175 | # Verify the connection by connecting to the database |
| 176 | connection = engine.connect() |
| 177 | |
| 178 | # Create a configured "Session" class |
| 179 | Session = sessionmaker(bind=engine) |
| 180 | |
| 181 | # Create a Session |
| 182 | session = Session() |
| 183 | |
| 184 | inspector = inspect(engine) |
| 185 | table_names = inspector.get_table_names() |
| 186 | |
| 187 | # Process tabels into schema |
| 188 | convert_tables(s, client, model, inspector, table_names) |
| 189 | |
| 190 | # Close the session when done |
| 191 | session.close() |
| 192 | |
| 193 | # Close the connection |
| 194 | connection.close() |
| 195 | |
| 196 | # Improve relations nameing |
| 197 | #for rel in s.relations: |
| 198 | # r = s.relations[rel] |
| 199 | # user_msg = f"""Suggest a name for a relationship-type connecting |
| 200 | # source node of type {r.src.name} to destination node of type {r.dest.name}""" |
| 201 | |
| 202 | # response = client.chat.completions.create( |
| 203 | # model=model, |
| 204 | # messages=[ |
| 205 | # {"role": "system", "content": RELATIONSHIP_NAMING_PROMPT}, |
| 206 | # {"role": "user", "content": user_msg} |
| 207 | # ] |
| 208 | # ) |
| 209 | |
| 210 | # old = r.name |
| 211 | # r.name = response.choices[0].message.content.upper() |
| 212 | # print(f"Renamed from {old} to: {r.name}") |
| 213 | |
| 214 | # OpenAI assistant tool |
| 215 | # queue sql statment |
| 216 | def run_sql(arg, queue): |
| 217 | sql = arg["sql"] |
| 218 | logger.debug(f"SQL: {sql}") |
| 219 | |
| 220 | queue.put(sql) |
| 221 | |
| 222 | # OpenAI available functions |
| 223 | available_functions = { |
| 224 | "run_sql": run_sql |
| 225 | } |
| 226 | |
| 227 | # Get OpenAI ontology detection assistant |
| 228 | def get_assistant(client, assistant_name, model): |
| 229 | # Try reusing existing assistant |
| 230 | for assistant in client.beta.assistants.list(): |
| 231 | if assistant.name == assistant_name: |
| 232 | return client.beta.assistants.retrieve(assistant.id) |
| 233 | |
| 234 | # Create OpenAI assistant |
| 235 | assistant = client.beta.assistants.create( |
| 236 | name = assistant_name, |
| 237 | instructions = ONTOLOGY_DETECTION_SYSTEM_PROMPT, |
| 238 | model = model, |
| 239 | tools=[{ |
| 240 | "type": "function", |
| 241 | "function": { |
| 242 | "name": "run_sql", |
| 243 | "description": "Run SQL statement", |
| 244 | "parameters": { |
| 245 | "type": "object", |
| 246 | "properties": { |
| 247 | "sql": {"type": "string", "description": "SQL statement"} |
| 248 | }, |
| 249 | "required": ["sql"] |
| 250 | } |
| 251 | } |
| 252 | }] |
| 253 | ) |
| 254 | |
| 255 | return assistant |
| 256 | |
| 257 | # Start an interaction with OpenAI assistant |
| 258 | def initiate_interaction(client, assistant, user_message): |
| 259 | run = client.beta.threads.create_and_run( |
| 260 | assistant_id=assistant.id, |
| 261 | thread={ "messages": [ {"role": "user", "content": user_message} ] } |
| 262 | ) |
| 263 | |
| 264 | return run |
| 265 | |
| 266 | # OpenAI run handler |
| 267 | def handle_run(client, run, queue): |
| 268 | while True: |
| 269 | run = client.beta.threads.runs.retrieve(thread_id=run.thread_id, run_id=run.id) |
| 270 | |
| 271 | if run.status == "completed": |
| 272 | logger.debug("Done processing document") |
| 273 | return |
| 274 | |
| 275 | if run.status == "expired": |
| 276 | logger.debug(f"Processing expired") |
| 277 | return |
| 278 | |
| 279 | if run.status == "cancelling" or run.status == "cancelled" or run.status == "failed": |
| 280 | logger.debug(f"Processing failed") |
| 281 | return |
| 282 | |
| 283 | # wait for run to complete |
| 284 | if run.status == "queued": |
| 285 | time.sleep(1) |
| 286 | continue |
| 287 | |
| 288 | if run.status == "in_progress": |
| 289 | last_step_id = None |
| 290 | run_steps = [] |
| 291 | run_steps = client.beta.threads.runs.steps.list(thread_id=run.thread_id, run_id=run.id) |
| 292 | |
| 293 | for step in run_steps.data: |
| 294 | if step.status == "in_progress": |
| 295 | step_details = step.step_details |
| 296 | if step_details.type == "tool_calls": |
| 297 | for tool_call in step_details.tool_calls: |
| 298 | try: |
| 299 | if tool_call.type == "function": |
| 300 | func = tool_call.function |
| 301 | func_name = func.name |
| 302 | args = func.arguments |
| 303 | args = json.loads(args) |
| 304 | f = available_functions[func_name] |
| 305 | f(args, queue) |
| 306 | except: |
| 307 | logger.debug(f"tool_call: {tool_call}") |
| 308 | pass |
| 309 | |
| 310 | last_step_id = run_steps.last_id |
| 311 | |
| 312 | time.sleep(1) |
| 313 | continue |
| 314 | |
| 315 | if run.status == "requires_action": |
| 316 | action = run.required_action |
| 317 | if action.type == "submit_tool_outputs": |
| 318 | tool_outputs = action.submit_tool_outputs |
| 319 | outputs = [] |
| 320 | for tool in tool_outputs.tool_calls: |
| 321 | tool_call_id = tool.id |
| 322 | tool_type = tool.type |
| 323 | func = tool.function |
| 324 | func_name = func.name |
| 325 | args = func.arguments |
| 326 | args = json.loads(args) |
| 327 | |
| 328 | f = available_functions[func_name] |
| 329 | f(args, queue) |
| 330 | |
| 331 | outputs.append({ "tool_call_id": tool_call_id, "output": "OK" }) |
| 332 | |
| 333 | # respond to action |
| 334 | run = client.beta.threads.runs.submit_tool_outputs( |
| 335 | thread_id=run.thread_id, |
| 336 | run_id=run.id, |
| 337 | tool_outputs=outputs |
| 338 | ) |
| 339 | |
| 340 | continue |
| 341 | |
| 342 | # process source |
| 343 | # present content to LLM for graph ontology detection |
| 344 | def process_source(client, assistant, src, queue): |
| 345 | for doc in src.load(): |
| 346 | text = doc.content[:32000] |
| 347 | user_message = "Extract schema from following text:" + text |
| 348 | |
| 349 | run = initiate_interaction(client, assistant, user_message) |
| 350 | |
| 351 | handle_run(client, run, queue) |
| 352 | |
| 353 | client.beta.threads.delete(run.thread_id) |
| 354 | |
| 355 | # Detect graph ontology from a set of sources |
| 356 | def schema_auto_detect(schema, sources, model="gpt-3.5-turbo-0125"): |
| 357 | client = OpenAI() |
| 358 | |
| 359 | # Get assistant |
| 360 | assistant = get_assistant(client, "ontology detection", model) |
| 361 | |
| 362 | # Create a new local SQLite DB |
| 363 | db_file = "ontology.db" |
| 364 | if os.path.exists(db_file): |
| 365 | os.remove(db_file) |
| 366 | |
| 367 | # Process sources |
| 368 | q = queue.Queue() |
| 369 | with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor: |
| 370 | tasks = [] |
| 371 | # extract entities and relationships from each page |
| 372 | for src in sources: |
| 373 | task = executor.submit(process_source, client, assistant, src, q) |
| 374 | |
| 375 | # Wait for all tasks to complete |
| 376 | concurrent.futures.wait(tasks) |
| 377 | |
| 378 | # Collect duplicated CREATE statments |
| 379 | n = q.qsize() |
| 380 | tables = {} |
| 381 | for i in range(n): |
| 382 | stmt = q.get() |
| 383 | logger.debug(f"sql: {stmt}") |
| 384 | |
| 385 | # group by table name |
| 386 | # CREATE TABLE MoviePersonnel ( |
| 387 | s = stmt.index("CREATE TABLE ") + len("CREATE TABLE ") |
| 388 | e = stmt.index("(") - 1 |
| 389 | tbl = stmt[s:e] |
| 390 | logger.debug(f"tbl: {tbl}") |
| 391 | |
| 392 | if tbl not in tables: |
| 393 | tables[tbl] = [] |
| 394 | tables[tbl].append(stmt) |
| 395 | |
| 396 | # Merge duplicated create table statments |
| 397 | for k in tables: |
| 398 | while len(tables[k]) > 1: |
| 399 | user_msg = f"""Merge to following two SQL CREATE TABLE statments: |
| 400 | 1. {tables[k].pop()} |
| 401 | 2. {tables[k].pop()} |
| 402 | """ |
| 403 | |
| 404 | response = client.chat.completions.create( |
| 405 | model=model, |
| 406 | messages=[ |
| 407 | {"role": "system", "content": SQL_FOLDING_PROMPT}, |
| 408 | {"role": "user", "content": user_msg} |
| 409 | ] |
| 410 | ) |
| 411 | |
| 412 | merged_stmt = response.choices[0].message.content |
| 413 | logger.debug(f"merged_stmt: {merged_stmt}") |
| 414 | tables[k].append(merged_stmt) |
| 415 | |
| 416 | # Switch back from dict to array |
| 417 | tables = [tables[x][0] for x in tables] |
| 418 | |
| 419 | # execute SQL statments |
| 420 | con = sqlite3.connect(db_file) |
| 421 | cur = con.cursor() |
| 422 | |
| 423 | for stmt in tables: |
| 424 | logger.debug(f"Executing: {stmt}") |
| 425 | cur.execute(stmt) |
| 426 | con.commit() |
| 427 | |
| 428 | # Remove esoteric columns |
| 429 | #for i, stmt in enumerate(tables): |
| 430 | # user_msg = f"""Remove less descriptive columns from the following |
| 431 | # CREATE TABLE SQL statment: {stmt}""" |
| 432 | |
| 433 | # response = client.chat.completions.create( |
| 434 | # model=model, |
| 435 | # messages=[ |
| 436 | # {"role": "system", "content": SQL_FOCUS_PROMPT}, |
| 437 | # {"role": "user", "content": user_msg} |
| 438 | # ] |
| 439 | # ) |
| 440 | |
| 441 | # refined_stmt = response.choices[0].message.content |
| 442 | # if not refined_stmt.startswith("CREATE TABLE"): |
| 443 | # refined_stmt = stmt |
| 444 | |
| 445 | # print(f"refined_stmt: {refined_stmt}") |
| 446 | # tables[i] = refined_stmt |
| 447 | |
| 448 | cur.close() |
| 449 | con.close() |
| 450 | |
| 451 | # generate schema |
| 452 | generate_graph_schema(schema, client, model) |