[KongchangAI]
· 5 min read· 2,518 words

Advanced RAG in Practice: Chunking, Hybrid Retrieval, and Reranking

Advanced RAG in Practice: Chunking, Hybrid Retrieval, and Reranking

A systematic walkthrough of the complete RAG optimization path from basic retrieval to reranking, query rewriting, hybrid retrieval, and agentification.

Using a fictional company employee handbook as the test document, the article connects RAG's core optimization techniques by conceptual logic. It compares fixed-size and recursive chunking, explains contextual enrichment, reranking with cross-encoders, query rewriting for multi-turn scenarios, hybrid retrieval with RRF, and wrapping retrieval as an Agent tool, ending with evaluation and multimodal retrieval and practical recommendations.

Why Basic RAG Isn't Enough

The simplest RAG (Retrieval-Augmented Generation) pipeline is three steps: embed documents into vectors, run a similarity search with the question vector, and stuff the most similar text chunk into the LLM's context. The demo at the start of the video does exactly this—a list full of single-line facts, ask "what's my dog's name," a vector dot product finds "my dog's name is Max," and the answer comes out.

But real-world scenarios are rarely this friendly. We deal with hundreds of pages of PDFs, complex Markdown manuals, and documents with tables. Here you hit several unavoidable problems: the entire document won't fit in the context window; chunking too finely breaks semantics; chunking too coarsely hurts retrieval accuracy; and the highest-similarity chunk may not actually answer the question. This video uses a fictional company employee handbook (about 3,000 words, covering vacation, reimbursement, product info, etc.) as the test document and walks through the technical paths for solving these problems one by one.

Each technique comes with a code demo and before/after comparison. This article reorganizes them by conceptual logic to make the "why" and the "how" clear.

Chunking Strategies: From Fixed-Size to Recursive Splitting

Fixed-Size Chunking

The most intuitive approach: set a chunk size (say 500 characters) and an overlap (say 100 characters). Cut every 500 characters, then step back 100 characters as the start of the next chunk. The point of overlap is to avoid splitting sentences in half—if "robot W" and "requires extensive manual setup" end up in two separate chunks, both read like gibberish on their own.

for i in range(0, len(text), chunk_size - overlap):
    chunks.append(text[i:i + chunk_size])

At retrieval time, embed the question, take the dot product with every chunk vector, and use the highest-similarity chunk as context. In the demo, asking "how many vacation days do I have" retrieves a chunk that happens to contain "each employee gets 25 days of vacation per year," and the answer is correct.

But the problems are obvious: the retrieved chunk may contain only half a sentence, and the model has to guess.

Code demo: reading a file and defining chunk_size and overlap parameters

Recursive Chunking

A more sensible default is to recursively split along the document's natural structure: first by level-one headings, and if a section is still too long, by level-two headings, then by paragraphs, and only as a last resort by sentences. The code defines a separator list ["\n## ", "\n### ", "\n\n", ". "], and a recursive function checks whether the current text exceeds the length limit and, if so, moves to the next finer separator and continues splitting.

The before/after comparison is striking: for the same vacation question, fixed-size chunking returns text truncated mid-sentence, while recursive chunking returns the complete "4.2 Vacation and Leave" subsection. A logically complete chunk is naturally easier for the model to understand accurately.

Semantic Chunking

The video only introduces the concept: keep merging new sentences into the current chunk until the similarity between the new sentence and the current chunk drops below a threshold, then start a new chunk. This sounds elegant, but in practice it's costly to implement and unstable in results. The author's advice: if you're unsure, use recursive chunking.

Semantic chunking illustration: start a new chunk only when similarity drops

Contextual Enrichment: Giving Each Chunk Its "Where Am I"

Fixed-size chunking has a hidden problem: a piece of text may be completely unintelligible on its own. For example, a chunk says "what percentage of revenue is hardware versus software," but you don't know whether this is 2022 or 2023 data—because the year is written in the parent heading.

Contextual enrichment works like this: feed the entire document or section to a small model (the video uses Haiku) and have it generate one or two sentences of "positioning description" for each chunk, then prepend that description to the chunk before embedding. The prompt is roughly: "Given the full section and one passage within it, use one or two sentences to explain this passage's position and context within the section. Output only these two sentences."

The comparison case in the demo is telling. When asked "which product is Daniel Okafor responsible for," the normal chunk's retrieval result is "the provided context does not mention Daniel Okafor"—because although the retrieved chunk is relevant, it lacks the complete information from the paragraph where the name appears. The enriched chunk, however, begins with a positioning sentence like "This passage belongs to section X, which describes the product team's division of labor," so retrieval hits directly and the model answers "Daniel Okafor is the product lead for the Atlas T-300."

