Documents and a PDF flowing through a retrieval cube into a language model, titled What is RAG

What Is RAG? A Beginner’s Guide to Retrieval-Augmented Generation (with a Basic Example)

I have been writing about local models, and more recently a Spring AI series that includes a RAG walkthrough with PgVector. Before I add more of those how-tos, I wanted a slower post that stays with the idea itself. What is RAG, why do people reach for it, what are the pieces in plain language, and what does a basic system look like if you build one on your own machine?

This post is meant to be the hub. Later articles can get more specific, like the Spring AI one, without having to re-explain the vocabulary every time.

What RAG actually is

RAG stands for retrieval-augmented generation. The name is a mouthful, but the job is simple. Before a language model writes an answer, the system looks up a few relevant passages from your own documents and puts those passages into the prompt. The model then writes from that material, not only from what it memorized during training.

The analogy I use most often is an open-book exam. A plain chatbot is the closed-book version. It answers from memory, and if it never studied your handbook, it guesses. RAG is the open-book version. A retriever finds the right pages, then the model writes with those pages in front of it.

The idea is not brand new. Patrick Lewis and colleagues described retrieval-augmented generation in a paper accepted at NeurIPS 2020. The practical systems most of us build today are simpler than that original setup, but the core is the same. You pair a generator with an external memory you can update.

In plain language, the mechanism has two phases. First you prepare your library. You take source documents, split them into chunks, turn each chunk into an embedding, and store those embeddings in a vector database. That work happens ahead of time, and you repeat it when the documents change. Then, for every question, you embed the question with the same model, fetch the closest chunks, pack them into the prompt, and let the language model write the answer.

Flowchart of a RAG query. A user question goes to a retriever, then a vector database, then top-k chunks, a prompt window, an LLM, and a grounded answer.
The query pipeline, from the question to a grounded answer.

Why RAG showed up in the first place

A large language model only knows what was in its training data, and that data has a cutoff. Ask it about a policy you wrote last week, or a product you have not published in a dataset, and it has no honest way to know. It also cannot see private material. Your contracts, your wiki, your support tickets and your internal PDFs never went into the public training run.

When the model does not know, it often still answers. That confident guess is what people call a hallucination. RAG does not magically end that habit, but it gives the model a much better place to look, and it lets you point back to a source.

People sometimes ask why they should not just fine-tune the model on their documents instead. Fine-tuning is useful when you want to change how a model behaves, its tone, or a narrow skill. It is a poor default if all you want is “answer from these files, and let me update the files next month.” Retraining is slower and more expensive, and a fine-tuned model still drifts out of date the moment the source changes. With RAG, you update the index. The model stays the same.

That is a big reason RAG became the default pattern for document-aware apps. Menlo Ventures’ 2024 State of Generative AI in the Enterprise report, based on a survey of 600 U.S. IT decision-makers, put RAG at 51 percent adoption among enterprise AI design patterns, up from 31 percent the year before. I am quoting the 2024 figure on purpose. I have not seen a later Menlo number for this specific pattern that I trust enough to repeat here.

What you gain, and what you should not expect

The obvious gain is access to your own knowledge. You can ask questions about a handbook, a set of PDFs or a help center, and the answer can name the page it came from. You can refresh that knowledge without training a new model. You also keep more control over cost, because you send a few retrieved passages instead of pasting an entire corpus into every prompt. If you want more detail on why that budget matters, I wrote about tokens and context windows and a shorter explainer on what tokens actually are.

RAG is also a practical way to run privately. The example later in this post uses Ollama on localhost, so the documents and the model stay on your machine. If you are choosing a local runtime, my Ollama vs LM Studio comparison is a useful starting point.

The limits are just as important. If the retriever brings back the wrong passage, the model will write a fluent answer from the wrong passage. Garbage in still means garbage out. A model can also ignore the retrieved text and lean on its training memory, especially if your prompt is vague. RAG reduces made-up answers. It does not guarantee a citation-perfect one.

There are operational limits too. An index goes stale if nobody re-ingests edited documents. Access control is easy to forget, and a vector store that contains everyone’s files will happily retrieve a salary policy for the wrong person. Very large, messy PDFs, tables split across chunks, and scanned pages that were never parsed properly will all hurt retrieval. And a basic RAG loop is not an agent. It answers from text you already have. It does not browse a live database or call a tool unless you add that later.

A glossary of the building blocks

If RAG feels like a pile of new words, it helps to treat them as a small toolkit rather than a single product. Here are the pieces I wish someone had lined up for me the first time.

Traditional database

This is the database you already know. It stores rows, columns or documents with named fields, and you query it with exact conditions. “Give me order 1024.” “Find the user whose email is this.” It is the right place for accounts, inventories and anything that must be precisely true. It is a weak place to ask, “which paragraph explains how we handle a late cancellation?”

