0Pricing
LangChain / RAG / Vector DBs · 강의

텍스트 분할 전략 이해

검색과 컨텍스트 창 사용을 최적화하기 위해 대규모 문서를 더 작고 의미 있는 청크로 나누는 이유와 방법을 학습합니다.

텍스트 분할 전략 이해은(는) CoddyKit의 무료 LangChain / RAG / Vector DBs 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 LangChain / RAG / Vector DBs 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. LangChain / RAG / Vector DBs 강의에는 총 4개의 강의가 포함되어 있습니다.

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

Why Split Documents?

Large Language Models (LLMs) have a 'context window' – a limit on how much text they can process at once. If you feed them a document that's too long, they simply can't handle it all.

Text splitting is the process of breaking down large documents into smaller, manageable chunks. This makes them suitable for LLMs and helps retrieval systems find more precise information.

The Context Window Limit

Imagine an LLM as a very smart person with a short-term memory limit. The context window is like that limit. If you give it too much information, it might forget the beginning or get confused.

  • LLMs can only process a certain number of tokens (words or sub-words).
  • Going over this limit means information is truncated or ignored.
  • Smaller chunks ensure all relevant information fits and is processed effectively.

Basic Splitting: By Character

One of the most straightforward ways to split text is using a CharacterTextSplitter. It simply breaks text based on a specified separator, usually a newline character (\n).

It's like cutting a long rope into smaller pieces at every knot you find. This method is easy to understand but can sometimes break sentences or paragraphs in awkward places.

Code: Simple Character Split

Try running this example. Notice how the CharacterTextSplitter breaks the text primarily at each newline character.

from langchain_text_splitters import CharacterTextSplitter

text = "Hello world.\nThis is a test.\nAnother line here." 

# Initialize the splitter
text_splitter = CharacterTextSplitter(
    separator="\n",
    chunk_size=20, # Max characters per chunk
    chunk_overlap=0, # No overlap for simplicity
    length_function=len # How to measure chunk length
)

# Split the text
chunks = text_splitter.split_text(text)

# Print the resulting chunks
for i, chunk in enumerate(chunks):
    print(f"Chunk {i+1}: '{chunk}'")

Understanding Chunk Size

The chunk_size parameter determines the maximum length of each piece of text. If a piece of text (before splitting by a separator) exceeds this size, the splitter will try to break it further.

Choosing the right size is crucial:

  • Too small: Context might be lost across multiple chunks, making it harder for the LLM to understand the full picture.
  • Too large: Might still exceed the LLM's context window or contain too much irrelevant information, diluting the focus.

The Role of Overlap

chunk_overlap specifies how many characters (or tokens) each chunk shares with the previous one. This is vital to maintain continuity and prevent loss of context at the boundaries of chunks.

Imagine a sentence that gets split perfectly in half across two chunks. Without overlap, the LLM might miss the connection between the two halves. Overlap ensures that key phrases or ideas aren't cut off abruptly, providing a smoother flow of information.

Recursive Character Splitting

The RecursiveCharacterTextSplitter is often preferred for general-purpose documents. Instead of just one separator, it tries a list of separators in order of preference (e.g., ["\n\n", "\n", " ", ""]).

It first tries to split by the largest, most semantically meaningful separator (like a double newline for paragraphs). If a chunk is still too big, it then tries the next smaller separator (like a single newline), and so on. This creates more semantically coherent chunks.

Code: Recursive Split in Action

This example uses a recursive splitter. Notice how it prioritizes paragraph breaks (double newlines) to keep related sentences together.

from langchain_text_splitters import RecursiveCharacterTextSplitter

text = """
LangChain is a framework for developing applications powered by language models.
It enables applications that are:
1. Data-aware: connect a language model to other sources of data.
2. Agentic: allow a language model to interact with its environment.

This framework provides tools and components to build complex LLM workflows.
"""

# Initialize the recursive splitter
text_splitter = RecursiveCharacterTextSplitter(
    chunk_size=100, # Max characters per chunk
    chunk_overlap=20, # Overlap to maintain context
    length_function=len # How to measure chunk length
)

# Split the text
chunks = text_splitter.split_text(text)

# Print the resulting chunks
for i, chunk in enumerate(chunks):
    print(f"Chunk {i+1}: '{chunk}'")

Choosing the Right Strategy

When should you use which splitter?

  • CharacterTextSplitter: Good for simple, highly structured text where you know the exact delimiters (e.g., CSV files, specific log formats).
  • RecursiveCharacterTextSplitter: Generally the default and best choice for most general-purpose documents (like articles, reports), as it aims for more logical and semantically coherent breaks.
  • Other splitters: LangChain offers specialized splitters for code, Markdown, and even semantic content. We'll touch on these in future lessons!

Text Splitting Challenge

You have a long article and need to split it into smaller chunks for an LLM. You decide to use a chunk_size of 500 and a chunk_overlap of 50.

Recap: Text Splitting Fundamentals

Great job! You've learned the fundamental concepts behind text splitting, a crucial step for preparing documents for LLMs.

  • We split text due to LLM context window limits and for more effective retrieval.
  • The CharacterTextSplitter provides basic splitting using a single separator.
  • The RecursiveCharacterTextSplitter offers a smarter, hierarchical approach for general text.
  • chunk_size controls the maximum length of your chunks.
  • chunk_overlap preserves context by sharing text between adjacent chunks.

Next, we'll dive deeper into customizing splitting strategies for specific content types!

자주 묻는 질문

“텍스트 분할 전략 이해” 강의는 무료인가요?

네 — “텍스트 분할 전략 이해” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 LangChain / RAG / Vector DBs 강의 전체를 잠금 해제할 수 있습니다. LangChain / RAG / Vector DBs 강의에는 총 4개의 강의가 포함되어 있습니다.

“텍스트 분할 전략 이해”에서 뭘 배우나요?

검색과 컨텍스트 창 사용을 최적화하기 위해 대규모 문서를 더 작고 의미 있는 청크로 나누는 이유와 방법을 학습합니다. 브라우저에서 직접 실행하는 실습 코드로 LangChain / RAG / Vector DBs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

LangChain / RAG / Vector DBs을(를) 시작하는 데 경험이 필요한가요?

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

“텍스트 분할 전략 이해” 강의는 얼마나 걸리나요?

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

이 LangChain / RAG / Vector DBs 강의에서 코드를 작성하고 실행할 수 있나요?

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

이 강의의 모든 강의

  1. 다양한 문서 유형 로딩
  2. 텍스트 분할 전략 이해
  3. 문서 분할 사용자 지정
  4. 문서 메타데이터 처리와 필터링
← LangChain / RAG / Vector DBs(으)로 돌아가기