Skip to main content

05 - Personalized Tutoring with LLMs: RAG for Knowledge Grounding

How to build a tutor that answers from the course notes: RAG with a tenant filter, graduated help and measured recall@k, with code run without calling models.

What do you think about this article?

At a Glance

How to build a tutor that answers from the course notes: RAG with a tenant filter, graduated help and measured recall@k, with code run without calling models.

A tutor that answers from the course notes, not from what it "knows"

A language model left to itself answers with what it absorbed during training, which is not your course syllabus, nor your lecturer's notes, nor the notation used in class. For a tutor this is a serious flaw: a plausible but out-of-context answer, or one with a different symbol from the one in the adopted textbook, confuses the student more than it helps. The technique that tackles the problem is Retrieval-Augmented Generation (RAG): before answering, the system searches the course material for the relevant passages and puts them in front of the model, asking it to answer only with those. What I call grounding is this: every answer points back to a passage you can check.

This article builds everything that sits around the model, and runs every piece: the splitting of the material, the search with the tenant and course filter, the pedagogical rules that decide how much help to give, and the measurement of how well the search works. One step is not run, the text generation, because it requires an AI engine that is not called here: the listing of the rules stops at the prompt ready for the model. It assumes Python and an idea of what a language model is. The student data the tutor can adapt to comes from the models in the article on Adaptive Learning Algorithms; the tenant filter is the same principle as in Scalable LMS Architecture.

What RAG promises, and what it does not

The original proposal, described by Lewis and colleagues in the 2020 paper that introduced the term, combines a parametric memory (what the model has learned) with a non-parametric memory (a searchable index of documents). The authors point to the difficulty of providing provenance for answers and of updating knowledge as limits of models alone: this is precisely what a tutor needs, because the lecturer can correct a handout without retraining anything and the student can see which passage the explanation comes from.

What RAG does not promise is the elimination of errors. The model can ignore the passage, cite it badly or mix it with what it already knows. That is why you will not find in this article a percentage of hallucinations avoided: there is none valid for your course, and it has to be measured on your own questions. A second limit concerns order: Liu and colleagues observed that model performance is often highest when the relevant information is at the beginning or at the end of the context, and degrades in the middle of a long context. The practical consequence is to give the model a few passages, the best ones, and not an entire handout.

Splitting the material and searching, with the filter in the right place

Each document is split into chunks, because you retrieve a passage and not a book. A chunk carries its metadata with it: the tenant (tenant), the course, the source. The listing below uses six chunks from two different tenants, a calculus course and a physics one, and the word "derivata" (derivative) appears in both. For the search it implements BM25, a classic lexical method that gives more points to chunks containing the words of the question, rarer ones in the corpus counting more, and with diminishing returns for how many times they appear; it uses the typical values k1=1.5 and b=0.75, which are parameters to tune. The token function strips accents and stop words and reduces every word to its first five characters: it is a crude stemmer that unites "derivata" and "derivate", and it has limits, as you will see.

The corpus, the stop words and the questions stay in Italian on purpose, because the stemmer and the stop list are Italian and the results depend on them: I gloss the questions in the text, and I translated into English the comments, the prompt and everything the program prints.

The most important point is where the filter sits. In cerca, the selection by tenant and course happens before the scores are computed, not after. Filtering afterwards, discarding the results that do not belong to the tenant, seems equivalent but is not: the search statistics (how many times a word appears in the corpus) would also be computed on the other tenants' material, and if the filter is forgotten, or fails, one tenant's data ends up in front of the model and then of another's student. The listing runs the same question with and without the filter.

Python - Chunks with metadata, BM25 search and a tenant and course filter
import math, re, unicodedata
from collections import Counter
from dataclasses import dataclass

@dataclass(frozen=True)
class Chunk:
    id: str
    tenant: str
    corso: str
    fonte: str
    testo: str

