extraction.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. import asyncio
  2. import json
  3. import logging
  4. import re
  5. import time
  6. from typing import Any, AsyncGenerator, Optional, Union
  7. from core.base import (
  8. AsyncState,
  9. CompletionProvider,
  10. DocumentChunk,
  11. Entity,
  12. GenerationConfig,
  13. KGExtraction,
  14. R2RDocumentProcessingError,
  15. R2RException,
  16. Relationship,
  17. )
  18. from core.base.pipes.base_pipe import AsyncPipe
  19. from ...database.postgres import PostgresDatabaseProvider
  20. logger = logging.getLogger()
  21. MIN_VALID_KG_EXTRACTION_RESPONSE_LENGTH = 128
  22. class ClientError(Exception):
  23. """Base class for client connection errors."""
  24. pass
  25. class GraphExtractionPipe(AsyncPipe[dict]):
  26. """
  27. Extracts knowledge graph information from document extractions.
  28. """
  29. # TODO - Apply correct type hints to storage messages
  30. class Input(AsyncPipe.Input):
  31. message: dict
  32. def __init__(
  33. self,
  34. database_provider: PostgresDatabaseProvider,
  35. llm_provider: CompletionProvider,
  36. config: AsyncPipe.PipeConfig,
  37. kg_batch_size: int = 1,
  38. graph_rag: bool = True,
  39. id_prefix: str = "demo",
  40. *args,
  41. **kwargs,
  42. ):
  43. super().__init__(
  44. config=config
  45. or AsyncPipe.PipeConfig(name="default_graph_extraction_pipe"),
  46. )
  47. self.database_provider = database_provider
  48. self.llm_provider = llm_provider
  49. self.kg_batch_size = kg_batch_size
  50. self.id_prefix = id_prefix
  51. self.pipe_run_info = None
  52. self.graph_rag = graph_rag
  53. async def extract_kg(
  54. self,
  55. extractions: list[DocumentChunk],
  56. generation_config: GenerationConfig,
  57. max_knowledge_relationships: int,
  58. entity_types: list[str],
  59. relation_types: list[str],
  60. retries: int = 5,
  61. delay: int = 2,
  62. task_id: Optional[int] = None,
  63. total_tasks: Optional[int] = None,
  64. ) -> KGExtraction:
  65. """
  66. Extracts NER relationships from a extraction with retries.
  67. """
  68. # combine all extractions into a single string
  69. combined_extraction: str = " ".join([extraction.data for extraction in extractions]) # type: ignore
  70. messages = await self.database_provider.prompts_handler.get_message_payload(
  71. task_prompt_name=self.database_provider.config.graph_creation_settings.graphrag_relationships_extraction_few_shot,
  72. task_inputs={
  73. "input": combined_extraction,
  74. "max_knowledge_relationships": max_knowledge_relationships,
  75. "entity_types": "\n".join(entity_types),
  76. "relation_types": "\n".join(relation_types),
  77. },
  78. )
  79. for attempt in range(retries):
  80. try:
  81. response = await self.llm_provider.aget_completion(
  82. messages,
  83. generation_config=generation_config,
  84. )
  85. kg_extraction = response.choices[0].message.content
  86. if not kg_extraction:
  87. raise R2RException(
  88. "No knowledge graph extraction found in the response string, the selected LLM likely failed to format it's response correctly.",
  89. 400,
  90. )
  91. entity_pattern = (
  92. r'\("entity"\${4}([^$]+)\${4}([^$]+)\${4}([^$]+)\)'
  93. )
  94. relationship_pattern = r'\("relationship"\${4}([^$]+)\${4}([^$]+)\${4}([^$]+)\${4}([^$]+)\${4}(\d+(?:\.\d+)?)\)'
  95. def parse_fn(response_str: str) -> Any:
  96. entities = re.findall(entity_pattern, response_str)
  97. if (
  98. len(kg_extraction)
  99. > MIN_VALID_KG_EXTRACTION_RESPONSE_LENGTH
  100. and len(entities) == 0
  101. ):
  102. raise R2RException(
  103. f"No entities found in the response string, the selected LLM likely failed to format it's response correctly. {response_str}",
  104. 400,
  105. )
  106. relationships = re.findall(
  107. relationship_pattern, response_str
  108. )
  109. entities_arr = []
  110. for entity in entities:
  111. entity_value = entity[0]
  112. entity_category = entity[1]
  113. entity_description = entity[2]
  114. entities_arr.append(
  115. Entity(
  116. category=entity_category,
  117. description=entity_description,
  118. name=entity_value,
  119. parent_id=extractions[0].document_id,
  120. chunk_ids=[
  121. extraction.id for extraction in extractions
  122. ],
  123. attributes={},
  124. )
  125. )
  126. relations_arr = []
  127. for relationship in relationships:
  128. subject = relationship[0]
  129. object = relationship[1]
  130. predicate = relationship[2]
  131. description = relationship[3]
  132. weight = float(relationship[4])
  133. # check if subject and object are in entities_dict
  134. relations_arr.append(
  135. Relationship(
  136. subject=subject,
  137. predicate=predicate,
  138. object=object,
  139. description=description,
  140. weight=weight,
  141. parent_id=extractions[0].document_id,
  142. chunk_ids=[
  143. extraction.id for extraction in extractions
  144. ],
  145. attributes={},
  146. )
  147. )
  148. return entities_arr, relations_arr
  149. entities, relationships = parse_fn(kg_extraction)
  150. return KGExtraction(
  151. entities=entities,
  152. relationships=relationships,
  153. )
  154. except (
  155. ClientError,
  156. json.JSONDecodeError,
  157. KeyError,
  158. IndexError,
  159. R2RException,
  160. ) as e:
  161. if attempt < retries - 1:
  162. await asyncio.sleep(delay)
  163. else:
  164. logger.error(
  165. f"Failed after retries with for chunk {extractions[0].id} of document {extractions[0].document_id}: {e}"
  166. )
  167. # raise e # you should raise an error.
  168. # add metadata to entities and relationships
  169. logger.info(
  170. f"GraphExtractionPipe: Completed task number {task_id} of {total_tasks} for document {extractions[0].document_id}",
  171. )
  172. return KGExtraction(
  173. entities=[],
  174. relationships=[],
  175. )
  176. async def _run_logic( # type: ignore
  177. self,
  178. input: Input,
  179. state: AsyncState,
  180. run_id: Any,
  181. *args: Any,
  182. **kwargs: Any,
  183. ) -> AsyncGenerator[Union[KGExtraction, R2RDocumentProcessingError], None]:
  184. start_time = time.time()
  185. document_id = input.message["document_id"]
  186. generation_config = input.message["generation_config"]
  187. chunk_merge_count = input.message["chunk_merge_count"]
  188. max_knowledge_relationships = input.message[
  189. "max_knowledge_relationships"
  190. ]
  191. entity_types = input.message["entity_types"]
  192. relation_types = input.message["relation_types"]
  193. filter_out_existing_chunks = input.message.get(
  194. "filter_out_existing_chunks", True
  195. )
  196. logger = input.message.get("logger", logging.getLogger())
  197. logger.info(
  198. f"GraphExtractionPipe: Processing document {document_id} for KG extraction",
  199. )
  200. # Then create the extractions from the results
  201. extractions = [
  202. DocumentChunk(
  203. id=extraction["id"],
  204. document_id=extraction["document_id"],
  205. owner_id=extraction["owner_id"],
  206. collection_ids=extraction["collection_ids"],
  207. data=extraction["text"],
  208. metadata=extraction["metadata"],
  209. )
  210. for extraction in (
  211. await self.database_provider.documents_handler.list_document_chunks( # FIXME: This was using the pagination defaults from before... We need to review if this is as intended.
  212. document_id=document_id,
  213. offset=0,
  214. limit=100,
  215. )
  216. )["results"]
  217. ]
  218. logger.info(
  219. f"Found {len(extractions)} extractions for document {document_id}"
  220. )
  221. if filter_out_existing_chunks:
  222. existing_chunk_ids = await self.database_provider.graphs_handler.get_existing_document_entity_chunk_ids(
  223. document_id=document_id
  224. )
  225. extractions = [
  226. extraction
  227. for extraction in extractions
  228. if extraction.id not in existing_chunk_ids
  229. ]
  230. logger.info(
  231. f"Filtered out {len(existing_chunk_ids)} existing extractions, remaining {len(extractions)} extractions for document {document_id}"
  232. )
  233. if len(extractions) == 0:
  234. logger.info(f"No extractions left for document {document_id}")
  235. return
  236. logger.info(
  237. f"GraphExtractionPipe: Obtained {len(extractions)} extractions to process, time from start: {time.time() - start_time:.2f} seconds",
  238. )
  239. # sort the extractions accroding to chunk_order field in metadata in ascending order
  240. extractions = sorted(
  241. extractions,
  242. key=lambda x: x.metadata.get("chunk_order", float("inf")),
  243. )
  244. # group these extractions into groups of chunk_merge_count
  245. extractions_groups = [
  246. extractions[i : i + chunk_merge_count]
  247. for i in range(0, len(extractions), chunk_merge_count)
  248. ]
  249. logger.info(
  250. f"GraphExtractionPipe: Extracting KG Relationships for document and created {len(extractions_groups)} tasks, time from start: {time.time() - start_time:.2f} seconds",
  251. )
  252. tasks = [
  253. asyncio.create_task(
  254. self.extract_kg(
  255. extractions=extractions_group,
  256. generation_config=generation_config,
  257. max_knowledge_relationships=max_knowledge_relationships,
  258. entity_types=entity_types,
  259. relation_types=relation_types,
  260. task_id=task_id,
  261. total_tasks=len(extractions_groups),
  262. )
  263. )
  264. for task_id, extractions_group in enumerate(extractions_groups)
  265. ]
  266. completed_tasks = 0
  267. total_tasks = len(tasks)
  268. logger.info(
  269. f"GraphExtractionPipe: Waiting for {total_tasks} KG extraction tasks to complete",
  270. )
  271. for completed_task in asyncio.as_completed(tasks):
  272. try:
  273. yield await completed_task
  274. completed_tasks += 1
  275. if completed_tasks % 100 == 0:
  276. logger.info(
  277. f"GraphExtractionPipe: Completed {completed_tasks}/{total_tasks} KG extraction tasks",
  278. )
  279. except Exception as e:
  280. logger.error(f"Error in Extracting KG Relationships: {e}")
  281. yield R2RDocumentProcessingError(
  282. document_id=document_id,
  283. error_message=str(e),
  284. )
  285. logger.info(
  286. f"GraphExtractionPipe: Completed {completed_tasks}/{total_tasks} KG extraction tasks, time from start: {time.time() - start_time:.2f} seconds",
  287. )