๐Ÿค– AI/ML

Chunking

Text Chunking / Document Splitting

A technique that splits long documents into small pieces (chunks). Performed before generating embeddings in RAG (retrieval-augmented generation) systems, and chunk size and overlap settings have a decisive effect on retrieval quality.

๐Ÿ“– Detailed Explanation

Chunking is a preprocessing technique that splits long text documents into smaller units called "chunks." LLMs (large language models) and embedding models have limits on the number of tokens they can process, and embedding a long document as a whole dilutes its meaning, so splitting it into appropriately sized pieces is essential. The search quality of a RAG system depends heavily on the chunking strategy.

The need for chunking stems from the context window limits of LLMs and the characteristics of embeddings. For example, OpenAI's text-embedding-3-small model can only process up to 8191 tokens, and compressing text that is too long into a single embedding causes loss of detailed information. Splitting text into appropriately sized chunks lets each chunk focus on a specific topic, which improves retrieval accuracy.

There are several chunking methods. The most basic is fixed-size splitting, which cuts text at a set number of characters or tokens. However, this can cut in the middle of a sentence and break the meaning. To address this, structure-based chunking is used, such as splitting by sentence, paragraph, or Markdown header. Recently, semantic chunking (splitting by units of meaning) has also been attracting attention, and it is also important to set an overlap between chunks to preserve the continuity of context.

In practice, the chunking strategy varies depending on the characteristics of the data. It is effective to split technical documents and legal documents by section/clause, conversation logs by utterance, and code by function/class. Generally, a chunk size of 500-1500 tokens and an overlap of about 10-20% are recommended, but you need to find the optimal values by measuring actual retrieval performance. Frameworks such as LangChain and LlamaIndex provide tools that make it easy to apply various chunking strategies.

๐Ÿ’ป Code Example

This is Python code that implements various chunking methods.

Python
# pip install langchain langchain-text-splitters tiktoken
from langchain_text_splitters import (
    RecursiveCharacterTextSplitter,
    CharacterTextSplitter,
    TokenTextSplitter,
    MarkdownHeaderTextSplitter
)
import tiktoken

# ์˜ˆ์‹œ ๋ฌธ์„œ
document = """
# ์ธ๊ณต์ง€๋Šฅ ๊ฐœ์š”

์ธ๊ณต์ง€๋Šฅ(AI)์€ ์ธ๊ฐ„์˜ ํ•™์Šต๋Šฅ๋ ฅ, ์ถ”๋ก ๋Šฅ๋ ฅ, ์–ธ์–ด์ดํ•ด๋Šฅ๋ ฅ ๋“ฑ์„
์ปดํ“จํ„ฐ ํ”„๋กœ๊ทธ๋žจ์œผ๋กœ ์‹คํ˜„ํ•œ ๊ธฐ์ˆ ์ž…๋‹ˆ๋‹ค.

## ๋จธ์‹ ๋Ÿฌ๋‹

๋จธ์‹ ๋Ÿฌ๋‹์€ ๋ฐ์ดํ„ฐ๋กœ๋ถ€ํ„ฐ ํŒจํ„ด์„ ํ•™์Šตํ•˜์—ฌ ์˜ˆ์ธกํ•˜๋Š” AI์˜ ํ•˜์œ„ ๋ถ„์•ผ์ž…๋‹ˆ๋‹ค.
์ง€๋„ํ•™์Šต, ๋น„์ง€๋„ํ•™์Šต, ๊ฐ•ํ™”ํ•™์Šต์œผ๋กœ ๋‚˜๋‰ฉ๋‹ˆ๋‹ค.

### ๋”ฅ๋Ÿฌ๋‹

๋”ฅ๋Ÿฌ๋‹์€ ์ธ๊ณต์‹ ๊ฒฝ๋ง์„ ์—ฌ๋Ÿฌ ์ธต์œผ๋กœ ์Œ“์•„ ๋ณต์žกํ•œ ํŒจํ„ด์„ ํ•™์Šตํ•˜๋Š” ๊ธฐ๋ฒ•์ž…๋‹ˆ๋‹ค.
CNN, RNN, Transformer ๋“ฑ์˜ ์•„ํ‚คํ…์ฒ˜๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค.

## ์ž์—ฐ์–ด ์ฒ˜๋ฆฌ

์ž์—ฐ์–ด ์ฒ˜๋ฆฌ(NLP)๋Š” ์ปดํ“จํ„ฐ๊ฐ€ ์ธ๊ฐ„์˜ ์–ธ์–ด๋ฅผ ์ดํ•ดํ•˜๊ณ  ์ƒ์„ฑํ•˜๋Š” ๊ธฐ์ˆ ์ž…๋‹ˆ๋‹ค.
ํ…์ŠคํŠธ ๋ถ„๋ฅ˜, ๋ฒˆ์—ญ, ์š”์•ฝ, ์งˆ๋ฌธ ์‘๋‹ต ๋“ฑ์— ํ™œ์šฉ๋ฉ๋‹ˆ๋‹ค.
"""

