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

doc.py 52KB

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