Elffuss BraidHub

kikocis/GraphRAG-SDK public

7d7ed3464b93 · 5.8 KiBRawPermalink
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
5TEMPLATE = '''import json
6import time
7import concurrent.futures
8from openai import OpenAI
9from .prompts import KNOWLEDGE_EXTRACTION_SYSTEM_PROMPT
10from falkordb import FalkorDB
11
12import logging
13logger = logging.getLogger(__name__)
14
15g = None # graph
16client = None # OpenAI client
17
18tools = [<TOOLS>]
19
20<FUNCTIONS>
21
22available_functions = <AVAILABLE_FUNCTIONS>
23
24def remove_none_values(args):
25 return {key: value for key, value in args.items() if value is not None}
26
27def 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
34def _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
44def 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
52def 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
136def process_source(client, assistant, src):
137 for doc in src.load():
138 text = doc.content[:32000]
139
140 user_message = f"Extracts entities and relations from the following text: {text}"
141 if src.instruction is not None:
142 user_message = f"{src.instruction}\\n{user_message}"
143
144 run = initiate_interaction(client, assistant, user_message)
145
146 handle_run(client, run)
147
148 client.beta.threads.delete(run.thread_id)
149
150 logger.debug(f"Done processing {src.source}")
151
152def build_graph_from_sources(kg, client, srcs:set):
153 global g
154 g = kg.graph
155
156 assistant = get_assistant(client, kg.name, KNOWLEDGE_EXTRACTION_SYSTEM_PROMPT, model=kg.model)
157
158 # Create thread pool
159 with concurrent.futures.ThreadPoolExecutor(max_workers=16) as executor:
160 tasks = []
161 # extract entities and relationships from each page
162 for src in srcs:
163 task = executor.submit(process_source, client, assistant, src)
164 tasks.append(task)
165
166 # Wait for all tasks to complete
167 concurrent.futures.wait(tasks)
168
169 logger.debug("Done")
170'''