# 1. ์žฌ๊ท€์  ๋ฌธ์ž ๋ถ„ํ•  (๊ฐ€์žฅ ์ถ”์ฒœ๋˜๋Š” ๋ฐฉ๋ฒ•)
recursive_splitter = RecursiveCharacterTextSplitter(
    chunk_size=200,           # ์ฒญํฌ ์ตœ๋Œ€ ํฌ๊ธฐ (๋ฌธ์ž ์ˆ˜)
    chunk_overlap=50,         # ์ฒญํฌ ๊ฐ„ ์˜ค๋ฒ„๋žฉ (๋ฌธ๋งฅ ์œ ์ง€)
    length_function=len,
    separators=["\n\n", "\n", ".", " ", ""]  # ๋ถ„ํ•  ์šฐ์„ ์ˆœ์œ„
)

chunks = recursive_splitter.split_text(document)
print("=== ์žฌ๊ท€์  ๋ฌธ์ž ๋ถ„ํ•  ===")
for i, chunk in enumerate(chunks):
    print(f"Chunk {i+1} ({len(chunk)}์ž): {chunk[:50]}...")

# 2. ํ† ํฐ ๊ธฐ๋ฐ˜ ๋ถ„ํ•  (ํ† ํฐ ์ œํ•œ ๊ณ ๋ ค ์‹œ)
token_splitter = TokenTextSplitter(
    encoding_name="cl100k_base",  # GPT-4/3.5์šฉ ํ† ํฌ๋‚˜์ด์ €
    chunk_size=100,               # ์ตœ๋Œ€ ํ† ํฐ ์ˆ˜
    chunk_overlap=20              # ์˜ค๋ฒ„๋žฉ ํ† ํฐ ์ˆ˜
)

token_chunks = token_splitter.split_text(document)
print("\n=== ํ† ํฐ ๊ธฐ๋ฐ˜ ๋ถ„ํ•  ===")
for i, chunk in enumerate(token_chunks):
    # ํ† ํฐ ์ˆ˜ ํ™•์ธ
    enc = tiktoken.get_encoding("cl100k_base")
    tokens = len(enc.encode(chunk))
    print(f"Chunk {i+1} ({tokens} tokens): {chunk[:40]}...")

# 3. ๋งˆํฌ๋‹ค์šด ํ—ค๋” ๊ธฐ๋ฐ˜ ๋ถ„ํ•  (๊ตฌ์กฐํ™”๋œ ๋ฌธ์„œ์— ์ ํ•ฉ)
headers_to_split_on = [
    ("#", "Header 1"),
    ("##", "Header 2"),
    ("###", "Header 3"),
]

markdown_splitter = MarkdownHeaderTextSplitter(
    headers_to_split_on=headers_to_split_on
)

md_chunks = markdown_splitter.split_text(document)
print("\n=== ๋งˆํฌ๋‹ค์šด ํ—ค๋” ๊ธฐ๋ฐ˜ ๋ถ„ํ•  ===")
for i, chunk in enumerate(md_chunks):
    print(f"Chunk {i+1}: {chunk.metadata} - {chunk.page_content[:40]}...")

# 4. ์‹œ๋งจํ‹ฑ ์ฒญํ‚น (์˜๋ฏธ ๋‹จ์œ„ ๋ถ„ํ• ) - ๊ณ ๊ธ‰ ๋ฐฉ๋ฒ•
from langchain_openai import OpenAIEmbeddings
from langchain_experimental.text_splitter import SemanticChunker

# ์˜๋ฏธ์  ์œ ์‚ฌ๋„ ๊ธฐ๋ฐ˜ ๋ถ„ํ• 
semantic_splitter = SemanticChunker(
    embeddings=OpenAIEmbeddings(),
    breakpoint_threshold_type="percentile",  # ๋ถ„ํ•  ๊ธฐ์ค€
    breakpoint_threshold_amount=95           # ์ž„๊ณ„๊ฐ’
)

