Course contents · Lesson 9 of 16

Build a RAG App over Your Own Documents

A RAG App · Lesson 9 of 16 · 12 min Hands-on

A new colleague at Kettle and Leaf asks the handbook assistant how many days a customer has to return tea. A chat model alone has never read your handbook, so it confidently describes a typical shop's policy. In this lesson you build a RAG app that first finds the handbook passages about returns, then makes the model answer from them, or say that it does not know.

Two steps: index once, then ask

RAG, retrieval-augmented generation, means your code retrieves the passages most related to a question and puts them in the prompt before the model answers, as lesson 7 introduced. Lessons 7 and 8 built chunks and embeddings; now you join them into a two-step app.

The index step runs once, offline, meaning ahead of time rather than while someone waits: it loads your documents, cuts them into chunks, embeds each chunk and stores chunks and vectors in one file, the index. The ask step runs for every question: it embeds the question, finds the closest chunks in that file and sends them to the chat model.

Two lanes. The index lane, run once with python3 index.py data/handbook: 6 Markdown files are cut into 34 chunks by heading, embedded into 768 numbers each, and saved with their vectors to index.json; rebuild when documents or settings change. No vector database is needed: 34 vectors fit in one JSON file. The ask lane, run for every question with python3 ask.py: the question is embedded with the same embedding model, the top 4 chunks are chosen by cosine similarity against the vectors read from index.json, and the chat model answers from the 4. Both lanes use the same file and the same embedding model.
The index lane writes the file once; a question only reads it and never re-embeds the documents.

The index step: load, chunk, embed, store

The lab folder course-labs/building-llm-apps/09-rag-app holds a copy of the handbook in data/handbook/ and three scripts: index.py reuses the chunking code of lesson 7, and rag.py holds the embedding, cosine and chat functions from lesson 8 and lesson 2. With both models pulled and a virtual environment as in lesson 2, run:

python3 index.py data/handbook

It cuts the six files by headings into chunks of up to 800 characters, embeds them 32 per request with the search_document: label, and saves everything. The time varies; the counts do not:

Loaded 6 files from data/handbook and cut 34 chunks (--mode headings --size 800 --overlap 100)
Embedded 34 chunks with nomic-embed-text in 4.3 s, 768 numbers each
Saved the chunks and their vectors to index.json

It worked if you see 34 chunks, as in lessons 7 and 8. Each record in index.json holds a chunk's id (file and start offset, such as 05-customer-returns.md#137), text, metadata and vector. cannot connect to Ollama means the container is stopped; HTTP 404 means a model is not pulled.

Why no vector database? A vector database finds the nearest vectors fast, even among millions. Comparing a question with 34 vectors takes milliseconds in plain Python, so one JSON file is enough. The loop gets slow only at many thousands of chunks.

The ask step: top 4 chunks, then the prompt

ask.py embeds the question with the index's model and the search_query: label, so question and chunks share one map of meaning. It scores every chunk with cosine similarity, which compares the directions of two vectors (1.0 is the same direction). Keeping the k best is called top-k retrieval, and TOP_K is 4. The core of ask.py:

def retrieve(question, index, top_k=TOP_K):
    query_vector = embed([index["query_prefix"] + question], index["model"])[0]
    scored = [(cosine(query_vector, chunk["embedding"]), chunk) for chunk in index["chunks"]]
    scored.sort(key=lambda pair: pair[0], reverse=True)   # highest score first
    return scored[:top_k]

Four chunks of up to 800 characters are at most about 800 tokens, a fifth of the 4,096-token window from lesson 3. In the flowchart, steps 2 to 4 are retrieval and steps 5 and 6 are generation, a split you will use to debug.

Flowchart of the ask step in seven numbered boxes. 1, the question, How many days do I have to return an item. 2, embed it with nomic-embed-text and the query label. 3, cosine score against all 34 stored vectors from index.json. 4, top 4 chunks, highest scores first, the other 30 dropped. The 4 chunks become the context for 5, the prompt builder: rule, then the 4 chunks, then the question. 6, the chat model llama3.2:3b at temperature 0. 7, the answer, from the chunks or I do not know. Steps 2 to 4 are retrieval, steps 5 and 6 generation.
The model never sees the other 30 chunks: whatever step 4 misses, step 6 cannot use.