# Material from two different tenants: the word «derivata» (derivative) appears in both.
# The corpus stays in Italian on purpose: the stop words and the 5-character stemmer below are Italian.
CORPUS = [
    Chunk("A1-def", "ateneo-a", "analisi-1", "dispensa-derivate", "La derivata di una funzione in un punto misura la velocità con cui la funzione cambia in quel punto. Si definisce come limite del rapporto incrementale: f'(x) = lim (f(x+h) - f(x)) / h per h che tende a 0."),
    Chunk("A1-prod", "ateneo-a", "analisi-1", "dispensa-derivate", "Regola del prodotto: la derivata del prodotto di due funzioni è (f g)' = f' g + f g'. Per esempio la derivata di x sin(x) è sin(x) + x cos(x)."),
    Chunk("A1-cat", "ateneo-a", "analisi-1", "dispensa-derivate", "Regola della catena: se h(x) = f(g(x)) allora h'(x) = f'(g(x)) g'(x). Per esempio la derivata di sin(x^2) è 2x cos(x^2)."),
    Chunk("A1-staz", "ateneo-a", "analisi-1", "dispensa-derivate", "Un punto stazionario è un punto in cui la derivata si annulla. Può essere un massimo, un minimo o un flesso: per distinguerli si studia il segno della derivata prima."),
    Chunk("A1-int", "ateneo-a", "analisi-1", "dispensa-integrali", "L'integrale definito tra a e b è l'area con segno sotto la curva. Il teorema fondamentale del calcolo lega l'integrale alla derivata: derivare l'integrale restituisce la funzione di partenza."),
    Chunk("B1-vel", "ateneo-b", "fisica-1", "appunti-cinematica", "In fisica la velocità istantanea è la derivata della posizione rispetto al tempo, e l'accelerazione è la derivata della velocità. La derivata della posizione dà la velocità in ogni istante."),
]

STOP = {"il", "lo", "la", "le", "gli", "un", "una", "di", "del", "della", "dei", "delle", "che", "in", "e", "si", "come", "per", "con", "è", "a", "da", "cos", "quando", "sono", "o"}

def token(testo: str) -> list[str]:
    senza_accenti = unicodedata.normalize("NFD", testo.lower())
    senza_accenti = "".join(c for c in senza_accenti if unicodedata.category(c) != "Mn")
    parole = re.findall(r"[a-z0-9]+", senza_accenti)
    return [p[:5] for p in parole if p not in STOP]      # crude "stemmer": the first 5 characters

def indice(chunks):
    docs = [token(c.testo) for c in chunks]
    df = Counter(t for d in docs for t in set(d))
    return docs, df, sum(len(d) for d in docs) / len(docs)

def bm25(query, chunk_tokens, df, n, media, k1=1.5, b=0.75):
    punteggio, tf = 0.0, Counter(chunk_tokens)
    for t in set(token(query)):
        if t not in tf:
            continue
        idf = math.log(1 + (n - df[t] + 0.5) / (df[t] + 0.5))
        punteggio += idf * tf[t] * (k1 + 1) / (tf[t] + k1 * (1 - b + b * len(chunk_tokens) / media))
    return punteggio

def cerca(query, tenant, corso, k=3, filtra=True):
    """The tenant and course filter is applied BEFORE ranking, not after."""
    candidati = [c for c in CORPUS if not filtra or (c.tenant == tenant and c.corso == corso)]
    docs, df, media = indice(candidati)
    punteggi = [(bm25(query, d, df, len(candidati), media), c) for d, c in zip(docs, candidati)]
    return sorted(((s, c) for s, c in punteggi if s > 0), key=lambda x: -x[0])[:k]

if __name__ == "__main__":
    q = "velocità istantanea e derivata"
    for etichetta, filtra in (("with filter", True), ("WITHOUT filter", False)):
        print(etichetta)
        for s, c in cerca(q, "ateneo-a", "analisi-1", filtra=filtra):
            print(f"   {s:5.2f}  {c.id:<8} ({c.tenant})")

# Output:
# with filter
#     1.37  A1-def   (ateneo-a)
#     0.14  A1-staz  (ateneo-a)
#     0.13  A1-prod  (ateneo-a)
# WITHOUT filter
#     4.29  B1-vel   (ateneo-b)
#     1.00  A1-def   (ateneo-a)
#     0.12  A1-staz  (ateneo-a)

