Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

extractor.py 11KB

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>.*</think>", "", response, flags=re.DOTALL)
  52. if response.find("**ERROR**") >= 0:
  53. raise Exception(response)
  54. set_llm_cache(self._llm.llm_name, system, response, history, gen_conf)
  55. return response
  56. def _entities_and_relations(self, chunk_key: str, records: list, tuple_delimiter: str):
  57. maybe_nodes = defaultdict(list)
  58. maybe_edges = defaultdict(list)
  59. ent_types = [t.lower() for t in self._entity_types]
  60. for record in records:
  61. record_attributes = split_string_by_multi_markers(
  62. record, [tuple_delimiter]
  63. )
  64. if_entities = handle_single_entity_extraction(
  65. record_attributes, chunk_key
  66. )
  67. if if_entities is not None and if_entities.get("entity_type", "unknown").lower() in ent_types:
  68. maybe_nodes[if_entities["entity_name"]].append(if_entities)
  69. continue
  70. if_relation = handle_single_relationship_extraction(
  71. record_attributes, chunk_key
  72. )
  73. if if_relation is not None:
  74. maybe_edges[(if_relation["src_id"], if_relation["tgt_id"])].append(
  75. if_relation
  76. )
  77. return dict(maybe_nodes), dict(maybe_edges)
  78. async def __call__(
  79. self, doc_id: str, chunks: list[str],
  80. callback: Callable | None = None
  81. ):
  82. self.callback = callback
  83. start_ts = trio.current_time()
  84. out_results = []
  85. async with trio.open_nursery() as nursery:
  86. for i, ck in enumerate(chunks):
  87. ck = truncate(ck, int(self._llm.max_length*0.8))
  88. nursery.start_soon(lambda: self._process_single_content((doc_id, ck), i, len(chunks), out_results))
  89. maybe_nodes = defaultdict(list)
  90. maybe_edges = defaultdict(list)
  91. sum_token_count = 0
  92. for m_nodes, m_edges, token_count in out_results:
  93. for k, v in m_nodes.items():
  94. maybe_nodes[k].extend(v)
  95. for k, v in m_edges.items():
  96. maybe_edges[tuple(sorted(k))].extend(v)
  97. sum_token_count += token_count
  98. now = trio.current_time()
  99. if callback:
  100. 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.")
  101. start_ts = now
  102. logging.info("Entities merging...")
  103. all_entities_data = []
  104. async with trio.open_nursery() as nursery:
  105. for en_nm, ents in maybe_nodes.items():
  106. nursery.start_soon(lambda: self._merge_nodes(en_nm, ents, all_entities_data))
  107. now = trio.current_time()
  108. if callback:
  109. callback(msg = f"Entities merging done, {now-start_ts:.2f}s.")
  110. start_ts = now
  111. logging.info("Relationships merging...")
  112. all_relationships_data = []
  113. async with trio.open_nursery() as nursery:
  114. for (src, tgt), rels in maybe_edges.items():
  115. nursery.start_soon(lambda: self._merge_edges(src, tgt, rels, all_relationships_data))
  116. now = trio.current_time()
  117. if callback:
  118. callback(msg = f"Relationships merging done, {now-start_ts:.2f}s.")
  119. if not len(all_entities_data) and not len(all_relationships_data):
  120. logging.warning(
  121. "Didn't extract any entities and relationships, maybe your LLM is not working"
  122. )
  123. if not len(all_entities_data):
  124. logging.warning("Didn't extract any entities")
  125. if not len(all_relationships_data):
  126. logging.warning("Didn't extract any relationships")
  127. return all_entities_data, all_relationships_data
  128. async def _merge_nodes(self, entity_name: str, entities: list[dict], all_relationships_data):
  129. if not entities:
  130. return
  131. entity_type = sorted(
  132. Counter(
  133. [dp["entity_type"] for dp in entities]
  134. ).items(),
  135. key=lambda x: x[1],
  136. reverse=True,
  137. )[0][0]
  138. description = GRAPH_FIELD_SEP.join(
  139. sorted(set([dp["description"] for dp in entities]))
  140. )
  141. already_source_ids = flat_uniq_list(entities, "source_id")
  142. description = await self._handle_entity_relation_summary(entity_name, description)
  143. node_data = dict(
  144. entity_type=entity_type,
  145. description=description,
  146. source_id=already_source_ids,
  147. )
  148. node_data["entity_name"] = entity_name
  149. all_relationships_data.append(node_data)
  150. async def _merge_edges(
  151. self,
  152. src_id: str,
  153. tgt_id: str,
  154. edges_data: list[dict],
  155. all_relationships_data=None
  156. ):
  157. if not edges_data:
  158. return
  159. weight = sum([edge["weight"] for edge in edges_data])
  160. description = GRAPH_FIELD_SEP.join(sorted(set([edge["description"] for edge in edges_data])))
  161. description = await self._handle_entity_relation_summary(f"{src_id} -> {tgt_id}", description)
  162. keywords = flat_uniq_list(edges_data, "keywords")
  163. source_id = flat_uniq_list(edges_data, "source_id")
  164. edge_data = dict(
  165. src_id=src_id,
  166. tgt_id=tgt_id,
  167. description=description,
  168. keywords=keywords,
  169. weight=weight,
  170. source_id=source_id
  171. )
  172. all_relationships_data.append(edge_data)
  173. async def _merge_graph_nodes(self, graph: nx.Graph, nodes: list[str], change: GraphChange):
  174. if len(nodes) <= 1:
  175. return
  176. change.added_updated_nodes.add(nodes[0])
  177. change.removed_nodes.extend(nodes[1:])
  178. nodes_set = set(nodes)
  179. node0_attrs = graph.nodes[nodes[0]]
  180. node0_neighbors = set(graph.neighbors(nodes[0]))
  181. for node1 in nodes[1:]:
  182. # Merge two nodes, keep "entity_name", "entity_type", "page_rank" unchanged.
  183. node1_attrs = graph.nodes[node1]
  184. node0_attrs["description"] += f"{GRAPH_FIELD_SEP}{node1_attrs['description']}"
  185. for attr in ["keywords", "source_id"]:
  186. node0_attrs[attr] = sorted(set(node0_attrs[attr].extend(node1_attrs[attr])))
  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. edge0_attrs["keywords"] = list(set(edge0_attrs["keywords"].extend(edge1_attrs["keywords"])))
  198. edge0_attrs["source_id"] = list(set(edge0_attrs["source_id"].extend(edge1_attrs["source_id"])))
  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