Elffuss BraidHub

kikocis/GraphRAG-SDK public

423ab603a5a9 · 5.1 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
12g = None # graph
13client = None # OpenAI client
14
15tools = [<TOOLS>]
16
17<FUNCTIONS>
18
19available_functions = <AVAILABLE_FUNCTIONS>
20
21def remove_none_values(args):
22 return {key: value for key, value in args.items() if value is not None}
23
24def 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
34def 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
42def 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
126def 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
136def 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'''