Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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. from flask import request
  18. from flask_login import login_required, current_user
  19. from elasticsearch_dsl import Q
  20. from rag.app.qa import rmPrefix, beAdoc
  21. from rag.nlp import search, huqie
  22. from rag.utils import ELASTICSEARCH, rmSpace
  23. from api.db import LLMType, ParserType
  24. from api.db.services.knowledgebase_service import KnowledgebaseService
  25. from api.db.services.llm_service import TenantLLMService
  26. from api.db.services.user_service import UserTenantService
  27. from api.utils.api_utils import server_error_response, get_data_error_result, validate_request
  28. from api.db.services.document_service import DocumentService
  29. from api.settings import RetCode, retrievaler
  30. from api.utils.api_utils import get_json_result
  31. import hashlib
  32. import re
  33. @manager.route('/list', methods=['POST'])
  34. @login_required
  35. @validate_request("doc_id")
  36. def list():
  37. req = request.json
  38. doc_id = req["doc_id"]
  39. page = int(req.get("page", 1))
  40. size = int(req.get("size", 30))
  41. question = req.get("keywords", "")
  42. try:
  43. tenant_id = DocumentService.get_tenant_id(req["doc_id"])
  44. if not tenant_id:
  45. return get_data_error_result(retmsg="Tenant not found!")
  46. e, doc = DocumentService.get_by_id(doc_id)
  47. if not e:
  48. return get_data_error_result(retmsg="Document not found!")
  49. query = {
  50. "doc_ids": [doc_id], "page": page, "size": size, "question": question, "sort": True
  51. }
  52. if "available_int" in req:
  53. query["available_int"] = int(req["available_int"])
  54. sres = retrievaler.search(query, search.index_name(tenant_id))
  55. res = {"total": sres.total, "chunks": [], "doc": doc.to_dict()}
  56. for id in sres.ids:
  57. d = {
  58. "chunk_id": id,
  59. "content_with_weight": rmSpace(sres.highlight[id]) if question else sres.field[id].get(
  60. "content_with_weight", ""),
  61. "doc_id": sres.field[id]["doc_id"],
  62. "docnm_kwd": sres.field[id]["docnm_kwd"],
  63. "important_kwd": sres.field[id].get("important_kwd", []),
  64. "img_id": sres.field[id].get("img_id", ""),
  65. "available_int": sres.field[id].get("available_int", 1),
  66. "positions": sres.field[id].get("position_int", "").split("\t")
  67. }
  68. if len(d["positions"]) % 5 == 0:
  69. poss = []
  70. for i in range(0, len(d["positions"]), 5):
  71. poss.append([float(d["positions"][i]), float(d["positions"][i + 1]), float(d["positions"][i + 2]),
  72. float(d["positions"][i + 3]), float(d["positions"][i + 4])])
  73. d["positions"] = poss
  74. res["chunks"].append(d)
  75. return get_json_result(data=res)
  76. except Exception as e:
  77. if str(e).find("not_found") > 0:
  78. return get_json_result(data=False, retmsg=f'Index not found!',
  79. retcode=RetCode.DATA_ERROR)
  80. return server_error_response(e)
  81. @manager.route('/get', methods=['GET'])
  82. @login_required
  83. def get():
  84. chunk_id = request.args["chunk_id"]
  85. try:
  86. tenants = UserTenantService.query(user_id=current_user.id)
  87. if not tenants:
  88. return get_data_error_result(retmsg="Tenant not found!")
  89. res = ELASTICSEARCH.get(
  90. chunk_id, search.index_name(
  91. tenants[0].tenant_id))
  92. if not res.get("found"):
  93. return server_error_response("Chunk not found")
  94. id = res["_id"]
  95. res = res["_source"]
  96. res["chunk_id"] = id
  97. k = []
  98. for n in res.keys():
  99. if re.search(r"(_vec$|_sm_|_tks|_ltks)", n):
  100. k.append(n)
  101. for n in k:
  102. del res[n]
  103. return get_json_result(data=res)
  104. except Exception as e:
  105. if str(e).find("NotFoundError") >= 0:
  106. return get_json_result(data=False, retmsg=f'Chunk not found!',
  107. retcode=RetCode.DATA_ERROR)
  108. return server_error_response(e)
  109. @manager.route('/set', methods=['POST'])
  110. @login_required
  111. @validate_request("doc_id", "chunk_id", "content_with_weight",
  112. "important_kwd")
  113. def set():
  114. req = request.json
  115. d = {"id": req["chunk_id"], "content_with_weight": req["content_with_weight"]}
  116. d["content_ltks"] = huqie.qie(req["content_with_weight"])
  117. d["content_sm_ltks"] = huqie.qieqie(d["content_ltks"])
  118. d["important_kwd"] = req["important_kwd"]
  119. d["important_tks"] = huqie.qie(" ".join(req["important_kwd"]))
  120. if "available_int" in req:
  121. d["available_int"] = req["available_int"]
  122. try:
  123. tenant_id = DocumentService.get_tenant_id(req["doc_id"])
  124. if not tenant_id:
  125. return get_data_error_result(retmsg="Tenant not found!")
  126. embd_mdl = TenantLLMService.model_instance(
  127. tenant_id, LLMType.EMBEDDING.value)
  128. e, doc = DocumentService.get_by_id(req["doc_id"])
  129. if not e:
  130. return get_data_error_result(retmsg="Document not found!")
  131. if doc.parser_id == ParserType.QA:
  132. arr = [t for t in re.split(r"[\n\t]", req["content_with_weight"]) if len(t) > 1]
  133. if len(arr) != 2: return get_data_error_result(retmsg="Q&A must be separated by TAB/ENTER key.")
  134. q, a = rmPrefix(arr[0]), rmPrefix[arr[1]]
  135. d = beAdoc(d, arr[0], arr[1], not any([huqie.is_chinese(t) for t in q + a]))
  136. v, c = embd_mdl.encode([doc.name, req["content_with_weight"]])
  137. v = 0.1 * v[0] + 0.9 * v[1] if doc.parser_id != ParserType.QA else v[1]
  138. d["q_%d_vec" % len(v)] = v.tolist()
  139. ELASTICSEARCH.upsert([d], search.index_name(tenant_id))
  140. return get_json_result(data=True)
  141. except Exception as e:
  142. return server_error_response(e)
  143. @manager.route('/switch', methods=['POST'])
  144. @login_required
  145. @validate_request("chunk_ids", "available_int", "doc_id")
  146. def switch():
  147. req = request.json
  148. try:
  149. tenant_id = DocumentService.get_tenant_id(req["doc_id"])
  150. if not tenant_id:
  151. return get_data_error_result(retmsg="Tenant not found!")
  152. if not ELASTICSEARCH.upsert([{"id": i, "available_int": int(req["available_int"])} for i in req["chunk_ids"]],
  153. search.index_name(tenant_id)):
  154. return get_data_error_result(retmsg="Index updating failure")
  155. return get_json_result(data=True)
  156. except Exception as e:
  157. return server_error_response(e)
  158. @manager.route('/rm', methods=['POST'])
  159. @login_required
  160. @validate_request("chunk_ids")
  161. def rm():
  162. req = request.json
  163. try:
  164. if not ELASTICSEARCH.deleteByQuery(Q("ids", values=req["chunk_ids"]), search.index_name(current_user.id)):
  165. return get_data_error_result(retmsg="Index updating failure")
  166. return get_json_result(data=True)
  167. except Exception as e:
  168. return server_error_response(e)
  169. @manager.route('/create', methods=['POST'])
  170. @login_required
  171. @validate_request("doc_id", "content_with_weight")
  172. def create():
  173. req = request.json
  174. md5 = hashlib.md5()
  175. md5.update((req["content_with_weight"] + req["doc_id"]).encode("utf-8"))
  176. chunck_id = md5.hexdigest()
  177. d = {"id": chunck_id, "content_ltks": huqie.qie(req["content_with_weight"]),
  178. "content_with_weight": req["content_with_weight"]}
  179. d["content_sm_ltks"] = huqie.qieqie(d["content_ltks"])
  180. d["important_kwd"] = req.get("important_kwd", [])
  181. d["important_tks"] = huqie.qie(" ".join(req.get("important_kwd", [])))
  182. d["create_time"] = str(datetime.datetime.now()).replace("T", " ")[:19]
  183. d["create_timestamp_flt"] = datetime.datetime.now().timestamp()
  184. try:
  185. e, doc = DocumentService.get_by_id(req["doc_id"])
  186. if not e:
  187. return get_data_error_result(retmsg="Document not found!")
  188. d["kb_id"] = [doc.kb_id]
  189. d["docnm_kwd"] = doc.name
  190. d["doc_id"] = doc.id
  191. tenant_id = DocumentService.get_tenant_id(req["doc_id"])
  192. if not tenant_id:
  193. return get_data_error_result(retmsg="Tenant not found!")
  194. embd_mdl = TenantLLMService.model_instance(
  195. tenant_id, LLMType.EMBEDDING.value)
  196. v, c = embd_mdl.encode([doc.name, req["content_with_weight"]])
  197. DocumentService.increment_chunk_num(req["doc_id"], doc.kb_id, c, 1, 0)
  198. v = 0.1 * v[0] + 0.9 * v[1]
  199. d["q_%d_vec" % len(v)] = v.tolist()
  200. ELASTICSEARCH.upsert([d], search.index_name(tenant_id))
  201. return get_json_result(data={"chunk_id": chunck_id})
  202. except Exception as e:
  203. return server_error_response(e)
  204. @manager.route('/retrieval_test', methods=['POST'])
  205. @login_required
  206. @validate_request("kb_id", "question")
  207. def retrieval_test():
  208. req = request.json
  209. page = int(req.get("page", 1))
  210. size = int(req.get("size", 30))
  211. question = req["question"]
  212. kb_id = req["kb_id"]
  213. doc_ids = req.get("doc_ids", [])
  214. similarity_threshold = float(req.get("similarity_threshold", 0.2))
  215. vector_similarity_weight = float(req.get("vector_similarity_weight", 0.3))
  216. top = int(req.get("top_k", 1024))
  217. try:
  218. e, kb = KnowledgebaseService.get_by_id(kb_id)
  219. if not e:
  220. return get_data_error_result(retmsg="Knowledgebase not found!")
  221. embd_mdl = TenantLLMService.model_instance(
  222. kb.tenant_id, LLMType.EMBEDDING.value)
  223. ranks = retrievaler.retrieval(question, embd_mdl, kb.tenant_id, [kb_id], page, size, similarity_threshold,
  224. vector_similarity_weight, top, doc_ids)
  225. for c in ranks["chunks"]:
  226. if "vector" in c:
  227. del c["vector"]
  228. return get_json_result(data=ranks)
  229. except Exception as e:
  230. if str(e).find("not_found") > 0:
  231. return get_json_result(data=False, retmsg=f'Index not found!',
  232. retcode=RetCode.DATA_ERROR)
  233. return server_error_response(e)