semantic-text-splitter 소개 — LLM 컨텍스트를 위한 청크 분할
semantic-text-splitter 소개
LLM은 많은 작업을 잘하지만 컨텍스트 크기가 제한돼요. 문서가 그 크기보다 클 때는 텍스트를 청크로 잘라 넣어야 하는데, 이때 단순히 글자 수로 자르면 경계가 어긋나 의미가 손상돼요. text-splitter는 원하는 청크 크기를 최대한 채우되 의미상 자연스러운 경계에서 나누는 라이브러리예요.
패키지 이름
Rust 크레이트는 text-splitter이고, 파이썬 바인딩은 semantic-text-splitter예요(같은 이름을 얻을 수 없어서죠). 파이썬에서 쓰고 싶다면 semantic-text-splitter를 설치하면 돼요.
시작하기
cargo add text-splitter
가장 간단한 사용법은 문자 수로 청크 크기를 정하는 기본 구현이에요.
use text_splitter::TextSplitter;
// Maximum number of characters in a chunk
let max_characters = 1000;
// Default implementation uses character count for chunk size
let splitter = TextSplitter::new(max_characters);
let chunks = splitter.chunks("your document text");
청크 크기를 범위로 지정
청크가 범위 안에 들어오면 반환하도록 지정할 수도 있어요. 단, 다음 조각을 더하면 end 용량을 넘어설 수 있으니 start보다 작은 청크가 나올 수도 있다는 점을 알아두면 돼요.
use text_splitter::{ChunkConfig, TextSplitter};
// Maximum number of characters in a chunk. Will fill up the
// chunk until it is somewhere in this range.
let max_characters = 500..2000;
let splitter = TextSplitter::new(max_characters);
let chunks = splitter.chunks("your document text");