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 24KB

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