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 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  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 itertools
  17. import re
  18. import time
  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
  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. removed_entities: list
  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. get_entity: Callable | None = None,
  48. set_entity: Callable | None = None,
  49. get_relation: Callable | None = None,
  50. set_relation: Callable | None = None
  51. ):
  52. super().__init__(llm_invoker, get_entity=get_entity, set_entity=set_entity, get_relation=get_relation, set_relation=set_relation)
  53. """Init method definition."""
  54. self._llm = llm_invoker
  55. self._resolution_prompt = ENTITY_RESOLUTION_PROMPT
  56. self._record_delimiter_key = "record_delimiter"
  57. self._entity_index_dilimiter_key = "entity_index_delimiter"
  58. self._resolution_result_delimiter_key = "resolution_result_delimiter"
  59. self._input_text_key = "input_text"
  60. async def __call__(self, graph: nx.Graph, prompt_variables: dict[str, Any] | None = None) -> EntityResolutionResult:
  61. """Call method definition."""
  62. if prompt_variables is None:
  63. prompt_variables = {}
  64. # Wire defaults into the prompt variables
  65. self.prompt_variables = {
  66. **prompt_variables,
  67. self._record_delimiter_key: prompt_variables.get(self._record_delimiter_key)
  68. or DEFAULT_RECORD_DELIMITER,
  69. self._entity_index_dilimiter_key: prompt_variables.get(self._entity_index_dilimiter_key)
  70. or DEFAULT_ENTITY_INDEX_DELIMITER,
  71. self._resolution_result_delimiter_key: prompt_variables.get(self._resolution_result_delimiter_key)
  72. or DEFAULT_RESOLUTION_RESULT_DELIMITER,
  73. }
  74. nodes = graph.nodes
  75. entity_types = list(set(graph.nodes[node].get('entity_type', '-') for node in nodes))
  76. node_clusters = {entity_type: [] for entity_type in entity_types}
  77. for node in nodes:
  78. node_clusters[graph.nodes[node].get('entity_type', '-')].append(node)
  79. candidate_resolution = {entity_type: [] for entity_type in entity_types}
  80. for k, v in node_clusters.items():
  81. candidate_resolution[k] = [(a, b) for a, b in itertools.combinations(v, 2) if self.is_similarity(a, b)]
  82. resolution_result = set()
  83. async with trio.open_nursery() as nursery:
  84. for candidate_resolution_i in candidate_resolution.items():
  85. if not candidate_resolution_i[1]:
  86. continue
  87. nursery.start_soon(lambda: self._resolve_candidate(candidate_resolution_i, resolution_result))
  88. connect_graph = nx.Graph()
  89. removed_entities = []
  90. connect_graph.add_edges_from(resolution_result)
  91. all_entities_data = []
  92. all_relationships_data = []
  93. for sub_connect_graph in nx.connected_components(connect_graph):
  94. sub_connect_graph = connect_graph.subgraph(sub_connect_graph)
  95. remove_nodes = list(sub_connect_graph.nodes)
  96. keep_node = remove_nodes.pop()
  97. await self._merge_nodes(keep_node, self._get_entity_(remove_nodes), all_entities_data)
  98. for remove_node in remove_nodes:
  99. removed_entities.append(remove_node)
  100. remove_node_neighbors = graph[remove_node]
  101. remove_node_neighbors = list(remove_node_neighbors)
  102. for remove_node_neighbor in remove_node_neighbors:
  103. rel = self._get_relation_(remove_node, remove_node_neighbor)
  104. if graph.has_edge(remove_node, remove_node_neighbor):
  105. graph.remove_edge(remove_node, remove_node_neighbor)
  106. if remove_node_neighbor == keep_node:
  107. if graph.has_edge(keep_node, remove_node):
  108. graph.remove_edge(keep_node, remove_node)
  109. continue
  110. if not rel:
  111. continue
  112. if graph.has_edge(keep_node, remove_node_neighbor):
  113. await self._merge_edges(keep_node, remove_node_neighbor, [rel], all_relationships_data)
  114. else:
  115. pair = sorted([keep_node, remove_node_neighbor])
  116. graph.add_edge(pair[0], pair[1], weight=rel['weight'])
  117. self._set_relation_(pair[0], pair[1],
  118. dict(
  119. src_id=pair[0],
  120. tgt_id=pair[1],
  121. weight=rel['weight'],
  122. description=rel['description'],
  123. keywords=[],
  124. source_id=rel.get("source_id", ""),
  125. metadata={"created_at": time.time()}
  126. ))
  127. graph.remove_node(remove_node)
  128. return EntityResolutionResult(
  129. graph=graph,
  130. removed_entities=removed_entities
  131. )
  132. async def _resolve_candidate(self, candidate_resolution_i, resolution_result):
  133. gen_conf = {"temperature": 0.5}
  134. pair_txt = [
  135. 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']
  136. for index, candidate in enumerate(candidate_resolution_i[1]):
  137. pair_txt.append(
  138. f'Question {index + 1}: name of{candidate_resolution_i[0]} A is {candidate[0]} ,name of{candidate_resolution_i[0]} B is {candidate[1]}')
  139. sent = 'question above' if len(pair_txt) == 1 else f'above {len(pair_txt)} questions'
  140. pair_txt.append(
  141. 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)')
  142. pair_prompt = '\n'.join(pair_txt)
  143. variables = {
  144. **self.prompt_variables,
  145. self._input_text_key: pair_prompt
  146. }
  147. text = perform_variable_replacements(self._resolution_prompt, variables=variables)
  148. async with chat_limiter:
  149. response = await trio.to_thread.run_sync(lambda: self._chat(text, [{"role": "user", "content": "Output:"}], gen_conf))
  150. result = self._process_results(len(candidate_resolution_i[1]), response,
  151. self.prompt_variables.get(self._record_delimiter_key,
  152. DEFAULT_RECORD_DELIMITER),
  153. self.prompt_variables.get(self._entity_index_dilimiter_key,
  154. DEFAULT_ENTITY_INDEX_DELIMITER),
  155. self.prompt_variables.get(self._resolution_result_delimiter_key,
  156. DEFAULT_RESOLUTION_RESULT_DELIMITER))
  157. for result_i in result:
  158. resolution_result.add(candidate_resolution_i[1][result_i[0] - 1])
  159. def _process_results(
  160. self,
  161. records_length: int,
  162. results: str,
  163. record_delimiter: str,
  164. entity_index_delimiter: str,
  165. resolution_result_delimiter: str
  166. ) -> list:
  167. ans_list = []
  168. records = [r.strip() for r in results.split(record_delimiter)]
  169. for record in records:
  170. pattern_int = f"{re.escape(entity_index_delimiter)}(\d+){re.escape(entity_index_delimiter)}"
  171. match_int = re.search(pattern_int, record)
  172. res_int = int(str(match_int.group(1) if match_int else '0'))
  173. if res_int > records_length:
  174. continue
  175. pattern_bool = f"{re.escape(resolution_result_delimiter)}([a-zA-Z]+){re.escape(resolution_result_delimiter)}"
  176. match_bool = re.search(pattern_bool, record)
  177. res_bool = str(match_bool.group(1) if match_bool else '')
  178. if res_int and res_bool:
  179. if res_bool.lower() == 'yes':
  180. ans_list.append((res_int, "yes"))
  181. return ans_list
  182. def is_similarity(self, a, b):
  183. if is_english(a) and is_english(b):
  184. if editdistance.eval(a, b) <= min(len(a), len(b)) // 2:
  185. return True
  186. if len(set(a) & set(b)) > 0:
  187. return True
  188. return False