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.

claim_extractor.py 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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 argparse
  8. import json
  9. import logging
  10. import re
  11. import traceback
  12. from dataclasses import dataclass
  13. from typing import Any
  14. import tiktoken
  15. from graphrag.claim_prompt import CLAIM_EXTRACTION_PROMPT, CONTINUE_PROMPT, LOOP_PROMPT
  16. from rag.llm.chat_model import Base as CompletionLLM
  17. from graphrag.utils import ErrorHandlerFn, perform_variable_replacements
  18. DEFAULT_TUPLE_DELIMITER = "<|>"
  19. DEFAULT_RECORD_DELIMITER = "##"
  20. DEFAULT_COMPLETION_DELIMITER = "<|COMPLETE|>"
  21. CLAIM_MAX_GLEANINGS = 1
  22. log = logging.getLogger(__name__)
  23. @dataclass
  24. class ClaimExtractorResult:
  25. """Claim extractor result class definition."""
  26. output: list[dict]
  27. source_docs: dict[str, Any]
  28. class ClaimExtractor:
  29. """Claim extractor class definition."""
  30. _llm: CompletionLLM
  31. _extraction_prompt: str
  32. _summary_prompt: str
  33. _output_formatter_prompt: str
  34. _input_text_key: str
  35. _input_entity_spec_key: str
  36. _input_claim_description_key: str
  37. _tuple_delimiter_key: str
  38. _record_delimiter_key: str
  39. _completion_delimiter_key: str
  40. _max_gleanings: int
  41. _on_error: ErrorHandlerFn
  42. def __init__(
  43. self,
  44. llm_invoker: CompletionLLM,
  45. extraction_prompt: str | None = None,
  46. input_text_key: str | None = None,
  47. input_entity_spec_key: str | None = None,
  48. input_claim_description_key: str | None = None,
  49. input_resolved_entities_key: str | None = None,
  50. tuple_delimiter_key: str | None = None,
  51. record_delimiter_key: str | None = None,
  52. completion_delimiter_key: str | None = None,
  53. encoding_model: str | None = None,
  54. max_gleanings: int | None = None,
  55. on_error: ErrorHandlerFn | None = None,
  56. ):
  57. """Init method definition."""
  58. self._llm = llm_invoker
  59. self._extraction_prompt = extraction_prompt or CLAIM_EXTRACTION_PROMPT
  60. self._input_text_key = input_text_key or "input_text"
  61. self._input_entity_spec_key = input_entity_spec_key or "entity_specs"
  62. self._tuple_delimiter_key = tuple_delimiter_key or "tuple_delimiter"
  63. self._record_delimiter_key = record_delimiter_key or "record_delimiter"
  64. self._completion_delimiter_key = (
  65. completion_delimiter_key or "completion_delimiter"
  66. )
  67. self._input_claim_description_key = (
  68. input_claim_description_key or "claim_description"
  69. )
  70. self._input_resolved_entities_key = (
  71. input_resolved_entities_key or "resolved_entities"
  72. )
  73. self._max_gleanings = (
  74. max_gleanings if max_gleanings is not None else CLAIM_MAX_GLEANINGS
  75. )
  76. self._on_error = on_error or (lambda _e, _s, _d: None)
  77. # Construct the looping arguments
  78. encoding = tiktoken.get_encoding(encoding_model or "cl100k_base")
  79. yes = encoding.encode("YES")
  80. no = encoding.encode("NO")
  81. self._loop_args = {"logit_bias": {yes[0]: 100, no[0]: 100}, "max_tokens": 1}
  82. def __call__(
  83. self, inputs: dict[str, Any], prompt_variables: dict | None = None
  84. ) -> ClaimExtractorResult:
  85. """Call method definition."""
  86. if prompt_variables is None:
  87. prompt_variables = {}
  88. texts = inputs[self._input_text_key]
  89. entity_spec = str(inputs[self._input_entity_spec_key])
  90. claim_description = inputs[self._input_claim_description_key]
  91. resolved_entities = inputs.get(self._input_resolved_entities_key, {})
  92. source_doc_map = {}
  93. prompt_args = {
  94. self._input_entity_spec_key: entity_spec,
  95. self._input_claim_description_key: claim_description,
  96. self._tuple_delimiter_key: prompt_variables.get(self._tuple_delimiter_key)
  97. or DEFAULT_TUPLE_DELIMITER,
  98. self._record_delimiter_key: prompt_variables.get(self._record_delimiter_key)
  99. or DEFAULT_RECORD_DELIMITER,
  100. self._completion_delimiter_key: prompt_variables.get(
  101. self._completion_delimiter_key
  102. )
  103. or DEFAULT_COMPLETION_DELIMITER,
  104. }
  105. all_claims: list[dict] = []
  106. for doc_index, text in enumerate(texts):
  107. document_id = f"d{doc_index}"
  108. try:
  109. claims = self._process_document(prompt_args, text, doc_index)
  110. all_claims += [
  111. self._clean_claim(c, document_id, resolved_entities) for c in claims
  112. ]
  113. source_doc_map[document_id] = text
  114. except Exception as e:
  115. log.exception("error extracting claim")
  116. self._on_error(
  117. e,
  118. traceback.format_exc(),
  119. {"doc_index": doc_index, "text": text},
  120. )
  121. continue
  122. return ClaimExtractorResult(
  123. output=all_claims,
  124. source_docs=source_doc_map,
  125. )
  126. def _clean_claim(
  127. self, claim: dict, document_id: str, resolved_entities: dict
  128. ) -> dict:
  129. # clean the parsed claims to remove any claims with status = False
  130. obj = claim.get("object_id", claim.get("object"))
  131. subject = claim.get("subject_id", claim.get("subject"))
  132. # If subject or object in resolved entities, then replace with resolved entity
  133. obj = resolved_entities.get(obj, obj)
  134. subject = resolved_entities.get(subject, subject)
  135. claim["object_id"] = obj
  136. claim["subject_id"] = subject
  137. claim["doc_id"] = document_id
  138. return claim
  139. def _process_document(
  140. self, prompt_args: dict, doc, doc_index: int
  141. ) -> list[dict]:
  142. record_delimiter = prompt_args.get(
  143. self._record_delimiter_key, DEFAULT_RECORD_DELIMITER
  144. )
  145. completion_delimiter = prompt_args.get(
  146. self._completion_delimiter_key, DEFAULT_COMPLETION_DELIMITER
  147. )
  148. variables = {
  149. self._input_text_key: doc,
  150. **prompt_args,
  151. }
  152. text = perform_variable_replacements(self._extraction_prompt, variables=variables)
  153. gen_conf = {"temperature": 0.5}
  154. results = self._llm.chat(text, [], gen_conf)
  155. claims = results.strip().removesuffix(completion_delimiter)
  156. history = [{"role": "system", "content": text}, {"role": "assistant", "content": results}]
  157. # Repeat to ensure we maximize entity count
  158. for i in range(self._max_gleanings):
  159. text = perform_variable_replacements(CONTINUE_PROMPT, history=history, variables=variables)
  160. history.append({"role": "user", "content": text})
  161. extension = self._llm.chat("", history, gen_conf)
  162. claims += record_delimiter + extension.strip().removesuffix(
  163. completion_delimiter
  164. )
  165. # If this isn't the last loop, check to see if we should continue
  166. if i >= self._max_gleanings - 1:
  167. break
  168. history.append({"role": "assistant", "content": extension})
  169. history.append({"role": "user", "content": LOOP_PROMPT})
  170. continuation = self._llm.chat("", history, self._loop_args)
  171. if continuation != "YES":
  172. break
  173. result = self._parse_claim_tuples(claims, prompt_args)
  174. for r in result:
  175. r["doc_id"] = f"{doc_index}"
  176. return result
  177. def _parse_claim_tuples(
  178. self, claims: str, prompt_variables: dict
  179. ) -> list[dict[str, Any]]:
  180. """Parse claim tuples."""
  181. record_delimiter = prompt_variables.get(
  182. self._record_delimiter_key, DEFAULT_RECORD_DELIMITER
  183. )
  184. completion_delimiter = prompt_variables.get(
  185. self._completion_delimiter_key, DEFAULT_COMPLETION_DELIMITER
  186. )
  187. tuple_delimiter = prompt_variables.get(
  188. self._tuple_delimiter_key, DEFAULT_TUPLE_DELIMITER
  189. )
  190. def pull_field(index: int, fields: list[str]) -> str | None:
  191. return fields[index].strip() if len(fields) > index else None
  192. result: list[dict[str, Any]] = []
  193. claims_values = (
  194. claims.strip().removesuffix(completion_delimiter).split(record_delimiter)
  195. )
  196. for claim in claims_values:
  197. claim = claim.strip().removeprefix("(").removesuffix(")")
  198. claim = re.sub(r".*Output:", "", claim)
  199. # Ignore the completion delimiter
  200. if claim == completion_delimiter:
  201. continue
  202. claim_fields = claim.split(tuple_delimiter)
  203. o = {
  204. "subject_id": pull_field(0, claim_fields),
  205. "object_id": pull_field(1, claim_fields),
  206. "type": pull_field(2, claim_fields),
  207. "status": pull_field(3, claim_fields),
  208. "start_date": pull_field(4, claim_fields),
  209. "end_date": pull_field(5, claim_fields),
  210. "description": pull_field(6, claim_fields),
  211. "source_text": pull_field(7, claim_fields),
  212. "doc_id": pull_field(8, claim_fields),
  213. }
  214. if any([not o["subject_id"], not o["object_id"], o["subject_id"].lower() == "none", o["object_id"] == "none"]):
  215. continue
  216. result.append(o)
  217. return result
  218. if __name__ == "__main__":
  219. parser = argparse.ArgumentParser()
  220. parser.add_argument('-t', '--tenant_id', default=False, help="Tenant ID", action='store', required=True)
  221. parser.add_argument('-d', '--doc_id', default=False, help="Document ID", action='store', required=True)
  222. args = parser.parse_args()
  223. from api.db import LLMType
  224. from api.db.services.llm_service import LLMBundle
  225. from api.settings import retrievaler
  226. ex = ClaimExtractor(LLMBundle(args.tenant_id, LLMType.CHAT))
  227. docs = [d["content_with_weight"] for d in retrievaler.chunk_list(args.doc_id, args.tenant_id, max_count=12, fields=["content_with_weight"])]
  228. info = {
  229. "input_text": docs,
  230. "entity_specs": "organization, person",
  231. "claim_description": ""
  232. }
  233. claim = ex(info)
  234. print(json.dumps(claim.output, ensure_ascii=False, indent=2))