您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

task_executor.py 28KB

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