Skip to content
RAG infrastructure on Kubernetes · Chapter 2 of 20 Day 1: RAG by Hand – Classify, Compare, Answer from a Card

Day 1: RAG by Hand – Classify, Compare, Answer from a Card

Goal: Walk the whole path of a question once without any helpers: turn texts and question into vectors, find the matching card by similarity, and let the language model answer using only that card · Duration: approx. 75 min · Prerequisite: Preparation

State before this chapter

Ollama runs on rag1, and the models from the preparation are downloaded.

# on rag1
ollama list

Expected: three lines with bge-m3, nomic-embed-text and qwen3:1.7b.

Introduction

Before you run the first component in Kubernetes on Day 3, today you walk the path of a question entirely by hand. No framework, no vector store, no library – just curl, jq and the Ollama API. That way you see every intermediate stage as a file in front of you, and later you know exactly what a RAG platform actually does when it “searches”.

Today’s material is four index cards from the operations manual of a practice company: print service, VPN, leave and backup. The cards are written in German, like the company’s manual. The company, the servers and the commands in it are made up; the point is not whether druck01 exists, but whether the model reproduces exactly these details.

Today you learn:

  • to turn several texts into embeddings in one call,
  • to check whether vectors are normalised, and why that simplifies the calculation,
  • to compute the similarity of a question to every card and find the best one,
  • to let a language model answer with a card as context,
  • to recognise when no card matches, and to make the model say “I don’t know” in that case.

Background

The picture for today: the librarian with the floor plan

In the library from the preparation, every index card stands at a place that matches its meaning. When a question arrives at the desk, it also gets a place in the same shelving system – it is “classified” as if it were a card. The librarian then walks to that spot and fetches the card that stands closest. Only with this card in hand does the person at the information desk answer.

Two things make this picture important:

  • Question and cards must be classified with the same classification system. A card that was shelved by a different system stands at a place that means nothing for the question.
  • “Closest” does not mean “matching”. If there is no matching card on the shelf, one is still the closest. The person at the desk must then be able to say: “I have nothing on that.”

The terms

Term Meaning in the picture
Embedding list of numbers (vector) that describes the meaning of a text place on the shelf
normalised a vector with length 1 all cards stand equally far from the entrance
Dot product sum of the pairwise products of two vectors how much two places point in the same direction
Cosine similarity dot product divided by the product of the lengths; for normalised vectors = dot product closeness of two cards
Retrieval finding the texts most similar to the question the librarian fetches the closest card
Context text given to the language model together with the question the card on the desk

Remember: RAG is two separate steps: first the librarian searches (embedding and similarity), then the information desk answers (language model with context). If the search goes wrong, the answer cannot be good.

The path of a question

The path of a question: classify cards and question, compare, answer with the best card

Drill 1: Creating the index cards

Where you are: on rag1.

What you have afterwards: four short text files in the folder ~/kurs/01 – the mini manual for today.

Step 1 – create the folder and change into it.

# on rag1
mkdir -p ~/kurs/01
# on rag1
cd ~/kurs/01

Step 2 – the first card. It describes how to restart the print service on the print server druck01.

# on rag1
nano karte-druck.txt
~/kurs/01/karte-druck.txt new file
Druckdienst neu starten: Melde dich am Druckserver druck01 an und führe sudo systemctl restart cups aus. Prüfe danach mit lpstat -r, ob der Dienst läuft. Hängen Aufträge, leere die Warteschlange mit cancel -a.

Each card is one line with one topic. How to split longer documents into such cards is what you learn on Day 6.

Step 3 – the three other cards. VPN access with the profile firma.ovpn, requesting leave in the HR portal, and restoring a file from the nightly backup on sich01.

# on rag1
nano karte-vpn.txt
~/kurs/01/karte-vpn.txt new file
VPN-Zugang einrichten: Lade das Profil firma.ovpn aus dem Self-Service-Portal und importiere es in den OpenVPN-Client. Benutzername ist deine Personalnummer, das Einmalpasswort kommt aus der Authenticator-App.
# on rag1
nano karte-urlaub.txt
~/kurs/01/karte-urlaub.txt new file
Urlaub beantragen: Trage den Urlaub im Personalportal unter Abwesenheiten ein. Deine Führungskraft bekommt eine E-Mail und genehmigt den Antrag innerhalb von drei Arbeitstagen.
# on rag1
nano karte-backup.txt
~/kurs/01/karte-backup.txt new file
Backup wiederherstellen: Die Sicherungen laufen jede Nacht um 2 Uhr auf den Server sich01. Eine einzelne Datei stellst du mit restic restore latest --include /pfad/zur/datei wieder her.

