转换
转换是一种以节点列表作为输入,并返回节点列表的操作。每个实现 Transformation 基类的组件都包含同步的 __call__() 定义和异步的 acall() 定义。
目前,以下组件是 Transformation 对象:
TextSplitterNodeParserMetadataExtractorEmbeddings模型(查看我们的支持的嵌入列表)
虽然转换功能最好与 IngestionPipeline 配合使用,但也可以直接使用。
from llama_index.core.node_parser import SentenceSplitterfrom llama_index.core.extractors import TitleExtractor
node_parser = SentenceSplitter(chunk_size=512)extractor = TitleExtractor()
# use transforms directlynodes = node_parser(documents)
# or use a transformation in asyncnodes = await extractor.acall(nodes)转换可以传递到索引或整体全局设置中,并在调用索引上的 from_documents() 或 insert() 时使用。
from llama_index.core import VectorStoreIndexfrom llama_index.core.extractors import ( TitleExtractor, QuestionsAnsweredExtractor,)from llama_index.core.ingestion import IngestionPipelinefrom llama_index.core.node_parser import TokenTextSplitter
transformations = [ TokenTextSplitter(chunk_size=512, chunk_overlap=128), TitleExtractor(nodes=5), QuestionsAnsweredExtractor(questions=3),]
# globalfrom llama_index.core import Settings
Settings.transformations = [text_splitter, title_extractor, qa_extractor]
# per-indexindex = VectorStoreIndex.from_documents( documents, transformations=transformations)您可以通过实现基类来自行实现任何转换。
以下自定义转换将移除文本中的任何特殊字符或标点符号。
import refrom llama_index.core import Documentfrom llama_index.embeddings.openai import OpenAIEmbeddingfrom llama_index.core.node_parser import SentenceSplitterfrom llama_index.core.ingestion import IngestionPipelinefrom llama_index.core.schema import TransformComponent
class TextCleaner(TransformComponent): def __call__(self, nodes, **kwargs): for node in nodes: node.text = re.sub(r"[^0-9A-Za-z ]", "", node.text) return nodes这些可以直接使用或用于任何 IngestionPipeline 中。
# use in a pipelinepipeline = IngestionPipeline( transformations=[ SentenceSplitter(chunk_size=25, chunk_overlap=0), TextCleaner(), OpenAIEmbedding(), ],)
nodes = pipeline.run(documents=[Document.example()])