Vector database

A vector database stores embeddings, which are long lists of numbers, together with the original text and some metadata. You query it by meaning. “Find the five chunks closest to this question.” Popular options include a Postgres extension such as pgvector, and dedicated stores such as Chroma or Qdrant. I am naming those only as examples of the same idea. Many teams start with the database they already run and add a vector extension, then move to a dedicated store if scale or filtering needs it.

Side by side comparison of a traditional database, which answers exact queries, and a vector database, which finds similar meanings.
A regular database matches exact values. A vector database matches meaning.

Source documents

These are the things you actually trust. PDFs, Word files, wiki pages, HTML help articles, markdown notes, maybe export dumps from a ticketing tool. RAG cannot invent a clean library for you. If the source is messy, the answers will be messy. Parsing is often the unglamorous first job, especially with PDFs and tables.

Chunking

Long documents are split into passages before they are embedded. You do this because embedding models have an input limit, and because a later prompt can only hold so many tokens. A chunk should be big enough to make sense on its own, and small enough that a few of them fit in the prompt.

There is no single best size. Microsoft’s Azure AI Search documentation suggests starting with 512-token chunks and about 25 percent overlap, which they describe as 128 tokens, or roughly 2,000 characters with a generous overlap. Treat that as a documented starting point, not a law. Overlap helps when a sentence or a rule would otherwise be cut in half.

Embeddings and embedding models

An embedding model reads a piece of text and returns a vector. Texts with similar meaning end up close together in that space, even when they use different words. “Reset my password” can sit near a paragraph that only says “terminating your subscription,” if the model has learned that those ideas are related.

The rule that catches people out is simple. You must use the same embedding model for the documents and for the question. Mix two models, and you are comparing points from two different maps.

Scatter plot of document chunks in embedding space, with a question in the center of a top-k neighborhood of leave policy passages.
Similar meanings sit close together. The retriever returns the nearest chunks.

Similarity search and top-k

Once the question is a vector, the database finds the stored vectors closest to it. That is similarity search. Top-k is just the number of neighbors you ask for, often three to eight in a first system. Too small, and you miss a useful passage. Too large, and you fill the prompt with weakly related text and give the model more chances to get confused.

The retriever

The retriever is the component that takes a question and returns those chunks. In a basic system it is “embed the question, then nearest neighbors.” In a stronger system it may rewrite the question, mix keyword search with vector search, or pass the first batch of results through a reranker.

The prompt and the context window

The retrieved passages and the user question are assembled into one prompt. Everything in that prompt, including instructions and earlier chat turns, has to fit in the model’s context window. This is why RAG exists at all. You cannot usually paste an entire company wiki into every request, and even when a window is huge, you still pay for every token you send.

The LLM

This is the language model that writes the answer. In a local setup it might be Llama 3.2 served by Ollama. In a hosted setup it might be a cloud chat model. RAG does not replace the model. It changes what the model is allowed to read before it writes.

Reranking

A first retrieval pass is fast but a bit rough. A reranker takes a wider set of candidates, maybe 20 or 50, and scores them more carefully against the question, then keeps the best few for the prompt. You do not need this on day one. It becomes useful when naive top-k keeps missing the right paragraph or bringing back near-duplicates.

Hybrid search

Vector search is good at meaning and weak at exact tokens. It can miss a precise error code, a SKU, or a person’s exact name. Hybrid search adds a classic keyword search, then merges the two lists. If your users often paste identifiers, this is usually worth adding before you reach for anything more exotic.

How a basic RAG system runs end to end

I find it easier to remember the system as two pipelines, not one magical box.

The ingest pipeline is the quiet one. Documents come in. You extract the text, split it into chunks, embed each chunk, and write the vectors plus the original text and metadata into a vector store. Metadata should at least include the source file, and ideally a heading or page number. You run this when the library is new, and again when files change.

Flowchart of the RAG ingest pipeline. Source documents are chunked, passed through an embedding model, and stored in a vector database.
The ingest pipeline, which you run before anyone asks a question.

The query pipeline is the one the user feels. A question comes in. The retriever embeds it, the vector store returns the top-k chunks, you build a prompt that says “answer from this context,” and the LLM writes a reply. If you did the ingest well, that reply can name the source. If you did not, the reply can still sound polished and still be wrong.

In words, the query flow looks like this. User question, then retriever, then vector database, then top-k chunks, then prompt inside the context window, then the LLM, then the answer. That is the same path shown in the first diagram above.

Build a minimal RAG system on your machine

The rest of this post is a small, runnable example. It uses Python, Ollama, nomic-embed-text for embeddings and llama3.2 for the answers. Instead of bringing in a full vector database, I stored the vectors in memory and ranked them with cosine similarity, so you can see the retrieval step instead of hiding it behind a client library. Later you can swap that store for Chroma, pgvector or Qdrant without changing the idea.