The run, with Python 3, shows the difference. For the question "velocità istantanea e derivata" (instantaneous speed and derivative), a student of the calculus course at university A with the filter receives as the first result the definition of derivative from their own course (A1-def, 1.37). Without the filter, the first result is B1-vel (4.29), a physics passage from another tenant: more relevant to the question, but not theirs. Note also that the scores of A1-def change (from 1.37 to 1.00) because the corpus on which the statistics are computed is different. One tenant's material must never enter another's candidates, and that is why the filter sits in the database or in the index, not in a later check in the application code. In a production RAG, the chunk B1-vel would be in a separate index or filtered out by a condition on the metadata of the same query.

The pedagogical guardrail: how much help to give, and when to refuse

A tutor that solves the exercises in place of the student is a homework solver, not a tutor. The guardrail in the listing makes three decisions before touching the model. If the best chunk has a score below the threshold (SOGLIA_BM25, set by hand to 1.0 for the example), it refuses: the course material does not cover the question, and it is better to say so than to leave the model free to invent. If the question contains a request for a solution (the words "risolvi", "svolgi", "dammi la soluzione", that is solve, work out, give me the solution), it decides a help level according to how many hints it has already given in the session: hint, guiding question, first step, annotated worked solution. Finally it builds the prompt, which includes the material numbered by id, the instruction to cite them and the one to say "I cannot find it" if the material is not enough.

Python - Refusal, help level and prompt construction (generation is not run)
import re
from rag import cerca

SOGLIA_BM25 = 1.0            # below this threshold the material does not answer: the example sets it by hand

# Italian trigger phrases (risolvi = solve, svolgi = work out, dammi la soluzione = give me the solution,
# dimmi il risultato = tell me the result, fammi l'esercizio = do the exercise for me)
PAROLE_SOLUZIONE = re.compile(r"\b(risolvi|svolgi|dammi la soluzione|dimmi il risultato|fammi l'esercizio)\b", re.I)

def livello_aiuto(suggerimenti_gia_dati: int) -> str:
    """Graduated scaffolding: the more hints have already been given, the more can be shown."""
    return ("hint", "guiding question", "first step", "annotated worked solution")[min(suggerimenti_gia_dati, 3)]

def prepara(domanda, tenant, corso, suggerimenti_gia_dati):
    trovati = cerca(domanda, tenant, corso, k=2)
    if not trovati or trovati[0][0] < SOGLIA_BM25:
        return {"action": "refuse", "reason": "the course material does not cover the question"}
    chiede_soluzione = bool(PAROLE_SOLUZIONE.search(domanda))
    livello = livello_aiuto(suggerimenti_gia_dati) if chiede_soluzione else "explanation"
    contesto = "\n".join(f"[{c.id}] {c.testo}" for _, c in trovati)
    prompt = (
        "You are a tutor. Answer ONLY with the material in [] below and cite the ids.\n"
        f"Help level: {livello}. Do not give the complete solution unless the level is 'annotated worked solution'.\n"
        f"If the material is not enough, say that you cannot find it.\n\nMaterial:\n{contesto}\n\nQuestion: {domanda}"
    )
    return {"action": "generate", "level": livello, "sources": [c.id for _, c in trovati], "prompt": prompt}

casi = [
    ("Risolvi la derivata di x sin(x)", 0),
    ("Risolvi la derivata di x sin(x)", 3),
    ("Che cos'è un punto stazionario?", 0),
    ("Come si risolve un'equazione differenziale?", 0),
]
for domanda, n in casi:
    r = prepara(domanda, "ateneo-a", "analisi-1", n)
    print(f"{domanda!r} (hints already given: {n})")
    print("   ->", {k: v for k, v in r.items() if k != "prompt"})
print("--- prompt of the first case ---")
print(prepara(casi[0][0], "ateneo-a", "analisi-1", 0)["prompt"])

