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

dataset.py 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  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. from flask import request
  17. from api.db import StatusEnum, FileSource
  18. from api.db.db_models import File
  19. from api.db.services.document_service import DocumentService
  20. from api.db.services.file2document_service import File2DocumentService
  21. from api.db.services.file_service import FileService
  22. from api.db.services.knowledgebase_service import KnowledgebaseService
  23. from api.db.services.llm_service import TenantLLMService, LLMService
  24. from api.db.services.user_service import TenantService
  25. from api import settings
  26. from api.utils import get_uuid
  27. from api.utils.api_utils import (
  28. get_result,
  29. token_required,
  30. get_error_data_result,
  31. valid,
  32. get_parser_config, valid_parser_config, dataset_readonly_fields,check_duplicate_ids
  33. )
  34. @manager.route("/datasets", methods=["POST"]) # noqa: F821
  35. @token_required
  36. def create(tenant_id):
  37. """
  38. Create a new dataset.
  39. ---
  40. tags:
  41. - Datasets
  42. security:
  43. - ApiKeyAuth: []
  44. parameters:
  45. - in: header
  46. name: Authorization
  47. type: string
  48. required: true
  49. description: Bearer token for authentication.
  50. - in: body
  51. name: body
  52. description: Dataset creation parameters.
  53. required: true
  54. schema:
  55. type: object
  56. required:
  57. - name
  58. properties:
  59. name:
  60. type: string
  61. description: Name of the dataset.
  62. permission:
  63. type: string
  64. enum: ['me', 'team']
  65. description: Dataset permission.
  66. chunk_method:
  67. type: string
  68. enum: ["naive", "manual", "qa", "table", "paper", "book", "laws",
  69. "presentation", "picture", "one", "email", "tag"
  70. ]
  71. description: Chunking method.
  72. parser_config:
  73. type: object
  74. description: Parser configuration.
  75. responses:
  76. 200:
  77. description: Successful operation.
  78. schema:
  79. type: object
  80. properties:
  81. data:
  82. type: object
  83. """
  84. req = request.json
  85. for k in req.keys():
  86. if dataset_readonly_fields(k):
  87. return get_result(code=settings.RetCode.ARGUMENT_ERROR, message=f"'{k}' is readonly.")
  88. e, t = TenantService.get_by_id(tenant_id)
  89. permission = req.get("permission")
  90. chunk_method = req.get("chunk_method")
  91. parser_config = req.get("parser_config")
  92. valid_parser_config(parser_config)
  93. valid_permission = ["me", "team"]
  94. valid_chunk_method = [
  95. "naive",
  96. "manual",
  97. "qa",
  98. "table",
  99. "paper",
  100. "book",
  101. "laws",
  102. "presentation",
  103. "picture",
  104. "one",
  105. "email",
  106. "tag"
  107. ]
  108. check_validation = valid(
  109. permission,
  110. valid_permission,
  111. chunk_method,
  112. valid_chunk_method,
  113. )
  114. if check_validation:
  115. return check_validation
  116. req["parser_config"] = get_parser_config(chunk_method, parser_config)
  117. if "tenant_id" in req:
  118. return get_error_data_result(message="`tenant_id` must not be provided")
  119. if "chunk_count" in req or "document_count" in req:
  120. return get_error_data_result(
  121. message="`chunk_count` or `document_count` must not be provided"
  122. )
  123. if "name" not in req:
  124. return get_error_data_result(message="`name` is not empty!")
  125. req["id"] = get_uuid()
  126. req["name"] = req["name"].strip()
  127. if req["name"] == "":
  128. return get_error_data_result(message="`name` is not empty string!")
  129. if len(req["name"]) >= 128:
  130. return get_error_data_result(
  131. message="Dataset name should not be longer than 128 characters."
  132. )
  133. if KnowledgebaseService.query(
  134. name=req["name"], tenant_id=tenant_id, status=StatusEnum.VALID.value
  135. ):
  136. return get_error_data_result(
  137. message="Duplicated dataset name in creating dataset."
  138. )
  139. req["tenant_id"] = tenant_id
  140. req["created_by"] = tenant_id
  141. if not req.get("embedding_model"):
  142. req["embedding_model"] = t.embd_id
  143. else:
  144. valid_embedding_models = [
  145. "BAAI/bge-large-zh-v1.5",
  146. "maidalun1020/bce-embedding-base_v1",
  147. ]
  148. embd_model = LLMService.query(
  149. llm_name=req["embedding_model"], model_type="embedding"
  150. )
  151. if embd_model:
  152. if req["embedding_model"] not in valid_embedding_models and not TenantLLMService.query(tenant_id=tenant_id,model_type="embedding",llm_name=req.get("embedding_model"),):
  153. return get_error_data_result(f"`embedding_model` {req.get('embedding_model')} doesn't exist")
  154. if not embd_model:
  155. embd_model=TenantLLMService.query(tenant_id=tenant_id,model_type="embedding", llm_name=req.get("embedding_model"))
  156. if not embd_model:
  157. return get_error_data_result(
  158. f"`embedding_model` {req.get('embedding_model')} doesn't exist"
  159. )
  160. key_mapping = {
  161. "chunk_num": "chunk_count",
  162. "doc_num": "document_count",
  163. "parser_id": "chunk_method",
  164. "embd_id": "embedding_model",
  165. }
  166. mapped_keys = {
  167. new_key: req[old_key]
  168. for new_key, old_key in key_mapping.items()
  169. if old_key in req
  170. }
  171. req.update(mapped_keys)
  172. flds = list(req.keys())
  173. for f in flds:
  174. if req[f] == "" and f in ["permission", "parser_id", "chunk_method"]:
  175. del req[f]
  176. if not KnowledgebaseService.save(**req):
  177. return get_error_data_result(message="Create dataset error.(Database error)")
  178. renamed_data = {}
  179. e, k = KnowledgebaseService.get_by_id(req["id"])
  180. for key, value in k.to_dict().items():
  181. new_key = key_mapping.get(key, key)
  182. renamed_data[new_key] = value
  183. return get_result(data=renamed_data)
  184. @manager.route("/datasets", methods=["DELETE"]) # noqa: F821
  185. @token_required
  186. def delete(tenant_id):
  187. """
  188. Delete datasets.
  189. ---
  190. tags:
  191. - Datasets
  192. security:
  193. - ApiKeyAuth: []
  194. parameters:
  195. - in: header
  196. name: Authorization
  197. type: string
  198. required: true
  199. description: Bearer token for authentication.
  200. - in: body
  201. name: body
  202. description: Dataset deletion parameters.
  203. required: true
  204. schema:
  205. type: object
  206. properties:
  207. ids:
  208. type: array
  209. items:
  210. type: string
  211. description: List of dataset IDs to delete.
  212. responses:
  213. 200:
  214. description: Successful operation.
  215. schema:
  216. type: object
  217. """
  218. errors = []
  219. success_count = 0
  220. req = request.json
  221. if not req:
  222. ids = None
  223. else:
  224. ids = req.get("ids")
  225. if not ids:
  226. id_list = []
  227. kbs = KnowledgebaseService.query(tenant_id=tenant_id)
  228. for kb in kbs:
  229. id_list.append(kb.id)
  230. else:
  231. id_list = ids
  232. unique_id_list, duplicate_messages = check_duplicate_ids(id_list, "dataset")
  233. id_list = unique_id_list
  234. for id in id_list:
  235. kbs = KnowledgebaseService.query(id=id, tenant_id=tenant_id)
  236. if not kbs:
  237. errors.append(f"You don't own the dataset {id}")
  238. continue
  239. for doc in DocumentService.query(kb_id=id):
  240. if not DocumentService.remove_document(doc, tenant_id):
  241. errors.append(f"Remove document error for dataset {id}")
  242. continue
  243. f2d = File2DocumentService.get_by_document_id(doc.id)
  244. FileService.filter_delete(
  245. [
  246. File.source_type == FileSource.KNOWLEDGEBASE,
  247. File.id == f2d[0].file_id,
  248. ]
  249. )
  250. File2DocumentService.delete_by_document_id(doc.id)
  251. FileService.filter_delete(
  252. [File.source_type == FileSource.KNOWLEDGEBASE, File.type == "folder", File.name == kbs[0].name])
  253. if not KnowledgebaseService.delete_by_id(id):
  254. errors.append(f"Delete dataset error for {id}")
  255. continue
  256. success_count += 1
  257. if errors:
  258. if success_count > 0:
  259. return get_result(
  260. data={"success_count": success_count, "errors": errors},
  261. message=f"Partially deleted {success_count} datasets with {len(errors)} errors"
  262. )
  263. else:
  264. return get_error_data_result(message="; ".join(errors))
  265. if duplicate_messages:
  266. if success_count > 0:
  267. return get_result(message=f"Partially deleted {success_count} datasets with {len(duplicate_messages)} errors", data={"success_count": success_count, "errors": duplicate_messages},)
  268. else:
  269. return get_error_data_result(message=";".join(duplicate_messages))
  270. return get_result(code=settings.RetCode.SUCCESS)
  271. @manager.route("/datasets/<dataset_id>", methods=["PUT"]) # noqa: F821
  272. @token_required
  273. def update(tenant_id, dataset_id):
  274. """
  275. Update a dataset.
  276. ---
  277. tags:
  278. - Datasets
  279. security:
  280. - ApiKeyAuth: []
  281. parameters:
  282. - in: path
  283. name: dataset_id
  284. type: string
  285. required: true
  286. description: ID of the dataset to update.
  287. - in: header
  288. name: Authorization
  289. type: string
  290. required: true
  291. description: Bearer token for authentication.
  292. - in: body
  293. name: body
  294. description: Dataset update parameters.
  295. required: true
  296. schema:
  297. type: object
  298. properties:
  299. name:
  300. type: string
  301. description: New name of the dataset.
  302. permission:
  303. type: string
  304. enum: ['me', 'team']
  305. description: Updated permission.
  306. chunk_method:
  307. type: string
  308. enum: ["naive", "manual", "qa", "table", "paper", "book", "laws",
  309. "presentation", "picture", "one", "email", "tag"
  310. ]
  311. description: Updated chunking method.
  312. parser_config:
  313. type: object
  314. description: Updated parser configuration.
  315. responses:
  316. 200:
  317. description: Successful operation.
  318. schema:
  319. type: object
  320. """
  321. if not KnowledgebaseService.query(id=dataset_id, tenant_id=tenant_id):
  322. return get_error_data_result(message="You don't own the dataset")
  323. req = request.json
  324. for k in req.keys():
  325. if dataset_readonly_fields(k):
  326. return get_result(code=settings.RetCode.ARGUMENT_ERROR, message=f"'{k}' is readonly.")
  327. e, t = TenantService.get_by_id(tenant_id)
  328. invalid_keys = {"id", "embd_id", "chunk_num", "doc_num", "parser_id", "create_date", "create_time", "created_by", "status","token_num","update_date","update_time"}
  329. if any(key in req for key in invalid_keys):
  330. return get_error_data_result(message="The input parameters are invalid.")
  331. permission = req.get("permission")
  332. chunk_method = req.get("chunk_method")
  333. parser_config = req.get("parser_config")
  334. valid_parser_config(parser_config)
  335. valid_permission = ["me", "team"]
  336. valid_chunk_method = [
  337. "naive",
  338. "manual",
  339. "qa",
  340. "table",
  341. "paper",
  342. "book",
  343. "laws",
  344. "presentation",
  345. "picture",
  346. "one",
  347. "email",
  348. "tag"
  349. ]
  350. check_validation = valid(
  351. permission,
  352. valid_permission,
  353. chunk_method,
  354. valid_chunk_method,
  355. )
  356. if check_validation:
  357. return check_validation
  358. if "tenant_id" in req:
  359. if req["tenant_id"] != tenant_id:
  360. return get_error_data_result(message="Can't change `tenant_id`.")
  361. e, kb = KnowledgebaseService.get_by_id(dataset_id)
  362. if "parser_config" in req:
  363. temp_dict = kb.parser_config
  364. temp_dict.update(req["parser_config"])
  365. req["parser_config"] = temp_dict
  366. if "chunk_count" in req:
  367. if req["chunk_count"] != kb.chunk_num:
  368. return get_error_data_result(message="Can't change `chunk_count`.")
  369. req.pop("chunk_count")
  370. if "document_count" in req:
  371. if req["document_count"] != kb.doc_num:
  372. return get_error_data_result(message="Can't change `document_count`.")
  373. req.pop("document_count")
  374. if req.get("chunk_method"):
  375. if kb.chunk_num != 0 and req["chunk_method"] != kb.parser_id:
  376. return get_error_data_result(
  377. message="If `chunk_count` is not 0, `chunk_method` is not changeable."
  378. )
  379. req["parser_id"] = req.pop("chunk_method")
  380. if req["parser_id"] != kb.parser_id:
  381. if not req.get("parser_config"):
  382. req["parser_config"] = get_parser_config(chunk_method, parser_config)
  383. if "embedding_model" in req:
  384. if kb.chunk_num != 0 and req["embedding_model"] != kb.embd_id:
  385. return get_error_data_result(
  386. message="If `chunk_count` is not 0, `embedding_model` is not changeable."
  387. )
  388. if not req.get("embedding_model"):
  389. return get_error_data_result("`embedding_model` can't be empty")
  390. valid_embedding_models = [
  391. "BAAI/bge-large-zh-v1.5",
  392. "BAAI/bge-base-en-v1.5",
  393. "BAAI/bge-large-en-v1.5",
  394. "BAAI/bge-small-en-v1.5",
  395. "BAAI/bge-small-zh-v1.5",
  396. "jinaai/jina-embeddings-v2-base-en",
  397. "jinaai/jina-embeddings-v2-small-en",
  398. "nomic-ai/nomic-embed-text-v1.5",
  399. "sentence-transformers/all-MiniLM-L6-v2",
  400. "text-embedding-v2",
  401. "text-embedding-v3",
  402. "maidalun1020/bce-embedding-base_v1",
  403. ]
  404. embd_model = LLMService.query(
  405. llm_name=req["embedding_model"], model_type="embedding"
  406. )
  407. if embd_model:
  408. if req["embedding_model"] not in valid_embedding_models and not TenantLLMService.query(tenant_id=tenant_id,model_type="embedding",llm_name=req.get("embedding_model"),):
  409. return get_error_data_result(f"`embedding_model` {req.get('embedding_model')} doesn't exist")
  410. if not embd_model:
  411. embd_model=TenantLLMService.query(tenant_id=tenant_id,model_type="embedding", llm_name=req.get("embedding_model"))
  412. if not embd_model:
  413. return get_error_data_result(
  414. f"`embedding_model` {req.get('embedding_model')} doesn't exist"
  415. )
  416. req["embd_id"] = req.pop("embedding_model")
  417. if "name" in req:
  418. req["name"] = req["name"].strip()
  419. if len(req["name"]) >= 128:
  420. return get_error_data_result(
  421. message="Dataset name should not be longer than 128 characters."
  422. )
  423. if (
  424. req["name"].lower() != kb.name.lower()
  425. and len(
  426. KnowledgebaseService.query(
  427. name=req["name"], tenant_id=tenant_id, status=StatusEnum.VALID.value
  428. )
  429. )
  430. > 0
  431. ):
  432. return get_error_data_result(
  433. message="Duplicated dataset name in updating dataset."
  434. )
  435. flds = list(req.keys())
  436. for f in flds:
  437. if req[f] == "" and f in ["permission", "parser_id", "chunk_method"]:
  438. del req[f]
  439. if not KnowledgebaseService.update_by_id(kb.id, req):
  440. return get_error_data_result(message="Update dataset error.(Database error)")
  441. return get_result(code=settings.RetCode.SUCCESS)
  442. @manager.route("/datasets", methods=["GET"]) # noqa: F821
  443. @token_required
  444. def list_datasets(tenant_id):
  445. """
  446. List datasets.
  447. ---
  448. tags:
  449. - Datasets
  450. security:
  451. - ApiKeyAuth: []
  452. parameters:
  453. - in: query
  454. name: id
  455. type: string
  456. required: false
  457. description: Dataset ID to filter.
  458. - in: query
  459. name: name
  460. type: string
  461. required: false
  462. description: Dataset name to filter.
  463. - in: query
  464. name: page
  465. type: integer
  466. required: false
  467. default: 1
  468. description: Page number.
  469. - in: query
  470. name: page_size
  471. type: integer
  472. required: false
  473. default: 1024
  474. description: Number of items per page.
  475. - in: query
  476. name: orderby
  477. type: string
  478. required: false
  479. default: "create_time"
  480. description: Field to order by.
  481. - in: query
  482. name: desc
  483. type: boolean
  484. required: false
  485. default: true
  486. description: Order in descending.
  487. - in: header
  488. name: Authorization
  489. type: string
  490. required: true
  491. description: Bearer token for authentication.
  492. responses:
  493. 200:
  494. description: Successful operation.
  495. schema:
  496. type: array
  497. items:
  498. type: object
  499. """
  500. id = request.args.get("id")
  501. name = request.args.get("name")
  502. if id:
  503. kbs = KnowledgebaseService.get_kb_by_id(id,tenant_id)
  504. if not kbs:
  505. return get_error_data_result(f"You don't own the dataset {id}")
  506. if name:
  507. kbs = KnowledgebaseService.get_kb_by_name(name,tenant_id)
  508. if not kbs:
  509. return get_error_data_result(f"You don't own the dataset {name}")
  510. page_number = int(request.args.get("page", 1))
  511. items_per_page = int(request.args.get("page_size", 30))
  512. orderby = request.args.get("orderby", "create_time")
  513. if request.args.get("desc", "false").lower() not in ["true", "false"]:
  514. return get_error_data_result("desc should be true or false")
  515. if request.args.get("desc", "true").lower() == "false":
  516. desc = False
  517. else:
  518. desc = True
  519. tenants = TenantService.get_joined_tenants_by_user_id(tenant_id)
  520. kbs = KnowledgebaseService.get_list(
  521. [m["tenant_id"] for m in tenants],
  522. tenant_id,
  523. page_number,
  524. items_per_page,
  525. orderby,
  526. desc,
  527. id,
  528. name,
  529. )
  530. renamed_list = []
  531. for kb in kbs:
  532. key_mapping = {
  533. "chunk_num": "chunk_count",
  534. "doc_num": "document_count",
  535. "parser_id": "chunk_method",
  536. "embd_id": "embedding_model",
  537. }
  538. renamed_data = {}
  539. for key, value in kb.items():
  540. new_key = key_mapping.get(key, key)
  541. renamed_data[new_key] = value
  542. renamed_list.append(renamed_data)
  543. return get_result(data=renamed_list)