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.

index.py 9.7KB

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