# How to Build a Minimal RAG Pipeline

> How to build a minimal RAG pipeline in five steps, what each part does and how to test it, explained simply for your AI interview.

**In short:** A minimal RAG (retrieval-augmented generation) pipeline cuts your documents into chunks, stores them as searchable numbers, finds the closest chunks for each question, and sends them to the model with numbered sources. Code then checks that every cited source was really sent.

AI and LLM interview question Q155, Retrieval-augmented generation (RAG). Intermediate, very common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/build-a-minimal-rag-pipeline

## Say it in 30 seconds

A minimal RAG pipeline has five steps. I cut the documents into chunks, turn each chunk into numbers and store them. For a question, I find the closest chunks, put them in the prompt with numbers, and have the model answer only from them. Last, my code checks that every cited number was really sent. I test it on real questions from the desk before anyone relies on it.

## Say it in 2 minutes

Picture a claims team with a 400-page handbook and a new handler who must answer questions from it. I would build a helper in five steps. First I cut the handbook into chunks, one rule or section each, so a search can return just the right part. Then I turn each chunk into numbers that describe its meaning, and I store them in an index.

When a handler asks whether a rented flat is covered for flood damage, the code turns the question into the same kind of numbers and finds the closest chunks. It puts those chunks in the prompt, numbered, and tells the model to answer only from them and cite the numbers. The model writes the answer.

