You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

entity_resolution.py 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import logging
  17. import itertools
  18. import re
  19. from dataclasses import dataclass
  20. from typing import Any, Callable
  21. import networkx as nx
  22. import trio
  23. from graphrag.general.extractor import Extractor
  24. from rag.nlp import is_english
  25. import editdistance
  26. from graphrag.entity_resolution_prompt import ENTITY_RESOLUTION_PROMPT
  27. from rag.llm.chat_model import Base as CompletionLLM
  28. from graphrag.utils import perform_variable_replacements, chat_limiter, GraphChange
  29. DEFAULT_RECORD_DELIMITER = "##"
  30. DEFAULT_ENTITY_INDEX_DELIMITER = "<|>"
  31. DEFAULT_RESOLUTION_RESULT_DELIMITER = "&&"
  32. @dataclass
  33. class EntityResolutionResult:
  34. """Entity resolution result class definition."""
  35. graph: nx.Graph
  36. change: GraphChange
  37. class EntityResolution(Extractor):
  38. """Entity resolution class definition."""
  39. _resolution_prompt: str
  40. _output_formatter_prompt: str
  41. _record_delimiter_key: str
  42. _entity_index_delimiter_key: str
  43. _resolution_result_delimiter_key: str
  44. def __init__(
  45. self,
  46. llm_invoker: CompletionLLM,
  47. ):
  48. super().__init__(llm_invoker)
  49. """Init method definition."""
  50. self._llm = llm_invoker
  51. self._resolution_prompt = ENTITY_RESOLUTION_PROMPT
  52. self._record_delimiter_key = "record_delimiter"
  53. self._entity_index_dilimiter_key = "entity_index_delimiter"
  54. self._resolution_result_delimiter_key = "resolution_result_delimiter"
  55. self._input_text_key = "input_text"
  56. async def __call__(self, graph: nx.Graph,
  57. subgraph_nodes: set[str],
  58. prompt_variables: dict[str, Any] | None = None,
  59. callback: Callable | None = None) -> EntityResolutionResult:
  60. """Call method definition."""
  61. if prompt_variables is None:
  62. prompt_variables = {}
  63. # Wire defaults into the prompt variables
  64. self.prompt_variables = {
  65. **prompt_variables,
  66. self._record_delimiter_key: prompt_variables.get(self._record_delimiter_key)
  67. or DEFAULT_RECORD_DELIMITER,
  68. self._entity_index_dilimiter_key: prompt_variables.get(self._entity_index_dilimiter_key)
  69. or DEFAULT_ENTITY_INDEX_DELIMITER,
  70. self._resolution_result_delimiter_key: prompt_variables.get(self._resolution_result_delimiter_key)
  71. or DEFAULT_RESOLUTION_RESULT_DELIMITER,
  72. }
  73. nodes = sorted(graph.nodes())
  74. entity_types = sorted(set(graph.nodes[node].get('entity_type', '-') for node in nodes))
  75. node_clusters = {entity_type: [] for entity_type in entity_types}
  76. for node in nodes:
  77. node_clusters[graph.nodes[node].get('entity_type', '-')].append(node)
  78. candidate_resolution = {entity_type: [] for entity_type in entity_types}
  79. for k, v in node_clusters.items():
  80. candidate_resolution[k] = [(a, b) for a, b in itertools.combinations(v, 2) if (a in subgraph_nodes or b in subgraph_nodes) and self.is_similarity(a, b)]
  81. num_candidates = sum([len(candidates) for _, candidates in candidate_resolution.items()])
  82. callback(msg=f"Identified {num_candidates} candidate pairs")
  83. remain_candidates_to_resolve = num_candidates
  84. resolution_result = set()
  85. resolution_result_lock = trio.Lock()
  86. resolution_batch_size = 100
  87. max_concurrent_tasks = 5
  88. semaphore = trio.Semaphore(max_concurrent_tasks)
  89. async def limited_resolve_candidate(candidate_batch, result_set, result_lock):
  90. nonlocal remain_candidates_to_resolve, callback
  91. async with semaphore:
  92. try:
  93. with trio.move_on_after(180) as cancel_scope:
  94. await self._resolve_candidate(candidate_batch, result_set, result_lock)
  95. remain_candidates_to_resolve = remain_candidates_to_resolve - len(candidate_batch[1])
  96. callback(msg=f"Resolved {len(candidate_batch[1])} pairs, {remain_candidates_to_resolve} are remained to resolve. ")
  97. if cancel_scope.cancelled_caught:
  98. logging.warning(f"Timeout resolving {candidate_batch}, skipping...")
  99. remain_candidates_to_resolve = remain_candidates_to_resolve - len(candidate_batch[1])
  100. callback(msg=f"Fail to resolved {len(candidate_batch[1])} pairs due to timeout reason, skipped. {remain_candidates_to_resolve} are remained to resolve. ")
  101. except Exception as e:
  102. logging.error(f"Error resolving candidate batch: {e}")
  103. async with trio.open_nursery() as nursery:
  104. for candidate_resolution_i in candidate_resolution.items():
  105. if not candidate_resolution_i[1]:
  106. continue
  107. for i in range(0, len(candidate_resolution_i[1]), resolution_batch_size):
  108. candidate_batch = candidate_resolution_i[0], candidate_resolution_i[1][i:i + resolution_batch_size]
  109. nursery.start_soon(limited_resolve_candidate, candidate_batch, resolution_result, resolution_result_lock)
  110. callback(msg=f"Resolved {num_candidates} candidate pairs, {len(resolution_result)} of them are selected to merge.")
  111. change = GraphChange()
  112. connect_graph = nx.Graph()
  113. connect_graph.add_edges_from(resolution_result)
  114. async def limited_merge_nodes(graph, nodes, change):
  115. async with semaphore:
  116. await self._merge_graph_nodes(graph, nodes, change)
  117. async with trio.open_nursery() as nursery:
  118. for sub_connect_graph in nx.connected_components(connect_graph):
  119. merging_nodes = list(sub_connect_graph)
  120. nursery.start_soon(limited_merge_nodes, graph, merging_nodes, change)
  121. # Update pagerank
  122. pr = nx.pagerank(graph)
  123. for node_name, pagerank in pr.items():
  124. graph.nodes[node_name]["pagerank"] = pagerank
  125. return EntityResolutionResult(
  126. graph=graph,
  127. change=change,
  128. )
  129. async def _resolve_candidate(self, candidate_resolution_i: tuple[str, list[tuple[str, str]]], resolution_result: set[str], resolution_result_lock: trio.Lock):
  130. gen_conf = {"temperature": 0.5}
  131. pair_txt = [
  132. f'When determining whether two {candidate_resolution_i[0]}s are the same, you should only focus on critical properties and overlook noisy factors.\n']
  133. for index, candidate in enumerate(candidate_resolution_i[1]):
  134. pair_txt.append(
  135. f'Question {index + 1}: name of{candidate_resolution_i[0]} A is {candidate[0]} ,name of{candidate_resolution_i[0]} B is {candidate[1]}')
  136. sent = 'question above' if len(pair_txt) == 1 else f'above {len(pair_txt)} questions'
  137. pair_txt.append(
  138. f'\nUse domain knowledge of {candidate_resolution_i[0]}s to help understand the text and answer the {sent} in the format: For Question i, Yes, {candidate_resolution_i[0]} A and {candidate_resolution_i[0]} B are the same {candidate_resolution_i[0]}./No, {candidate_resolution_i[0]} A and {candidate_resolution_i[0]} B are different {candidate_resolution_i[0]}s. For Question i+1, (repeat the above procedures)')
  139. pair_prompt = '\n'.join(pair_txt)
  140. variables = {
  141. **self.prompt_variables,
  142. self._input_text_key: pair_prompt
  143. }
  144. text = perform_variable_replacements(self._resolution_prompt, variables=variables)
  145. logging.info(f"Created resolution prompt {len(text)} bytes for {len(candidate_resolution_i[1])} entity pairs of type {candidate_resolution_i[0]}")
  146. async with chat_limiter:
  147. try:
  148. with trio.move_on_after(120) as cancel_scope:
  149. response = await trio.to_thread.run_sync(self._chat, text, [{"role": "user", "content": "Output:"}], gen_conf)
  150. if cancel_scope.cancelled_caught:
  151. logging.warning("_resolve_candidate._chat timeout, skipping...")
  152. return
  153. except Exception as e:
  154. logging.error(f"_resolve_candidate._chat failed: {e}")
  155. return
  156. logging.debug(f"_resolve_candidate chat prompt: {text}\nchat response: {response}")
  157. result = self._process_results(len(candidate_resolution_i[1]), response,
  158. self.prompt_variables.get(self._record_delimiter_key,
  159. DEFAULT_RECORD_DELIMITER),
  160. self.prompt_variables.get(self._entity_index_dilimiter_key,
  161. DEFAULT_ENTITY_INDEX_DELIMITER),
  162. self.prompt_variables.get(self._resolution_result_delimiter_key,
  163. DEFAULT_RESOLUTION_RESULT_DELIMITER))
  164. async with resolution_result_lock:
  165. for result_i in result:
  166. resolution_result.add(candidate_resolution_i[1][result_i[0] - 1])
  167. def _process_results(
  168. self,
  169. records_length: int,
  170. results: str,
  171. record_delimiter: str,
  172. entity_index_delimiter: str,
  173. resolution_result_delimiter: str
  174. ) -> list:
  175. ans_list = []
  176. records = [r.strip() for r in results.split(record_delimiter)]
  177. for record in records:
  178. pattern_int = f"{re.escape(entity_index_delimiter)}(\d+){re.escape(entity_index_delimiter)}"
  179. match_int = re.search(pattern_int, record)
  180. res_int = int(str(match_int.group(1) if match_int else '0'))
  181. if res_int > records_length:
  182. continue
  183. pattern_bool = f"{re.escape(resolution_result_delimiter)}([a-zA-Z]+){re.escape(resolution_result_delimiter)}"
  184. match_bool = re.search(pattern_bool, record)
  185. res_bool = str(match_bool.group(1) if match_bool else '')
  186. if res_int and res_bool:
  187. if res_bool.lower() == 'yes':
  188. ans_list.append((res_int, "yes"))
  189. return ans_list
  190. def is_similarity(self, a, b):
  191. if is_english(a) and is_english(b):
  192. if editdistance.eval(a, b) <= min(len(a), len(b)) // 2:
  193. return True
  194. return False
  195. if len(set(a) & set(b)) > 1:
  196. return True
  197. return False