변환
변환 (Transformations)
변환(transformation)은 노드 목록을 입력으로 받아 노드 목록을 반환하는 것이에요. Transformation 기본 클래스를 구현하는 각 컴포넌트는 동기 __call__() 정의와 비동기 acall() 정의를 모두 가져요.
출처: 문서
본문
현재 다음 컴포넌트들이 Transformation 객체예요:
TextSplitterNodeParserMetadataExtractorEmbeddings모델 (지원되는 임베딩 목록 확인)
사용 패턴
변환은 IngestionPipeline과 함께 사용하는 것이 가장 좋지만, 직접 사용할 수도 있어요.
from llama_index.core.node_parser import SentenceSplitter
from llama_index.core.extractors import TitleExtractor
node_parser = SentenceSplitter(chunk_size=512)
extractor = TitleExtractor()
# use transforms directly
nodes = node_parser(documents)
# or use a transformation in async
nodes = await extractor.acall(nodes)
인덱스와 결합하기
변환을 인덱스나 전역 설정에 전달하면, 인덱스에서 from_documents() 또는 insert()를 호출할 때 사용돼요.
from llama_index.core import VectorStoreIndex
from llama_index.core.extractors import (
TitleExtractor,
QuestionsAnsweredExtractor,
)
from llama_index.core.ingestion import IngestionPipeline
from llama_index.core.node_parser import TokenTextSplitter
transformations = [
TokenTextSplitter(chunk_size=512, chunk_overlap=128),
TitleExtractor(nodes=5),
QuestionsAnsweredExtractor(questions=3),
]
# global
from llama_index.core import Settings
Settings.transformations = [text_splitter, title_extractor, qa_extractor]
# per-index
index = VectorStoreIndex.from_documents(
documents, transformations=transformations
)
커스텀 변환
기본 클래스를 구현하면 어떤 변환이든 직접 구현할 수 있어요.
다음 커스텀 변환은 텍스트에서 특수 문자나 구두점을 제거해요.
import re
from llama_index.core import Document
from llama_index.embeddings.openai import OpenAIEmbedding
from llama_index.core.node_parser import SentenceSplitter
from llama_index.core.ingestion import IngestionPipeline
from 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 pipeline
pipeline = IngestionPipeline(
transformations=[
SentenceSplitter(chunk_size=25, chunk_overlap=0),
TextCleaner(),
OpenAIEmbedding(),
],
)
nodes = pipeline.run(documents=[Document.example()])