# 5. ์ปค์Šคํ…€ ์ฒญํ‚น ํ•จ์ˆ˜
def custom_chunker(
    text: str,
    chunk_size: int = 500,
    chunk_overlap: int = 100,
    min_chunk_size: int = 50
) -> list:
    """
    ๋ฌธ์žฅ ๊ฒฝ๊ณ„๋ฅผ ์กด์ค‘ํ•˜๋Š” ์ปค์Šคํ…€ ์ฒญ์ปค

    Args:
        text: ๋ถ„ํ• ํ•  ํ…์ŠคํŠธ
        chunk_size: ๋ชฉํ‘œ ์ฒญํฌ ํฌ๊ธฐ
        chunk_overlap: ์˜ค๋ฒ„๋žฉ ํฌ๊ธฐ
        min_chunk_size: ์ตœ์†Œ ์ฒญํฌ ํฌ๊ธฐ

    Returns:
        ์ฒญํฌ ๋ฆฌ์ŠคํŠธ
    """
    import re

    # ๋ฌธ์žฅ ๋‹จ์œ„๋กœ ๋ถ„๋ฆฌ
    sentences = re.split(r'(?<=[.!?])\s+', text)
    chunks = []
    current_chunk = ""

    for sentence in sentences:
        if len(current_chunk) + len(sentence) <= chunk_size:
            current_chunk += " " + sentence if current_chunk else sentence
        else:
            if len(current_chunk) >= min_chunk_size:
                chunks.append(current_chunk.strip())
            # ์˜ค๋ฒ„๋žฉ ์ ์šฉ
            overlap_text = current_chunk[-chunk_overlap:] if len(current_chunk) > chunk_overlap else current_chunk
            current_chunk = overlap_text + " " + sentence

    if len(current_chunk) >= min_chunk_size:
        chunks.append(current_chunk.strip())

    return chunks

custom_chunks = custom_chunker(document, chunk_size=300, chunk_overlap=50)
print("\n=== ์ปค์Šคํ…€ ๋ฌธ์žฅ ๊ธฐ๋ฐ˜ ๋ถ„ํ•  ===")
for i, chunk in enumerate(custom_chunks):
    print(f"Chunk {i+1} ({len(chunk)}์ž): {chunk[:50]}...")

๐Ÿ—ฃ๏ธ Examples of Practical Conversations

Team Lead "The RAG search quality isn't good. Irrelevant content is often retrieved. How can we improve it?"
Developer "The current chunk size is 2000 characters, and I think that's too large. Multiple topics are mixed in a single chunk, so the embeddings are being diluted. I think it would be good to reduce it to 500-800 characters and add about 20% overlap."
Team Lead "Won't the context be cut off if the chunks get smaller?"
Developer "Overlap plays that role. Also, if you fetch the top 3-5 chunks during retrieval and combine them, you can provide sufficient context. Alternatively, you can use the Parent Document Retriever pattern, which searches with small chunks and returns the larger original document."
Interviewer "Please explain why chunking is important in RAG."
Candidate "There are three reasons. First, embedding models have token limits. Second, compressing text that is too long into a single vector causes loss of detailed information. Third, you need appropriately sized chunks to accurately retrieve only highly relevant information during retrieval."
Interviewer "How do you decide the chunk size?"
Candidate "It depends on the characteristics of the data and the use case. Generally 500-1500 tokens is recommended, but in practice you should build an evaluation set and measure retrieval performance with various chunk sizes. Also, if the document has a structure, splitting by section/header is effective."

Take a mock interview on this topic โ†’ WIA SOOM AI Interview ยท Start for free

Senior "You're using CharacterTextSplitter with only separator='\n'. That's a problem."
Junior "What's the problem? It seems to split well on line breaks."
Senior "If there's a long paragraph without line breaks, it just passes it through even if it exceeds chunk_size. Using RecursiveCharacterTextSplitter is safer because it tries multiple separators in sequence. Also, the overlap is 0, so the context is cut off at chunk boundaries."
Junior "I'll switch to RecursiveCharacterTextSplitter and set chunk_overlap to 10-20% of chunk_size. Thank you!"

โš ๏ธ Cautions

๐Ÿ”— Related Terms

๐Ÿ“š Learn More