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

task_executor.py 28KB

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