Step 4 – check the length.

# on rag1
wc -w karte-*.txt

wc -w counts the words; karte-*.txt means all four cards.

Expected:

 27 karte-backup.txt
 33 karte-druck.txt
 23 karte-urlaub.txt
 25 karte-vpn.txt
108 total

Remember: An index card carries one thought. What is on a card later goes to the model as a whole – no more and no less.

Save your progress? Sign up for free

Drill 2: Classifying all cards in one call

Where you are: on rag1, in ~/kurs/01.

What you have afterwards: the file karten-embed.json with four vectors – one per card.

Instead of a single text, /api/embed also accepts a list of texts. That saves calls: the model is loaded once and classifies all cards one after another.

Step 1 – build the request. The cards contain colons, commas and hyphens. So that they become valid JSON, jq builds the request and takes care of the escaping:

# on rag1
jq -n --rawfile druck karte-druck.txt --rawfile vpn karte-vpn.txt --rawfile urlaub karte-urlaub.txt --rawfile backup karte-backup.txt '{model: "bge-m3", input: [$druck, $vpn, $urlaub, $backup]}' > karten-anfrage.json
Option Value Meaning
-n – start without an input file; the JSON is built entirely from the expression
--rawfile druck karte-druck.txt variable $druck reads the file as text into a variable – likewise for the other three
'{model: …, input: […]}' jq expression an object with the model name and the list of the four texts
> karten-anfrage.json redirection writes the result to a file instead of the terminal

Step 2 – check the request.

# on rag1
jq '.input | length' karten-anfrage.json

Expected:

4
# on rag1
jq -r '.input[0]' karten-anfrage.json

Expected: the text of the print card, exactly as in the file.

Step 3 – classify. -d @file sends the content of the file as the request body.

# on rag1
curl -s http://127.0.0.1:11434/api/embed -d @karten-anfrage.json -o karten-embed.json

Step 4 – four vectors?

# on rag1
jq '[.embeddings[] | length]' karten-embed.json

.embeddings[] iterates over all vectors, length counts the entries of each, [ … ] collects the results in a list.

Expected:

[
  1024,
  1024,
  1024,
  1024
]

Step 5 – how long did it take?

# on rag1
jq '{total_duration, load_duration, prompt_eval_count}' karten-embed.json

Expected:

{
  "total_duration": 17554163932,
  "load_duration": 15672033904,
  "prompt_eval_count": 216
}

What you see: 17.6 s in total, 15.7 s of it loading – the model had been unloaded. Classifying the four cards with 216 tokens altogether took less than two seconds.

Step 6 – are the vectors normalised? The length of a vector is the square root of the sum of its squares:

# on rag1
jq '[.embeddings[] | map(. * .) | add | sqrt]' karten-embed.json
Part Meaning
map(. * .) multiply each number by itself
add add up all squares
sqrt take the square root

Expected:

[
  1.0000001204723366,
  1.000000161465372,
  0.9999998624942399,
  0.9999996764938394
]

What you see: all four vectors have length 1 – apart from rounding in the seventh decimal place. Through Ollama, bge-m3 delivers normalised vectors. That saves a calculation later: for vectors of length 1, the cosine similarity is simply the dot product.

Remember: First check whether the vectors are normalised, then compute. Many vector databases assume this for “cosine” – if it is not true, the hits are not right.

Save your progress? Sign up for free

Drill 3: Classifying the question and finding the best card

Where you are: on rag1, in ~/kurs/01.

What you have afterwards: for three questions, one list of four similarities each – and a feel for when a hit is clear-cut.

Step 1 – classify the first question. With the same model as the cards. The question is in German (“How do I restart the print service?”):

# on rag1
curl -s http://127.0.0.1:11434/api/embed -d '{"model":"bge-m3","input":"Wie starte ich den Druckdienst neu?"}' -o frage1-embed.json

Step 2 – similarity to every card. The following expression takes the question’s vector and computes the dot product with every card vector:

