| 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 | import logging |
| 13 | logger = logging.getLogger(__name__) |
| 14 | |
| 15 | g = None # graph |
| 16 | client = None # OpenAI client |
| 17 | |
| 18 | tools = [<TOOLS>] |
| 19 | |
| 20 | <FUNCTIONS> |
| 21 | |
| 22 | available_functions = <AVAILABLE_FUNCTIONS> |
| 23 | |
| 24 | def remove_none_values(args): |
| 25 | return {key: value for key, value in args.items() if value is not None} |
| 26 | |
| 27 | def get_assistant(client, assistant_name, instructions, model): |
| 28 | for assistant in client.beta.assistants.list(): |
| 29 | if assistant.name == assistant_name: |
| 30 | return client.beta.assistants.retrieve(assistant.id) |
| 31 | |
| 32 | return _create_assistant(client, assistant_name, instructions, model) |
| 33 | |
| 34 | def _create_assistant(client, assistant_name, instructions, model): |
| 35 | assistant = client.beta.assistants.create( |
| 36 | name = assistant_name, |
| 37 | instructions = instructions, |
| 38 | model = model, |
| 39 | tools = tools |
| 40 | ) |
| 41 | |
| 42 | return assistant |
| 43 | |
| 44 | def initiate_interaction(client, assistant, user_message): |
| 45 | run = client.beta.threads.create_and_run( |
| 46 | assistant_id=assistant.id, |
| 47 | thread={ "messages": [ {"role": "user", "content": user_message} ] } |
| 48 | ) |
| 49 | |
| 50 | return run |
| 51 | |
| 52 | def handle_run(client, run): |
| 53 | while True: |
| 54 | run = client.beta.threads.runs.retrieve(thread_id=run.thread_id, run_id=run.id) |
| 55 | |
| 56 | if run.status == "completed": |
| 57 | logger.debug("Run completed") |
| 58 | return |
| 59 | |
| 60 | if run.status == "expired": |
| 61 | logger.debug(f"Run expired") |
| 62 | return |
| 63 | |
| 64 | if run.status == "cancelling" or run.status == "cancelled" or run.status == "failed": |
| 65 | logger.debug(f"Run failed") |
| 66 | return |
| 67 | |
| 68 | # wait for run to complete |
| 69 | if run.status == "queued": |
| 70 | logger.debug("Run queued") |
| 71 | time.sleep(1) |
| 72 | continue |
| 73 | |
| 74 | if run.status == "in_progress": |
| 75 | last_step_id = None |
| 76 | logger.debug("Run in progress") |
| 77 | run_steps = [] |
| 78 | # if last_step_id is None: |
| 79 | # run_steps = client.beta.threads.runs.steps.list(thread_id=run.thread_id, run_id=run.id) |
| 80 | # else: |
| 81 | # run_steps = client.beta.threads.runs.steps.list(thread_id=run.thread_id, run_id=run.id, after=last_step_id) |
| 82 | run_steps = client.beta.threads.runs.steps.list(thread_id=run.thread_id, run_id=run.id) |
| 83 | |
| 84 | for step in run_steps.data: |
| 85 | if step.status == "in_progress": |
| 86 | step_details = step.step_details |
| 87 | if step_details.type == "tool_calls": |
| 88 | for tool_call in step_details.tool_calls: |
| 89 | try: |
| 90 | if tool_call.type == "function": |
| 91 | func = tool_call.function |
| 92 | func_name = func.name |
| 93 | args = func.arguments |
| 94 | args = json.loads(args) |
| 95 | logger.debug(f"Function: {func_name}, {args}") |
| 96 | f = available_functions[func_name] |
| 97 | f(args) |
| 98 | except: |
| 99 | logger.debug(f"tool_call: {tool_call}") |
| 100 | pass |
| 101 | |
| 102 | last_step_id = run_steps.last_id |
| 103 | |
| 104 | time.sleep(1) |
| 105 | continue |
| 106 | |
| 107 | if run.status == "requires_action": |
| 108 | logger.debug(f"Run requires action") |
| 109 | action = run.required_action |
| 110 | if action.type == "submit_tool_outputs": |
| 111 | tool_outputs = action.submit_tool_outputs |
| 112 | outputs = [] |
| 113 | for tool in tool_outputs.tool_calls: |
| 114 | tool_call_id = tool.id |
| 115 | tool_type = tool.type |
| 116 | func = tool.function |
| 117 | func_name = func.name |
| 118 | args = func.arguments |
| 119 | args = json.loads(args) |
| 120 | logger.debug(f"Function: {func_name}, {args}") |
| 121 | |
| 122 | f = available_functions[func_name] |
| 123 | f(args) |
| 124 | |
| 125 | outputs.append({ "tool_call_id": tool_call_id, "output": "OK" }) |
| 126 | |
| 127 | # respond to action |
| 128 | run = client.beta.threads.runs.submit_tool_outputs( |
| 129 | thread_id=run.thread_id, |
| 130 | run_id=run.id, |
| 131 | tool_outputs=outputs |
| 132 | ) |
| 133 | |
| 134 | continue |
| 135 | |
| 136 | def process_source(client, assistant, src): |
| 137 | text = src.load()[:32000] |
| 138 | user_message = f"Extracts entities and relations from the following text: {text}" |
| 139 | if src.instruction is not None: |
| 140 | user_message = f"{src.instruction}\\n{user_message}" |
| 141 | |
| 142 | run = initiate_interaction(client, assistant, user_message) |
| 143 | |
| 144 | handle_run(client, run) |
| 145 | |
| 146 | client.beta.threads.delete(run.thread_id) |
| 147 | logger.debug(f"Done processing {src.source}") |
| 148 | |
| 149 | def build_graph_from_sources(kg, client, srcs:set): |
| 150 | global g |
| 151 | g = kg.graph |
| 152 | |
| 153 | assistant = get_assistant(client, kg.name, KNOWLEDGE_EXTRACTION_SYSTEM_PROMPT, model=kg.model) |
| 154 | |
| 155 | # Create thread pool |
| 156 | with concurrent.futures.ThreadPoolExecutor(max_workers=16) as executor: |
| 157 | tasks = [] |
| 158 | # extract entities and relationships from each page |
| 159 | for src in srcs: |
| 160 | task = executor.submit(process_source, client, assistant, src) |
| 161 | tasks.append(task) |
| 162 | |
| 163 | # Wait for all tasks to complete |
| 164 | concurrent.futures.wait(tasks) |
| 165 | |
| 166 | logger.debug("Done") |
| 167 | ''' |