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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  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. response = await trio.to_thread.run_sync(lambda: self._chat(text, [{"role": "user", "content": "Output:"}], gen_conf))
  81. token_count += num_tokens_from_string(text + response)
  82. response = re.sub(r"^[^\{]*", "", response)
  83. response = re.sub(r"[^\}]*$", "", response)
  84. response = re.sub(r"\{\{", "{", response)
  85. response = re.sub(r"\}\}", "}", response)
  86. logging.debug(response)
  87. try:
  88. response = json.loads(response)
  89. except json.JSONDecodeError as e:
  90. logging.error(f"Failed to parse JSON response: {e}")
  91. logging.error(f"Response content: {response}")
  92. return
  93. if not dict_has_keys_with_types(response, [
  94. ("title", str),
  95. ("summary", str),
  96. ("findings", list),
  97. ("rating", float),
  98. ("rating_explanation", str),
  99. ]):
  100. return
  101. response["weight"] = weight
  102. response["entities"] = ents
  103. add_community_info2graph(graph, ents, response["title"])
  104. res_str.append(self._get_text_output(response))
  105. res_dict.append(response)
  106. over += 1
  107. if callback:
  108. callback(msg=f"Communities: {over}/{total}, used tokens: {token_count}")
  109. st = trio.current_time()
  110. async with trio.open_nursery() as nursery:
  111. for level, comm in communities.items():
  112. logging.info(f"Level {level}: Community: {len(comm.keys())}")
  113. for community in comm.items():
  114. nursery.start_soon(extract_community_report, community)
  115. if callback:
  116. callback(msg=f"Community reports done in {trio.current_time() - st:.2f}s, used tokens: {token_count}")
  117. return CommunityReportsResult(
  118. structured_output=res_dict,
  119. output=res_str,
  120. )
  121. def _get_text_output(self, parsed_output: dict) -> str:
  122. title = parsed_output.get("title", "Report")
  123. summary = parsed_output.get("summary", "")
  124. findings = parsed_output.get("findings", [])
  125. def finding_summary(finding: dict):
  126. if isinstance(finding, str):
  127. return finding
  128. return finding.get("summary")
  129. def finding_explanation(finding: dict):
  130. if isinstance(finding, str):
  131. return ""
  132. return finding.get("explanation")
  133. report_sections = "\n\n".join(
  134. f"## {finding_summary(f)}\n\n{finding_explanation(f)}" for f in findings
  135. )
  136. return f"# {title}\n\n{summary}\n\n{report_sections}"