You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.py 9.9KB

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