You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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