Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

extractor.py 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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 re
  18. from collections import defaultdict, Counter
  19. from copy import deepcopy
  20. from typing import Callable
  21. import trio
  22. from graphrag.general.graph_prompt import SUMMARIZE_DESCRIPTIONS_PROMPT
  23. from graphrag.utils import get_llm_cache, set_llm_cache, handle_single_entity_extraction, \
  24. handle_single_relationship_extraction, split_string_by_multi_markers, flat_uniq_list, chat_limiter
  25. from rag.llm.chat_model import Base as CompletionLLM
  26. from rag.prompts import message_fit_in
  27. from rag.utils import truncate
  28. GRAPH_FIELD_SEP = "<SEP>"
  29. DEFAULT_ENTITY_TYPES = ["organization", "person", "geo", "event", "category"]
  30. ENTITY_EXTRACTION_MAX_GLEANINGS = 2
  31. class Extractor:
  32. _llm: CompletionLLM
  33. def __init__(
  34. self,
  35. llm_invoker: CompletionLLM,
  36. language: str | None = "English",
  37. entity_types: list[str] | None = None,
  38. get_entity: Callable | None = None,
  39. set_entity: Callable | None = None,
  40. get_relation: Callable | None = None,
  41. set_relation: Callable | None = None,
  42. ):
  43. self._llm = llm_invoker
  44. self._language = language
  45. self._entity_types = entity_types or DEFAULT_ENTITY_TYPES
  46. self._get_entity_ = get_entity
  47. self._set_entity_ = set_entity
  48. self._get_relation_ = get_relation
  49. self._set_relation_ = set_relation
  50. def _chat(self, system, history, gen_conf):
  51. hist = deepcopy(history)
  52. conf = deepcopy(gen_conf)
  53. response = get_llm_cache(self._llm.llm_name, system, hist, conf)
  54. if response:
  55. return response
  56. _, system_msg = message_fit_in([{"role": "system", "content": system}], int(self._llm.max_length * 0.92))
  57. response = self._llm.chat(system_msg[0]["content"], hist, conf)
  58. response = re.sub(r"<think>.*</think>", "", response, flags=re.DOTALL)
  59. if response.find("**ERROR**") >= 0:
  60. raise Exception(response)
  61. set_llm_cache(self._llm.llm_name, system, response, history, gen_conf)
  62. return response
  63. def _entities_and_relations(self, chunk_key: str, records: list, tuple_delimiter: str):
  64. maybe_nodes = defaultdict(list)
  65. maybe_edges = defaultdict(list)
  66. ent_types = [t.lower() for t in self._entity_types]
  67. for record in records:
  68. record_attributes = split_string_by_multi_markers(
  69. record, [tuple_delimiter]
  70. )
  71. if_entities = handle_single_entity_extraction(
  72. record_attributes, chunk_key
  73. )
  74. if if_entities is not None and if_entities.get("entity_type", "unknown").lower() in ent_types:
  75. maybe_nodes[if_entities["entity_name"]].append(if_entities)
  76. continue
  77. if_relation = handle_single_relationship_extraction(
  78. record_attributes, chunk_key
  79. )
  80. if if_relation is not None:
  81. maybe_edges[(if_relation["src_id"], if_relation["tgt_id"])].append(
  82. if_relation
  83. )
  84. return dict(maybe_nodes), dict(maybe_edges)
  85. async def __call__(
  86. self, doc_id: str, chunks: list[str],
  87. callback: Callable | None = None
  88. ):
  89. self.callback = callback
  90. start_ts = trio.current_time()
  91. out_results = []
  92. async with trio.open_nursery() as nursery:
  93. for i, ck in enumerate(chunks):
  94. ck = truncate(ck, int(self._llm.max_length*0.8))
  95. nursery.start_soon(lambda: self._process_single_content((doc_id, ck), i, len(chunks), out_results))
  96. maybe_nodes = defaultdict(list)
  97. maybe_edges = defaultdict(list)
  98. sum_token_count = 0
  99. for m_nodes, m_edges, token_count in out_results:
  100. for k, v in m_nodes.items():
  101. maybe_nodes[k].extend(v)
  102. for k, v in m_edges.items():
  103. maybe_edges[tuple(sorted(k))].extend(v)
  104. sum_token_count += token_count
  105. now = trio.current_time()
  106. if callback:
  107. callback(msg = f"Entities and relationships extraction done, {len(maybe_nodes)} nodes, {len(maybe_edges)} edges, {sum_token_count} tokens, {now-start_ts:.2f}s.")
  108. start_ts = now
  109. logging.info("Entities merging...")
  110. all_entities_data = []
  111. async with trio.open_nursery() as nursery:
  112. for en_nm, ents in maybe_nodes.items():
  113. nursery.start_soon(lambda: self._merge_nodes(en_nm, ents, all_entities_data))
  114. now = trio.current_time()
  115. if callback:
  116. callback(msg = f"Entities merging done, {now-start_ts:.2f}s.")
  117. start_ts = now
  118. logging.info("Relationships merging...")
  119. all_relationships_data = []
  120. async with trio.open_nursery() as nursery:
  121. for (src, tgt), rels in maybe_edges.items():
  122. nursery.start_soon(lambda: self._merge_edges(src, tgt, rels, all_relationships_data))
  123. now = trio.current_time()
  124. if callback:
  125. callback(msg = f"Relationships merging done, {now-start_ts:.2f}s.")
  126. if not len(all_entities_data) and not len(all_relationships_data):
  127. logging.warning(
  128. "Didn't extract any entities and relationships, maybe your LLM is not working"
  129. )
  130. if not len(all_entities_data):
  131. logging.warning("Didn't extract any entities")
  132. if not len(all_relationships_data):
  133. logging.warning("Didn't extract any relationships")
  134. return all_entities_data, all_relationships_data
  135. async def _merge_nodes(self, entity_name: str, entities: list[dict], all_relationships_data):
  136. if not entities:
  137. return
  138. already_entity_types = []
  139. already_source_ids = []
  140. already_description = []
  141. already_node = self._get_entity_(entity_name)
  142. if already_node:
  143. already_entity_types.append(already_node["entity_type"])
  144. already_source_ids.extend(already_node["source_id"])
  145. already_description.append(already_node["description"])
  146. entity_type = sorted(
  147. Counter(
  148. [dp["entity_type"] for dp in entities] + already_entity_types
  149. ).items(),
  150. key=lambda x: x[1],
  151. reverse=True,
  152. )[0][0]
  153. description = GRAPH_FIELD_SEP.join(
  154. sorted(set([dp["description"] for dp in entities] + already_description))
  155. )
  156. already_source_ids = flat_uniq_list(entities, "source_id")
  157. description = await self._handle_entity_relation_summary(entity_name, description)
  158. node_data = dict(
  159. entity_type=entity_type,
  160. description=description,
  161. source_id=already_source_ids,
  162. )
  163. node_data["entity_name"] = entity_name
  164. self._set_entity_(entity_name, node_data)
  165. all_relationships_data.append(node_data)
  166. async def _merge_edges(
  167. self,
  168. src_id: str,
  169. tgt_id: str,
  170. edges_data: list[dict],
  171. all_relationships_data=None
  172. ):
  173. if not edges_data:
  174. return
  175. already_weights = []
  176. already_source_ids = []
  177. already_description = []
  178. already_keywords = []
  179. relation = self._get_relation_(src_id, tgt_id)
  180. if relation:
  181. already_weights = [relation["weight"]]
  182. already_source_ids = relation["source_id"]
  183. already_description = [relation["description"]]
  184. already_keywords = relation["keywords"]
  185. weight = sum([dp["weight"] for dp in edges_data] + already_weights)
  186. description = GRAPH_FIELD_SEP.join(
  187. sorted(set([dp["description"] for dp in edges_data] + already_description))
  188. )
  189. keywords = flat_uniq_list(edges_data, "keywords") + already_keywords
  190. source_id = flat_uniq_list(edges_data, "source_id") + already_source_ids
  191. for need_insert_id in [src_id, tgt_id]:
  192. if self._get_entity_(need_insert_id):
  193. continue
  194. self._set_entity_(need_insert_id, {
  195. "source_id": source_id,
  196. "description": description,
  197. "entity_type": 'UNKNOWN'
  198. })
  199. description = await self._handle_entity_relation_summary(
  200. f"({src_id}, {tgt_id})", description
  201. )
  202. edge_data = dict(
  203. src_id=src_id,
  204. tgt_id=tgt_id,
  205. description=description,
  206. keywords=keywords,
  207. weight=weight,
  208. source_id=source_id
  209. )
  210. self._set_relation_(src_id, tgt_id, edge_data)
  211. if all_relationships_data is not None:
  212. all_relationships_data.append(edge_data)
  213. async def _handle_entity_relation_summary(
  214. self,
  215. entity_or_relation_name: str,
  216. description: str
  217. ) -> str:
  218. summary_max_tokens = 512
  219. use_description = truncate(description, summary_max_tokens)
  220. description_list=use_description.split(GRAPH_FIELD_SEP),
  221. if len(description_list) <= 12:
  222. return use_description
  223. prompt_template = SUMMARIZE_DESCRIPTIONS_PROMPT
  224. context_base = dict(
  225. entity_name=entity_or_relation_name,
  226. description_list=description_list,
  227. language=self._language,
  228. )
  229. use_prompt = prompt_template.format(**context_base)
  230. logging.info(f"Trigger summary: {entity_or_relation_name}")
  231. async with chat_limiter:
  232. summary = await trio.to_thread.run_sync(lambda: self._chat(use_prompt, [{"role": "user", "content": "Output: "}], {"temperature": 0.8}))
  233. return summary