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

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