# Output:
# 'Risolvi la derivata di x sin(x)' (hints already given: 0)
#    -> {'action': 'generate', 'level': 'hint', 'sources': ['A1-prod', 'A1-cat']}
# 'Risolvi la derivata di x sin(x)' (hints already given: 3)
#    -> {'action': 'generate', 'level': 'annotated worked solution', 'sources': ['A1-prod', 'A1-cat']}
# "Che cos'è un punto stazionario?" (hints already given: 0)
#    -> {'action': 'generate', 'level': 'explanation', 'sources': ['A1-staz', 'A1-def']}
# "Come si risolve un'equazione differenziale?" (hints already given: 0)
#    -> {'action': 'refuse', 'reason': 'the course material does not cover the question'}
# --- prompt of the first case ---
# You are a tutor. Answer ONLY with the material in [] below and cite the ids.
# Help level: hint. Do not give the complete solution unless the level is 'annotated worked solution'.
# If the material is not enough, say that you cannot find it.
#
# Material:
# [A1-prod] Regola del prodotto: la derivata del prodotto di due funzioni è (f g)' = f' g + f g'. Per esempio la derivata di x sin(x) è sin(x) + x cos(x).
# [A1-cat] Regola della catena: se h(x) = f(g(x)) allora h'(x) = f'(g(x)) g'(x). Per esempio la derivata di sin(x^2) è 2x cos(x^2).
#
# Question: Risolvi la derivata di x sin(x)

The four questions in the example show the three outcomes. "Risolvi la derivata di x sin(x)" (solve the derivative of x sin(x)) with zero hints already given receives the level hint; the same question after three hints reaches annotated worked solution. "Che cos'è un punto stazionario?" (what is a stationary point?) is not a request for a solution, so it receives an explanation. The question about differential equations ("Come si risolve un'equazione differenziale?") finds nothing relevant and is refused. The printed prompt is the one that would go to the model; its next step, the call, is not run here. The values (threshold, keywords, four levels) are choices made for the example, and a real intent classifier would use a model, not a regular expression.

There is, however, a flaw that the listing brings out without having looked for it, and it is instructive. For the question about x sin(x) the retrieved material contains the already worked example (A1-prod reports the result). The request in the prompt ("do not give the complete solution") is a plea, not a guarantee: a model that sees the solution in the context can still return it. The remedy is structural and not lexical: label the worked exercises and their results in the metadata and, at the low help levels, exclude them from the context before building the prompt. In the same way, a check on the answer (that it does not contain the result) is worth more than a sterner sentence in the instruction.

Measuring retrieval before trusting the answer

A tutor that gets the search wrong always gets the answer wrong, which is why the first measurement to make is on retrieval and not on the generated text. You prepare a small set of questions written the way students would write them, each with the chunk that should be retrieved, and you compute the recall@k: the share of questions whose expected chunk appears among the top k results. The listing does it on six questions.

Python - recall@k on labelled questions
from rag import cerca

# Questions written the way a student would write them (in Italian, like the corpus), with the chunk that SHOULD be retrieved.
PROVE = [
    ("come si calcola la derivata di un prodotto di funzioni", "A1-prod"),
    ("derivata di una funzione composta", "A1-cat"),
    ("quando la derivata si annulla", "A1-staz"),
    ("cos'è il limite del rapporto incrementale", "A1-def"),
    ("come si calcola un integrale", "A1-int"),
    ("cosa succede nei massimi e nei minimi", "A1-staz"),
]

def valuta(k):
    giusti, dettaglio = 0, []
    for domanda, atteso in PROVE:
        ids = [c.id for _, c in cerca(domanda, "ateneo-a", "analisi-1", k=k)]
        giusti += atteso in ids
        dettaglio.append((domanda, atteso, ids))
    return giusti / len(PROVE), dettaglio

for k in (1, 3):
    r, dettaglio = valuta(k)
    print(f"recall@{k} = {r:.2f}  ({round(r * len(PROVE))} out of {len(PROVE)})")
    if k == 1:
        for domanda, atteso, ids in dettaglio:
            if atteso not in ids:
                print(f"   missed: {domanda!r} wanted {atteso}, found {ids}")

