您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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