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.4metadata:5 source: skills/rag-chunking-evaluator/rag-chunking-evaluator.md6---78# RAG Chunking Evaluator910## Prerequisites & Dependencies11- Python 3.10+ with `pip install langchain openai tiktoken`12- Access to an LLM API key (OpenAI, Anthropic, or similar) for generating test embeddings13- A sample document corpus (PDFs, txt files, web pages) to analyze14- Optional: `pip install mlflow` for experiment tracking1516## Execution Steps171. Load the document corpus and split into individual pages or sections182. Tokenize each section using `tiktoken` with the target model's encoder (e.g., `gpt-4o` or `gpt-4-turbo`)193. Experiment with chunking strategies:20 - **Fixed-size chunks**: constant token count (e.g., 256, 512, 1024 tokens)21 - **Recursive character splitting**: break on paragraphs, sentences, words with overlap22 - **Section-aware splitting**: respect headings, tables, and code blocks as natural boundaries234. For each strategy, generate embeddings via the LLM API and index into a vector store (Chroma, Pinecone, Qdrant)245. Retrieve test queries and measure retrieval metrics:25 - **Recall@k**: percentage of relevant documents found in top-k results26 - **Precision@k**: percentage of retrieved documents that are relevant27 - **Answer accuracy**: end-to-end QA correctness using the retrieved context286. Tune overlap ratios (typically 10–25% of chunk size) to minimize information loss at boundaries297. Document the optimal strategy and produce a config file (`chunk_size`, `overlap`, `splitter_type`) for production RAG pipelines3031```python32# Example: Recursive chunking with tiktoken and overlap33import tiktoken34from langchain.text_splitter import RecursiveCharacterTextSplitter3536enc = tiktoken.get_encoding("cl100k_base") # gpt-4o encoding3738def count_tokens(text):39 return len(enc.encode(text))4041def chunk_documents(documents, chunk_size=512, chunk_overlap=60):42 splitter = RecursiveCharacterTextSplitter(43 chunk_size=chunk_size,44 chunk_overlap=chunk_overlap,45 separators=["\n\n", "\n", " ", ""],46 )47 chunks = []48 for doc in documents:49 chunks.extend(splitter.split_text(doc))50 return chunks5152documents = [53 """Artificial Intelligence (AI) refers to the simulation of human intelligence processes by computer systems. These processes include learning, reasoning, and self-correction. ...""",54 """Machine Learning (ML) is a subset of AI that focuses on the development of algorithms that allow computers to learn from data ...""",55]5657chunks = chunk_documents(documents, chunk_size=300, chunk_overlap=50)58print(f"Total chunks generated: {len(chunks)}")59for i, c in enumerate(chunks[:3]):60 print(f"Chunk {i}: {count_tokens(c)} tokens – {c[:60]}...")61```6263```bash64pip install langchain openai tiktoken65python rag_chunking.py66```