您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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