Dify知识库-RAG流程解析

【Dify】RAG开源框架Dify:技术深度剖析与实践指南 Dify作为一个开源的RAG框架,凭借其强大的数据集管理功能、可视化的Prompt编排、高效的RAG管道、灵活的Agent功能以及多种大型语言模型的支持,为开发者提供了一个快速搭建生产级AI应用的平台。无论是对于技术人员还是非技术人员来说,Dify都大大降低了AI应用开发的复杂度,使得更多人能够参与到AI应用的开发和创新中来。未来,随着技术的不断进步和应用场景的不断拓展,Dify有望在人工智能领域发挥更加重要的作用。例如,通过引入更多的自然语言理解和生成技术,Dify可以进一步提升其问答和文本生成的能力。 阅读详情
AI摘要

本文对Dify知识库RAG流程进行解析。先介绍了document_indexing_task,包括查询文章限制及更新状态,还涉及IndexingRunner.run()的实现细节。接着详细阐述了提取文本、转化数据切片、存储片段和索引中间件加载等步骤,如不同类的具体调用和方法实现。

Dify知识库RAG代码流程图

源码解析
document_indexing_task

代码目录:dify/api/tasks/document_indexing_task.py

主要做了以下两件事

1.查询dataset的文章限制是否超出限制,超出抛出异常,将所有document_ids状态改为 error 如果正 常,则更新所有文章状态为 “解析中” parsing

@shared_task(queue='dataset')
def document_indexing_task(dataset_id: str, document_ids: list):
    """
    异步处理文档索引任务。
    :param dataset_id:数据集ID
    :param document_ids:需要处理的文档ID列表

    Usage: document_indexing_task.delay(dataset_id, document_id)
    主要功能:1.查询dataset的文章限制是否超出 入宫超出抛出异常,将所有document_ids状态改为 error 如果正常,则更新所有文章状态为 “解析中” parsing
    2.IndexingRunner.run()中包含了RAG索引的实现细节
    """


    # 初始化文档列表和开始时间
    documents = []
    start_at = time.perf_counter()
    # 从数据库中获取数据集信息
    dataset = db.session.query(Dataset).filter(Dataset.id == dataset_id).first()

    # 检查文档数量限制
    features = FeatureService.get_features(dataset.tenant_id)
    try:
        if features.billing.enabled:
            # 获取向量空间信息
            vector_space = features.vector_space
            count = len(document_ids)
            # 批量上传限制
            batch_upload_limit = int(dify_config.BATCH_UPLOAD_LIMIT)
            if count > batch_upload_limit:
                raise ValueError(f"You have reached the batch upload limit of {batch_upload_limit}.")

            # 检查是否超过订阅限制
            if 0 < vector_space.limit <= vector_space.size:
                raise ValueError("Your total number of documents plus the number of uploads have over the limit of "
                                 "your subscription.")
    except Exception as e:
        # 如果有异常,更新所有相关文档的状态为错误,并记录异常信息
        for document_id in document_ids:
            document = db.session.query(Document).filter(
                Document.id == document_id,
                Document.dataset_id == dataset_id
            ).first()
            if document:
                document.indexing_status = 'error'
                document.error = str(e)
                document.stopped_at = datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)
                db.session.add(document)
        db.session.commit()
        return
    # 更新文档状态为解析中,并添加到处理列表
    for document_id in document_ids:
        logging.info(click.style('Start process document: {}'.format(document_id), fg='green'))

        document = db.session.query(Document).filter(
            Document.id == document_id,
            Document.dataset_id == dataset_id
        ).first()

        if document:
            document.indexing_status = 'parsing'
            document.processing_started_at = datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)
            documents.append(document)
            db.session.add(document)
    db.session.commit()
    #......

2.IndexingRunner.run()中包含了RAG索引的实现细节

@shared_task(queue='dataset')
def document_indexing_task(dataset_id: str, document_ids: list):
    """
    异步处理文档索引任务。
    :param dataset_id:数据集ID
    :param document_ids:需要处理的文档ID列表

    Usage: document_indexing_task.delay(dataset_id, document_id)
    主要功能:1.查询dataset的文章限制是否超出 入宫超出抛出异常,将所有document_ids状态改为 error 如果正常,则更新所有文章状态为 “解析中” parsing
    2.IndexingRunner.run()中包含了RAG索引的实现细节
    """
    #......
    # 尝试运行索引处理
    try:
        # RAG索引的实现细节
        indexing_runner = IndexingRunner()
        indexing_runner.run(documents)
        end_at = time.perf_counter()
        logging.info(click.style('Processed dataset: {} latency: {}'.format(dataset_id, end_at - start_at), fg='green'))
    except DocumentIsPausedException as ex:
        # 如果文档被暂停,记录信息
        logging.info(click.style(str(ex), fg='yellow'))
    except Exception:
        pass
IndexingRunner

代码目录:dify/api/core/indexing_runner.py

run() 该函数主要做了以下三件事

1.提取文本

2.转化数据切片

3.将切片后的文本 构造 document_segment 入库

4.索引中间件加载

