Comprendre les stratégies de découpage du texte
Découvrez pourquoi et comment découper de grands documents en segments plus petits et pertinents afin d’optimiser la récupération et l’utilisation de la fenêtre de contexte.
Comprendre les stratégies de découpage du texte est une leçon LangChain / RAG / Vector DBs gratuite sur CoddyKit. Ceci est la leçon 2 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage LangChain / RAG / Vector DBs, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours LangChain / RAG / Vector DBs comprend 4 leçons au total.
Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.
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
CharacterTextSplitterprovides basic splitting using a single separator. - The
RecursiveCharacterTextSplitteroffers a smarter, hierarchical approach for general text. chunk_sizecontrols the maximum length of your chunks.chunk_overlappreserves context by sharing text between adjacent chunks.
Next, we'll dive deeper into customizing splitting strategies for specific content types!
Apprends LangChain / RAG / Vector DBs avec un tuteur IA — gratuit
Écris et exécute du vrai code dans ton navigateur, obtiens de l'aide instantanée d'un tuteur IA disponible 24h/24, et reprends là où tu t'es arrêté sur le web ou dans l'app.
- Cours
- 12
- Leçons
- 48
Questions Fréquemment Posées
La leçon « Comprendre les stratégies de découpage du texte » est-elle gratuite ?
Oui — le texte complet de « Comprendre les stratégies de découpage du texte » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours LangChain / RAG / Vector DBs, passe à CoddyKit PRO. Le cours LangChain / RAG / Vector DBs comprend 4 leçons au total.
Qu'est-ce que j'apprendrai dans « Comprendre les stratégies de découpage du texte » ?
Découvrez pourquoi et comment découper de grands documents en segments plus petits et pertinents afin d’optimiser la récupération et l’utilisation de la fenêtre de contexte. Tu pratiques LangChain / RAG / Vector DBs avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.
Dois-je avoir de l'expérience pour commencer LangChain / RAG / Vector DBs ?
Aucune expérience préalable n'est requise. LangChain / RAG / Vector DBs sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 2 sur 4.
Combien de temps prend la leçon « Comprendre les stratégies de découpage du texte » ?
La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.
Peux-tu écrire et exécuter du code dans cette leçon LangChain / RAG / Vector DBs ?
Oui. Chaque leçon LangChain / RAG / Vector DBs inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.
Toutes les leçons de ce cours
- Chargement de différents types de documents
- Comprendre les stratégies de découpage du texte
- Personnalisation du découpage des documents
- Gérer les métadonnées des documents et le filtrage