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 31KB

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