RAG · Lesson 41 of 120
Grounding
Only from the context.
A grounded answer uses only the facts in the context. Without context, a model falls back on what it learned in training, which knows nothing about Northwind. Let's compare the two.

- Use only the context
- Training knows nothing of us
- Compare
With and without context
First we ask the model directly, with no context. Then we ask through our answer helper, which adds the best chunks and the grounding rule. Run it. Without context, the model can't know Northwind's price. With context, it gives the real one.
grounding.pypython
from rag_kit import load_docs, make_chunks, Index
from llm import llm, answer
index = Index(make_chunks(load_docs()))
q = "How much is a Basic service at Northwind Bikes? One short sentence."
print("No context:", llm.invoke(q).text.strip()[:80])
print("With RAG: ", answer(q, [c for s, c in index.search(q)]))Output
No context: A Basic service at Northwind Bikes costs $75. With RAG: A Basic service costs £49.
Also uses rag_kit.py
import warnings; warnings.filterwarnings("ignore")
from pathlib import Path
import numpy as np
from sentence_transformers import SentenceTransformer
import faiss # after torch, so the two libraries load safely together
faiss.omp_set_num_threads(1)
from langchain_text_splitters import RecursiveCharacterTextSplitter
def load_docs(folder="data/rag/northwind"):
return [{"source": p.name, "text": p.read_text()} for p in sorted(Path(folder).glob("*.md"))]
def make_chunks(docs, size=300, overlap=50):
splitter = RecursiveCharacterTextSplitter(chunk_size=size, chunk_overlap=overlap)
return [{"source": d["source"], "text": t.replace("\n", " ")}
for d in docs for t in splitter.split_text(d["text"])]
embedder = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")
def embed(texts):
return embedder.encode(texts, normalize_embeddings=True)
class Index:
def __init__(self, chunks):
self.chunks = chunks
self.vectors = embed([c["text"] for c in chunks])
def search(self, query, k=3):
scores = self.vectors @ embed([query])[0]
top = np.argsort(-scores)[:k]
return [(round(float(scores[i]), 2), self.chunks[i]) for i in top]Also uses llm.py
from langchain.chat_models import init_chat_model
llm = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)
PROMPT = """Answer the question using only the context below.
If the answer is not in the context, say "I don't know".
Context:
{context}
Question: {question}"""
def answer(question, chunks):
context = "\n\n".join(f"[{c['source']}] {c['text']}" for c in chunks)
return llm.invoke(PROMPT.format(context=context, question=question)).text.strip()Grounded or not
An ungrounded answer sounds confident, but may be invented. A grounded answer is tied to your documents, so you can check it. That's the whole point of RAG.
Ungrounded
- From trainingMay be inventedCan't be checked
Grounded
- From your documentsReal factsEasy to check
Summary
Grounding means answering only from the context. Tell the model so, clearly, in the prompt. Next, what to do when the facts are missing.
Key takeaways- Only the context
- Your real facts
- Checkable
Next up: Saying I Don't Know — when the facts are missing