Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. from flask import request
  2. from flask_login import current_user
  3. from flask_restx import marshal, reqparse
  4. from werkzeug.exceptions import NotFound
  5. from controllers.service_api import service_api_ns
  6. from controllers.service_api.app.error import ProviderNotInitializeError
  7. from controllers.service_api.wraps import (
  8. DatasetApiResource,
  9. cloud_edition_billing_knowledge_limit_check,
  10. cloud_edition_billing_rate_limit_check,
  11. cloud_edition_billing_resource_check,
  12. )
  13. from core.errors.error import LLMBadRequestError, ProviderTokenNotInitError
  14. from core.model_manager import ModelManager
  15. from core.model_runtime.entities.model_entities import ModelType
  16. from extensions.ext_database import db
  17. from fields.segment_fields import child_chunk_fields, segment_fields
  18. from models.dataset import Dataset
  19. from services.dataset_service import DatasetService, DocumentService, SegmentService
  20. from services.entities.knowledge_entities.knowledge_entities import SegmentUpdateArgs
  21. from services.errors.chunk import ChildChunkDeleteIndexError, ChildChunkIndexingError
  22. from services.errors.chunk import ChildChunkDeleteIndexError as ChildChunkDeleteIndexServiceError
  23. from services.errors.chunk import ChildChunkIndexingError as ChildChunkIndexingServiceError
  24. # Define parsers for segment operations
  25. segment_create_parser = reqparse.RequestParser()
  26. segment_create_parser.add_argument("segments", type=list, required=False, nullable=True, location="json")
  27. segment_list_parser = reqparse.RequestParser()
  28. segment_list_parser.add_argument("status", type=str, action="append", default=[], location="args")
  29. segment_list_parser.add_argument("keyword", type=str, default=None, location="args")
  30. segment_update_parser = reqparse.RequestParser()
  31. segment_update_parser.add_argument("segment", type=dict, required=False, nullable=True, location="json")
  32. child_chunk_create_parser = reqparse.RequestParser()
  33. child_chunk_create_parser.add_argument("content", type=str, required=True, nullable=False, location="json")
  34. child_chunk_list_parser = reqparse.RequestParser()
  35. child_chunk_list_parser.add_argument("limit", type=int, default=20, location="args")
  36. child_chunk_list_parser.add_argument("keyword", type=str, default=None, location="args")
  37. child_chunk_list_parser.add_argument("page", type=int, default=1, location="args")
  38. child_chunk_update_parser = reqparse.RequestParser()
  39. child_chunk_update_parser.add_argument("content", type=str, required=True, nullable=False, location="json")
  40. @service_api_ns.route("/datasets/<uuid:dataset_id>/documents/<uuid:document_id>/segments")
  41. class SegmentApi(DatasetApiResource):
  42. """Resource for segments."""
  43. @service_api_ns.expect(segment_create_parser)
  44. @service_api_ns.doc("create_segments")
  45. @service_api_ns.doc(description="Create segments in a document")
  46. @service_api_ns.doc(params={"dataset_id": "Dataset ID", "document_id": "Document ID"})
  47. @service_api_ns.doc(
  48. responses={
  49. 200: "Segments created successfully",
  50. 400: "Bad request - segments data is missing",
  51. 401: "Unauthorized - invalid API token",
  52. 404: "Dataset or document not found",
  53. }
  54. )
  55. @cloud_edition_billing_resource_check("vector_space", "dataset")
  56. @cloud_edition_billing_knowledge_limit_check("add_segment", "dataset")
  57. @cloud_edition_billing_rate_limit_check("knowledge", "dataset")
  58. def post(self, tenant_id: str, dataset_id: str, document_id: str):
  59. """Create single segment."""
  60. # check dataset
  61. dataset = db.session.query(Dataset).where(Dataset.tenant_id == tenant_id, Dataset.id == dataset_id).first()
  62. if not dataset:
  63. raise NotFound("Dataset not found.")
  64. # check document
  65. document = DocumentService.get_document(dataset.id, document_id)
  66. if not document:
  67. raise NotFound("Document not found.")
  68. if document.indexing_status != "completed":
  69. raise NotFound("Document is not completed.")
  70. if not document.enabled:
  71. raise NotFound("Document is disabled.")
  72. # check embedding model setting
  73. if dataset.indexing_technique == "high_quality":
  74. try:
  75. model_manager = ModelManager()
  76. model_manager.get_model_instance(
  77. tenant_id=current_user.current_tenant_id,
  78. provider=dataset.embedding_model_provider,
  79. model_type=ModelType.TEXT_EMBEDDING,
  80. model=dataset.embedding_model,
  81. )
  82. except LLMBadRequestError:
  83. raise ProviderNotInitializeError(
  84. "No Embedding Model available. Please configure a valid provider in the Settings -> Model Provider."
  85. )
  86. except ProviderTokenNotInitError as ex:
  87. raise ProviderNotInitializeError(ex.description)
  88. # validate args
  89. args = segment_create_parser.parse_args()
  90. if args["segments"] is not None:
  91. for args_item in args["segments"]:
  92. SegmentService.segment_create_args_validate(args_item, document)
  93. segments = SegmentService.multi_create_segment(args["segments"], document, dataset)
  94. return {"data": marshal(segments, segment_fields), "doc_form": document.doc_form}, 200
  95. else:
  96. return {"error": "Segments is required"}, 400
  97. @service_api_ns.expect(segment_list_parser)
  98. @service_api_ns.doc("list_segments")
  99. @service_api_ns.doc(description="List segments in a document")
  100. @service_api_ns.doc(params={"dataset_id": "Dataset ID", "document_id": "Document ID"})
  101. @service_api_ns.doc(
  102. responses={
  103. 200: "Segments retrieved successfully",
  104. 401: "Unauthorized - invalid API token",
  105. 404: "Dataset or document not found",
  106. }
  107. )
  108. def get(self, tenant_id: str, dataset_id: str, document_id: str):
  109. """Get segments."""
  110. # check dataset
  111. page = request.args.get("page", default=1, type=int)
  112. limit = request.args.get("limit", default=20, type=int)
  113. dataset = db.session.query(Dataset).where(Dataset.tenant_id == tenant_id, Dataset.id == dataset_id).first()
  114. if not dataset:
  115. raise NotFound("Dataset not found.")
  116. # check document
  117. document = DocumentService.get_document(dataset.id, document_id)
  118. if not document:
  119. raise NotFound("Document not found.")
  120. # check embedding model setting
  121. if dataset.indexing_technique == "high_quality":
  122. try:
  123. model_manager = ModelManager()
  124. model_manager.get_model_instance(
  125. tenant_id=current_user.current_tenant_id,
  126. provider=dataset.embedding_model_provider,
  127. model_type=ModelType.TEXT_EMBEDDING,
  128. model=dataset.embedding_model,
  129. )
  130. except LLMBadRequestError:
  131. raise ProviderNotInitializeError(
  132. "No Embedding Model available. Please configure a valid provider in the Settings -> Model Provider."
  133. )
  134. except ProviderTokenNotInitError as ex:
  135. raise ProviderNotInitializeError(ex.description)
  136. args = segment_list_parser.parse_args()
  137. segments, total = SegmentService.get_segments(
  138. document_id=document_id,
  139. tenant_id=current_user.current_tenant_id,
  140. status_list=args["status"],
  141. keyword=args["keyword"],
  142. page=page,
  143. limit=limit,
  144. )
  145. response = {
  146. "data": marshal(segments, segment_fields),
  147. "doc_form": document.doc_form,
  148. "total": total,
  149. "has_more": len(segments) == limit,
  150. "limit": limit,
  151. "page": page,
  152. }
  153. return response, 200
  154. @service_api_ns.route("/datasets/<uuid:dataset_id>/documents/<uuid:document_id>/segments/<uuid:segment_id>")
  155. class DatasetSegmentApi(DatasetApiResource):
  156. @service_api_ns.doc("delete_segment")
  157. @service_api_ns.doc(description="Delete a specific segment")
  158. @service_api_ns.doc(
  159. params={"dataset_id": "Dataset ID", "document_id": "Document ID", "segment_id": "Segment ID to delete"}
  160. )
  161. @service_api_ns.doc(
  162. responses={
  163. 204: "Segment deleted successfully",
  164. 401: "Unauthorized - invalid API token",
  165. 404: "Dataset, document, or segment not found",
  166. }
  167. )
  168. @cloud_edition_billing_rate_limit_check("knowledge", "dataset")
  169. def delete(self, tenant_id: str, dataset_id: str, document_id: str, segment_id: str):
  170. # check dataset
  171. dataset = db.session.query(Dataset).where(Dataset.tenant_id == tenant_id, Dataset.id == dataset_id).first()
  172. if not dataset:
  173. raise NotFound("Dataset not found.")
  174. # check user's model setting
  175. DatasetService.check_dataset_model_setting(dataset)
  176. # check document
  177. document = DocumentService.get_document(dataset_id, document_id)
  178. if not document:
  179. raise NotFound("Document not found.")
  180. # check segment
  181. segment = SegmentService.get_segment_by_id(segment_id=segment_id, tenant_id=current_user.current_tenant_id)
  182. if not segment:
  183. raise NotFound("Segment not found.")
  184. SegmentService.delete_segment(segment, document, dataset)
  185. return 204
  186. @service_api_ns.expect(segment_update_parser)
  187. @service_api_ns.doc("update_segment")
  188. @service_api_ns.doc(description="Update a specific segment")
  189. @service_api_ns.doc(
  190. params={"dataset_id": "Dataset ID", "document_id": "Document ID", "segment_id": "Segment ID to update"}
  191. )
  192. @service_api_ns.doc(
  193. responses={
  194. 200: "Segment updated successfully",
  195. 401: "Unauthorized - invalid API token",
  196. 404: "Dataset, document, or segment not found",
  197. }
  198. )
  199. @cloud_edition_billing_resource_check("vector_space", "dataset")
  200. @cloud_edition_billing_rate_limit_check("knowledge", "dataset")
  201. def post(self, tenant_id: str, dataset_id: str, document_id: str, segment_id: str):
  202. # check dataset
  203. dataset = db.session.query(Dataset).where(Dataset.tenant_id == tenant_id, Dataset.id == dataset_id).first()
  204. if not dataset:
  205. raise NotFound("Dataset not found.")
  206. # check user's model setting
  207. DatasetService.check_dataset_model_setting(dataset)
  208. # check document
  209. document = DocumentService.get_document(dataset_id, document_id)
  210. if not document:
  211. raise NotFound("Document not found.")
  212. if dataset.indexing_technique == "high_quality":
  213. # check embedding model setting
  214. try:
  215. model_manager = ModelManager()
  216. model_manager.get_model_instance(
  217. tenant_id=current_user.current_tenant_id,
  218. provider=dataset.embedding_model_provider,
  219. model_type=ModelType.TEXT_EMBEDDING,
  220. model=dataset.embedding_model,
  221. )
  222. except LLMBadRequestError:
  223. raise ProviderNotInitializeError(
  224. "No Embedding Model available. Please configure a valid provider in the Settings -> Model Provider."
  225. )
  226. except ProviderTokenNotInitError as ex:
  227. raise ProviderNotInitializeError(ex.description)
  228. # check segment
  229. segment = SegmentService.get_segment_by_id(segment_id=segment_id, tenant_id=current_user.current_tenant_id)
  230. if not segment:
  231. raise NotFound("Segment not found.")
  232. # validate args
  233. args = segment_update_parser.parse_args()
  234. updated_segment = SegmentService.update_segment(
  235. SegmentUpdateArgs(**args["segment"]), segment, document, dataset
  236. )
  237. return {"data": marshal(updated_segment, segment_fields), "doc_form": document.doc_form}, 200
  238. @service_api_ns.doc("get_segment")
  239. @service_api_ns.doc(description="Get a specific segment by ID")
  240. @service_api_ns.doc(
  241. responses={
  242. 200: "Segment retrieved successfully",
  243. 401: "Unauthorized - invalid API token",
  244. 404: "Dataset, document, or segment not found",
  245. }
  246. )
  247. def get(self, tenant_id: str, dataset_id: str, document_id: str, segment_id: str):
  248. # check dataset
  249. dataset = db.session.query(Dataset).where(Dataset.tenant_id == tenant_id, Dataset.id == dataset_id).first()
  250. if not dataset:
  251. raise NotFound("Dataset not found.")
  252. # check user's model setting
  253. DatasetService.check_dataset_model_setting(dataset)
  254. # check document
  255. document = DocumentService.get_document(dataset_id, document_id)
  256. if not document:
  257. raise NotFound("Document not found.")
  258. # check segment
  259. segment = SegmentService.get_segment_by_id(segment_id=segment_id, tenant_id=current_user.current_tenant_id)
  260. if not segment:
  261. raise NotFound("Segment not found.")
  262. return {"data": marshal(segment, segment_fields), "doc_form": document.doc_form}, 200
  263. @service_api_ns.route(
  264. "/datasets/<uuid:dataset_id>/documents/<uuid:document_id>/segments/<uuid:segment_id>/child_chunks"
  265. )
  266. class ChildChunkApi(DatasetApiResource):
  267. """Resource for child chunks."""
  268. @service_api_ns.expect(child_chunk_create_parser)
  269. @service_api_ns.doc("create_child_chunk")
  270. @service_api_ns.doc(description="Create a new child chunk for a segment")
  271. @service_api_ns.doc(
  272. params={"dataset_id": "Dataset ID", "document_id": "Document ID", "segment_id": "Parent segment ID"}
  273. )
  274. @service_api_ns.doc(
  275. responses={
  276. 200: "Child chunk created successfully",
  277. 401: "Unauthorized - invalid API token",
  278. 404: "Dataset, document, or segment not found",
  279. }
  280. )
  281. @cloud_edition_billing_resource_check("vector_space", "dataset")
  282. @cloud_edition_billing_knowledge_limit_check("add_segment", "dataset")
  283. @cloud_edition_billing_rate_limit_check("knowledge", "dataset")
  284. def post(self, tenant_id: str, dataset_id: str, document_id: str, segment_id: str):
  285. """Create child chunk."""
  286. # check dataset
  287. dataset = db.session.query(Dataset).where(Dataset.tenant_id == tenant_id, Dataset.id == dataset_id).first()
  288. if not dataset:
  289. raise NotFound("Dataset not found.")
  290. # check document
  291. document = DocumentService.get_document(dataset.id, document_id)
  292. if not document:
  293. raise NotFound("Document not found.")
  294. # check segment
  295. segment = SegmentService.get_segment_by_id(segment_id=segment_id, tenant_id=current_user.current_tenant_id)
  296. if not segment:
  297. raise NotFound("Segment not found.")
  298. # check embedding model setting
  299. if dataset.indexing_technique == "high_quality":
  300. try:
  301. model_manager = ModelManager()
  302. model_manager.get_model_instance(
  303. tenant_id=current_user.current_tenant_id,
  304. provider=dataset.embedding_model_provider,
  305. model_type=ModelType.TEXT_EMBEDDING,
  306. model=dataset.embedding_model,
  307. )
  308. except LLMBadRequestError:
  309. raise ProviderNotInitializeError(
  310. "No Embedding Model available. Please configure a valid provider in the Settings -> Model Provider."
  311. )
  312. except ProviderTokenNotInitError as ex:
  313. raise ProviderNotInitializeError(ex.description)
  314. # validate args
  315. args = child_chunk_create_parser.parse_args()
  316. try:
  317. child_chunk = SegmentService.create_child_chunk(args["content"], segment, document, dataset)
  318. except ChildChunkIndexingServiceError as e:
  319. raise ChildChunkIndexingError(str(e))
  320. return {"data": marshal(child_chunk, child_chunk_fields)}, 200
  321. @service_api_ns.expect(child_chunk_list_parser)
  322. @service_api_ns.doc("list_child_chunks")
  323. @service_api_ns.doc(description="List child chunks for a segment")
  324. @service_api_ns.doc(
  325. params={"dataset_id": "Dataset ID", "document_id": "Document ID", "segment_id": "Parent segment ID"}
  326. )
  327. @service_api_ns.doc(
  328. responses={
  329. 200: "Child chunks retrieved successfully",
  330. 401: "Unauthorized - invalid API token",
  331. 404: "Dataset, document, or segment not found",
  332. }
  333. )
  334. def get(self, tenant_id: str, dataset_id: str, document_id: str, segment_id: str):
  335. """Get child chunks."""
  336. # check dataset
  337. dataset = db.session.query(Dataset).where(Dataset.tenant_id == tenant_id, Dataset.id == dataset_id).first()
  338. if not dataset:
  339. raise NotFound("Dataset not found.")
  340. # check document
  341. document = DocumentService.get_document(dataset.id, document_id)
  342. if not document:
  343. raise NotFound("Document not found.")
  344. # check segment
  345. segment = SegmentService.get_segment_by_id(segment_id=segment_id, tenant_id=current_user.current_tenant_id)
  346. if not segment:
  347. raise NotFound("Segment not found.")
  348. args = child_chunk_list_parser.parse_args()
  349. page = args["page"]
  350. limit = min(args["limit"], 100)
  351. keyword = args["keyword"]
  352. child_chunks = SegmentService.get_child_chunks(segment_id, document_id, dataset_id, page, limit, keyword)
  353. return {
  354. "data": marshal(child_chunks.items, child_chunk_fields),
  355. "total": child_chunks.total,
  356. "total_pages": child_chunks.pages,
  357. "page": page,
  358. "limit": limit,
  359. }, 200
  360. @service_api_ns.route(
  361. "/datasets/<uuid:dataset_id>/documents/<uuid:document_id>/segments/<uuid:segment_id>/child_chunks/<uuid:child_chunk_id>"
  362. )
  363. class DatasetChildChunkApi(DatasetApiResource):
  364. """Resource for updating child chunks."""
  365. @service_api_ns.doc("delete_child_chunk")
  366. @service_api_ns.doc(description="Delete a specific child chunk")
  367. @service_api_ns.doc(
  368. params={
  369. "dataset_id": "Dataset ID",
  370. "document_id": "Document ID",
  371. "segment_id": "Parent segment ID",
  372. "child_chunk_id": "Child chunk ID to delete",
  373. }
  374. )
  375. @service_api_ns.doc(
  376. responses={
  377. 204: "Child chunk deleted successfully",
  378. 401: "Unauthorized - invalid API token",
  379. 404: "Dataset, document, segment, or child chunk not found",
  380. }
  381. )
  382. @cloud_edition_billing_knowledge_limit_check("add_segment", "dataset")
  383. @cloud_edition_billing_rate_limit_check("knowledge", "dataset")
  384. def delete(self, tenant_id: str, dataset_id: str, document_id: str, segment_id: str, child_chunk_id: str):
  385. """Delete child chunk."""
  386. # check dataset
  387. dataset = db.session.query(Dataset).where(Dataset.tenant_id == tenant_id, Dataset.id == dataset_id).first()
  388. if not dataset:
  389. raise NotFound("Dataset not found.")
  390. # check document
  391. document = DocumentService.get_document(dataset.id, document_id)
  392. if not document:
  393. raise NotFound("Document not found.")
  394. # check segment
  395. segment = SegmentService.get_segment_by_id(segment_id=segment_id, tenant_id=current_user.current_tenant_id)
  396. if not segment:
  397. raise NotFound("Segment not found.")
  398. # validate segment belongs to the specified document
  399. if str(segment.document_id) != str(document_id):
  400. raise NotFound("Document not found.")
  401. # check child chunk
  402. child_chunk = SegmentService.get_child_chunk_by_id(
  403. child_chunk_id=child_chunk_id, tenant_id=current_user.current_tenant_id
  404. )
  405. if not child_chunk:
  406. raise NotFound("Child chunk not found.")
  407. # validate child chunk belongs to the specified segment
  408. if str(child_chunk.segment_id) != str(segment.id):
  409. raise NotFound("Child chunk not found.")
  410. try:
  411. SegmentService.delete_child_chunk(child_chunk, dataset)
  412. except ChildChunkDeleteIndexServiceError as e:
  413. raise ChildChunkDeleteIndexError(str(e))
  414. return 204
  415. @service_api_ns.expect(child_chunk_update_parser)
  416. @service_api_ns.doc("update_child_chunk")
  417. @service_api_ns.doc(description="Update a specific child chunk")
  418. @service_api_ns.doc(
  419. params={
  420. "dataset_id": "Dataset ID",
  421. "document_id": "Document ID",
  422. "segment_id": "Parent segment ID",
  423. "child_chunk_id": "Child chunk ID to update",
  424. }
  425. )
  426. @service_api_ns.doc(
  427. responses={
  428. 200: "Child chunk updated successfully",
  429. 401: "Unauthorized - invalid API token",
  430. 404: "Dataset, document, segment, or child chunk not found",
  431. }
  432. )
  433. @cloud_edition_billing_resource_check("vector_space", "dataset")
  434. @cloud_edition_billing_knowledge_limit_check("add_segment", "dataset")
  435. @cloud_edition_billing_rate_limit_check("knowledge", "dataset")
  436. def patch(self, tenant_id: str, dataset_id: str, document_id: str, segment_id: str, child_chunk_id: str):
  437. """Update child chunk."""
  438. # check dataset
  439. dataset = db.session.query(Dataset).where(Dataset.tenant_id == tenant_id, Dataset.id == dataset_id).first()
  440. if not dataset:
  441. raise NotFound("Dataset not found.")
  442. # get document
  443. document = DocumentService.get_document(dataset_id, document_id)
  444. if not document:
  445. raise NotFound("Document not found.")
  446. # get segment
  447. segment = SegmentService.get_segment_by_id(segment_id=segment_id, tenant_id=current_user.current_tenant_id)
  448. if not segment:
  449. raise NotFound("Segment not found.")
  450. # validate segment belongs to the specified document
  451. if str(segment.document_id) != str(document_id):
  452. raise NotFound("Segment not found.")
  453. # get child chunk
  454. child_chunk = SegmentService.get_child_chunk_by_id(
  455. child_chunk_id=child_chunk_id, tenant_id=current_user.current_tenant_id
  456. )
  457. if not child_chunk:
  458. raise NotFound("Child chunk not found.")
  459. # validate child chunk belongs to the specified segment
  460. if str(child_chunk.segment_id) != str(segment.id):
  461. raise NotFound("Child chunk not found.")
  462. # validate args
  463. args = child_chunk_update_parser.parse_args()
  464. try:
  465. child_chunk = SegmentService.update_child_chunk(args["content"], child_chunk, segment, document, dataset)
  466. except ChildChunkIndexingServiceError as e:
  467. raise ChildChunkIndexingError(str(e))
  468. return {"data": marshal(child_chunk, child_chunk_fields)}, 200