Then my code checks the citations. If the answer cites a number that was never sent, the answer is blocked. That check is cheap. It only shows that the citation points at a sent source. It does not show that the source says what the answer claims. The minimal version also skips reranking (a second pass that re-scores the chunks), metadata filters (rules such as only this year's policies) and a separate vector database, because one handbook does not need them yet.

The real test is a set of questions from the desk, each with its right section known in advance. I measure whether the right chunk is found, and whether the answer uses only it. Only when those numbers are steady do I add the next layer.

## What is a minimal RAG pipeline, in plain words?

RAG stands for retrieval-augmented generation. It means the model reads material you hand it at question time, instead of answering only from what it learned in training. A 2020 paper by Patrick Lewis and colleagues uses the phrase in its title: "Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks".

A minimal pipeline is the smallest chain of steps that gets from your documents to a sourced answer. Think of a new claims handler on day one. You give them a binder of rules and say: answer only from it, and give the page number. The pipeline is the set of steps that finds the right page and hands it over.

The key idea is the vector: a list of numbers that stands for what a piece of text means. Texts about the same thing get numbers that sit close together, so a search can match a question to a rule that uses different words.

The prompt is the text you send the model: your rules, the numbered sources and the question.

- **Chunk:** A section of a document, small enough to search and to fit in a prompt.
- **Vector:** A list of numbers that stands for what a text means.
- **Embedding model:** The AI model that turns a piece of text into a vector.
- **Index:** The stored chunks and their vectors, ready to search.
- **Retrieve:** Find the chunks closest to the question and hand them over.

## What are the five steps, in order?

Build it in this order. Each step is small, and each one can be tested on its own.

*Diagram, The five steps, from handbook to answer: Cutting and indexing run once, when the handbook changes. Searching, prompting, answering and checking run for every question. The numbers on the arrows match the key under the chart.*
1. The handbook is cut into sections, one rule per chunk.
2. Each chunk is turned into numbers and stored in the index.
3. The search compares the stored chunks with the question.
4. The handler's question is the search's input.
5. The closest two chunks go into a numbered prompt.
6. The model writes an answer from those sources only.
7. Code checks that each cited number was really sent.
8. Only checked answers reach the handler.

1. **Cut the documents into chunks:** Split the handbook by section, so each chunk holds one rule. Keep the section title with it, so the handler can find it again.
2. **Turn each chunk into a vector:** In a real build, an embedding model does this and stores the numbers with the chunk text. The code below uses word counts, so it runs with no network.
3. **Retrieve the closest chunks:** Turn the question into the same kind of numbers, then pick the two chunks that sit closest. For this three-chunk demo, two is enough. A real build should test the number, because Anthropic's contextual retrieval article found that passing the top-20 chunks beat the top-10 or top-5.
4. **Build a numbered prompt:** Put the chunks in the prompt as [1] and [2]. Tell the model to answer only from them and to cite the numbers.
5. **Let the model write, then check its citations:** The model writes the answer. Code then checks that every cited number was really sent, and blocks the answer if not. Also require at least one citation.

## How does one question travel through it?

A handler asks "Is a rented flat covered for flood damage?" The question becomes numbers, and the search compares it with the three chunks. The flood section scores highest. The escape-of-water section comes second, and only because it shares the small words "a" and "for". That weak match is a warning sign, and a real embedding model may score it differently.

The code builds the prompt and prints it first. Each line does one job, and the last two lines are the citation check.

```python
# A minimal RAG pipeline, no network: word counts stand in for embeddings.
import math
import re
from collections import Counter

HANDBOOK = [  # made-up claims handbook: one section per chunk
    "Flood cover: a rented flat is covered for contents only, up to 15,000 pounds, if the tenant holds a policy.",
    "Escape of water: landlords must report a leak within 72 hours to claim for the repairs.",
    "Storm damage: roof repairs need two quotes from approved contractors before any work starts.",
]
vec = lambda text: Counter(re.findall(r"[a-z]+", text.lower()))
cos = lambda a, b: sum(a[w] * b[w] for w in a) / (math.hypot(*a.values()) * math.hypot(*b.values()))
INDEX = [(chunk, vec(chunk)) for chunk in HANDBOOK]  # index: chunk and its vector

def retrieve(question, k=2):
    q = vec(question)
    return [c for c, v in sorted(INDEX, key=lambda i: cos(q, i[1]), reverse=True)[:k]]

def build_prompt(question, chunks):
    sources = "\n".join(f"[{i}] {c}" for i, c in enumerate(chunks, 1))
    return f"Answer only from the sources and cite them as [n].\n{sources}\nQuestion: {question}"

question = "Is a rented flat covered for flood damage?"
chunks = retrieve(question)
print(build_prompt(question, chunks))

# A made-up model answer: check that every cited number was really sent.
answer = "Contents are covered up to 15,000 pounds [1][3]."
cited = {int(n) for n in re.findall(r"\[(\d+)\]", answer)}
print("Bad citations:", sorted(cited - set(range(1, len(chunks) + 1))))
```

Output:

```text
Answer only from the sources and cite them as [n].
[1] Flood cover: a rented flat is covered for contents only, up to 15,000 pounds, if the tenant holds a policy.
[2] Escape of water: landlords must report a leak within 72 hours to claim for the repairs.
Question: Is a rented flat covered for flood damage?
Bad citations: [3]
```

The made-up answer cites [1] and [3], but only two sources were sent. The check finds the bad number and prints it. In a real build the model writes that answer, and the same check runs on it.

Anthropic's article on contextual retrieval says: "Sometimes the simplest solution is the best." It adds that a knowledge base under 200,000 tokens (about 500 pages) can go straight into the prompt with no RAG at all. So check first whether the handbook fits. If it does not, start with this small pipeline, measure it, and add a layer only when the numbers ask for it.

## Which parts are hard, even in a small build?

Three parts cause most of the trouble, and each one looks easy at first.

> "Anthropic does not offer its own embedding model." (Anthropic, embeddings guide)
>
> "While you can see annotations (references to files) in the output text, the file search call will not return search results by default." (OpenAI, file search guide)

The first is chunking. Cut too small and a rule loses the line that says what it covers. Cut too big and the search returns noise. Cut on section headings where you can.

The second is the embedding model. Anthropic does not offer one, so you pick a vendor and test it on your own questions. Its guide tells readers to assess several vendors for their use case. Hosted tools such as OpenAI's file search do the search for you, which is convenient, but you then have to ask for the search results to see what was found.

The third is the answer. The model can still ignore the sources and write from memory. Microsoft's guide names groundedness, completeness, utilization and relevancy as things to measure in a response. In plain words: groundedness means the answer sticks to the sources, completeness means it covers the whole question, utilization means it uses the sources it was given, and relevancy means it answers what was asked.

> **Tip:** Say what you would measure before you say what you would build. Interviewers listen for that order.

## How do you stop a made-up citation?

The check is ordinary code. It does not need a second model. It reads each number in the answer and fails the answer if a number was never in the prompt. That rule stops an answer from citing a source number that was never sent. It does not prove the source says what the answer claims, so that still needs testing.

*Diagram, A made-up citation, caught in code: The model's draft cites [1] and [3], but only [1] and [2] were sent. The code finds the missing [3] and blocks the answer before the handler sees it.*
1. The draft goes to the check before anyone sees it.
2. If every number was sent, the answer goes out.
3. Here [3] was never sent, so the answer is blocked.

Some hosted tools help here. Anthropic's citations feature helps you track and verify the sources behind each response, and its docs say citations are guaranteed to contain valid pointers to the provided documents. Its docs also say document contents are chunked to define the smallest citable part.

### How would you take it to a live claims tool?

A minimal build is a start. A live tool needs four more things, and each one is a small step.

- **Log every question:** Keep the question, the sources sent and the answer. A bad answer can then be traced to the search or to the model.
- **Re-index when a rule changes:** An old copy of a rule gives an old answer. Re-index a section on the day its rule changes.
- **Respect access:** A handler should only search the rules they are allowed to see. Filter the chunks before they reach the prompt.
- **Keep the test set alive:** Add every live question that failed to the test set, then re-run the set after each change.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] A plain definition: find the right text, give it to the model, cite it.
- [ ] The five steps in order, and what each one does.
- [ ] Why the vector matters, and that the embedding model is a choice to test.
- [ ] The citation check in code, not a request in the prompt.
- [ ] A test set of real questions, measured before any new feature.
- [ ] Honest limits: chunk size, weak matches and a model that ignores sources.