# on rag1
jq -n --slurpfile k karten-embed.json --slurpfile f frage1-embed.json '$f[0].embeddings[0] as $q | [$k[0].embeddings[] | [., $q] | transpose | map(.[0] * .[1]) | add]'
Part Meaning
--slurpfile k karten-embed.json reads the file into the variable $k (as a list with one element, hence $k[0])
$f[0].embeddings[0] as $q the question’s vector is called $q from here on
$k[0].embeddings[] iterates over the four card vectors
[., $q] \| transpose puts card and question side by side: 1024 pairs
map(.[0] * .[1]) \| add multiply the pairs and sum them up – the dot product

Expected (order as in the request: print, VPN, leave, backup):

[
  0.7544958303555799,
  0.4392355246478485,
  0.38482364389264256,
  0.46350167508729523
]

What you see: with 0.75, the print card is far ahead of the others (0.38 to 0.46). A clear hit. Values around 0.4 do not mean “matches a little” here: that is how similar questions and cards are in this lab even when they have nothing to do with each other.

Step 3 – a paraphrased question. This question (“My printout doesn’t come out, what can I do?”) contains neither “Druckdienst” (print service) nor “neu starten” (restart):

# on rag1
curl -s http://127.0.0.1:11434/api/embed -d '{"model":"bge-m3","input":"Mein Ausdruck kommt nicht raus, was kann ich tun?"}' -o frage2-embed.json
# on rag1
jq -n --slurpfile k karten-embed.json --slurpfile f frage2-embed.json '$f[0].embeddings[0] as $q | [$k[0].embeddings[] | [., $q] | transpose | map(.[0] * .[1]) | add]'

Expected:

[
  0.4626510750099765,
  0.38622913162118816,
  0.41066038599888444,
  0.3839740667058124
]

What you see: the print card wins here too – although not a single word matches. But only narrowly: 0.46 against 0.41 for the leave card. That is the difference from keyword search: meaning is found, but with a small margin. How to improve such narrow cases is what you measure on Days 7 and 8.

Step 4 – an English question.

# on rag1
curl -s http://127.0.0.1:11434/api/embed -d '{"model":"bge-m3","input":"How do I restore a deleted file?"}' -o frage3-embed.json
# on rag1
jq -n --slurpfile k karten-embed.json --slurpfile f frage3-embed.json '$f[0].embeddings[0] as $q | [$k[0].embeddings[] | [., $q] | transpose | map(.[0] * .[1]) | add]'

Expected:

[
  0.41823317285289385,
  0.40386157223560026,
  0.35826890640368564,
  0.5733427405648066
]

What you see: the backup card is German, the question English – and still it leads with 0.57. bge-m3 is multilingual: the same meaning lands at a similar place on the shelf, no matter which language.

Remember: The librarian finds meaning, not words. How clear-cut a hit is, only the margin to the second-best card tells you.

Save your progress? Sign up for free

Drill 4: Answering with and without a card

Where you are: on rag1, in ~/kurs/01.

What you have afterwards: two answers to the same question – once guessed, once from the card – and their durations compared.

Step 1 – ask without a card.

# on rag1
curl -s http://127.0.0.1:11434/api/generate -d '{"model":"qwen3:1.7b","prompt":"Wie starte ich den Druckdienst neu?","stream":false,"think":false}' -o ohne.json
# on rag1
jq -r .response ohne.json

Expected (excerpt, the full answer has 78 lines):

Um den **Druckdienst** neu zu starten, gibt es mehrere Möglichkeiten, abhängig von dem Betriebssystem und dem verwendeten Druckdienst. Hier sind die gängigsten Methoden:
#### **Linux (z. B. CUPS):**
   sudo systemctl restart cups
3. Falls CUPS nicht läuft, versuche:
   sudo systemctl restart printer-jawbreakers

What you see: the model knows nothing about your company and guesses. It mixes Windows, macOS and Linux, names no server – and invents a service printer-jawbreakers that does not exist.

# on rag1
jq '{total_duration, eval_count}' ohne.json

Expected:

{
  "total_duration": 82646385414,
  "eval_count": 722
}

722 tokens in 82.6 s – over a minute for a wrong answer.

Step 2 – build the request with a card. The prompt consists of an instruction (“Answer the question only with the text between the lines.”), the card between two lines, and the question:

