選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

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