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 tobookings.csv, a file you can open in a spreadsheet. - The query. Reading the file back and counting rows whose machine is
laser cutterand whose date starts with2026-03is 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 needs | Use | Why |
|---|---|---|
| A count, sum, average or list of every matching item | A database query (or a spreadsheet) | Exact over all rows; retrieval sees only a few |
| One answer from a short text the user already has | The text in the prompt | It fits; retrieval adds nothing but a chance to miss |
| A style, format or tone | Prompt instructions, or fine-tuning for a stable house style at scale | That is behaviour, not missing knowledge |
| The right documents, with the user reading them | Search 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 private | RAG | Retrieval 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.
- "Summarise the contract I just pasted."
- "What is the total value of invoices overdue by more than 30 days?"
- "Which of our 4,000 policy pages say how long we keep CCTV footage? Show me the pages."
- "Answer staff questions about the 600-page handbook, with the section each answer comes from."
- "Write every reply in our support team's friendly, short style."
- "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
- The text in the prompt: it is short and already supplied.
- A database query: an exact total over every matching invoice.
- Search alone: the user wants the pages, not a generated answer.
- RAG: a large collection, a specific answer, and the source required.
- Prompt instructions, or fine-tuning if the style must hold across very many requests: it is behaviour, not knowledge.
- 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.)