Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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