def run(self, dataset_documents: list[DatasetDocument]):
    """Run the indexing process."""
    """
    运行索引过程,对每个提供的数据集文档进行处理。
    """
    for dataset_document in dataset_documents:
        try:
            # get dataset
            dataset = Dataset.query.filter_by(
                id=dataset_document.dataset_id
            ).first()

            if not dataset:
                raise ValueError("no dataset found")

            # 获取处理规则
            processing_rule = db.session.query(DatasetProcessRule). \
                filter(DatasetProcessRule.id == dataset_document.dataset_process_rule_id). \
                first()
            index_type = dataset_document.doc_form  # 文档的形式,用于确定索引处理器类型
            index_processor = IndexProcessorFactory(index_type).init_index_processor()  # 创建索引处理器实例
            # 提取文本数据
            text_docs = self._extract(index_processor, dataset_document, processing_rule.to_dict())
            # print('提取文本数据', text_docs)
            # 转换数据
            documents = self._transform(index_processor, dataset, text_docs, dataset_document.doc_language,
                                        processing_rule.to_dict())
            # print('转换数据', documents)
            # 保存片段 将最终切片后的 chunks 构造 document_segment 入库
            self._load_segments(dataset, dataset_document, documents)

            # load
            self._load(
                index_processor=index_processor,
                dataset=dataset,
                dataset_document=dataset_document,
                documents=documents
            )
        except DocumentIsPausedException:
            # 如果文档被暂停,抛出异常
            raise DocumentIsPausedException('Document paused, document id: {}'.format(dataset_document.id))
        except ProviderTokenNotInitError as e:
            # 如果提供商令牌未初始化,更新文档状态并提交更改
            dataset_document.indexing_status = 'error'
            dataset_document.error = str(e.description)
            dataset_document.stopped_at = datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)
            db.session.commit()
        except ObjectDeletedError:
            # 如果对象被删除,记录警告日志
            logging.warning('Document deleted, document id: {}'.format(dataset_document.id))
        except Exception as e:  # 对于其他异常,记录异常信息并更新文档状态
            logging.exception("consume document failed")
            dataset_document.indexing_status = 'error'
            dataset_document.error = str(e)
            dataset_document.stopped_at = datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)
            db.session.commit()

提取文本

text_docs = self._extract(index_processor, dataset_document, processing_rule.to_dict())

假如 index_processor根据用户所选为: ParagraphIndexProcessor类,则self._extract调用的实际为ParagraphIndexProcessor.extract

self._extract()

加载数据源,判断数据类型 根据数据类型匹配不同的提取设置,最终调用extract函数

def _extract(self, index_processor: BaseIndexProcessor, dataset_document: DatasetDocument, process_rule: dict) \
        -> list[Document]:
    """
        根据数据源类型提取文档内容。
        :param index_processor: 索引处理器实例
        :param dataset_document: 数据集文档对象
        :param process_rule: 处理规则字典
        :return: 包含提取后文档内容的列表
        这段代码定义了一个名为_extract的方法,用于根据不同的数据源类型(上传文件、Notion导入、网站爬取)提取文档内容。
        它首先检查数据源类型,然后根据类型创建相应的ExtractSetting对象,
        并调用index_processor的extract方法来提取文档。
        之后,它会更新文档的状态为“分割”,计算并更新文档的词数,以及完成解析的时间。
        最后,它会更新提取的文档元数据中的文档ID和数据集ID,以关联到正确的数据集文档。

    """
    # 加载文件,如果数据源类型不是上传文件、Notion导入或网站爬取,则返回空列表
    if dataset_document.data_source_type not in ["upload_file", "notion_import", "website_crawl"]:
        return []

    data_source_info = dataset_document.data_source_info_dict
    text_docs = []  # 初始化文本文档列表
    # 处理上传文件数据源
    if dataset_document.data_source_type == 'upload_file':
        if not data_source_info or 'upload_file_id' not in data_source_info:
            raise ValueError("no upload file found")

        # 查询上传文件详情
        file_detail = db.session.query(UploadFile). \
            filter(UploadFile.id == data_source_info['upload_file_id']). \
            one_or_none()

        if file_detail:
            # 创建提取设置
            extract_setting = ExtractSetting(
                datasource_type="upload_file",
                upload_file=file_detail,
                document_model=dataset_document.doc_form
            )
            # 使用索引处理器提取文档
            text_docs = index_processor.extract(extract_setting, process_rule_mode=process_rule['mode'])
    # 处理Notion导入数据源
    elif dataset_document.data_source_type == 'notion_import':
        if (not data_source_info or 'notion_workspace_id' not in data_source_info
                or 'notion_page_id' not in data_source_info):
            raise ValueError("no notion import info found")
        # 创建提取设置
        extract_setting = ExtractSetting(
            datasource_type="notion_import",
            notion_info={
                "notion_workspace_id": data_source_info['notion_workspace_id'],
                "notion_obj_id": data_source_info['notion_page_id'],
                "notion_page_type": data_source_info['type'],
                "document": dataset_document,
                "tenant_id": dataset_document.tenant_id
            },
            document_model=dataset_document.doc_form
        )
        # 使用索引处理器提取文档
        text_docs = index_processor.extract(extract_setting, process_rule_mode=process_rule['mode'])
    # 处理网站爬取数据源
    elif dataset_document.data_source_type == 'website_crawl':
        if (not data_source_info or 'provider' not in data_source_info
                or 'url' not in data_source_info or 'job_id' not in data_source_info):
            raise ValueError("no website import info found")
        # 创建提取设置
        extract_setting = ExtractSetting(
            datasource_type="website_crawl",
            website_info={
                "provider": data_source_info['provider'],
                "job_id": data_source_info['job_id'],
                "tenant_id": dataset_document.tenant_id,
                "url": data_source_info['url'],
                "mode": data_source_info['mode'],
                "only_main_content": data_source_info['only_main_content']
            },
            document_model=dataset_document.doc_form
        )
        # 使用索引处理器提取文档
        text_docs = index_processor.extract(extract_setting, process_rule_mode=process_rule['mode'])
    # update document status to splitting
    # 更新文档状态为“分割”阶段
    self._update_document_index_status(
        document_id=dataset_document.id,
        after_indexing_status="splitting",
        extra_update_params={
            DatasetDocument.word_count: sum(len(text_doc.page_content) for text_doc in text_docs),
            DatasetDocument.parsing_completed_at: datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)
        }
    )

    ## 替换文档ID为数据集文档模型ID
    text_docs = cast(list[Document], text_docs)  # 类型断言,确保text_docs为Document列表
    for text_doc in text_docs:
        text_doc.metadata['document_id'] = dataset_document.id
        text_doc.metadata['dataset_id'] = dataset_document.dataset_id

    return text_docs

