您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

community_reports_extractor.py 5.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  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
  20. from rag.utils import num_tokens_from_string
  21. from timeit import default_timer as timer
  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. get_entity: Callable | None = None,
  36. set_entity: Callable | None = None,
  37. get_relation: Callable | None = None,
  38. set_relation: Callable | None = None,
  39. max_report_length: int | None = None,
  40. ):
  41. super().__init__(llm_invoker, get_entity=get_entity, set_entity=set_entity, get_relation=get_relation, set_relation=set_relation)
  42. """Init method definition."""
  43. self._llm = llm_invoker
  44. self._extraction_prompt = COMMUNITY_REPORT_PROMPT
  45. self._max_report_length = max_report_length or 1500
  46. def __call__(self, graph: nx.Graph, callback: Callable | None = None):
  47. for node_degree in graph.degree:
  48. graph.nodes[str(node_degree[0])]["rank"] = int(node_degree[1])
  49. communities: dict[str, dict[str, list]] = leiden.run(graph, {})
  50. total = sum([len(comm.items()) for _, comm in communities.items()])
  51. res_str = []
  52. res_dict = []
  53. over, token_count = 0, 0
  54. st = timer()
  55. for level, comm in communities.items():
  56. logging.info(f"Level {level}: Community: {len(comm.keys())}")
  57. for cm_id, ents in comm.items():
  58. weight = ents["weight"]
  59. ents = ents["nodes"]
  60. ent_df = pd.DataFrame(self._get_entity_(ents)).dropna()#[{"entity": n, **graph.nodes[n]} for n in ents])
  61. if ent_df.empty:
  62. continue
  63. ent_df["entity"] = ent_df["entity_name"]
  64. del ent_df["entity_name"]
  65. rela_df = pd.DataFrame(self._get_relation_(list(ent_df["entity"]), list(ent_df["entity"]), 10000))
  66. if rela_df.empty:
  67. continue
  68. rela_df["source"] = rela_df["src_id"]
  69. rela_df["target"] = rela_df["tgt_id"]
  70. del rela_df["src_id"]
  71. del rela_df["tgt_id"]
  72. prompt_variables = {
  73. "entity_df": ent_df.to_csv(index_label="id"),
  74. "relation_df": rela_df.to_csv(index_label="id")
  75. }
  76. text = perform_variable_replacements(self._extraction_prompt, variables=prompt_variables)
  77. gen_conf = {"temperature": 0.3}
  78. try:
  79. response = self._chat(text, [{"role": "user", "content": "Output:"}], gen_conf)
  80. token_count += num_tokens_from_string(text + response)
  81. response = re.sub(r"^[^\{]*", "", response)
  82. response = re.sub(r"[^\}]*$", "", response)
  83. response = re.sub(r"\{\{", "{", response)
  84. response = re.sub(r"\}\}", "}", response)
  85. logging.debug(response)
  86. response = json.loads(response)
  87. if not dict_has_keys_with_types(response, [
  88. ("title", str),
  89. ("summary", str),
  90. ("findings", list),
  91. ("rating", float),
  92. ("rating_explanation", str),
  93. ]):
  94. continue
  95. response["weight"] = weight
  96. response["entities"] = ents
  97. except Exception:
  98. logging.exception("CommunityReportsExtractor got exception")
  99. continue
  100. add_community_info2graph(graph, ents, response["title"])
  101. res_str.append(self._get_text_output(response))
  102. res_dict.append(response)
  103. over += 1
  104. if callback:
  105. callback(msg=f"Communities: {over}/{total}, elapsed: {timer() - st}s, used tokens: {token_count}")
  106. return CommunityReportsResult(
  107. structured_output=res_dict,
  108. output=res_str,
  109. )
  110. def _get_text_output(self, parsed_output: dict) -> str:
  111. title = parsed_output.get("title", "Report")
  112. summary = parsed_output.get("summary", "")
  113. findings = parsed_output.get("findings", [])
  114. def finding_summary(finding: dict):
  115. if isinstance(finding, str):
  116. return finding
  117. return finding.get("summary")
  118. def finding_explanation(finding: dict):
  119. if isinstance(finding, str):
  120. return ""
  121. return finding.get("explanation")
  122. report_sections = "\n\n".join(
  123. f"## {finding_summary(f)}\n\n{finding_explanation(f)}" for f in findings
  124. )
  125. return f"# {title}\n\n{summary}\n\n{report_sections}"