0Pricing
AI Engineering Academy · 강의

분할 전략: 고정 크기, 문장 단위, 재귀 방식

고정 크기, 문장 경계, 재귀적 문자 텍스트 분할기를 구현하고 비교하며, 분할 크기와 겹침이 검색 품질에 미치는 영향을 이해합니다.

분할 전략: 고정 크기, 문장 단위, 재귀 방식은(는) CoddyKit의 무료 AI Engineering Academy 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 AI Engineering Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. AI Engineering Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Why Chunking Quality Matters

Chunking is the process of splitting loaded documents into smaller pieces that fit within the LLM's context window and can be individually indexed and retrieved. The way you chunk determines retrieval quality more than almost any other factor. A chunk that splits an answer across two pieces means neither chunk alone is sufficient to answer the question. A chunk that mixes two unrelated topics gets retrieved for questions about both but is useful for neither.

Fixed-Size Chunking

Fixed-size chunking splits text into chunks of exactly N characters or N tokens, regardless of sentence or paragraph boundaries. It is the simplest strategy and fast to implement. The major drawback is that it often cuts sentences in half, creating chunks that start or end mid-thought. This is acceptable for dense, uniformly formatted text like database export dumps, but produces poor retrieval quality on narrative prose or technical documentation.

def fixed_size_chunks(text, chunk_size=500, overlap=50):
    '''Split text into fixed-size character chunks with overlap'''
    chunks = []
    start = 0
    while start < len(text):
        end = start + chunk_size
        chunk = text[start:end]
        chunks.append(chunk)
        start += chunk_size - overlap  # overlap keeps context at boundaries
    return chunks

example = 'This is a long document. ' * 100
chunks = fixed_size_chunks(example, chunk_size=200, overlap=20)
print(f'Produced {len(chunks)} chunks, first: {chunks[0][:80]}...')

Adding Overlap to Fixed Chunks

The key improvement to fixed-size chunking is overlap: each chunk shares N characters with the previous chunk. This ensures that information near a chunk boundary appears in both adjacent chunks. With 50-100 token overlap, a sentence that crosses a boundary will be fully captured in at least one of the two chunks. More overlap means better coverage but larger index size and redundant content in retrieval results.

# Overlap example with a sentence at the boundary
text = 'A B C D E F G H I J'
chunk_size = 6  # characters
overlap = 2

i = 0
while i < len(text):
    print(repr(text[i:i+chunk_size]))
    i += chunk_size - overlap

# Output shows overlapping content:
# 'A B C D'
# 'C D E F'
# 'E F G H'
# Each adjacent pair shares 2 chars

Sentence-Boundary Chunking

Sentence-boundary chunking uses NLP libraries like nltk or spacy to detect sentence ends before splitting. This guarantees that no sentence is cut in half. You accumulate sentences until adding the next one would exceed the target size, then start a new chunk. The result is chunks that always contain complete thoughts, which produces significantly better embedding quality than fixed-character splitting.

import nltk
nltk.download('punkt', quiet=True)

def sentence_chunks(text, max_tokens=300):
    sentences = nltk.sent_tokenize(text)
    chunks = []
    current = []
    current_len = 0

    for sent in sentences:
        sent_tokens = len(sent.split())
        if current_len + sent_tokens > max_tokens and current:
            chunks.append(' '.join(current))
            current = []
            current_len = 0
        current.append(sent)
        current_len += sent_tokens

    if current:
        chunks.append(' '.join(current))
    return chunks

Recursive Character Text Splitting

Recursive character splitting is the most widely used strategy in production RAG systems. It tries a hierarchy of separators in order: first paragraph breaks (\n\n), then newlines (\n), then sentence-ending periods, then spaces, and finally individual characters. It splits at the largest meaningful boundary that keeps the chunk under the target size, resulting in chunks that respect document structure as much as possible.

from langchain_text_splitters import RecursiveCharacterTextSplitter

splitter = RecursiveCharacterTextSplitter(
    chunk_size=1000,       # target size in characters
    chunk_overlap=200,     # overlap between consecutive chunks
    separators=['\n\n', '\n', '. ', '! ', '? ', ' ', ''],
    length_function=len
)

with open('document.txt') as f:
    text = f.read()

chunks = splitter.split_text(text)
print(f'Split into {len(chunks)} chunks')
for i, chunk in enumerate(chunks[:3]):
    print(f'Chunk {i}: {len(chunk)} chars — {chunk[:60]}...')

Token-Aware Splitting

Character counts are an imprecise proxy for token counts. A 1000-character chunk might be 200 tokens or 400 tokens depending on word length and language. For precise control, split by token count using tiktoken. This matters for fitting chunks to the model's context window and for accurate cost estimation. LangChain's TokenTextSplitter wraps tiktoken for token-aware chunking.

from langchain_text_splitters import TokenTextSplitter
import tiktoken

# Split by actual token count, not characters
splitter = TokenTextSplitter(
    encoding_name='cl100k_base',  # GPT-4 tokenizer
    chunk_size=256,               # target tokens per chunk
    chunk_overlap=32              # overlap in tokens
)

chunks = splitter.split_text(text)

# Verify token count
enc = tiktoken.get_encoding('cl100k_base')
for chunk in chunks[:3]:
    tokens = len(enc.encode(chunk))
    print(f'Chunk: {tokens} tokens')

Choosing the Right Chunk Size

