Sub topic 12
Answering from Your Own Documents with Retrieval
This chapter assumes you can read Python and JSON, and that you know what an embedding is: a list of numbers that places a piece of text in a space where similar meanings sit close together. If not, read the previous chapter on embeddings and semantic search first.
Why retrieval helps
A model only knows what was in its training data and what you put in the prompt. It has never seen your refund policy or your internal wiki. Retrieval-augmented generation (RAG) fixes this. Your program finds the passages most relevant to a question and places them in the prompt. The model then answers from that text instead of from memory.
RAG also reduces hallucination, because you can instruct the model to answer only from the supplied passages. It does not remove hallucination.
The pipeline
Indexing happens once, and again when documents change. Querying happens on every question.
Retrieval in miniature
The ranking step compares the query vector with each chunk vector using cosine similarity. This example uses two-dimensional vectors so you can check the result by hand.
import math
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
norm_a = math.sqrt(sum(x * x for x in a))
norm_b = math.sqrt(sum(y * y for y in b))
return dot / (norm_a * norm_b)
def top_k(query_vec, docs, k=2):
# docs is a list of (text, vector) pairs
ranked = sorted(docs, key=lambda d: cosine(query_vec, d[1]), reverse=True)
return [text for text, _ in ranked[:k]]
docs = [("refund policy", [1.0, 0.0]), ("shipping times", [0.0, 1.0]), ("refund steps", [0.9, 0.1])]
print(top_k([1.0, 0.0], docs))This prints ['refund policy', 'refund steps']. A real system uses an embedding model for the vectors, which have hundreds or thousands of dimensions, and a vector index instead of sorting every document.
Building the prompt
Put the retrieved chunks in the prompt, label them, and tell the model what to do when they do not contain the answer.
- State the rule: answer only from the sources below.
- Give a fallback: if the sources do not answer the question, say so.
- List each chunk with an identifier so the model can cite it.
- Place the question last.
Common errors
- Chunks that are too large or too small. Large chunks bury the relevant sentence and use up context. Tiny chunks lose the surrounding meaning. Start with a few hundred words and a small overlap between neighbors, then tune.
- Retrieving the wrong passages. If the right chunk never reaches the prompt, the model cannot use it. Test retrieval on its own before judging the answers.
- Too many chunks. Adding more text raises cost and can distract the model. Raise
konly when tests show it helps. - No fallback instruction. Without one, the model fills gaps with plausible guesses.
- Stale index. If documents change and the index does not, answers quote outdated text.
- Untrusted documents. Retrieved text is data, but a model may follow instructions hidden inside it. Treat documents from outside your control with care.
Exercise
A RAG assistant gives a wrong answer, and you find that the correct policy paragraph exists in your documents. Name the first thing to check and why.
Show answer
Check whether that paragraph was among the chunks retrieved for the question. If it was not, the fault is in chunking, embeddings, or search, and changing the prompt will not help. If it was retrieved, the fault is in the prompt or the model's use of the text.