Language models only know what was in their training data and what you put in the prompt. Your company handbook, last week’s incident notes and your product manuals aren’t in the first, and are usually too long for the second. Retrieval solves this: find the few passages relevant to a question, and give the model only those. The approach was named retrieval-augmented generation (RAG) in research by Lewis and colleagues in 2020, and it underpins most document assistants today.
In Stage 2 you measured extraction accuracy. Here you’ll build a small document assistant and measure the part most likely to fail: finding the right passage.
You need: the earlier setup plus a local embedding model:
ollama pull nomic-embed-text
1. Embeddings in one paragraph
An embedding is a list of numbers (a vector) representing the meaning of a piece of text. The embedding model is trained so that texts with similar meanings get vectors pointing in similar directions. Cosine similarity measures that: close to 1 means very similar, and lower means less related. Retrieval is then simple: embed every passage once, embed each question, and return the passages with the highest similarity.
2. The assistant
Save this as rag.py. It chunks every .md and .txt file in a folder, embeds the chunks, retrieves the top three for a question, and asks the model to answer only from them, citing each passage.
import json, math, pathlib, sys
import requests
OLLAMA = "http://localhost:11434"
EMBED_MODEL = "nomic-embed-text"
def embed(texts: list[str], kind: str) -> list[list[float]]:
# nomic-embed-text expects a task prefix: "search_document: " for passages, "search_query: " for questions.
prefixed = [f"search_{kind}: {t}" for t in texts]
r = requests.post(f"{OLLAMA}/api/embed", json={"model": EMBED_MODEL, "input": prefixed}, timeout=300)
r.raise_for_status()
return r.json()["embeddings"]
def chunk(text: str, size: int = 120, overlap: int = 30) -> list[str]:
words = text.split()
step = size - overlap
return [" ".join(words[i:i + size]) for i in range(0, max(len(words) - overlap, 1), step)]
def build_index(folder: str) -> list[dict]:
chunks = []
for path in sorted(pathlib.Path(folder).glob("*.md")) + sorted(pathlib.Path(folder).glob("*.txt")):
for n, text in enumerate(chunk(path.read_text())):
chunks.append({"id": f"{path.name}#{n}", "text": text})
for c, v in zip(chunks, embed([c["text"] for c in chunks], "document")):
c["vec"] = v
pathlib.Path("index.json").write_text(json.dumps(chunks))
return chunks
def cosine(a: list[float], b: list[float]) -> float:
dot = sum(x * y for x, y in zip(a, b))
return dot / (math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b)))
def search(chunks: list[dict], question: str, k: int = 3) -> list[tuple[float, dict]]:
q = embed([question], "query")[0]
return sorted(((cosine(q, c["vec"]), c) for c in chunks), key=lambda x: -x[0])[:k]
def answer(model: str, chunks: list[dict], question: str, min_score: float = 0.55) -> str:
hits = search(chunks, question)
if not hits or hits[0][0] < min_score:
return "I don't know: nothing relevant was found in the documents."
passages = "\n\n".join(f"[{c['id']}] {c['text']}" for _, c in hits)
messages = [
{"role": "system", "content": "Answer only from the passages. After each claim, cite the passage id in "
"square brackets. If the passages don't contain the answer, say you don't know."},
{"role": "user", "content": f"Passages:\n{passages}\n\nQuestion: {question}"},
]
r = requests.post(f"{OLLAMA}/api/chat", json={"model": model, "messages": messages, "stream": False,
"options": {"temperature": 0}}, timeout=300)
r.raise_for_status()
return r.json()["message"]["content"]
if __name__ == "__main__":
folder, model, question = sys.argv[1], sys.argv[2], sys.argv[3]
index = pathlib.Path("index.json")
chunks = json.loads(index.read_text()) if index.exists() else build_index(folder)
print(answer(model, chunks, question))
A few choices worth understanding:
- Chunks overlap (120 words, with 30 shared between neighbours), so a sentence cut at a boundary still appears whole in one chunk.
- Task prefixes.
nomic-embed-textis trained withsearch_document:andsearch_query:prefixes, and retrieval quality drops without them. Other embedding models have their own conventions, so check the model card. - The threshold (
min_score) is what lets the system refuse. Below it, the code never calls the chat model, so it can’t make something up. - Citations in square brackets let a reader, or a later automated check, verify every claim against its passage.
Try it on a folder of your own notes:
python rag.py notes/ <chat-model> "Who approves an expense of 800?"
3. Measure retrieval on its own
If the right passage isn’t retrieved, no prompt can produce the right answer. So test retrieval separately, with questions whose source you know, plus at least one the documents can’t answer. Save this as eval_retrieval.py:
import json, pathlib, sys
from rag import build_index, search
# (question, the file that should be retrieved). Include one question the documents can't answer.
CASES = [
("How many days of annual leave do employees get?", "handbook.md"),
("Who approves expenses above the limit?", "expenses.md"),
("What is the on-call rotation length?", "oncall.md"),
("What is the company's stock ticker?", None),
]
def main(folder: str) -> None:
chunks = build_index(folder)
hits = 0
for question, want in CASES:
results = search(chunks, question)
top_file, top_score = results[0][1]["id"].split("#")[0], results[0][0]
if want is None:
print(f" (unanswerable) top score {top_score:.2f} from {top_file}")
continue
found = any(c["id"].startswith(want) for _, c in results)
hits += found
print(f" {'hit ' if found else 'MISS'} {question} -> top {top_file} ({top_score:.2f})")
print(f"retrieval hit rate @3: {hits}/{sum(1 for _, w in CASES if w)}")
if __name__ == "__main__":
main(sys.argv[1])
4. What our test run showed
We ran both scripts on three short policy documents (a handbook, an expense policy and an on-call guide), with nomic-embed-text for embeddings and a small local chat model:
| Question | Retrieved first | Score |
|---|---|---|
| How many days of annual leave do employees get? | handbook.md | 0.88 |
| Who approves expenses above the limit? | expenses.md | 0.72 |
| What is the on-call rotation length? | oncall.md | 0.80 |
| What is the company’s stock ticker? (unanswerable) | oncall.md | 0.51 |
Retrieval found the right document for all three answerable questions. The unanswerable question still returned a “best” match, at 0.51, which is why the threshold matters: at 0.55, the assistant answered “I don’t know: nothing relevant was found in the documents.” For the expense question it answered “The employee’s department head must approve a single expense of 800 [expenses.md#0]”, which is correct and cited.
Set your own threshold from data, not from this example. Run your evaluation, look at the scores of right answers and of unanswerable questions, and put the threshold between them. Scores are only comparable within one embedding model.
5. When retrieval misses
| Symptom | Likely cause | Try |
|---|---|---|
| Right document, wrong chunk | Chunks too small, or the answer spans two | Larger chunks or more overlap |
| Wrong document scores highest | Vocabulary mismatch (“leave” vs “vacation”) | Add synonyms to documents, or combine with keyword search |
| Good passages, bad answer | The model ignores or misreads the context | Tighten the system prompt; check the citations |
| Confident answers to unanswerable questions | Threshold too low | Raise it, using your evaluation’s scores |
Project checklist
-
rag.pyanswers questions over a folder of your documents, with citations. -
eval_retrieval.pyreports a hit rate on at least eight questions, including two unanswerable ones. - You chose
min_scorefrom your evaluation’s scores, and wrote down why. - One experiment: change the chunk size, re-run the evaluation, and keep the better setting.
Prepared with AI assistance and reviewed by an editor before publication. Editorial & AI policy.