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.

community_reports_extractor.py 6.2KB

fix(nursery): Fix Closure Trap Issues in Trio Concurrent Tasks (#7106) ## Problem Description Multiple files in the RAGFlow project contain closure trap issues when using lambda functions with `trio.open_nursery()`. This problem causes concurrent tasks created in loops to reference the same variable, resulting in all tasks processing the same data (the data from the last iteration) rather than each task processing its corresponding data from the loop. ## Issue Details When using a `lambda` to create a closure function and passing it to `nursery.start_soon()` within a loop, the lambda function captures a reference to the loop variable rather than its value. For example: ```python # Problematic code async with trio.open_nursery() as nursery: for d in docs: nursery.start_soon(lambda: doc_keyword_extraction(chat_mdl, d, topn)) ``` In this pattern, when concurrent tasks begin execution, `d` has already become the value after the loop ends (typically the last element), causing all tasks to use the same data. ## Fix Solution Changed the way concurrent tasks are created with `nursery.start_soon()` by leveraging Trio's API design to directly pass the function and its arguments separately: ```python # Fixed code async with trio.open_nursery() as nursery: for d in docs: nursery.start_soon(doc_keyword_extraction, chat_mdl, d, topn) ``` This way, each task uses the parameter values at the time of the function call, rather than references captured through closures. ## Fixed Files Fixed closure traps in the following files: 1. `rag/svr/task_executor.py`: 3 fixes, involving document keyword extraction, question generation, and tag processing 2. `rag/raptor.py`: 1 fix, involving document summarization 3. `graphrag/utils.py`: 2 fixes, involving graph node and edge processing 4. `graphrag/entity_resolution.py`: 2 fixes, involving entity resolution and graph node merging 5. `graphrag/general/mind_map_extractor.py`: 2 fixes, involving document processing 6. `graphrag/general/extractor.py`: 3 fixes, involving content processing and graph node/edge merging 7. `graphrag/general/community_reports_extractor.py`: 1 fix, involving community report extraction ## Potential Impact This fix resolves a serious concurrency issue that could have caused: - Data processing errors (processing duplicate data) - Performance degradation (all tasks working on the same data) - Inconsistent results (some data not being processed) After the fix, all concurrent tasks should correctly process their respective data, improving system correctness and reliability.
6 kuukautta sitten
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. # Copyright (c) 2024 Microsoft Corporation.
  2. # Licensed under the MIT License
  3. """
  4. Reference:
  5. - [graphrag](https://github.com/microsoft/graphrag)
  6. """
  7. import logging
  8. import json
  9. import re
  10. from typing import Callable
  11. from dataclasses import dataclass
  12. import networkx as nx
  13. import pandas as pd
  14. from graphrag.general import leiden
  15. from graphrag.general.community_report_prompt import COMMUNITY_REPORT_PROMPT
  16. from graphrag.general.extractor import Extractor
  17. from graphrag.general.leiden import add_community_info2graph
  18. from rag.llm.chat_model import Base as CompletionLLM
  19. from graphrag.utils import perform_variable_replacements, dict_has_keys_with_types, chat_limiter
  20. from rag.utils import num_tokens_from_string
  21. import trio
  22. @dataclass
  23. class CommunityReportsResult:
  24. """Community reports result class definition."""
  25. output: list[str]
  26. structured_output: list[dict]
  27. class CommunityReportsExtractor(Extractor):
  28. """Community reports extractor class definition."""
  29. _extraction_prompt: str
  30. _output_formatter_prompt: str
  31. _max_report_length: int
  32. def __init__(
  33. self,
  34. llm_invoker: CompletionLLM,
  35. max_report_length: int | None = None,
  36. ):
  37. super().__init__(llm_invoker)
  38. """Init method definition."""
  39. self._llm = llm_invoker
  40. self._extraction_prompt = COMMUNITY_REPORT_PROMPT
  41. self._max_report_length = max_report_length or 1500
  42. async def __call__(self, graph: nx.Graph, callback: Callable | None = None):
  43. for node_degree in graph.degree:
  44. graph.nodes[str(node_degree[0])]["rank"] = int(node_degree[1])
  45. communities: dict[str, dict[str, list]] = leiden.run(graph, {})
  46. total = sum([len(comm.items()) for _, comm in communities.items()])
  47. res_str = []
  48. res_dict = []
  49. over, token_count = 0, 0
  50. async def extract_community_report(community):
  51. nonlocal res_str, res_dict, over, token_count
  52. cm_id, cm = community
  53. weight = cm["weight"]
  54. ents = cm["nodes"]
  55. if len(ents) < 2:
  56. return
  57. ent_list = [{"entity": ent, "description": graph.nodes[ent]["description"]} for ent in ents]
  58. ent_df = pd.DataFrame(ent_list)
  59. rela_list = []
  60. k = 0
  61. for i in range(0, len(ents)):
  62. if k >= 10000:
  63. break
  64. for j in range(i + 1, len(ents)):
  65. if k >= 10000:
  66. break
  67. edge = graph.get_edge_data(ents[i], ents[j])
  68. if edge is None:
  69. continue
  70. rela_list.append({"source": ents[i], "target": ents[j], "description": edge["description"]})
  71. k += 1
  72. rela_df = pd.DataFrame(rela_list)
  73. prompt_variables = {
  74. "entity_df": ent_df.to_csv(index_label="id"),
  75. "relation_df": rela_df.to_csv(index_label="id")
  76. }
  77. text = perform_variable_replacements(self._extraction_prompt, variables=prompt_variables)
  78. gen_conf = {"temperature": 0.3}
  79. async with chat_limiter:
  80. try:
  81. with trio.move_on_after(120) as cancel_scope:
  82. response = await trio.to_thread.run_sync( self._chat, text, [{"role": "user", "content": "Output:"}], gen_conf)
  83. if cancel_scope.cancelled_caught:
  84. logging.warning("extract_community_report._chat timeout, skipping...")
  85. return
  86. except Exception as e:
  87. logging.error(f"extract_community_report._chat failed: {e}")
  88. return
  89. token_count += num_tokens_from_string(text + response)
  90. response = re.sub(r"^[^\{]*", "", response)
  91. response = re.sub(r"[^\}]*$", "", response)
  92. response = re.sub(r"\{\{", "{", response)
  93. response = re.sub(r"\}\}", "}", response)
  94. logging.debug(response)
  95. try:
  96. response = json.loads(response)
  97. except json.JSONDecodeError as e:
  98. logging.error(f"Failed to parse JSON response: {e}")
  99. logging.error(f"Response content: {response}")
  100. return
  101. if not dict_has_keys_with_types(response, [
  102. ("title", str),
  103. ("summary", str),
  104. ("findings", list),
  105. ("rating", float),
  106. ("rating_explanation", str),
  107. ]):
  108. return
  109. response["weight"] = weight
  110. response["entities"] = ents
  111. add_community_info2graph(graph, ents, response["title"])
  112. res_str.append(self._get_text_output(response))
  113. res_dict.append(response)
  114. over += 1
  115. if callback:
  116. callback(msg=f"Communities: {over}/{total}, used tokens: {token_count}")
  117. st = trio.current_time()
  118. async with trio.open_nursery() as nursery:
  119. for level, comm in communities.items():
  120. logging.info(f"Level {level}: Community: {len(comm.keys())}")
  121. for community in comm.items():
  122. nursery.start_soon(extract_community_report, community)
  123. if callback:
  124. callback(msg=f"Community reports done in {trio.current_time() - st:.2f}s, used tokens: {token_count}")
  125. return CommunityReportsResult(
  126. structured_output=res_dict,
  127. output=res_str,
  128. )
  129. def _get_text_output(self, parsed_output: dict) -> str:
  130. title = parsed_output.get("title", "Report")
  131. summary = parsed_output.get("summary", "")
  132. findings = parsed_output.get("findings", [])
  133. def finding_summary(finding: dict):
  134. if isinstance(finding, str):
  135. return finding
  136. return finding.get("summary")
  137. def finding_explanation(finding: dict):
  138. if isinstance(finding, str):
  139. return ""
  140. return finding.get("explanation")
  141. report_sections = "\n\n".join(
  142. f"## {finding_summary(f)}\n\n{finding_explanation(f)}" for f in findings
  143. )
  144. return f"# {title}\n\n{summary}\n\n{report_sections}"