# Output:
# recall@1 = 0.83  (5 out of 6)
#    missed: 'derivata di una funzione composta' wanted A1-cat, found ['A1-def']
# recall@3 = 0.83  (5 out of 6)

The result is 5 out of 6 (0.83), both with k = 1 and with k = 3, and the failure is the one that matters: "derivata di una funzione composta" (derivative of a composite function) does not find the chain rule, because the handout does not contain the word "composta" and BM25 compares words. This is the classic limit of lexical search, the lexical gap. It is addressed with embedding search (vectors that bring phrases with the same meaning close together) or by combining the two, but I did not run it here: it requires an embedding model, and I do not want to present an unmeasured result. With six questions, moreover, the estimate is very uncertain: you need a set written with the lecturers, of tens or hundreds of questions, updated with every new handout.

To evaluate the answer too there is the Ragas project, which proposes metrics that do not need hand-written reference answers: they evaluate the retrieval's ability to find relevant and focused passages, the model's ability to use them faithfully, and the quality of the generation itself. Some of these metrics rely on a model acting as judge, so they require an AI engine and a cost for every evaluation, and they were not run in this article.

Memory, privacy and what to put into production

A tutor's memory has two scales: the conversation in progress, which lives in the session and is discarded at the end, and the history between sessions, which makes it possible to remember that last week the student struggled with derivatives. The second is personal data and deserves attention. The GDPR, in Article 5, asks for data that is "adequate, relevant and limited to what is necessary" (minimisation) and kept no longer than needed for the purposes. In practice: keep a summary of the difficulties and not the text of every conversation, link it to a pseudonymous identifier (see AI Proctoring Systems for a method that holds up) and decide in writing how long you keep it. A number of days valid for everyone does not exist.

Before opening a tutor to students, four conditions matter. None of the four depends on a particular model, and the order in which you check them is irrelevant: if one is missing, you do not launch.

  • The tenant and course filter is in the index, and there is a test that tries to read another tenant's data.
  • A question outside the material receives a refusal, not an invented answer.
  • A set of labelled questions exists and the recall@k is measured on the real material.
  • Worked exercises do not reach the model at the low help levels.

The four conditions have in common that they can be checked without calling the model: they are properties of the system around it. They are also the ones that many implementations skip, because the showy part is the streaming answer and not the filter. If you have to choose where to spend the first week, spend it here.

What you can do now

You can build the surroundings of a tutor based on the course material: split documents with metadata, search by applying the tenant filter before the ranking, decide how much help to give and when to refuse, and measure retrieval with a recall@k. You also know where a word-based search fails and why a sentence of instruction is not enough to stop the model from returning a solution. In the next article the tutor meets another lever of motivation: Gamification Engine.

Frequently asked questions

Does RAG eliminate a tutor's hallucinations?

No. It reduces the model's need to remember facts and makes it possible to cite the source, but the model can ignore the passage or cite it badly. Effectiveness has to be measured on your own questions, with a recall@k for retrieval and a check of the faithfulness of the answers.

Is word-based search (BM25) or embedding search better?

It depends on the material. BM25 is simple and predictable but does not see synonyms: in the example it does not connect "funzione composta" (composite function) to the chain rule. Embeddings close the gap but require a model and have to be evaluated. Many systems combine them.

How do you stop the tutor from giving the solution directly?

A rule in the prompt is not enough. Exclude worked exercises from the context at the low help levels, using the metadata, and check that the answer does not contain the result before showing it.

Sources

The three Python listings were run with Python 3 (python3 -I rag.py, python3 guardrail.py, python3 valuta.py; the last two import rag.py, so without -I and in the same folder) and the outputs are the real ones. The corpus is invented and the recall@k value is a measurement on six questions, not an estimate. No language model or embedding model was called: the generation and the judge-based Ragas metrics were not run. The article does not name a model provider.

Commenti

Caricamento commenti...

Sign in to comment

New articles and tools on Telegram too

The Telegram channel flags the site's new articles and tools.

Did you like this article?

Explore other content on the blog or discover my projects