AI & Automation
RAG Explained: How to Make AI Answer From Your Own Business Data
Retrieval-Augmented Generation is the most practical way to build a “ChatGPT for our company” without training a model. Here is how it works, how to build it, and the mistakes that sink most projects.
By Philip Mutuku · Published · Updated · 6 min read
The most common request we get from businesses exploring AI is some version of: “Can we have something like ChatGPT, but that knows our policies, products and customers?” The answer is yes, and the technique behind it is called Retrieval-Augmented Generation, or RAG.
What RAG actually is
The idea was formalised in a 2020 paper from Facebook AI Research, which combined a language model's built-in knowledge with a retrievable external memory so answers could draw on up-to-date, verifiable sources.[1] Strip away the jargon and it's three steps:
- Retrieve. When a user asks a question, search your own documents for the passages most relevant to it.
- Augment. Paste those passages into the prompt, along with the question.
- Generate. Ask the model to answer using only that material, and to cite where it came from.
The model never “learns” your data. It reads the relevant slice of it, fresh, on every question. That is exactly why RAG is popular: update a document and the very next answer reflects it.
RAG or fine-tuning?
People often reach for fine-tuning when they really need retrieval. A good rule: fine-tune to change how a model behaves; use RAG to change what it knows.
| RAG | Fine-tuning | |
|---|---|---|
| Best for | Facts, policies, product docs, anything that changes | Tone, format, specialised task behaviour |
| Updating knowledge | Edit the document; instant | Retrain; slow and costly |
| Can cite sources | Yes, naturally | Not reliably |
| Per-user permissions | Enforce at retrieval time | Hard: data is baked into the weights |
| Upfront cost | Low to moderate | Moderate to high |
Building a minimal pipeline
A first version fits in one file. This sketch uses placeholder functions for the embedding model, vector store and LLM so you can plug in whichever providers you prefer:
// 1. INGEST (run when documents change)
async function ingest(documents) {
for (const doc of documents) {
const chunks = splitIntoChunks(doc.text, { size: 500, overlap: 80 });
for (const [i, text] of chunks.entries()) {
await vectorStore.upsert({
id: doc.id + ':' + i,
vector: await embed(text),
metadata: { docId: doc.id, title: doc.title, text, allowedRoles: doc.allowedRoles },
});
}
}
}
// 2. ANSWER (run on every question)
async function answer(question, user) {
const queryVector = await embed(question);
// Permissions are enforced HERE, before the model ever sees the text.
const hits = await vectorStore.search(queryVector, {
topK: 6,
filter: { allowedRoles: { contains: user.role } },
});
if (hits.length === 0) return { text: "I couldn't find that in our documents.", sources: [] };
const context = hits
.map((h, i) => '[' + (i + 1) + '] ' + h.metadata.title + ': ' + h.metadata.text)
.join('\n\n');
const reply = await llm.complete({
system:
'Answer using ONLY the numbered sources. Cite them like [1]. ' +
'If the sources do not contain the answer, say you do not know.',
user: 'Sources:\n' + context + '\n\nQuestion: ' + question,
});
return { text: reply, sources: hits.map((h) => h.metadata.title) };
}
Six mistakes that sink RAG projects
- Bad chunking. Splitting mid-sentence or mid-table destroys meaning. Chunk by headings and paragraphs, keep some overlap, and keep tables whole.
- Embeddings only. Pure semantic search misses exact terms such as product codes, invoice numbers and names. Combine it with keyword search (BM25). Anthropic reported that adding contextual information to chunks and combining embeddings with BM25 substantially reduced failed retrievals in their tests.[2]
- Ignoring permissions. If HR documents and sales documents sit in one index, filter by the asker's access at retrieval time. Never rely on the prompt to “not reveal” things.
- No “I don't know” path. A model forced to answer will invent something. Tell it explicitly to refuse when the sources are silent.
- Trusting retrieved text. A document can contain instructions (“ignore previous rules…”). That is indirect prompt injection, and it sits at the top of the OWASP LLM risk list.[3] Treat retrieved content as data, never as commands.
- Not measuring. “It seems good” is not an evaluation. Build 50 question-and-answer pairs from real staff questions and track the score every time you change anything.
Chunking: the decision that quietly decides quality
Before a document can be searched, it is split into chunks. Too small and each chunk loses the context that makes it meaningful; too large and the retrieved text is padded with irrelevant material that dilutes the answer. A sensible starting point is chunks of a few hundred words that follow the document’s own structure, such as a section under a heading, with a small overlap so sentences are not cut in half.
- Keep headings with their text. Prepend the document title and section heading to each chunk so the retrieved passage still says what it is about.
- Handle tables and lists carefully. Splitting a price table across two chunks produces confident wrong answers. Keep tables whole or convert rows to sentences.
- Store metadata. Record the source file, date, department and access level for every chunk. You will need it for filtering, citations and permissions.
- Re-index when documents change. A policy updated last month but indexed last year is a classic source of wrong answers.
How to know whether your RAG system is any good
Build a test set before you tune anything. Collect 40 to 60 real questions that staff or customers ask, and write down the correct answer and the document it comes from. Then measure two things separately. Retrieval quality asks whether the right passage appeared in the top results. Answer quality asks whether the final response was correct, complete and faithful to the sources.
Separating the two tells you where to work. If retrieval is poor, improve chunking, add keyword search alongside vector search, or add a re-ranking step. If retrieval is good but answers are wrong, fix the prompt, instruct the model to say “I don’t know” when the sources do not cover the question, and require citations.
| Symptom | Likely cause | First thing to try |
|---|---|---|
| Answers are confident but wrong | Right passage not retrieved | Check top results; improve chunking |
| Answers ignore the documents | Prompt allows outside knowledge | Tell the model to use only the sources |
| Misses exact codes or names | Vector search blurs rare terms | Add keyword (hybrid) search |
| Shows staff-only content to customers | No permission filtering | Filter by access level before retrieval |
| Quality drops over time | Stale index | Schedule re-indexing on document changes |
Frequently asked questions
Do we need a dedicated vector database?
Not at the start. For a few thousand documents, the vector features of a database you already run, such as PostgreSQL with pgvector, are usually enough. Move to a dedicated service when scale, latency or filtering needs demand it.
Can RAG work with Swahili or mixed-language documents?
It can, but test it. Embedding models vary in how well they handle Swahili and code-switching between English and Swahili. Include real Swahili and mixed-language questions in your test set and compare models on your own data instead of trusting generic benchmarks.
Is our confidential data safe?
It depends on where it goes. Check whether your provider stores prompts, whether data leaves the country, and whether your contract allows it. Strip or mask personal data you do not need, and apply the same access rules to the assistant that staff already have to the documents.
Where RAG pays off fastest
- Internal helpdesk for HR policy, IT procedures, onboarding.
- Customer support that drafts answers from your product docs and past tickets.
- Sales enablement: instant, cited answers to RFP and security-questionnaire questions.
- Compliance lookups across contracts, regulations and internal standards.
Done well, RAG turns the documents you already own, and nobody reads, into something your team actually uses. Done badly, it's a confident liar with access to your files. The difference is almost entirely in the boring parts: chunking, permissions and evaluation.
References & further reading
- Lewis, P. et al., “Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks” (2020), arXiv:2005.11401. https://arxiv.org/abs/2005.11401
- Anthropic, “Introducing Contextual Retrieval” (September 2024). https://www.anthropic.com/news/contextual-retrieval
- OWASP GenAI Security Project, “OWASP Top 10 for LLM Applications”. https://genai.owasp.org/llm-top-10/