# on rag1
jq -n --rawfile karte karte-druck.txt --arg frage "Wie starte ich den Druckdienst neu?" '{model: "qwen3:1.7b", stream: false, think: false, prompt: ("Beantworte die Frage nur mit dem Text zwischen den Linien.\n---\n" + $karte + "---\nFrage: " + $frage)}' > mit-anfrage.json
Option Meaning
--rawfile karte karte-druck.txt the best card from Drill 3 as the variable $karte
--arg frage "…" the question as the variable $frage
"…" + $karte + "…" joins instruction, card and question into one text; \n is a line break

Step 3 – look at the prompt.

# on rag1
jq -r .prompt mit-anfrage.json

Expected:

Beantworte die Frage nur mit dem Text zwischen den Linien.
---
Druckdienst neu starten: Melde dich am Druckserver druck01 an und führe sudo systemctl restart cups aus. Prüfe danach mit lpstat -r, ob der Dienst läuft. Hängen Aufträge, leere die Warteschlange mit cancel -a.
---
Frage: Wie starte ich den Druckdienst neu?

Step 4 – ask with the card.

# on rag1
curl -s http://127.0.0.1:11434/api/generate -d @mit-anfrage.json -o mit.json
# on rag1
jq -r .response mit.json

Expected:

Druckdienst neu starten: Melde dich am Druckserver druck01 an und führe sudo systemctl restart cups aus. Prüfe danach mit lpstat -r, ob der Dienst läuft. Hängen Aufträge, leere die Warteschlange mit cancel -a.
# on rag1
jq '{total_duration, prompt_eval_count, eval_count}' mit.json

Expected:

{
  "total_duration": 9293513125,
  "prompt_eval_count": 116,
  "eval_count": 69
}

What you see: the answer is verbatim from the card – with server, command and check. It arrives in 9.3 s instead of 82.6 s, because the model writes only 69 instead of 722 tokens. Here, context makes the answer not only more correct but also nine times faster.

Remember: Without a card the information desk guesses; with a card it quotes. The context is not an addition to the question but the source of the answer.

Save your progress? Sign up for free

Diagnosis task

A colleague asks: “How do I get a new laptop?” The manual has no card on that. You have 15 minutes. What does the search deliver, what does the model answer – and how do you get it to be honest?

Solution:

1. Classify the question and compare:

# on rag1
curl -s http://127.0.0.1:11434/api/embed -d '{"model":"bge-m3","input":"Wie bekomme ich einen neuen Laptop?"}' -o frage4-embed.json
# on rag1
jq -n --slurpfile k karten-embed.json --slurpfile f frage4-embed.json '$f[0].embeddings[0] as $q | [$k[0].embeddings[] | [., $q] | transpose | map(.[0] * .[1]) | add]'

Expected:

[
  0.42799924142933915,
  0.4319794688546486,
  0.43492999260691706,
  0.3807812239076133
]

All four values are in the background noise (0.38 to 0.43); no card stands out. Still, one is “the best”: the leave card with 0.435.

2. Ask with this card and the instruction from Drill 4:

# on rag1
jq -n --rawfile karte karte-urlaub.txt --arg frage "Wie bekomme ich einen neuen Laptop?" '{model: "qwen3:1.7b", stream: false, think: false, prompt: ("Beantworte die Frage nur mit dem Text zwischen den Linien.\n---\n" + $karte + "---\nFrage: " + $frage)}' > laptop-anfrage.json
# on rag1
curl -s http://127.0.0.1:11434/api/generate -d @laptop-anfrage.json -o laptop.json
# on rag1
jq -r .response laptop.json

Expected:

Wie bekomme ich einen neuen Laptop?

The model only repeats the question – it is supposed to answer from the text, finds nothing and does not know what to do then.

3. Give the instruction a way out (“If the answer is not in it, answer exactly: That is not in the manual.”):

# on rag1
jq -n --rawfile karte karte-urlaub.txt --arg frage "Wie bekomme ich einen neuen Laptop?" '{model: "qwen3:1.7b", stream: false, think: false, prompt: ("Beantworte die Frage nur mit dem Text zwischen den Linien. Steht die Antwort nicht darin, antworte genau: Das steht nicht im Handbuch.\n---\n" + $karte + "---\nFrage: " + $frage)}' > laptop2-anfrage.json
# on rag1
curl -s http://127.0.0.1:11434/api/generate -d @laptop2-anfrage.json -o laptop2.json
# on rag1
jq -r .response laptop2.json

