RAG: embeddings, chunking, retrieval
RAG finds relevant document chunks and adds them to the context, so the model answers from current or private data without retraining. Documents are split into chunks, turned into vectors and the top-k nearest are returned for a query. Retrieval and generation are evaluated separately, and for a wrong answer you check the logged context first. Access rights are filtered at the retrieval step.
AI for QA · Agents and RAG
The bot quotes a return policy that was cancelled last year. Is the model to blame or the retrieval?
A help bot answers that a return is possible within 30 days, and the policy changed last year. The tester files a "model makes things up" bug, but the prompt the model saw did contain exactly the old article. The model answered honestly from what it was shown. In RAG systems the answer depends on two separate parts, retrieval and generation, and they must be told apart, otherwise the error is treated in the wrong place.
How it works and why. RAG (retrieval-augmented generation) gives a model current or private data without retraining: the system finds relevant document chunks and adds them to the context. This answers two problems: the model does not know your documents, and a long window with all the documents is expensive and uneven in quality (see the lesson on the context window). The pipeline is in the figure.
The RAG pipeline and where it breaks
Chunking. A document is cut into chunks that fit the context and carry complete meaning. Too small ones lose context ("30 days" without the thing it is about), too large ones blur the match and spend tokens. Usually the cut follows structure (headings, paragraphs), adds a small overlap between neighbouring chunks and stores metadata: document, section, version, access rights.
Embeddings. A model turns text into a vector so that texts close in meaning have close vectors. The query is turned into a vector the same way, and the vector database returns the top-k nearest chunks. Closeness in meaning is not the same as a word match: that is a strength (synonyms) but also a weakness (an article number or an exact name may be found worse than by keyword search). So vector and keyword search are often combined (hybrid search).
Example: analysing a wrong answer. For the return question you log everything that went to the model: the list of chunks, their documents, versions and similarity scores. The diagnosis is then simple and separates two cases:
Where to look at a wrong answer
The needed chunk is not in top-k
Symptom: the logged context has no answer. Causes: chunking, embeddings, small k, a metadata filter. Fix retrieval.
The chunk is there, the answer is wrong
Symptom: the answer is in the context, but the model ignores or mixes it up. Causes: prompt, order, noise. Fix the prompt and the context.
In our story the 2023 article got into top-k and the fresh version did not: the old one is closer in wording, and version metadata is not used in retrieval. This is a retrieval error, not a model error. The fix: remove outdated documents from the index or filter by version, and update the index when the source changes. To catch such errors systematically, retrieval is measured separately from the answer on a labelled set:
type Case = { question: string; relevantDocIds: string[] };
// share of questions where top-k has at least one needed document
async function hitRateAtK(cases: Case[], k: number) {
let hits = 0;
for (const c of cases) {
const chunks = await retrieve(c.question, k);
const ids = chunks.map((ch) => ch.docId);
if (c.relevantDocIds.some((id) => ids.includes(id))) hits++;
}
return hits / cases.length;
}
For each question in the set the documents holding the answer are labelled. The function shows how the share of found documents changes with another chunk size, another k or another embedding model. This is a simplified measure: full recall@k takes the share of found among all relevant documents, and precision@k the share of relevant among the returned. For the model's answer, faithfulness (does the answer rely only on the provided chunks) and answer relevance (does it answer the question) are measured, usually by a judge with a rubric.
Access rights. A separate risk class: a user must not receive a chunk of a document they have no access to. Filter by rights at the retrieval stage, and do not ask the model "not to disclose": whatever reached the context, the model can quote.
test('an employee does not see a foreign HR document', async () => {
const chunks = await retrieve('salary bands', 5, { user: 'support-agent' });
expect(chunks.map((c) => c.docId)).not.toContain('hr-salary-bands');
});
Limits and alternatives. RAG does not make answers true: the model can ignore the found context or mix it with its own "knowledge". A found document can itself contain instructions ("ignore previous rules"): that is indirect prompt injection, so the content of chunks is treated as data, not commands. Other approaches: a long context for a small knowledge base, fine-tuning for style or format (not for current facts) and plain search with citations and no generation.
Common mistakes.
- Evaluating only the final answer. Consequence: it is not visible whether retrieval or generation is to blame.
- Not updating the index when documents change. Consequence: the bot quotes outdated content.
- One chunk size for all documents. Consequence: tables and long instructions are cut in the middle of their meaning.
- Checking access rights after retrieval, in the answer. Consequence: a foreign chunk in the context and in the answer.
- Not testing questions with no answer in the base. Consequence: instead of "I do not know" the bot makes something up.
Check yourself
The bot answered wrongly. The logged context has the correct paragraph, but the answer ignores it. What do you fix, retrieval or generation, and what do you try?
Answer
Generation. Retrieval did its job. Try the prompt (a requirement to rely only on the context and cite), the order and number of chunks (noise distracts) and an example of refusing when the context has no answer. Measure the result on a labelled set.
After the chunk size was reduced, the share of found needed documents grew, but the answers got worse. How is that possible?
Answer
Small chunks match the query more precisely but lose context: the chunk "within 30 days" does not say what it is about. Retrieval improved while generation got incomplete context. That is why retrieval and the answer are measured separately and together.
How do you check that the bot does not disclose a document the user has no rights to?
Answer
A case at the retrieval level: ask, as a user without rights, about the content of the restricted document and check that its chunks are not among the returned ones, not only absent from the answer text. Add a case with a rephrased bypass and one with an indirect injection in an accessible document.