ParagraphIndexProcessor.extract()

代码目录:api/core/rag/index_processor/processor/paragraph_index_processor.py

实际进来调用的是ExtractProcessor这个类的extract。这个类具体编写了所有常见文本格式的提取器的具体实现

class ParagraphIndexProcessor(BaseIndexProcessor):

    def extract(self, extract_setting: ExtractSetting, **kwargs) -> list[Document]:

        text_docs = ExtractProcessor.extract(extract_setting=extract_setting,
                                             is_automatic=kwargs.get('process_rule_mode') == "automatic")

        return text_docs

ExtractProcessor.extract()

代码目录:api/core/rag/extractor/extract_processor.py

根据文件后缀名调用不同的文档解析器提取文档内容,根据不同的文本格式,调用不同的类,去处理文本,最终会返回提取的文本内容

def extract(cls, extract_setting: ExtractSetting, is_automatic: bool = False,
            file_path: str = None) -> list[Document]:
    if extract_setting.datasource_type == DatasourceType.FILE.value:
        with tempfile.TemporaryDirectory() as temp_dir:
            if not file_path:
                upload_file: UploadFile = extract_setting.upload_file
                suffix = Path(upload_file.key).suffix
                file_path = f"{temp_dir}/{next(tempfile._get_candidate_names())}{suffix}"
                storage.download(upload_file.key, file_path)
            input_file = Path(file_path)
            file_extension = input_file.suffix.lower()
            etl_type = current_app.config['ETL_TYPE']
            unstructured_api_url = current_app.config['UNSTRUCTURED_API_URL']
            unstructured_api_key = current_app.config['UNSTRUCTURED_API_KEY']
            if etl_type == 'Unstructured':
                if file_extension == '.xlsx' or file_extension == '.xls':
                    extractor = ExcelExtractor(file_path)
                elif file_extension == '.pdf':
                    extractor = PdfExtractor(file_path)
                elif file_extension in ['.md', '.markdown']:
                    extractor = UnstructuredMarkdownExtractor(file_path, unstructured_api_url) if is_automatic \
                        else MarkdownExtractor(file_path, autodetect_encoding=True)
                elif file_extension in ['.htm', '.html']:
                    extractor = HtmlExtractor(file_path)
                elif file_extension in ['.docx']:
                    extractor = WordExtractor(file_path, upload_file.tenant_id, upload_file.created_by)
                elif file_extension == '.csv':
                    extractor = CSVExtractor(file_path, autodetect_encoding=True)
                elif file_extension == '.msg':
                    extractor = UnstructuredMsgExtractor(file_path, unstructured_api_url)
                elif file_extension == '.eml':
                    extractor = UnstructuredEmailExtractor(file_path, unstructured_api_url)
                elif file_extension == '.ppt':
                    extractor = UnstructuredPPTExtractor(file_path, unstructured_api_url, unstructured_api_key)
                elif file_extension == '.pptx':
                    extractor = UnstructuredPPTXExtractor(file_path, unstructured_api_url)
                elif file_extension == '.xml':
                    extractor = UnstructuredXmlExtractor(file_path, unstructured_api_url)
                elif file_extension == 'epub':
                    extractor = UnstructuredEpubExtractor(file_path, unstructured_api_url)
                else:
                    # txt
                    extractor = UnstructuredTextExtractor(file_path, unstructured_api_url) if is_automatic \
                        else TextExtractor(file_path, autodetect_encoding=True)
            else:
                if file_extension == '.xlsx' or file_extension == '.xls':
                    extractor = ExcelExtractor(file_path)
                elif file_extension == '.pdf':
                    extractor = PdfExtractor(file_path)
                elif file_extension in ['.md', '.markdown']:
                    extractor = MarkdownExtractor(file_path, autodetect_encoding=True)
                elif file_extension in ['.htm', '.html']:
                    extractor = HtmlExtractor(file_path)
                elif file_extension in ['.docx']:
                    extractor = WordExtractor(file_path, upload_file.tenant_id, upload_file.created_by)
                elif file_extension == '.csv':
                    extractor = CSVExtractor(file_path, autodetect_encoding=True)
                elif file_extension == 'epub':
                    extractor = UnstructuredEpubExtractor(file_path)
                else:
                    # txt
                    extractor = TextExtractor(file_path, autodetect_encoding=True)
            return extractor.extract()
    elif extract_setting.datasource_type == DatasourceType.NOTION.value:
        extractor = NotionExtractor(
            notion_workspace_id=extract_setting.notion_info.notion_workspace_id,
            notion_obj_id=extract_setting.notion_info.notion_obj_id,
            notion_page_type=extract_setting.notion_info.notion_page_type,
            document_model=extract_setting.notion_info.document,
            tenant_id=extract_setting.notion_info.tenant_id,
        )
        return extractor.extract()
    elif extract_setting.datasource_type == DatasourceType.WEBSITE.value:
        if extract_setting.website_info.provider == 'firecrawl':
            extractor = FirecrawlWebExtractor(
                url=extract_setting.website_info.url,
                job_id=extract_setting.website_info.job_id,
                tenant_id=extract_setting.website_info.tenant_id,
                mode=extract_setting.website_info.mode,
                only_main_content=extract_setting.website_info.only_main_content
            )
            return extractor.extract()
        else:
            raise ValueError(f"Unsupported website provider: {extract_setting.website_info.provider}")
    else:
        raise ValueError(f"Unsupported datasource type: {extract_setting.datasource_type}")

