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.

task_executor.py 30KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. # from beartype import BeartypeConf
  16. # from beartype.claw import beartype_all # <-- you didn't sign up for this
  17. # beartype_all(conf=BeartypeConf(violation_type=UserWarning)) # <-- emit warnings from all code
  18. import random
  19. import sys
  20. from api.utils.log_utils import initRootLogger, get_project_base_directory
  21. from graphrag.general.index import WithCommunity, WithResolution, Dealer
  22. from graphrag.light.graph_extractor import GraphExtractor as LightKGExt
  23. from graphrag.general.graph_extractor import GraphExtractor as GeneralKGExt
  24. from graphrag.utils import get_llm_cache, set_llm_cache, get_tags_from_cache, set_tags_to_cache
  25. CONSUMER_NO = "0" if len(sys.argv) < 2 else sys.argv[1]
  26. CONSUMER_NAME = "task_executor_" + CONSUMER_NO
  27. initRootLogger(CONSUMER_NAME)
  28. import logging
  29. import os
  30. from datetime import datetime
  31. import json
  32. import xxhash
  33. import copy
  34. import re
  35. import time
  36. import threading
  37. from functools import partial
  38. from io import BytesIO
  39. from multiprocessing.context import TimeoutError
  40. from timeit import default_timer as timer
  41. import tracemalloc
  42. import signal
  43. import numpy as np
  44. from peewee import DoesNotExist
  45. from api.db import LLMType, ParserType, TaskStatus
  46. from api.db.services.dialog_service import keyword_extraction, question_proposal, content_tagging
  47. from api.db.services.document_service import DocumentService
  48. from api.db.services.llm_service import LLMBundle
  49. from api.db.services.task_service import TaskService
  50. from api.db.services.file2document_service import File2DocumentService
  51. from api import settings
  52. from api.versions import get_ragflow_version
  53. from api.db.db_models import close_connection
  54. from rag.app import laws, paper, presentation, manual, qa, table, book, resume, picture, naive, one, audio, \
  55. email, tag
  56. from rag.nlp import search, rag_tokenizer
  57. from rag.raptor import RecursiveAbstractiveProcessing4TreeOrganizedRetrieval as Raptor
  58. from rag.settings import DOC_MAXIMUM_SIZE, SVR_QUEUE_NAME, print_rag_settings, TAG_FLD, PAGERANK_FLD
  59. from rag.utils import num_tokens_from_string
  60. from rag.utils.redis_conn import REDIS_CONN, Payload
  61. from rag.utils.storage_factory import STORAGE_IMPL
  62. BATCH_SIZE = 64
  63. FACTORY = {
  64. "general": naive,
  65. ParserType.NAIVE.value: naive,
  66. ParserType.PAPER.value: paper,
  67. ParserType.BOOK.value: book,
  68. ParserType.PRESENTATION.value: presentation,
  69. ParserType.MANUAL.value: manual,
  70. ParserType.LAWS.value: laws,
  71. ParserType.QA.value: qa,
  72. ParserType.TABLE.value: table,
  73. ParserType.RESUME.value: resume,
  74. ParserType.PICTURE.value: picture,
  75. ParserType.ONE.value: one,
  76. ParserType.AUDIO.value: audio,
  77. ParserType.EMAIL.value: email,
  78. ParserType.KG.value: naive,
  79. ParserType.TAG.value: tag
  80. }
  81. CONSUMER_NAME = "task_consumer_" + CONSUMER_NO
  82. PAYLOAD: Payload | None = None
  83. BOOT_AT = datetime.now().astimezone().isoformat(timespec="milliseconds")
  84. PENDING_TASKS = 0
  85. LAG_TASKS = 0
  86. mt_lock = threading.Lock()
  87. DONE_TASKS = 0
  88. FAILED_TASKS = 0
  89. CURRENT_TASK = None
  90. tracemalloc_started = False
  91. # SIGUSR1 handler: start tracemalloc and take snapshot
  92. def start_tracemalloc_and_snapshot(signum, frame):
  93. global tracemalloc_started
  94. if not tracemalloc_started:
  95. logging.info("got SIGUSR1, start tracemalloc")
  96. tracemalloc.start()
  97. tracemalloc_started = True
  98. else:
  99. logging.info("got SIGUSR1, tracemalloc is already running")
  100. timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  101. snapshot_file = f"snapshot_{timestamp}.trace"
  102. snapshot_file = os.path.abspath(os.path.join(get_project_base_directory(), "logs", f"{os.getpid()}_snapshot_{timestamp}.trace"))
  103. snapshot = tracemalloc.take_snapshot()
  104. snapshot.dump(snapshot_file)
  105. logging.info(f"taken snapshot {snapshot_file}")
  106. # SIGUSR2 handler: stop tracemalloc
  107. def stop_tracemalloc(signum, frame):
  108. global tracemalloc_started
  109. if tracemalloc_started:
  110. logging.info("go SIGUSR2, stop tracemalloc")
  111. tracemalloc.stop()
  112. tracemalloc_started = False
  113. else:
  114. logging.info("got SIGUSR2, tracemalloc not running")
  115. class TaskCanceledException(Exception):
  116. def __init__(self, msg):
  117. self.msg = msg
  118. def set_progress(task_id, from_page=0, to_page=-1, prog=None, msg="Processing..."):
  119. global PAYLOAD
  120. if prog is not None and prog < 0:
  121. msg = "[ERROR]" + msg
  122. try:
  123. cancel = TaskService.do_cancel(task_id)
  124. except DoesNotExist:
  125. logging.warning(f"set_progress task {task_id} is unknown")
  126. if PAYLOAD:
  127. PAYLOAD.ack()
  128. PAYLOAD = None
  129. return
  130. if cancel:
  131. msg += " [Canceled]"
  132. prog = -1
  133. if to_page > 0:
  134. if msg:
  135. if from_page < to_page:
  136. msg = f"Page({from_page + 1}~{to_page + 1}): " + msg
  137. if msg:
  138. msg = datetime.now().strftime("%H:%M:%S") + " " + msg
  139. d = {"progress_msg": msg}
  140. if prog is not None:
  141. d["progress"] = prog
  142. logging.info(f"set_progress({task_id}), progress: {prog}, progress_msg: {msg}")
  143. try:
  144. TaskService.update_progress(task_id, d)
  145. except DoesNotExist:
  146. logging.warning(f"set_progress task {task_id} is unknown")
  147. if PAYLOAD:
  148. PAYLOAD.ack()
  149. PAYLOAD = None
  150. return
  151. close_connection()
  152. if cancel and PAYLOAD:
  153. PAYLOAD.ack()
  154. PAYLOAD = None
  155. raise TaskCanceledException(msg)
  156. def collect():
  157. global CONSUMER_NAME, PAYLOAD, DONE_TASKS, FAILED_TASKS
  158. try:
  159. PAYLOAD = REDIS_CONN.get_unacked_for(CONSUMER_NAME, SVR_QUEUE_NAME, "rag_flow_svr_task_broker")
  160. if not PAYLOAD:
  161. PAYLOAD = REDIS_CONN.queue_consumer(SVR_QUEUE_NAME, "rag_flow_svr_task_broker", CONSUMER_NAME)
  162. if not PAYLOAD:
  163. time.sleep(1)
  164. return None
  165. except Exception:
  166. logging.exception("Get task event from queue exception")
  167. return None
  168. msg = PAYLOAD.get_message()
  169. if not msg:
  170. return None
  171. task = None
  172. canceled = False
  173. try:
  174. task = TaskService.get_task(msg["id"])
  175. if task:
  176. _, doc = DocumentService.get_by_id(task["doc_id"])
  177. canceled = doc.run == TaskStatus.CANCEL.value or doc.progress < 0
  178. except DoesNotExist:
  179. pass
  180. except Exception:
  181. logging.exception("collect get_task exception")
  182. if not task or canceled:
  183. state = "is unknown" if not task else "has been cancelled"
  184. with mt_lock:
  185. DONE_TASKS += 1
  186. logging.info(f"collect task {msg['id']} {state}")
  187. return None
  188. task["task_type"] = msg.get("task_type", "")
  189. return task
  190. def get_storage_binary(bucket, name):
  191. return STORAGE_IMPL.get(bucket, name)
  192. def build_chunks(task, progress_callback):
  193. if task["size"] > DOC_MAXIMUM_SIZE:
  194. set_progress(task["id"], prog=-1, msg="File size exceeds( <= %dMb )" %
  195. (int(DOC_MAXIMUM_SIZE / 1024 / 1024)))
  196. return []
  197. chunker = FACTORY[task["parser_id"].lower()]
  198. try:
  199. st = timer()
  200. bucket, name = File2DocumentService.get_storage_address(doc_id=task["doc_id"])
  201. binary = get_storage_binary(bucket, name)
  202. logging.info("From minio({}) {}/{}".format(timer() - st, task["location"], task["name"]))
  203. except TimeoutError:
  204. progress_callback(-1, "Internal server error: Fetch file from minio timeout. Could you try it again.")
  205. logging.exception(
  206. "Minio {}/{} got timeout: Fetch file from minio timeout.".format(task["location"], task["name"]))
  207. raise
  208. except Exception as e:
  209. if re.search("(No such file|not found)", str(e)):
  210. progress_callback(-1, "Can not find file <%s> from minio. Could you try it again?" % task["name"])
  211. else:
  212. progress_callback(-1, "Get file from minio: %s" % str(e).replace("'", ""))
  213. logging.exception("Chunking {}/{} got exception".format(task["location"], task["name"]))
  214. raise
  215. try:
  216. cks = chunker.chunk(task["name"], binary=binary, from_page=task["from_page"],
  217. to_page=task["to_page"], lang=task["language"], callback=progress_callback,
  218. kb_id=task["kb_id"], parser_config=task["parser_config"], tenant_id=task["tenant_id"])
  219. logging.info("Chunking({}) {}/{} done".format(timer() - st, task["location"], task["name"]))
  220. except TaskCanceledException:
  221. raise
  222. except Exception as e:
  223. progress_callback(-1, "Internal server error while chunking: %s" % str(e).replace("'", ""))
  224. logging.exception("Chunking {}/{} got exception".format(task["location"], task["name"]))
  225. raise
  226. docs = []
  227. doc = {
  228. "doc_id": task["doc_id"],
  229. "kb_id": str(task["kb_id"])
  230. }
  231. if task["pagerank"]:
  232. doc[PAGERANK_FLD] = int(task["pagerank"])
  233. el = 0
  234. for ck in cks:
  235. d = copy.deepcopy(doc)
  236. d.update(ck)
  237. d["id"] = xxhash.xxh64((ck["content_with_weight"] + str(d["doc_id"])).encode("utf-8")).hexdigest()
  238. d["create_time"] = str(datetime.now()).replace("T", " ")[:19]
  239. d["create_timestamp_flt"] = datetime.now().timestamp()
  240. if not d.get("image"):
  241. _ = d.pop("image", None)
  242. d["img_id"] = ""
  243. docs.append(d)
  244. continue
  245. try:
  246. output_buffer = BytesIO()
  247. if isinstance(d["image"], bytes):
  248. output_buffer = BytesIO(d["image"])
  249. else:
  250. d["image"].save(output_buffer, format='JPEG')
  251. st = timer()
  252. STORAGE_IMPL.put(task["kb_id"], d["id"], output_buffer.getvalue())
  253. el += timer() - st
  254. except Exception:
  255. logging.exception(
  256. "Saving image of chunk {}/{}/{} got exception".format(task["location"], task["name"], d["id"]))
  257. raise
  258. d["img_id"] = "{}-{}".format(task["kb_id"], d["id"])
  259. del d["image"]
  260. docs.append(d)
  261. logging.info("MINIO PUT({}):{}".format(task["name"], el))
  262. if task["parser_config"].get("auto_keywords", 0):
  263. st = timer()
  264. progress_callback(msg="Start to generate keywords for every chunk ...")
  265. chat_mdl = LLMBundle(task["tenant_id"], LLMType.CHAT, llm_name=task["llm_id"], lang=task["language"])
  266. for d in docs:
  267. cached = get_llm_cache(chat_mdl.llm_name, d["content_with_weight"], "keywords",
  268. {"topn": task["parser_config"]["auto_keywords"]})
  269. if not cached:
  270. cached = keyword_extraction(chat_mdl, d["content_with_weight"],
  271. task["parser_config"]["auto_keywords"])
  272. if cached:
  273. set_llm_cache(chat_mdl.llm_name, d["content_with_weight"], cached, "keywords",
  274. {"topn": task["parser_config"]["auto_keywords"]})
  275. d["important_kwd"] = cached.split(",")
  276. d["important_tks"] = rag_tokenizer.tokenize(" ".join(d["important_kwd"]))
  277. progress_callback(msg="Keywords generation completed in {:.2f}s".format(timer() - st))
  278. if task["parser_config"].get("auto_questions", 0):
  279. st = timer()
  280. progress_callback(msg="Start to generate questions for every chunk ...")
  281. chat_mdl = LLMBundle(task["tenant_id"], LLMType.CHAT, llm_name=task["llm_id"], lang=task["language"])
  282. for d in docs:
  283. cached = get_llm_cache(chat_mdl.llm_name, d["content_with_weight"], "question",
  284. {"topn": task["parser_config"]["auto_questions"]})
  285. if not cached:
  286. cached = question_proposal(chat_mdl, d["content_with_weight"], task["parser_config"]["auto_questions"])
  287. if cached:
  288. set_llm_cache(chat_mdl.llm_name, d["content_with_weight"], cached, "question",
  289. {"topn": task["parser_config"]["auto_questions"]})
  290. d["question_kwd"] = cached.split("\n")
  291. d["question_tks"] = rag_tokenizer.tokenize("\n".join(d["question_kwd"]))
  292. progress_callback(msg="Question generation completed in {:.2f}s".format(timer() - st))
  293. if task["kb_parser_config"].get("tag_kb_ids", []):
  294. progress_callback(msg="Start to tag for every chunk ...")
  295. kb_ids = task["kb_parser_config"]["tag_kb_ids"]
  296. tenant_id = task["tenant_id"]
  297. topn_tags = task["kb_parser_config"].get("topn_tags", 3)
  298. S = 1000
  299. st = timer()
  300. examples = []
  301. all_tags = get_tags_from_cache(kb_ids)
  302. if not all_tags:
  303. all_tags = settings.retrievaler.all_tags_in_portion(tenant_id, kb_ids, S)
  304. set_tags_to_cache(kb_ids, all_tags)
  305. else:
  306. all_tags = json.loads(all_tags)
  307. chat_mdl = LLMBundle(task["tenant_id"], LLMType.CHAT, llm_name=task["llm_id"], lang=task["language"])
  308. for d in docs:
  309. if settings.retrievaler.tag_content(tenant_id, kb_ids, d, all_tags, topn_tags=topn_tags, S=S):
  310. examples.append({"content": d["content_with_weight"], TAG_FLD: d[TAG_FLD]})
  311. continue
  312. cached = get_llm_cache(chat_mdl.llm_name, d["content_with_weight"], all_tags, {"topn": topn_tags})
  313. if not cached:
  314. cached = content_tagging(chat_mdl, d["content_with_weight"], all_tags,
  315. random.choices(examples, k=2) if len(examples)>2 else examples,
  316. topn=topn_tags)
  317. if cached:
  318. cached = json.dumps(cached)
  319. if cached:
  320. set_llm_cache(chat_mdl.llm_name, d["content_with_weight"], cached, all_tags, {"topn": topn_tags})
  321. d[TAG_FLD] = json.loads(cached)
  322. progress_callback(msg="Tagging completed in {:.2f}s".format(timer() - st))
  323. return docs
  324. def init_kb(row, vector_size: int):
  325. idxnm = search.index_name(row["tenant_id"])
  326. return settings.docStoreConn.createIdx(idxnm, row.get("kb_id", ""), vector_size)
  327. def embedding(docs, mdl, parser_config=None, callback=None):
  328. if parser_config is None:
  329. parser_config = {}
  330. batch_size = 16
  331. tts, cnts = [], []
  332. for d in docs:
  333. tts.append(d.get("docnm_kwd", "Title"))
  334. c = "\n".join(d.get("question_kwd", []))
  335. if not c:
  336. c = d["content_with_weight"]
  337. c = re.sub(r"</?(table|td|caption|tr|th)( [^<>]{0,12})?>", " ", c)
  338. if not c:
  339. c = "None"
  340. cnts.append(c)
  341. tk_count = 0
  342. if len(tts) == len(cnts):
  343. vts, c = mdl.encode(tts[0: 1])
  344. tts = np.concatenate([vts for _ in range(len(tts))], axis=0)
  345. tk_count += c
  346. cnts_ = np.array([])
  347. for i in range(0, len(cnts), batch_size):
  348. vts, c = mdl.encode(cnts[i: i + batch_size])
  349. if len(cnts_) == 0:
  350. cnts_ = vts
  351. else:
  352. cnts_ = np.concatenate((cnts_, vts), axis=0)
  353. tk_count += c
  354. callback(prog=0.7 + 0.2 * (i + 1) / len(cnts), msg="")
  355. cnts = cnts_
  356. title_w = float(parser_config.get("filename_embd_weight", 0.1))
  357. vects = (title_w * tts + (1 - title_w) *
  358. cnts) if len(tts) == len(cnts) else cnts
  359. assert len(vects) == len(docs)
  360. vector_size = 0
  361. for i, d in enumerate(docs):
  362. v = vects[i].tolist()
  363. vector_size = len(v)
  364. d["q_%d_vec" % len(v)] = v
  365. return tk_count, vector_size
  366. def run_raptor(row, chat_mdl, embd_mdl, vector_size, callback=None):
  367. chunks = []
  368. vctr_nm = "q_%d_vec"%vector_size
  369. for d in settings.retrievaler.chunk_list(row["doc_id"], row["tenant_id"], [str(row["kb_id"])],
  370. fields=["content_with_weight", vctr_nm]):
  371. chunks.append((d["content_with_weight"], np.array(d[vctr_nm])))
  372. raptor = Raptor(
  373. row["parser_config"]["raptor"].get("max_cluster", 64),
  374. chat_mdl,
  375. embd_mdl,
  376. row["parser_config"]["raptor"]["prompt"],
  377. row["parser_config"]["raptor"]["max_token"],
  378. row["parser_config"]["raptor"]["threshold"]
  379. )
  380. original_length = len(chunks)
  381. chunks = raptor(chunks, row["parser_config"]["raptor"]["random_seed"], callback)
  382. doc = {
  383. "doc_id": row["doc_id"],
  384. "kb_id": [str(row["kb_id"])],
  385. "docnm_kwd": row["name"],
  386. "title_tks": rag_tokenizer.tokenize(row["name"])
  387. }
  388. if row["pagerank"]:
  389. doc[PAGERANK_FLD] = int(row["pagerank"])
  390. res = []
  391. tk_count = 0
  392. for content, vctr in chunks[original_length:]:
  393. d = copy.deepcopy(doc)
  394. d["id"] = xxhash.xxh64((content + str(d["doc_id"])).encode("utf-8")).hexdigest()
  395. d["create_time"] = str(datetime.now()).replace("T", " ")[:19]
  396. d["create_timestamp_flt"] = datetime.now().timestamp()
  397. d[vctr_nm] = vctr.tolist()
  398. d["content_with_weight"] = content
  399. d["content_ltks"] = rag_tokenizer.tokenize(content)
  400. d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
  401. res.append(d)
  402. tk_count += num_tokens_from_string(content)
  403. return res, tk_count
  404. def run_graphrag(row, chat_model, language, embedding_model, callback=None):
  405. chunks = []
  406. for d in settings.retrievaler.chunk_list(row["doc_id"], row["tenant_id"], [str(row["kb_id"])],
  407. fields=["content_with_weight", "doc_id"]):
  408. chunks.append((d["doc_id"], d["content_with_weight"]))
  409. Dealer(LightKGExt if row["parser_config"]["graphrag"]["method"] != 'general' else GeneralKGExt,
  410. row["tenant_id"],
  411. str(row["kb_id"]),
  412. chat_model,
  413. chunks=chunks,
  414. language=language,
  415. entity_types=row["parser_config"]["graphrag"]["entity_types"],
  416. embed_bdl=embedding_model,
  417. callback=callback)
  418. def do_handle_task(task):
  419. task_id = task["id"]
  420. task_from_page = task["from_page"]
  421. task_to_page = task["to_page"]
  422. task_tenant_id = task["tenant_id"]
  423. task_embedding_id = task["embd_id"]
  424. task_language = task["language"]
  425. task_llm_id = task["llm_id"]
  426. task_dataset_id = task["kb_id"]
  427. task_doc_id = task["doc_id"]
  428. task_document_name = task["name"]
  429. task_parser_config = task["parser_config"]
  430. # prepare the progress callback function
  431. progress_callback = partial(set_progress, task_id, task_from_page, task_to_page)
  432. # FIXME: workaround, Infinity doesn't support table parsing method, this check is to notify user
  433. lower_case_doc_engine = settings.DOC_ENGINE.lower()
  434. if lower_case_doc_engine == 'infinity' and task['parser_id'].lower() == 'table':
  435. error_message = "Table parsing method is not supported by Infinity, please use other parsing methods or use Elasticsearch as the document engine."
  436. progress_callback(-1, msg=error_message)
  437. raise Exception(error_message)
  438. try:
  439. task_canceled = TaskService.do_cancel(task_id)
  440. except DoesNotExist:
  441. logging.warning(f"task {task_id} is unknown")
  442. return
  443. if task_canceled:
  444. progress_callback(-1, msg="Task has been canceled.")
  445. return
  446. try:
  447. # bind embedding model
  448. embedding_model = LLMBundle(task_tenant_id, LLMType.EMBEDDING, llm_name=task_embedding_id, lang=task_language)
  449. except Exception as e:
  450. error_message = f'Fail to bind embedding model: {str(e)}'
  451. progress_callback(-1, msg=error_message)
  452. logging.exception(error_message)
  453. raise
  454. vts, _ = embedding_model.encode(["ok"])
  455. vector_size = len(vts[0])
  456. init_kb(task, vector_size)
  457. # Either using RAPTOR or Standard chunking methods
  458. if task.get("task_type", "") == "raptor":
  459. try:
  460. # bind LLM for raptor
  461. chat_model = LLMBundle(task_tenant_id, LLMType.CHAT, llm_name=task_llm_id, lang=task_language)
  462. # run RAPTOR
  463. chunks, token_count = run_raptor(task, chat_model, embedding_model, vector_size, progress_callback)
  464. except TaskCanceledException:
  465. raise
  466. except Exception as e:
  467. error_message = f'Fail to bind LLM used by RAPTOR: {str(e)}'
  468. progress_callback(-1, msg=error_message)
  469. logging.exception(error_message)
  470. raise
  471. # Either using graphrag or Standard chunking methods
  472. elif task.get("task_type", "") == "graphrag":
  473. start_ts = timer()
  474. try:
  475. chat_model = LLMBundle(task_tenant_id, LLMType.CHAT, llm_name=task_llm_id, lang=task_language)
  476. run_graphrag(task, chat_model, task_language, embedding_model, progress_callback)
  477. progress_callback(prog=1.0, msg="Knowledge Graph is done ({:.2f}s)".format(timer() - start_ts))
  478. except TaskCanceledException:
  479. raise
  480. except Exception as e:
  481. error_message = f'Fail to bind LLM used by Knowledge Graph: {str(e)}'
  482. progress_callback(-1, msg=error_message)
  483. logging.exception(error_message)
  484. raise
  485. return
  486. elif task.get("task_type", "") == "graph_resolution":
  487. start_ts = timer()
  488. try:
  489. chat_model = LLMBundle(task_tenant_id, LLMType.CHAT, llm_name=task_llm_id, lang=task_language)
  490. WithResolution(
  491. task["tenant_id"], str(task["kb_id"]),chat_model, embedding_model,
  492. progress_callback
  493. )
  494. progress_callback(prog=1.0, msg="Knowledge Graph resolution is done ({:.2f}s)".format(timer() - start_ts))
  495. except TaskCanceledException:
  496. raise
  497. except Exception as e:
  498. error_message = f'Fail to bind LLM used by Knowledge Graph resolution: {str(e)}'
  499. progress_callback(-1, msg=error_message)
  500. logging.exception(error_message)
  501. raise
  502. return
  503. elif task.get("task_type", "") == "graph_community":
  504. start_ts = timer()
  505. try:
  506. chat_model = LLMBundle(task_tenant_id, LLMType.CHAT, llm_name=task_llm_id, lang=task_language)
  507. WithCommunity(
  508. task["tenant_id"], str(task["kb_id"]), chat_model, embedding_model,
  509. progress_callback
  510. )
  511. progress_callback(prog=1.0, msg="GraphRAG community reports generation is done ({:.2f}s)".format(timer() - start_ts))
  512. except TaskCanceledException:
  513. raise
  514. except Exception as e:
  515. error_message = f'Fail to bind LLM used by GraphRAG community reports generation: {str(e)}'
  516. progress_callback(-1, msg=error_message)
  517. logging.exception(error_message)
  518. raise
  519. return
  520. else:
  521. # Standard chunking methods
  522. start_ts = timer()
  523. chunks = build_chunks(task, progress_callback)
  524. logging.info("Build document {}: {:.2f}s".format(task_document_name, timer() - start_ts))
  525. if chunks is None:
  526. return
  527. if not chunks:
  528. progress_callback(1., msg=f"No chunk built from {task_document_name}")
  529. return
  530. # TODO: exception handler
  531. ## set_progress(task["did"], -1, "ERROR: ")
  532. progress_callback(msg="Generate {} chunks".format(len(chunks)))
  533. start_ts = timer()
  534. try:
  535. token_count, vector_size = embedding(chunks, embedding_model, task_parser_config, progress_callback)
  536. except Exception as e:
  537. error_message = "Generate embedding error:{}".format(str(e))
  538. progress_callback(-1, error_message)
  539. logging.exception(error_message)
  540. token_count = 0
  541. raise
  542. progress_message = "Embedding chunks ({:.2f}s)".format(timer() - start_ts)
  543. logging.info(progress_message)
  544. progress_callback(msg=progress_message)
  545. chunk_count = len(set([chunk["id"] for chunk in chunks]))
  546. start_ts = timer()
  547. doc_store_result = ""
  548. es_bulk_size = 4
  549. for b in range(0, len(chunks), es_bulk_size):
  550. doc_store_result = settings.docStoreConn.insert(chunks[b:b + es_bulk_size], search.index_name(task_tenant_id),
  551. task_dataset_id)
  552. if b % 128 == 0:
  553. progress_callback(prog=0.8 + 0.1 * (b + 1) / len(chunks), msg="")
  554. if doc_store_result:
  555. error_message = f"Insert chunk error: {doc_store_result}, please check log file and Elasticsearch/Infinity status!"
  556. progress_callback(-1, msg=error_message)
  557. raise Exception(error_message)
  558. chunk_ids = [chunk["id"] for chunk in chunks[:b + es_bulk_size]]
  559. chunk_ids_str = " ".join(chunk_ids)
  560. try:
  561. TaskService.update_chunk_ids(task["id"], chunk_ids_str)
  562. except DoesNotExist:
  563. logging.warning(f"do_handle_task update_chunk_ids failed since task {task['id']} is unknown.")
  564. doc_store_result = settings.docStoreConn.delete({"id": chunk_ids}, search.index_name(task_tenant_id),
  565. task_dataset_id)
  566. return
  567. logging.info("Indexing doc({}), page({}-{}), chunks({}), elapsed: {:.2f}".format(task_document_name, task_from_page,
  568. task_to_page, len(chunks),
  569. timer() - start_ts))
  570. DocumentService.increment_chunk_num(task_doc_id, task_dataset_id, token_count, chunk_count, 0)
  571. time_cost = timer() - start_ts
  572. progress_callback(prog=1.0, msg="Done ({:.2f}s)".format(time_cost))
  573. logging.info(
  574. "Chunk doc({}), page({}-{}), chunks({}), token({}), elapsed:{:.2f}".format(task_document_name, task_from_page,
  575. task_to_page, len(chunks),
  576. token_count, time_cost))
  577. def handle_task():
  578. global PAYLOAD, mt_lock, DONE_TASKS, FAILED_TASKS, CURRENT_TASK
  579. task = collect()
  580. if task:
  581. try:
  582. logging.info(f"handle_task begin for task {json.dumps(task)}")
  583. with mt_lock:
  584. CURRENT_TASK = copy.deepcopy(task)
  585. do_handle_task(task)
  586. with mt_lock:
  587. DONE_TASKS += 1
  588. CURRENT_TASK = None
  589. logging.info(f"handle_task done for task {json.dumps(task)}")
  590. except TaskCanceledException:
  591. with mt_lock:
  592. DONE_TASKS += 1
  593. CURRENT_TASK = None
  594. try:
  595. set_progress(task["id"], prog=-1, msg="handle_task got TaskCanceledException")
  596. except Exception:
  597. pass
  598. logging.debug("handle_task got TaskCanceledException", exc_info=True)
  599. except Exception as e:
  600. with mt_lock:
  601. FAILED_TASKS += 1
  602. CURRENT_TASK = None
  603. try:
  604. set_progress(task["id"], prog=-1, msg=f"[Exception]: {e}")
  605. except Exception:
  606. pass
  607. logging.exception(f"handle_task got exception for task {json.dumps(task)}")
  608. if PAYLOAD:
  609. PAYLOAD.ack()
  610. PAYLOAD = None
  611. def report_status():
  612. global CONSUMER_NAME, BOOT_AT, PENDING_TASKS, LAG_TASKS, mt_lock, DONE_TASKS, FAILED_TASKS, CURRENT_TASK
  613. REDIS_CONN.sadd("TASKEXE", CONSUMER_NAME)
  614. while True:
  615. try:
  616. now = datetime.now()
  617. group_info = REDIS_CONN.queue_info(SVR_QUEUE_NAME, "rag_flow_svr_task_broker")
  618. if group_info is not None:
  619. PENDING_TASKS = int(group_info.get("pending", 0))
  620. LAG_TASKS = int(group_info.get("lag", 0))
  621. with mt_lock:
  622. heartbeat = json.dumps({
  623. "name": CONSUMER_NAME,
  624. "now": now.astimezone().isoformat(timespec="milliseconds"),
  625. "boot_at": BOOT_AT,
  626. "pending": PENDING_TASKS,
  627. "lag": LAG_TASKS,
  628. "done": DONE_TASKS,
  629. "failed": FAILED_TASKS,
  630. "current": CURRENT_TASK,
  631. })
  632. REDIS_CONN.zadd(CONSUMER_NAME, heartbeat, now.timestamp())
  633. logging.info(f"{CONSUMER_NAME} reported heartbeat: {heartbeat}")
  634. expired = REDIS_CONN.zcount(CONSUMER_NAME, 0, now.timestamp() - 60 * 30)
  635. if expired > 0:
  636. REDIS_CONN.zpopmin(CONSUMER_NAME, expired)
  637. except Exception:
  638. logging.exception("report_status got exception")
  639. time.sleep(30)
  640. def analyze_heap(snapshot1: tracemalloc.Snapshot, snapshot2: tracemalloc.Snapshot, snapshot_id: int, dump_full: bool):
  641. msg = ""
  642. if dump_full:
  643. stats2 = snapshot2.statistics('lineno')
  644. msg += f"{CONSUMER_NAME} memory usage of snapshot {snapshot_id}:\n"
  645. for stat in stats2[:10]:
  646. msg += f"{stat}\n"
  647. stats1_vs_2 = snapshot2.compare_to(snapshot1, 'lineno')
  648. msg += f"{CONSUMER_NAME} memory usage increase from snapshot {snapshot_id - 1} to snapshot {snapshot_id}:\n"
  649. for stat in stats1_vs_2[:10]:
  650. msg += f"{stat}\n"
  651. msg += f"{CONSUMER_NAME} detailed traceback for the top memory consumers:\n"
  652. for stat in stats1_vs_2[:3]:
  653. msg += '\n'.join(stat.traceback.format())
  654. logging.info(msg)
  655. def main():
  656. logging.info(r"""
  657. ______ __ ______ __
  658. /_ __/___ ______/ /__ / ____/ _____ _______ __/ /_____ _____
  659. / / / __ `/ ___/ //_/ / __/ | |/_/ _ \/ ___/ / / / __/ __ \/ ___/
  660. / / / /_/ (__ ) ,< / /____> </ __/ /__/ /_/ / /_/ /_/ / /
  661. /_/ \__,_/____/_/|_| /_____/_/|_|\___/\___/\__,_/\__/\____/_/
  662. """)
  663. logging.info(f'TaskExecutor: RAGFlow version: {get_ragflow_version()}')
  664. settings.init_settings()
  665. print_rag_settings()
  666. signal.signal(signal.SIGUSR1, start_tracemalloc_and_snapshot)
  667. signal.signal(signal.SIGUSR2, stop_tracemalloc)
  668. TRACE_MALLOC_ENABLED = int(os.environ.get('TRACE_MALLOC_ENABLED', "0"))
  669. if TRACE_MALLOC_ENABLED:
  670. start_tracemalloc_and_snapshot(None, None)
  671. background_thread = threading.Thread(target=report_status)
  672. background_thread.daemon = True
  673. background_thread.start()
  674. while True:
  675. handle_task()
  676. if __name__ == "__main__":
  677. main()