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 10KB

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