A plain chat bot will happily invent a fee. If a parent asks, “How much is monthly tuition at Shree Vidya?” and you send that question to a model with no notes attached, the model may guess ₹2,000 or a discount you never ran. Retrieval-augmented generation (RAG) reduces that risk: first find the passages you already trust, then ask the model to answer only from those passages.
The idea is language-agnostic. This lesson uses Python for the working code, but the three steps — embed, retrieve, generate — are the same in PHP or JavaScript. You will implement cosine similarity, test it on tiny vectors, and only then wire in mock API calls.
Key takeaways
- RAG has three steps: embed text, find the nearest passages, then generate an answer grounded in those passages.
- Cosine similarity scores how close two vectors are; you can test it without an API.
- If the best score is below a threshold, refuse rather than let the model improvise.
- The prompt must say “use only these passages” and must include the retrieved text.
- API keys still belong in the environment; retrieval does not replace careful prompting.
The three steps
- Index. Store short factual passages, such as “Monthly tuition is ₹1,500, payable by the 5th.” Each passage becomes a list of numbers — an embedding — so similar meanings sit near each other.
- Retrieve. Embed the parent’s question, score it against every stored passage, and keep the top one or two.
- Generate. Send the question plus those passages to a chat model, with a hard instruction: answer only from the passages, or say you do not have it in your notes.
Without retrieval you have a chatbot. Without the refusal, you still have a chatbot that can wander. Both pieces matter.
Cosine similarity, written out
An embedding is just a vector. Cosine similarity is the cosine of the angle between two vectors: 1 means they point the same way, 0 means they are orthogonal, and −1 means they point opposite ways. Closer to 1 usually means “more related.”
import math
def cosine_similarity(a, b):
if len(a) != len(b):
raise ValueError("Vectors must be the same length.")
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(y * y for y in b))
if na == 0.0 or nb == 0.0:
return 0.0
return dot / (na * nb)
This function was tested on this machine: identical vectors score 1.0, orthogonal vectors score 0.0, opposite vectors score −1.0, [1, 1] vs [1, 0] scores 1 / √2 ≈ 0.7071, and a zero vector scores 0.0 (no divide by zero). Get the maths right first, then plug in real embeddings.
Rank the notes
Store each passage with an id, the text, and a vector. A lesson-sized FAQ can live in a list. In production you might use a vector database, but the ranking logic is the same.
docs = [
{
"id": "fees",
"text": "Monthly tuition is ₹1,500, payable by the 5th.",
"vector": [1.0, 0.1, 0.0],
},
{
"id": "hours",
"text": "The centre opens at 4:00 pm and closes at 8:00 pm.",
"vector": [0.1, 1.0, 0.0],
},
{
"id": "science",
"text": "Science batch is on Thursday from 5:00 pm to 6:00 pm.",
"vector": [0.0, 0.1, 1.0],
},
]
def top_k(query, docs, k=2):
scored = [(cosine_similarity(query, doc["vector"]), doc) for doc in docs]
scored.sort(key=lambda item: item[0], reverse=True)
return scored[:k]
A fee-like query vector such as [0.95, 0.12, 0.02] ranked the fees passage first in the test (score ≈ 0.999), with hours far behind (≈ 0.223). A question about money should not retrieve the Thursday science batch as its top hit.
In a real system the vectors come from an embeddings API, for example POST /v1/embeddings with the question as input, and the same Authorization: Bearer … header you use for chat. Read the key from AI_API_KEY. On this machine that call was tested against a local mock: a valid key returned a vector close to the fees passage; a wrong key returned HTTP 401.
Ground the prompt, or refuse
Retrieval is not enough. You must attach the winning passages to the chat prompt, and you must set a floor. If every score is weak, say so.
def build_grounded_prompt(question, retrieved, threshold=0.5):
usable = [(score, doc) for score, doc in retrieved if score >= threshold]
if not usable:
return (
"The knowledge base has no passage similar enough to this question. "
"Reply with exactly: I do not have that in my notes.",
[],
)
lines = [f"- ({doc['id']}) {doc['text']}" for score, doc in usable]
context = "\n".join(lines)
prompt = (
"Answer the question using only the facts in the passages below. "
"If the passages do not contain the answer, say you do not have that "
"in your notes. Do not invent fees, times, or names.\n\n"
f"Passages:\n{context}\n\n"
f"Question: {question}"
)
return prompt, [doc["id"] for score, doc in usable]
For “How much is the monthly fee?” the tests built a prompt that included the ₹1,500 passage. For a zero vector — a stand-in for “What is the canteen menu?” when you have no canteen note — the helper returned no passage ids and instructed the model to say it does not have that in its notes. A helpful-sounding guess about a canteen you do not run is worse than a short “I do not know.”
Then send the prompt to /v1/chat/completions as in the earlier lessons (timeout, JSON parse, check choices[0].message.content, never hardcode the key). You can also check that any rupee amount in the reply appears in the retrieved text.
Try this
Add a fourth passage about a ₹100 late charge, with a vector close to the fees one (for example [0.9, 0.15, 0.05]). Ask “Is there a late fee?” and confirm it ranks above hours and science. Then ask about a Sunday cricket batch with a vector far from all notes, and confirm that build_grounded_prompt refuses.
What this pattern does not do
RAG is not magic: stale notes produce confidently wrong answers, and a wrong passage can still “ground” a bad fact. Embed each passage once, store the vector, and only embed new questions at query time. Start with a dozen proof-read notes and a logged “I do not know” path.
What you learned
- RAG means retrieve first, then generate, with the retrieved text in the prompt.
- Cosine similarity is enough to rank a small FAQ and can be tested locally.
- A similarity threshold plus “use only these passages” is what makes the answer grounded.
- Embeddings and chat calls still use an environment-stored key and the same error handling as a plain chat script.
Quick quiz
-
1. What is the main reason to retrieve passages before you call the chat model?
- A) So the model can invent a more confident fee
- B) So the answer can be grounded in notes you already trust
- C) So you can avoid using an API key
Show answer
B. RAG does not remove the key or the model. It constrains the model to your passages.
-
2. Cosine similarity of
[1, 0]and[0, 1]is:- A) 1
- B) 0
- C) −1
Show answer
B. The vectors are orthogonal. Identical vectors score 1; opposite vectors score −1.
-
3. Every stored passage scores 0.1 against “What is the canteen menu?” and your threshold is 0.5. What should happen?
- A) Send all passages anyway and hope
- B) Refuse, and tell the model (or the user) that you do not have that in your notes
- C) Lower the threshold to 0 for this question only, quietly
Show answer
B. A weak match is how invented answers sneak back in. Refusal is the safe default.
-
4. You change the monthly fee from ₹1,500 to ₹1,600 in real life. What must you update?
- A) Nothing — the model will notice
- B) The passage text, and then you must re-embed that passage
- C) Only the system prompt, not the notes
Show answer
B. The index is the source of truth. Stale notes produce stale grounded answers. Re-embed after you edit.
Next lesson
A natural follow-on (not yet drafted) is to persist the notes, re-embed when a passage changes, and keep a small set of questions with known good matches. Until then, expand the Shree Vidya FAQ and watch which passage wins.