You need Ollama running at http://127.0.0.1:11434, then two pulls.

ollama pull nomic-embed-text
ollama pull llama3.2

The sample document is a short, fictional staff handbook for a place I called Willow Street Studio. I made the facts specific on purpose, so you can tell whether the model actually read the file. Full-time staff get 22 days of paid leave plus 3 wellness days. The studio is open 9:30 to 18:30, Tuesday to Saturday. A guest who cancels a workshop two days before the start gets a 50 percent credit, not a cash refund.

I split the text into overlapping character chunks, which is crude but clear. For a real corpus I would start closer to the 512-token guidance above and split on headings or paragraphs first.

def chunk_text(text, size=420, overlap=80):
    text = " ".join(text.split())
    chunks, i = [], 0
    while i < len(text):
        piece = text[i:i + size]
        if piece.strip():
            chunks.append(piece.strip())
        if i + size >= len(text):
            break
        i += size - overlap
    return chunks

One nomic-embed-text detail is easy to miss. The model is trained with task prefixes. Documents should start with search_document:, and questions should start with search_query:. Skip those prefixes and retrieval usually gets worse, even though the code still “works.”

def ollama_embed(text, prefix):
    payload = {"model": "nomic-embed-text", "input": f"{prefix} {text}"}
    r = requests.post("http://127.0.0.1:11434/api/embed", json=payload, timeout=120)
    r.raise_for_status()
    return r.json()["embeddings"][0]
def cosine(a, b):
    dot = sum(x * y for x, y in zip(a, b))
    na = math.sqrt(sum(x * x for x in a))
    nb = math.sqrt(sum(x * x for x in b))
    return dot / (na * nb) if na and nb else 0.0

def retrieve(store, question, k=3):
    qvec = ollama_embed(question, "search_query:")
    ranked = sorted(store, key=lambda row: cosine(qvec, row["embedding"]), reverse=True)
    return ranked[:k]

The prompt is intentionally strict. If the retrieved text does not contain the answer, the model should say it does not know, rather than filling the gap from memory.

prompt = (
    "Answer the question using only the sources below. "
    "If the sources do not contain the answer, say you do not know. "
    "Mention the source file you used.\n\n"
    f"{context}\n\n"
    f"Question: {question}"
)
reply = requests.post(
    "http://127.0.0.1:11434/api/chat",
    json={
        "model": "llama3.2",
        "messages": [{"role": "user", "content": prompt}],
        "stream": False,
        "options": {"temperature": 0.1},
    },
    timeout=300,
).json()["message"]["content"]

The full script in the demo folder is a single file, plus the sample handbook and a short README. On your own machine, put rag_demo.py, requirements.txt and a docs folder together, install requests, and run python rag_demo.py.

I ran this exact script against a local Ollama instance on CPU. Official ollama pull for these models was blocked on the machine I used to write the post, so I imported public GGUF files under the same names, nomic-embed-text-v1.5 Q4_K_M and Llama 3.2 3B Instruct Q4_K_M. On a normal machine, ollama pull nomic-embed-text and ollama pull llama3.2 is the simpler path. The embedding vectors came back with 768 dimensions.

The first two questions landed cleanly. The handbook says 22 days of paid leave plus 3 wellness days, and the studio is open 9:30 to 18:30, Tuesday to Saturday. The third question is the one worth lingering on. The retriever did fetch the refund chunk, which says a cancellation inside 5 days gets a 50 percent credit, not cash. The model still answered that it did not know, because I asked about “2 days” and the text never uses that number. That is RAG in real life. Retrieval can be right and the answer can still miss a simple inference.

Ingesting documents...
  indexed willow-street-studio.txt chunk 1 (420 chars, 768 dims)
  indexed willow-street-studio.txt chunk 2 (420 chars, 768 dims)
  indexed willow-street-studio.txt chunk 3 (420 chars, 768 dims)
  indexed willow-street-studio.txt chunk 4 (277 chars, 768 dims)
Store holds 4 chunks.


Q: How many paid leave days do full-time staff get, and how many wellness days?
  retrieved willow-street-studio.txt#chunk-1  score=0.783
    Willow Street Studio staff handbook (fictional sample for a RAG demo) Leave policy Full-time staff at Willow Street Studio receive 22 days of paid annual leave ...
  retrieved willow-street-studio.txt#chunk-3  score=0.656
    sted on the internal board two weeks ahead. Workshop refunds If a booked weekend workshop is cancelled by the guest at least 5 full days before the start time, ...
  retrieved willow-street-studio.txt#chunk-4  score=0.631
    ve a full refund. Podcast room The podcast room has two mics, a recorder and a small desk. Staff may reserve it on the shared calendar at least 24 hours ahead. ...