The prompt has three parts in a fixed order. A system message holds the rule: answer only from the context, and if the answer is not there, reply exactly "I do not know". One user message then carries the context, the chunks numbered 1 to 4, and the question last:

def build_messages(question, retrieved):
    context = "\n\n".join(f"[{number}]\n{chunk['text']}"
                          for number, (_, chunk) in enumerate(retrieved, start=1))
    return [
        {"role": "system", "content": SYSTEM_RULE},
        {"role": "user", "content": f"Context:\n\n{context}\n\nQuestion: {question}"},
    ]

A fixed refusal phrase is easy for you, and later for code, to spot. The request sets temperature 0, as in lesson 4, so a question usually gets the same answer each time. The prompt for the returns question:

Stacked boxes of the prompt. A system message with the rule, shortened: answer only from the context; if it is not there, reply: I do not know. A user message with Context, then four chunks numbered 1 to 4, best score first, order illustrative: the return window, Refunds, Customer returns and Handling a return request. Last, the question: How many days do I have to return an item? Notes: 1, the rule, how to answer and when to refuse; 2, the evidence, the top 4 chunks, at most 800 characters each; 3, the question, last, just before the answer begins.
The model reads the rule and the evidence before it reaches the question it must answer.

Run it, with and without your documents

Ask a question the handbook answers. The script prints the retrieved chunks first, with score, id and opening text, then the answer. The output is trimmed, the scores, token counts and order after chunk 1 are illustrative, and the answer's wording will vary:

python3 ask.py 'How many days do I have to return an item?'

Question: How many days do I have to return an item?

Top 4 of 34 chunks from index.json:
  1. 0.781  05-customer-returns.md#137
     ## The return window Customers can return unopened tea within 30 days of delivery for a full ...
  2. 0.702  05-customer-returns.md#620
     ## Refunds When the parcel arrives, the warehouse checks it and marks the order as returned. ...
  ...

Answer from llama3.2:3b, with the 4 chunks above as context:
Customers can return unopened tea within 30 days of delivery for a full refund.
(tokens in: 352, tokens out: 18)

It worked if 05-customer-returns.md#137, the return window, is among the four and the answer says 30 days from delivery. index.json not found means you skipped the index step.

Now ask something the handbook does not cover: python3 ask.py 'Who won the 2011 cricket World Cup?'. Four chunks still print, since top-k always returns four, but none is about cricket, so the model should reply I do not know. A 3B model sometimes breaks the rule; the next lesson adds a refusal in code.

Then compare with the model alone: --no-rag sends only the question. Asked 'How many days of paid sick leave do I get?' that way, it can only guess; without the flag it should say 8 days, from 03-leave.md. With --no-rag the cricket question usually gets "India": right, but not from your documents.

Tune and debug: retrieval or generation?

When an answer is wrong, find which half failed. Is the chunk that holds the answer in the printed list? If not, it is a retrieval failure: the model never saw the fact. If it is there and the answer is still wrong, it is a generation failure. --show-prompt prints exactly what the model read.

What you seeFailureWhat to change
The right chunk is missingRetrievalRaise --top-k, change chunk size, reword
The right chunk is there, the answer is wrongGenerationSharper rule, fewer chunks, larger model
Nothing relevant, yet it answersGenerationStricter rule; a score threshold next lesson

--top-k sets how many chunks reach the prompt. Run python3 ask.py 'Who pays the return postage?' --top-k 1: is that one chunk "Refunds", which holds the answer? A larger k makes it likelier that the right chunk is included, but adds noise and tokens.

Chunk size lives in the index step. Run python3 index.py data/handbook --size 300, ask again and compare: smaller pieces match more sharply, but a piece cut from a long section can lose its heading. Run python3 index.py data/handbook to go back.

Check yourself

You add a new file to data/handbook, but ask.py never retrieves anything from it. Why?

ask.py only reads index.json, written before the file existed. Run the index step again whenever the documents change.

For "Who pays the return postage?" the printed chunks include Refunds, yet the answer is "I do not know". Which half failed, and would a larger --top-k help?

Generation: the fact reached the model, so retrieval worked. More chunks add noise, not the fact; check the prompt, sharpen the rule or try a larger model.

Why does the cricket question still print four chunks, although none is relevant?

Top-k returns the k best chunks whatever their scores: cosine similarity ranks chunks against each other and never says "nothing matches". So the rule must refuse; the next lesson adds a score threshold.

Go deeper