2.转化数据切片(和提取文本类似)最终会调用ParagraphIndexProcessor.transform

# 转换数据
documents = self._transform(index_processor, dataset, text_docs, dataset_document.doc_language,
                            processing_rule.to_dict())

ParagraphIndexProcessor.transform()

代码目录:api/core/rag/index_processor/processor/paragraph_index_processor.py

将文本文档分割成节点,并对每个节点进行清理和元数据处理。

def transform(self, documents: list[Document], **kwargs) -> list[Document]:
    """
       将文本文档分割成节点,并对每个节点进行清理和元数据处理。

       :param documents: 待处理的文档列表
       :param kwargs: 关键字参数,包括处理规则、嵌入模型实例等
       :return: 处理后的文档节点列表
       这段代码实现了将一系列文档分割成更小的节点,并对这些节点进行清理和元数据处理的功能。
       它首先根据传入的处理规则和嵌入模型实例选择一个适当的文档分割器。
       然后,遍历每个文档,先清理文档内容,再使用分割器将其分割成多个节点。
       对于每个节点,它生成一个唯一的文档ID和内容的哈希值,更新节点的元数据,并清除可能存在的分割符。
       最后,将处理后的文档节点添加到结果列表中并返回。
       """
    #  # 选择文档分割器
    splitter = self._get_splitter(processing_rule=kwargs.get('process_rule'),  # 处理规则
                                  embedding_model_instance=kwargs.get('embedding_model_instance'))# 嵌入模型实例
    all_documents = []  # 初始化所有文档节点列表
    for document in documents: # 遍历每个文档
        # 清理文档内容
        document_text = CleanProcessor.clean(document.page_content, kwargs.get('process_rule'))
        document.page_content = document_text # 更新文档内容
        #  # 将文档分割成节点
        document_nodes = splitter.split_documents([document]) #为文档的切片具体实现
        split_documents = [] # 初始化分割后的文档节点列表
        for document_node in document_nodes: # 遍历每个文档节点

            if document_node.page_content.strip():  # 如果节点内容非空
                # 生成唯一文档ID和哈希值
                doc_id = str(uuid.uuid4())
                hash = helper.generate_text_hash(document_node.page_content)
                # 更新文档节点元数据
                document_node.metadata['doc_id'] = doc_id
                document_node.metadata['doc_hash'] = hash
                # # 清除分割符
                page_content = document_node.page_content
                if page_content.startswith(".") or page_content.startswith("。"):
                    page_content = page_content[1:].strip() # 去除开头的点或句号
                else:
                    page_content = page_content
                if len(page_content) > 0: # 如果处理后的内容长度大于0
                    document_node.page_content = page_content # 更新文档节点内容
                    split_documents.append(document_node)  # 添加到分割文档列表
        all_documents.extend(split_documents) # 将分割后的文档添加到总列表
    return all_documents # 返回处理后的文档节点列表

其中CleanProcessor.clean(document.page_content, kwargs.get('process_rule'))是做了文本清除

splitter.split_documents([document]) 是文档的切片具体实现目录:dify/api/core/splitter

对 text_splitter的分析:

TextSplitter

  • 抽象方法 split_text:这个方法必须在子类中实现。

  • 方法 create_documents、splits_documents、transfer_documents、_merge_splits:这些是TextSplitter类中的具体方法,可以在子类中调用或重写。

RecursiveCharacterTextSplitterSplitter

  • 继承自 TextSplitter。

  • 方法 split_text:这个方法重写了TextSplitter中的抽象方法split_text。

