Elffuss BraidHub

kikocis/GraphRAG-SDK public

main · 7.1 KiBRawPermalink
1from graphrag_sdk.steps.Step import Step
2from graphrag_sdk.source import AbstractSource
3from graphrag_sdk.document import Document
4from concurrent.futures import Future, ThreadPoolExecutor, wait
5from graphrag_sdk.ontology import Ontology
6from graphrag_sdk.fixtures.prompts import (
7 CREATE_ONTOLOGY_SYSTEM,
8 CREATE_ONTOLOGY_PROMPT,
9 FIX_ONTOLOGY_PROMPT,
10 FIX_JSON_PROMPT,
11 BOUNDARIES_PREFIX,
12)
13import logging
14from graphrag_sdk.helpers import extract_json
15from ratelimit import limits, sleep_and_retry
16import time
17from graphrag_sdk.models import (
18 GenerativeModel,
19 GenerativeModelChatSession,
20 GenerativeModelConfig,
21 GenerationResponse,
22 FinishReason,
23)
24import json
25from typing import Optional
26
27logger = logging.getLogger(__name__)
28logger.setLevel(logging.DEBUG)
29
30
31class CreateOntologyStep(Step):
32 """
33 Create Ontology Step
34 """
35
36 def __init__(
37 self,
38 sources: list[AbstractSource],
39 ontology: Ontology,
40 model: GenerativeModel,
41 config: dict = {
42 "max_workers": 16,
43 "max_input_tokens": 500000,
44 "max_output_tokens": 8192,
45 },
46 ) -> None:
47 self.sources = sources
48 self.ontology = ontology
49 self.model = model.with_system_instruction(CREATE_ONTOLOGY_SYSTEM)
50 self.config = config
51
52 def _create_chat(self):
53 return self.model.start_chat({"response_validation": False})
54
55 def run(self, boundaries: Optional[str] = None):
56 tasks: list[Future[Ontology]] = []
57 with ThreadPoolExecutor(max_workers=self.config["max_workers"]) as executor:
58 # extract entities and relationships from each page
59
60 documents = [
61 document for source in self.sources for document in source.load()
62 ]
63 for source in documents:
64 task = executor.submit(
65 self._process_source,
66 self._create_chat(),
67 source,
68 self.ontology,
69 boundaries,
70 )
71 tasks.append(task)
72
73 # Wait for all tasks to complete
74 wait(tasks)
75
76 for task in tasks:
77 self.ontology = self.ontology.merge_with(task.result())
78
79 if len(self.ontology.entities) == 0:
80 raise Exception("Failed to create ontology")
81
82 self.ontology = self._fix_ontology(self._create_chat(), self.ontology)
83
84 return self.ontology
85
86 def _process_source(
87 self,
88 chat_session: GenerativeModelChatSession,
89 document: Document,
90 o: Ontology,
91 boundaries: Optional[str] = None,
92 ):
93 text = document.content[: self.config["max_input_tokens"]]
94
95 user_message = CREATE_ONTOLOGY_PROMPT.format(
96 text = text,
97 boundaries = BOUNDARIES_PREFIX.format(user_boundaries=boundaries) if boundaries is not None else "",
98 )
99
100 responses: list[GenerationResponse] = []
101 response_idx = 0
102
103 responses.append(self._call_model(chat_session, user_message))
104
105 logger.debug(f"Model response: {responses[response_idx]}")
106
107 while responses[response_idx].finish_reason == FinishReason.MAX_TOKENS:
108 response_idx += 1
109 responses.append(self._call_model(chat_session, "continue"))
110
111 if responses[response_idx].finish_reason != FinishReason.STOP:
112 raise Exception(
113 f"Model stopped unexpectedly: {responses[response_idx].finish_reason}"
114 )
115
116 combined_text = " ".join([r.text for r in responses])
117
118 try:
119 data = json.loads(extract_json(combined_text))
120 except json.decoder.JSONDecodeError as e:
121 logger.debug(f"Error extracting JSON: {e}")
122 logger.debug(f"Prompting model to fix JSON")
123 json_fix_response = self._call_model(
124 self._create_chat(),
125 FIX_JSON_PROMPT.format(json=combined_text, error=str(e)),
126 )
127 try:
128 data = json.loads(extract_json(json_fix_response.text))
129 logger.debug(f"Fixed JSON: {data}")
130 except json.decoder.JSONDecodeError as e:
131 logger.error(f"Failed to fix JSON: {e} {json_fix_response.text}")
132 data = None
133
134 if data is None:
135 return o
136
137 try:
138 new_ontology = Ontology.from_json(data)
139 except Exception as e:
140 logger.error(f"Exception while extracting JSON: {e}")
141 new_ontology = None
142
143 if new_ontology is not None:
144 o = o.merge_with(new_ontology)
145
146 logger.debug(f"Processed document: {document}")
147
148 return o
149
150 def _fix_ontology(self, chat_session: GenerativeModelChatSession, o: Ontology):
151 logger.debug(f"Fixing ontology...")
152
153 user_message = FIX_ONTOLOGY_PROMPT.format(ontology=o)
154
155 responses: list[GenerationResponse] = []
156 response_idx = 0
157
158 responses.append(self._call_model(chat_session, user_message))
159
160 logger.debug(f"Model response: {responses[response_idx]}")
161
162 while responses[response_idx].finish_reason == FinishReason.MAX_TOKENS:
163 response_idx += 1
164 responses.append(self._call_model(chat_session, "continue"))
165
166 if responses[response_idx].finish_reason != FinishReason.STOP:
167 raise Exception(
168 f"Model stopped unexpectedly: {responses[response_idx].finish_reason}"
169 )
170
171 combined_text = " ".join([r.text for r in responses])
172
173 try:
174 data = json.loads(extract_json(combined_text))
175 except json.decoder.JSONDecodeError as e:
176 logger.debug(f"Error extracting JSON: {e}")
177 logger.debug(f"Prompting model to fix JSON")
178 json_fix_response = self._call_model(
179 self._create_chat(),
180 FIX_JSON_PROMPT.format(json=combined_text, error=str(e)),
181 )
182 try:
183 data = json.loads(extract_json(json_fix_response.text))
184 logger.debug(f"Fixed JSON: {data}")
185 except json.decoder.JSONDecodeError as e:
186 logger.error(f"Failed to fix JSON: {e} {json_fix_response.text}")
187 data = None
188
189 if data is None:
190 return o
191
192 try:
193 new_ontology = Ontology.from_json(data)
194 except Exception as e:
195 logger.debug(f"Exception while extracting JSON: {e}")
196 new_ontology = None
197
198 if new_ontology is not None:
199 o = o.merge_with(new_ontology)
200
201 logger.debug(f"Fixed ontology: {o}")
202
203 return o
204
205 @sleep_and_retry
206 @limits(calls=15, period=60)
207 def _call_model(
208 self,
209 chat_session: GenerativeModelChatSession,
210 prompt: str,
211 retry=6,
212 ):
213 try:
214 return chat_session.send_message(prompt)
215 except Exception as e:
216 # If exception is caused by quota exceeded, wait 10 seconds and try again for 6 times
217 if "Quota exceeded" in str(e) and retry > 0:
218 time.sleep(10)
219 retry -= 1
220 return self._call_model(chat_session, prompt, retry)
221 else:
222 raise e