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.

graph_extractor.py 5.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  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 re
  8. from typing import Any
  9. from dataclasses import dataclass
  10. from graphrag.general.extractor import Extractor, ENTITY_EXTRACTION_MAX_GLEANINGS
  11. from graphrag.light.graph_prompt import PROMPTS
  12. from graphrag.utils import pack_user_ass_to_openai_messages, split_string_by_multi_markers, chat_limiter
  13. from rag.llm.chat_model import Base as CompletionLLM
  14. import networkx as nx
  15. from rag.utils import num_tokens_from_string
  16. import trio
  17. @dataclass
  18. class GraphExtractionResult:
  19. """Unipartite graph extraction result class definition."""
  20. output: nx.Graph
  21. source_docs: dict[Any, Any]
  22. class GraphExtractor(Extractor):
  23. _max_gleanings: int
  24. def __init__(
  25. self,
  26. llm_invoker: CompletionLLM,
  27. language: str | None = "English",
  28. entity_types: list[str] | None = None,
  29. example_number: int = 2,
  30. max_gleanings: int | None = None,
  31. ):
  32. super().__init__(llm_invoker, language, entity_types)
  33. """Init method definition."""
  34. self._max_gleanings = (
  35. max_gleanings
  36. if max_gleanings is not None
  37. else ENTITY_EXTRACTION_MAX_GLEANINGS
  38. )
  39. self._example_number = example_number
  40. examples = "\n".join(
  41. PROMPTS["entity_extraction_examples"][: int(self._example_number)]
  42. )
  43. example_context_base = dict(
  44. tuple_delimiter=PROMPTS["DEFAULT_TUPLE_DELIMITER"],
  45. record_delimiter=PROMPTS["DEFAULT_RECORD_DELIMITER"],
  46. completion_delimiter=PROMPTS["DEFAULT_COMPLETION_DELIMITER"],
  47. entity_types=",".join(self._entity_types),
  48. language=self._language,
  49. )
  50. # add example's format
  51. examples = examples.format(**example_context_base)
  52. self._entity_extract_prompt = PROMPTS["entity_extraction"]
  53. self._context_base = dict(
  54. tuple_delimiter=PROMPTS["DEFAULT_TUPLE_DELIMITER"],
  55. record_delimiter=PROMPTS["DEFAULT_RECORD_DELIMITER"],
  56. completion_delimiter=PROMPTS["DEFAULT_COMPLETION_DELIMITER"],
  57. entity_types=",".join(self._entity_types),
  58. examples=examples,
  59. language=self._language,
  60. )
  61. self._continue_prompt = PROMPTS["entiti_continue_extraction"]
  62. self._if_loop_prompt = PROMPTS["entiti_if_loop_extraction"]
  63. self._left_token_count = llm_invoker.max_length - num_tokens_from_string(
  64. self._entity_extract_prompt.format(
  65. **self._context_base, input_text="{input_text}"
  66. ).format(**self._context_base, input_text="")
  67. )
  68. self._left_token_count = max(llm_invoker.max_length * 0.6, self._left_token_count)
  69. async def _process_single_content(self, chunk_key_dp: tuple[str, str], chunk_seq: int, num_chunks: int, out_results):
  70. token_count = 0
  71. chunk_key = chunk_key_dp[0]
  72. content = chunk_key_dp[1]
  73. hint_prompt = self._entity_extract_prompt.format(
  74. **self._context_base, input_text="{input_text}"
  75. ).format(**self._context_base, input_text=content)
  76. gen_conf = {"temperature": 0.8}
  77. async with chat_limiter:
  78. final_result = await trio.to_thread.run_sync(lambda: self._chat(hint_prompt, [{"role": "user", "content": "Output:"}], gen_conf))
  79. token_count += num_tokens_from_string(hint_prompt + final_result)
  80. history = pack_user_ass_to_openai_messages("Output:", final_result, self._continue_prompt)
  81. for now_glean_index in range(self._max_gleanings):
  82. async with chat_limiter:
  83. glean_result = await trio.to_thread.run_sync(lambda: self._chat(hint_prompt, history, gen_conf))
  84. history.extend([{"role": "assistant", "content": glean_result}, {"role": "user", "content": self._continue_prompt}])
  85. token_count += num_tokens_from_string("\n".join([m["content"] for m in history]) + hint_prompt + self._continue_prompt)
  86. final_result += glean_result
  87. if now_glean_index == self._max_gleanings - 1:
  88. break
  89. async with chat_limiter:
  90. if_loop_result = await trio.to_thread.run_sync(lambda: self._chat(self._if_loop_prompt, history, gen_conf))
  91. token_count += num_tokens_from_string("\n".join([m["content"] for m in history]) + if_loop_result + self._if_loop_prompt)
  92. if_loop_result = if_loop_result.strip().strip('"').strip("'").lower()
  93. if if_loop_result != "yes":
  94. break
  95. records = split_string_by_multi_markers(
  96. final_result,
  97. [self._context_base["record_delimiter"], self._context_base["completion_delimiter"]],
  98. )
  99. rcds = []
  100. for record in records:
  101. record = re.search(r"\((.*)\)", record)
  102. if record is None:
  103. continue
  104. rcds.append(record.group(1))
  105. records = rcds
  106. maybe_nodes, maybe_edges = self._entities_and_relations(chunk_key, records, self._context_base["tuple_delimiter"])
  107. out_results.append((maybe_nodes, maybe_edges, token_count))
  108. if self.callback:
  109. self.callback(0.5+0.1*len(out_results)/num_chunks, msg = f"Entities extraction of chunk {chunk_seq} {len(out_results)}/{num_chunks} done, {len(maybe_nodes)} nodes, {len(maybe_edges)} edges, {token_count} tokens.")