RAG Chunking Evaluator
Prerequisites & Dependencies
- Python 3.10+ with
pip install langchain openai tiktoken
- Access to an LLM API key (OpenAI, Anthropic, or similar) for generating test embeddings
- A sample document corpus (PDFs, txt files, web pages) to analyze
- Optional:
pip install mlflow for experiment tracking
Execution Steps
- Load the document corpus and split into individual pages or sections
- Tokenize each section using
tiktoken with the target model's encoder (e.g., gpt-4o or gpt-4-turbo)
- Experiment with chunking strategies:
- Fixed-size chunks: constant token count (e.g., 256, 512, 1024 tokens)
- Recursive character splitting: break on paragraphs, sentences, words with overlap
- Section-aware splitting: respect headings, tables, and code blocks as natural boundaries
- For each strategy, generate embeddings via the LLM API and index into a vector store (Chroma, Pinecone, Qdrant)
- Retrieve test queries and measure retrieval metrics:
- Recall@k: percentage of relevant documents found in top-k results
- Precision@k: percentage of retrieved documents that are relevant
- Answer accuracy: end-to-end QA correctness using the retrieved context
- Tune overlap ratios (typically 10–25% of chunk size) to minimize information loss at boundaries
- Document the optimal strategy and produce a config file (
chunk_size, overlap, splitter_type) for production RAG pipelines
# Example: Recursive chunking with tiktoken and overlap
import tiktoken
from langchain.text_splitter import RecursiveCharacterTextSplitter
enc = tiktoken.get_encoding("cl100k_base") # gpt-4o encoding
def count_tokens(text):
return len(enc.encode(text))
def chunk_documents(documents, chunk_size=512, chunk_overlap=60):
splitter = RecursiveCharacterTextSplitter(
chunk_size=chunk_size,
chunk_overlap=chunk_overlap,
separators=["\n\n", "\n", " ", ""],
)
chunks = []
for doc in documents:
chunks.extend(splitter.split_text(doc))
return chunks
documents = [
"""Artificial Intelligence (AI) refers to the simulation of human intelligence processes by computer systems. These processes include learning, reasoning, and self-correction. ...""",
"""Machine Learning (ML) is a subset of AI that focuses on the development of algorithms that allow computers to learn from data ...""",
]
chunks = chunk_documents(documents, chunk_size=300, chunk_overlap=50)
print(f"Total chunks generated: {len(chunks)}")
for i, c in enumerate(chunks[:3]):
print(f"Chunk {i}: {count_tokens(c)} tokens – {c[:60]}...")
pip install langchain openai tiktoken
python rag_chunking.py
1---2name: rag-chunking-evaluator3description: Analyze document structures to recommend optimal chunking strategies and overlap ratios for RAG pipelines.4---56# RAG Chunking Evaluator78## Prerequisites & Dependencies9- Python 3.10+ with `pip install langchain openai tiktoken`10- Access to an LLM API key (OpenAI, Anthropic, or similar) for generating test embeddings11- A sample document corpus (PDFs, txt files, web pages) to analyze12- Optional: `pip install mlflow` for experiment tracking1314## Execution Steps151. Load the document corpus and split into individual pages or sections162. Tokenize each section using `tiktoken` with the target model's encoder (e.g., `gpt-4o` or `gpt-4-turbo`)173. Experiment with chunking strategies:18 - **Fixed-size chunks**: constant token count (e.g., 256, 512, 1024 tokens)19 - **Recursive character splitting**: break on paragraphs, sentences, words with overlap20 - **Section-aware splitting**: respect headings, tables, and code blocks as natural boundaries214. For each strategy, generate embeddings via the LLM API and index into a vector store (Chroma, Pinecone, Qdrant)225. Retrieve test queries and measure retrieval metrics:23 - **Recall@k**: percentage of relevant documents found in top-k results24 - **Precision@k**: percentage of retrieved documents that are relevant25 - **Answer accuracy**: end-to-end QA correctness using the retrieved context266. Tune overlap ratios (typically 10–25% of chunk size) to minimize information loss at boundaries277. Document the optimal strategy and produce a config file (`chunk_size`, `overlap`, `splitter_type`) for production RAG pipelines2829```python30# Example: Recursive chunking with tiktoken and overlap31import tiktoken32from langchain.text_splitter import RecursiveCharacterTextSplitter3334enc = tiktoken.get_encoding("cl100k_base") # gpt-4o encoding3536def count_tokens(text):37 return len(enc.encode(text))3839def chunk_documents(documents, chunk_size=512, chunk_overlap=60):40 splitter = RecursiveCharacterTextSplitter(41 chunk_size=chunk_size,42 chunk_overlap=chunk_overlap,43 separators=["\n\n", "\n", " ", ""],44 )45 chunks = []46 for doc in documents:47 chunks.extend(splitter.split_text(doc))48 return chunks4950documents = [51 """Artificial Intelligence (AI) refers to the simulation of human intelligence processes by computer systems. These processes include learning, reasoning, and self-correction. ...""",52 """Machine Learning (ML) is a subset of AI that focuses on the development of algorithms that allow computers to learn from data ...""",53]5455chunks = chunk_documents(documents, chunk_size=300, chunk_overlap=50)56print(f"Total chunks generated: {len(chunks)}")57for i, c in enumerate(chunks[:3]):58 print(f"Chunk {i}: {count_tokens(c)} tokens – {c[:60]}...")59```6061```bash62pip install langchain openai tiktoken63python rag_chunking.py64```