Retrieval-Augmented Generation (RAG) and Vector Databases / How RAG Works

Choose when RAG is the right tool

Lesson 5 of 43. Open to read. No account needed.

The Decision

RAG is the right tool when the answer is written down somewhere in a collection too large to give the model whole, and you want the answer with its source. It is the wrong tool for several common requests, and using it anyway produces answers that look right and are not. This lesson shows the clearest case with a run, then gives you a way to decide.

A Question RAG Cannot Answer Well

"How many laser cutter bookings were made in March?" needs every booking from March, counted. Retrieval returns the few passages most similar to the question, not all matching passages, so a RAG answer counts only what it was shown.

Starting state: the course environment and Ollama with granite4.1:3b.

mkdir -p ~/rag-practice/rag-or-query
cd ~/rag-practice/rag-or-query

Save this as rag_or_query.py in ~/rag-practice/rag-or-query:

"""Answer an aggregate question with a query and with RAG, and compare."""

import csv
import os
import random
from datetime import date, timedelta
from pathlib import Path

PRACTICE = Path.home() / "rag-practice"
os.environ["HF_HOME"] = str(PRACTICE / "hf-cache")
os.environ["HF_HUB_OFFLINE"] = "1"

import httpx  # noqa: E402
import numpy as np  # noqa: E402
from sentence_transformers import SentenceTransformer  # noqa: E402

QUESTION = "How many laser cutter bookings were made in March 2026?"

# A small booking table, generated with a fixed seed so every learner gets the same rows.
rng = random.Random(42)
machines = ["laser cutter", "wood lathe", "CNC router", "3D printer"]
rows = []
for n in range(160):
    day = date(2026, 1, 1) + timedelta(days=rng.randrange(120))
    rows.append({"booking": f"B{n + 1:03d}", "date": day.isoformat(), "machine": rng.choice(machines),
                 "minutes": rng.choice([30, 60, 90])})
with open("bookings.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.DictWriter(f, fieldnames=list(rows[0]))
    writer.writeheader()
    writer.writerows(rows)

# 1. The query: filter and count every row. Exact, and cheap.
with open("bookings.csv", encoding="utf-8") as f:
    exact = sum(1 for r in csv.DictReader(f) if r["machine"] == "laser cutter" and r["date"].startswith("2026-03"))
print(f"Query over all {len(rows)} rows: {exact} laser cutter bookings in March 2026")

# 2. RAG: the same rows as short notes; retrieve the four most similar and ask the model.
notes = [f"Booking {r['booking']} on {r['date']}: {r['machine']} for {r['minutes']} minutes." for r in rows]
embedder = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2",
                               revision="1110a243fdf4706b3f48f1d95db1a4f5529b4d41", device="cpu")
note_vectors = embedder.encode(notes, normalize_embeddings=True)
top = np.argsort(-(note_vectors @ embedder.encode(QUESTION, normalize_embeddings=True)))[:4]
sources = "\n".join(notes[i] for i in top)
reply = httpx.post("http://127.0.0.1:11434/api/chat", timeout=300, json={
    "model": "granite4.1:3b", "stream": False, "think": False,
    "options": {"temperature": 0, "seed": 7, "num_ctx": 4096},
    "messages": [{"role": "system", "content": "Answer using only the booking notes in the user's message."},
                 {"role": "user", "content": f"Booking notes:\n{sources}\n\nQuestion: {QUESTION}"}],
}).json()
print("RAG retrieved 4 of 160 notes:")
for i in top:
    print(f"  {notes[i]}")
print(f"RAG answer: {reply['message']['content'].strip()}")

What each part does:

  • The booking table. random.Random(42) is a random generator with a fixed seed, so every learner's script creates the same 160 bookings between 1 January and 30 April 2026. They are written to bookings.csv, a file you can open in a spreadsheet.
  • The query. Reading the file back and counting rows whose machine is laser cutter and whose date starts with 2026-03 is an exact computation over every row. In a real system this would be one SQL statement: SELECT count(*) FROM bookings WHERE machine = 'laser cutter' AND date LIKE '2026-03%'.
  • The RAG attempt. The same rows become one-line notes, the notes are embedded, and the four most similar to the question go to the model, as in the demonstration.

Predict before you run: will the RAG answer match the query's count?

python rag_or_query.py

Illustrative output:

Query over all 160 rows: 6 laser cutter bookings in March 2026

RAG retrieved 4 of 160 notes:
  Booking B007 on 2026-03-06: laser cutter for 90 minutes.
  Booking B054 on 2026-04-27: laser cutter for 90 minutes.
  Booking B057 on 2026-04-10: laser cutter for 90 minutes.
  Booking B048 on 2026-04-03: laser cutter for 90 minutes.
RAG answer: 1 laser cutter booking was made in March 2026.

The query is exact. The model saw four notes, so at best it can count those; it may also guess, or say the notes are insufficient. Neither is a reliable count, and nothing in its reply warns you that 156 rows were never seen. Asking for more passages does not fix this: retrieval ranks by similarity, so every March laser booking is no more similar to the question than a February one, and a large enough number of passages no longer fits the prompt.

Choosing the Tool

If the request needsUseWhy
A count, sum, average or list of every matching itemA database query (or a spreadsheet)Exact over all rows; retrieval sees only a few
One answer from a short text the user already hasThe text in the promptIt fits; retrieval adds nothing but a chance to miss
A style, format or tonePrompt instructions, or fine-tuning for a stable house style at scaleThat is behaviour, not missing knowledge
The right documents, with the user reading themSearch alone (keyword, semantic or both)No generation means no invented sentences
A specific answer from a large collection, with its source, that changes over time or is privateRAGRetrieval supplies the passage; citations make it checkable; updating the index updates answers

Permissions add a strong reason for RAG over fine-tuning: a document's text can be kept out of the prompt for users who may not see it, but text a model was fine-tuned on cannot be withheld per user.

Systems often combine tools. An assistant can send counting questions to a query and policy questions to RAG; deciding which is the same judgement as the table, made by code.

Your Turn

Classify each scenario: RAG, a database query, the text in the prompt, prompt instructions or fine-tuning, or search alone. Give the deciding property.

  1. "Summarise the contract I just pasted."
  2. "What is the total value of invoices overdue by more than 30 days?"
  3. "Which of our 4,000 policy pages say how long we keep CCTV footage? Show me the pages."
  4. "Answer staff questions about the 600-page handbook, with the section each answer comes from."
  5. "Write every reply in our support team's friendly, short style."
  6. "Can a Day Pass holder bring a guest?", asked of the makerspace's documents.

Then write one question about the makerspace where RAG is clearly the better tool and one where the text in the prompt is.

Answers

  1. The text in the prompt: it is short and already supplied.
  2. A database query: an exact total over every matching invoice.
  3. Search alone: the user wants the pages, not a generated answer.
  4. RAG: a large collection, a specific answer, and the source required.
  5. Prompt instructions, or fine-tuning if the style must hold across very many requests: it is behaviour, not knowledge.
  6. RAG: the answer is in one of many documents, and a citation lets the member check it.

Cleanup

rm -r ~/rag-practice/rag-or-query

(In PowerShell: Remove-Item -Recurse $HOME\rag-practice\rag-or-query.)

38 more lessons in the full course

Course access opens every lesson and adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 199 plus 18% GST. 90 days of online access. No auto-renewal.

Get the full course

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy