Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

task_executor.py 32KB

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