選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

chunk_app.py 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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. #
  16. import datetime
  17. import json
  18. import re
  19. import xxhash
  20. from flask import request
  21. from flask_login import current_user, login_required
  22. from api import settings
  23. from api.db import LLMType, ParserType
  24. from api.db.services.dialog_service import meta_filter
  25. from api.db.services.document_service import DocumentService
  26. from api.db.services.knowledgebase_service import KnowledgebaseService
  27. from api.db.services.llm_service import LLMBundle
  28. from api.db.services.search_service import SearchService
  29. from api.db.services.user_service import UserTenantService
  30. from api.utils.api_utils import get_data_error_result, get_json_result, server_error_response, validate_request
  31. from rag.app.qa import beAdoc, rmPrefix
  32. from rag.app.tag import label_question
  33. from rag.nlp import rag_tokenizer, search
  34. from rag.prompts import cross_languages, keyword_extraction
  35. from rag.prompts.prompts import gen_meta_filter
  36. from rag.settings import PAGERANK_FLD
  37. from rag.utils import rmSpace
  38. @manager.route('/list', methods=['POST']) # noqa: F821
  39. @login_required
  40. @validate_request("doc_id")
  41. def list_chunk():
  42. req = request.json
  43. doc_id = req["doc_id"]
  44. page = int(req.get("page", 1))
  45. size = int(req.get("size", 30))
  46. question = req.get("keywords", "")
  47. try:
  48. tenant_id = DocumentService.get_tenant_id(req["doc_id"])
  49. if not tenant_id:
  50. return get_data_error_result(message="Tenant not found!")
  51. e, doc = DocumentService.get_by_id(doc_id)
  52. if not e:
  53. return get_data_error_result(message="Document not found!")
  54. kb_ids = KnowledgebaseService.get_kb_ids(tenant_id)
  55. query = {
  56. "doc_ids": [doc_id], "page": page, "size": size, "question": question, "sort": True
  57. }
  58. if "available_int" in req:
  59. query["available_int"] = int(req["available_int"])
  60. sres = settings.retrievaler.search(query, search.index_name(tenant_id), kb_ids, highlight=True)
  61. res = {"total": sres.total, "chunks": [], "doc": doc.to_dict()}
  62. for id in sres.ids:
  63. d = {
  64. "chunk_id": id,
  65. "content_with_weight": rmSpace(sres.highlight[id]) if question and id in sres.highlight else sres.field[
  66. id].get(
  67. "content_with_weight", ""),
  68. "doc_id": sres.field[id]["doc_id"],
  69. "docnm_kwd": sres.field[id]["docnm_kwd"],
  70. "important_kwd": sres.field[id].get("important_kwd", []),
  71. "question_kwd": sres.field[id].get("question_kwd", []),
  72. "image_id": sres.field[id].get("img_id", ""),
  73. "available_int": int(sres.field[id].get("available_int", 1)),
  74. "positions": sres.field[id].get("position_int", []),
  75. }
  76. assert isinstance(d["positions"], list)
  77. assert len(d["positions"]) == 0 or (isinstance(d["positions"][0], list) and len(d["positions"][0]) == 5)
  78. res["chunks"].append(d)
  79. return get_json_result(data=res)
  80. except Exception as e:
  81. if str(e).find("not_found") > 0:
  82. return get_json_result(data=False, message='No chunk found!',
  83. code=settings.RetCode.DATA_ERROR)
  84. return server_error_response(e)
  85. @manager.route('/get', methods=['GET']) # noqa: F821
  86. @login_required
  87. def get():
  88. chunk_id = request.args["chunk_id"]
  89. try:
  90. tenants = UserTenantService.query(user_id=current_user.id)
  91. if not tenants:
  92. return get_data_error_result(message="Tenant not found!")
  93. for tenant in tenants:
  94. kb_ids = KnowledgebaseService.get_kb_ids(tenant.tenant_id)
  95. chunk = settings.docStoreConn.get(chunk_id, search.index_name(tenant.tenant_id), kb_ids)
  96. if chunk:
  97. break
  98. if chunk is None:
  99. return server_error_response(Exception("Chunk not found"))
  100. k = []
  101. for n in chunk.keys():
  102. if re.search(r"(_vec$|_sm_|_tks|_ltks)", n):
  103. k.append(n)
  104. for n in k:
  105. del chunk[n]
  106. return get_json_result(data=chunk)
  107. except Exception as e:
  108. if str(e).find("NotFoundError") >= 0:
  109. return get_json_result(data=False, message='Chunk not found!',
  110. code=settings.RetCode.DATA_ERROR)
  111. return server_error_response(e)
  112. @manager.route('/set', methods=['POST']) # noqa: F821
  113. @login_required
  114. @validate_request("doc_id", "chunk_id", "content_with_weight")
  115. def set():
  116. req = request.json
  117. d = {
  118. "id": req["chunk_id"],
  119. "content_with_weight": req["content_with_weight"]}
  120. d["content_ltks"] = rag_tokenizer.tokenize(req["content_with_weight"])
  121. d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
  122. if "important_kwd" in req:
  123. if not isinstance(req["important_kwd"], list):
  124. return get_data_error_result(message="`important_kwd` should be a list")
  125. d["important_kwd"] = req["important_kwd"]
  126. d["important_tks"] = rag_tokenizer.tokenize(" ".join(req["important_kwd"]))
  127. if "question_kwd" in req:
  128. if not isinstance(req["question_kwd"], list):
  129. return get_data_error_result(message="`question_kwd` should be a list")
  130. d["question_kwd"] = req["question_kwd"]
  131. d["question_tks"] = rag_tokenizer.tokenize("\n".join(req["question_kwd"]))
  132. if "tag_kwd" in req:
  133. d["tag_kwd"] = req["tag_kwd"]
  134. if "tag_feas" in req:
  135. d["tag_feas"] = req["tag_feas"]
  136. if "available_int" in req:
  137. d["available_int"] = req["available_int"]
  138. try:
  139. tenant_id = DocumentService.get_tenant_id(req["doc_id"])
  140. if not tenant_id:
  141. return get_data_error_result(message="Tenant not found!")
  142. embd_id = DocumentService.get_embd_id(req["doc_id"])
  143. embd_mdl = LLMBundle(tenant_id, LLMType.EMBEDDING, embd_id)
  144. e, doc = DocumentService.get_by_id(req["doc_id"])
  145. if not e:
  146. return get_data_error_result(message="Document not found!")
  147. if doc.parser_id == ParserType.QA:
  148. arr = [
  149. t for t in re.split(
  150. r"[\n\t]",
  151. req["content_with_weight"]) if len(t) > 1]
  152. q, a = rmPrefix(arr[0]), rmPrefix("\n".join(arr[1:]))
  153. d = beAdoc(d, q, a, not any(
  154. [rag_tokenizer.is_chinese(t) for t in q + a]))
  155. v, c = embd_mdl.encode([doc.name, req["content_with_weight"] if not d.get("question_kwd") else "\n".join(d["question_kwd"])])
  156. v = 0.1 * v[0] + 0.9 * v[1] if doc.parser_id != ParserType.QA else v[1]
  157. d["q_%d_vec" % len(v)] = v.tolist()
  158. settings.docStoreConn.update({"id": req["chunk_id"]}, d, search.index_name(tenant_id), doc.kb_id)
  159. return get_json_result(data=True)
  160. except Exception as e:
  161. return server_error_response(e)
  162. @manager.route('/switch', methods=['POST']) # noqa: F821
  163. @login_required
  164. @validate_request("chunk_ids", "available_int", "doc_id")
  165. def switch():
  166. req = request.json
  167. try:
  168. e, doc = DocumentService.get_by_id(req["doc_id"])
  169. if not e:
  170. return get_data_error_result(message="Document not found!")
  171. for cid in req["chunk_ids"]:
  172. if not settings.docStoreConn.update({"id": cid},
  173. {"available_int": int(req["available_int"])},
  174. search.index_name(DocumentService.get_tenant_id(req["doc_id"])),
  175. doc.kb_id):
  176. return get_data_error_result(message="Index updating failure")
  177. return get_json_result(data=True)
  178. except Exception as e:
  179. return server_error_response(e)
  180. @manager.route('/rm', methods=['POST']) # noqa: F821
  181. @login_required
  182. @validate_request("chunk_ids", "doc_id")
  183. def rm():
  184. from rag.utils.storage_factory import STORAGE_IMPL
  185. req = request.json
  186. try:
  187. e, doc = DocumentService.get_by_id(req["doc_id"])
  188. if not e:
  189. return get_data_error_result(message="Document not found!")
  190. if not settings.docStoreConn.delete({"id": req["chunk_ids"]},
  191. search.index_name(DocumentService.get_tenant_id(req["doc_id"])),
  192. doc.kb_id):
  193. return get_data_error_result(message="Chunk deleting failure")
  194. deleted_chunk_ids = req["chunk_ids"]
  195. chunk_number = len(deleted_chunk_ids)
  196. DocumentService.decrement_chunk_num(doc.id, doc.kb_id, 1, chunk_number, 0)
  197. for cid in deleted_chunk_ids:
  198. if STORAGE_IMPL.obj_exist(doc.kb_id, cid):
  199. STORAGE_IMPL.rm(doc.kb_id, cid)
  200. return get_json_result(data=True)
  201. except Exception as e:
  202. return server_error_response(e)
  203. @manager.route('/create', methods=['POST']) # noqa: F821
  204. @login_required
  205. @validate_request("doc_id", "content_with_weight")
  206. def create():
  207. req = request.json
  208. chunck_id = xxhash.xxh64((req["content_with_weight"] + req["doc_id"]).encode("utf-8")).hexdigest()
  209. d = {"id": chunck_id, "content_ltks": rag_tokenizer.tokenize(req["content_with_weight"]),
  210. "content_with_weight": req["content_with_weight"]}
  211. d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
  212. d["important_kwd"] = req.get("important_kwd", [])
  213. if not isinstance(d["important_kwd"], list):
  214. return get_data_error_result(message="`important_kwd` is required to be a list")
  215. d["important_tks"] = rag_tokenizer.tokenize(" ".join(d["important_kwd"]))
  216. d["question_kwd"] = req.get("question_kwd", [])
  217. if not isinstance(d["question_kwd"], list):
  218. return get_data_error_result(message="`question_kwd` is required to be a list")
  219. d["question_tks"] = rag_tokenizer.tokenize("\n".join(d["question_kwd"]))
  220. d["create_time"] = str(datetime.datetime.now()).replace("T", " ")[:19]
  221. d["create_timestamp_flt"] = datetime.datetime.now().timestamp()
  222. if "tag_feas" in req:
  223. d["tag_feas"] = req["tag_feas"]
  224. if "tag_feas" in req:
  225. d["tag_feas"] = req["tag_feas"]
  226. try:
  227. e, doc = DocumentService.get_by_id(req["doc_id"])
  228. if not e:
  229. return get_data_error_result(message="Document not found!")
  230. d["kb_id"] = [doc.kb_id]
  231. d["docnm_kwd"] = doc.name
  232. d["title_tks"] = rag_tokenizer.tokenize(doc.name)
  233. d["doc_id"] = doc.id
  234. tenant_id = DocumentService.get_tenant_id(req["doc_id"])
  235. if not tenant_id:
  236. return get_data_error_result(message="Tenant not found!")
  237. e, kb = KnowledgebaseService.get_by_id(doc.kb_id)
  238. if not e:
  239. return get_data_error_result(message="Knowledgebase not found!")
  240. if kb.pagerank:
  241. d[PAGERANK_FLD] = kb.pagerank
  242. embd_id = DocumentService.get_embd_id(req["doc_id"])
  243. embd_mdl = LLMBundle(tenant_id, LLMType.EMBEDDING.value, embd_id)
  244. v, c = embd_mdl.encode([doc.name, req["content_with_weight"] if not d["question_kwd"] else "\n".join(d["question_kwd"])])
  245. v = 0.1 * v[0] + 0.9 * v[1]
  246. d["q_%d_vec" % len(v)] = v.tolist()
  247. settings.docStoreConn.insert([d], search.index_name(tenant_id), doc.kb_id)
  248. DocumentService.increment_chunk_num(
  249. doc.id, doc.kb_id, c, 1, 0)
  250. return get_json_result(data={"chunk_id": chunck_id})
  251. except Exception as e:
  252. return server_error_response(e)
  253. @manager.route('/retrieval_test', methods=['POST']) # noqa: F821
  254. @login_required
  255. @validate_request("kb_id", "question")
  256. def retrieval_test():
  257. req = request.json
  258. page = int(req.get("page", 1))
  259. size = int(req.get("size", 30))
  260. question = req["question"]
  261. kb_ids = req["kb_id"]
  262. if isinstance(kb_ids, str):
  263. kb_ids = [kb_ids]
  264. doc_ids = req.get("doc_ids", [])
  265. use_kg = req.get("use_kg", False)
  266. top = int(req.get("top_k", 1024))
  267. langs = req.get("cross_languages", [])
  268. tenant_ids = []
  269. if req.get("search_id", ""):
  270. search_config = SearchService.get_detail(req.get("search_id", "")).get("search_config", {})
  271. meta_data_filter = search_config.get("meta_data_filter", {})
  272. metas = DocumentService.get_meta_by_kbs(kb_ids)
  273. if meta_data_filter.get("method") == "auto":
  274. chat_mdl = LLMBundle(current_user.id, LLMType.CHAT, llm_name=search_config.get("chat_id", ""))
  275. filters = gen_meta_filter(chat_mdl, metas, question)
  276. doc_ids.extend(meta_filter(metas, filters))
  277. if not doc_ids:
  278. doc_ids = None
  279. elif meta_data_filter.get("method") == "manual":
  280. doc_ids.extend(meta_filter(metas, meta_data_filter["manual"]))
  281. if not doc_ids:
  282. doc_ids = None
  283. try:
  284. tenants = UserTenantService.query(user_id=current_user.id)
  285. for kb_id in kb_ids:
  286. for tenant in tenants:
  287. if KnowledgebaseService.query(
  288. tenant_id=tenant.tenant_id, id=kb_id):
  289. tenant_ids.append(tenant.tenant_id)
  290. break
  291. else:
  292. return get_json_result(
  293. data=False, message='Only owner of knowledgebase authorized for this operation.',
  294. code=settings.RetCode.OPERATING_ERROR)
  295. e, kb = KnowledgebaseService.get_by_id(kb_ids[0])
  296. if not e:
  297. return get_data_error_result(message="Knowledgebase not found!")
  298. if langs:
  299. question = cross_languages(kb.tenant_id, None, question, langs)
  300. embd_mdl = LLMBundle(kb.tenant_id, LLMType.EMBEDDING.value, llm_name=kb.embd_id)
  301. rerank_mdl = None
  302. if req.get("rerank_id"):
  303. rerank_mdl = LLMBundle(kb.tenant_id, LLMType.RERANK.value, llm_name=req["rerank_id"])
  304. if req.get("keyword", False):
  305. chat_mdl = LLMBundle(kb.tenant_id, LLMType.CHAT)
  306. question += keyword_extraction(chat_mdl, question)
  307. labels = label_question(question, [kb])
  308. ranks = settings.retrievaler.retrieval(question, embd_mdl, tenant_ids, kb_ids, page, size,
  309. float(req.get("similarity_threshold", 0.0)),
  310. float(req.get("vector_similarity_weight", 0.3)),
  311. top,
  312. doc_ids, rerank_mdl=rerank_mdl, highlight=req.get("highlight"),
  313. rank_feature=labels
  314. )
  315. if use_kg:
  316. ck = settings.kg_retrievaler.retrieval(question,
  317. tenant_ids,
  318. kb_ids,
  319. embd_mdl,
  320. LLMBundle(kb.tenant_id, LLMType.CHAT))
  321. if ck["content_with_weight"]:
  322. ranks["chunks"].insert(0, ck)
  323. for c in ranks["chunks"]:
  324. c.pop("vector", None)
  325. ranks["labels"] = labels
  326. return get_json_result(data=ranks)
  327. except Exception as e:
  328. if str(e).find("not_found") > 0:
  329. return get_json_result(data=False, message='No chunk found! Check the chunk status please!',
  330. code=settings.RetCode.DATA_ERROR)
  331. return server_error_response(e)
  332. @manager.route('/knowledge_graph', methods=['GET']) # noqa: F821
  333. @login_required
  334. def knowledge_graph():
  335. doc_id = request.args["doc_id"]
  336. tenant_id = DocumentService.get_tenant_id(doc_id)
  337. kb_ids = KnowledgebaseService.get_kb_ids(tenant_id)
  338. req = {
  339. "doc_ids": [doc_id],
  340. "knowledge_graph_kwd": ["graph", "mind_map"]
  341. }
  342. sres = settings.retrievaler.search(req, search.index_name(tenant_id), kb_ids)
  343. obj = {"graph": {}, "mind_map": {}}
  344. for id in sres.ids[:2]:
  345. ty = sres.field[id]["knowledge_graph_kwd"]
  346. try:
  347. content_json = json.loads(sres.field[id]["content_with_weight"])
  348. except Exception:
  349. continue
  350. if ty == 'mind_map':
  351. node_dict = {}
  352. def repeat_deal(content_json, node_dict):
  353. if 'id' in content_json:
  354. if content_json['id'] in node_dict:
  355. node_name = content_json['id']
  356. content_json['id'] += f"({node_dict[content_json['id']]})"
  357. node_dict[node_name] += 1
  358. else:
  359. node_dict[content_json['id']] = 1
  360. if 'children' in content_json and content_json['children']:
  361. for item in content_json['children']:
  362. repeat_deal(item, node_dict)
  363. repeat_deal(content_json, node_dict)
  364. obj[ty] = content_json
  365. return get_json_result(data=obj)