A: According to the Willow Street Studio staff handbook, full-time staff receive 22 days of paid annual leave each calendar year, plus 3 wellness days that cannot be carried forward.

Source: willow-street-studio.txt


Q: What are the studio opening hours, and which days is it closed?
  retrieved willow-street-studio.txt#chunk-2  score=0.862
    The studio is a small team, so no more than two people may be on planned leave in the same week. Opening hours The studio at 18 Willow Street is open from 9:30 ...
  retrieved willow-street-studio.txt#chunk-1  score=0.696
    Willow Street Studio staff handbook (fictional sample for a RAG demo) Leave policy Full-time staff at Willow Street Studio receive 22 days of paid annual leave ...
  retrieved willow-street-studio.txt#chunk-3  score=0.664
    sted on the internal board two weeks ahead. Workshop refunds If a booked weekend workshop is cancelled by the guest at least 5 full days before the start time, ...
A: According to the provided sources, the studio opening hours are from 9:30 to 18:30, Tuesday to Saturday. It is closed on Sunday and Monday.

Source: willow-street-studio.txt


Q: If a guest cancels a workshop 2 days before it starts, what do they get back?
  retrieved willow-street-studio.txt#chunk-3  score=0.825
    sted on the internal board two weeks ahead. Workshop refunds If a booked weekend workshop is cancelled by the guest at least 5 full days before the start time, ...
  retrieved willow-street-studio.txt#chunk-2  score=0.688
    The studio is a small team, so no more than two people may be on planned leave in the same week. Opening hours The studio at 18 Willow Street is open from 9:30 ...
  retrieved willow-street-studio.txt#chunk-4  score=0.676
    ve a full refund. Podcast room The podcast room has two mics, a recorder and a small desk. Staff may reserve it on the shared calendar at least 24 hours ahead. ...
A: I do not know. The provided source file does not contain information about the refund policy for cancellations made 2 days before the workshop starts. 

Source: willow-street-studio.txt

Mistakes I see in first RAG projects

The most common one is messy chunking. If you slice a table through the middle, or cut a policy so the condition is in one chunk and the exception is in another, retrieval will look random. Keep tables with their headers, and put the document title or section heading on each chunk. It costs almost nothing and helps a lot.

The second is mixing embedding models, or forgetting model-specific prefixes like the nomic ones above. The third is stuffing too many chunks into the prompt and hoping the model will sort it out. A tighter top-k, or a reranker, usually beats a bigger pile of text.

Two more are quieter, and they cause real damage. People skip metadata, then cannot say where an answer came from. And people index documents that not every user should see, then expose them through the chat box. Retrieval does not know about your permissions unless you filter on them.

Finally, do not skip a small evaluation set. Ten real questions with known answers will tell you more than another weekend spent switching vector databases.

What to learn next

If you want to see the same idea in a Java stack, I already have a Spring AI RAG tutorial that uses PgVector and Ollama. It is the natural next step after this explainer, and it builds on the Spring AI chatbot tutorial. I plan to write more RAG posts from this hub, including more practical setups, not only Spring.

When this basic loop feels comfortable, the next upgrades are usually better parsing, hybrid search, and a reranker. Those are improvements to retrieval. A bigger model will not fix a bad chunk.

Frequently Asked Questions

What does RAG stand for?

Retrieval-augmented generation. The system retrieves relevant passages first, then a language model generates an answer using those passages as context.

How is RAG different from fine-tuning?

Fine-tuning changes a model’s behaviour by training it further. RAG leaves the model as it is and adds current or private text at question time. Use fine-tuning when you care about style or a skill. Use RAG when you care about answering from documents you can update.

Do I need a dedicated vector database?

Not to learn the idea. The example in this post keeps vectors in memory. For a real app, a vector extension in Postgres, or a store such as Chroma or Qdrant, gives you persistence, indexing and filtering. Pick the one that fits how you already run databases.

Can I run RAG completely offline?

Yes, once the models are downloaded. Ollama can serve both the embedding model and the chat model on your own machine. You still need a network for the first ollama pull and for any Python packages you install.

Does RAG stop hallucinations completely?

No. It usually reduces them, especially when the prompt tells the model to stay on the retrieved text. The model can still ignore that context, or write fluently from the wrong chunk, so you should keep sources next to the answer and test with real questions.

What chunk size should I start with?

Start with a moderate size and a little overlap, then test on your own questions. Microsoft’s Azure AI Search documentation suggests 512 tokens with about 25 percent overlap as a starting point. I used smaller character chunks in the demo only so the example stayed easy to inspect.

Why do my answers ignore my documents?

Usual causes are a weak retriever, mixed embedding models, missing task prefixes, chunks that were split badly, or a prompt that never tells the model to use only the provided sources. Print the retrieved chunks before you blame the chat model.

Content Protection by DMCA.com
Spread the love
Scroll to Top
×