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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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. ck = truncate(ck, int(self._llm.max_length*0.8))
  92. threads.append(
  93. exe.submit(self._process_single_content, (cid, ck)))
  94. for i, _ in enumerate(threads):
  95. n, r, tc = _.result()
  96. if not isinstance(n, Exception):
  97. results.append((n, r))
  98. if callback:
  99. callback(0.5 + 0.1 * i / len(threads), f"Entities extraction progress ... {i + 1}/{len(threads)} ({tc} tokens)")
  100. elif callback:
  101. callback(msg="Knowledge graph extraction error:{}".format(str(n)))
  102. maybe_nodes = defaultdict(list)
  103. maybe_edges = defaultdict(list)
  104. for m_nodes, m_edges in results:
  105. for k, v in m_nodes.items():
  106. maybe_nodes[k].extend(v)
  107. for k, v in m_edges.items():
  108. maybe_edges[tuple(sorted(k))].extend(v)
  109. logging.info("Inserting entities into storage...")
  110. all_entities_data = []
  111. for en_nm, ents in maybe_nodes.items():
  112. all_entities_data.append(self._merge_nodes(en_nm, ents))
  113. logging.info("Inserting relationships into storage...")
  114. all_relationships_data = []
  115. for (src,tgt), rels in maybe_edges.items():
  116. all_relationships_data.append(self._merge_edges(src, tgt, rels))
  117. if not len(all_entities_data) and not len(all_relationships_data):
  118. logging.warning(
  119. "Didn't extract any entities and relationships, maybe your LLM is not working"
  120. )
  121. if not len(all_entities_data):
  122. logging.warning("Didn't extract any entities")
  123. if not len(all_relationships_data):
  124. logging.warning("Didn't extract any relationships")
  125. return all_entities_data, all_relationships_data
  126. def _merge_nodes(self, entity_name: str, entities: list[dict]):
  127. if not entities:
  128. return
  129. already_entity_types = []
  130. already_source_ids = []
  131. already_description = []
  132. already_node = self._get_entity_(entity_name)
  133. if already_node:
  134. already_entity_types.append(already_node["entity_type"])
  135. already_source_ids.extend(already_node["source_id"])
  136. already_description.append(already_node["description"])
  137. entity_type = sorted(
  138. Counter(
  139. [dp["entity_type"] for dp in entities] + already_entity_types
  140. ).items(),
  141. key=lambda x: x[1],
  142. reverse=True,
  143. )[0][0]
  144. description = GRAPH_FIELD_SEP.join(
  145. sorted(set([dp["description"] for dp in entities] + already_description))
  146. )
  147. already_source_ids = flat_uniq_list(entities, "source_id")
  148. description = self._handle_entity_relation_summary(
  149. entity_name, description
  150. )
  151. node_data = dict(
  152. entity_type=entity_type,
  153. description=description,
  154. source_id=already_source_ids,
  155. )
  156. node_data["entity_name"] = entity_name
  157. self._set_entity_(entity_name, node_data)
  158. return node_data
  159. def _merge_edges(
  160. self,
  161. src_id: str,
  162. tgt_id: str,
  163. edges_data: list[dict]
  164. ):
  165. if not edges_data:
  166. return
  167. already_weights = []
  168. already_source_ids = []
  169. already_description = []
  170. already_keywords = []
  171. relation = self._get_relation_(src_id, tgt_id)
  172. if relation:
  173. already_weights = [relation["weight"]]
  174. already_source_ids = relation["source_id"]
  175. already_description = [relation["description"]]
  176. already_keywords = relation["keywords"]
  177. weight = sum([dp["weight"] for dp in edges_data] + already_weights)
  178. description = GRAPH_FIELD_SEP.join(
  179. sorted(set([dp["description"] for dp in edges_data] + already_description))
  180. )
  181. keywords = flat_uniq_list(edges_data, "keywords") + already_keywords
  182. source_id = flat_uniq_list(edges_data, "source_id") + already_source_ids
  183. for need_insert_id in [src_id, tgt_id]:
  184. if self._get_entity_(need_insert_id):
  185. continue
  186. self._set_entity_(need_insert_id, {
  187. "source_id": source_id,
  188. "description": description,
  189. "entity_type": 'UNKNOWN'
  190. })
  191. description = self._handle_entity_relation_summary(
  192. f"({src_id}, {tgt_id})", description
  193. )
  194. edge_data = dict(
  195. src_id=src_id,
  196. tgt_id=tgt_id,
  197. description=description,
  198. keywords=keywords,
  199. weight=weight,
  200. source_id=source_id
  201. )
  202. self._set_relation_(src_id, tgt_id, edge_data)
  203. return edge_data
  204. def _handle_entity_relation_summary(
  205. self,
  206. entity_or_relation_name: str,
  207. description: str
  208. ) -> str:
  209. summary_max_tokens = 512
  210. use_description = truncate(description, summary_max_tokens)
  211. prompt_template = SUMMARIZE_DESCRIPTIONS_PROMPT
  212. context_base = dict(
  213. entity_name=entity_or_relation_name,
  214. description_list=use_description.split(GRAPH_FIELD_SEP),
  215. language=self._language,
  216. )
  217. use_prompt = prompt_template.format(**context_base)
  218. logging.info(f"Trigger summary: {entity_or_relation_name}")
  219. summary = self._chat(use_prompt, [{"role": "user", "content": "Output: "}], {"temperature": 0.8})
  220. return summary