+42









Yeuoly
GitHub
kurokobo
Hiroshi Fujita
NFish
Gen Sato
eux
huangzhuo1949
huangzhuo
lotsik
crazywoola
Wu Tianwei
nite-knite
Jyong
github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
gakkiyomi
CN-P5
CN-P5
Chuehnone
yihong
Kevin9703
-LAN-
Boris Feld
mbo
mabo
Warren Chen
KVOJJJin
JzoNgKVO
jiandanfeng
zhu-an
zhaoqingyu.1075
海狸大師
Xu Song
rayshaw001
Ding Jiatong
Bowen Liang
JasonVV
le0zh
zhuxinliang
k-zaku
Joel
luckylhb90
hobo.l
jiangbo721
刘江波
Shun Miyazawa
EricPan
crazywoola
zxhlyh
sino
Jhvcc
lowell
899df30bf6
Signed-off-by: yihong0618 <[email protected]> Signed-off-by: -LAN- <[email protected]> Co-authored-by: kurokobo <[email protected]> Co-authored-by: Hiroshi Fujita <[email protected]> Co-authored-by: NFish <[email protected]> Co-authored-by: Gen Sato <[email protected]> Co-authored-by: eux <[email protected]> Co-authored-by: huangzhuo1949 <[email protected]> Co-authored-by: huangzhuo <[email protected]> Co-authored-by: lotsik <[email protected]> Co-authored-by: crazywoola <[email protected]> Co-authored-by: Wu Tianwei <[email protected]> Co-authored-by: nite-knite <[email protected]> Co-authored-by: Jyong <[email protected]> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: gakkiyomi <[email protected]> Co-authored-by: CN-P5 <[email protected]> Co-authored-by: CN-P5 <[email protected]> Co-authored-by: Chuehnone <[email protected]> Co-authored-by: yihong <[email protected]> Co-authored-by: Kevin9703 <[email protected]> Co-authored-by: -LAN- <[email protected]> Co-authored-by: Boris Feld <[email protected]> Co-authored-by: mbo <[email protected]> Co-authored-by: mabo <[email protected]> Co-authored-by: Warren Chen <[email protected]> Co-authored-by: KVOJJJin <[email protected]> Co-authored-by: JzoNgKVO <[email protected]> Co-authored-by: jiandanfeng <[email protected]> Co-authored-by: zhu-an <[email protected]> Co-authored-by: zhaoqingyu.1075 <[email protected]> Co-authored-by: 海狸大師 <[email protected]> Co-authored-by: Xu Song <[email protected]> Co-authored-by: rayshaw001 <[email protected]> Co-authored-by: Ding Jiatong <[email protected]> Co-authored-by: Bowen Liang <[email protected]> Co-authored-by: JasonVV <[email protected]> Co-authored-by: le0zh <[email protected]> Co-authored-by: zhuxinliang <[email protected]> Co-authored-by: k-zaku <[email protected]> Co-authored-by: Joel <[email protected]> Co-authored-by: luckylhb90 <[email protected]> Co-authored-by: hobo.l <[email protected]> Co-authored-by: jiangbo721 <[email protected]> Co-authored-by: 刘江波 <[email protected]> Co-authored-by: Shun Miyazawa <[email protected]> Co-authored-by: EricPan <[email protected]> Co-authored-by: crazywoola <[email protected]> Co-authored-by: zxhlyh <[email protected]> Co-authored-by: sino <[email protected]> Co-authored-by: Jhvcc <[email protected]> Co-authored-by: lowell <[email protected]>
202 lines
9.1 KiB
Python
202 lines
9.1 KiB
Python
from flask_login import current_user # type: ignore
|
|
from flask_restful import marshal, reqparse # type: ignore
|
|
from werkzeug.exceptions import NotFound
|
|
|
|
from controllers.service_api import api
|
|
from controllers.service_api.app.error import ProviderNotInitializeError
|
|
from controllers.service_api.wraps import (
|
|
DatasetApiResource,
|
|
cloud_edition_billing_knowledge_limit_check,
|
|
cloud_edition_billing_resource_check,
|
|
)
|
|
from core.errors.error import LLMBadRequestError, ProviderTokenNotInitError
|
|
from core.model_manager import ModelManager
|
|
from core.model_runtime.entities.model_entities import ModelType
|
|
from extensions.ext_database import db
|
|
from fields.segment_fields import segment_fields
|
|
from models.dataset import Dataset, DocumentSegment
|
|
from services.dataset_service import DatasetService, DocumentService, SegmentService
|
|
from services.entities.knowledge_entities.knowledge_entities import SegmentUpdateArgs
|
|
|
|
|
|
class SegmentApi(DatasetApiResource):
|
|
"""Resource for segments."""
|
|
|
|
@cloud_edition_billing_resource_check("vector_space", "dataset")
|
|
@cloud_edition_billing_knowledge_limit_check("add_segment", "dataset")
|
|
def post(self, tenant_id, dataset_id, document_id):
|
|
"""Create single segment."""
|
|
# check dataset
|
|
dataset_id = str(dataset_id)
|
|
tenant_id = str(tenant_id)
|
|
dataset = db.session.query(Dataset).filter(Dataset.tenant_id == tenant_id, Dataset.id == dataset_id).first()
|
|
if not dataset:
|
|
raise NotFound("Dataset not found.")
|
|
# check document
|
|
document_id = str(document_id)
|
|
document = DocumentService.get_document(dataset.id, document_id)
|
|
if not document:
|
|
raise NotFound("Document not found.")
|
|
if document.indexing_status != "completed":
|
|
raise NotFound("Document is not completed.")
|
|
if not document.enabled:
|
|
raise NotFound("Document is disabled.")
|
|
# check embedding model setting
|
|
if dataset.indexing_technique == "high_quality":
|
|
try:
|
|
model_manager = ModelManager()
|
|
model_manager.get_model_instance(
|
|
tenant_id=current_user.current_tenant_id,
|
|
provider=dataset.embedding_model_provider,
|
|
model_type=ModelType.TEXT_EMBEDDING,
|
|
model=dataset.embedding_model,
|
|
)
|
|
except LLMBadRequestError:
|
|
raise ProviderNotInitializeError(
|
|
"No Embedding Model available. Please configure a valid provider in the Settings -> Model Provider."
|
|
)
|
|
except ProviderTokenNotInitError as ex:
|
|
raise ProviderNotInitializeError(ex.description)
|
|
# validate args
|
|
parser = reqparse.RequestParser()
|
|
parser.add_argument("segments", type=list, required=False, nullable=True, location="json")
|
|
args = parser.parse_args()
|
|
if args["segments"] is not None:
|
|
for args_item in args["segments"]:
|
|
SegmentService.segment_create_args_validate(args_item, document)
|
|
segments = SegmentService.multi_create_segment(args["segments"], document, dataset)
|
|
return {"data": marshal(segments, segment_fields), "doc_form": document.doc_form}, 200
|
|
else:
|
|
return {"error": "Segments is required"}, 400
|
|
|
|
def get(self, tenant_id, dataset_id, document_id):
|
|
"""Create single segment."""
|
|
# check dataset
|
|
dataset_id = str(dataset_id)
|
|
tenant_id = str(tenant_id)
|
|
dataset = db.session.query(Dataset).filter(Dataset.tenant_id == tenant_id, Dataset.id == dataset_id).first()
|
|
if not dataset:
|
|
raise NotFound("Dataset not found.")
|
|
# check document
|
|
document_id = str(document_id)
|
|
document = DocumentService.get_document(dataset.id, document_id)
|
|
if not document:
|
|
raise NotFound("Document not found.")
|
|
# check embedding model setting
|
|
if dataset.indexing_technique == "high_quality":
|
|
try:
|
|
model_manager = ModelManager()
|
|
model_manager.get_model_instance(
|
|
tenant_id=current_user.current_tenant_id,
|
|
provider=dataset.embedding_model_provider,
|
|
model_type=ModelType.TEXT_EMBEDDING,
|
|
model=dataset.embedding_model,
|
|
)
|
|
except LLMBadRequestError:
|
|
raise ProviderNotInitializeError(
|
|
"No Embedding Model available. Please configure a valid provider in the Settings -> Model Provider."
|
|
)
|
|
except ProviderTokenNotInitError as ex:
|
|
raise ProviderNotInitializeError(ex.description)
|
|
|
|
parser = reqparse.RequestParser()
|
|
parser.add_argument("status", type=str, action="append", default=[], location="args")
|
|
parser.add_argument("keyword", type=str, default=None, location="args")
|
|
args = parser.parse_args()
|
|
|
|
status_list = args["status"]
|
|
keyword = args["keyword"]
|
|
|
|
query = DocumentSegment.query.filter(
|
|
DocumentSegment.document_id == str(document_id), DocumentSegment.tenant_id == current_user.current_tenant_id
|
|
)
|
|
|
|
if status_list:
|
|
query = query.filter(DocumentSegment.status.in_(status_list))
|
|
|
|
if keyword:
|
|
query = query.where(DocumentSegment.content.ilike(f"%{keyword}%"))
|
|
|
|
total = query.count()
|
|
segments = query.order_by(DocumentSegment.position).all()
|
|
return {"data": marshal(segments, segment_fields), "doc_form": document.doc_form, "total": total}, 200
|
|
|
|
|
|
class DatasetSegmentApi(DatasetApiResource):
|
|
def delete(self, tenant_id, dataset_id, document_id, segment_id):
|
|
# check dataset
|
|
dataset_id = str(dataset_id)
|
|
tenant_id = str(tenant_id)
|
|
dataset = db.session.query(Dataset).filter(Dataset.tenant_id == tenant_id, Dataset.id == dataset_id).first()
|
|
if not dataset:
|
|
raise NotFound("Dataset not found.")
|
|
# check user's model setting
|
|
DatasetService.check_dataset_model_setting(dataset)
|
|
# check document
|
|
document_id = str(document_id)
|
|
document = DocumentService.get_document(dataset_id, document_id)
|
|
if not document:
|
|
raise NotFound("Document not found.")
|
|
# check segment
|
|
segment = DocumentSegment.query.filter(
|
|
DocumentSegment.id == str(segment_id), DocumentSegment.tenant_id == current_user.current_tenant_id
|
|
).first()
|
|
if not segment:
|
|
raise NotFound("Segment not found.")
|
|
SegmentService.delete_segment(segment, document, dataset)
|
|
return {"result": "success"}, 200
|
|
|
|
@cloud_edition_billing_resource_check("vector_space", "dataset")
|
|
def post(self, tenant_id, dataset_id, document_id, segment_id):
|
|
# check dataset
|
|
dataset_id = str(dataset_id)
|
|
tenant_id = str(tenant_id)
|
|
dataset = db.session.query(Dataset).filter(Dataset.tenant_id == tenant_id, Dataset.id == dataset_id).first()
|
|
if not dataset:
|
|
raise NotFound("Dataset not found.")
|
|
# check user's model setting
|
|
DatasetService.check_dataset_model_setting(dataset)
|
|
# check document
|
|
document_id = str(document_id)
|
|
document = DocumentService.get_document(dataset_id, document_id)
|
|
if not document:
|
|
raise NotFound("Document not found.")
|
|
if dataset.indexing_technique == "high_quality":
|
|
# check embedding model setting
|
|
try:
|
|
model_manager = ModelManager()
|
|
model_manager.get_model_instance(
|
|
tenant_id=current_user.current_tenant_id,
|
|
provider=dataset.embedding_model_provider,
|
|
model_type=ModelType.TEXT_EMBEDDING,
|
|
model=dataset.embedding_model,
|
|
)
|
|
except LLMBadRequestError:
|
|
raise ProviderNotInitializeError(
|
|
"No Embedding Model available. Please configure a valid provider in the Settings -> Model Provider."
|
|
)
|
|
except ProviderTokenNotInitError as ex:
|
|
raise ProviderNotInitializeError(ex.description)
|
|
# check segment
|
|
segment_id = str(segment_id)
|
|
segment = DocumentSegment.query.filter(
|
|
DocumentSegment.id == str(segment_id), DocumentSegment.tenant_id == current_user.current_tenant_id
|
|
).first()
|
|
if not segment:
|
|
raise NotFound("Segment not found.")
|
|
|
|
# validate args
|
|
parser = reqparse.RequestParser()
|
|
parser.add_argument("segment", type=dict, required=False, nullable=True, location="json")
|
|
args = parser.parse_args()
|
|
|
|
SegmentService.segment_create_args_validate(args["segment"], document)
|
|
segment = SegmentService.update_segment(SegmentUpdateArgs(**args["segment"]), segment, document, dataset)
|
|
return {"data": marshal(segment, segment_fields), "doc_form": document.doc_form}, 200
|
|
|
|
|
|
api.add_resource(SegmentApi, "/datasets/<uuid:dataset_id>/documents/<uuid:document_id>/segments")
|
|
api.add_resource(
|
|
DatasetSegmentApi, "/datasets/<uuid:dataset_id>/documents/<uuid:document_id>/segments/<uuid:segment_id>"
|
|
)
|