The cost is one extra LLM call per chunk, which needs to be considered when the document volume is large.

Reranking: Using a More Expensive Model for the Final Selection

Vector retrieval is fundamentally about using a bi-encoder to encode the question and documents separately. It's fast but limited in precision. A cross-encoder concatenates the question and document and runs them through the model together, capturing fine-grained semantic matching, but it can't pre-encode all documents—every query requires recomputation, which is infeasible at scale.

The compromise is reranking: first use vector retrieval to recall the top-10 candidates, then use a cross-encoder to rescore and reorder those 10 candidates. The video implements this with FastEmbed's TextCrossEncoder, using the model ms-marco-MiniLM-L6-v2.

In the demo, asking "what does error code E-217 mean," pure vector retrieval returns a top-1 chunk about E-001, and the model answers "E-217 is not defined in the context." After reranking, the top-1 chunk correctly points to the explanation about battery cell imbalance, and the answer is accurate.

One implementation detail is worth noting: reranker.rerank() returns a generator, so you must convert it with list(). Otherwise, indexing 0 every time gets you the first item, and reranking does nothing.

Reranking comparison experiment: verifying the difference using only the top-1 result

Bi-encoder vs. Cross-encoder

A bi-encoder maps the question and document through the same or two separate encoders into fixed-dimensional vectors, and similarity is computed via dot product or cosine distance. Because document vectors can be precomputed offline and indexed (e.g., HNSW), at query time you only need to encode the question and perform a nearest-neighbor search, giving very low latency and strong scalability. But there is no interaction between question and document during encoding, so fine-grained matching information is lost.

A cross-encoder concatenates the question and document into a single input sequence and feeds it into a Transformer for joint encoding, outputting a relevance score. Because the attention mechanism allows direct interaction between question terms and document terms, it can capture precise correspondences like "E-217" and "error code E-217," with significantly higher precision. However, each (question, document) pair requires a forward pass and cannot be precomputed, making scoring the entire corpus infeasible—so it's only suitable for fine-ranking a small number of candidates. Reranking exploits their complementarity: the bi-encoder handles high recall, and the cross-encoder handles high precision.

Query Rewriting: Compressing Conversation History into a Standalone Question

In multi-turn conversations, user questions often depend on context. The user first asks "can I get a laptop," the assistant answers "yes, a MacBook Pro," and then the user asks "how often is it replaced." Running vector retrieval directly on "how often is it replaced" will inevitably yield poor results.

Query rewriting works like this: give the conversation history and the latest question to the LLM and ask it to rewrite the last user message into a standalone question that doesn't depend on context. The prompt in the video is "Rewrite the last user message into a standalone question, output only the question itself," and the rewritten result is "how often are laptops replaced."

The comparison is dramatic: without rewriting, the retrieved chunk is unrelated to the question, and the model can only answer "I don't know." After rewriting, it accurately hits the passage "company laptops are replaced every three years, and employees can buy old devices at a discount."

This step costs almost nothing extra (one small-model call) but greatly improves the multi-turn RAG experience—an extremely cost-effective optimization.

Metadata Filtering and Hybrid Retrieval

Metadata Filtering

When writing to the vector database, you can attach structured metadata alongside the vector itself. The video demonstrates with Qdrant: each point's payload stores the chunk text and the section title it belongs to. At query time you can add hard filters, for example restricting retrieval to "Section 7 Customer Support and Warranty."

The use case is clear: when you know the intent scope of the current query (e.g., the user is on a particular feature page), you can use metadata to narrow the retrieval space and avoid recalling chunks that are vector-similar but off-topic.

Hybrid Retrieval

Dense vectors excel at semantic matching but may be insensitive to exact keywords (product models, error codes, proper nouns). Sparse retrieval (BM25) is based on term frequency statistics and fills exactly this gap. Qdrant supports configuring both dense and sparse vectors in the same collection, executing both retrieval paths in parallel at query time and merging results with RRF (Reciprocal Rank Fusion).

In the demo, asking "what is the SC-50 part used for," pure dense retrieval answers "the context does not mention SC-50," while hybrid retrieval correctly hits "SC-50 is the suction cup for the gripper." The author also acknowledges that this is a cherry-picked example and hybrid retrieval isn't always better, but it has a clear advantage on queries containing exact model numbers.

BM25 sparse retrieval: a simple but effective complement based on term frequency

RRF (Reciprocal Rank Fusion)

RRF is a rank fusion method that requires no training and no score normalization. For each document, its rank in each retrieval path is rank_i, and the fused score is Σ 1/(k + rank_i), where k is a smoothing constant (commonly 60).

