Advanced RAG
When basic RAG is not good enough, the fix is almost always in retrieval, not in the model. First build a retrieval test set and find out why the right chunk is missing. Then add only what the failures ask for: hybrid search (keywords and vectors, joined with RRF) for codes and rare words, a reranker to pick the best few from many candidates, query rewriting for follow-up questions, and chunks that carry their context. Every step adds time and cost, so measure the gain of each one.
Author: bezzad
Contents
The problem: 7 out of 10 is not enough
The help assistant uses basic RAG: embed the question, take the top 5 chunks, answer. The team wrote 120 real questions with the correct article for each. The right chunk is in the top 5 for only 71% of them. Reading the failures shows four kinds:
- Codes: “Is the KX-200 blender dishwasher safe?” The manual of the KX-200 is not found; manuals of other blenders are.
- Follow-ups: “And what about the blue one?” Alone, this question means nothing.
- Lost context: the chunk says “Clean the jar by hand”, but it does not say which product. Its vector does not match the product name.
- Near misses: the right chunk is number 9. The top 5 has three copies of the same general cleaning text.
A bigger language model fixes none of these. The model never sees the right chunk.
Step zero: measure retrieval
- A test set: real questions (from logs, with personal data removed), each with the ids of the chunks or articles that answer it. Start with 50 to 100. Add every new failure you find.
- Recall at k: how often the right chunk is in the top k. Measure k = 5, 20 and 50. If it is in the top 50 but not the top 5, ranking is the problem (a reranker helps). If it is not even in the top 50, the search itself is missing it (hybrid search or better chunks help).
- Group the failures by kind, like the list above. Fix the biggest group first.
- Run the set on every change, like unit tests.
Hybrid search: keywords and vectors together
Embeddings are good at meaning and weak at exact tokens like “KX-200”. Classic keyword search (full-text search, BM25) is the opposite. Run both, and join the two ranked lists.
The usual way to join is reciprocal rank fusion (RRF). It uses only the rank, not the scores, so you do not need to compare a cosine score with a keyword score:
static List<int> Fuse(IReadOnlyList<int> vectorIds, IReadOnlyList<int> keywordIds, int k = 60)
{
var score = new Dictionary<int, double>();
foreach (var list in new[] { vectorIds, keywordIds })
for (int rank = 0; rank < list.Count; rank++)
score[list[rank]] = score.GetValueOrDefault(list[rank]) + 1.0 / (k + rank + 1);
return score.OrderByDescending(p => p.Value).Select(p => p.Key).ToList();
}
- k = 60 is the value from the paper that introduced RRF, and a common default. It makes the top ranks matter more, but not too much.
- In PostgreSQL, the keyword side can be built-in full-text search next to pgvector. Many search engines (Elasticsearch, OpenSearch, Azure AI Search) have hybrid search built in.
- Persian needs care: PostgreSQL has no Persian stemmer, so a simple configuration (no stemming) is a common start. Measure it.
Reranking: many candidates, few winners
An embedding search compares the question vector with chunk vectors that were made separately. A reranker (often a cross-encoder model) reads the question and one chunk together and gives a relevance score. It is much more accurate, and much slower, so we use it only on a short list.
- Retrieve 30 to 50 with hybrid search.
- Rerank them, and keep the top 5 (or all above a score you measured).
- Watch the time: reranking 50 pairs adds tens to hundreds of milliseconds, depending on the model and hardware. Measure the 95th percentile.
- Do not use a big chat model as the reranker for 50 chunks one by one. It is slow and costly. Use a model made for reranking, hosted or local.
Query rewriting
Follow-up questions need the chat history. Before the search, ask a small, cheap model to write a standalone question:
string standalone = (await chat.GetResponseAsync(
[
new(ChatRole.System, "Rewrite the last user message as one standalone search question. Return only the question."),
.. history.TakeLast(6),
], cancellationToken: ct)).Text;
“And what about the blue one?” becomes “Is the blue KX-200 blender dishwasher safe?”. Search with this, but answer the customer’s real message.
Two more ideas, used only when the test set shows the need:
- Split a question with two parts (“price and delivery time of X”) into two searches.
- Several phrasings of the same question, searched and joined with RRF. Better recall, but more cost.
Chunks that carry their context
- Add a short header to each chunk before embedding: product name, article title, section. “KX-200 blender, Care, Cleaning: Clean the jar by hand.” Some teams ask a model to write one sentence of context for each chunk, once, at ingest time.
- Small to search, big to read: embed small chunks for exact matching, but send the whole parent section to the model.
- Remove near-duplicates from the final list, so 5 slots hold 5 different facts.
Every step has a price
| Step | Usually helps with | Cost |
|---|---|---|
| Hybrid search | Codes, names, rare words | A second index, a little time |
| Reranker | Right chunk is found but ranked low | Tens to hundreds of ms per question |
| Query rewriting | Follow-ups, chatty questions | One small model call per question |
| Chunk headers | Chunks that lose their subject | One-time ingest cost |
After each change, run the test set and write down recall at 5, answer quality, and time. Keep the change only if the numbers say so. In an interview, this “measure, then add” answer is worth more than a long list of tricks.
Common mistakes
| Mistake | Result | Right way |
|---|---|---|
| Changing the model when retrieval fails | More cost, same misses. | Measure recall at k first. |
| Adding every trick at once | Slow, costly, and no idea what helped. | One change at a time, measured. |
| Joining vector and keyword scores by adding them | One scale wins by accident. | Use ranks (RRF), or tune weights on the test set. |
| A big chat model reranks 50 chunks | Seconds of delay. | A rerank model on a short list. |
| Searching the follow-up as it is | “The blue one” finds nothing useful. | Rewrite into a standalone question. |
Summary in six lines
- Fix retrieval before the model: build a test set and measure recall at 5, 20 and 50.
- Hybrid search joins keyword and vector results; RRF uses ranks, so scales do not matter.
- A reranker reads question and chunk together; use it on a short list.
- Rewrite follow-ups into standalone questions before searching.
- Give chunks their context with headers, and remove near-duplicates.
- Every step costs time and money; keep only what the numbers support.