How to Chunk a Long Document for RAG Retrieval in Python
Split text into overlapping chunks at sentence boundaries using a custom Python function suitable for RAG retrieval pipelines.
Python code
42 linesimport re
from pathlib import Path
def chunk_document(text, chunk_size=500, overlap=100):
"""Split text into overlapping chunks suitable for RAG retrieval."""
# Normalize whitespace
text = re.sub(r'\s+', ' ', text).strip()
chunks = []
start = 0
while start < len(text):
end = min(start + chunk_size, len(text))
# If not at the end, try to break at a sentence boundary
if end < len(text):
# Look back for the last period, question mark, or exclamation
boundary = max(text.rfind('.', start, end),
text.rfind('?', start, end),
text.rfind('!', start, end))
if boundary > start + chunk_size // 2:
end = boundary + 1
chunk = text[start:end].strip()
if chunk:
chunks.append(chunk)
# Move start with overlap
start = max(end - overlap, start + 1)
return chunks
if __name__ == "__main__":
document = (
"Python is a powerful programming language. It is widely used in data science. "
"Machine learning models can be built quickly. RAG retrieval enhances AI answers. "
"Chunking documents is essential for efficient search. Proper overlap preserves context. "
"This ensures no important information is lost between chunks."
)
chunks = chunk_document(document, chunk_size=100, overlap=30)
for i, chunk in enumerate(chunks):
print(f"Chunk {i+1}: {chunk}")
Output
Chunk 1: Python is a powerful programming language. It is widely used in data science.
Chunk 2: Machine learning models can be built quickly. RAG retrieval enhances AI answers.
Chunk 3: Chunking documents is essential for efficient search. Proper overlap preserves context.
Chunk 4: This ensures no important information is lost between chunks.
How it works
The chunk_document function first normalizes whitespace so that split points align with words and sentences. It then iterates through the text, creating chunks of a fixed chunk_size, but when possible it moves the end boundary back to a sentence-ending punctuation mark to keep chunks coherent. The overlap parameter shifts the start position backward, so consecutive chunks share a portion of text, preserving context across boundaries. This prevents losing meaning at chunk edges, which is critical when feeding text to an embedding model for retrieval.
Common mistakes
- Splitting mid-sentence, which breaks semantic meaning and hurts retrieval accuracy.
- Setting overlap too small or zero, causing context loss at chunk boundaries.
- Forgetting to strip extra whitespace, leading to chunks with inconsistent formatting.
- Not handling chunks shorter than the chunk size when the text ends.
Variations
- Use tiktoken to split by token count instead of characters for LLM context limits.
- Use a sliding window with fixed step size for simpler, though less coherent, chunks.
Real-world use cases
- Preparing a large PDF corpus for a retrieval-augmented generation (RAG) Q&A chatbot by indexing chunks into a vector database.
- Splitting support ticket histories into chunks for semantic search where each chunk captures a complete incident description.
- Segmenting legal or compliance documents into overlapping sections so contract clauses remain searchable without losing context.
Sponsored
More from AI & LLM integration patterns
- Cache LLM Completions by Hashing the Prompt in Python easy
- Chain of Thought Prompting in Python: Step-by-Step Reasoning Demo easy
- Circuit Breaker Pattern in Python for LLM API Calls medium
- Cosine Similarity to Retrieve Top K Chunks in Python easy
- Demonstrate Prompt Injection Bypass in Python easy
- How to Accumulate Streamed Tokens into a Final String in Python easy
Keep learning
Related tutorials and quizzes for this topic.