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

task_executor.py 27KB

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