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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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. import time
  20. from dataclasses import dataclass
  21. from typing import Any, Callable
  22. import networkx as nx
  23. import trio
  24. from graphrag.general.extractor import Extractor
  25. from rag.nlp import is_english
  26. import editdistance
  27. from graphrag.entity_resolution_prompt import ENTITY_RESOLUTION_PROMPT
  28. from rag.llm.chat_model import Base as CompletionLLM
  29. from graphrag.utils import perform_variable_replacements, chat_limiter
  30. DEFAULT_RECORD_DELIMITER = "##"
  31. DEFAULT_ENTITY_INDEX_DELIMITER = "<|>"
  32. DEFAULT_RESOLUTION_RESULT_DELIMITER = "&&"
  33. @dataclass
  34. class EntityResolutionResult:
  35. """Entity resolution result class definition."""
  36. graph: nx.Graph
  37. removed_entities: list
  38. class EntityResolution(Extractor):
  39. """Entity resolution class definition."""
  40. _resolution_prompt: str
  41. _output_formatter_prompt: str
  42. _record_delimiter_key: str
  43. _entity_index_delimiter_key: str
  44. _resolution_result_delimiter_key: str
  45. def __init__(
  46. self,
  47. llm_invoker: CompletionLLM,
  48. get_entity: Callable | None = None,
  49. set_entity: Callable | None = None,
  50. get_relation: Callable | None = None,
  51. set_relation: Callable | None = None
  52. ):
  53. super().__init__(llm_invoker, get_entity=get_entity, set_entity=set_entity, get_relation=get_relation, set_relation=set_relation)
  54. """Init method definition."""
  55. self._llm = llm_invoker
  56. self._resolution_prompt = ENTITY_RESOLUTION_PROMPT
  57. self._record_delimiter_key = "record_delimiter"
  58. self._entity_index_dilimiter_key = "entity_index_delimiter"
  59. self._resolution_result_delimiter_key = "resolution_result_delimiter"
  60. self._input_text_key = "input_text"
  61. async def __call__(self, graph: nx.Graph, prompt_variables: dict[str, Any] | None = None, callback: Callable | None = None) -> EntityResolutionResult:
  62. """Call method definition."""
  63. if prompt_variables is None:
  64. prompt_variables = {}
  65. # Wire defaults into the prompt variables
  66. self.prompt_variables = {
  67. **prompt_variables,
  68. self._record_delimiter_key: prompt_variables.get(self._record_delimiter_key)
  69. or DEFAULT_RECORD_DELIMITER,
  70. self._entity_index_dilimiter_key: prompt_variables.get(self._entity_index_dilimiter_key)
  71. or DEFAULT_ENTITY_INDEX_DELIMITER,
  72. self._resolution_result_delimiter_key: prompt_variables.get(self._resolution_result_delimiter_key)
  73. or DEFAULT_RESOLUTION_RESULT_DELIMITER,
  74. }
  75. nodes = graph.nodes
  76. entity_types = list(set(graph.nodes[node].get('entity_type', '-') for node in nodes))
  77. node_clusters = {entity_type: [] for entity_type in entity_types}
  78. for node in nodes:
  79. node_clusters[graph.nodes[node].get('entity_type', '-')].append(node)
  80. candidate_resolution = {entity_type: [] for entity_type in entity_types}
  81. for k, v in node_clusters.items():
  82. candidate_resolution[k] = [(a, b) for a, b in itertools.combinations(v, 2) if self.is_similarity(a, b)]
  83. num_candidates = sum([len(candidates) for _, candidates in candidate_resolution.items()])
  84. callback(msg=f"Identified {num_candidates} candidate pairs")
  85. resolution_result = set()
  86. async with trio.open_nursery() as nursery:
  87. for candidate_resolution_i in candidate_resolution.items():
  88. if not candidate_resolution_i[1]:
  89. continue
  90. nursery.start_soon(lambda: self._resolve_candidate(candidate_resolution_i, resolution_result))
  91. callback(msg=f"Resolved {num_candidates} candidate pairs, {len(resolution_result)} of them are selected to merge.")
  92. connect_graph = nx.Graph()
  93. removed_entities = []
  94. connect_graph.add_edges_from(resolution_result)
  95. all_entities_data = []
  96. all_relationships_data = []
  97. all_remove_nodes = []
  98. async with trio.open_nursery() as nursery:
  99. for sub_connect_graph in nx.connected_components(connect_graph):
  100. sub_connect_graph = connect_graph.subgraph(sub_connect_graph)
  101. remove_nodes = list(sub_connect_graph.nodes)
  102. keep_node = remove_nodes.pop()
  103. all_remove_nodes.append(remove_nodes)
  104. nursery.start_soon(lambda: self._merge_nodes(keep_node, self._get_entity_(remove_nodes), all_entities_data))
  105. for remove_node in remove_nodes:
  106. removed_entities.append(remove_node)
  107. remove_node_neighbors = graph[remove_node]
  108. remove_node_neighbors = list(remove_node_neighbors)
  109. for remove_node_neighbor in remove_node_neighbors:
  110. rel = self._get_relation_(remove_node, remove_node_neighbor)
  111. if graph.has_edge(remove_node, remove_node_neighbor):
  112. graph.remove_edge(remove_node, remove_node_neighbor)
  113. if remove_node_neighbor == keep_node:
  114. if graph.has_edge(keep_node, remove_node):
  115. graph.remove_edge(keep_node, remove_node)
  116. continue
  117. if not rel:
  118. continue
  119. if graph.has_edge(keep_node, remove_node_neighbor):
  120. nursery.start_soon(lambda: self._merge_edges(keep_node, remove_node_neighbor, [rel], all_relationships_data))
  121. else:
  122. pair = sorted([keep_node, remove_node_neighbor])
  123. graph.add_edge(pair[0], pair[1], weight=rel['weight'])
  124. self._set_relation_(pair[0], pair[1],
  125. dict(
  126. src_id=pair[0],
  127. tgt_id=pair[1],
  128. weight=rel['weight'],
  129. description=rel['description'],
  130. keywords=[],
  131. source_id=rel.get("source_id", ""),
  132. metadata={"created_at": time.time()}
  133. ))
  134. graph.remove_node(remove_node)
  135. return EntityResolutionResult(
  136. graph=graph,
  137. removed_entities=removed_entities
  138. )
  139. async def _resolve_candidate(self, candidate_resolution_i, resolution_result):
  140. gen_conf = {"temperature": 0.5}
  141. pair_txt = [
  142. 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']
  143. for index, candidate in enumerate(candidate_resolution_i[1]):
  144. pair_txt.append(
  145. f'Question {index + 1}: name of{candidate_resolution_i[0]} A is {candidate[0]} ,name of{candidate_resolution_i[0]} B is {candidate[1]}')
  146. sent = 'question above' if len(pair_txt) == 1 else f'above {len(pair_txt)} questions'
  147. pair_txt.append(
  148. 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)')
  149. pair_prompt = '\n'.join(pair_txt)
  150. variables = {
  151. **self.prompt_variables,
  152. self._input_text_key: pair_prompt
  153. }
  154. text = perform_variable_replacements(self._resolution_prompt, variables=variables)
  155. logging.info(f"Created resolution prompt {len(text)} bytes for {len(candidate_resolution_i[1])} entity pairs of type {candidate_resolution_i[0]}")
  156. async with chat_limiter:
  157. response = await trio.to_thread.run_sync(lambda: self._chat(text, [{"role": "user", "content": "Output:"}], gen_conf))
  158. logging.debug(f"_resolve_candidate chat prompt: {text}\nchat response: {response}")
  159. result = self._process_results(len(candidate_resolution_i[1]), response,
  160. self.prompt_variables.get(self._record_delimiter_key,
  161. DEFAULT_RECORD_DELIMITER),
  162. self.prompt_variables.get(self._entity_index_dilimiter_key,
  163. DEFAULT_ENTITY_INDEX_DELIMITER),
  164. self.prompt_variables.get(self._resolution_result_delimiter_key,
  165. DEFAULT_RESOLUTION_RESULT_DELIMITER))
  166. for result_i in result:
  167. resolution_result.add(candidate_resolution_i[1][result_i[0] - 1])
  168. def _process_results(
  169. self,
  170. records_length: int,
  171. results: str,
  172. record_delimiter: str,
  173. entity_index_delimiter: str,
  174. resolution_result_delimiter: str
  175. ) -> list:
  176. ans_list = []
  177. records = [r.strip() for r in results.split(record_delimiter)]
  178. for record in records:
  179. pattern_int = f"{re.escape(entity_index_delimiter)}(\d+){re.escape(entity_index_delimiter)}"
  180. match_int = re.search(pattern_int, record)
  181. res_int = int(str(match_int.group(1) if match_int else '0'))
  182. if res_int > records_length:
  183. continue
  184. pattern_bool = f"{re.escape(resolution_result_delimiter)}([a-zA-Z]+){re.escape(resolution_result_delimiter)}"
  185. match_bool = re.search(pattern_bool, record)
  186. res_bool = str(match_bool.group(1) if match_bool else '')
  187. if res_int and res_bool:
  188. if res_bool.lower() == 'yes':
  189. ans_list.append((res_int, "yes"))
  190. return ans_list
  191. def is_similarity(self, a, b):
  192. if is_english(a) and is_english(b):
  193. if editdistance.eval(a, b) <= min(len(a), len(b)) // 2:
  194. return True
  195. if len(set(a) & set(b)) > 0:
  196. return True
  197. return False