Chunk size is a critical hyperparameter. Small chunks (100-200 tokens) are precise — they contain tightly focused information that embeds well. But they lose surrounding context, so the LLM may not have enough information to answer. Large chunks (500-1000 tokens) provide more context but their embeddings average over a broader topic, making them harder to retrieve for specific queries. Most production systems use 256-512 tokens with empirical testing on their data.

Adding Context to Chunks

A powerful enhancement is contextual chunk headers: prepend the document title and section heading to each chunk's text before embedding. This means the embedding captures not just the chunk's content but also where it came from in the document. A chunk reading Benefits and Vacation Policy: Employees accrue 15 days annually... retrieves much more accurately for questions about vacation policy than the same text without the header.

def create_contextual_chunks(doc, splitter):
    title = doc['metadata'].get('title', '')
    section = doc['metadata'].get('section', '')
    text = doc['text']

    raw_chunks = splitter.split_text(text)
    contextual_chunks = []
    for chunk in raw_chunks:
        # Prepend document context to each chunk
        context_header = f'{title}\n{section}\n\n' if title else ''
        contextual_chunks.append({
            'text': context_header + chunk,
            'metadata': doc['metadata']
        })
    return contextual_chunks

Comparing Strategies on Your Data

No single chunking strategy is universally best. Build a quick evaluation: take 20 questions you know the answers to, run retrieval with each chunking strategy, and measure how often the correct chunk ranks in the top 5 results (hit rate@5). This takes an hour to set up and saves weeks of guessing. You will often find that your specific document format (dense legal prose vs. structured technical docs) strongly favors one strategy over others.

def evaluate_chunking_strategy(questions_and_answers, retriever):
    hits = 0
    for qa in questions_and_answers:
        results = retriever.retrieve(qa['question'], top_k=5)
        result_texts = [r['text'] for r in results]
        # Check if answer text appears in any retrieved chunk
        if any(qa['answer'] in text for text in result_texts):
            hits += 1
    hit_rate = hits / len(questions_and_answers)
    print(f'Hit rate@5: {hit_rate:.1%} ({hits}/{len(questions_and_answers)})')
    return hit_rate

Handling Special Document Types

Some document types need special-purpose chunking. Code files should be split by function or class boundaries, not character count. Markdown files should be split at heading boundaries so each chunk corresponds to one section. Tables should be kept intact as a single chunk (splitting mid-table makes the content uninterpretable). Plan your chunking strategy based on the document types in your corpus rather than applying a one-size-fits-all splitter.

from langchain_text_splitters import MarkdownHeaderTextSplitter

# Split Markdown by header hierarchy
md_splitter = MarkdownHeaderTextSplitter(
    headers_to_split_on=[
        ('#', 'h1'),
        ('##', 'h2'),
        ('###', 'h3')
    ]
)

with open('documentation.md') as f:
    md_text = f.read()

# Each chunk gets metadata from its heading hierarchy
chunks = md_splitter.split_text(md_text)
for chunk in chunks[:3]:
    print('Section:', chunk.metadata)
    print('Text:', chunk.page_content[:80])
    print()

Tracking Chunk Lineage

Every chunk needs a stable, unique ID derived from its source document and position. Use this ID to update specific chunks when documents change without re-indexing the entire corpus. A deterministic hash of the source path plus chunk index works well. Also record chunk position (chunk 3 of 12 from document X) in metadata — this helps re-assemble full sections when multiple adjacent chunks are retrieved together.

import hashlib

def assign_chunk_ids(chunks, source_path):
    for i, chunk in enumerate(chunks):
        key = f'{source_path}::chunk_{i}'
        chunk_id = hashlib.sha256(key.encode()).hexdigest()[:16]
        chunk['id'] = chunk_id
        chunk['metadata']['chunk_index'] = i
        chunk['metadata']['total_chunks'] = len(chunks)
    return chunks

# IDs are stable across re-runs if source and position match
chunks = sentence_chunks(text)
chunks = [{'text': c, 'metadata': {}} for c in chunks]
assign_chunk_ids(chunks, 'docs/policy_v3.pdf')

Quick Check

Test your understanding of AI Engineering concepts from this lesson.

Lesson Recap

In this lesson you learned: fixed-size chunking is simple but cuts sentences in half, sentence-boundary chunking preserves complete thoughts, recursive character splitting respects document structure and is the most common production choice, and advanced techniques including token-aware splitting, contextual headers, special-purpose splitters for Markdown and code, and stable chunk IDs for incremental updates. Next up we embed and store these chunks in a vector database.

자주 묻는 질문

“분할 전략: 고정 크기, 문장 단위, 재귀 방식” 강의는 무료인가요?

네 — “분할 전략: 고정 크기, 문장 단위, 재귀 방식” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 AI Engineering Academy 강의 전체를 잠금 해제할 수 있습니다. AI Engineering Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“분할 전략: 고정 크기, 문장 단위, 재귀 방식”에서 뭘 배우나요?

고정 크기, 문장 경계, 재귀적 문자 텍스트 분할기를 구현하고 비교하며, 분할 크기와 겹침이 검색 품질에 미치는 영향을 이해합니다. 브라우저에서 직접 실행하는 실습 코드로 AI Engineering Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

AI Engineering Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 AI Engineering Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“분할 전략: 고정 크기, 문장 단위, 재귀 방식” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 AI Engineering Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 AI Engineering Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 문서 불러오기와 텍스트 추출
  2. 분할 전략: 고정 크기, 문장 단위, 재귀 방식
  3. 색인: 분할 조각 임베딩 및 저장
  4. 질의, 검색, 생성
← AI Engineering Academy(으)로 돌아가기