Expected:

Das steht nicht im Handbuch.

4. Cross-check – the new instruction must not break correct answers. Build the same request with karte-druck.txt and the print question as druck2-anfrage.json and send it. In the author’s lab, the first sentence of the card came back:

Druckdienst neu starten: Melde dich am Druckserver druck01 an und führe sudo systemctl restart cups aus.

Correct, but shorter than before – the check with lpstat is missing. Every change to the prompt also changes the answers that were good before. That is why you measure with fixed test questions from Day 7 on.

Challenge

Additionally classify the four cards and the question “How do I restore a deleted file?” with nomic-embed-text and compute the similarities. Is the backup card still ahead, and how large is the margin? Write down the result – on Day 2 you compare the models systematically.

Save your progress? Sign up for free

Checkpoint

# on rag1
ls ~/kurs/01

Expected:

druck2-anfrage.json
druck2.json
frage1-embed.json
frage2-embed.json
frage3-embed.json
frage4-embed.json
karte-backup.txt
karte-druck.txt
karte-urlaub.txt
karte-vpn.txt
karten-anfrage.json
karten-embed.json
laptop-anfrage.json
laptop.json
laptop2-anfrage.json
laptop2.json
mit-anfrage.json
mit.json
ohne.json
# on rag1
jq '.embeddings | length' ~/kurs/01/karten-embed.json

Expected:

4

Test yourself

  1. Why must question and cards be classified with the same embedding model?
  2. How do you recognise that you may compute the cosine similarity as a simple dot product?
  3. The best card has 0.44, the second-best 0.43. What does that say about the hit?
  4. Why was the answer with a card faster than without?
  5. What happens when no card matches and the instruction names no way out?

Answers:

  1. Every model has its own classification system. Vectors from two models live in different spaces; their dot product means nothing.
  2. The length of every vector is 1 (map(. * .) | add | sqrt). Then cosine = dot product.
  3. Nothing good: the margin is so small that the hit may be chance – in the lab, everything without a real hit was between 0.38 and 0.46.
  4. The model wrote 69 instead of 722 tokens. For a model on the CPU, the length of the answer almost single-handedly determines the duration.
  5. The model does something or other – in the lab it repeated the question. Only “answer exactly: That is not in the manual” gives it a permitted answer.

Interview note

“Explain RAG in two minutes.” – Two models, two steps: an embedding model places documents and question in the same vector space, the most similar passages are searched, and a language model answers only from them. Add what goes wrong: narrow hits, no matching passage, a prompt without a way out. Naming numbers – “with context 9 instead of 83 seconds” – shows that you have measured it.

Enterprise note

In production nobody works out similarity with jq. But every RAG platform performs exactly these steps, and errors can only be found if every stage can be queried individually: which passages did the search return, with which similarity, which prompt went to the model? Platforms that do not log this are blind in operation. That is why, from Day 9 on, you build an answer service that returns its sources.

Summary

You classified four index cards in one call, checked that bge-m3 delivers normalised vectors, and computed the similarity of questions to every card with jq. Clear-cut questions hit clearly (0.75), paraphrased ones only narrowly (0.46 against 0.41), English questions found German cards. With the matching card, qwen3 answered correctly in 9.3 s; without a card it guessed for 82.6 s. When no card matched, only an instruction with a way out helped: “Das steht nicht im Handbuch.” (That is not in the manual.)

Commands at a glance

Command What it does Parameters
jq -n --rawfile v datei '{…}' > anfrage.json build a JSON request from text files -n no input, --rawfile file as text, --arg value
curl -s …/api/embed -d @anfrage.json -o embed.json request embeddings -d @file body from file, -o output file
jq '[.embeddings[] \| length]' embed.json length of every vector –
jq '[.embeddings[] \| map(. * .) \| add \| sqrt]' embed.json norm of every vector –
jq -n --slurpfile k … --slurpfile f … '…transpose…' similarity question ↔︎ cards --slurpfile JSON file as variable
curl -s …/api/generate -d @anfrage.json -o antwort.json generate an answer with a prompt "stream":false, "think":false
jq -r .response antwort.json read the answer text -r without quotes
wc -w datei count words -w words

Contents

More