RAG explained: how to make an LLM answer from your own documents
5 min readAI · LLM · Guides
A language model knows what it learned during training, and nothing after. It has never seen your company handbook, your invoices, your notes or last week's meeting. Ask it about them and one of two things happens: it says it does not know, or, worse, it makes something up that sounds right. I explained why in my LLM post. This post is about the most common fix, called RAG.
RAG stands for retrieval-augmented generation. The idea is almost embarrassingly simple: before the model answers, look up the relevant text yourself and put it in the prompt. The model then answers from what you handed it, instead of from memory. Everything else in this field is detail about doing that lookup well.
RAG, fine-tuning and long context
People often ask whether they should fine-tune a model on their documents instead. For most document question-answering, I would start with RAG. Fine-tuning changes how a model behaves and writes; it is a poor way to teach it facts, and the facts go stale as soon as a document changes. With RAG you update the index and the next answer reflects it.
Another alternative is to paste everything into a very long context window. That works for a handful of files and costs more with every question. Once your material grows past what fits, or you need to point at exactly which passage supported an answer, retrieval earns its place.
The pipeline in two phases
A RAG system has an offline phase that prepares your documents, and an online phase that runs for every question.
- Ingest - load documents, clean them and split them into chunks.
- Embed - turn each chunk into a vector of numbers with an embedding model.
- Store - save the vectors and the original text in an index or vector database.
- Retrieve - at question time, embed the question and fetch the closest chunks.
- Generate - put those chunks and the question into a prompt and let the model answer.
Embeddings in plain words
An embedding model reads text and outputs a long list of numbers, a vector. Texts with similar meaning end up with vectors that point in similar directions. That is the trick. You do not need the words in the question to match the words in the document. A question about refund time can find a paragraph about money-back windows, because their vectors are close.
Finding the nearest vectors is called similarity search. For small collections a simple in-memory search is enough. For larger ones people use a vector database or a database extension, such as the vector support in Postgres. I would pick whichever fits the stack you already run rather than adding a new service on day one.
Chunking: where most quality is won or lost
You cannot embed a whole book as one vector and expect to retrieve a precise answer. You split documents into chunks, typically a few paragraphs each. Too large and a chunk contains many topics, so it matches everything vaguely. Too small and it loses the context that gives it meaning, such as which product or year a sentence refers to.
- Split on structure first: headings, sections, paragraphs. Fall back to size only when needed.
- Use a little overlap between neighbouring chunks so a sentence is not cut off from its context.
- Store metadata with every chunk: file name, title, section, date. You will need it for filtering and for citing sources.
- Keep tables, code and lists intact where you can; splitting them mid-row ruins them.
- Re-chunk and re-embed when you change the embedding model. Vectors from different models are not comparable.
A minimal sketch
This is pseudocode on purpose. Each helper maps to whichever library or API you choose, and the structure is what matters.
def build_index(documents):
chunks = []
for doc in documents:
for piece in split_into_chunks(doc.text, size=800, overlap=100):
chunks.append({"text": piece, "source": doc.name})
vectors = embed([c["text"] for c in chunks])
return store(chunks, vectors)
def answer(question, index):
hits = index.search(embed([question])[0], top_k=5)
context = "\n\n".join(f"[{h['source']}] {h['text']}" for h in hits)
prompt = (
"Answer using only the context below. "
"If the answer is not there, say you do not know. "
"Cite the source name.\n\n"
f"Context:\n{context}\n\nQuestion: {question}"
)
return llm(prompt)Look at the prompt. The instruction to answer only from the context and to admit when the answer is missing is the part that reduces made-up answers. It is not a guarantee, but it changes behaviour a lot. Asking for the source name next to each claim also lets a human check the answer against the original.
Improving retrieval
Plain vector search is a good start and a common weak point. Exact terms such as product codes, error numbers and names are exactly where embeddings are fuzzy. Many production systems combine vector search with keyword search, often called hybrid search, and then add a reranker: a second model that reads the question and each candidate chunk together and orders them by real relevance. Retrieve more candidates than you need, then keep the best few.
Other useful moves: rewrite a vague follow-up question into a standalone query before searching, filter by metadata such as department or date, and keep the number of chunks modest. Stuffing twenty chunks into a prompt tends to bury the useful one.
Where it bites
- Retrieval fails silently - if the right chunk is not fetched, the model answers from the wrong one or from nothing, and sounds confident either way.
- Stale or duplicate documents - old versions in the index produce contradictory answers. Track versions and remove what is obsolete.
- Permissions leak - if everyone's documents share one index, a user can retrieve text they should never see. Filter by access rights at query time, not afterwards.
- Prompt injection - a document can contain instructions aimed at the model. Treat retrieved text as untrusted data and never let it trigger sensitive actions unchecked.
- Privacy and cost - sending private text to a hosted model or embedding API means it leaves your machine. Read the provider's data terms, or run models locally.
- Scanned and messy files - bad PDF extraction means bad text. Look at what the parser actually produced before blaming the model.
How to know it works
Do not judge a RAG system by trying three questions and feeling good. Write a small test set of real questions with the document and passage that should answer each. Then measure two things separately. First, did retrieval bring back the right chunk in the top results? Second, given the right chunk, did the model answer correctly and stay inside it? Splitting the two tells you whether to fix chunking and search or the prompt.
Re-run that test set every time you change the chunk size, the embedding model or the prompt. It is the only way to tell an improvement from a coincidence.
RAG does not make a model smarter. It makes the model well-informed for one question, and the quality of the answer is mostly the quality of the lookup.

Written by
Shihab Hossain — Full-Stack Developer
I build thoughtful digital products from Bangladesh — fast web experiences with Next.js, Android apps with Flutter, and the infrastructure behind them.
Work with me