**Common traps**

- Trap: "Put the documents in a vector database and the RAG is done." Better: The database only stores and searches vectors. Chunking, the prompt and the citation check are still yours to build.
- Trap: "The model cites its sources, so the answers are trustworthy." Better: A cited number can be made up. Only a check in code shows that every cited number was really sent.
- Trap: "Bigger chunks keep more context, so bigger is safer." Better: Bigger chunks bring noise and cost more to read. Test a few sizes on real questions.

## Can you spot the broken step?

**Spot the broken step:** Which line stops the answers coming from the handbook?

A. chunks = retrieve(question, k=2)
B. answer = call_model(question)  # no chunks sent
C. sources = [f'[{i}] {c}' for i, c in enumerate(chunks, 1)]
D. assert set(cited) <= set(range(1, len(chunks) + 1))

**Answer:** B. The second line sends no chunks, so the model answers from its training and has no source to cite. The other three find, number and check the sources.

**Quick check:** Your ten test questions get good answers, but live staff get poor ones. What should you do first?

A. Switch to a bigger model
B. Log the live questions with their sources, then add the failures to the test set
C. Ask the model to be more creative
D. Write a longer system prompt

**Answer:** B. Live failures show what your test set missed. The logged sources show whether search or the answer broke, and the new cases make the next test honest.

## Can you answer these from memory?

**Flash cards**

- **What is RAG?** Finding the relevant text and giving it to the model with the question.
- **What are the five steps?** Chunk, index, retrieve, build a numbered prompt, then check the citations.
- **What is a chunk?** A section of a document, small enough to search and to fit in a prompt.
- **What is a vector?** A list of numbers that stands for what a piece of text means.
- **Does Anthropic sell an embedding model?** No. You pick an embeddings vendor and test it on your own questions.
- **What is the first check to add?** Code that blocks any answer citing a number that was never sent.

## Likely follow-up questions

- Q112 Walk through a RAG pipeline end to end. https://designervenkat.online/interview/ai/rag-pipeline-end-to-end
- Q113 What is chunking, and why does size matter? https://designervenkat.online/interview/ai/what-is-chunking-in-rag
- Q117 What is a vector database? https://designervenkat.online/interview/ai/what-is-a-vector-database
- Q131 Retrieval metrics: recall@k, MRR, nDCG? https://designervenkat.online/interview/ai/retrieval-metrics-recall-at-k-mrr-ndcg
- Q132 Generation metrics: faithfulness, answer relevance? https://designervenkat.online/interview/ai/rag-generation-metrics-faithfulness-answer-relevance
- Q135 How do you add citations? https://designervenkat.online/interview/ai/how-do-you-add-citations

## Learn it in depth

- [Build RAG by hand](https://designervenkat.online/learn/ai-engineering/manual-implementation)
- [From question to context](https://designervenkat.online/learn/ai-engineering/retrieval-process)