RRF's advantage is that it relies only on ranks rather than raw similarity scores, avoiding the score normalization problem when directly weighting dense vector cosine similarity (typically between 0 and 1) with BM25 scores (unbounded, different scale). Documents ranked higher get more weight, and documents that rank high across multiple paths are significantly boosted. In Qdrant, you can use Prefetch to execute dense and sparse queries separately, then merge with Fusion.RRF, completing hybrid retrieval in a single request.

Turning Retrieval into an Agent Tool

Some questions can't be answered with a single retrieval. For example, "what's the hotel reimbursement cap for the city where our newest office is located" requires first finding which city the newest office is in, then looking up that city's reimbursement standard.

The approach is to wrap the retrieval function as a tool: define a search(query) function that returns the text of the top-3 chunks, then register it in the Anthropic SDK's tools list, declaring the parameter as a query string. The Agent automatically decides how many times to call it and what arguments to pass each time. In the demo, the Agent makes three consecutive retrieval calls—"newest office location," "third office opening date," and "Austin office hotel limit"—and finally assembles the complete answer.

The value of this pattern: retrieval is no longer a one-off fixed pipeline but a capability unit that the Agent can orchestrate autonomously.

Evaluation and Multimodal Retrieval

Simple Evaluation

The video offers a minimalist retrieval evaluation method: prepare a test set where each entry contains a question and a piece of "source text that must appear in the retrieval results," then use string matching to determine hits. For example, ask "what does error E-104 mean," and the ground truth is that exact sentence from the manual; a retrieved chunk counts as a hit as long as it contains that string.

Using this method to compare hit rates between dense retrieval and reranking, reranking performs better in the demo. Of course, the author notes that proper evaluation should use frameworks like LLM-as-judge or RAGAS.

RAGAS and LLM-as-judge Evaluation Frameworks

RAGAS (Retrieval Augmented Generation Assessment) is an automated evaluation framework for RAG systems. Its core metrics include faithfulness (whether the answer is entirely grounded in the retrieved context, used to detect hallucinations), answer relevancy, context precision (whether relevant chunks are ranked higher), and context recall (whether the information needed for the ground-truth answer was retrieved). It typically uses an LLM as a judge to score each sample and then aggregates into system-level metrics.

LLM-as-judge is a more general paradigm: given the question, retrieved context, and model answer, a more capable LLM judges answer quality according to predefined scoring criteria. Compared with string matching, it can handle semantically equivalent but differently worded cases, making it better suited to open-ended QA. The cost is higher evaluation expense, and the judge model itself has biases that need to be calibrated with human-annotated samples.

Multimodal Retrieval

When the knowledge base contains images (e.g., product dimension diagrams), you can encode images with an image embedding model and questions with a text embedding model, then perform similarity retrieval in the same vector space. The prerequisite is that the two models are aligned—same family or same dimensionality.

In the demo, asking "how tall is the Atlas T-300," retrieval hits the "robot dimensions" image; the image is base64-encoded and passed to Claude as image content, and the model reads "32 centimeters" from the image.

Beyond These Techniques

The video ends by mentioning several advanced directions: Graph RAG (using knowledge graphs to enhance retrieval), professional evaluation with RAGAS, and having the model cite sources in its answers. The author's view is that RAG technology itself has covered most core concepts by this point; going further is more about engineering concerns around deployment, observability, and MLOps.

Advice for practitioners: use recursive chunking as the default starting point, prioritize adding reranking and query rewriting (low cost, clear benefits), configure hybrid retrieval in domains dense with terminology, and choose contextual enrichment and metadata filtering based on the scenario.

One-line Summary

A systematic walkthrough of the complete RAG optimization path from basic retrieval to reranking, query rewriting, hybrid retrieval, and agentification.

Paragraph Summary

Using a fictional company employee handbook as the test document, the article connects RAG's core optimization techniques by conceptual logic. At the chunking level, it compares fixed-size splitting with recursive splitting, noting that splitting progressively along document structure preserves complete semantic units, while semantic chunking is not recommended as a default due to high cost and instability. Contextual enrichment uses an LLM to generate positioning descriptions for each chunk before embedding, solving the problem of chunks losing meaning when detached from their sections. Reranking uses a cross-encoder to fine-rank vector-recalled candidates, clearly outperforming pure vector similarity on precise queries like error codes. Query rewriting compresses questions that depend on conversation history into standalone questions—a low-cost, high-benefit technique in multi-turn scenarios. Hybrid retrieval combines dense vectors with BM25 and fuses them with RRF, especially effective for product models and proper nouns. Finally, it covers wrapping retrieval as an Agent tool, simple hit-rate evaluation, and multimodal image retrieval, and offers practical advice: start with recursive chunking and prioritize adding reranking and query rewriting.

#RAG#retrieval-augmented generation#chunking#hybrid retrieval#reranking#query rewriting#Qdrant#cross-encoder
Share:

Related articles