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

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