Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

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