Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

task_executor.py 28KB

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