Day 9: The Answer Service
Goal: Connect search and language model into one service that answers with source references, streams the answer, does not wait forever and can say “I don’t know” – and measure where the time goes · Duration: approx. 120 min · Prerequisite: Day 8
State before this chapter
# on rag1
kubectl -n rag get pod curl qdrant-0Expected: both 1/1 Running. If
curl shows Completed, recreate the pod as on
Day 6, Drill 6, Step 1.
# on rag1
kubectl -n rag get deployment embed rerankExpected:
NAME READY UP-TO-DATE AVAILABLE AGE
embed 1/1 1 1 18h
rerank 1/1 1 1 69m
Your age will be different. The embedding service from Day 3 and the reranker from Day 8 are running.
Introduction
Since Day 1 the librarian has been fetching cards from the cabinet,
and since Day 7 you have been measuring how well he does it. In all that
time nobody has received an answer – except on Day 1, when you put the
prompt together by hand with jq. Today you turn that into a
service: an address in the cluster that you send a
question to and that returns an answer with card numbers.
On the way you meet four questions that every answer service in operation has to answer: How does the user know where the answer comes from? What does he see while the model is computing? How long does the service wait before it gives up? And what does it answer when there is nothing suitable in the collection? At the end of the day you will also see an answer that is wrong, sounds fluent and names a source.
Today you learn:
- to run a language model as a service of its own next to the embedding service,
- an answer service with source references in about 180 lines of Python without libraries,
- where the time of an answer goes – search, reading the prompt, writing the answer,
- streaming and why it only seems to speed up the first word,
- timeouts that relieve not only the user but also the model,
- “I don’t know” with a score threshold and an instruction in the prompt – and where both reach their limits.
Background
The picture for today: the information desk
So far you have worked in the stacks. Today the information desk opens. A visitor asks a question. The librarian fetches three cards, numbers them and puts them in front of the person at the information desk. She reads all three cards in full before she says the first sentence. Then she answers and, for every statement, names the number of the card it is on.
Three rules hang at the desk. First: the person at the desk speaks as soon as she knows the first sentence, instead of first writing the whole answer on a slip of paper. Second: whoever waits too long at the desk draws a waiting ticket – when it expires he leaves, and the person at the desk stops working for him. Third: if the librarian only finds cards that are far from the topic, he says “we have nothing on that” right at the shelf – the person at the desk then does not have to read at all.
The terms
| Term | Meaning | in the picture |
|---|---|---|
| Answer service | service that embeds the question, searches for cards, builds the prompt and asks the language model | the desk |
| System message | instruction and cards that the model gets before the question | the cards lying on the desk |
| User message | the question itself | what the visitor says |
| Source reference | card number in square brackets after a statement,
e.g. [1] |
“it says so on card 1” |
| Reading the prompt (prompt eval) | the model processes all input tokens before it generates the first word | reading through the cards |
| Writing the answer (eval) | the model generates the answer token by token | speaking |
| Streaming | pass on every generated piece immediately instead of everything at once at the end | speaking sentence by sentence |
| First word | time from the question to the first piece of the answer (time to first token) | until the person at the desk opens her mouth |
| Prompt cache | Ollama keeps prompts it has read in RAM; an identical beginning is not read again | the cards are still on the table |
| Timeout | how long the answer service waits for the model | waiting ticket |
| Score threshold | minimum similarity of the best card; below it the service answers “I don’t know” without the model | “we have nothing on that” at the shelf |
| Hallucination | statement that is on no card | answer without a card |
Remember: The person at the desk answers only as well as the cards you put in front of her – and she reads them in full every time before she speaks.
Drill 1: The person at the desk moves in
Where you are: on rag1.
What you have afterwards: a service
llmin the namespaceragthat offers the language modelqwen3:1.7bon rag1 – separate from the embedding service.
Why a service of its own. The embedding service from
Day 3 is Ollama too. You could load qwen3:1.7b there as
well. Then embedding and answering would compute in the same pod, share
memory limit and restarts, and on Day 10 you could no longer see which
stage is slowing things down. Two tasks, two services – as with the
reranker on Day 8.
Step 1 – how full rag1 is. The scheduler places pods according to their requests – what a pod is supposed to be guaranteed. Look at how much of it is already allocated on rag1:
# on rag1
kubectl describe node rag1Expected (excerpt – the section
Allocated resources at the end):
Allocated resources:
(Total limits may be over 100 percent, i.e., overcommitted.)
Resource Requests Limits
-------- -------- ------
cpu 3200m (80%) 2 (50%)
memory 3212Mi (40%) 5290Mi (66%)
| Column | Value | Meaning |
|---|---|---|
cpu Requests |
3200m (80%) |
3.2 of 4 cores are promised: embedding service 2, reranker 1, CoreDNS and metrics server 0.1 each |
memory Requests |
3212Mi (40%) |
promised memory |
| Limits | 2, 5290Mi |
upper limits; the CPU limit of 2 comes from the reranker |
What you see: There is no room left for a language
model that is supposed to get at least one and a half cores. A new pod
with this request would stay Pending.
Step 2 – send the expert reader on a break. On Day 8 you decided: the reranker stays as a switch, switched off by default. Switched off also means: it does not need a pod. You set the number of replicas to zero. Deployment, volume with the model and service are kept:
# on rag1
kubectl -n rag scale deployment rerank --replicas=0scale … --replicas=0: the deployment should no longer have a pod; Kubernetes stops the running one.
Expected:
deployment.apps/rerank scaled
# on rag1
kubectl -n rag get deployment rerankExpected:
NAME READY UP-TO-DATE AVAILABLE AGE
rerank 0/0 0 0 69m
0/0 means: zero pods wanted, zero ready. With
--replicas=1 the reranker is back within a minute – the
model is still in the volume.
Step 3 – the folder for today.
# on rag1
mkdir -p ~/kurs/09# on rag1
cd ~/kurs/09Step 4 – the manifest. It follows the pattern of the embedding service from Day 3: volume for the model, deployment, service.
# on rag1
nano llm.yamlapiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: llm-modell
namespace: rag
spec:
accessModes: ["ReadWriteOnce"]
storageClassName: local-path
resources:
requests:
storage: 5Gi
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: llm
namespace: rag
spec:
replicas: 1
strategy:
type: Recreate
selector:
matchLabels:
app: llm
template:
metadata:
labels:
app: llm
spec:
nodeSelector:
kubernetes.io/hostname: rag1
containers:
- name: ollama
image: ollama/ollama:0.40.19
env:
- name: OLLAMA_KEEP_ALIVE
value: "-1"
ports:
- containerPort: 11434
resources:
requests:
cpu: 1500m
memory: 2Gi
limits:
memory: 3Gi
readinessProbe:
httpGet:
path: /api/version
port: 11434
periodSeconds: 5
volumeMounts:
- name: modell
mountPath: /root/.ollama
volumes:
- name: modell
persistentVolumeClaim:
claimName: llm-modell
---
apiVersion: v1
kind: Service
metadata:
name: llm
namespace: rag
spec:
selector:
app: llm
ports:
- port: 11434
targetPort: 11434| Setting | Value | Meaning |
|---|---|---|
PVC llm-modell |
5 GiB, local-path |
a volume of its own; the model is 1.4 GB and survives restarts of the pod |
strategy: Recreate |
– | first stop the old pod, then start the new one; the RWO volume is attached to one pod |
nodeSelector |
rag1 |
four cores, and that is where the volume is after the first start |
image |
ollama/ollama:0.40.19 |
the same version as the embedding service |
OLLAMA_KEEP_ALIVE |
"-1" |
never unload the model – otherwise the first question after a five-minute pause is cold |
requests.cpu |
1500m |
one and a half cores promised; fits next to the 2.2 cores that are allocated after Step 2 |
requests.memory / limits.memory |
2 GiB / 3 GiB | memory for model and context; above that the kernel stops the pod |
| no CPU limit | – | as with the embedding service: the model may use free cores (Day 3, Drill 5) |
readinessProbe |
/api/version |
requests only once Ollama answers |
Service llm |
port 11434 | address in the cluster: http://llm.rag:11434 |
Step 5 – apply.
# on rag1
kubectl apply -f llm.yamlExpected:
persistentvolumeclaim/llm-modell created
deployment.apps/llm created
service/llm created
# on rag1
kubectl -n rag rollout status deployment/llm --timeout=300sExpected (in the lab after 12 seconds):
Waiting for deployment "llm" rollout to finish: 0 of 1 updated replicas are available...
deployment "llm" successfully rolled out
Step 6 – load the model. The pod is ready, but the volume is empty. You load the model with the Ollama program inside the pod:
# on rag1
kubectl -n rag exec deployment/llm -- ollama pull qwen3:1.7bexec deployment/llm: run the command in a pod of the deployment,--: everything after it is the command in the pod,ollama pull qwen3:1.7b: load the model from the Ollama registry into the volume.
Expected (excerpt – the last two lines, in the lab after 2 minutes 5 seconds):
writing manifest
success
# on rag1
kubectl -n rag exec deployment/llm -- ollama listExpected:
NAME ID SIZE MODIFIED
qwen3:1.7b 8f68893c685c 1.4 GB 1 second ago
Step 7 – what the model brings along.
# on rag1
kubectl -n rag exec deployment/llm -- ollama show qwen3:1.7bExpected (excerpt):
Model
architecture qwen3
parameters 2.0B
context length 40960
embedding length 2048
quantization Q4_K_M
Capabilities
completion
tools
thinking
levels false, true
default true
Parameters
repeat_penalty 1
stop "<|im_start|>"
stop "<|im_end|>"
temperature 0.6
top_k 20
top_p 0.95
| Line | Value | Meaning |
|---|---|---|
parameters |
2.0B |
around two billion weights – small enough for the CPU |
quantization |
Q4_K_M |
weights stored with about 4 bits; hence only 1.4 GB |
thinking … default true |
– | without further instructions, the model first “thinks” out loud
before it answers; the answer service switches that off with
"think": false as on Day 1 |
temperature |
0.6 |
randomness in the choice of words; the answer service sets 0 so that the same question with the same cards gets the same answer |
Step 8 – look again.
# on rag1
kubectl describe node rag1Expected (excerpt – section
Allocated resources):
Resource Requests Limits
-------- -------- ------
cpu 3700m (92%) 0 (0%)
memory 4236Mi (53%) 6314Mi (79%)
What you see: One core less for the reranker, one and a half more for the language model – 3.7 of 4 cores are promised. The CPU limit has dropped to 0: no pod on rag1 has one any more.
Remember: A switched-off service is a deployment with zero replicas – not deleted, just on leave. That way the switch from Day 8 stays a switch and still does not occupy a core.
Save your progress? Sign up for free
Drill 2: The answer service
Where you are: on rag1, in
~/kurs/09.What you have afterwards: the service
antwortin the namespacerag, reachable viahttp://antwort.rag, with the path/fragefor questions and/healthfor the probes.
Step 1 – the code. Like ingestion and the test bench, the answer service only uses Python’s standard library. Read it through once in full before you type it in – the table below guides you through the parts.
# on rag1
nano antwort.py"""Antwortdienst: Frage einbetten, Karten suchen, mit Quellenangabe antworten."""
import json
import os
import time
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
EMBED = os.environ.get("EMBED_URL", "http://embed.rag:11434")
QDRANT = os.environ.get("QDRANT_URL", "http://qdrant.rag:6333")
LLM = os.environ.get("LLM_URL", "http://llm.rag:11434")
RERANK = os.environ.get("RERANK_URL", "")
SAMMLUNG = os.environ.get("SAMMLUNG", "wissen")
MODELL = os.environ.get("MODELL", "bge-m3")
LLM_MODELL = os.environ.get("LLM_MODELL", "qwen3:1.7b")
KARTEN = int(os.environ.get("KARTEN", "3"))
KANDIDATEN = int(os.environ.get("KANDIDATEN", "20"))
MINDEST = float(os.environ.get("MINDEST_SCORE", "0"))
LLM_TIMEOUT = float(os.environ.get("LLM_TIMEOUT", "120"))
MAX_TOKEN = int(os.environ.get("MAX_TOKEN", "300"))
KEINE = "Dazu steht nichts im Handbuch."
ANWEISUNG = (
"Du bist die IT-Auskunft einer Firma. Beantworte die Frage des Nutzers auf "
"Deutsch, kurz, und nur mit dem Inhalt der Karten unten. Nenne hinter jeder "
"Aussage die Nummer der Karte in eckigen Klammern, zum Beispiel [1]. Steht die "
f"Antwort auf keiner Karte, antworte genau: {KEINE}\n\nKarten:\n"
)
def anfrage(url, daten, timeout=30):
req = urllib.request.Request(
url,
data=json.dumps(daten).encode(),
headers={"Content-Type": "application/json"},
)
return urllib.request.urlopen(req, timeout=timeout)
def suchen(frage):
"""Frage einbetten, Karten holen, auf Wunsch vom Reranker neu ordnen."""
with anfrage(f"{EMBED}/api/embed", {"model": MODELL, "input": [frage]}) as a:
vektor = json.load(a)["embeddings"][0]
koerper = {
"query": vektor,
"limit": KANDIDATEN if RERANK else KARTEN,
"with_payload": True,
}
with anfrage(f"{QDRANT}/collections/{SAMMLUNG}/points/query", koerper) as a:
punkte = json.load(a)["result"]["points"]
if RERANK and punkte:
texte = [p["payload"]["text"] for p in punkte]
with anfrage(f"{RERANK}/rerank", {"query": frage, "texts": texte}, 120) as a:
punkte = [punkte[u["index"]] for u in json.load(a)]
return punkte[:KARTEN]
def nachrichten(frage, punkte):
"""Anweisung und nummerierte Karten als System-, die Frage als Nutzernachricht."""
karten = [
f"[{nr}] {p['payload']['abschnitt']}\n{p['payload']['text']}\n"
for nr, p in enumerate(punkte, start=1)
]
return [
{"role": "system", "content": ANWEISUNG + "\n".join(karten)},
{"role": "user", "content": frage},
]
class Auskunft(BaseHTTPRequestHandler):
def senden(self, status, daten):
rumpf = json.dumps(daten, ensure_ascii=False).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(rumpf)))
self.end_headers()
self.wfile.write(rumpf)
def zeile(self, daten):
self.wfile.write(json.dumps(daten, ensure_ascii=False).encode() + b"\n")
self.wfile.flush()
def do_GET(self):
if self.path == "/health":
self.senden(200, {"status": "ok"})
else:
self.senden(404, {"fehler": "unbekannter Pfad"})
def do_POST(self):
if self.path != "/frage":
self.senden(404, {"fehler": "unbekannter Pfad"})
return
laenge = int(self.headers.get("Content-Length", 0))
eingabe = json.loads(self.rfile.read(laenge) or b"{}")
frage = str(eingabe.get("frage", "")).strip()
if not frage:
self.senden(400, {"fehler": "frage fehlt"})
return
start = time.time()
punkte = suchen(frage)
zeiten = {"suche": round(time.time() - start, 2)}
bester = punkte[0]["score"] if punkte else 0.0
if bester < MINDEST:
print(f"keine Karte bester {bester:.3f} {frage}", flush=True)
self.senden(200, {"antwort": KEINE, "quellen": [], "sekunden": zeiten})
return
quellen = [
{
"nr": nr,
"quelle": p["payload"]["quelle"],
"abschnitt": p["payload"]["abschnitt"],
"score": round(p["score"], 3),
}
for nr, p in enumerate(punkte, start=1)
]
if eingabe.get("stream"):
self.strom(frage, punkte, quellen, start, zeiten)
else:
self.ganz(frage, punkte, quellen, start, zeiten)
def ganz(self, frage, punkte, quellen, start, zeiten):
"""Auf die ganze Antwort warten und sie in einem Stück senden."""
koerper = {
"model": LLM_MODELL,
"messages": nachrichten(frage, punkte),
"stream": False,
"think": False,
"options": {"num_predict": MAX_TOKEN, "temperature": 0},
}
try:
with anfrage(f"{LLM}/api/chat", koerper, LLM_TIMEOUT) as a:
antwort = json.load(a)["message"]["content"].strip()
except TimeoutError:
print(f"Zeitüberschreitung nach {LLM_TIMEOUT} s {frage}", flush=True)
self.senden(504, {"fehler": f"keine Antwort in {LLM_TIMEOUT} s"})
return
zeiten["gesamt"] = round(time.time() - start, 2)
print(f"antwort {zeiten} {frage}", flush=True)
self.senden(200, {"antwort": antwort, "quellen": quellen, "sekunden": zeiten})
def strom(self, frage, punkte, quellen, start, zeiten):
"""Jedes Stück der Antwort sofort weiterreichen, eine JSON-Zeile je Stück."""
koerper = {
"model": LLM_MODELL,
"messages": nachrichten(frage, punkte),
"stream": True,
"think": False,
"options": {"num_predict": MAX_TOKEN, "temperature": 0},
}
self.send_response(200)
self.send_header("Content-Type", "application/x-ndjson")
self.end_headers()
self.zeile({"quellen": quellen})
try:
with anfrage(f"{LLM}/api/chat", koerper, LLM_TIMEOUT) as a:
for roh in a:
stueck = json.loads(roh)["message"]["content"]
if stueck and "erstes_wort" not in zeiten:
zeiten["erstes_wort"] = round(time.time() - start, 2)
if stueck:
self.zeile({"text": stueck})
except TimeoutError:
print(f"Zeitüberschreitung nach {LLM_TIMEOUT} s {frage}", flush=True)
self.zeile({"fehler": f"keine Antwort in {LLM_TIMEOUT} s"})
return
zeiten["gesamt"] = round(time.time() - start, 2)
print(f"strom {zeiten} {frage}", flush=True)
self.zeile({"fertig": True, "sekunden": zeiten})
def log_message(self, format, *args):
pass
if __name__ == "__main__":
print(
f"Antwortdienst auf Port 8080, Sammlung {SAMMLUNG}, LLM {LLM_MODELL}",
flush=True,
)
ThreadingHTTPServer(("", 8080), Auskunft).serve_forever()| Part | Lines | What it does |
|---|---|---|
| Switches | 9–21 | addresses of the three services, collection, models;
KARTEN (how many cards the model gets),
MINDEST_SCORE, LLM_TIMEOUT,
MAX_TOKEN (longest answer in tokens),
RERANK_URL (empty = off) |
ANWEISUNG |
23–28 | the rules for the person at the desk: only from the cards, name the card number, otherwise exactly “Dazu steht nichts im Handbuch.” (“There is nothing about this in the handbook.”) |
anfrage |
31–37 | a POST with JSON; returns the open response so that
strom can read it line by line |
suchen |
40–55 | embed the question, fetch cards from Qdrant; with a reranker, first
fetch KANDIDATEN cards and reorder them (Day 8); the first
KARTEN are returned |
nachrichten |
58–67 | builds two messages: system = instruction plus numbered cards, user = the question |
senden, zeile |
71–81 | send a whole JSON response or one JSON line in the stream |
do_GET |
83–87 | /health for the readiness probe |
do_POST |
89–119 | read the question, search, measure time; if the best card is worse
than MINDEST_SCORE, immediately “Dazu steht nichts im
Handbuch.”; otherwise build the list of sources and call
ganz or strom |
ganz |
121–139 | /api/chat without streaming; waits at most
LLM_TIMEOUT seconds, otherwise status 504 |
strom |
141–168 | /api/chat with streaming; status 200 and
sources immediately, then one line per piece of the answer, at the end
fertig with the times |
log_message |
170–171 | switches off the access log; instead the service writes a line of its own per question |
| Start | 174–179 | ThreadingHTTPServer: every request in a thread of its
own, so that /health answers while a question is
running |
Three decisions are in the code that you should know:
/api/chatinstead of/api/generate. On Day 1 everything went through/api/generatewith a single block of text. In the lab,qwen3:1.7bwith three long cards in one block only repeated the question:"/Der Drucker druckt nicht mehr. Was soll ich tun? [1]"(the printer question itself). With cards as system message and the question as user message, it answered."think": falseand"temperature": 0. No thinking out loud (saves time), no randomness (same question, same cards, same answer – that way errors can be reproduced).- Times in every answer.
sekunden.sucheandsekunden.gesamtare in the answer and in the log. Without them you would not know on Day 10 where to start.
Step 2 – the code into the cluster.
# on rag1
kubectl -n rag create configmap antwort-code --from-file=antwort.pyExpected:
configmap/antwort-code created
Step 3 – deployment and service.
# on rag1
nano antwort.yamlapiVersion: apps/v1
kind: Deployment
metadata:
name: antwort
namespace: rag
spec:
replicas: 1
selector:
matchLabels:
app: antwort
template:
metadata:
labels:
app: antwort
spec:
containers:
- name: antwort
image: python:3.14.10-slim-trixie
command: ["python", "/code/antwort.py"]
env:
- name: SAMMLUNG
value: wissen
- name: KARTEN
value: "3"
- name: LLM_TIMEOUT
value: "60"
- name: MINDEST_SCORE
value: "0"
- name: RERANK_URL
value: ""
ports:
- containerPort: 8080
resources:
requests:
cpu: 100m
memory: 64Mi
limits:
memory: 128Mi
readinessProbe:
httpGet:
path: /health
port: 8080
volumeMounts:
- name: code
mountPath: /code
volumes:
- name: code
configMap:
name: antwort-code
---
apiVersion: v1
kind: Service
metadata:
name: antwort
namespace: rag
spec:
selector:
app: antwort
ports:
- port: 80
targetPort: 8080| Setting | Value | Meaning |
|---|---|---|
image |
python:3.14.10-slim-trixie |
the same image as ingestion and test bench |
command |
python /code/antwort.py |
the code comes from the ConfigMap |
KARTEN |
"3" |
three cards in the prompt – the decision from Day 8, Drill 6: hits@3 counts |
LLM_TIMEOUT |
"60" |
wait at most 60 seconds for the model |
MINDEST_SCORE |
"0" |
no threshold yet – you set it in Drill 6 |
RERANK_URL |
"" |
reranker off |
requests / limits |
0.1 core, 64–128 MiB | the service itself hardly computes; it waits for others |
readinessProbe |
/health |
requests only once the server is running |
no nodeSelector |
– | the answer service has no volume and may run anywhere |
Service antwort |
port 80 → 8080 | address in the cluster: http://antwort.rag |
# on rag1
kubectl apply -f antwort.yamlExpected:
deployment.apps/antwort created
service/antwort created
# on rag1
kubectl -n rag rollout status deployment/antwort --timeout=120sExpected (excerpt – the last line):
deployment "antwort" successfully rolled out
Step 4 – is it alive?
# on rag1
kubectl -n rag logs deployment/antwortExpected:
Antwortdienst auf Port 8080, Sammlung wissen, LLM qwen3:1.7b
# on rag1
kubectl -n rag get pods -o wideExpected (excerpt – the running pods, cut off on the right):
NAME READY STATUS RESTARTS AGE IP NODE
antwort-5864f9865c-jvkb6 1/1 Running 0 13s 10.42.1.52 rag2
curl 1/1 Running 0 15h 10.42.1.28 rag2
embed-66bdc7c6c9-rqqpn 1/1 Running 0 16h 10.42.0.12 rag1
llm-64c9d597d8-9vwcx 1/1 Running 0 2m33s 10.42.0.29 rag1
pg-1 1/1 Running 0 15h 10.42.1.9 rag2
qdrant-0 1/1 Running 0 16h 10.42.1.5 rag2
What you see: The answer service has landed on rag2,
next to Qdrant – it has no nodeSelector, and rag1 is fully
promised. A question therefore travels from rag2 (answer service) to
rag1 (embedding), back to rag2 (Qdrant) and again to rag1 (language
model).
Remember: The answer service is the desk service: it computes almost nothing itself, calls three other services and measures how long each one takes.
Save your progress? Sign up for free
Drill 3: The first answer with sources
Where you are: on rag1, in
~/kurs/09.What you have afterwards: two answers with card numbers – and a measurement of how long each stage took.
Step 1 – the question as a file.
# on rag1
nano f02.json{"frage": "Wie groß darf ein Secret höchstens sein?"}Step 2 – ask. As on Day 8, you send the file into
the cluster via the helper pod curl. What is new is
> antwort.json at the end: the answer ends up in a file
on rag1, which you then read with jq.
# on rag1
kubectl -n rag exec -i curl -- curl -s -X POST http://antwort.rag/frage -H "Content-Type: application/json" -d @- < f02.json > antwort.json| Setting | Meaning |
|---|---|
exec -i curl -- |
run curl in the helper pod, pass standard input
through |
-X POST http://antwort.rag/frage |
the path for questions |
-d @- < f02.json |
read the request body from the file on rag1 |
> antwort.json |
the output of curl ends up in a file on rag1 |
The command only returns after a good 20 seconds – without output, that is in the file.
# on rag1
jq . antwort.jsonExpected:
{
"antwort": "[1] Ein Secret darf maximal 1 MiB in Größe haben.",
"quellen": [
{
"nr": 1,
"quelle": "k8s-secret.md",
"abschnitt": "Size limit",
"score": 0.733
},
{
"nr": 2,
"quelle": "k8s-secret.md",
"abschnitt": "Secrets",
"score": 0.608
},
{
"nr": 3,
"quelle": "k8s-secret.md",
"abschnitt": "Secrets",
"score": 0.582
}
],
"sekunden": {
"suche": 0.57,
"gesamt": 22.83
}
}
| Field | Value | Meaning |
|---|---|---|
antwort |
[1] Ein Secret darf maximal 1 MiB … |
correct (“a Secret may be at most 1 MiB”) – the documentation states 1 MiB; the number is at the front instead of the back, the instruction is not followed literally |
quellen[].nr |
1–3 | the numbers under which the cards were in the prompt |
quellen[].abschnitt |
Size limit |
card 1 is the right one (as in the test bench on Day 7) |
sekunden.suche |
0.57 |
embedding plus Qdrant |
sekunden.gesamt |
22.83 |
the whole question; the rest is the language model |
What you see: The answer is short and correct and names card 1. Of 22.8 seconds, half a second goes to the search and a good 22 to the language model.
Step 3 – a question from our own handbook.
# on rag1
nano f12.json{"frage": "Der Drucker druckt nicht mehr. Was soll ich tun?"}# on rag1
kubectl -n rag exec -i curl -- curl -s -X POST http://antwort.rag/frage -H "Content-Type: application/json" -d @- < f12.json > antwort.json# on rag1
jq -r .antwort antwort.json-r: output the text raw – without quotation marks and with real line breaks.
Expected:
Der Drucker druckt nicht mehr. Nutze den Befehl `sudo systemctl restart cups` im Druckserver druck02, um den Druckdienst neu zu starten. Prüfe anschließend mit `lpstat -r` ob der Dienst läuft. Wenn das nicht funktioniert, überprüfe die Warteschlange mit `cancel -a`. [1]
# on rag1
jq -c '.quellen[]' antwort.jsonExpected:
{"nr":1,"quelle":"karte-druck.txt","abschnitt":"Druckdienst neu starten","score":0.642}
{"nr":2,"quelle":"k8s-taint-and-toleration.md","abschnitt":"Taint based Evictions","score":0.452}
{"nr":3,"quelle":"k8s-taint-and-toleration.md","abschnitt":"Taint based Evictions","score":0.449}
What you see: The commands match the printer card.
One sentence does not: according to the card, cancel -a
empties the queue, the answer says “überprüfe” (“check”). Cards 2 and 3
have nothing to do with printers – the service always sends three cards,
even if only one fits. Here the person at the desk rightly ignored
them.
Step 4 – where the time goes. After every answer,
Ollama writes two lines with times to the log. You filter them out with
grep – the words eval time only appear in
these lines:
# on rag1
kubectl -n rag logs deployment/llm | grep "eval time"Expected (cut off on the right):
slot print_timing: id 0 | task 0 | prompt eval time = 13606.24 ms / 546 tokens ( 24.92 ms per token, 40.13 tokens per second)
slot print_timing: id 0 | task 0 | eval time = 1374.40 ms / 16 tokens ( 91.63 ms per token, 10.91 tokens per second)
slot print_timing: id 0 | task 18 | prompt eval time = 14824.41 ms / 560 tokens ( 26.47 ms per token, 37.78 tokens per second)
slot print_timing: id 0 | task 18 | eval time = 8983.55 ms / 88 tokens ( 103.26 ms per token, 9.68 tokens per second)
| Line | f02 (Secret) | f12 (printer) | Meaning |
|---|---|---|---|
prompt eval time |
13.6 s for 546 tokens | 14.8 s for 560 tokens | reading the cards: around 40 tokens per second |
eval time |
1.4 s for 16 tokens | 9.0 s for 88 tokens | writing the answer: around 10 tokens per second |
What you see: The biggest item is not the writing but the reading. For the Secret question it was 13.6 seconds of reading against 1.4 seconds of writing. Three cards of up to 1000 characters each are a good 500 tokens, and the model reads them on two to four cores at 40 tokens per second. The first question took about 7 seconds longer in total than reading and writing together: on the first call, Ollama loads the model into memory.
Step 5 – what it costs.
# on rag1
kubectl top pod -n ragExpected (directly after the printer question):
NAME CPU(cores) MEMORY(bytes)
antwort-5864f9865c-jvkb6 2m 17Mi
curl 1m 1Mi
embed-66bdc7c6c9-rqqpn 58m 1379Mi
llm-64c9d597d8-9vwcx 3724m 2070Mi
pg-1 20m 55Mi
qdrant-0 6m 63Mi
What you see: While computing, the language model uses 3.7 cores – all four of rag1, because it has no CPU limit. The answer service needs 2 millicores and 17 MiB: it only waits.
Remember: The source reference is the card number in the prompt. And the most expensive stage of an answer here is reading the cards, not writing: every additional card costs every question a good four seconds.
Save your progress? Sign up for free
Drill 4: Streaming
Where you are: on rag1, in
~/kurs/09.What you have afterwards: a streamed answer – and the measurement of when the first word arrives, cold and with prompt cache.
Step 1 – the question with stream. The
answer service streams if the question contains
"stream": true.
# on rag1
nano f06-strom.json{"frage": "Wozu dient eine Startup-Probe?", "stream": true}Step 2 – ask and watch. This time without a file as the target – you should see the lines coming:
# on rag1
kubectl -n rag exec -i curl -- curl -sN -X POST http://antwort.rag/frage -H "Content-Type: application/json" -d @- < f06-strom.json-N:curldoes not buffer the output, every line appears immediately.
Expected (excerpt – the first six and the last four of 62 lines):
{"quellen": [{"nr": 1, "quelle": "k8s-pod-lifecycle.md", "abschnitt": "Startup probe", "score": 0.68}, {"nr": 2, "quelle": "k8s-pod-lifecycle.md", "abschnitt": "Liveness probe", "score": 0.561}, {"nr": 3, "quelle": "k8s-pod-lifecycle.md", "abschnitt": "Readiness probe", "score": 0.546}]}
{"text": "Eine"}
{"text": " Startup"}
{"text": "-Pro"}
{"text": "be"}
{"text": " wird"}
{"text": " ["}
{"text": "1"}
{"text": "]"}
{"fertig": true, "sekunden": {"suche": 0.5, "erstes_wort": 10.63, "gesamt": 15.76}}
Put together, the answer reads: “Eine Startup-Probe wird verwendet, um zu überprüfen, ob ein Container korrekt gestartet ist. Wenn eine Startup-Probe fehlschlägt, wird der Container von Kubernetes gelöscht und entsprechend der Restart-Policy wieder angemeldet. [1]” (a startup probe checks whether a container has started correctly; if it fails, Kubernetes deletes the container and “re-registers” it according to the restart policy).
| Line | When | Meaning |
|---|---|---|
{"quellen": …} |
after half a second | the cards are fixed before the model begins – a client can display them immediately |
{"text": …} |
from second 10.6 | one token per line, often only part of a word (“-Pro”, “be”) |
{"fertig": …} |
after 15.8 seconds | end, with the times |
erstes_wort |
10.63 |
for this long the user only sees the sources |
What you see: The first word arrives after 10.6 seconds, the whole answer after 15.8. Streaming has not made the answer faster. It lets the user read along for the last five seconds instead of waiting. The first ten seconds remain: that is the reading of the cards, and it happens before the first word. By the way, the answer contains an inaccuracy: the container is not “gelöscht” (deleted) but stopped and restarted according to the restart policy. The “wieder angemeldet” (re-registered) is on no card.
Step 3 – the same question again.
# on rag1
kubectl -n rag exec -i curl -- curl -sN -X POST http://antwort.rag/frage -H "Content-Type: application/json" -d @- < f06-strom.jsonExpected (excerpt – the first and the last line):
{"quellen": [{"nr": 1, "quelle": "k8s-pod-lifecycle.md", "abschnitt": "Startup probe", "score": 0.68}, {"nr": 2, "quelle": "k8s-pod-lifecycle.md", "abschnitt": "Liveness probe", "score": 0.561}, {"nr": 3, "quelle": "k8s-pod-lifecycle.md", "abschnitt": "Readiness probe", "score": 0.546}]}
{"fertig": true, "sekunden": {"suche": 0.46, "erstes_wort": 0.7, "gesamt": 6.05}}
What you see: The same answer, word for word –
temperature 0 – but the first word arrives after 0.7
instead of 10.6 seconds.
Step 4 – why.
# on rag1
kubectl -n rag logs deployment/llm | grep "cached n_tokens"Expected (excerpt – the last three lines, cut off on the left):
task 18 | cached n_tokens = 605, memory_seq_rm [605, end)
task 108 | cached n_tokens = 93, memory_seq_rm [93, end)
task 170 | cached n_tokens = 466, memory_seq_rm [466, end)
# on rag1
kubectl -n rag logs deployment/llm | grep "prompt eval time"Expected (excerpt – the last two lines, cut off on the right):
slot print_timing: id 0 | task 108 | prompt eval time = 9758.47 ms / 374 tokens
slot print_timing: id 0 | task 170 | prompt eval time = 199.34 ms / 1 tokens
| Call | cached n_tokens |
read | Meaning |
|---|---|---|---|
| task 108 (first startup call) | 93 | 374 tokens in 9.8 s | only the beginning of the instruction was still in memory – it is the same for every question |
| task 170 (second call) | 466 | 1 token in 0.2 s | the whole prompt was still in memory |
What you see: Ollama keeps prompts it has read in RAM. If a new prompt begins like a stored one, the model only reads the rest. The 93 tokens saved on every question are the instruction before the cards. With a repeated question, everything is saved – even if other questions came in between. How large this cache may grow and what that means for the pod’s memory, you measure on day 10.
Remember: Streaming shortens the perceived waiting time, not the computing time. The first word only arrives once the cards have been read. That is why whoever measures asks every question only once – otherwise they measure the cache.
Save your progress? Sign up for free
Drill 5: The waiting ticket
Where you are: on rag1, in
~/kurs/09.What you have afterwards: measured what a timeout does at the answer service, for the user and at the language model – without streaming and with.
Step 1 – a waiting ticket that is too short. So that you reliably trigger a timeout, you set it to five seconds for this drill – shorter than reading the cards takes.
# on rag1
nano antwort.yamlapiVersion: apps/v1
kind: Deployment
metadata:
name: antwort
namespace: rag
spec:
replicas: 1
selector:
matchLabels:
app: antwort
template:
metadata:
labels:
app: antwort
spec:
containers:
- name: antwort
image: python:3.14.10-slim-trixie
command: ["python", "/code/antwort.py"]
env:
- name: SAMMLUNG
value: wissen
- name: KARTEN
value: "3"
- name: LLM_TIMEOUT
value: "5"
- name: MINDEST_SCORE
value: "0"
- name: RERANK_URL
value: ""
ports:
- containerPort: 8080
resources:
requests:
cpu: 100m
memory: 64Mi
limits:
memory: 128Mi
readinessProbe:
httpGet:
path: /health
port: 8080
volumeMounts:
- name: code
mountPath: /code
volumes:
- name: code
configMap:
name: antwort-code
---
apiVersion: v1
kind: Service
metadata:
name: antwort
namespace: rag
spec:
selector:
app: antwort
ports:
- port: 80
targetPort: 8080# on rag1
kubectl apply -f antwort.yamlExpected:
deployment.apps/antwort configured
service/antwort unchanged
# on rag1
kubectl -n rag rollout status deployment/antwort --timeout=120sExpected (excerpt – the last line):
deployment "antwort" successfully rolled out
# on rag1
kubectl -n rag get pods -l app=antwortExpected:
NAME READY STATUS RESTARTS AGE
antwort-6b7fbd5cc6-7mnmq 1/1 Terminating 0 68s
antwort-f974bb55c-rb5mz 1/1 Running 0 13s
The old pod is still in Terminating. Repeat the command
until only one pod is left – in the lab that took a good 30 seconds.
Otherwise kubectl logs deployment/antwort will read the log
of the old pod. Why it takes so long is cleared up in the diagnosis
task.
Step 2 – a new question without streaming. Take a question that has not been asked today yet – otherwise the prompt cache from Drill 4 helps.
# on rag1
nano f11.json{"frage": "Wie hinterlege ich Zugangsdaten für eine private Container-Registry?"}# on rag1
kubectl -n rag exec -i curl -- curl -s -w "\n%{http_code} %{time_total}\n" -X POST http://antwort.rag/frage -H "Content-Type: application/json" -d @- < f11.json-w "\n%{http_code} %{time_total}\n": after the answer, output the HTTP status and the total duration.
Expected:
{"fehler": "keine Antwort in 5.0 s"}
504 5.597062
What you see: After 5.6 seconds – half a second of
search plus five seconds of waiting – the answer service gives up and
reports 504 Gateway Timeout: “The service behind me did not
answer in time.”
Step 3 – what the answer service notes down.
# on rag1
kubectl -n rag logs deployment/antwort --tail=1Expected:
Zeitüberschreitung nach 5.0 s Wie hinterlege ich Zugangsdaten für eine private Container-Registry?
Step 4 – what the language model does. Does it keep computing although nobody is waiting any more?
# on rag1
kubectl -n rag logs deployment/llm --tail=3Expected:
[GIN] 2026/12/02 - 12:52:06 | 200 | 92.486µs | 10.42.0.1 | GET "/api/version"
[GIN] 2026/12/02 - 12:52:09 | 500 | 5s | 10.42.1.62 | POST "/api/chat"
srv stop: cancel task, id_task = 485
| Line | Meaning |
|---|---|
GET "/api/version" |
the readiness probe, every five seconds |
500 \| 5s \| … POST "/api/chat" |
the request of the answer service ended after 5 seconds without an answer |
stop: cancel task |
Ollama cancelled the work on this request |
What you see: When the answer service closed the connection, Ollama stopped computing. So the waiting ticket protects not only the user from long waits, but also the model from work that nobody collects any more. Without a timeout, an abandoned question would keep occupying the model’s only computing slot.
Step 5 – the same question with streaming.
# on rag1
nano f11-strom.json{"frage": "Wie hinterlege ich Zugangsdaten für eine private Container-Registry?", "stream": true}# on rag1
kubectl -n rag exec -i curl -- curl -sN -w "\n%{http_code} %{time_total}\n" -X POST http://antwort.rag/frage -H "Content-Type: application/json" -d @- < f11-strom.jsonExpected:
{"quellen": [{"nr": 1, "quelle": "k8s-secret.md", "abschnitt": "Docker config Secrets", "score": 0.599}, {"nr": 2, "quelle": "k8s-secret.md", "abschnitt": "Docker config Secrets", "score": 0.563}, {"nr": 3, "quelle": "k8s-secret.md", "abschnitt": "Secrets", "score": 0.559}]}
{"fehler": "keine Antwort in 5.0 s"}
200 8.092549
What you see: The same timeout, but the status is
200. With streaming, the answer service
had already sent status and sources before the model began. An HTTP
status cannot be changed after that. The error therefore comes as a line
of its own in the stream. A client that only looks at the status
considers this answer a success.
Step 6 – the waiting ticket back to 60 seconds. In
antwort.yaml, set line 26 back to "60" – the
file is then as in Drill 2 again.
# on rag1
nano antwort.yaml# on rag1
kubectl apply -f antwort.yaml# on rag1
kubectl -n rag rollout status deployment/antwort --timeout=120sWait as in Step 1 until
kubectl -n rag get pods -l app=antwort only shows one
pod.
Step 7 – once more with streaming.
# on rag1
kubectl -n rag exec -i curl -- curl -sN -w "\n%{http_code} %{time_total}\n" -X POST http://antwort.rag/frage -H "Content-Type: application/json" -d @- < f11-strom.jsonExpected (excerpt – the first and the last two lines):
{"quellen": [{"nr": 1, "quelle": "k8s-secret.md", "abschnitt": "Docker config Secrets", "score": 0.599}, {"nr": 2, "quelle": "k8s-secret.md", "abschnitt": "Docker config Secrets", "score": 0.563}, {"nr": 3, "quelle": "k8s-secret.md", "abschnitt": "Secrets", "score": 0.559}]}
{"fertig": true, "sekunden": {"suche": 0.58, "erstes_wort": 6.74, "gesamt": 22.81}}
200 22.817517
What you see: With 60 seconds the answer arrives –
instructions with kubectl create secret docker-registry,
22.8 seconds in total. The first word arrived after 6.7 seconds,
although the question was new: the cancelled attempt from Step 5 had
already read 605 tokens of the prompt, and they were still in the cache
(in the log: cached n_tokens = 605).
How the timeout counts in the code.
urlopen(…, timeout=60) does not limit the whole request,
but every single wait for data. Without streaming,
Ollama only sends something at the end – the wait lasts as long as the
whole answer, and the timeout acts like an overall limit. With
streaming, the clock starts anew with every token. An answer that
trickles in word by word for two minutes therefore does not trigger a
60-second timeout. Against endless answers, MAX_TOKEN
helps: at most 300 tokens, so at 10 tokens per second around 30 seconds
of writing.
Remember: A timeout is a waiting ticket for both sides: the user gets a clear refusal, the model stops computing. With streaming, the refusal comes as a line after status 200 – clients have to check every line, not just the status.
Save your progress? Sign up for free
Drill 6: “I don’t know”
Where you are: on rag1, in
~/kurs/09.What you have afterwards: a score threshold in the answer service – and five questions that show what it and the instruction in the prompt achieve and what they do not.
Step 1 – a question for which there is no card. There is nothing about laptops in the handbook.
# on rag1
nano laptop.json{"frage": "Wie bekomme ich einen neuen Laptop?"}# on rag1
kubectl -n rag exec -i curl -- curl -s -X POST http://antwort.rag/frage -H "Content-Type: application/json" -d @- < laptop.json > antwort.json# on rag1
jq . antwort.jsonExpected:
{
"antwort": "Dazu steht nichts im Handbuch.",
"quellen": [
{
"nr": 1,
"quelle": "k8s-taint-and-toleration.md",
"abschnitt": "Example Use Cases",
"score": 0.452
},
{
"nr": 2,
"quelle": "k8s-pod-lifecycle.md",
"abschnitt": "Resizing by launching replacement Pods",
"score": 0.444
},
{
"nr": 3,
"quelle": "karte-druck.txt",
"abschnitt": "Druckdienst neu starten",
"score": 0.426
}
],
"sekunden": {
"suche": 0.39,
"gesamt": 16.16
}
}
What you see: The instruction worked: literally “Dazu steht nichts im Handbuch.” But for that, the model spent 16 seconds reading three cards that have nothing to do with laptops. The best one was at 0.452.
Step 2 – where a threshold could lie. For a threshold you need to know which scores the best card has for questions with and without a matching card. In the lab, the search (without language model) returned these values for the 13 test questions from Day 7 and eight questions without an answer in the collection:
| Question | best card | Score |
|---|---|---|
| f05 Guaranteed (correct) | Criteria | 0.746 |
| f02 Secret size (correct) | Size limit | 0.733 |
| f12 printer (correct) | Druckdienst neu starten | 0.642 |
| f01 memory shortage (wrong card) | Pods and fault recovery | 0.615 |
| f11 registry (correct) | Docker config Secrets | 0.599 |
| f13 VPN (correct) | VPN-Zugang einrichten | 0.489 |
| Vacation days? (not in the collection) | Urlaub beantragen | 0.599 |
| Reset password? (not in the collection) | VPN-Zugang einrichten | 0.588 |
| Install Kubernetes? (not in the collection) | Secrets | 0.566 |
| Laptop? (not in the collection) | Example Use Cases | 0.452 |
| What is a Deployment? (not in the collection) | Pod-level container restart policy | 0.420 |
| Canteen? (not in the collection) | Individual container restart policy … | 0.415 |
| Park a bicycle? (not in the collection) | In-place Pod resize | 0.403 |
| Time in Tokyo? (not in the collection) | Taint based Evictions | 0.400 |
The remaining test questions lie between 0.606 and 0.717.
What you see: The two groups overlap. The weakest correct question (f13, VPN, 0.489 – German question, short card, different words) lies below three questions without an answer in the collection. A threshold that catches all questions without an answer would also reject correct questions. A threshold that rejects no correct question has to lie below 0.489 – and then only catches the questions that are far off.
Step 3 – set the threshold. You set it just above the laptop question and below f13: 0.46. That is a lab number for this collection and this embedding model, not a general value.
# on rag1
nano antwort.yamlapiVersion: apps/v1
kind: Deployment
metadata:
name: antwort
namespace: rag
spec:
replicas: 1
selector:
matchLabels:
app: antwort
template:
metadata:
labels:
app: antwort
spec:
containers:
- name: antwort
image: python:3.14.10-slim-trixie
command: ["python", "/code/antwort.py"]
env:
- name: SAMMLUNG
value: wissen
- name: KARTEN
value: "3"
- name: LLM_TIMEOUT
value: "60"
- name: MINDEST_SCORE
value: "0.46"
- name: RERANK_URL
value: ""
ports:
- containerPort: 8080
resources:
requests:
cpu: 100m
memory: 64Mi
limits:
memory: 128Mi
readinessProbe:
httpGet:
path: /health
port: 8080
volumeMounts:
- name: code
mountPath: /code
volumes:
- name: code
configMap:
name: antwort-code
---
apiVersion: v1
kind: Service
metadata:
name: antwort
namespace: rag
spec:
selector:
app: antwort
ports:
- port: 80
targetPort: 8080# on rag1
kubectl apply -f antwort.yaml# on rag1
kubectl -n rag rollout status deployment/antwort --timeout=120sWait again until kubectl -n rag get pods -l app=antwort
only shows one pod.
Step 4 – the laptop question with a threshold.
# on rag1
kubectl -n rag exec -i curl -- curl -s -X POST http://antwort.rag/frage -H "Content-Type: application/json" -d @- < laptop.json > antwort.json# on rag1
jq . antwort.jsonExpected:
{
"antwort": "Dazu steht nichts im Handbuch.",
"quellen": [],
"sekunden": {
"suche": 0.38
}
}
# on rag1
kubectl -n rag logs deployment/antwort --tail=1Expected:
keine Karte bester 0.452 Wie bekomme ich einen neuen Laptop?
What you see: The same answer, but after 0.38 instead of 16 seconds – the language model was not asked at all. The log names the score at which the question failed. With these lines you check in operation whether the threshold rejects correct questions.
Step 5 – the narrowly correct question.
# on rag1
nano f13.json{"frage": "Wie komme ich von zu Hause ins Firmennetz?"}# on rag1
kubectl -n rag exec -i curl -- curl -s -X POST http://antwort.rag/frage -H "Content-Type: application/json" -d @- < f13.json > antwort.json# on rag1
jq -r .antwort antwort.jsonExpected:
[1] 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.
What you see: f13 gets through (0.489 above 0.46) and is answered correctly – the answer reproduces the VPN card almost word for word.
Step 6 – two questions above the threshold without an answer in the collection. The threshold does not catch these questions. Now the instruction in the prompt has to take effect.
# on rag1
nano passwort.json{"frage": "Wie setze ich mein Passwort zurück?"}# on rag1
kubectl -n rag exec -i curl -- curl -s -X POST http://antwort.rag/frage -H "Content-Type: application/json" -d @- < passwort.json > antwort.json# on rag1
jq -r .antwort antwort.jsonExpected:
Das Passwort reseten ist nicht direkt möglich. Es gibt keine Karte, die dies beschreibt.
# on rag1
nano urlaub.json{"frage": "Wie viele Urlaubstage habe ich?"}# on rag1
kubectl -n rag exec -i curl -- curl -s -X POST http://antwort.rag/frage -H "Content-Type: application/json" -d @- < urlaub.json > antwort.json# on rag1
jq -r .antwort antwort.jsonExpected:
Die Anzahl der Urlaubstage steht nicht in der Datenbank. Dazu steht nichts im Handbuch.
| Question | Answer | Assessment |
|---|---|---|
| Password | “… nicht direkt möglich. Es gibt keine Karte, die dies beschreibt.” (“not directly possible. There is no card that describes this.”) | refused in substance, but not with the required sentence – and “nicht direkt möglich” is written nowhere |
| Vacation days | “… steht nicht in der Datenbank. Dazu steht nichts im Handbuch.” (“is not in the database. There is nothing about this in the handbook.”) | refused, with the sentence – plus an invented “database” |
What you see: The instruction works, but not literally. A program that checks whether the answer is exactly “Dazu steht nichts im Handbuch.” would not have recognised the password answer. And both answers contain a half-sentence that is on no card.
Step 7 – the most dangerous answer. The question that has not found its card since Day 6:
# on rag1
nano f01.json{"frage": "Welche Pods werden zuerst entfernt, wenn einem Node der Speicher ausgeht?"}# on rag1
kubectl -n rag exec -i curl -- curl -s -X POST http://antwort.rag/frage -H "Content-Type: application/json" -d @- < f01.json > antwort.json# on rag1
jq -r .antwort antwort.jsonExpected:
Wenn einem Node der Speicher ausgeht, wird die Pod, die den Node belegt hat, zuerst entfernt. [1]
# on rag1
jq -c '.quellen[]' antwort.jsonExpected:
{"nr":1,"quelle":"k8s-pod-lifecycle.md","abschnitt":"Pods and fault recovery","score":0.615}
{"nr":2,"quelle":"k8s-pod-lifecycle.md","abschnitt":"Termination of Pods","score":0.612}
{"nr":3,"quelle":"k8s-pod-lifecycle.md","abschnitt":"Termination of Pods","score":0.608}
What you see: A fluent, confident answer with the
source reference [1] (“when a node runs out of memory, the
pod that occupied the node is removed first”) – and it is
wrong. The correct answer is on the QoS card: first
BestEffort, then Burstable, finally
Guaranteed. Card 1, “Pods and fault recovery”, only says
that a pod does not survive an eviction due to a lack of resources (“A
Pod won’t survive an eviction due to a lack of resources”). Which goes
first is not written there. The person at the desk turned a card that
touches on the topic into a rule. The score of 0.615 is far above the
threshold – it does not help here. And neither does the instruction:
from the model’s point of view, there was something suitable on the card
after all.
Remember: “I don’t know” has two guards: the score threshold before the model (cheap, only catches far-off questions) and the instruction in the prompt (expensive, not followed literally). Neither of them helps against a wrong card. A source reference only proves which card was on the table – not that the answer is on it.
If it does not work
- The answer only repeats the question,
e.g.
"/Der Drucker druckt nicht mehr. Was soll ich tun? [1]": in the lab this happened when instruction, cards and question went to/api/generateas one block of text. With/api/chat, cards in the system message and question in the user message, the model answered. kubectl logs deployment/antwortshows an old line, above itFound 2 pods, using pod/…: the old pod is still inTerminating. Wait untilkubectl -n rag get pods -l app=antwortonly shows one – or solve the diagnosis task.- A timeout attempt goes through although
LLM_TIMEOUTis 5: the question had been asked before, the whole prompt was in the cache, the first word arrived before the five seconds were up. In the lab the service answered such a repeated question in 3.5 seconds. Take a new question. - The pod
llmstaysPending,kubectl -n rag describe pod -l app=llmreportsInsufficient cpu: the CPU requests on rag1 are not enough. Check whether the reranker really is at zero replicas (Drill 1, Step 2).
Save your progress? Sign up for free
Diagnosis task
A colleague complains: “Every change to the answer service takes half
a minute until it is really there. rollout status says done
after ten seconds, but kubectl logs still shows the old
log.” You saw this yourself in Drills 5 and 6. Find the cause.
Step 1 – how long stopping takes. Delete the running
pod and measure the time. You read the name with
kubectl -n rag get pods -l app=antwort:
# on rag1
time kubectl -n rag delete pod antwort-f4b48bccd-xkvxctime: measures how long the command takes,delete pod: waits until the pod is really gone.
Expected:
pod "antwort-f4b48bccd-xkvxc" deleted from rag namespace
real 0m31.808s
user 0m0.497s
sys 0m0.208s
What you see: 31.8 seconds. When stopping,
Kubernetes first sends SIGTERM and then waits for the
terminationGracePeriodSeconds – 30 seconds if nothing else
is set. Only after that does SIGKILL follow. The service
did not react to SIGTERM.
Step 2 – why not. In the container, Python runs as
the process with number 1. Which signals it catches is in
/proc/1/status:
# on rag1
kubectl -n rag exec deployment/antwort -- grep -E '^(Name|Pid|SigIgn|SigCgt)' /proc/1/statusgrep -E '^(…)': only the lines that begin with one of the four names.
Expected:
Name: python
Pid: 1
SigIgn: 0000000201001000
SigCgt: 0000000100000002
| Line | Value | Meaning |
|---|---|---|
Pid |
1 |
Python is the first process in the container |
SigCgt |
…00000002 |
caught signals as a bit mask: bit 2 = SIGINT (Ctrl+C) –
Python only catches that one |
SigCgt without …4000 |
– | bit 15 = SIGTERM is not caught |
What you see: A normal process that does not catch
SIGTERM is terminated by it. Not process
1: for the first process of a PID namespace, the Linux kernel
ignores all signals for which it has no handler of its own. Python has
none for SIGTERM – so nothing happens for 30 seconds until
SIGKILL arrives, which cannot be ignored.
Step 3 – the remedy. The service gets a handler that
ends cleanly on SIGTERM:
# on rag1
nano antwort.py"""Antwortdienst: Frage einbetten, Karten suchen, mit Quellenangabe antworten."""
import json
import os
import signal
import time
import urllib.request
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
EMBED = os.environ.get("EMBED_URL", "http://embed.rag:11434")
QDRANT = os.environ.get("QDRANT_URL", "http://qdrant.rag:6333")
LLM = os.environ.get("LLM_URL", "http://llm.rag:11434")
RERANK = os.environ.get("RERANK_URL", "")
SAMMLUNG = os.environ.get("SAMMLUNG", "wissen")
MODELL = os.environ.get("MODELL", "bge-m3")
LLM_MODELL = os.environ.get("LLM_MODELL", "qwen3:1.7b")
KARTEN = int(os.environ.get("KARTEN", "3"))
KANDIDATEN = int(os.environ.get("KANDIDATEN", "20"))
MINDEST = float(os.environ.get("MINDEST_SCORE", "0"))
LLM_TIMEOUT = float(os.environ.get("LLM_TIMEOUT", "120"))
MAX_TOKEN = int(os.environ.get("MAX_TOKEN", "300"))
KEINE = "Dazu steht nichts im Handbuch."
ANWEISUNG = (
"Du bist die IT-Auskunft einer Firma. Beantworte die Frage des Nutzers auf "
"Deutsch, kurz, und nur mit dem Inhalt der Karten unten. Nenne hinter jeder "
"Aussage die Nummer der Karte in eckigen Klammern, zum Beispiel [1]. Steht die "
f"Antwort auf keiner Karte, antworte genau: {KEINE}\n\nKarten:\n"
)
def anfrage(url, daten, timeout=30):
req = urllib.request.Request(
url,
data=json.dumps(daten).encode(),
headers={"Content-Type": "application/json"},
)
return urllib.request.urlopen(req, timeout=timeout)
def suchen(frage):
"""Frage einbetten, Karten holen, auf Wunsch vom Reranker neu ordnen."""
with anfrage(f"{EMBED}/api/embed", {"model": MODELL, "input": [frage]}) as a:
vektor = json.load(a)["embeddings"][0]
koerper = {
"query": vektor,
"limit": KANDIDATEN if RERANK else KARTEN,
"with_payload": True,
}
with anfrage(f"{QDRANT}/collections/{SAMMLUNG}/points/query", koerper) as a:
punkte = json.load(a)["result"]["points"]
if RERANK and punkte:
texte = [p["payload"]["text"] for p in punkte]
with anfrage(f"{RERANK}/rerank", {"query": frage, "texts": texte}, 120) as a:
punkte = [punkte[u["index"]] for u in json.load(a)]
return punkte[:KARTEN]
def nachrichten(frage, punkte):
"""Anweisung und nummerierte Karten als System-, die Frage als Nutzernachricht."""
karten = [
f"[{nr}] {p['payload']['abschnitt']}\n{p['payload']['text']}\n"
for nr, p in enumerate(punkte, start=1)
]
return [
{"role": "system", "content": ANWEISUNG + "\n".join(karten)},
{"role": "user", "content": frage},
]
class Auskunft(BaseHTTPRequestHandler):
def senden(self, status, daten):
rumpf = json.dumps(daten, ensure_ascii=False).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(rumpf)))
self.end_headers()
self.wfile.write(rumpf)
def zeile(self, daten):
self.wfile.write(json.dumps(daten, ensure_ascii=False).encode() + b"\n")
self.wfile.flush()
def do_GET(self):
if self.path == "/health":
self.senden(200, {"status": "ok"})
else:
self.senden(404, {"fehler": "unbekannter Pfad"})
def do_POST(self):
if self.path != "/frage":
self.senden(404, {"fehler": "unbekannter Pfad"})
return
laenge = int(self.headers.get("Content-Length", 0))
eingabe = json.loads(self.rfile.read(laenge) or b"{}")
frage = str(eingabe.get("frage", "")).strip()
if not frage:
self.senden(400, {"fehler": "frage fehlt"})
return
start = time.time()
punkte = suchen(frage)
zeiten = {"suche": round(time.time() - start, 2)}
bester = punkte[0]["score"] if punkte else 0.0
if bester < MINDEST:
print(f"keine Karte bester {bester:.3f} {frage}", flush=True)
self.senden(200, {"antwort": KEINE, "quellen": [], "sekunden": zeiten})
return
quellen = [
{
"nr": nr,
"quelle": p["payload"]["quelle"],
"abschnitt": p["payload"]["abschnitt"],
"score": round(p["score"], 3),
}
for nr, p in enumerate(punkte, start=1)
]
if eingabe.get("stream"):
self.strom(frage, punkte, quellen, start, zeiten)
else:
self.ganz(frage, punkte, quellen, start, zeiten)
def ganz(self, frage, punkte, quellen, start, zeiten):
"""Auf die ganze Antwort warten und sie in einem Stück senden."""
koerper = {
"model": LLM_MODELL,
"messages": nachrichten(frage, punkte),
"stream": False,
"think": False,
"options": {"num_predict": MAX_TOKEN, "temperature": 0},
}
try:
with anfrage(f"{LLM}/api/chat", koerper, LLM_TIMEOUT) as a:
antwort = json.load(a)["message"]["content"].strip()
except TimeoutError:
print(f"Zeitüberschreitung nach {LLM_TIMEOUT} s {frage}", flush=True)
self.senden(504, {"fehler": f"keine Antwort in {LLM_TIMEOUT} s"})
return
zeiten["gesamt"] = round(time.time() - start, 2)
print(f"antwort {zeiten} {frage}", flush=True)
self.senden(200, {"antwort": antwort, "quellen": quellen, "sekunden": zeiten})
def strom(self, frage, punkte, quellen, start, zeiten):
"""Jedes Stück der Antwort sofort weiterreichen, eine JSON-Zeile je Stück."""
koerper = {
"model": LLM_MODELL,
"messages": nachrichten(frage, punkte),
"stream": True,
"think": False,
"options": {"num_predict": MAX_TOKEN, "temperature": 0},
}
self.send_response(200)
self.send_header("Content-Type", "application/x-ndjson")
self.end_headers()
self.zeile({"quellen": quellen})
try:
with anfrage(f"{LLM}/api/chat", koerper, LLM_TIMEOUT) as a:
for roh in a:
stueck = json.loads(roh)["message"]["content"]
if stueck and "erstes_wort" not in zeiten:
zeiten["erstes_wort"] = round(time.time() - start, 2)
if stueck:
self.zeile({"text": stueck})
except TimeoutError:
print(f"Zeitüberschreitung nach {LLM_TIMEOUT} s {frage}", flush=True)
self.zeile({"fehler": f"keine Antwort in {LLM_TIMEOUT} s"})
return
zeiten["gesamt"] = round(time.time() - start, 2)
print(f"strom {zeiten} {frage}", flush=True)
self.zeile({"fertig": True, "sekunden": zeiten})
def log_message(self, format, *args):
pass
def beenden(signum, frame):
"""Auf SIGTERM von Kubernetes sofort und sauber enden."""
print("SIGTERM erhalten, Antwortdienst endet", flush=True)
raise SystemExit(0)
if __name__ == "__main__":
signal.signal(signal.SIGTERM, beenden)
print(
f"Antwortdienst auf Port 8080, Sammlung {SAMMLUNG}, LLM {LLM_MODELL}",
flush=True,
)
ThreadingHTTPServer(("", 8080), Auskunft).serve_forever()| Part | What changes |
|---|---|
import signal |
the module for signals |
beenden |
writes a line to the log and ends the server with
SystemExit |
signal.signal(signal.SIGTERM, beenden) |
registers the handler for SIGTERM – before the server
starts |
Running answers are cancelled in the process. For an answer service running behind a service, that is acceptable: when stopping, Kubernetes first takes the pod out of the service, and new questions go to the new pod.
Step 4 – roll out the new code.
# on rag1
kubectl -n rag delete configmap antwort-code# on rag1
kubectl -n rag create configmap antwort-code --from-file=antwort.py# on rag1
kubectl -n rag rollout restart deployment/antwortrollout restart: restarts the pods of the deployment although the manifest has not changed – in doing so they read the new ConfigMap.
# on rag1
kubectl -n rag rollout status deployment/antwort --timeout=120sOne last time, stopping the old pod takes 30 seconds – it is still running with the old code.
Step 5 – measure again.
# on rag1
kubectl -n rag exec deployment/antwort -- grep -E '^(SigIgn|SigCgt)' /proc/1/statusExpected:
SigIgn: 0000000201001000
SigCgt: 0000000100004002
SigCgt now contains 4000 – bit 15,
SIGTERM. Read the name of the new pod and delete it:
# on rag1
time kubectl -n rag delete pod antwort-67f984d799-xvnprExpected:
pod "antwort-67f984d799-xvnpr" deleted from rag namespace
real 0m2.019s
user 0m0.459s
sys 0m0.189s
What you see: 2 seconds instead of 31.8. The deployment immediately starts a replacement pod.
Challenge
Get the answer service to answer f01 correctly. From Day 8 you know
how the right card gets onto the table: reranker with 50 candidates.
Switch the reranker back on, set RERANK_URL and
KANDIDATEN in the answer service, ask f01 and note down
answer, sources and sekunden.
Two hints from the lab: with --replicas=1 the reranker
does not come up but stays Pending with
1 Insufficient cpu – next to the language model and the
embedding model, rag1 no longer has a whole core free. In the lab it was
enough to lower the CPU request in ../08/rerank.yaml to
250m (the limit of 2 cores stays). After that the correct
answer came: “… werden zunächst BestEffort Pods entfernt,
gefolgt von Burstable Pods, und schließlich
Guaranteed Pods. [2]” (first BestEffort pods
are removed, followed by Burstable pods and finally
Guaranteed pods) – card 2 was “Quality of Service classes”.
The search took 16.45 seconds, the whole answer 36.06.
Afterwards: is the correct answer worth 20 more seconds to you? And
what does the field score in the sources show now – the
reranker’s score or that of the vector search? Finally, put the answer
service and the reranker back (apply antwort.yaml without
reranker, reranker to zero replicas).
Save your progress? Sign up for free
Checkpoint
# on rag1
kubectl -n rag get deployment llm antwort rerankExpected:
NAME READY UP-TO-DATE AVAILABLE AGE
llm 1/1 1 1 11m
antwort 1/1 1 1 9m16s
rerank 0/0 0 0 80m
Your age will be different.
# on rag1
kubectl -n rag exec curl -- curl -s http://antwort.rag/healthExpected:
{"status": "ok"}
# on rag1
kubectl -n rag exec -i curl -- curl -s -X POST http://antwort.rag/frage -H "Content-Type: application/json" -d @- < f02.json > antwort.json# on rag1
jq -r .antwort antwort.jsonExpected:
[1] Ein Secret darf maximal 1 MiB in Größe haben.
# on rag1
kubectl -n rag exec deployment/antwort -- grep SigCgt /proc/1/statusExpected:
SigCgt: 0000000100004002
Test yourself
- Why does the language model run as a service of its own and not in the embedding service, although both are Ollama?
- An answer takes 22 seconds. How do you find out how much of it was reading the cards?
- With streaming, the first word arrives after 10.6 seconds; without streaming, the whole answer after 15.8. What has streaming gained, and what not?
- Why did the first word arrive after 0.7 seconds for the repeated question – and what does that mean for measurements?
- For a streamed timeout, a client reports “status 200, all good”. What did it overlook?
- The score threshold 0.46 rejects the laptop question. Why does it let the wrong answer to f01 through, and why can this not be solved with a higher threshold?
Answers:
- Separate services have their own memory limits, their own restarts and their own logs. Only that way can you measure which stage is slowing things down, and only that way can a stage be scaled or switched off on its own.
- In the log of the language model:
kubectl -n rag logs deployment/llm | grep "eval time". The lineprompt eval timeis the reading,eval timethe writing; the rest is supplied bysekunden.sucheof the answer service. - The user reads along for the last five seconds instead of waiting, and sees the sources after half a second. The computing time is the same, and the ten seconds of reading before the first word remain.
- Ollama held the whole prompt of the identical question in the cache
(
cached n_tokens = 466) and only had to read one token. Measurements must not repeat any question, otherwise they measure the cache. - With streaming, status and sources are fixed before the model
computes. The timeout comes afterwards as a line
{"fehler": …}in the stream. The client has to check every line. - The best card for f01 has 0.615 – it touches on the topic but does not answer the question. The threshold only measures how close the best card is, not whether it contains the answer. A threshold above 0.615 would also reject f13 (0.489), f11 (0.599) and other correct questions.
Interview note
“How do you prevent hallucinations in a RAG system?” – They cannot be prevented, only contained and made visible. In the lab I had two guards: a score threshold before the model that cheaply rejects questions without a matching card, and an instruction in the prompt. The threshold only caught the questions that were far off, because the scores of questions with and without an answer overlapped. The instruction was followed in substance, but not literally. The most dangerous answer had a source reference: the model turned a card that touched on the topic into a wrong rule. That is why sources belong in every answer, so that users can check them, and the test bench must also assess the answers, not just the search.
Enterprise note
In production, the language model runs on GPUs behind a server such as vLLM, which batches many requests at the same time. Reading the prompt takes milliseconds there instead of seconds. The patterns of this day remain: times per stage in every answer and in the log, streaming with an error format in the stream, timeouts that really cancel at the model, and an upper limit for the answer length. Teams use the prompt cache deliberately: the part that stays the same – instruction, rules, examples – comes first, so that it comes from the cache for every question. Whether answers are actually on their cards is checked with evaluation runs of their own, often with a second model as checker – never as the only judge, but alongside rules and spot checks by humans.
Summary
You put the language model qwen3:1.7b as a service of
its own, llm, next to the embedding service and set the
reranker to zero replicas for it. The answer service – 180 lines of
Python without libraries – embeds the question, fetches three cards,
sends them numbered as a system message to the model and returns answer,
sources and times. The first answer came after 22.8 seconds, of which
0.6 was search and 13.6 reading the cards. Streaming brought the first
word after 10.6 seconds instead of the whole answer after 15.8. A
repeated question began after 0.7 seconds – thanks to the prompt cache.
A timeout of five seconds cancelled the work at the model and, with
streaming, came as a line after status 200. The score threshold 0.46
answers the laptop question in 0.38 instead of 16 seconds, but cannot
catch all questions without an answer. And f01 got a wrong answer with a
source reference. In the diagnosis task you found out why every rollout
hung for 30 seconds: Python as PID 1 ignores SIGTERM. On
Day 10 you measure what happens when several users ask at the same
time.
Commands at a glance
| Command | What it does | Parameters |
|---|---|---|
kubectl describe node rag1 |
promised requests and limits of the node | section Allocated resources |
kubectl -n rag scale deployment rerank --replicas=0 |
switch off a service without deleting it | --replicas |
kubectl -n rag exec deployment/llm -- ollama pull qwen3:1.7b |
load a model into the pod’s volume | -- separates the command in the pod |
kubectl -n rag exec deployment/llm -- ollama show qwen3:1.7b |
size, capabilities and default settings of the model | – |
kubectl -n rag exec -i curl -- curl -s -X POST http://antwort.rag/frage … -d @- < f02.json > antwort.json |
question to the answer service, answer into a file | -i, -d @-, > |
jq -r .antwort antwort.json |
only the answer text | -r raw |
kubectl -n rag logs deployment/llm \| grep "eval time" |
reading and writing time of the model per request | – |
kubectl -n rag exec -i curl -- curl -sN … |
streamed answer line by line | -N without buffer |
curl -w "\n%{http_code} %{time_total}\n" |
append HTTP status and duration | -w |
kubectl -n rag get pods -l app=antwort |
pods of the answer service, including Terminating |
-l label |
time kubectl -n rag delete pod <name> |
measure how long stopping takes | time |
kubectl -n rag exec deployment/antwort -- grep -E '^(SigIgn\|SigCgt)' /proc/1/status |
which signals process 1 ignores and catches | -E |
kubectl -n rag rollout restart deployment/antwort |
restart pods so that they read a changed ConfigMap | – |