Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

extractor.py 9.8KB

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