Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

graph_extractor.py 6.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  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. import tiktoken
  11. import trio
  12. from graphrag.general.extractor import Extractor, ENTITY_EXTRACTION_MAX_GLEANINGS
  13. from graphrag.general.graph_prompt import GRAPH_EXTRACTION_PROMPT, CONTINUE_PROMPT, LOOP_PROMPT
  14. from graphrag.utils import ErrorHandlerFn, perform_variable_replacements, chat_limiter, split_string_by_multi_markers
  15. from rag.llm.chat_model import Base as CompletionLLM
  16. import networkx as nx
  17. from rag.utils import num_tokens_from_string
  18. DEFAULT_TUPLE_DELIMITER = "<|>"
  19. DEFAULT_RECORD_DELIMITER = "##"
  20. DEFAULT_COMPLETION_DELIMITER = "<|COMPLETE|>"
  21. @dataclass
  22. class GraphExtractionResult:
  23. """Unipartite graph extraction result class definition."""
  24. output: nx.Graph
  25. source_docs: dict[Any, Any]
  26. class GraphExtractor(Extractor):
  27. """Unipartite graph extractor class definition."""
  28. _join_descriptions: bool
  29. _tuple_delimiter_key: str
  30. _record_delimiter_key: str
  31. _entity_types_key: str
  32. _input_text_key: str
  33. _completion_delimiter_key: str
  34. _entity_name_key: str
  35. _input_descriptions_key: str
  36. _extraction_prompt: str
  37. _summarization_prompt: str
  38. _loop_args: dict[str, Any]
  39. _max_gleanings: int
  40. _on_error: ErrorHandlerFn
  41. def __init__(
  42. self,
  43. llm_invoker: CompletionLLM,
  44. language: str | None = "English",
  45. entity_types: list[str] | None = None,
  46. tuple_delimiter_key: str | None = None,
  47. record_delimiter_key: str | None = None,
  48. input_text_key: str | None = None,
  49. entity_types_key: str | None = None,
  50. completion_delimiter_key: str | None = None,
  51. join_descriptions=True,
  52. max_gleanings: int | None = None,
  53. on_error: ErrorHandlerFn | None = None,
  54. ):
  55. super().__init__(llm_invoker, language, entity_types)
  56. """Init method definition."""
  57. # TODO: streamline construction
  58. self._llm = llm_invoker
  59. self._join_descriptions = join_descriptions
  60. self._input_text_key = input_text_key or "input_text"
  61. self._tuple_delimiter_key = tuple_delimiter_key or "tuple_delimiter"
  62. self._record_delimiter_key = record_delimiter_key or "record_delimiter"
  63. self._completion_delimiter_key = (
  64. completion_delimiter_key or "completion_delimiter"
  65. )
  66. self._entity_types_key = entity_types_key or "entity_types"
  67. self._extraction_prompt = GRAPH_EXTRACTION_PROMPT
  68. self._max_gleanings = (
  69. max_gleanings
  70. if max_gleanings is not None
  71. else ENTITY_EXTRACTION_MAX_GLEANINGS
  72. )
  73. self._on_error = on_error or (lambda _e, _s, _d: None)
  74. self.prompt_token_count = num_tokens_from_string(self._extraction_prompt)
  75. # Construct the looping arguments
  76. encoding = tiktoken.get_encoding("cl100k_base")
  77. yes = encoding.encode("YES")
  78. no = encoding.encode("NO")
  79. self._loop_args = {"logit_bias": {yes[0]: 100, no[0]: 100}, "max_tokens": 1}
  80. # Wire defaults into the prompt variables
  81. self._prompt_variables = {
  82. self._tuple_delimiter_key: DEFAULT_TUPLE_DELIMITER,
  83. self._record_delimiter_key: DEFAULT_RECORD_DELIMITER,
  84. self._completion_delimiter_key: DEFAULT_COMPLETION_DELIMITER,
  85. self._entity_types_key: ",".join(entity_types),
  86. }
  87. async def _process_single_content(self, chunk_key_dp: tuple[str, str], chunk_seq: int, num_chunks: int, out_results):
  88. token_count = 0
  89. chunk_key = chunk_key_dp[0]
  90. content = chunk_key_dp[1]
  91. variables = {
  92. **self._prompt_variables,
  93. self._input_text_key: content,
  94. }
  95. gen_conf = {"temperature": 0.3}
  96. hint_prompt = perform_variable_replacements(self._extraction_prompt, variables=variables)
  97. async with chat_limiter:
  98. response = await trio.to_thread.run_sync(lambda: self._chat(hint_prompt, [{"role": "user", "content": "Output:"}], gen_conf))
  99. token_count += num_tokens_from_string(hint_prompt + response)
  100. results = response or ""
  101. history = [{"role": "system", "content": hint_prompt}, {"role": "user", "content": response}]
  102. # Repeat to ensure we maximize entity count
  103. for i in range(self._max_gleanings):
  104. history.append({"role": "user", "content": CONTINUE_PROMPT})
  105. async with chat_limiter:
  106. response = await trio.to_thread.run_sync(lambda: self._chat("", history, gen_conf))
  107. token_count += num_tokens_from_string("\n".join([m["content"] for m in history]) + response)
  108. results += response or ""
  109. # if this is the final glean, don't bother updating the continuation flag
  110. if i >= self._max_gleanings - 1:
  111. break
  112. history.append({"role": "assistant", "content": response})
  113. history.append({"role": "user", "content": LOOP_PROMPT})
  114. async with chat_limiter:
  115. continuation = await trio.to_thread.run_sync(lambda: self._chat("", history))
  116. token_count += num_tokens_from_string("\n".join([m["content"] for m in history]) + response)
  117. if continuation != "Y":
  118. break
  119. history.append({"role": "assistant", "content": "Y"})
  120. records = split_string_by_multi_markers(
  121. results,
  122. [self._prompt_variables[self._record_delimiter_key], self._prompt_variables[self._completion_delimiter_key]],
  123. )
  124. rcds = []
  125. for record in records:
  126. record = re.search(r"\((.*)\)", record)
  127. if record is None:
  128. continue
  129. rcds.append(record.group(1))
  130. records = rcds
  131. maybe_nodes, maybe_edges = self._entities_and_relations(chunk_key, records, self._prompt_variables[self._tuple_delimiter_key])
  132. out_results.append((maybe_nodes, maybe_edges, token_count))
  133. if self.callback:
  134. 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.")