EnhanceRecursiveCharacterTextSplitterSplitter

  • 继承自 RecursiveCharacterTextSplitterSplitter。

  • 类方法 from_encoder:这是一个类方法,可以通过类本身而不是类的实例来调用。

splitter.split_documents([document])最终调用的是RecursiveCharacterTextSplitter._split_text

里面包含了_split_text_with_regex(text, separator, self._keep_separator)去分割字符串

self._merge_splits(_good_splits, _separator)合并短句

class RecursiveCharacterTextSplitter(TextSplitter):
    #......
    def _split_text(self, text: str, separators: list[str]) -> list[str]:
        """
        将输入文本按照给定的分隔符分割成块,并递归地处理过长的文本块。
    
        :param text: 待分割的原始文本
        :param separators: 可选的分隔符列表,用于文本分割
        :return: 分割后的文本块列表
        此段代码实现了一个文本分割算法,主要逻辑如下:
    
        从给定的分隔符列表中选择一个有效的分隔符,用于分割文本。
        使用选定的分隔符将文本分割成多个部分。
        遍历分割后的每一部分,如果部分的长度小于设定的块大小,将其标记为合适的短文本块;否则,如果还有其他分隔符可用,递归地继续分割这部分文本;如果没有其他分隔符,直接将这部分文本作为块添加到最终结果中。
        在每次处理完一个长文本块后,将之前累积的短文本块合并,并添加到最终的文本块列表中。
        最终返回分割后的所有文本块组成的列表。
        """
        """Split incoming text and return chunks."""
        final_chunks = []  # 初始化最终的文本块列表
        # 从separators中选取一个有效的分隔符
        separator = separators[-1]  # 默认使用最后一个分隔符
        new_separators = []  # 初始化新的分隔符列表
        for i, _s in enumerate(separators):
            if _s == "":  # 初始化新的分隔符列表
                separator = _s
                break
            if re.search(_s, text):# 如果当前分隔符在文本中存在
                separator = _s# 使用这个分隔符
                new_separators = separators[i + 1:] # 更新新的分隔符列表
                break
        # 使用选定的分隔符分割文本
        splits = _split_text_with_regex(text, separator, self._keep_separator)
        # # 合并短文本块,递归分割长文本块
        _good_splits = [] # 初始化合适的短文本块列表
        _separator = "" if self._keep_separator else separator # 确定是否保留分隔符
        for s in splits:
            if self._length_function(s) < self._chunk_size:  # 如果文本块长度小于设定的块大小
                _good_splits.append(s) # 将其添加到合适的短文本块列表
            else:
                if _good_splits:  # 如果有合适的短文本块
                    merged_text = self._merge_splits(_good_splits, _separator) # 合并它们
                    final_chunks.extend(merged_text)  # 将合并后的文本块添加到最终的文本块列表
                    _good_splits = [] # 清空短文本块列表
                # 如果没有新的分隔符,直接将当前过长的文本块添加到最终列表
                if not new_separators:
                    final_chunks.append(s)
                else:
                    # 如果有新的分隔符,递归地分割当前过长的文本块
                    other_info = self._split_text(s, new_separators)
                    final_chunks.extend(other_info) # 将递归分割的结果添加到最终列表
        # 最后处理剩余的合适短文本块
        if _good_splits:
            merged_text = self._merge_splits(_good_splits, _separator)
            final_chunks.extend(merged_text)
        return final_chunks

3.存储片段

保存片段 将最终切片后的 chunks 构造 document_segment 入库

self._load_segments(dataset, dataset_document, documents)

代码目录:api/core/indexing_runner.py

def _load_segments(self, dataset, dataset_document, documents):
    # 创建一个DatasetDocumentStore实例,用于存储文档片段
    doc_store = DatasetDocumentStore(
        dataset=dataset,
        user_id=dataset_document.created_by,
        document_id=dataset_document.id
    )

    # 将文档片段添加到文档存储中
    doc_store.add_documents(documents)

    # 获取当前时间,用于记录文档处理的完成时间
    cur_time = datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)
    # 更新文档的状态至“索引中”,并记录文档的清洗和分割完成时间
    self._update_document_index_status(
        document_id=dataset_document.id,
        after_indexing_status="indexing",
        extra_update_params={
            DatasetDocument.cleaning_completed_at: cur_time,
            DatasetDocument.splitting_completed_at: cur_time,
        }
    )

    ## 更新文档片段的状态至“索引中”,并记录片段的索引开始时间
    self._update_segments_by_document(
        dataset_document_id=dataset_document.id,
        update_params={
            DocumentSegment.status: "indexing",
            DocumentSegment.indexing_at: datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None)
        }
    )
    pass

4.索引中间件加载

