Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420
  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
  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. root_folder = FileService.get_root_folder(tenant_id)
  570. pf_id = root_folder["id"]
  571. FileService.init_knowledgebase_docs(pf_id, tenant_id)
  572. errors = ""
  573. for doc_id in doc_list:
  574. try:
  575. e, doc = DocumentService.get_by_id(doc_id)
  576. if not e:
  577. return get_error_data_result(message="Document not found!")
  578. tenant_id = DocumentService.get_tenant_id(doc_id)
  579. if not tenant_id:
  580. return get_error_data_result(message="Tenant not found!")
  581. b, n = File2DocumentService.get_storage_address(doc_id=doc_id)
  582. if not DocumentService.remove_document(doc, tenant_id):
  583. return get_error_data_result(
  584. message="Database error (Document removal)!"
  585. )
  586. f2d = File2DocumentService.get_by_document_id(doc_id)
  587. FileService.filter_delete(
  588. [
  589. File.source_type == FileSource.KNOWLEDGEBASE,
  590. File.id == f2d[0].file_id,
  591. ]
  592. )
  593. File2DocumentService.delete_by_document_id(doc_id)
  594. STORAGE_IMPL.rm(b, n)
  595. except Exception as e:
  596. errors += str(e)
  597. if errors:
  598. return get_result(message=errors, code=settings.RetCode.SERVER_ERROR)
  599. return get_result()
  600. @manager.route("/datasets/<dataset_id>/chunks", methods=["POST"]) # noqa: F821
  601. @token_required
  602. def parse(tenant_id, dataset_id):
  603. """
  604. Start parsing documents into chunks.
  605. ---
  606. tags:
  607. - Chunks
  608. security:
  609. - ApiKeyAuth: []
  610. parameters:
  611. - in: path
  612. name: dataset_id
  613. type: string
  614. required: true
  615. description: ID of the dataset.
  616. - in: body
  617. name: body
  618. description: Parsing parameters.
  619. required: true
  620. schema:
  621. type: object
  622. properties:
  623. document_ids:
  624. type: array
  625. items:
  626. type: string
  627. description: List of document IDs to parse.
  628. - in: header
  629. name: Authorization
  630. type: string
  631. required: true
  632. description: Bearer token for authentication.
  633. responses:
  634. 200:
  635. description: Parsing started successfully.
  636. schema:
  637. type: object
  638. """
  639. if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id):
  640. return get_error_data_result(message=f"You don't own the dataset {dataset_id}.")
  641. req = request.json
  642. if not req.get("document_ids"):
  643. return get_error_data_result("`document_ids` is required")
  644. for id in req["document_ids"]:
  645. doc = DocumentService.query(id=id, kb_id=dataset_id)
  646. if not doc:
  647. return get_error_data_result(message=f"You don't own the document {id}.")
  648. if doc[0].progress != 0.0:
  649. return get_error_data_result(
  650. "Can't stop parsing document with progress at 0 or 100"
  651. )
  652. info = {"run": "1", "progress": 0}
  653. info["progress_msg"] = ""
  654. info["chunk_num"] = 0
  655. info["token_num"] = 0
  656. DocumentService.update_by_id(id, info)
  657. settings.docStoreConn.delete({"doc_id": id}, search.index_name(tenant_id), dataset_id)
  658. TaskService.filter_delete([Task.doc_id == id])
  659. e, doc = DocumentService.get_by_id(id)
  660. doc = doc.to_dict()
  661. doc["tenant_id"] = tenant_id
  662. bucket, name = File2DocumentService.get_storage_address(doc_id=doc["id"])
  663. queue_tasks(doc, bucket, name)
  664. return get_result()
  665. @manager.route("/datasets/<dataset_id>/chunks", methods=["DELETE"]) # noqa: F821
  666. @token_required
  667. def stop_parsing(tenant_id, dataset_id):
  668. """
  669. Stop parsing documents into chunks.
  670. ---
  671. tags:
  672. - Chunks
  673. security:
  674. - ApiKeyAuth: []
  675. parameters:
  676. - in: path
  677. name: dataset_id
  678. type: string
  679. required: true
  680. description: ID of the dataset.
  681. - in: body
  682. name: body
  683. description: Stop parsing parameters.
  684. required: true
  685. schema:
  686. type: object
  687. properties:
  688. document_ids:
  689. type: array
  690. items:
  691. type: string
  692. description: List of document IDs to stop parsing.
  693. - in: header
  694. name: Authorization
  695. type: string
  696. required: true
  697. description: Bearer token for authentication.
  698. responses:
  699. 200:
  700. description: Parsing stopped successfully.
  701. schema:
  702. type: object
  703. """
  704. if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id):
  705. return get_error_data_result(message=f"You don't own the dataset {dataset_id}.")
  706. req = request.json
  707. if not req.get("document_ids"):
  708. return get_error_data_result("`document_ids` is required")
  709. for id in req["document_ids"]:
  710. doc = DocumentService.query(id=id, kb_id=dataset_id)
  711. if not doc:
  712. return get_error_data_result(message=f"You don't own the document {id}.")
  713. if int(doc[0].progress) == 1 or doc[0].progress == 0:
  714. return get_error_data_result(
  715. "Can't stop parsing document with progress at 0 or 1"
  716. )
  717. info = {"run": "2", "progress": 0, "chunk_num": 0}
  718. DocumentService.update_by_id(id, info)
  719. settings.docStoreConn.delete({"doc_id": doc[0].id}, search.index_name(tenant_id), dataset_id)
  720. return get_result()
  721. @manager.route("/datasets/<dataset_id>/documents/<document_id>/chunks", methods=["GET"]) # noqa: F821
  722. @token_required
  723. def list_chunks(tenant_id, dataset_id, document_id):
  724. """
  725. List chunks of a document.
  726. ---
  727. tags:
  728. - Chunks
  729. security:
  730. - ApiKeyAuth: []
  731. parameters:
  732. - in: path
  733. name: dataset_id
  734. type: string
  735. required: true
  736. description: ID of the dataset.
  737. - in: path
  738. name: document_id
  739. type: string
  740. required: true
  741. description: ID of the document.
  742. - in: query
  743. name: page
  744. type: integer
  745. required: false
  746. default: 1
  747. description: Page number.
  748. - in: query
  749. name: page_size
  750. type: integer
  751. required: false
  752. default: 30
  753. description: Number of items per page.
  754. - in: header
  755. name: Authorization
  756. type: string
  757. required: true
  758. description: Bearer token for authentication.
  759. responses:
  760. 200:
  761. description: List of chunks.
  762. schema:
  763. type: object
  764. properties:
  765. total:
  766. type: integer
  767. description: Total number of chunks.
  768. chunks:
  769. type: array
  770. items:
  771. type: object
  772. properties:
  773. id:
  774. type: string
  775. description: Chunk ID.
  776. content:
  777. type: string
  778. description: Chunk content.
  779. document_id:
  780. type: string
  781. description: ID of the document.
  782. important_keywords:
  783. type: array
  784. items:
  785. type: string
  786. description: Important keywords.
  787. image_id:
  788. type: string
  789. description: Image ID associated with the chunk.
  790. doc:
  791. type: object
  792. description: Document details.
  793. """
  794. if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id):
  795. return get_error_data_result(message=f"You don't own the dataset {dataset_id}.")
  796. doc = DocumentService.query(id=document_id, kb_id=dataset_id)
  797. if not doc:
  798. return get_error_data_result(
  799. message=f"You don't own the document {document_id}."
  800. )
  801. doc = doc[0]
  802. req = request.args
  803. doc_id = document_id
  804. page = int(req.get("page", 1))
  805. size = int(req.get("page_size", 30))
  806. question = req.get("keywords", "")
  807. query = {
  808. "doc_ids": [doc_id],
  809. "page": page,
  810. "size": size,
  811. "question": question,
  812. "sort": True,
  813. }
  814. key_mapping = {
  815. "chunk_num": "chunk_count",
  816. "kb_id": "dataset_id",
  817. "token_num": "token_count",
  818. "parser_id": "chunk_method",
  819. }
  820. run_mapping = {
  821. "0": "UNSTART",
  822. "1": "RUNNING",
  823. "2": "CANCEL",
  824. "3": "DONE",
  825. "4": "FAIL",
  826. }
  827. doc = doc.to_dict()
  828. renamed_doc = {}
  829. for key, value in doc.items():
  830. new_key = key_mapping.get(key, key)
  831. renamed_doc[new_key] = value
  832. if key == "run":
  833. renamed_doc["run"] = run_mapping.get(str(value))
  834. res = {"total": 0, "chunks": [], "doc": renamed_doc}
  835. if req.get("id"):
  836. chunk = settings.docStoreConn.get(req.get("id"), search.index_name(tenant_id), [dataset_id])
  837. k = []
  838. for n in chunk.keys():
  839. if re.search(r"(_vec$|_sm_|_tks|_ltks)", n):
  840. k.append(n)
  841. for n in k:
  842. del chunk[n]
  843. if not chunk:
  844. return get_error_data_result(f"Chunk `{req.get('id')}` not found.")
  845. res['total'] = 1
  846. final_chunk = {
  847. "id":chunk.get("id",chunk.get("chunk_id")),
  848. "content":chunk["content_with_weight"],
  849. "document_id":chunk.get("doc_id",chunk.get("document_id")),
  850. "docnm_kwd":chunk["docnm_kwd"],
  851. "important_keywords":chunk.get("important_kwd",[]),
  852. "questions":chunk.get("question_kwd",[]),
  853. "dataset_id":chunk.get("kb_id",chunk.get("dataset_id")),
  854. "image_id":chunk["img_id"],
  855. "available":bool(chunk.get("available_int",1)),
  856. "positions":chunk.get("position_int",[]),
  857. }
  858. res["chunks"].append(final_chunk)
  859. _ = Chunk(**final_chunk)
  860. elif settings.docStoreConn.indexExist(search.index_name(tenant_id), dataset_id):
  861. sres = settings.retrievaler.search(query, search.index_name(tenant_id), [dataset_id], emb_mdl=None,
  862. highlight=True)
  863. res["total"] = sres.total
  864. for id in sres.ids:
  865. d = {
  866. "id": id,
  867. "content": (
  868. rmSpace(sres.highlight[id])
  869. if question and id in sres.highlight
  870. else sres.field[id].get("content_with_weight", "")
  871. ),
  872. "document_id": sres.field[id]["doc_id"],
  873. "docnm_kwd": sres.field[id]["docnm_kwd"],
  874. "important_keywords": sres.field[id].get("important_kwd", []),
  875. "questions": sres.field[id].get("question_kwd", []),
  876. "dataset_id": sres.field[id].get("kb_id", sres.field[id].get("dataset_id")),
  877. "image_id": sres.field[id].get("img_id", ""),
  878. "available": bool(sres.field[id].get("available_int", 1)),
  879. "positions": sres.field[id].get("position_int",[]),
  880. }
  881. res["chunks"].append(d)
  882. _ = Chunk(**d) # validate the chunk
  883. return get_result(data=res)
  884. @manager.route( # noqa: F821
  885. "/datasets/<dataset_id>/documents/<document_id>/chunks", methods=["POST"]
  886. )
  887. @token_required
  888. def add_chunk(tenant_id, dataset_id, document_id):
  889. """
  890. Add a chunk to a document.
  891. ---
  892. tags:
  893. - Chunks
  894. security:
  895. - ApiKeyAuth: []
  896. parameters:
  897. - in: path
  898. name: dataset_id
  899. type: string
  900. required: true
  901. description: ID of the dataset.
  902. - in: path
  903. name: document_id
  904. type: string
  905. required: true
  906. description: ID of the document.
  907. - in: body
  908. name: body
  909. description: Chunk data.
  910. required: true
  911. schema:
  912. type: object
  913. properties:
  914. content:
  915. type: string
  916. required: true
  917. description: Content of the chunk.
  918. important_keywords:
  919. type: array
  920. items:
  921. type: string
  922. description: Important keywords.
  923. - in: header
  924. name: Authorization
  925. type: string
  926. required: true
  927. description: Bearer token for authentication.
  928. responses:
  929. 200:
  930. description: Chunk added successfully.
  931. schema:
  932. type: object
  933. properties:
  934. chunk:
  935. type: object
  936. properties:
  937. id:
  938. type: string
  939. description: Chunk ID.
  940. content:
  941. type: string
  942. description: Chunk content.
  943. document_id:
  944. type: string
  945. description: ID of the document.
  946. important_keywords:
  947. type: array
  948. items:
  949. type: string
  950. description: Important keywords.
  951. """
  952. if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id):
  953. return get_error_data_result(message=f"You don't own the dataset {dataset_id}.")
  954. doc = DocumentService.query(id=document_id, kb_id=dataset_id)
  955. if not doc:
  956. return get_error_data_result(
  957. message=f"You don't own the document {document_id}."
  958. )
  959. doc = doc[0]
  960. req = request.json
  961. if not req.get("content"):
  962. return get_error_data_result(message="`content` is required")
  963. if "important_keywords" in req:
  964. if not isinstance(req["important_keywords"], list):
  965. return get_error_data_result(
  966. "`important_keywords` is required to be a list"
  967. )
  968. if "questions" in req:
  969. if not isinstance(req["questions"], list):
  970. return get_error_data_result(
  971. "`questions` is required to be a list"
  972. )
  973. chunk_id = xxhash.xxh64((req["content"] + document_id).encode("utf-8")).hexdigest()
  974. d = {
  975. "id": chunk_id,
  976. "content_ltks": rag_tokenizer.tokenize(req["content"]),
  977. "content_with_weight": req["content"],
  978. }
  979. d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
  980. d["important_kwd"] = req.get("important_keywords", [])
  981. d["important_tks"] = rag_tokenizer.tokenize(
  982. " ".join(req.get("important_keywords", []))
  983. )
  984. d["question_kwd"] = req.get("questions", [])
  985. d["question_tks"] = rag_tokenizer.tokenize(
  986. "\n".join(req.get("questions", []))
  987. )
  988. d["create_time"] = str(datetime.datetime.now()).replace("T", " ")[:19]
  989. d["create_timestamp_flt"] = datetime.datetime.now().timestamp()
  990. d["kb_id"] = dataset_id
  991. d["docnm_kwd"] = doc.name
  992. d["doc_id"] = document_id
  993. embd_id = DocumentService.get_embd_id(document_id)
  994. embd_mdl = TenantLLMService.model_instance(
  995. tenant_id, LLMType.EMBEDDING.value, embd_id
  996. )
  997. v, c = embd_mdl.encode([doc.name, req["content"] if not d["question_kwd"] else "\n".join(d["question_kwd"])])
  998. v = 0.1 * v[0] + 0.9 * v[1]
  999. d["q_%d_vec" % len(v)] = v.tolist()
  1000. settings.docStoreConn.insert([d], search.index_name(tenant_id), dataset_id)
  1001. DocumentService.increment_chunk_num(doc.id, doc.kb_id, c, 1, 0)
  1002. # rename keys
  1003. key_mapping = {
  1004. "id": "id",
  1005. "content_with_weight": "content",
  1006. "doc_id": "document_id",
  1007. "important_kwd": "important_keywords",
  1008. "question_kwd": "questions",
  1009. "kb_id": "dataset_id",
  1010. "create_timestamp_flt": "create_timestamp",
  1011. "create_time": "create_time",
  1012. "document_keyword": "document",
  1013. }
  1014. renamed_chunk = {}
  1015. for key, value in d.items():
  1016. if key in key_mapping:
  1017. new_key = key_mapping.get(key, key)
  1018. renamed_chunk[new_key] = value
  1019. _ = Chunk(**renamed_chunk) # validate the chunk
  1020. return get_result(data={"chunk": renamed_chunk})
  1021. # return get_result(data={"chunk_id": chunk_id})
  1022. @manager.route( # noqa: F821
  1023. "datasets/<dataset_id>/documents/<document_id>/chunks", methods=["DELETE"]
  1024. )
  1025. @token_required
  1026. def rm_chunk(tenant_id, dataset_id, document_id):
  1027. """
  1028. Remove chunks from a document.
  1029. ---
  1030. tags:
  1031. - Chunks
  1032. security:
  1033. - ApiKeyAuth: []
  1034. parameters:
  1035. - in: path
  1036. name: dataset_id
  1037. type: string
  1038. required: true
  1039. description: ID of the dataset.
  1040. - in: path
  1041. name: document_id
  1042. type: string
  1043. required: true
  1044. description: ID of the document.
  1045. - in: body
  1046. name: body
  1047. description: Chunk removal parameters.
  1048. required: true
  1049. schema:
  1050. type: object
  1051. properties:
  1052. chunk_ids:
  1053. type: array
  1054. items:
  1055. type: string
  1056. description: List of chunk IDs to remove.
  1057. - in: header
  1058. name: Authorization
  1059. type: string
  1060. required: true
  1061. description: Bearer token for authentication.
  1062. responses:
  1063. 200:
  1064. description: Chunks removed successfully.
  1065. schema:
  1066. type: object
  1067. """
  1068. if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id):
  1069. return get_error_data_result(message=f"You don't own the dataset {dataset_id}.")
  1070. req = request.json
  1071. condition = {"doc_id": document_id}
  1072. if "chunk_ids" in req:
  1073. condition["id"] = req["chunk_ids"]
  1074. chunk_number = settings.docStoreConn.delete(condition, search.index_name(tenant_id), dataset_id)
  1075. if chunk_number != 0:
  1076. DocumentService.decrement_chunk_num(document_id, dataset_id, 1, chunk_number, 0)
  1077. if "chunk_ids" in req and chunk_number != len(req["chunk_ids"]):
  1078. return get_error_data_result(message=f"rm_chunk deleted chunks {chunk_number}, expect {len(req['chunk_ids'])}")
  1079. return get_result(message=f"deleted {chunk_number} chunks")
  1080. @manager.route( # noqa: F821
  1081. "/datasets/<dataset_id>/documents/<document_id>/chunks/<chunk_id>", methods=["PUT"]
  1082. )
  1083. @token_required
  1084. def update_chunk(tenant_id, dataset_id, document_id, chunk_id):
  1085. """
  1086. Update a chunk within a document.
  1087. ---
  1088. tags:
  1089. - Chunks
  1090. security:
  1091. - ApiKeyAuth: []
  1092. parameters:
  1093. - in: path
  1094. name: dataset_id
  1095. type: string
  1096. required: true
  1097. description: ID of the dataset.
  1098. - in: path
  1099. name: document_id
  1100. type: string
  1101. required: true
  1102. description: ID of the document.
  1103. - in: path
  1104. name: chunk_id
  1105. type: string
  1106. required: true
  1107. description: ID of the chunk to update.
  1108. - in: body
  1109. name: body
  1110. description: Chunk update parameters.
  1111. required: true
  1112. schema:
  1113. type: object
  1114. properties:
  1115. content:
  1116. type: string
  1117. description: Updated content of the chunk.
  1118. important_keywords:
  1119. type: array
  1120. items:
  1121. type: string
  1122. description: Updated important keywords.
  1123. available:
  1124. type: boolean
  1125. description: Availability status of the chunk.
  1126. - in: header
  1127. name: Authorization
  1128. type: string
  1129. required: true
  1130. description: Bearer token for authentication.
  1131. responses:
  1132. 200:
  1133. description: Chunk updated successfully.
  1134. schema:
  1135. type: object
  1136. """
  1137. chunk = settings.docStoreConn.get(chunk_id, search.index_name(tenant_id), [dataset_id])
  1138. if chunk is None:
  1139. return get_error_data_result(f"Can't find this chunk {chunk_id}")
  1140. if not KnowledgebaseService.accessible(kb_id=dataset_id, user_id=tenant_id):
  1141. return get_error_data_result(message=f"You don't own the dataset {dataset_id}.")
  1142. doc = DocumentService.query(id=document_id, kb_id=dataset_id)
  1143. if not doc:
  1144. return get_error_data_result(
  1145. message=f"You don't own the document {document_id}."
  1146. )
  1147. doc = doc[0]
  1148. req = request.json
  1149. if "content" in req:
  1150. content = req["content"]
  1151. else:
  1152. content = chunk.get("content_with_weight", "")
  1153. d = {"id": chunk_id, "content_with_weight": content}
  1154. d["content_ltks"] = rag_tokenizer.tokenize(d["content_with_weight"])
  1155. d["content_sm_ltks"] = rag_tokenizer.fine_grained_tokenize(d["content_ltks"])
  1156. if "important_keywords" in req:
  1157. if not isinstance(req["important_keywords"], list):
  1158. return get_error_data_result("`important_keywords` should be a list")
  1159. d["important_kwd"] = req.get("important_keywords", [])
  1160. d["important_tks"] = rag_tokenizer.tokenize(" ".join(req["important_keywords"]))
  1161. if "questions" in req:
  1162. if not isinstance(req["questions"], list):
  1163. return get_error_data_result("`questions` should be a list")
  1164. d["question_kwd"] = req.get("questions")
  1165. d["question_tks"] = rag_tokenizer.tokenize("\n".join(req["questions"]))
  1166. if "available" in req:
  1167. d["available_int"] = int(req["available"])
  1168. embd_id = DocumentService.get_embd_id(document_id)
  1169. embd_mdl = TenantLLMService.model_instance(
  1170. tenant_id, LLMType.EMBEDDING.value, embd_id
  1171. )
  1172. if doc.parser_id == ParserType.QA:
  1173. arr = [t for t in re.split(r"[\n\t]", d["content_with_weight"]) if len(t) > 1]
  1174. if len(arr) != 2:
  1175. return get_error_data_result(
  1176. message="Q&A must be separated by TAB/ENTER key."
  1177. )
  1178. q, a = rmPrefix(arr[0]), rmPrefix(arr[1])
  1179. d = beAdoc(
  1180. d, arr[0], arr[1], not any([rag_tokenizer.is_chinese(t) for t in q + a])
  1181. )
  1182. v, c = embd_mdl.encode([doc.name, d["content_with_weight"] if not d.get("question_kwd") else "\n".join(d["question_kwd"])])
  1183. v = 0.1 * v[0] + 0.9 * v[1] if doc.parser_id != ParserType.QA else v[1]
  1184. d["q_%d_vec" % len(v)] = v.tolist()
  1185. settings.docStoreConn.update({"id": chunk_id}, d, search.index_name(tenant_id), dataset_id)
  1186. return get_result()
  1187. @manager.route("/retrieval", methods=["POST"]) # noqa: F821
  1188. @token_required
  1189. def retrieval_test(tenant_id):
  1190. """
  1191. Retrieve chunks based on a query.
  1192. ---
  1193. tags:
  1194. - Retrieval
  1195. security:
  1196. - ApiKeyAuth: []
  1197. parameters:
  1198. - in: body
  1199. name: body
  1200. description: Retrieval parameters.
  1201. required: true
  1202. schema:
  1203. type: object
  1204. properties:
  1205. dataset_ids:
  1206. type: array
  1207. items:
  1208. type: string
  1209. required: true
  1210. description: List of dataset IDs to search in.
  1211. question:
  1212. type: string
  1213. required: true
  1214. description: Query string.
  1215. document_ids:
  1216. type: array
  1217. items:
  1218. type: string
  1219. description: List of document IDs to filter.
  1220. similarity_threshold:
  1221. type: number
  1222. format: float
  1223. description: Similarity threshold.
  1224. vector_similarity_weight:
  1225. type: number
  1226. format: float
  1227. description: Vector similarity weight.
  1228. top_k:
  1229. type: integer
  1230. description: Maximum number of chunks to return.
  1231. highlight:
  1232. type: boolean
  1233. description: Whether to highlight matched content.
  1234. - in: header
  1235. name: Authorization
  1236. type: string
  1237. required: true
  1238. description: Bearer token for authentication.
  1239. responses:
  1240. 200:
  1241. description: Retrieval results.
  1242. schema:
  1243. type: object
  1244. properties:
  1245. chunks:
  1246. type: array
  1247. items:
  1248. type: object
  1249. properties:
  1250. id:
  1251. type: string
  1252. description: Chunk ID.
  1253. content:
  1254. type: string
  1255. description: Chunk content.
  1256. document_id:
  1257. type: string
  1258. description: ID of the document.
  1259. dataset_id:
  1260. type: string
  1261. description: ID of the dataset.
  1262. similarity:
  1263. type: number
  1264. format: float
  1265. description: Similarity score.
  1266. """
  1267. req = request.json
  1268. if not req.get("dataset_ids"):
  1269. return get_error_data_result("`dataset_ids` is required.")
  1270. kb_ids = req["dataset_ids"]
  1271. if not isinstance(kb_ids, list):
  1272. return get_error_data_result("`dataset_ids` should be a list")
  1273. for id in kb_ids:
  1274. if not KnowledgebaseService.accessible(kb_id=id, user_id=tenant_id):
  1275. return get_error_data_result(f"You don't own the dataset {id}.")
  1276. kbs = KnowledgebaseService.get_by_ids(kb_ids)
  1277. embd_nms = list(set([TenantLLMService.split_model_name_and_factory(kb.embd_id)[0] for kb in kbs])) # remove vendor suffix for comparison
  1278. if len(embd_nms) != 1:
  1279. return get_result(
  1280. message='Datasets use different embedding models."',
  1281. code=settings.RetCode.DATA_ERROR,
  1282. )
  1283. if "question" not in req:
  1284. return get_error_data_result("`question` is required.")
  1285. page = int(req.get("page", 1))
  1286. size = int(req.get("page_size", 30))
  1287. question = req["question"]
  1288. doc_ids = req.get("document_ids", [])
  1289. use_kg = req.get("use_kg", False)
  1290. if not isinstance(doc_ids, list):
  1291. return get_error_data_result("`documents` should be a list")
  1292. doc_ids_list = KnowledgebaseService.list_documents_by_ids(kb_ids)
  1293. for doc_id in doc_ids:
  1294. if doc_id not in doc_ids_list:
  1295. return get_error_data_result(
  1296. f"The datasets don't own the document {doc_id}"
  1297. )
  1298. similarity_threshold = float(req.get("similarity_threshold", 0.2))
  1299. vector_similarity_weight = float(req.get("vector_similarity_weight", 0.3))
  1300. top = int(req.get("top_k", 1024))
  1301. if req.get("highlight") == "False" or req.get("highlight") == "false":
  1302. highlight = False
  1303. else:
  1304. highlight = True
  1305. try:
  1306. e, kb = KnowledgebaseService.get_by_id(kb_ids[0])
  1307. if not e:
  1308. return get_error_data_result(message="Dataset not found!")
  1309. embd_mdl = LLMBundle(kb.tenant_id, LLMType.EMBEDDING, llm_name=kb.embd_id)
  1310. rerank_mdl = None
  1311. if req.get("rerank_id"):
  1312. rerank_mdl = LLMBundle(kb.tenant_id, LLMType.RERANK, llm_name=req["rerank_id"])
  1313. if req.get("keyword", False):
  1314. chat_mdl = LLMBundle(kb.tenant_id, LLMType.CHAT)
  1315. question += keyword_extraction(chat_mdl, question)
  1316. ranks = settings.retrievaler.retrieval(
  1317. question,
  1318. embd_mdl,
  1319. kb.tenant_id,
  1320. kb_ids,
  1321. page,
  1322. size,
  1323. similarity_threshold,
  1324. vector_similarity_weight,
  1325. top,
  1326. doc_ids,
  1327. rerank_mdl=rerank_mdl,
  1328. highlight=highlight,
  1329. rank_feature=label_question(question, kbs)
  1330. )
  1331. if use_kg:
  1332. ck = settings.kg_retrievaler.retrieval(question,
  1333. [k.tenant_id for k in kbs],
  1334. kb_ids,
  1335. embd_mdl,
  1336. LLMBundle(kb.tenant_id, LLMType.CHAT))
  1337. if ck["content_with_weight"]:
  1338. ranks["chunks"].insert(0, ck)
  1339. for c in ranks["chunks"]:
  1340. c.pop("vector", None)
  1341. ##rename keys
  1342. renamed_chunks = []
  1343. for chunk in ranks["chunks"]:
  1344. key_mapping = {
  1345. "chunk_id": "id",
  1346. "content_with_weight": "content",
  1347. "doc_id": "document_id",
  1348. "important_kwd": "important_keywords",
  1349. "question_kwd": "questions",
  1350. "docnm_kwd": "document_keyword",
  1351. "kb_id":"dataset_id"
  1352. }
  1353. rename_chunk = {}
  1354. for key, value in chunk.items():
  1355. new_key = key_mapping.get(key, key)
  1356. rename_chunk[new_key] = value
  1357. renamed_chunks.append(rename_chunk)
  1358. ranks["chunks"] = renamed_chunks
  1359. return get_result(data=ranks)
  1360. except Exception as e:
  1361. if str(e).find("not_found") > 0:
  1362. return get_result(
  1363. message="No chunk found! Check the chunk status please!",
  1364. code=settings.RetCode.DATA_ERROR,
  1365. )
  1366. return server_error_response(e)