QA Interview Hub · Knowledge base · Quizzes · Українська

AI › Prompts, RAG, tools, agents, MCP

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

Documents → chunkingcutting into chunks that keep structureEmbeddings → vector databasevector + metadata (version, access)Query → top-k chunksmost mistakes get lost hereChunks into the promptorder, boundaries, access rightsAnswer with sourcesgroundedness: does it rely on them
Figure 1. Most mistakes arise in retrieval: the model cannot use what it was not shown.

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

Retrieval

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.

Generation

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.

Figure 2. First find out whether the needed chunk was in the context. What to fix depends on that.

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.

In an interview. Junior: RAG finds document chunks, adds them to the prompt and the model answers from them. Retrieval and the answer are tested separately. Middle/Senior: For a wrong answer I first look at the logged context: if the needed chunk is missing it is retrieval (chunking, embeddings, k, metadata), if it is there it is generation. I measure retrieval on a labelled set (hit rate and recall@k) and the answer by faithfulness and answer relevance. I filter access rights before the model and test them separately, and I treat chunk content as data, because indirect prompt injection is possible.

More articles in this chapter