self._load(
    index_processor=index_processor,
    dataset=dataset,
    dataset_document=dataset_document,
    documents=documents
)
def _load(self, index_processor: BaseIndexProcessor, dataset: Dataset,
          dataset_document: DatasetDocument, documents: list[Document]) -> None:
    """
    插入索引并更新文档/片段状态至已完成。
    """
    # 如果索引技术设置为'high_quality',则获取相应的嵌入模型实例
    embedding_model_instance = None
    if dataset.indexing_technique == 'high_quality':
        embedding_model_instance = self.model_manager.get_model_instance(
            tenant_id=dataset.tenant_id,
            provider=dataset.embedding_model_provider,
            model_type=ModelType.TEXT_EMBEDDING,
            model=dataset.embedding_model
        )

    # 记录索引开始时间
    indexing_start_at = time.perf_counter()
    # 初始化计数器,用于统计处理的token数量
    tokens = 0
    # 设置每次处理的文档块大小
    chunk_size = 10

    # 创建关键词索引的线程
    create_keyword_thread = threading.Thread(target=self._process_keyword_index,
                                             args=(current_app._get_current_object(),
                                                   dataset.id, dataset_document.id, documents))
    create_keyword_thread.start()  # 启动线程
    # 如果索引技术为'high_quality',则并行处理文档块
    if dataset.indexing_technique == 'high_quality':
        with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
            futures = []  # 存储Future对象的列表
            # 将文档列表分割成多个块
            for i in range(0, len(documents), chunk_size):
                chunk_documents = documents[i:i + chunk_size]
                # 提交任务到线程池
                futures.append(
                    executor.submit(self._process_chunk, current_app._get_current_object(), index_processor,
                                    chunk_documents, dataset,
                                    dataset_document, embedding_model_instance))
            # 收集并处理所有Future的结果
            for future in futures:
                tokens += future.result() # 累加处理的token数量
    # 等待关键词索引线程完成
    create_keyword_thread.join()

    # 记录索引结束时间
    indexing_end_at = time.perf_counter()

    # 更新文档状态至已完成
    self._update_document_index_status(
        document_id=dataset_document.id,  # 文档ID
        after_indexing_status="completed", # 更新后的状态
        extra_update_params={ # 额外更新参数
            DatasetDocument.tokens: tokens,  # 处理的token总数
            DatasetDocument.completed_at: datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None), # 完成时间
            DatasetDocument.indexing_latency: indexing_end_at - indexing_start_at, # 索引延迟时间
        }
    )

深入 Dify 源码,洞察 Dify RAG 切片机制实现细节 最近测试时发现 Dify 的 RAG 分片效果一般,不管是使用之前深入 Dify 源码,洞察 Dify RAG 核心机制中有调研过的默认解析还是 Unstructured 解析。因此调研比较了大量的开源框架实现了特定格式的结构化解析方案,并与 Dify 现有解析流程进行了适配。为了保证文件的解析能真正发挥出效果,需要保证预处理中其他环节也遵循前面的结构化方案进行处理,其中重要的一块就是文本的分片机制。深入了解 Dify 的实现细节后整理相关内容在这边,方便对 Dify RAG 实现机制感兴趣的同学。 阅读详情

相关推荐

Dify构建企业级RAG知识库实战指南

RAG(检索增强生成)技术通过结合检索与生成模型,有效解决大模型在私有知识场景下的幻觉问题。其核心原理是将文档向量化后建立索引,在生成阶段动态检索相关知识片段作为上下文。这种技术显著提升回答准确性,特别适合金融、法律等对事实性要求高的领域。Dify作为开源平台提供完整的RAG流水线,支持多模态文档处理和混合检索策略。通过Docker本地化部署,企业可在保障数据安全的前提下,快速构建知识库系统。本文以金融行业为例,详细演示从环境配置到生产运维的全流程实践,涵盖向量化策略调优、混合检索配置等关键环节。

weixin_34015336的博客 538

Dify中的RAG和知识库

向量检索优势:复杂语义的文本查找,相近语义理解,多语言理解,多模态理解,容错性。传统关键词搜索优势:精确匹配,少量字符的匹配,倾向低频词汇的匹配。向量检索和关键词检索在检索领域各有其优势。混合检索通过多个检索系统的组合,实现了多个检索技术之间的互补。

NLP工程化 7845

【Dify(v1.x) 核心源码深入解析】Agent 模块

Agent 模块是 Dify 中负责处理用户请求的核心组件。接收用户输入并解析请求。根据请求内容调用合适的工具或模型。生成响应并返回给用户。管理整个交互流程,包括工具调用、消息处理和状态管理。通过本文的详细解析,我们深入了解了 Dify 的 Agent 模块的架构设计和实现细节。Agent 模块通过灵活的策略、丰富的工具、高效的消息处理和状态管理,为开发者提供了一个强大的 AI 应用开发平台。希望本文能帮助你更好地理解和使用 Dify 的 Agent 模块。更智能的策略。

1593

一文彻底搞懂大模型 - Dify(Agent + RAG)

该平台结合了后端即服务(Backend as Service, BaaS)和LLMOps的理念,为开发者提供了。

m0_59163425的博客 27万+

超越幻觉:Dify 中 RAG 与知识库的深度解析与工程实践

摘要: 大型语言模型(LLM)面临"幻觉"问题,检索增强生成(RAG)通过结合外部知识库提升回答准确性。Dify平台将RAG流程封装为易用的知识库功能,支持文档上传、分块、向量化及检索,并可与AI应用绑定。其核心流程包括:用户提问→向量化检索→结果筛选→增强提示→LLM生成答案。Dify通过可视化配置降低了RAG应用开发门槛,使LLM能基于最新、可靠数据生成回答,适用于客服、金融等专业场景。

reset2021的博客 351

Geant4 案例分析(一): B1

