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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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 json
  17. import logging
  18. import networkx as nx
  19. import trio
  20. from api import settings
  21. from api.utils import get_uuid
  22. from api.utils.api_utils import timeout
  23. from graphrag.light.graph_extractor import GraphExtractor as LightKGExt
  24. from graphrag.general.graph_extractor import GraphExtractor as GeneralKGExt
  25. from graphrag.general.community_reports_extractor import CommunityReportsExtractor
  26. from graphrag.entity_resolution import EntityResolution
  27. from graphrag.general.extractor import Extractor
  28. from graphrag.utils import (
  29. graph_merge,
  30. get_graph,
  31. set_graph,
  32. chunk_id,
  33. does_graph_contains,
  34. tidy_graph,
  35. GraphChange,
  36. )
  37. from rag.nlp import rag_tokenizer, search
  38. from rag.utils.redis_conn import RedisDistributedLock
  39. async def run_graphrag(
  40. row: dict,
  41. language,
  42. with_resolution: bool,
  43. with_community: bool,
  44. chat_model,
  45. embedding_model,
  46. callback,
  47. ):
  48. start = trio.current_time()
  49. tenant_id, kb_id, doc_id = row["tenant_id"], str(row["kb_id"]), row["doc_id"]
  50. chunks = []
  51. for d in settings.retrievaler.chunk_list(
  52. doc_id, tenant_id, [kb_id], fields=["content_with_weight", "doc_id"]
  53. ):
  54. chunks.append(d["content_with_weight"])
  55. subgraph = await generate_subgraph(
  56. LightKGExt
  57. if "method" not in row["kb_parser_config"].get("graphrag", {}) or row["kb_parser_config"]["graphrag"]["method"] != "general"
  58. else GeneralKGExt,
  59. tenant_id,
  60. kb_id,
  61. doc_id,
  62. chunks,
  63. language,
  64. row["kb_parser_config"]["graphrag"].get("entity_types", []),
  65. chat_model,
  66. embedding_model,
  67. callback,
  68. )
  69. if not subgraph:
  70. return
  71. graphrag_task_lock = RedisDistributedLock(f"graphrag_task_{kb_id}", lock_value=doc_id, timeout=1200)
  72. await graphrag_task_lock.spin_acquire()
  73. callback(msg=f"run_graphrag {doc_id} graphrag_task_lock acquired")
  74. try:
  75. subgraph_nodes = set(subgraph.nodes())
  76. new_graph = await merge_subgraph(
  77. tenant_id,
  78. kb_id,
  79. doc_id,
  80. subgraph,
  81. embedding_model,
  82. callback,
  83. )
  84. assert new_graph is not None
  85. if not with_resolution and not with_community:
  86. return
  87. if with_resolution:
  88. await graphrag_task_lock.spin_acquire()
  89. callback(msg=f"run_graphrag {doc_id} graphrag_task_lock acquired")
  90. await resolve_entities(
  91. new_graph,
  92. subgraph_nodes,
  93. tenant_id,
  94. kb_id,
  95. doc_id,
  96. chat_model,
  97. embedding_model,
  98. callback,
  99. )
  100. if with_community:
  101. await graphrag_task_lock.spin_acquire()
  102. callback(msg=f"run_graphrag {doc_id} graphrag_task_lock acquired")
  103. await extract_community(
  104. new_graph,
  105. tenant_id,
  106. kb_id,
  107. doc_id,
  108. chat_model,
  109. embedding_model,
  110. callback,
  111. )
  112. finally:
  113. graphrag_task_lock.release()
  114. now = trio.current_time()
  115. callback(msg=f"GraphRAG for doc {doc_id} done in {now - start:.2f} seconds.")
  116. return
  117. @timeout(60*60, 1)
  118. async def generate_subgraph(
  119. extractor: Extractor,
  120. tenant_id: str,
  121. kb_id: str,
  122. doc_id: str,
  123. chunks: list[str],
  124. language,
  125. entity_types,
  126. llm_bdl,
  127. embed_bdl,
  128. callback,
  129. ):
  130. contains = await does_graph_contains(tenant_id, kb_id, doc_id)
  131. if contains:
  132. callback(msg=f"Graph already contains {doc_id}")
  133. return None
  134. start = trio.current_time()
  135. ext = extractor(
  136. llm_bdl,
  137. language=language,
  138. entity_types=entity_types,
  139. )
  140. ents, rels = await ext(doc_id, chunks, callback)
  141. subgraph = nx.Graph()
  142. for ent in ents:
  143. assert "description" in ent, f"entity {ent} does not have description"
  144. ent["source_id"] = [doc_id]
  145. subgraph.add_node(ent["entity_name"], **ent)
  146. ignored_rels = 0
  147. for rel in rels:
  148. assert "description" in rel, f"relation {rel} does not have description"
  149. if not subgraph.has_node(rel["src_id"]) or not subgraph.has_node(rel["tgt_id"]):
  150. ignored_rels += 1
  151. continue
  152. rel["source_id"] = [doc_id]
  153. subgraph.add_edge(
  154. rel["src_id"],
  155. rel["tgt_id"],
  156. **rel,
  157. )
  158. if ignored_rels:
  159. callback(msg=f"ignored {ignored_rels} relations due to missing entities.")
  160. tidy_graph(subgraph, callback, check_attribute=False)
  161. subgraph.graph["source_id"] = [doc_id]
  162. chunk = {
  163. "content_with_weight": json.dumps(
  164. nx.node_link_data(subgraph, edges="edges"), ensure_ascii=False
  165. ),
  166. "knowledge_graph_kwd": "subgraph",
  167. "kb_id": kb_id,
  168. "source_id": [doc_id],
  169. "available_int": 0,
  170. "removed_kwd": "N",
  171. }
  172. cid = chunk_id(chunk)
  173. await trio.to_thread.run_sync(
  174. lambda: settings.docStoreConn.delete(
  175. {"knowledge_graph_kwd": "subgraph", "source_id": doc_id}, search.index_name(tenant_id), kb_id
  176. )
  177. )
  178. await trio.to_thread.run_sync(
  179. lambda: settings.docStoreConn.insert(
  180. [{"id": cid, **chunk}], search.index_name(tenant_id), kb_id
  181. )
  182. )
  183. now = trio.current_time()
  184. callback(msg=f"generated subgraph for doc {doc_id} in {now - start:.2f} seconds.")
  185. return subgraph
  186. @timeout(60*3)
  187. async def merge_subgraph(
  188. tenant_id: str,
  189. kb_id: str,
  190. doc_id: str,
  191. subgraph: nx.Graph,
  192. embedding_model,
  193. callback,
  194. ):
  195. start = trio.current_time()
  196. change = GraphChange()
  197. old_graph = await get_graph(tenant_id, kb_id, subgraph.graph["source_id"])
  198. if old_graph is not None:
  199. logging.info("Merge with an exiting graph...................")
  200. tidy_graph(old_graph, callback)
  201. new_graph = graph_merge(old_graph, subgraph, change)
  202. else:
  203. new_graph = subgraph
  204. change.added_updated_nodes = set(new_graph.nodes())
  205. change.added_updated_edges = set(new_graph.edges())
  206. pr = nx.pagerank(new_graph)
  207. for node_name, pagerank in pr.items():
  208. new_graph.nodes[node_name]["pagerank"] = pagerank
  209. await set_graph(tenant_id, kb_id, embedding_model, new_graph, change, callback)
  210. now = trio.current_time()
  211. callback(
  212. msg=f"merging subgraph for doc {doc_id} into the global graph done in {now - start:.2f} seconds."
  213. )
  214. return new_graph
  215. @timeout(60*30, 1)
  216. async def resolve_entities(
  217. graph,
  218. subgraph_nodes: set[str],
  219. tenant_id: str,
  220. kb_id: str,
  221. doc_id: str,
  222. llm_bdl,
  223. embed_bdl,
  224. callback,
  225. ):
  226. start = trio.current_time()
  227. er = EntityResolution(
  228. llm_bdl,
  229. )
  230. reso = await er(graph, subgraph_nodes, callback=callback)
  231. graph = reso.graph
  232. change = reso.change
  233. callback(msg=f"Graph resolution removed {len(change.removed_nodes)} nodes and {len(change.removed_edges)} edges.")
  234. callback(msg="Graph resolution updated pagerank.")
  235. await set_graph(tenant_id, kb_id, embed_bdl, graph, change, callback)
  236. now = trio.current_time()
  237. callback(msg=f"Graph resolution done in {now - start:.2f}s.")
  238. @timeout(60*30, 1)
  239. async def extract_community(
  240. graph,
  241. tenant_id: str,
  242. kb_id: str,
  243. doc_id: str,
  244. llm_bdl,
  245. embed_bdl,
  246. callback,
  247. ):
  248. start = trio.current_time()
  249. ext = CommunityReportsExtractor(
  250. llm_bdl,
  251. )
  252. cr = await ext(graph, callback=callback)
  253. community_structure = cr.structured_output
  254. community_reports = cr.output
  255. doc_ids = graph.graph["source_id"]
  256. now = trio.current_time()
  257. callback(
  258. msg=f"Graph extracted {len(cr.structured_output)} communities in {now - start:.2f}s."
  259. )
  260. start = now
  261. chunks = []
  262. for stru, rep in zip(community_structure, community_reports):
  263. obj = {
  264. "report": rep,
  265. "evidences": "\n".join([f.get("explanation", "") for f in stru["findings"]]),
  266. }
  267. chunk = {
  268. "id": get_uuid(),
  269. "docnm_kwd": stru["title"],
  270. "title_tks": rag_tokenizer.tokenize(stru["title"]),
  271. "content_with_weight": json.dumps(obj, ensure_ascii=False),
  272. "content_ltks": rag_tokenizer.tokenize(
  273. obj["report"] + " " + obj["evidences"]
  274. ),
  275. "knowledge_graph_kwd": "community_report",
  276. "weight_flt": stru["weight"],
  277. "entities_kwd": stru["entities"],
  278. "important_kwd": stru["entities"],
  279. "kb_id": kb_id,
  280. "source_id": list(doc_ids),
  281. "available_int": 0,
  282. }
  283. chunk["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(
  284. chunk["content_ltks"]
  285. )
  286. chunks.append(chunk)
  287. await trio.to_thread.run_sync(
  288. lambda: settings.docStoreConn.delete(
  289. {"knowledge_graph_kwd": "community_report", "kb_id": kb_id},
  290. search.index_name(tenant_id),
  291. kb_id,
  292. )
  293. )
  294. es_bulk_size = 4
  295. for b in range(0, len(chunks), es_bulk_size):
  296. doc_store_result = await trio.to_thread.run_sync(lambda: settings.docStoreConn.insert(chunks[b:b + es_bulk_size], search.index_name(tenant_id), kb_id))
  297. if doc_store_result:
  298. error_message = f"Insert chunk error: {doc_store_result}, please check log file and Elasticsearch/Infinity status!"
  299. raise Exception(error_message)
  300. now = trio.current_time()
  301. callback(
  302. msg=f"Graph indexed {len(cr.structured_output)} communities in {now - start:.2f}s."
  303. )
  304. return community_structure, community_reports