mirror of
https://github.com/langgenius/dify.git
synced 2026-10-04 13:47:55 +08:00
refactor(api): establish dataset application boundaries (#41729)
Co-authored-by: Jyong <jyong@dify.ai>
This commit is contained in:
1 parent
c005932db9
commit
a67cd87eb0
417 files changed
+30522
-23751
No files matched your search
@@ -147,7 +147,12 @@ class BaseIndexProcessor(ABC):
|
||||
return character_splitter
|
||||
|
||||
def _get_content_files(
|
||||
self, document: Document, current_user: Account | None = None, *, session: Session
|
||||
self,
|
||||
document: Document,
|
||||
current_user: Account | None = None,
|
||||
*,
|
||||
tenant_id: str,
|
||||
session: Session,
|
||||
) -> list[AttachmentDocument]:
|
||||
"""
|
||||
Get the content files from the document.
|
||||
@@ -185,7 +190,12 @@ class BaseIndexProcessor(ABC):
|
||||
if match:
|
||||
if current_user:
|
||||
tool_file_id = match.group(1)
|
||||
upload_file_id = self._download_tool_file(tool_file_id, current_user, session=session)
|
||||
upload_file_id = self._download_tool_file(
|
||||
tool_file_id,
|
||||
current_user,
|
||||
tenant_id=tenant_id,
|
||||
session=session,
|
||||
)
|
||||
if upload_file_id:
|
||||
upload_file_id_list.append(upload_file_id)
|
||||
continue
|
||||
@@ -208,7 +218,12 @@ class BaseIndexProcessor(ABC):
|
||||
|
||||
# Get unique IDs for database query
|
||||
unique_upload_file_ids = list(set(upload_file_id_list))
|
||||
upload_files = session.scalars(select(UploadFile).where(UploadFile.id.in_(unique_upload_file_ids))).all()
|
||||
upload_files = session.scalars(
|
||||
select(UploadFile).where(
|
||||
UploadFile.tenant_id == tenant_id,
|
||||
UploadFile.id.in_(unique_upload_file_ids),
|
||||
)
|
||||
).all()
|
||||
|
||||
# Create a mapping from ID to UploadFile for quick lookup
|
||||
upload_file_map = {upload_file.id: upload_file for upload_file in upload_files}
|
||||
@@ -314,13 +329,22 @@ class BaseIndexProcessor(ABC):
|
||||
logging.warning("Unexpected error downloading image from %s", image_url, exc_info=True)
|
||||
return None
|
||||
|
||||
def _download_tool_file(self, tool_file_id: str, current_user: Account, *, session: Session) -> str | None:
|
||||
def _download_tool_file(
|
||||
self,
|
||||
tool_file_id: str,
|
||||
current_user: Account,
|
||||
*,
|
||||
tenant_id: str,
|
||||
session: Session,
|
||||
) -> str | None:
|
||||
"""
|
||||
Download the tool file from the ID.
|
||||
"""
|
||||
from services.file_service import FileService
|
||||
|
||||
tool_file = session.get(ToolFile, tool_file_id)
|
||||
tool_file = session.scalar(
|
||||
select(ToolFile).where(ToolFile.id == tool_file_id, ToolFile.tenant_id == tenant_id).limit(1)
|
||||
)
|
||||
if not tool_file:
|
||||
return None
|
||||
blob = storage.load_once(tool_file.file_key)
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import logging
|
||||
import re
|
||||
import uuid
|
||||
from collections.abc import Callable
|
||||
from typing import Any, TypedDict, cast, override
|
||||
|
||||
from sqlalchemy import select
|
||||
@@ -46,7 +47,7 @@ from models.account import Account
|
||||
from models.dataset import Dataset, DatasetProcessRule, DocumentSegment, SegmentAttachmentBinding
|
||||
from models.dataset import Document as DatasetDocument
|
||||
from services.account_service import AccountService
|
||||
from services.summary_index_service import SummaryIndexService
|
||||
from services.knowledge.summaries.adapters import SummaryIndexAdapter
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -113,7 +114,12 @@ class ParagraphIndexProcessor(BaseIndexProcessor):
|
||||
document_node.metadata["doc_id"] = doc_id
|
||||
document_node.metadata["doc_hash"] = hash
|
||||
multimodal_documents = (
|
||||
self._get_content_files(document_node, current_user, session=session)
|
||||
self._get_content_files(
|
||||
document_node,
|
||||
current_user,
|
||||
tenant_id=kwargs["tenant_id"],
|
||||
session=session,
|
||||
)
|
||||
if document_node.metadata
|
||||
else None
|
||||
)
|
||||
@@ -172,10 +178,10 @@ class ParagraphIndexProcessor(BaseIndexProcessor):
|
||||
).all()
|
||||
segment_ids = [segment.id for segment in segments]
|
||||
if segment_ids:
|
||||
SummaryIndexService.delete_summaries_for_segments(dataset, segment_ids, session=session)
|
||||
SummaryIndexAdapter.delete_summaries_for_segments(dataset, segment_ids, session=session)
|
||||
else:
|
||||
# Delete all summaries for the dataset
|
||||
SummaryIndexService.delete_summaries_for_segments(dataset, None, session=session)
|
||||
SummaryIndexAdapter.delete_summaries_for_segments(dataset, None, session=session)
|
||||
|
||||
if dataset.indexing_technique == IndexTechniqueType.HIGH_QUALITY:
|
||||
vector = Vector(dataset, session=session)
|
||||
@@ -204,7 +210,7 @@ class ParagraphIndexProcessor(BaseIndexProcessor):
|
||||
"doc_hash": helper.generate_text_hash(content),
|
||||
}
|
||||
doc = Document(page_content=content, metadata=metadata)
|
||||
attachments = self._get_content_files(doc, session=session)
|
||||
attachments = self._get_content_files(doc, tenant_id=dataset.tenant_id, session=session)
|
||||
if attachments:
|
||||
doc.attachments = attachments
|
||||
all_multimodal_documents.extend(attachments)
|
||||
@@ -240,7 +246,12 @@ class ParagraphIndexProcessor(BaseIndexProcessor):
|
||||
account = AccountService.load_user(document.created_by, account_session)
|
||||
if not account:
|
||||
raise ValueError("Invalid account")
|
||||
doc.attachments = self._get_content_files(doc, current_user=account, session=session)
|
||||
doc.attachments = self._get_content_files(
|
||||
doc,
|
||||
current_user=account,
|
||||
tenant_id=dataset.tenant_id,
|
||||
session=session,
|
||||
)
|
||||
if doc.attachments:
|
||||
all_multimodal_documents.extend(doc.attachments)
|
||||
documents.append(doc)
|
||||
@@ -378,7 +389,6 @@ class ParagraphIndexProcessor(BaseIndexProcessor):
|
||||
return preview_texts
|
||||
|
||||
@staticmethod
|
||||
@with_credit_usage_created_by(CreditUsageCreatedBy.KNOWLEDGE_INDEXING)
|
||||
def generate_summary(
|
||||
tenant_id: str,
|
||||
text: str,
|
||||
@@ -404,6 +414,30 @@ class ParagraphIndexProcessor(BaseIndexProcessor):
|
||||
Returns:
|
||||
Tuple of (summary_content, llm_usage) where llm_usage is LLMUsage object
|
||||
"""
|
||||
|
||||
def load_images() -> list[File]:
|
||||
images = (
|
||||
ParagraphIndexProcessor._extract_images_from_segment_attachments(tenant_id, segment_id, session)
|
||||
if segment_id
|
||||
else []
|
||||
)
|
||||
return images or ParagraphIndexProcessor._extract_images_from_text(tenant_id, text, session)
|
||||
|
||||
return ParagraphIndexProcessor.generate_summary_from_inputs(
|
||||
tenant_id, text, summary_index_setting, document_language=document_language, image_loader=load_images
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
@with_credit_usage_created_by(CreditUsageCreatedBy.KNOWLEDGE_INDEXING)
|
||||
def generate_summary_from_inputs(
|
||||
tenant_id: str,
|
||||
text: str,
|
||||
summary_index_setting: SummaryIndexSettingDict | None,
|
||||
*,
|
||||
document_language: str | None,
|
||||
image_loader: Callable[[], list[File]],
|
||||
) -> tuple[str, LLMUsage]:
|
||||
"""Generate a summary after an explicit loader materializes any required images."""
|
||||
if not summary_index_setting or not summary_index_setting.get("enable"):
|
||||
raise ValueError("summary_index_setting is required and must be enabled to generate summary.")
|
||||
|
||||
@@ -447,15 +481,7 @@ class ParagraphIndexProcessor(BaseIndexProcessor):
|
||||
# Extract images if model supports vision
|
||||
image_files = []
|
||||
if supports_vision:
|
||||
# First, try to get images from SegmentAttachmentBinding (preferred method)
|
||||
if segment_id:
|
||||
image_files = ParagraphIndexProcessor._extract_images_from_segment_attachments(
|
||||
tenant_id, segment_id, session
|
||||
)
|
||||
|
||||
# If no images from attachments, fall back to extracting from text
|
||||
if not image_files:
|
||||
image_files = ParagraphIndexProcessor._extract_images_from_text(tenant_id, text, session)
|
||||
image_files = image_loader()
|
||||
|
||||
# Build prompt messages
|
||||
prompt_messages = []
|
||||
@@ -603,6 +629,7 @@ class ParagraphIndexProcessor(BaseIndexProcessor):
|
||||
.where(
|
||||
SegmentAttachmentBinding.segment_id == segment_id,
|
||||
SegmentAttachmentBinding.tenant_id == tenant_id,
|
||||
UploadFile.tenant_id == tenant_id,
|
||||
)
|
||||
).all()
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ from models.dataset import ChildChunk, Dataset, DatasetProcessRule, DocumentSegm
|
||||
from models.dataset import Document as DatasetDocument
|
||||
from models.enums import ProcessRuleMode
|
||||
from services.account_service import AccountService
|
||||
from services.summary_index_service import SummaryIndexService
|
||||
from services.knowledge.summaries.adapters import SummaryIndexAdapter
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -99,11 +99,16 @@ class ParentChildIndexProcessor(BaseIndexProcessor):
|
||||
page_content = page_content
|
||||
if len(page_content) > 0:
|
||||
document_node.page_content = page_content
|
||||
multimodel_documents = self._get_content_files(document_node, current_user, session=session)
|
||||
multimodel_documents = self._get_content_files(
|
||||
document_node,
|
||||
current_user,
|
||||
tenant_id=kwargs["tenant_id"],
|
||||
session=session,
|
||||
)
|
||||
if multimodel_documents:
|
||||
document_node.attachments = multimodel_documents
|
||||
# parse document to child nodes
|
||||
child_nodes = self._split_child_nodes(
|
||||
child_nodes = self.split_child_nodes(
|
||||
document_node, rules, process_rule.get("mode"), kwargs.get("embedding_model_instance")
|
||||
)
|
||||
document_node.children = child_nodes
|
||||
@@ -112,11 +117,15 @@ class ParentChildIndexProcessor(BaseIndexProcessor):
|
||||
elif rules.parent_mode == ParentMode.FULL_DOC:
|
||||
page_content = "\n".join([document.page_content for document in documents])
|
||||
document = Document(page_content=page_content, metadata=documents[0].metadata)
|
||||
multimodel_documents = self._get_content_files(document, session=session)
|
||||
multimodel_documents = self._get_content_files(
|
||||
document,
|
||||
tenant_id=kwargs["tenant_id"],
|
||||
session=session,
|
||||
)
|
||||
if multimodel_documents:
|
||||
document.attachments = multimodel_documents
|
||||
# parse document to child nodes
|
||||
child_nodes = self._split_child_nodes(
|
||||
child_nodes = self.split_child_nodes(
|
||||
document, rules, process_rule.get("mode"), kwargs.get("embedding_model_instance")
|
||||
)
|
||||
if kwargs.get("preview"):
|
||||
@@ -176,10 +185,10 @@ class ParentChildIndexProcessor(BaseIndexProcessor):
|
||||
).all()
|
||||
segment_ids = [segment.id for segment in segments]
|
||||
if segment_ids:
|
||||
SummaryIndexService.delete_summaries_for_segments(dataset, segment_ids, session=session)
|
||||
SummaryIndexAdapter.delete_summaries_for_segments(dataset, segment_ids, session=session)
|
||||
else:
|
||||
# Delete all summaries for the dataset
|
||||
SummaryIndexService.delete_summaries_for_segments(dataset, None, session=session)
|
||||
SummaryIndexAdapter.delete_summaries_for_segments(dataset, None, session=session)
|
||||
|
||||
if dataset.indexing_technique == IndexTechniqueType.HIGH_QUALITY:
|
||||
delete_child_chunks = kwargs.get("delete_child_chunks") or False
|
||||
@@ -227,7 +236,7 @@ class ParentChildIndexProcessor(BaseIndexProcessor):
|
||||
)
|
||||
session.flush()
|
||||
|
||||
def _split_child_nodes(
|
||||
def split_child_nodes(
|
||||
self,
|
||||
document_node: Document,
|
||||
rules: Rule,
|
||||
@@ -302,7 +311,12 @@ class ParentChildIndexProcessor(BaseIndexProcessor):
|
||||
account = AccountService.load_user(document.created_by, account_session)
|
||||
if not account:
|
||||
raise ValueError("Invalid account")
|
||||
doc.attachments = self._get_content_files(doc, current_user=account, session=session)
|
||||
doc.attachments = self._get_content_files(
|
||||
doc,
|
||||
current_user=account,
|
||||
tenant_id=dataset.tenant_id,
|
||||
session=session,
|
||||
)
|
||||
documents.append(doc)
|
||||
if documents:
|
||||
token_counts = calculate_segment_token_counts(dataset=dataset, documents=documents)
|
||||
|
||||
@@ -29,7 +29,7 @@ from libs import helper
|
||||
from models.account import Account
|
||||
from models.dataset import Dataset, DocumentSegment
|
||||
from models.dataset import Document as DatasetDocument
|
||||
from services.summary_index_service import SummaryIndexService
|
||||
from services.knowledge.summaries.adapters import SummaryIndexAdapter
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -180,10 +180,10 @@ class QAIndexProcessor(BaseIndexProcessor):
|
||||
).all()
|
||||
segment_ids = [segment.id for segment in segments]
|
||||
if segment_ids:
|
||||
SummaryIndexService.delete_summaries_for_segments(dataset, segment_ids, session=session)
|
||||
SummaryIndexAdapter.delete_summaries_for_segments(dataset, segment_ids, session=session)
|
||||
else:
|
||||
# Delete all summaries for the dataset
|
||||
SummaryIndexService.delete_summaries_for_segments(dataset, None, session=session)
|
||||
SummaryIndexAdapter.delete_summaries_for_segments(dataset, None, session=session)
|
||||
|
||||
vector = Vector(dataset, session=session)
|
||||
if node_ids:
|
||||
|
||||
Reference in new issue
Block a user