您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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