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 10.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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("graphrag_task", 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("graphrag_task", lock_value=doc_id, timeout=600)
  218. while True:
  219. if graphrag_task_lock.acquire():
  220. break
  221. await trio.sleep(10)
  222. start = trio.current_time()
  223. er = EntityResolution(
  224. llm_bdl,
  225. )
  226. reso = await er(graph, 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. graphrag_task_lock.release()
  233. now = trio.current_time()
  234. callback(msg=f"Graph resolution done in {now - start:.2f}s.")
  235. async def extract_community(
  236. graph,
  237. tenant_id: str,
  238. kb_id: str,
  239. doc_id: str,
  240. llm_bdl,
  241. embed_bdl,
  242. callback,
  243. ):
  244. graphrag_task_lock = RedisDistributedLock("graphrag_task", lock_value=doc_id, timeout=600)
  245. while True:
  246. if graphrag_task_lock.acquire():
  247. break
  248. await trio.sleep(10)
  249. start = trio.current_time()
  250. ext = CommunityReportsExtractor(
  251. llm_bdl,
  252. )
  253. cr = await ext(graph, callback=callback)
  254. community_structure = cr.structured_output
  255. community_reports = cr.output
  256. doc_ids = graph.graph["source_id"]
  257. now = trio.current_time()
  258. callback(
  259. msg=f"Graph extracted {len(cr.structured_output)} communities in {now - start:.2f}s."
  260. )
  261. start = now
  262. chunks = []
  263. for stru, rep in zip(community_structure, community_reports):
  264. obj = {
  265. "report": rep,
  266. "evidences": "\n".join([f["explanation"] for f in stru["findings"]]),
  267. }
  268. chunk = {
  269. "id": get_uuid(),
  270. "docnm_kwd": stru["title"],
  271. "title_tks": rag_tokenizer.tokenize(stru["title"]),
  272. "content_with_weight": json.dumps(obj, ensure_ascii=False),
  273. "content_ltks": rag_tokenizer.tokenize(
  274. obj["report"] + " " + obj["evidences"]
  275. ),
  276. "knowledge_graph_kwd": "community_report",
  277. "weight_flt": stru["weight"],
  278. "entities_kwd": stru["entities"],
  279. "important_kwd": stru["entities"],
  280. "kb_id": kb_id,
  281. "source_id": list(doc_ids),
  282. "available_int": 0,
  283. }
  284. chunk["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(
  285. chunk["content_ltks"]
  286. )
  287. chunks.append(chunk)
  288. await trio.to_thread.run_sync(
  289. lambda: settings.docStoreConn.delete(
  290. {"knowledge_graph_kwd": "community_report", "kb_id": kb_id},
  291. search.index_name(tenant_id),
  292. kb_id,
  293. )
  294. )
  295. es_bulk_size = 4
  296. for b in range(0, len(chunks), es_bulk_size):
  297. 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))
  298. if doc_store_result:
  299. error_message = f"Insert chunk error: {doc_store_result}, please check log file and Elasticsearch/Infinity status!"
  300. raise Exception(error_message)
  301. graphrag_task_lock.release()
  302. now = trio.current_time()
  303. callback(
  304. msg=f"Graph indexed {len(cr.structured_output)} communities in {now - start:.2f}s."
  305. )
  306. return community_structure, community_reports