本文是对Geant4 B1的案例分析,其中特定的功能不做介绍,而注重于各个文件的主要功能,以及它们组织的方式。

m0_51809467的博客 1584

Dify+RAG本地知识库搭建:从环境配置到智能问答全流程解析

本文详细解析了如何使用Dify和RAG技术搭建本地知识库,从环境配置到智能问答全流程。通过实战指南,介绍了Dify部署、向量数据库选型、模型对接及知识库优化等关键步骤,帮助开发者高效构建企业级智能问答系统,解决传统知识管理效率低下的问题。

eee77的博客 1024

ESP32-BLE学习1-建立简单的server

start 学习之前,我想尝试使用ESP32的demo建立一个简单的server与手机接进行最基本的数据通信。 这里有BLE的简单讲解BLE资料 因为BLE的连接是具有主从机特性的,就像SPI,USB一些请求只能由主机端发起,连接也需要主机端发起。所以手机要想连上ESP32,就得将ESP32设置为从机模式。 从资料上可以看到,从机端通过Notify通知主机,所以从机就是GATT Server。 在进行ESP32 的demo学习之前,得大体看下ESP32的蓝牙组成,ESP32支持经典蓝牙和低功耗蓝牙4.2,

Spark的博客 1846

Dify 解析-RAG

Dify 是一个流行的开源大模型应用开发平台。其核心理念是 "Do It For You"。Dify 内置了构建 LLM 应用所需的关键技术栈,包括插件、代理/反向代理、数据库/缓存、实验训练和可观测(Open Telemetry)。Dify 通过 RAG 技术,实现了对外部知识的高效利用,极大地提升了大模型生成内容的质量和相关性。RAG 架构中的知识库管理、检索引擎、提示词管理和模型推理服务等组件相互配合,共同构成了一个完整的 RAG 系统。

CCbleach的专栏 3015

Setup&Hold互卡问题和Useful Skew的影响

setup和hold互卡问题分析

godping的博客 5106

SpringBoot3 + Vben5.0实战:从零搭建企业级管理后台(附完整代码)

本文详细介绍了如何从零开始,使用SpringBoot3与Vben5.0技术栈搭建现代化企业级管理后台。通过对比分析,阐述了该组合在开发效率、性能(如虚拟线程)和权限模型(RBAC)方面的优势,并提供了从项目初始化、核心功能开发到部署运维的完整实战指南,帮助开发者快速构建高性能、易维护的后台系统。

weixin_29306317的博客 174

Dify+RAGFlow强强联合打造知识库

就目前而言RAGFlow在知识库方面还是比dify强的,因此如果dify能和ragflow联合使用,那么效果岂不是更强,现在教程来了。文章首发公众号 DataSpeed欢迎关注。

fengjian的博客 3万+

机器学习笔记——30种常见机器学习算法简要汇总

本笔记介绍机器学习中常见的30种机器学习算法。

haopinglianlian的博客 3202

RAG知识库实战:基于Dify构建多端智能问答应用

RAG(检索增强生成)是解决大模型幻觉、知识陈旧与私有数据不可用问题的关键技术,其核心原理并非让模型记住文档,而是在回答前先从知识库检索相关片段,再作为上下文生成答案。这一技术价值已在企业知识库、客服问答等场景中广泛验证。Dify 作为开源 LLMOps 平台,将文档解析、分段切块、向量化、检索重排等 RAG 流水线环节可视化,大幅降低了开发门槛。本文以企业级实践为导向,完整演示基于 Dify 从零搭建知识库问答应用的过程,涵盖本地部署、分段策略、混合检索、Prompt 设计,以及通过 API 将问答能力扩

weixin_34252686的博客 396

RK3588与FocalTech触摸屏代码适配全解析:从原理到实战

摘要:本文详细介绍了瑞芯微RK3588处理器与FocalTech触摸屏的适配过程,包括硬件特性、驱动加载、设备树配置和常见问题解决方案。RK3588作为8nm工艺的高性能处理器,具备强大的计算能力和丰富的接口资源;FocalTech触摸屏则采用电容式技术,支持I2C/SPI接口。适配关键步骤包括驱动程序加载、硬件连接检查、设备树配置和内核版本兼容性处理,并提供了代码示例和问题排查方法。随着嵌入式设备智能化发展,该适配技术将持续优化,为智能交互提供更优解决方案。

远程部署调试 运行安装 项目调试 二次开发 项目技术新 持续迭代 部分源码免费分享 278

Python全栈入门到实战【进阶篇 1】类与对象:面向对象编程的基石

Python中定义类使用**class关键字**,创建对象使用**类名()**(类似调用函数),语法简洁,我们从最基础的空类开始,逐步拆解。class# 定义空的学生类,pass表示占位,无实际内容 class Student : pass编码规范:类名遵循大驼峰命名法(每个单词首字母大写,无下划线),如StudentCarPhone,这是Python官方推荐的PEP8规范,便于区分类和其他标识符。实例方法必须定义在类内部;实例方法的第一个参数必须是self(名称可自定义,如this。

那些看似不起波澜的日复一日,会在某天让你看到坚持的意义 3425

私有化 Dify 应用开发(5):Dify 接入 RAGFlow 外部知识库

