| 1 | from graphrag_sdk.steps.Step import Step |
| 2 | from graphrag_sdk.source import AbstractSource |
| 3 | from concurrent.futures import Future, ThreadPoolExecutor, wait |
| 4 | from graphrag_sdk.ontology import Ontology |
| 5 | from graphrag_sdk.models import ( |
| 6 | GenerativeModel, |
| 7 | GenerativeModelChatSession, |
| 8 | GenerationResponse, |
| 9 | FinishReason, |
| 10 | ) |
| 11 | |
| 12 | from graphrag_sdk.fixtures.prompts import ( |
| 13 | EXTRACT_DATA_SYSTEM, |
| 14 | EXTRACT_DATA_PROMPT, |
| 15 | FIX_JSON_PROMPT, |
| 16 | ) |
| 17 | import logging |
| 18 | from graphrag_sdk.helpers import extract_json, map_dict_to_cypher_properties |
| 19 | import json |
| 20 | from falkordb import Graph |
| 21 | from graphrag_sdk.document import Document |
| 22 | from uuid import uuid4 |
| 23 | import os |
| 24 | import time |
| 25 | from ratelimit import limits, sleep_and_retry |
| 26 | |
| 27 | logger = logging.getLogger(__name__) |
| 28 | logger.setLevel(logging.DEBUG) |
| 29 | |
| 30 | |
| 31 | class ExtractDataStep(Step): |
| 32 | """ |
| 33 | Extract Data Step |
| 34 | """ |
| 35 | |
| 36 | def __init__( |
| 37 | self, |
| 38 | sources: list[AbstractSource], |
| 39 | ontology: Ontology, |
| 40 | model: GenerativeModel, |
| 41 | graph: Graph, |
| 42 | config: dict = { |
| 43 | "max_workers": 16, |
| 44 | "max_input_tokens": 500000, |
| 45 | "max_output_tokens": 8192, |
| 46 | }, |
| 47 | ) -> None: |
| 48 | self.sources = sources |
| 49 | self.ontology = ontology |
| 50 | self.config = config |
| 51 | self.model = model.with_system_instruction( |
| 52 | EXTRACT_DATA_SYSTEM.replace("#ONTOLOGY", str(self.ontology.to_json())) |
| 53 | ) |
| 54 | self.graph = graph |
| 55 | |
| 56 | if not os.path.exists("logs"): |
| 57 | os.makedirs("logs") |
| 58 | |
| 59 | def _create_chat(self): |
| 60 | return self.model.start_chat({"response_validation": False}) |
| 61 | |
| 62 | def run(self, instructions: str = None): |
| 63 | |
| 64 | tasks: list[Future[Ontology]] = [] |
| 65 | with ThreadPoolExecutor(max_workers=self.config["max_workers"]) as executor: |
| 66 | # extract entities and relationships from each page |
| 67 | documents = [ |
| 68 | (document, source.instruction) |
| 69 | for source in self.sources |
| 70 | for document in source.load() |
| 71 | if document is not None |
| 72 | and document.content is not None |
| 73 | and len(document.content) > 0 |
| 74 | ] |
| 75 | logger.debug(f"Processing {len(documents)} documents") |
| 76 | for document, source_instructions in documents: |
| 77 | task_id = "extract_data_step_" + str(uuid4()) |
| 78 | task = executor.submit( |
| 79 | self._process_source, |
| 80 | task_id, |
| 81 | self._create_chat(), |
| 82 | document, |
| 83 | self.ontology, |
| 84 | self.graph, |
| 85 | source_instructions, |
| 86 | instructions, |
| 87 | ) |
| 88 | tasks.append(task) |
| 89 | |
| 90 | # Wait for all tasks to complete |
| 91 | wait(tasks) |
| 92 | |
| 93 | def _process_source( |
| 94 | self, |
| 95 | task_id: str, |
| 96 | chat_session: GenerativeModelChatSession, |
| 97 | document: Document, |
| 98 | ontology: Ontology, |
| 99 | graph: Graph, |
| 100 | source_instructions: str = "", |
| 101 | instructions: str = "", |
| 102 | ): |
| 103 | try: |
| 104 | _task_logger = logging.getLogger(task_id) |
| 105 | _task_logger.setLevel(logging.DEBUG) |
| 106 | |
| 107 | fh = logging.FileHandler(f"logs/{task_id}.log") |
| 108 | fh.setFormatter( |
| 109 | logging.Formatter( |
| 110 | "%(asctime)s - %(name)s - %(levelname)s - %(message)s", |
| 111 | ) |
| 112 | ) |
| 113 | fh.setLevel(logging.DEBUG) |
| 114 | |
| 115 | _task_logger.addHandler(fh) |
| 116 | |
| 117 | logger.debug(f"Processing task: {task_id}") |
| 118 | _task_logger.debug(f"Processing task: {task_id}") |
| 119 | text = document.content[: self.config["max_input_tokens"]] |
| 120 | user_message = EXTRACT_DATA_PROMPT.format( |
| 121 | text=text, |
| 122 | instructions="\n".join( |
| 123 | [ |
| 124 | source_instructions if source_instructions is not None else "", |
| 125 | instructions if instructions is not None else "", |
| 126 | ] |
| 127 | ), |
| 128 | ) |
| 129 | |
| 130 | # logger.debug(f"User message: {user_message}") |
| 131 | _task_logger.debug("User message: " + user_message.replace("\n", " ")) |
| 132 | |
| 133 | responses: list[GenerationResponse] = [] |
| 134 | response_idx = 0 |
| 135 | |
| 136 | responses.append(self._call_model(chat_session, user_message)) |
| 137 | |
| 138 | _task_logger.debug(f"Model response: {responses[response_idx].text}") |
| 139 | |
| 140 | while responses[response_idx].finish_reason == FinishReason.MAX_TOKENS: |
| 141 | _task_logger.debug("Asking model to continue") |
| 142 | response_idx += 1 |
| 143 | responses.append(self._call_model(chat_session, "continue")) |
| 144 | _task_logger.debug( |
| 145 | f"Model response after continue: {responses[response_idx].text}" |
| 146 | ) |
| 147 | |
| 148 | if responses[response_idx].finish_reason != FinishReason.STOP: |
| 149 | _task_logger.debug( |
| 150 | f"Model stopped unexpectedly: {responses[response_idx].finish_reason}" |
| 151 | ) |
| 152 | raise Exception( |
| 153 | f"Model stopped unexpectedly: {responses[response_idx].finish_reason}" |
| 154 | ) |
| 155 | |
| 156 | combined_text = " ".join([r.text for r in responses]) |
| 157 | |
| 158 | try: |
| 159 | data = json.loads(extract_json(combined_text)) |
| 160 | except Exception as e: |
| 161 | _task_logger.debug(f"Error extracting JSON: {e}") |
| 162 | _task_logger.debug(f"Prompting model to fix JSON") |
| 163 | json_fix_response = self._call_model( |
| 164 | self._create_chat(), |
| 165 | FIX_JSON_PROMPT.format(json=combined_text, error=str(e)), |
| 166 | ) |
| 167 | data = json.loads(extract_json(json_fix_response.text)) |
| 168 | _task_logger.debug(f"Fixed JSON: {data}") |
| 169 | |
| 170 | if "entities" not in data or "relations" not in data: |
| 171 | _task_logger.debug( |
| 172 | f"Invalid data format. Missing entities or relations. {data}" |
| 173 | ) |
| 174 | raise Exception( |
| 175 | f"Invalid data format. Missing 'entities' or 'relations' in JSON." |
| 176 | ) |
| 177 | for entity in data["entities"]: |
| 178 | try: |
| 179 | self._create_entity(graph, entity, ontology) |
| 180 | except Exception as e: |
| 181 | _task_logger.error(f"Error creating entity: {e}") |
| 182 | continue |
| 183 | |
| 184 | for relation in data["relations"]: |
| 185 | try: |
| 186 | self._create_relation(graph, relation, ontology) |
| 187 | except Exception as e: |
| 188 | _task_logger.error(f"Error creating relation: {e}") |
| 189 | continue |
| 190 | |
| 191 | except Exception as e: |
| 192 | logger.exception(e) |
| 193 | raise e |
| 194 | |
| 195 | def _create_entity(self, graph: Graph, args: dict, ontology: Ontology): |
| 196 | # Get unique attributes from entity |
| 197 | entity = ontology.get_entity_with_label(args["label"]) |
| 198 | if entity is None: |
| 199 | print(f"Entity with label {args['label']} not found in ontology") |
| 200 | return None |
| 201 | unique_attributes_schema = [attr for attr in entity.attributes if attr.unique] |
| 202 | unique_attributes = { |
| 203 | attr.name: ( |
| 204 | args["attributes"][attr.name] if attr.name in args["attributes"] else "" |
| 205 | ) |
| 206 | for attr in unique_attributes_schema |
| 207 | } |
| 208 | unique_attributes_text = map_dict_to_cypher_properties(unique_attributes) |
| 209 | non_unique_attributes = { |
| 210 | attr.name: args["attributes"][attr.name] |
| 211 | for attr in entity.attributes |
| 212 | if not attr.unique and attr.name in args["attributes"] |
| 213 | } |
| 214 | non_unique_attributes_text = map_dict_to_cypher_properties( |
| 215 | non_unique_attributes |
| 216 | ) |
| 217 | set_statement = ( |
| 218 | f"SET n += {non_unique_attributes_text}" |
| 219 | if len(non_unique_attributes.keys()) > 0 |
| 220 | else "" |
| 221 | ) |
| 222 | query = f"MERGE (n:{args['label']} {unique_attributes_text}) {set_statement}" |
| 223 | logger.debug(f"Query: {query}") |
| 224 | result = graph.query(query) |
| 225 | return result |
| 226 | |
| 227 | def _create_relation(self, graph: Graph, args: dict, ontology: Ontology): |
| 228 | relations = ontology.get_relations_with_label(args["label"]) |
| 229 | if len(relations) == 0: |
| 230 | print(f"Relations with label {args['label']} not found in ontology") |
| 231 | return None |
| 232 | source_unique_attributes = ( |
| 233 | args["source"]["attributes"] |
| 234 | if "source" in args and "attributes" in args["source"] |
| 235 | else {} |
| 236 | ) |
| 237 | source_unique_attributes_text = map_dict_to_cypher_properties( |
| 238 | source_unique_attributes |
| 239 | ) |
| 240 | |
| 241 | target_unique_attributes = ( |
| 242 | args["target"]["attributes"] |
| 243 | if "target" in args and "attributes" in args["target"] |
| 244 | else {} |
| 245 | ) |
| 246 | target_unique_attributes_text = map_dict_to_cypher_properties( |
| 247 | target_unique_attributes |
| 248 | ) |
| 249 | |
| 250 | relation_attributes = ( |
| 251 | map_dict_to_cypher_properties(args["attributes"]) |
| 252 | if "attributes" in args |
| 253 | else {} |
| 254 | ) |
| 255 | set_statement = ( |
| 256 | f"SET r += {relation_attributes}" |
| 257 | if "attributes" in args |
| 258 | and len( |
| 259 | args["attributes"] |
| 260 | if isinstance(args["attributes"], list) |
| 261 | else args["attributes"].keys() |
| 262 | ) |
| 263 | > 0 |
| 264 | else "" |
| 265 | ) |
| 266 | query = f"MATCH (s:{args['source']['label']} {source_unique_attributes_text}) MATCH (d:{args['target']['label']} {target_unique_attributes_text}) MERGE (s)-[r:{args['label']}]->(d) {set_statement}" |
| 267 | logger.debug(f"Query: {query}") |
| 268 | result = graph.query(query) |
| 269 | return result |
| 270 | |
| 271 | @sleep_and_retry |
| 272 | @limits(calls=15, period=60) |
| 273 | def _call_model( |
| 274 | self, |
| 275 | chat_session: GenerativeModelChatSession, |
| 276 | prompt: str, |
| 277 | retry=6, |
| 278 | ): |
| 279 | try: |
| 280 | return chat_session.send_message(prompt) |
| 281 | except Exception as e: |
| 282 | # If exception is caused by quota exceeded, wait 10 seconds and try again for 6 times |
| 283 | if "Quota exceeded" in str(e) and retry > 0: |
| 284 | time.sleep(10) |
| 285 | retry -= 1 |
| 286 | return self._call_model(chat_session, prompt, retry) |
| 287 | else: |
| 288 | if retry == 0: |
| 289 | logger.error("Quota exceeded") |
| 290 | raise e |