Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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 os
  18. from collections import defaultdict, Counter
  19. from concurrent.futures import ThreadPoolExecutor
  20. from copy import deepcopy
  21. from typing import Callable
  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
  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. if response.find("**ERROR**") >= 0:
  57. raise Exception(response)
  58. set_llm_cache(self._llm.llm_name, system, response, history, gen_conf)
  59. return response
  60. def _entities_and_relations(self, chunk_key: str, records: list, tuple_delimiter: str):
  61. maybe_nodes = defaultdict(list)
  62. maybe_edges = defaultdict(list)
  63. ent_types = [t.lower() for t in self._entity_types]
  64. for record in records:
  65. record_attributes = split_string_by_multi_markers(
  66. record, [tuple_delimiter]
  67. )
  68. if_entities = handle_single_entity_extraction(
  69. record_attributes, chunk_key
  70. )
  71. if if_entities is not None and if_entities.get("entity_type", "unknown").lower() in ent_types:
  72. maybe_nodes[if_entities["entity_name"]].append(if_entities)
  73. continue
  74. if_relation = handle_single_relationship_extraction(
  75. record_attributes, chunk_key
  76. )
  77. if if_relation is not None:
  78. maybe_edges[(if_relation["src_id"], if_relation["tgt_id"])].append(
  79. if_relation
  80. )
  81. return dict(maybe_nodes), dict(maybe_edges)
  82. def __call__(
  83. self, chunks: list[tuple[str, str]],
  84. callback: Callable | None = None
  85. ):
  86. results = []
  87. max_workers = int(os.environ.get('GRAPH_EXTRACTOR_MAX_WORKERS', 50))
  88. with ThreadPoolExecutor(max_workers=max_workers) as exe:
  89. threads = []
  90. for i, (cid, ck) in enumerate(chunks):
  91. threads.append(
  92. exe.submit(self._process_single_content, (cid, ck)))
  93. for i, _ in enumerate(threads):
  94. n, r, tc = _.result()
  95. if not isinstance(n, Exception):
  96. results.append((n, r))
  97. if callback:
  98. callback(0.5 + 0.1 * i / len(threads), f"Entities extraction progress ... {i + 1}/{len(threads)} ({tc} tokens)")
  99. elif callback:
  100. callback(msg="Knowledge graph extraction error:{}".format(str(n)))
  101. maybe_nodes = defaultdict(list)
  102. maybe_edges = defaultdict(list)
  103. for m_nodes, m_edges in results:
  104. for k, v in m_nodes.items():
  105. maybe_nodes[k].extend(v)
  106. for k, v in m_edges.items():
  107. maybe_edges[tuple(sorted(k))].extend(v)
  108. logging.info("Inserting entities into storage...")
  109. all_entities_data = []
  110. for en_nm, ents in maybe_nodes.items():
  111. all_entities_data.append(self._merge_nodes(en_nm, ents))
  112. logging.info("Inserting relationships into storage...")
  113. all_relationships_data = []
  114. for (src,tgt), rels in maybe_edges.items():
  115. all_relationships_data.append(self._merge_edges(src, tgt, rels))
  116. if not len(all_entities_data) and not len(all_relationships_data):
  117. logging.warning(
  118. "Didn't extract any entities and relationships, maybe your LLM is not working"
  119. )
  120. if not len(all_entities_data):
  121. logging.warning("Didn't extract any entities")
  122. if not len(all_relationships_data):
  123. logging.warning("Didn't extract any relationships")
  124. return all_entities_data, all_relationships_data
  125. def _merge_nodes(self, entity_name: str, entities: list[dict]):
  126. if not entities:
  127. return
  128. already_entity_types = []
  129. already_source_ids = []
  130. already_description = []
  131. already_node = self._get_entity_(entity_name)
  132. if already_node:
  133. already_entity_types.append(already_node["entity_type"])
  134. already_source_ids.extend(already_node["source_id"])
  135. already_description.append(already_node["description"])
  136. entity_type = sorted(
  137. Counter(
  138. [dp["entity_type"] for dp in entities] + already_entity_types
  139. ).items(),
  140. key=lambda x: x[1],
  141. reverse=True,
  142. )[0][0]
  143. description = GRAPH_FIELD_SEP.join(
  144. sorted(set([dp["description"] for dp in entities] + already_description))
  145. )
  146. already_source_ids = flat_uniq_list(entities, "source_id")
  147. description = self._handle_entity_relation_summary(
  148. entity_name, description
  149. )
  150. node_data = dict(
  151. entity_type=entity_type,
  152. description=description,
  153. source_id=already_source_ids,
  154. )
  155. node_data["entity_name"] = entity_name
  156. self._set_entity_(entity_name, node_data)
  157. return node_data
  158. def _merge_edges(
  159. self,
  160. src_id: str,
  161. tgt_id: str,
  162. edges_data: list[dict]
  163. ):
  164. if not edges_data:
  165. return
  166. already_weights = []
  167. already_source_ids = []
  168. already_description = []
  169. already_keywords = []
  170. relation = self._get_relation_(src_id, tgt_id)
  171. if relation:
  172. already_weights = [relation["weight"]]
  173. already_source_ids = relation["source_id"]
  174. already_description = [relation["description"]]
  175. already_keywords = relation["keywords"]
  176. weight = sum([dp["weight"] for dp in edges_data] + already_weights)
  177. description = GRAPH_FIELD_SEP.join(
  178. sorted(set([dp["description"] for dp in edges_data] + already_description))
  179. )
  180. keywords = flat_uniq_list(edges_data, "keywords") + already_keywords
  181. source_id = flat_uniq_list(edges_data, "source_id") + already_source_ids
  182. for need_insert_id in [src_id, tgt_id]:
  183. if self._get_entity_(need_insert_id):
  184. continue
  185. self._set_entity_(need_insert_id, {
  186. "source_id": source_id,
  187. "description": description,
  188. "entity_type": 'UNKNOWN'
  189. })
  190. description = self._handle_entity_relation_summary(
  191. f"({src_id}, {tgt_id})", description
  192. )
  193. edge_data = dict(
  194. src_id=src_id,
  195. tgt_id=tgt_id,
  196. description=description,
  197. keywords=keywords,
  198. weight=weight,
  199. source_id=source_id
  200. )
  201. self._set_relation_(src_id, tgt_id, edge_data)
  202. return edge_data
  203. def _handle_entity_relation_summary(
  204. self,
  205. entity_or_relation_name: str,
  206. description: str
  207. ) -> str:
  208. summary_max_tokens = 512
  209. use_description = truncate(description, summary_max_tokens)
  210. prompt_template = SUMMARIZE_DESCRIPTIONS_PROMPT
  211. context_base = dict(
  212. entity_name=entity_or_relation_name,
  213. description_list=use_description.split(GRAPH_FIELD_SEP),
  214. language=self._language,
  215. )
  216. use_prompt = prompt_template.format(**context_base)
  217. logging.info(f"Trigger summary: {entity_or_relation_name}")
  218. summary = self._chat(use_prompt, [{"role": "assistant", "content": "Output: "}], {"temperature": 0.8})
  219. return summary