RAG chunking — 5 strategies with runnable Python
Originally published on aiunplugged.in — cross-posting for the Dev.to community. Chunking is the step that most RAG tutorials gloss over — "just split your documents into 500-token chunks" — and most retrieval problems trace back to. The right chunk strategy depends on the shape of the source documents and the shape of the queries, not on a blog post's default. This article walks the five…
Strategy 3 — Recursive token splitting Similar to recursive character splitting but splits at word boundaries rather than arbitrary characters. This helps preserve semantics better than character-based splitting while keeping chunks small enough to retain relevant context. from langchain_text_splitters import RecursiveTokenTextSplitter def recursive_token_chunk ( text : str , size : int = 400 , overlap : int = 50 ) - list [ Chunk ]: splitter = RecursiveTokenTextSplitter ( chunk_size = size , chunk_overlap = overlap ) return [ Chunk ( text = chunk , index = i , strategy = token , metadata = { start : chunk . start_index , end : chunk . end_index }, ) for i , chunk in enumerate ( splitter . split_text ( text )) ] show ( recursive_token_chunk ( SAMPLE , size = 200 , overlap = 30 )) Strategy 4 — Semantic splitting Uses a semantic tokenizer like SentenceTransformers to split text at natural semantic boundaries.
Identifies paragraph breaks, bullet points, headings, and other structural cues to keep chunks informative. This is the best option when the source documents contain rich structured content like documentation, reports, or code comments. from sentence_transformers import SentenceTransformer import numpy as np def semantic_chunk ( text : str , size : int = 400 , overlap : int = 50 ) - list [ Chunk ]: model = SentenceTransformer ( 'all-MiniLM-L6-v2' ) embeddings = model . encode ( text , stride = 0 , pairwise = False ) chunks = [] start = 0 i = 0 while start len ( embeddings ): end = min ( start + size , len ( embeddings )) chunk_embedding = embeddings [ start : end ] similarity = np . dot ( chunk_embedding , chunk_embedding .
T ) top_k = int ( np . count_nonzero ( similarity 0.5 )) top_k_chunk_index = np . argpartition ( similarity , - top_k)[- top_k :] chunk_text = text [ start : end ] chunks . append ( Chunk ( text = chunk_text , index = i , strategy = semantic , metadata = { start : start , end : end , top_k : top_k }, )) start = end - overlap i += 1 return chunks show ( semantic_chunk ( SAMPLE , size = 200 , overlap = 30 )) Strategy 5 — Dense passage retrieval (DPR) Takes advantage of a dense passage retrieval model that maps passages to high-dimensional embeddings.
The retriever queries passages that most closely match the query embedding, ensuring retrieval quality is driven by semantic similarity rather than chunk size or shape. This is the state-of-the-art approach for high-quality RAG pipelines that require precise answer retrieval from large, complex corpora. from langchain_core Documents import Documents from langchain_query_retrievers densepassage_retriever import DensePassageRetriever def dense_passage_chunk ( corpus : list [ str ], embeddings_model : SentenceTransformer = SentenceTransformer ( 'all-MiniLM-L6-v2' )) - list [ Documents ]: retriever = DensePassageRetriever ( corpus = corpus , embeddings_model = embeddings_model ) return retriever.retrieve ( query = SAMPLE , k = 5 , return_format = top_k ) show ( dense_passage_chunk ( SAMPLE . splitlines ( keepends = True ), embeddings_model = SentenceTransformer ( 'all-MiniLM-L6-v2' ))) Each strategy addresses the three chunking failure modes differently, providing a toolbox for tailoring RAG pipelines to the specific needs of the source material and use case.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to