本文针对Dify自带知识库在复杂文档处理上的不足,提出通过对接专业RAG引擎RAGFlow的解决方案。文章详细讲解了RAGFlow的核心优势(深度OCR解析、十多种分片模式)、与Dify共存的Docker部署方法(含端口冲突解决)、知识库创建流程,以及Dify对接RAGFlow的完整步骤(获取API、配置连接、应用集成)。该方案实现Dify流程编排与RAGFlow深度解析的优势互补,可显著提升企业级知识库的问答准确率。

2501_94250394的博客 530

CREO图文教程:三维设计案例之矿泉水瓶实例图文教程之详细攻略

草绘,先绘制中心线,绘制底部宽度;对称标注:点击左端点,中心线,左端点,中键即可标注;给定高度;样条曲线绘制外形(双击样条曲线,点击下栏的控制模式(第一个按钮),再拉动控制样条曲线上的各个点)打勾即可得到三维实体。......

走向CTO之路 1939

Dify RAG 实战:用知识库让 AI 读懂你的文档

--- title: "Dify RAG 实战:用知识库让 AI 读懂你的文档" description: "在 Dify 中搭建 RAG 知识库的完整流程:文档上传、切分、向量化、混合检索、重排,用 NVC 沟通助手做案例,踩坑经验全记录。" keywords: - Dify - RAG - 知识库 - 向量检索 - 重排 - Qwen - NVC - AI应用 tags: - Dify - RAG - 知识库 - 向量检索 - 重排 - Qwen

2301_80117363的博客 539

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

基于Dify与RAG技术构建企业级AI知识库:从原理到部署实战

检索增强生成(RAG)是一种将信息检索与大语言模型生成能力相结合的技术范式,其核心原理在于通过向量化技术将非结构化文档转换为语义向量,并利用向量数据库实现高效相似度检索,从而为LLM提供精准的上下文依据。这项技术的核心价值在于有效解决了传统关键词搜索在语义理解上的不足,大幅提升了知识查询的准确性与可靠性,同时确保了生成内容的事实依据。在应用场景上,RAG技术特别适用于构建企业智能客服、内部知识问答系统、个人知识管理助手等,能够将散落的文档资料转化为可对话的智能资产。本文以开源LLM应用开发平台Dify为例,

weixin_29057163的博客 299

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

(保姆级教程)Dify RAG升级全解析!Knowledge pipeline,让你的Agent知识库“活”起来!

Dify 知识库9 月份迎来了一个非常重大的升级,Knowledge Pipeline ! 这次升级,给用户提供了一套可视化、可编排的 RAG 数据处理基础设施,从而系统性地解决了企业级 AI 应用落地的上下文工程(Context Engineering) 瓶颈。

m0_59235945的博客 1656

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

Dify知识库增强检索全攻略,从原理到实战,看这一篇就够了!

RAG(检索增强生成,Retrieval-Augmented Generation)增强检索知识库是一种结合信息检索与生成式人工智能的技术框架,旨在通过动态调用外部知识库提升大语言模型(LLM)回答的准确性、相关性和时效性。其核心在于将传统检索系统与生成模型结合,解决大模型自身训练数据局限性、知识过时及“幻觉”(虚构信息)等问题。以下是具体解析。

m0_59163425的博客 3703

【AI大模型实战】手把手教你基于Dify搭建RAG知识库,全程干货,零基础小白也能轻松学会!!

Dify 是一款开源的大模型应用开发平台,旨在帮助开发者快速构建生产级生成式 AI 应用。它集成了模型管理、提示词工程、数据检索、工作流编排和运维监控等核心功能,支持数百种开源及商业大模型(如 Llama3、GPT-4、Claude 等),并提供可视化工作流设计、RAG(检索增强生成)管道、Agent 智能体框架等特色能力。

Android23333的博客 1622

Agent 开发者重大利好!Dify 知识库 RAG 升级 Knowledge pipeline

Dify知识库迎来重大升级,推出Knowledge Pipeline功能,为企业AI应用提供可视化、可编排的RAG数据处理基础设施。该升级解决了非结构化文件处理、数据处理黑盒问题,降低开发维护成本,并支持多种数据源接入。测试显示,新系统能有效解析图片PDF、表格等复杂文档信息,并支持多文档综合检索。用户可通过内置模板快速配置知识库流水线,选择适合的embedding和rerank模型,完成知识库部署。这一升级为开发者提供了更强大的知识管理工具,助力企业AI应用落地。

AI_today的博客 1588

Dify数据集管理功能深度解析

Dify通过智能文档解析、语义分块与向量检索,将企业知识转化为AI可用的动态资源。支持版本控制、权限协作与RAG增强生成,实现精准问答与跨部门知识共享,推动AI从黑箱走向可维护的协同生态。

weixin_42510201的博客 718

【万字长文】Dify 知识库全链路图解:7 个关键节点,彻底拆解 RAG 黑盒

在这篇文章中,我们了解下dify内部知识库的整个流转实现。通过该篇,我们能详细的了解到dify数据是如何解析的。

2301_81888214的博客 899
上一篇: 三大排序算法总结:冒泡、选择、归并排序
下一篇: C字符串的幕后英雄:结束符 `‘\0‘`
AI航海家(Ethan)
博客等级 码龄7年 477粉丝 91原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值