文档API 参考📓 教程🧑‍🍳 食谱🤝 集成💜 Discord🎨 Studio
API 参考

Preprocessors

将管道包装为组件。

模块 haystack_experimental.components.preprocessors.embedding_based_document_splitter

EmbeddingBasedDocumentSplitter

基于嵌入相似性分割文档,使用连续句子组之间的余弦距离。

此组件首先将文本分割成句子,可选地对它们进行分组,计算每个组的嵌入,然后使用连续嵌入之间的余弦距离来确定分割点。高于指定百分位数的任何距离都被视为断点。该组件还根据原始文档中的换页符( )跟踪页码。

此组件的灵感来自 Greg Kamradt 的 5 Levels of Text Splitting

使用示例

from haystack import Document
from haystack.components.embedders import SentenceTransformersDocumentEmbedder
from haystack_experimental.components.preprocessors import EmbeddingBasedDocumentSplitter

doc = Document(
    content="This is a first sentence. This is a second sentence. This is a third sentence. "
    "Completely different topic. The same completely different topic."
)

embedder = SentenceTransformersDocumentEmbedder()

splitter = EmbeddingBasedDocumentSplitter(
    document_embedder=embedder,
    sentences_per_group=2,
    percentile=0.95,
    min_length=50,
    max_length=1000
)
splitter.warm_up()
result = splitter.run(documents=[doc])

EmbeddingBasedDocumentSplitter.__init__

def __init__(*,
             document_embedder: DocumentEmbedder,
             sentences_per_group: int = 3,
             percentile: float = 0.95,
             min_length: int = 50,
             max_length: int = 1000,
             language: Language = "en",
             use_split_rules: bool = True,
             extend_abbreviations: bool = True)

初始化 EmbeddingBasedDocumentSplitter。

参数:

  • document_embedder: 用于计算嵌入的 DocumentEmbedder。
  • sentences_per_group: 在嵌入前将句子分组的数量。
  • percentile: 余弦距离的百分位数阈值。高于此百分位数的距离被视为断点。
  • min_length: 分割后的最小长度(以字符计)。长度小于此值的分割将被合并。
  • max_length: 分割后的最大长度(以字符计)。长度大于此值的分割将被递归分割。
  • language: 用于句子分词的语言。
  • use_split_rules: 是否使用额外的分割规则进行句子分词。
  • extend_abbreviations: 是否扩展 NLTK 缩写。

EmbeddingBasedDocumentSplitter.warm_up

def warm_up() -> None

通过初始化句子分词器来预热组件。

EmbeddingBasedDocumentSplitter.run

@component.output_types(documents=List[Document])
def run(documents: List[Document]) -> Dict[str, List[Document]]

基于嵌入相似性分割文档。

参数:

  • documents: 要分割的文档。

引发:

  • None: - RuntimeError: 如果组件未预热。
  • TypeError: 如果输入不是 Document 列表。
  • ValueError: 如果文档内容为 None 或为空。

返回值:

一个字典,其中包含以下键

  • documents: 包含分割文本的文档列表。每个文档包含
  • 一个元数据字段source_id 用于跟踪原始文档。
  • 一个元数据字段split_id 用于跟踪分割编号。
  • 一个元数据字段page_number 用于跟踪原始页码。
  • 所有其他元数据均从原始文档复制。

EmbeddingBasedDocumentSplitter.to_dict

def to_dict() -> Dict[str, Any]

将组件序列化为字典。

EmbeddingBasedDocumentSplitter.from_dict

@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "EmbeddingBasedDocumentSplitter"

从字典反序列化组件。