Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

doc.py 51KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499
  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.parser_id.lower() == req["chunk_method"].lower():
  296. return get_result()
  297. if doc.type == FileType.VISUAL or re.search(r"\.(ppt|pptx|pages)$", doc.name):
  298. return get_error_data_result(message="Not supported yet!")
  299. e = DocumentService.update_by_id(
  300. doc.id,
  301. {
  302. "parser_id": req["chunk_method"],
  303. "progress": 0,
  304. "progress_msg": "",
  305. "run": TaskStatus.UNSTART.value,
  306. },
  307. )
  308. if not e:
  309. return get_error_data_result(message="Document not found!")
  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: header
  811. name: Authorization
  812. type: string
  813. required: true
  814. description: Bearer token for authentication.
  815. responses:
  816. 200:
  817. description: List of chunks.
  818. schema:
  819. type: object
  820. properties:
  821. total:
  822. type: integer
  823. description: Total number of chunks.
  824. chunks:
  825. type: array
  826. items:
  827. type: object
  828. properties:
  829. id:
  830. type: string
  831. description: Chunk ID.
  832. content:
  833. type: string
  834. description: Chunk content.
  835. document_id:
  836. type: string
  837. description: ID of the document.
  838. important_keywords:
  839. type: array
  840. items:
  841. type: string
  842. description: Important keywords.
  843. image_id:
  844. type: string
  845. description: Image ID associated with the chunk.
  846. doc:
  847. type: object
  848. description: Document details.
  849. """
  850. if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id):
  851. return get_error_data_result(message=f"You don't own the dataset {dataset_id}.")
  852. doc = DocumentService.query(id=document_id, kb_id=dataset_id)
  853. if not doc:
  854. return get_error_data_result(
  855. message=f"You don't own the document {document_id}."
  856. )
  857. doc = doc[0]
  858. req = request.args
  859. doc_id = document_id
  860. page = int(req.get("page", 1))
  861. size = int(req.get("page_size", 30))
  862. question = req.get("keywords", "")
  863. query = {
  864. "doc_ids": [doc_id],
  865. "page": page,
  866. "size": size,
  867. "question": question,
  868. "sort": True,
  869. }
  870. key_mapping = {
  871. "chunk_num": "chunk_count",
  872. "kb_id": "dataset_id",
  873. "token_num": "token_count",
  874. "parser_id": "chunk_method",
  875. }
  876. run_mapping = {
  877. "0": "UNSTART",
  878. "1": "RUNNING",
  879. "2": "CANCEL",
  880. "3": "DONE",
  881. "4": "FAIL",
  882. }
  883. doc = doc.to_dict()
  884. renamed_doc = {}
  885. for key, value in doc.items():
  886. new_key = key_mapping.get(key, key)
  887. renamed_doc[new_key] = value
  888. if key == "run":
  889. renamed_doc["run"] = run_mapping.get(str(value))
  890. res = {"total": 0, "chunks": [], "doc": renamed_doc}
  891. if req.get("id"):
  892. chunk = settings.docStoreConn.get(req.get("id"), search.index_name(tenant_id), [dataset_id])
  893. if not chunk:
  894. return get_result(message=f"Chunk not found: {dataset_id}/{req.get('id')}", code=settings.RetCode.NOT_FOUND)
  895. k = []
  896. for n in chunk.keys():
  897. if re.search(r"(_vec$|_sm_|_tks|_ltks)", n):
  898. k.append(n)
  899. for n in k:
  900. del chunk[n]
  901. if not chunk:
  902. return get_error_data_result(f"Chunk `{req.get('id')}` not found.")
  903. res['total'] = 1
  904. final_chunk = {
  905. "id":chunk.get("id",chunk.get("chunk_id")),
  906. "content":chunk["content_with_weight"],
  907. "document_id":chunk.get("doc_id",chunk.get("document_id")),
  908. "docnm_kwd":chunk["docnm_kwd"],
  909. "important_keywords":chunk.get("important_kwd",[]),
  910. "questions":chunk.get("question_kwd",[]),
  911. "dataset_id":chunk.get("kb_id",chunk.get("dataset_id")),
  912. "image_id":chunk.get("img_id", ""),
  913. "available":bool(chunk.get("available_int",1)),
  914. "positions":chunk.get("position_int",[]),
  915. }
  916. res["chunks"].append(final_chunk)
  917. _ = Chunk(**final_chunk)
  918. elif settings.docStoreConn.indexExist(search.index_name(tenant_id), dataset_id):
  919. sres = settings.retrievaler.search(query, search.index_name(tenant_id), [dataset_id], emb_mdl=None,
  920. highlight=True)
  921. res["total"] = sres.total
  922. for id in sres.ids:
  923. d = {
  924. "id": id,
  925. "content": (
  926. rmSpace(sres.highlight[id])
  927. if question and id in sres.highlight
  928. else sres.field[id].get("content_with_weight", "")
  929. ),
  930. "document_id": sres.field[id]["doc_id"],
  931. "docnm_kwd": sres.field[id]["docnm_kwd"],
  932. "important_keywords": sres.field[id].get("important_kwd", []),
  933. "questions": sres.field[id].get("question_kwd", []),
  934. "dataset_id": sres.field[id].get("kb_id", sres.field[id].get("dataset_id")),
  935. "image_id": sres.field[id].get("img_id", ""),
  936. "available": bool(int(sres.field[id].get("available_int", "1"))),
  937. "positions": sres.field[id].get("position_int",[]),
  938. }
  939. res["chunks"].append(d)
  940. _ = Chunk(**d) # validate the chunk
  941. return get_result(data=res)
  942. @manager.route( # noqa: F821
  943. "/datasets/<dataset_id>/documents/<document_id>/chunks", methods=["POST"]
  944. )
  945. @token_required
  946. def add_chunk(tenant_id, dataset_id, document_id):
  947. """
  948. Add a chunk to a document.
  949. ---
  950. tags:
  951. - Chunks
  952. security:
  953. - ApiKeyAuth: []
  954. parameters:
  955. - in: path
  956. name: dataset_id
  957. type: string
  958. required: true
  959. description: ID of the dataset.
  960. - in: path
  961. name: document_id
  962. type: string
  963. required: true
  964. description: ID of the document.
  965. - in: body
  966. name: body
  967. description: Chunk data.
  968. required: true
  969. schema:
  970. type: object
  971. properties:
  972. content:
  973. type: string
  974. required: true
  975. description: Content of the chunk.
  976. important_keywords:
  977. type: array
  978. items:
  979. type: string
  980. description: Important keywords.
  981. - in: header
  982. name: Authorization
  983. type: string
  984. required: true
  985. description: Bearer token for authentication.
  986. responses:
  987. 200:
  988. description: Chunk added successfully.
  989. schema:
  990. type: object
  991. properties:
  992. chunk:
  993. type: object
  994. properties:
  995. id:
  996. type: string
  997. description: Chunk ID.
  998. content:
  999. type: string
  1000. description: Chunk content.
  1001. document_id:
  1002. type: string
  1003. description: ID of the document.
  1004. important_keywords:
  1005. type: array
  1006. items:
  1007. type: string
  1008. description: Important keywords.
  1009. """
  1010. if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id):
  1011. return get_error_data_result(message=f"You don't own the dataset {dataset_id}.")
  1012. doc = DocumentService.query(id=document_id, kb_id=dataset_id)
  1013. if not doc:
  1014. return get_error_data_result(
  1015. message=f"You don't own the document {document_id}."
  1016. )
  1017. doc = doc[0]
  1018. req = request.json
  1019. if not str(req.get("content", "")).strip():
  1020. return get_error_data_result(message="`content` is required")
  1021. if "important_keywords" in req:
  1022. if not isinstance(req["important_keywords"], list):
  1023. return get_error_data_result(
  1024. "`important_keywords` is required to be a list"
  1025. )
  1026. if "questions" in req:
  1027. if not isinstance(req["questions"], list):
  1028. return get_error_data_result(
  1029. "`questions` is required to be a list"
  1030. )
  1031. chunk_id = xxhash.xxh64((req["content"] + document_id).encode("utf-8")).hexdigest()
  1032. d = {
  1033. "id": chunk_id,
  1034. "content_ltks": rag_tokenizer.tokenize(req["content"]),
  1035. "content_with_weight": req["content"],
  1036. }
  1037. d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
  1038. d["important_kwd"] = req.get("important_keywords", [])
  1039. d["important_tks"] = rag_tokenizer.tokenize(
  1040. " ".join(req.get("important_keywords", []))
  1041. )
  1042. d["question_kwd"] = [str(q).strip() for q in req.get("questions", []) if str(q).strip()]
  1043. d["question_tks"] = rag_tokenizer.tokenize(
  1044. "\n".join(req.get("questions", []))
  1045. )
  1046. d["create_time"] = str(datetime.datetime.now()).replace("T", " ")[:19]
  1047. d["create_timestamp_flt"] = datetime.datetime.now().timestamp()
  1048. d["kb_id"] = dataset_id
  1049. d["docnm_kwd"] = doc.name
  1050. d["doc_id"] = document_id
  1051. embd_id = DocumentService.get_embd_id(document_id)
  1052. embd_mdl = TenantLLMService.model_instance(
  1053. tenant_id, LLMType.EMBEDDING.value, embd_id
  1054. )
  1055. v, c = embd_mdl.encode([doc.name, req["content"] if not d["question_kwd"] else "\n".join(d["question_kwd"])])
  1056. v = 0.1 * v[0] + 0.9 * v[1]
  1057. d["q_%d_vec" % len(v)] = v.tolist()
  1058. settings.docStoreConn.insert([d], search.index_name(tenant_id), dataset_id)
  1059. DocumentService.increment_chunk_num(doc.id, doc.kb_id, c, 1, 0)
  1060. # rename keys
  1061. key_mapping = {
  1062. "id": "id",
  1063. "content_with_weight": "content",
  1064. "doc_id": "document_id",
  1065. "important_kwd": "important_keywords",
  1066. "question_kwd": "questions",
  1067. "kb_id": "dataset_id",
  1068. "create_timestamp_flt": "create_timestamp",
  1069. "create_time": "create_time",
  1070. "document_keyword": "document",
  1071. }
  1072. renamed_chunk = {}
  1073. for key, value in d.items():
  1074. if key in key_mapping:
  1075. new_key = key_mapping.get(key, key)
  1076. renamed_chunk[new_key] = value
  1077. _ = Chunk(**renamed_chunk) # validate the chunk
  1078. return get_result(data={"chunk": renamed_chunk})
  1079. # return get_result(data={"chunk_id": chunk_id})
  1080. @manager.route( # noqa: F821
  1081. "datasets/<dataset_id>/documents/<document_id>/chunks", methods=["DELETE"]
  1082. )
  1083. @token_required
  1084. def rm_chunk(tenant_id, dataset_id, document_id):
  1085. """
  1086. Remove chunks from a document.
  1087. ---
  1088. tags:
  1089. - Chunks
  1090. security:
  1091. - ApiKeyAuth: []
  1092. parameters:
  1093. - in: path
  1094. name: dataset_id
  1095. type: string
  1096. required: true
  1097. description: ID of the dataset.
  1098. - in: path
  1099. name: document_id
  1100. type: string
  1101. required: true
  1102. description: ID of the document.
  1103. - in: body
  1104. name: body
  1105. description: Chunk removal parameters.
  1106. required: true
  1107. schema:
  1108. type: object
  1109. properties:
  1110. chunk_ids:
  1111. type: array
  1112. items:
  1113. type: string
  1114. description: List of chunk IDs to remove.
  1115. - in: header
  1116. name: Authorization
  1117. type: string
  1118. required: true
  1119. description: Bearer token for authentication.
  1120. responses:
  1121. 200:
  1122. description: Chunks removed successfully.
  1123. schema:
  1124. type: object
  1125. """
  1126. if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id):
  1127. return get_error_data_result(message=f"You don't own the dataset {dataset_id}.")
  1128. docs = DocumentService.get_by_ids([document_id])
  1129. if not docs:
  1130. raise LookupError(f"Can't find the document with ID {document_id}!")
  1131. req = request.json
  1132. condition = {"doc_id": document_id}
  1133. if "chunk_ids" in req:
  1134. unique_chunk_ids, duplicate_messages = check_duplicate_ids(req["chunk_ids"], "chunk")
  1135. condition["id"] = unique_chunk_ids
  1136. chunk_number = settings.docStoreConn.delete(condition, search.index_name(tenant_id), dataset_id)
  1137. if chunk_number != 0:
  1138. DocumentService.decrement_chunk_num(document_id, dataset_id, 1, chunk_number, 0)
  1139. if "chunk_ids" in req and chunk_number != len(unique_chunk_ids):
  1140. if len(unique_chunk_ids) == 0:
  1141. return get_result(message=f"deleted {chunk_number} chunks")
  1142. return get_error_data_result(message=f"rm_chunk deleted chunks {chunk_number}, expect {len(unique_chunk_ids)}")
  1143. if duplicate_messages:
  1144. return get_result(message=f"Partially deleted {chunk_number} chunks with {len(duplicate_messages)} errors", data={"success_count": chunk_number, "errors": duplicate_messages},)
  1145. return get_result(message=f"deleted {chunk_number} chunks")
  1146. @manager.route( # noqa: F821
  1147. "/datasets/<dataset_id>/documents/<document_id>/chunks/<chunk_id>", methods=["PUT"]
  1148. )
  1149. @token_required
  1150. def update_chunk(tenant_id, dataset_id, document_id, chunk_id):
  1151. """
  1152. Update a chunk within a document.
  1153. ---
  1154. tags:
  1155. - Chunks
  1156. security:
  1157. - ApiKeyAuth: []
  1158. parameters:
  1159. - in: path
  1160. name: dataset_id
  1161. type: string
  1162. required: true
  1163. description: ID of the dataset.
  1164. - in: path
  1165. name: document_id
  1166. type: string
  1167. required: true
  1168. description: ID of the document.
  1169. - in: path
  1170. name: chunk_id
  1171. type: string
  1172. required: true
  1173. description: ID of the chunk to update.
  1174. - in: body
  1175. name: body
  1176. description: Chunk update parameters.
  1177. required: true
  1178. schema:
  1179. type: object
  1180. properties:
  1181. content:
  1182. type: string
  1183. description: Updated content of the chunk.
  1184. important_keywords:
  1185. type: array
  1186. items:
  1187. type: string
  1188. description: Updated important keywords.
  1189. available:
  1190. type: boolean
  1191. description: Availability status of the chunk.
  1192. - in: header
  1193. name: Authorization
  1194. type: string
  1195. required: true
  1196. description: Bearer token for authentication.
  1197. responses:
  1198. 200:
  1199. description: Chunk updated successfully.
  1200. schema:
  1201. type: object
  1202. """
  1203. chunk = settings.docStoreConn.get(chunk_id, search.index_name(tenant_id), [dataset_id])
  1204. if chunk is None:
  1205. return get_error_data_result(f"Can't find this chunk {chunk_id}")
  1206. if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id):
  1207. return get_error_data_result(message=f"You don't own the dataset {dataset_id}.")
  1208. doc = DocumentService.query(id=document_id, kb_id=dataset_id)
  1209. if not doc:
  1210. return get_error_data_result(
  1211. message=f"You don't own the document {document_id}."
  1212. )
  1213. doc = doc[0]
  1214. req = request.json
  1215. if "content" in req:
  1216. content = req["content"]
  1217. else:
  1218. content = chunk.get("content_with_weight", "")
  1219. d = {"id": chunk_id, "content_with_weight": content}
  1220. d["content_ltks"] = rag_tokenizer.tokenize(d["content_with_weight"])
  1221. d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
  1222. if "important_keywords" in req:
  1223. if not isinstance(req["important_keywords"], list):
  1224. return get_error_data_result("`important_keywords` should be a list")
  1225. d["important_kwd"] = req.get("important_keywords", [])
  1226. d["important_tks"] = rag_tokenizer.tokenize(" ".join(req["important_keywords"]))
  1227. if "questions" in req:
  1228. if not isinstance(req["questions"], list):
  1229. return get_error_data_result("`questions` should be a list")
  1230. d["question_kwd"] = [str(q).strip() for q in req.get("questions", []) if str(q).strip()]
  1231. d["question_tks"] = rag_tokenizer.tokenize("\n".join(req["questions"]))
  1232. if "available" in req:
  1233. d["available_int"] = int(req["available"])
  1234. embd_id = DocumentService.get_embd_id(document_id)
  1235. embd_mdl = TenantLLMService.model_instance(
  1236. tenant_id, LLMType.EMBEDDING.value, embd_id
  1237. )
  1238. if doc.parser_id == ParserType.QA:
  1239. arr = [t for t in re.split(r"[\n\t]", d["content_with_weight"]) if len(t) > 1]
  1240. if len(arr) != 2:
  1241. return get_error_data_result(
  1242. message="Q&A must be separated by TAB/ENTER key."
  1243. )
  1244. q, a = rmPrefix(arr[0]), rmPrefix(arr[1])
  1245. d = beAdoc(
  1246. d, arr[0], arr[1], not any([rag_tokenizer.is_chinese(t) for t in q + a])
  1247. )
  1248. v, c = embd_mdl.encode([doc.name, d["content_with_weight"] if not d.get("question_kwd") else "\n".join(d["question_kwd"])])
  1249. v = 0.1 * v[0] + 0.9 * v[1] if doc.parser_id != ParserType.QA else v[1]
  1250. d["q_%d_vec" % len(v)] = v.tolist()
  1251. settings.docStoreConn.update({"id": chunk_id}, d, search.index_name(tenant_id), dataset_id)
  1252. return get_result()
  1253. @manager.route("/retrieval", methods=["POST"]) # noqa: F821
  1254. @token_required
  1255. def retrieval_test(tenant_id):
  1256. """
  1257. Retrieve chunks based on a query.
  1258. ---
  1259. tags:
  1260. - Retrieval
  1261. security:
  1262. - ApiKeyAuth: []
  1263. parameters:
  1264. - in: body
  1265. name: body
  1266. description: Retrieval parameters.
  1267. required: true
  1268. schema:
  1269. type: object
  1270. properties:
  1271. dataset_ids:
  1272. type: array
  1273. items:
  1274. type: string
  1275. required: true
  1276. description: List of dataset IDs to search in.
  1277. question:
  1278. type: string
  1279. required: true
  1280. description: Query string.
  1281. document_ids:
  1282. type: array
  1283. items:
  1284. type: string
  1285. description: List of document IDs to filter.
  1286. similarity_threshold:
  1287. type: number
  1288. format: float
  1289. description: Similarity threshold.
  1290. vector_similarity_weight:
  1291. type: number
  1292. format: float
  1293. description: Vector similarity weight.
  1294. top_k:
  1295. type: integer
  1296. description: Maximum number of chunks to return.
  1297. highlight:
  1298. type: boolean
  1299. description: Whether to highlight matched content.
  1300. - in: header
  1301. name: Authorization
  1302. type: string
  1303. required: true
  1304. description: Bearer token for authentication.
  1305. responses:
  1306. 200:
  1307. description: Retrieval results.
  1308. schema:
  1309. type: object
  1310. properties:
  1311. chunks:
  1312. type: array
  1313. items:
  1314. type: object
  1315. properties:
  1316. id:
  1317. type: string
  1318. description: Chunk ID.
  1319. content:
  1320. type: string
  1321. description: Chunk content.
  1322. document_id:
  1323. type: string
  1324. description: ID of the document.
  1325. dataset_id:
  1326. type: string
  1327. description: ID of the dataset.
  1328. similarity:
  1329. type: number
  1330. format: float
  1331. description: Similarity score.
  1332. """
  1333. req = request.json
  1334. if not req.get("dataset_ids"):
  1335. return get_error_data_result("`dataset_ids` is required.")
  1336. kb_ids = req["dataset_ids"]
  1337. if not isinstance(kb_ids, list):
  1338. return get_error_data_result("`dataset_ids` should be a list")
  1339. for id in kb_ids:
  1340. if not KnowledgebaseService.accessible(kb_id=id, user_id=tenant_id):
  1341. return get_error_data_result(f"You don't own the dataset {id}.")
  1342. kbs = KnowledgebaseService.get_by_ids(kb_ids)
  1343. embd_nms = list(set([TenantLLMService.split_model_name_and_factory(kb.embd_id)[0] for kb in kbs])) # remove vendor suffix for comparison
  1344. if len(embd_nms) != 1:
  1345. return get_result(
  1346. message='Datasets use different embedding models."',
  1347. code=settings.RetCode.DATA_ERROR,
  1348. )
  1349. if "question" not in req:
  1350. return get_error_data_result("`question` is required.")
  1351. page = int(req.get("page", 1))
  1352. size = int(req.get("page_size", 30))
  1353. question = req["question"]
  1354. doc_ids = req.get("document_ids", [])
  1355. use_kg = req.get("use_kg", False)
  1356. if not isinstance(doc_ids, list):
  1357. return get_error_data_result("`documents` should be a list")
  1358. doc_ids_list = KnowledgebaseService.list_documents_by_ids(kb_ids)
  1359. for doc_id in doc_ids:
  1360. if doc_id not in doc_ids_list:
  1361. return get_error_data_result(
  1362. f"The datasets don't own the document {doc_id}"
  1363. )
  1364. similarity_threshold = float(req.get("similarity_threshold", 0.2))
  1365. vector_similarity_weight = float(req.get("vector_similarity_weight", 0.3))
  1366. top = int(req.get("top_k", 1024))
  1367. if req.get("highlight") == "False" or req.get("highlight") == "false":
  1368. highlight = False
  1369. else:
  1370. highlight = True
  1371. try:
  1372. tenant_ids = list(set([kb.tenant_id for kb in kbs]))
  1373. e, kb = KnowledgebaseService.get_by_id(kb_ids[0])
  1374. if not e:
  1375. return get_error_data_result(message="Dataset not found!")
  1376. embd_mdl = LLMBundle(kb.tenant_id, LLMType.EMBEDDING, llm_name=kb.embd_id)
  1377. rerank_mdl = None
  1378. if req.get("rerank_id"):
  1379. rerank_mdl = LLMBundle(kb.tenant_id, LLMType.RERANK, llm_name=req["rerank_id"])
  1380. if req.get("keyword", False):
  1381. chat_mdl = LLMBundle(kb.tenant_id, LLMType.CHAT)
  1382. question += keyword_extraction(chat_mdl, question)
  1383. ranks = settings.retrievaler.retrieval(
  1384. question,
  1385. embd_mdl,
  1386. tenant_ids,
  1387. kb_ids,
  1388. page,
  1389. size,
  1390. similarity_threshold,
  1391. vector_similarity_weight,
  1392. top,
  1393. doc_ids,
  1394. rerank_mdl=rerank_mdl,
  1395. highlight=highlight,
  1396. rank_feature=label_question(question, kbs)
  1397. )
  1398. if use_kg:
  1399. ck = settings.kg_retrievaler.retrieval(question,
  1400. [k.tenant_id for k in kbs],
  1401. kb_ids,
  1402. embd_mdl,
  1403. LLMBundle(kb.tenant_id, LLMType.CHAT))
  1404. if ck["content_with_weight"]:
  1405. ranks["chunks"].insert(0, ck)
  1406. for c in ranks["chunks"]:
  1407. c.pop("vector", None)
  1408. ##rename keys
  1409. renamed_chunks = []
  1410. for chunk in ranks["chunks"]:
  1411. key_mapping = {
  1412. "chunk_id": "id",
  1413. "content_with_weight": "content",
  1414. "doc_id": "document_id",
  1415. "important_kwd": "important_keywords",
  1416. "question_kwd": "questions",
  1417. "docnm_kwd": "document_keyword",
  1418. "kb_id":"dataset_id"
  1419. }
  1420. rename_chunk = {}
  1421. for key, value in chunk.items():
  1422. new_key = key_mapping.get(key, key)
  1423. rename_chunk[new_key] = value
  1424. renamed_chunks.append(rename_chunk)
  1425. ranks["chunks"] = renamed_chunks
  1426. return get_result(data=ranks)
  1427. except Exception as e:
  1428. if str(e).find("not_found") > 0:
  1429. return get_result(
  1430. message="No chunk found! Check the chunk status please!",
  1431. code=settings.RetCode.DATA_ERROR,
  1432. )
  1433. return server_error_response(e)