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.

doc.py 51KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465
  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 logging
  18. import pathlib
  19. import re
  20. from io import BytesIO
  21. import xxhash
  22. from flask import request, send_file
  23. from peewee import OperationalError
  24. from pydantic import BaseModel, Field, validator
  25. from api import settings
  26. from api.constants import FILE_NAME_LEN_LIMIT
  27. from api.db import FileSource, FileType, LLMType, ParserType, TaskStatus
  28. from api.db.db_models import File, Task
  29. from api.db.services.document_service import DocumentService
  30. from api.db.services.file2document_service import File2DocumentService
  31. from api.db.services.file_service import FileService
  32. from api.db.services.knowledgebase_service import KnowledgebaseService
  33. from api.db.services.llm_service import LLMBundle, TenantLLMService
  34. from api.db.services.task_service import TaskService, queue_tasks
  35. from api.utils.api_utils import check_duplicate_ids, construct_json_result, get_error_data_result, get_parser_config, get_result, server_error_response, token_required
  36. from rag.app.qa import beAdoc, rmPrefix
  37. from rag.app.tag import label_question
  38. from rag.nlp import rag_tokenizer, search
  39. from rag.prompts import keyword_extraction, cross_languages
  40. from rag.utils import rmSpace
  41. from rag.utils.storage_factory import STORAGE_IMPL
  42. MAXIMUM_OF_UPLOADING_FILES = 256
  43. class Chunk(BaseModel):
  44. id: str = ""
  45. content: str = ""
  46. document_id: str = ""
  47. docnm_kwd: str = ""
  48. important_keywords: list = Field(default_factory=list)
  49. questions: list = Field(default_factory=list)
  50. question_tks: str = ""
  51. image_id: str = ""
  52. available: bool = True
  53. positions: list[list[int]] = Field(default_factory=list)
  54. @validator("positions")
  55. def validate_positions(cls, value):
  56. for sublist in value:
  57. if len(sublist) != 5:
  58. raise ValueError("Each sublist in positions must have a length of 5")
  59. return value
  60. @manager.route("/datasets/<dataset_id>/documents", methods=["POST"]) # noqa: F821
  61. @token_required
  62. def upload(dataset_id, tenant_id):
  63. """
  64. Upload documents to a dataset.
  65. ---
  66. tags:
  67. - Documents
  68. security:
  69. - ApiKeyAuth: []
  70. parameters:
  71. - in: path
  72. name: dataset_id
  73. type: string
  74. required: true
  75. description: ID of the dataset.
  76. - in: header
  77. name: Authorization
  78. type: string
  79. required: true
  80. description: Bearer token for authentication.
  81. - in: formData
  82. name: file
  83. type: file
  84. required: true
  85. description: Document files to upload.
  86. responses:
  87. 200:
  88. description: Successfully uploaded documents.
  89. schema:
  90. type: object
  91. properties:
  92. data:
  93. type: array
  94. items:
  95. type: object
  96. properties:
  97. id:
  98. type: string
  99. description: Document ID.
  100. name:
  101. type: string
  102. description: Document name.
  103. chunk_count:
  104. type: integer
  105. description: Number of chunks.
  106. token_count:
  107. type: integer
  108. description: Number of tokens.
  109. dataset_id:
  110. type: string
  111. description: ID of the dataset.
  112. chunk_method:
  113. type: string
  114. description: Chunking method used.
  115. run:
  116. type: string
  117. description: Processing status.
  118. """
  119. if "file" not in request.files:
  120. return get_error_data_result(message="No file part!", code=settings.RetCode.ARGUMENT_ERROR)
  121. file_objs = request.files.getlist("file")
  122. for file_obj in file_objs:
  123. if file_obj.filename == "":
  124. return get_result(message="No file selected!", code=settings.RetCode.ARGUMENT_ERROR)
  125. if len(file_obj.filename.encode("utf-8")) > FILE_NAME_LEN_LIMIT:
  126. return get_result(message=f"File name must be {FILE_NAME_LEN_LIMIT} bytes or less.", code=settings.RetCode.ARGUMENT_ERROR)
  127. """
  128. # total size
  129. total_size = 0
  130. for file_obj in file_objs:
  131. file_obj.seek(0, os.SEEK_END)
  132. total_size += file_obj.tell()
  133. file_obj.seek(0)
  134. MAX_TOTAL_FILE_SIZE = 10 * 1024 * 1024
  135. if total_size > MAX_TOTAL_FILE_SIZE:
  136. return get_result(
  137. message=f"Total file size exceeds 10MB limit! ({total_size / (1024 * 1024):.2f} MB)",
  138. code=settings.RetCode.ARGUMENT_ERROR,
  139. )
  140. """
  141. e, kb = KnowledgebaseService.get_by_id(dataset_id)
  142. if not e:
  143. raise LookupError(f"Can't find the dataset with ID {dataset_id}!")
  144. err, files = FileService.upload_document(kb, file_objs, tenant_id)
  145. if err:
  146. return get_result(message="\n".join(err), code=settings.RetCode.SERVER_ERROR)
  147. # rename key's name
  148. renamed_doc_list = []
  149. for file in files:
  150. doc = file[0]
  151. key_mapping = {
  152. "chunk_num": "chunk_count",
  153. "kb_id": "dataset_id",
  154. "token_num": "token_count",
  155. "parser_id": "chunk_method",
  156. }
  157. renamed_doc = {}
  158. for key, value in doc.items():
  159. new_key = key_mapping.get(key, key)
  160. renamed_doc[new_key] = value
  161. renamed_doc["run"] = "UNSTART"
  162. renamed_doc_list.append(renamed_doc)
  163. return get_result(data=renamed_doc_list)
  164. @manager.route("/datasets/<dataset_id>/documents/<document_id>", methods=["PUT"]) # noqa: F821
  165. @token_required
  166. def update_doc(tenant_id, dataset_id, document_id):
  167. """
  168. Update a document within a dataset.
  169. ---
  170. tags:
  171. - Documents
  172. security:
  173. - ApiKeyAuth: []
  174. parameters:
  175. - in: path
  176. name: dataset_id
  177. type: string
  178. required: true
  179. description: ID of the dataset.
  180. - in: path
  181. name: document_id
  182. type: string
  183. required: true
  184. description: ID of the document to update.
  185. - in: header
  186. name: Authorization
  187. type: string
  188. required: true
  189. description: Bearer token for authentication.
  190. - in: body
  191. name: body
  192. description: Document update parameters.
  193. required: true
  194. schema:
  195. type: object
  196. properties:
  197. name:
  198. type: string
  199. description: New name of the document.
  200. parser_config:
  201. type: object
  202. description: Parser configuration.
  203. chunk_method:
  204. type: string
  205. description: Chunking method.
  206. enabled:
  207. type: boolean
  208. description: Document status.
  209. responses:
  210. 200:
  211. description: Document updated successfully.
  212. schema:
  213. type: object
  214. """
  215. req = request.json
  216. if not KnowledgebaseService.query(id=dataset_id, tenant_id=tenant_id):
  217. return get_error_data_result(message="You don't own the dataset.")
  218. e, kb = KnowledgebaseService.get_by_id(dataset_id)
  219. if not e:
  220. return get_error_data_result(message="Can't find this knowledgebase!")
  221. doc = DocumentService.query(kb_id=dataset_id, id=document_id)
  222. if not doc:
  223. return get_error_data_result(message="The dataset doesn't own the document.")
  224. doc = doc[0]
  225. if "chunk_count" in req:
  226. if req["chunk_count"] != doc.chunk_num:
  227. return get_error_data_result(message="Can't change `chunk_count`.")
  228. if "token_count" in req:
  229. if req["token_count"] != doc.token_num:
  230. return get_error_data_result(message="Can't change `token_count`.")
  231. if "progress" in req:
  232. if req["progress"] != doc.progress:
  233. return get_error_data_result(message="Can't change `progress`.")
  234. if "meta_fields" in req:
  235. if not isinstance(req["meta_fields"], dict):
  236. return get_error_data_result(message="meta_fields must be a dictionary")
  237. DocumentService.update_meta_fields(document_id, req["meta_fields"])
  238. if "name" in req and req["name"] != doc.name:
  239. if len(req["name"].encode("utf-8")) > FILE_NAME_LEN_LIMIT:
  240. return get_result(
  241. message=f"File name must be {FILE_NAME_LEN_LIMIT} bytes or less.",
  242. code=settings.RetCode.ARGUMENT_ERROR,
  243. )
  244. if pathlib.Path(req["name"].lower()).suffix != pathlib.Path(doc.name.lower()).suffix:
  245. return get_result(
  246. message="The extension of file can't be changed",
  247. code=settings.RetCode.ARGUMENT_ERROR,
  248. )
  249. for d in DocumentService.query(name=req["name"], kb_id=doc.kb_id):
  250. if d.name == req["name"]:
  251. return get_error_data_result(message="Duplicated document name in the same dataset.")
  252. if not DocumentService.update_by_id(document_id, {"name": req["name"]}):
  253. return get_error_data_result(message="Database error (Document rename)!")
  254. informs = File2DocumentService.get_by_document_id(document_id)
  255. if informs:
  256. e, file = FileService.get_by_id(informs[0].file_id)
  257. FileService.update_by_id(file.id, {"name": req["name"]})
  258. if "parser_config" in req:
  259. DocumentService.update_parser_config(doc.id, req["parser_config"])
  260. if "chunk_method" in req:
  261. valid_chunk_method = {"naive", "manual", "qa", "table", "paper", "book", "laws", "presentation", "picture", "one", "knowledge_graph", "email", "tag"}
  262. if req.get("chunk_method") not in valid_chunk_method:
  263. return get_error_data_result(f"`chunk_method` {req['chunk_method']} doesn't exist")
  264. if doc.type == FileType.VISUAL or re.search(r"\.(ppt|pptx|pages)$", doc.name):
  265. return get_error_data_result(message="Not supported yet!")
  266. if doc.parser_id.lower() != req["chunk_method"].lower():
  267. e = DocumentService.update_by_id(
  268. doc.id,
  269. {
  270. "parser_id": req["chunk_method"],
  271. "progress": 0,
  272. "progress_msg": "",
  273. "run": TaskStatus.UNSTART.value,
  274. },
  275. )
  276. if not e:
  277. return get_error_data_result(message="Document not found!")
  278. if not req.get("parser_config"):
  279. req["parser_config"] = get_parser_config(req["chunk_method"], req.get("parser_config"))
  280. DocumentService.update_parser_config(doc.id, req["parser_config"])
  281. if doc.token_num > 0:
  282. e = DocumentService.increment_chunk_num(
  283. doc.id,
  284. doc.kb_id,
  285. doc.token_num * -1,
  286. doc.chunk_num * -1,
  287. doc.process_duration * -1,
  288. )
  289. if not e:
  290. return get_error_data_result(message="Document not found!")
  291. settings.docStoreConn.delete({"doc_id": doc.id}, search.index_name(tenant_id), dataset_id)
  292. if "enabled" in req:
  293. status = int(req["enabled"])
  294. if doc.status != req["enabled"]:
  295. try:
  296. if not DocumentService.update_by_id(doc.id, {"status": str(status)}):
  297. return get_error_data_result(message="Database error (Document update)!")
  298. settings.docStoreConn.update({"doc_id": doc.id}, {"available_int": status}, search.index_name(kb.tenant_id), doc.kb_id)
  299. return get_result(data=True)
  300. except Exception as e:
  301. return server_error_response(e)
  302. try:
  303. ok, doc = DocumentService.get_by_id(doc.id)
  304. if not ok:
  305. return get_error_data_result(message="Dataset created failed")
  306. except OperationalError as e:
  307. logging.exception(e)
  308. return get_error_data_result(message="Database operation failed")
  309. key_mapping = {
  310. "chunk_num": "chunk_count",
  311. "kb_id": "dataset_id",
  312. "token_num": "token_count",
  313. "parser_id": "chunk_method",
  314. }
  315. run_mapping = {
  316. "0": "UNSTART",
  317. "1": "RUNNING",
  318. "2": "CANCEL",
  319. "3": "DONE",
  320. "4": "FAIL",
  321. }
  322. renamed_doc = {}
  323. for key, value in doc.to_dict().items():
  324. if key == "run":
  325. renamed_doc["run"] = run_mapping.get(str(value))
  326. new_key = key_mapping.get(key, key)
  327. renamed_doc[new_key] = value
  328. if key == "run":
  329. renamed_doc["run"] = run_mapping.get(value)
  330. return get_result(data=renamed_doc)
  331. @manager.route("/datasets/<dataset_id>/documents/<document_id>", methods=["GET"]) # noqa: F821
  332. @token_required
  333. def download(tenant_id, dataset_id, document_id):
  334. """
  335. Download a document from a dataset.
  336. ---
  337. tags:
  338. - Documents
  339. security:
  340. - ApiKeyAuth: []
  341. produces:
  342. - application/octet-stream
  343. parameters:
  344. - in: path
  345. name: dataset_id
  346. type: string
  347. required: true
  348. description: ID of the dataset.
  349. - in: path
  350. name: document_id
  351. type: string
  352. required: true
  353. description: ID of the document to download.
  354. - in: header
  355. name: Authorization
  356. type: string
  357. required: true
  358. description: Bearer token for authentication.
  359. responses:
  360. 200:
  361. description: Document file stream.
  362. schema:
  363. type: file
  364. 400:
  365. description: Error message.
  366. schema:
  367. type: object
  368. """
  369. if not document_id:
  370. return get_error_data_result(message="Specify document_id please.")
  371. if not KnowledgebaseService.query(id=dataset_id, tenant_id=tenant_id):
  372. return get_error_data_result(message=f"You do not own the dataset {dataset_id}.")
  373. doc = DocumentService.query(kb_id=dataset_id, id=document_id)
  374. if not doc:
  375. return get_error_data_result(message=f"The dataset not own the document {document_id}.")
  376. # The process of downloading
  377. doc_id, doc_location = File2DocumentService.get_storage_address(doc_id=document_id) # minio address
  378. file_stream = STORAGE_IMPL.get(doc_id, doc_location)
  379. if not file_stream:
  380. return construct_json_result(message="This file is empty.", code=settings.RetCode.DATA_ERROR)
  381. file = BytesIO(file_stream)
  382. # Use send_file with a proper filename and MIME type
  383. return send_file(
  384. file,
  385. as_attachment=True,
  386. download_name=doc[0].name,
  387. mimetype="application/octet-stream", # Set a default MIME type
  388. )
  389. @manager.route("/datasets/<dataset_id>/documents", methods=["GET"]) # noqa: F821
  390. @token_required
  391. def list_docs(dataset_id, tenant_id):
  392. """
  393. List documents in a dataset.
  394. ---
  395. tags:
  396. - Documents
  397. security:
  398. - ApiKeyAuth: []
  399. parameters:
  400. - in: path
  401. name: dataset_id
  402. type: string
  403. required: true
  404. description: ID of the dataset.
  405. - in: query
  406. name: id
  407. type: string
  408. required: false
  409. description: Filter by document ID.
  410. - in: query
  411. name: page
  412. type: integer
  413. required: false
  414. default: 1
  415. description: Page number.
  416. - in: query
  417. name: page_size
  418. type: integer
  419. required: false
  420. default: 30
  421. description: Number of items per page.
  422. - in: query
  423. name: orderby
  424. type: string
  425. required: false
  426. default: "create_time"
  427. description: Field to order by.
  428. - in: query
  429. name: desc
  430. type: boolean
  431. required: false
  432. default: true
  433. description: Order in descending.
  434. - in: header
  435. name: Authorization
  436. type: string
  437. required: true
  438. description: Bearer token for authentication.
  439. responses:
  440. 200:
  441. description: List of documents.
  442. schema:
  443. type: object
  444. properties:
  445. total:
  446. type: integer
  447. description: Total number of documents.
  448. docs:
  449. type: array
  450. items:
  451. type: object
  452. properties:
  453. id:
  454. type: string
  455. description: Document ID.
  456. name:
  457. type: string
  458. description: Document name.
  459. chunk_count:
  460. type: integer
  461. description: Number of chunks.
  462. token_count:
  463. type: integer
  464. description: Number of tokens.
  465. dataset_id:
  466. type: string
  467. description: ID of the dataset.
  468. chunk_method:
  469. type: string
  470. description: Chunking method used.
  471. run:
  472. type: string
  473. description: Processing status.
  474. """
  475. if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id):
  476. return get_error_data_result(message=f"You don't own the dataset {dataset_id}. ")
  477. id = request.args.get("id")
  478. name = request.args.get("name")
  479. if id and not DocumentService.query(id=id, kb_id=dataset_id):
  480. return get_error_data_result(message=f"You don't own the document {id}.")
  481. if name and not DocumentService.query(name=name, kb_id=dataset_id):
  482. return get_error_data_result(message=f"You don't own the document {name}.")
  483. page = int(request.args.get("page", 1))
  484. keywords = request.args.get("keywords", "")
  485. page_size = int(request.args.get("page_size", 30))
  486. orderby = request.args.get("orderby", "create_time")
  487. if request.args.get("desc") == "False":
  488. desc = False
  489. else:
  490. desc = True
  491. docs, tol = DocumentService.get_list(dataset_id, page, page_size, orderby, desc, keywords, id, name)
  492. # rename key's name
  493. renamed_doc_list = []
  494. key_mapping = {
  495. "chunk_num": "chunk_count",
  496. "kb_id": "dataset_id",
  497. "token_num": "token_count",
  498. "parser_id": "chunk_method",
  499. }
  500. run_mapping = {
  501. "0": "UNSTART",
  502. "1": "RUNNING",
  503. "2": "CANCEL",
  504. "3": "DONE",
  505. "4": "FAIL",
  506. }
  507. for doc in docs:
  508. renamed_doc = {}
  509. for key, value in doc.items():
  510. if key == "run":
  511. renamed_doc["run"] = run_mapping.get(str(value))
  512. new_key = key_mapping.get(key, key)
  513. renamed_doc[new_key] = value
  514. if key == "run":
  515. renamed_doc["run"] = run_mapping.get(value)
  516. renamed_doc_list.append(renamed_doc)
  517. return get_result(data={"total": tol, "docs": renamed_doc_list})
  518. @manager.route("/datasets/<dataset_id>/documents", methods=["DELETE"]) # noqa: F821
  519. @token_required
  520. def delete(tenant_id, dataset_id):
  521. """
  522. Delete documents from a dataset.
  523. ---
  524. tags:
  525. - Documents
  526. security:
  527. - ApiKeyAuth: []
  528. parameters:
  529. - in: path
  530. name: dataset_id
  531. type: string
  532. required: true
  533. description: ID of the dataset.
  534. - in: body
  535. name: body
  536. description: Document deletion parameters.
  537. required: true
  538. schema:
  539. type: object
  540. properties:
  541. ids:
  542. type: array
  543. items:
  544. type: string
  545. description: List of document IDs to delete.
  546. - in: header
  547. name: Authorization
  548. type: string
  549. required: true
  550. description: Bearer token for authentication.
  551. responses:
  552. 200:
  553. description: Documents deleted successfully.
  554. schema:
  555. type: object
  556. """
  557. if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id):
  558. return get_error_data_result(message=f"You don't own the dataset {dataset_id}. ")
  559. req = request.json
  560. if not req:
  561. doc_ids = None
  562. else:
  563. doc_ids = req.get("ids")
  564. if not doc_ids:
  565. doc_list = []
  566. docs = DocumentService.query(kb_id=dataset_id)
  567. for doc in docs:
  568. doc_list.append(doc.id)
  569. else:
  570. doc_list = doc_ids
  571. unique_doc_ids, duplicate_messages = check_duplicate_ids(doc_list, "document")
  572. doc_list = unique_doc_ids
  573. root_folder = FileService.get_root_folder(tenant_id)
  574. pf_id = root_folder["id"]
  575. FileService.init_knowledgebase_docs(pf_id, tenant_id)
  576. errors = ""
  577. not_found = []
  578. success_count = 0
  579. for doc_id in doc_list:
  580. try:
  581. e, doc = DocumentService.get_by_id(doc_id)
  582. if not e:
  583. not_found.append(doc_id)
  584. continue
  585. tenant_id = DocumentService.get_tenant_id(doc_id)
  586. if not tenant_id:
  587. return get_error_data_result(message="Tenant not found!")
  588. b, n = File2DocumentService.get_storage_address(doc_id=doc_id)
  589. if not DocumentService.remove_document(doc, tenant_id):
  590. return get_error_data_result(message="Database error (Document removal)!")
  591. f2d = File2DocumentService.get_by_document_id(doc_id)
  592. FileService.filter_delete(
  593. [
  594. File.source_type == FileSource.KNOWLEDGEBASE,
  595. File.id == f2d[0].file_id,
  596. ]
  597. )
  598. File2DocumentService.delete_by_document_id(doc_id)
  599. STORAGE_IMPL.rm(b, n)
  600. success_count += 1
  601. except Exception as e:
  602. errors += str(e)
  603. if not_found:
  604. return get_result(message=f"Documents not found: {not_found}", code=settings.RetCode.DATA_ERROR)
  605. if errors:
  606. return get_result(message=errors, code=settings.RetCode.SERVER_ERROR)
  607. if duplicate_messages:
  608. if success_count > 0:
  609. return get_result(
  610. message=f"Partially deleted {success_count} datasets with {len(duplicate_messages)} errors",
  611. data={"success_count": success_count, "errors": duplicate_messages},
  612. )
  613. else:
  614. return get_error_data_result(message=";".join(duplicate_messages))
  615. return get_result()
  616. @manager.route("/datasets/<dataset_id>/chunks", methods=["POST"]) # noqa: F821
  617. @token_required
  618. def parse(tenant_id, dataset_id):
  619. """
  620. Start parsing documents into chunks.
  621. ---
  622. tags:
  623. - Chunks
  624. security:
  625. - ApiKeyAuth: []
  626. parameters:
  627. - in: path
  628. name: dataset_id
  629. type: string
  630. required: true
  631. description: ID of the dataset.
  632. - in: body
  633. name: body
  634. description: Parsing parameters.
  635. required: true
  636. schema:
  637. type: object
  638. properties:
  639. document_ids:
  640. type: array
  641. items:
  642. type: string
  643. description: List of document IDs to parse.
  644. - in: header
  645. name: Authorization
  646. type: string
  647. required: true
  648. description: Bearer token for authentication.
  649. responses:
  650. 200:
  651. description: Parsing started successfully.
  652. schema:
  653. type: object
  654. """
  655. if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id):
  656. return get_error_data_result(message=f"You don't own the dataset {dataset_id}.")
  657. req = request.json
  658. if not req.get("document_ids"):
  659. return get_error_data_result("`document_ids` is required")
  660. doc_list = req.get("document_ids")
  661. unique_doc_ids, duplicate_messages = check_duplicate_ids(doc_list, "document")
  662. doc_list = unique_doc_ids
  663. not_found = []
  664. success_count = 0
  665. for id in doc_list:
  666. doc = DocumentService.query(id=id, kb_id=dataset_id)
  667. if not doc:
  668. not_found.append(id)
  669. continue
  670. if not doc:
  671. return get_error_data_result(message=f"You don't own the document {id}.")
  672. if 0.0 < doc[0].progress < 1.0:
  673. return get_error_data_result("Can't parse document that is currently being processed")
  674. info = {"run": "1", "progress": 0, "progress_msg": "", "chunk_num": 0, "token_num": 0}
  675. DocumentService.update_by_id(id, info)
  676. settings.docStoreConn.delete({"doc_id": id}, search.index_name(tenant_id), dataset_id)
  677. TaskService.filter_delete([Task.doc_id == id])
  678. e, doc = DocumentService.get_by_id(id)
  679. doc = doc.to_dict()
  680. doc["tenant_id"] = tenant_id
  681. bucket, name = File2DocumentService.get_storage_address(doc_id=doc["id"])
  682. queue_tasks(doc, bucket, name, 0)
  683. success_count += 1
  684. if not_found:
  685. return get_result(message=f"Documents not found: {not_found}", code=settings.RetCode.DATA_ERROR)
  686. if duplicate_messages:
  687. if success_count > 0:
  688. return get_result(
  689. message=f"Partially parsed {success_count} documents with {len(duplicate_messages)} errors",
  690. data={"success_count": success_count, "errors": duplicate_messages},
  691. )
  692. else:
  693. return get_error_data_result(message=";".join(duplicate_messages))
  694. return get_result()
  695. @manager.route("/datasets/<dataset_id>/chunks", methods=["DELETE"]) # noqa: F821
  696. @token_required
  697. def stop_parsing(tenant_id, dataset_id):
  698. """
  699. Stop parsing documents into chunks.
  700. ---
  701. tags:
  702. - Chunks
  703. security:
  704. - ApiKeyAuth: []
  705. parameters:
  706. - in: path
  707. name: dataset_id
  708. type: string
  709. required: true
  710. description: ID of the dataset.
  711. - in: body
  712. name: body
  713. description: Stop parsing parameters.
  714. required: true
  715. schema:
  716. type: object
  717. properties:
  718. document_ids:
  719. type: array
  720. items:
  721. type: string
  722. description: List of document IDs to stop parsing.
  723. - in: header
  724. name: Authorization
  725. type: string
  726. required: true
  727. description: Bearer token for authentication.
  728. responses:
  729. 200:
  730. description: Parsing stopped successfully.
  731. schema:
  732. type: object
  733. """
  734. if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id):
  735. return get_error_data_result(message=f"You don't own the dataset {dataset_id}.")
  736. req = request.json
  737. if not req.get("document_ids"):
  738. return get_error_data_result("`document_ids` is required")
  739. doc_list = req.get("document_ids")
  740. unique_doc_ids, duplicate_messages = check_duplicate_ids(doc_list, "document")
  741. doc_list = unique_doc_ids
  742. success_count = 0
  743. for id in doc_list:
  744. doc = DocumentService.query(id=id, kb_id=dataset_id)
  745. if not doc:
  746. return get_error_data_result(message=f"You don't own the document {id}.")
  747. if int(doc[0].progress) == 1 or doc[0].progress == 0:
  748. return get_error_data_result("Can't stop parsing document with progress at 0 or 1")
  749. info = {"run": "2", "progress": 0, "chunk_num": 0}
  750. DocumentService.update_by_id(id, info)
  751. settings.docStoreConn.delete({"doc_id": doc[0].id}, search.index_name(tenant_id), dataset_id)
  752. success_count += 1
  753. if duplicate_messages:
  754. if success_count > 0:
  755. return get_result(
  756. message=f"Partially stopped {success_count} documents with {len(duplicate_messages)} errors",
  757. data={"success_count": success_count, "errors": duplicate_messages},
  758. )
  759. else:
  760. return get_error_data_result(message=";".join(duplicate_messages))
  761. return get_result()
  762. @manager.route("/datasets/<dataset_id>/documents/<document_id>/chunks", methods=["GET"]) # noqa: F821
  763. @token_required
  764. def list_chunks(tenant_id, dataset_id, document_id):
  765. """
  766. List chunks of a document.
  767. ---
  768. tags:
  769. - Chunks
  770. security:
  771. - ApiKeyAuth: []
  772. parameters:
  773. - in: path
  774. name: dataset_id
  775. type: string
  776. required: true
  777. description: ID of the dataset.
  778. - in: path
  779. name: document_id
  780. type: string
  781. required: true
  782. description: ID of the document.
  783. - in: query
  784. name: page
  785. type: integer
  786. required: false
  787. default: 1
  788. description: Page number.
  789. - in: query
  790. name: page_size
  791. type: integer
  792. required: false
  793. default: 30
  794. description: Number of items per page.
  795. - in: query
  796. name: id
  797. type: string
  798. required: false
  799. default: ""
  800. description: Chunk Id.
  801. - in: header
  802. name: Authorization
  803. type: string
  804. required: true
  805. description: Bearer token for authentication.
  806. responses:
  807. 200:
  808. description: List of chunks.
  809. schema:
  810. type: object
  811. properties:
  812. total:
  813. type: integer
  814. description: Total number of chunks.
  815. chunks:
  816. type: array
  817. items:
  818. type: object
  819. properties:
  820. id:
  821. type: string
  822. description: Chunk ID.
  823. content:
  824. type: string
  825. description: Chunk content.
  826. document_id:
  827. type: string
  828. description: ID of the document.
  829. important_keywords:
  830. type: array
  831. items:
  832. type: string
  833. description: Important keywords.
  834. image_id:
  835. type: string
  836. description: Image ID associated with the chunk.
  837. doc:
  838. type: object
  839. description: Document details.
  840. """
  841. if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id):
  842. return get_error_data_result(message=f"You don't own the dataset {dataset_id}.")
  843. doc = DocumentService.query(id=document_id, kb_id=dataset_id)
  844. if not doc:
  845. return get_error_data_result(message=f"You don't own the document {document_id}.")
  846. doc = doc[0]
  847. req = request.args
  848. doc_id = document_id
  849. page = int(req.get("page", 1))
  850. size = int(req.get("page_size", 30))
  851. question = req.get("keywords", "")
  852. query = {
  853. "doc_ids": [doc_id],
  854. "page": page,
  855. "size": size,
  856. "question": question,
  857. "sort": True,
  858. }
  859. key_mapping = {
  860. "chunk_num": "chunk_count",
  861. "kb_id": "dataset_id",
  862. "token_num": "token_count",
  863. "parser_id": "chunk_method",
  864. }
  865. run_mapping = {
  866. "0": "UNSTART",
  867. "1": "RUNNING",
  868. "2": "CANCEL",
  869. "3": "DONE",
  870. "4": "FAIL",
  871. }
  872. doc = doc.to_dict()
  873. renamed_doc = {}
  874. for key, value in doc.items():
  875. new_key = key_mapping.get(key, key)
  876. renamed_doc[new_key] = value
  877. if key == "run":
  878. renamed_doc["run"] = run_mapping.get(str(value))
  879. res = {"total": 0, "chunks": [], "doc": renamed_doc}
  880. if req.get("id"):
  881. chunk = settings.docStoreConn.get(req.get("id"), search.index_name(tenant_id), [dataset_id])
  882. if not chunk:
  883. return get_result(message=f"Chunk not found: {dataset_id}/{req.get('id')}", code=settings.RetCode.NOT_FOUND)
  884. k = []
  885. for n in chunk.keys():
  886. if re.search(r"(_vec$|_sm_|_tks|_ltks)", n):
  887. k.append(n)
  888. for n in k:
  889. del chunk[n]
  890. if not chunk:
  891. return get_error_data_result(f"Chunk `{req.get('id')}` not found.")
  892. res["total"] = 1
  893. final_chunk = {
  894. "id": chunk.get("id", chunk.get("chunk_id")),
  895. "content": chunk["content_with_weight"],
  896. "document_id": chunk.get("doc_id", chunk.get("document_id")),
  897. "docnm_kwd": chunk["docnm_kwd"],
  898. "important_keywords": chunk.get("important_kwd", []),
  899. "questions": chunk.get("question_kwd", []),
  900. "dataset_id": chunk.get("kb_id", chunk.get("dataset_id")),
  901. "image_id": chunk.get("img_id", ""),
  902. "available": bool(chunk.get("available_int", 1)),
  903. "positions": chunk.get("position_int", []),
  904. }
  905. res["chunks"].append(final_chunk)
  906. _ = Chunk(**final_chunk)
  907. elif settings.docStoreConn.indexExist(search.index_name(tenant_id), dataset_id):
  908. sres = settings.retrievaler.search(query, search.index_name(tenant_id), [dataset_id], emb_mdl=None, highlight=True)
  909. res["total"] = sres.total
  910. for id in sres.ids:
  911. d = {
  912. "id": id,
  913. "content": (rmSpace(sres.highlight[id]) if question and id in sres.highlight else sres.field[id].get("content_with_weight", "")),
  914. "document_id": sres.field[id]["doc_id"],
  915. "docnm_kwd": sres.field[id]["docnm_kwd"],
  916. "important_keywords": sres.field[id].get("important_kwd", []),
  917. "questions": sres.field[id].get("question_kwd", []),
  918. "dataset_id": sres.field[id].get("kb_id", sres.field[id].get("dataset_id")),
  919. "image_id": sres.field[id].get("img_id", ""),
  920. "available": bool(int(sres.field[id].get("available_int", "1"))),
  921. "positions": sres.field[id].get("position_int", []),
  922. }
  923. res["chunks"].append(d)
  924. _ = Chunk(**d) # validate the chunk
  925. return get_result(data=res)
  926. @manager.route( # noqa: F821
  927. "/datasets/<dataset_id>/documents/<document_id>/chunks", methods=["POST"]
  928. )
  929. @token_required
  930. def add_chunk(tenant_id, dataset_id, document_id):
  931. """
  932. Add a chunk to a document.
  933. ---
  934. tags:
  935. - Chunks
  936. security:
  937. - ApiKeyAuth: []
  938. parameters:
  939. - in: path
  940. name: dataset_id
  941. type: string
  942. required: true
  943. description: ID of the dataset.
  944. - in: path
  945. name: document_id
  946. type: string
  947. required: true
  948. description: ID of the document.
  949. - in: body
  950. name: body
  951. description: Chunk data.
  952. required: true
  953. schema:
  954. type: object
  955. properties:
  956. content:
  957. type: string
  958. required: true
  959. description: Content of the chunk.
  960. important_keywords:
  961. type: array
  962. items:
  963. type: string
  964. description: Important keywords.
  965. - in: header
  966. name: Authorization
  967. type: string
  968. required: true
  969. description: Bearer token for authentication.
  970. responses:
  971. 200:
  972. description: Chunk added successfully.
  973. schema:
  974. type: object
  975. properties:
  976. chunk:
  977. type: object
  978. properties:
  979. id:
  980. type: string
  981. description: Chunk ID.
  982. content:
  983. type: string
  984. description: Chunk content.
  985. document_id:
  986. type: string
  987. description: ID of the document.
  988. important_keywords:
  989. type: array
  990. items:
  991. type: string
  992. description: Important keywords.
  993. """
  994. if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id):
  995. return get_error_data_result(message=f"You don't own the dataset {dataset_id}.")
  996. doc = DocumentService.query(id=document_id, kb_id=dataset_id)
  997. if not doc:
  998. return get_error_data_result(message=f"You don't own the document {document_id}.")
  999. doc = doc[0]
  1000. req = request.json
  1001. if not str(req.get("content", "")).strip():
  1002. return get_error_data_result(message="`content` is required")
  1003. if "important_keywords" in req:
  1004. if not isinstance(req["important_keywords"], list):
  1005. return get_error_data_result("`important_keywords` is required to be a list")
  1006. if "questions" in req:
  1007. if not isinstance(req["questions"], list):
  1008. return get_error_data_result("`questions` is required to be a list")
  1009. chunk_id = xxhash.xxh64((req["content"] + document_id).encode("utf-8")).hexdigest()
  1010. d = {
  1011. "id": chunk_id,
  1012. "content_ltks": rag_tokenizer.tokenize(req["content"]),
  1013. "content_with_weight": req["content"],
  1014. }
  1015. d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
  1016. d["important_kwd"] = req.get("important_keywords", [])
  1017. d["important_tks"] = rag_tokenizer.tokenize(" ".join(req.get("important_keywords", [])))
  1018. d["question_kwd"] = [str(q).strip() for q in req.get("questions", []) if str(q).strip()]
  1019. d["question_tks"] = rag_tokenizer.tokenize("\n".join(req.get("questions", [])))
  1020. d["create_time"] = str(datetime.datetime.now()).replace("T", " ")[:19]
  1021. d["create_timestamp_flt"] = datetime.datetime.now().timestamp()
  1022. d["kb_id"] = dataset_id
  1023. d["docnm_kwd"] = doc.name
  1024. d["doc_id"] = document_id
  1025. embd_id = DocumentService.get_embd_id(document_id)
  1026. embd_mdl = TenantLLMService.model_instance(tenant_id, LLMType.EMBEDDING.value, embd_id)
  1027. v, c = embd_mdl.encode([doc.name, req["content"] if not d["question_kwd"] else "\n".join(d["question_kwd"])])
  1028. v = 0.1 * v[0] + 0.9 * v[1]
  1029. d["q_%d_vec" % len(v)] = v.tolist()
  1030. settings.docStoreConn.insert([d], search.index_name(tenant_id), dataset_id)
  1031. DocumentService.increment_chunk_num(doc.id, doc.kb_id, c, 1, 0)
  1032. # rename keys
  1033. key_mapping = {
  1034. "id": "id",
  1035. "content_with_weight": "content",
  1036. "doc_id": "document_id",
  1037. "important_kwd": "important_keywords",
  1038. "question_kwd": "questions",
  1039. "kb_id": "dataset_id",
  1040. "create_timestamp_flt": "create_timestamp",
  1041. "create_time": "create_time",
  1042. "document_keyword": "document",
  1043. }
  1044. renamed_chunk = {}
  1045. for key, value in d.items():
  1046. if key in key_mapping:
  1047. new_key = key_mapping.get(key, key)
  1048. renamed_chunk[new_key] = value
  1049. _ = Chunk(**renamed_chunk) # validate the chunk
  1050. return get_result(data={"chunk": renamed_chunk})
  1051. # return get_result(data={"chunk_id": chunk_id})
  1052. @manager.route( # noqa: F821
  1053. "datasets/<dataset_id>/documents/<document_id>/chunks", methods=["DELETE"]
  1054. )
  1055. @token_required
  1056. def rm_chunk(tenant_id, dataset_id, document_id):
  1057. """
  1058. Remove chunks from a document.
  1059. ---
  1060. tags:
  1061. - Chunks
  1062. security:
  1063. - ApiKeyAuth: []
  1064. parameters:
  1065. - in: path
  1066. name: dataset_id
  1067. type: string
  1068. required: true
  1069. description: ID of the dataset.
  1070. - in: path
  1071. name: document_id
  1072. type: string
  1073. required: true
  1074. description: ID of the document.
  1075. - in: body
  1076. name: body
  1077. description: Chunk removal parameters.
  1078. required: true
  1079. schema:
  1080. type: object
  1081. properties:
  1082. chunk_ids:
  1083. type: array
  1084. items:
  1085. type: string
  1086. description: List of chunk IDs to remove.
  1087. - in: header
  1088. name: Authorization
  1089. type: string
  1090. required: true
  1091. description: Bearer token for authentication.
  1092. responses:
  1093. 200:
  1094. description: Chunks removed successfully.
  1095. schema:
  1096. type: object
  1097. """
  1098. if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id):
  1099. return get_error_data_result(message=f"You don't own the dataset {dataset_id}.")
  1100. docs = DocumentService.get_by_ids([document_id])
  1101. if not docs:
  1102. raise LookupError(f"Can't find the document with ID {document_id}!")
  1103. req = request.json
  1104. condition = {"doc_id": document_id}
  1105. if "chunk_ids" in req:
  1106. unique_chunk_ids, duplicate_messages = check_duplicate_ids(req["chunk_ids"], "chunk")
  1107. condition["id"] = unique_chunk_ids
  1108. chunk_number = settings.docStoreConn.delete(condition, search.index_name(tenant_id), dataset_id)
  1109. if chunk_number != 0:
  1110. DocumentService.decrement_chunk_num(document_id, dataset_id, 1, chunk_number, 0)
  1111. if "chunk_ids" in req and chunk_number != len(unique_chunk_ids):
  1112. if len(unique_chunk_ids) == 0:
  1113. return get_result(message=f"deleted {chunk_number} chunks")
  1114. return get_error_data_result(message=f"rm_chunk deleted chunks {chunk_number}, expect {len(unique_chunk_ids)}")
  1115. if duplicate_messages:
  1116. return get_result(
  1117. message=f"Partially deleted {chunk_number} chunks with {len(duplicate_messages)} errors",
  1118. data={"success_count": chunk_number, "errors": duplicate_messages},
  1119. )
  1120. return get_result(message=f"deleted {chunk_number} chunks")
  1121. @manager.route( # noqa: F821
  1122. "/datasets/<dataset_id>/documents/<document_id>/chunks/<chunk_id>", methods=["PUT"]
  1123. )
  1124. @token_required
  1125. def update_chunk(tenant_id, dataset_id, document_id, chunk_id):
  1126. """
  1127. Update a chunk within a document.
  1128. ---
  1129. tags:
  1130. - Chunks
  1131. security:
  1132. - ApiKeyAuth: []
  1133. parameters:
  1134. - in: path
  1135. name: dataset_id
  1136. type: string
  1137. required: true
  1138. description: ID of the dataset.
  1139. - in: path
  1140. name: document_id
  1141. type: string
  1142. required: true
  1143. description: ID of the document.
  1144. - in: path
  1145. name: chunk_id
  1146. type: string
  1147. required: true
  1148. description: ID of the chunk to update.
  1149. - in: body
  1150. name: body
  1151. description: Chunk update parameters.
  1152. required: true
  1153. schema:
  1154. type: object
  1155. properties:
  1156. content:
  1157. type: string
  1158. description: Updated content of the chunk.
  1159. important_keywords:
  1160. type: array
  1161. items:
  1162. type: string
  1163. description: Updated important keywords.
  1164. available:
  1165. type: boolean
  1166. description: Availability status of the chunk.
  1167. - in: header
  1168. name: Authorization
  1169. type: string
  1170. required: true
  1171. description: Bearer token for authentication.
  1172. responses:
  1173. 200:
  1174. description: Chunk updated successfully.
  1175. schema:
  1176. type: object
  1177. """
  1178. chunk = settings.docStoreConn.get(chunk_id, search.index_name(tenant_id), [dataset_id])
  1179. if chunk is None:
  1180. return get_error_data_result(f"Can't find this chunk {chunk_id}")
  1181. if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id):
  1182. return get_error_data_result(message=f"You don't own the dataset {dataset_id}.")
  1183. doc = DocumentService.query(id=document_id, kb_id=dataset_id)
  1184. if not doc:
  1185. return get_error_data_result(message=f"You don't own the document {document_id}.")
  1186. doc = doc[0]
  1187. req = request.json
  1188. if "content" in req:
  1189. content = req["content"]
  1190. else:
  1191. content = chunk.get("content_with_weight", "")
  1192. d = {"id": chunk_id, "content_with_weight": content}
  1193. d["content_ltks"] = rag_tokenizer.tokenize(d["content_with_weight"])
  1194. d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
  1195. if "important_keywords" in req:
  1196. if not isinstance(req["important_keywords"], list):
  1197. return get_error_data_result("`important_keywords` should be a list")
  1198. d["important_kwd"] = req.get("important_keywords", [])
  1199. d["important_tks"] = rag_tokenizer.tokenize(" ".join(req["important_keywords"]))
  1200. if "questions" in req:
  1201. if not isinstance(req["questions"], list):
  1202. return get_error_data_result("`questions` should be a list")
  1203. d["question_kwd"] = [str(q).strip() for q in req.get("questions", []) if str(q).strip()]
  1204. d["question_tks"] = rag_tokenizer.tokenize("\n".join(req["questions"]))
  1205. if "available" in req:
  1206. d["available_int"] = int(req["available"])
  1207. embd_id = DocumentService.get_embd_id(document_id)
  1208. embd_mdl = TenantLLMService.model_instance(tenant_id, LLMType.EMBEDDING.value, embd_id)
  1209. if doc.parser_id == ParserType.QA:
  1210. arr = [t for t in re.split(r"[\n\t]", d["content_with_weight"]) if len(t) > 1]
  1211. if len(arr) != 2:
  1212. return get_error_data_result(message="Q&A must be separated by TAB/ENTER key.")
  1213. q, a = rmPrefix(arr[0]), rmPrefix(arr[1])
  1214. d = beAdoc(d, arr[0], arr[1], not any([rag_tokenizer.is_chinese(t) for t in q + a]))
  1215. v, c = embd_mdl.encode([doc.name, d["content_with_weight"] if not d.get("question_kwd") else "\n".join(d["question_kwd"])])
  1216. v = 0.1 * v[0] + 0.9 * v[1] if doc.parser_id != ParserType.QA else v[1]
  1217. d["q_%d_vec" % len(v)] = v.tolist()
  1218. settings.docStoreConn.update({"id": chunk_id}, d, search.index_name(tenant_id), dataset_id)
  1219. return get_result()
  1220. @manager.route("/retrieval", methods=["POST"]) # noqa: F821
  1221. @token_required
  1222. def retrieval_test(tenant_id):
  1223. """
  1224. Retrieve chunks based on a query.
  1225. ---
  1226. tags:
  1227. - Retrieval
  1228. security:
  1229. - ApiKeyAuth: []
  1230. parameters:
  1231. - in: body
  1232. name: body
  1233. description: Retrieval parameters.
  1234. required: true
  1235. schema:
  1236. type: object
  1237. properties:
  1238. dataset_ids:
  1239. type: array
  1240. items:
  1241. type: string
  1242. required: true
  1243. description: List of dataset IDs to search in.
  1244. question:
  1245. type: string
  1246. required: true
  1247. description: Query string.
  1248. document_ids:
  1249. type: array
  1250. items:
  1251. type: string
  1252. description: List of document IDs to filter.
  1253. similarity_threshold:
  1254. type: number
  1255. format: float
  1256. description: Similarity threshold.
  1257. vector_similarity_weight:
  1258. type: number
  1259. format: float
  1260. description: Vector similarity weight.
  1261. top_k:
  1262. type: integer
  1263. description: Maximum number of chunks to return.
  1264. highlight:
  1265. type: boolean
  1266. description: Whether to highlight matched content.
  1267. - in: header
  1268. name: Authorization
  1269. type: string
  1270. required: true
  1271. description: Bearer token for authentication.
  1272. responses:
  1273. 200:
  1274. description: Retrieval results.
  1275. schema:
  1276. type: object
  1277. properties:
  1278. chunks:
  1279. type: array
  1280. items:
  1281. type: object
  1282. properties:
  1283. id:
  1284. type: string
  1285. description: Chunk ID.
  1286. content:
  1287. type: string
  1288. description: Chunk content.
  1289. document_id:
  1290. type: string
  1291. description: ID of the document.
  1292. dataset_id:
  1293. type: string
  1294. description: ID of the dataset.
  1295. similarity:
  1296. type: number
  1297. format: float
  1298. description: Similarity score.
  1299. """
  1300. req = request.json
  1301. if not req.get("dataset_ids"):
  1302. return get_error_data_result("`dataset_ids` is required.")
  1303. kb_ids = req["dataset_ids"]
  1304. if not isinstance(kb_ids, list):
  1305. return get_error_data_result("`dataset_ids` should be a list")
  1306. for id in kb_ids:
  1307. if not KnowledgebaseService.accessible(kb_id=id, user_id=tenant_id):
  1308. return get_error_data_result(f"You don't own the dataset {id}.")
  1309. kbs = KnowledgebaseService.get_by_ids(kb_ids)
  1310. embd_nms = list(set([TenantLLMService.split_model_name_and_factory(kb.embd_id)[0] for kb in kbs])) # remove vendor suffix for comparison
  1311. if len(embd_nms) != 1:
  1312. return get_result(
  1313. message='Datasets use different embedding models."',
  1314. code=settings.RetCode.DATA_ERROR,
  1315. )
  1316. if "question" not in req:
  1317. return get_error_data_result("`question` is required.")
  1318. page = int(req.get("page", 1))
  1319. size = int(req.get("page_size", 30))
  1320. question = req["question"]
  1321. doc_ids = req.get("document_ids", [])
  1322. use_kg = req.get("use_kg", False)
  1323. langs = req.get("cross_languages", [])
  1324. if not isinstance(doc_ids, list):
  1325. return get_error_data_result("`documents` should be a list")
  1326. doc_ids_list = KnowledgebaseService.list_documents_by_ids(kb_ids)
  1327. for doc_id in doc_ids:
  1328. if doc_id not in doc_ids_list:
  1329. return get_error_data_result(f"The datasets don't own the document {doc_id}")
  1330. similarity_threshold = float(req.get("similarity_threshold", 0.2))
  1331. vector_similarity_weight = float(req.get("vector_similarity_weight", 0.3))
  1332. top = int(req.get("top_k", 1024))
  1333. if req.get("highlight") == "False" or req.get("highlight") == "false":
  1334. highlight = False
  1335. else:
  1336. highlight = True
  1337. try:
  1338. tenant_ids = list(set([kb.tenant_id for kb in kbs]))
  1339. e, kb = KnowledgebaseService.get_by_id(kb_ids[0])
  1340. if not e:
  1341. return get_error_data_result(message="Dataset not found!")
  1342. embd_mdl = LLMBundle(kb.tenant_id, LLMType.EMBEDDING, llm_name=kb.embd_id)
  1343. rerank_mdl = None
  1344. if req.get("rerank_id"):
  1345. rerank_mdl = LLMBundle(kb.tenant_id, LLMType.RERANK, llm_name=req["rerank_id"])
  1346. if langs:
  1347. question = cross_languages(kb.tenant_id, None, question, langs)
  1348. if req.get("keyword", False):
  1349. chat_mdl = LLMBundle(kb.tenant_id, LLMType.CHAT)
  1350. question += keyword_extraction(chat_mdl, question)
  1351. ranks = settings.retrievaler.retrieval(
  1352. question,
  1353. embd_mdl,
  1354. tenant_ids,
  1355. kb_ids,
  1356. page,
  1357. size,
  1358. similarity_threshold,
  1359. vector_similarity_weight,
  1360. top,
  1361. doc_ids,
  1362. rerank_mdl=rerank_mdl,
  1363. highlight=highlight,
  1364. rank_feature=label_question(question, kbs),
  1365. )
  1366. if use_kg:
  1367. ck = settings.kg_retrievaler.retrieval(question, [k.tenant_id for k in kbs], kb_ids, embd_mdl, LLMBundle(kb.tenant_id, LLMType.CHAT))
  1368. if ck["content_with_weight"]:
  1369. ranks["chunks"].insert(0, ck)
  1370. for c in ranks["chunks"]:
  1371. c.pop("vector", None)
  1372. ##rename keys
  1373. renamed_chunks = []
  1374. for chunk in ranks["chunks"]:
  1375. key_mapping = {
  1376. "chunk_id": "id",
  1377. "content_with_weight": "content",
  1378. "doc_id": "document_id",
  1379. "important_kwd": "important_keywords",
  1380. "question_kwd": "questions",
  1381. "docnm_kwd": "document_keyword",
  1382. "kb_id": "dataset_id",
  1383. }
  1384. rename_chunk = {}
  1385. for key, value in chunk.items():
  1386. new_key = key_mapping.get(key, key)
  1387. rename_chunk[new_key] = value
  1388. renamed_chunks.append(rename_chunk)
  1389. ranks["chunks"] = renamed_chunks
  1390. return get_result(data=ranks)
  1391. except Exception as e:
  1392. if str(e).find("not_found") > 0:
  1393. return get_result(
  1394. message="No chunk found! Check the chunk status please!",
  1395. code=settings.RetCode.DATA_ERROR,
  1396. )
  1397. return server_error_response(e)