Project: a document Q&A CLI
Chunk, embed, retrieve, answer with citations, then measure how often it is wrong. Naive on purpose: this is the baseline module A3 fixes
The brief
Build a command-line tool that answers questions about a folder of documents and cites where the answer came from. The corpus is five markdown files from this repository’s docs/ folder (LABS.md, AUTHORING.md, COURSES.md, DESIGN.md, DEPLOY.md) about the ATLAS project, its courses and its lab stacks, which is enough to be real and small enough to re-embed in under a minute. You copy them into the project once, so later edits to the docs cannot move your baseline or the answers your questions expect. The pipeline runs against the shared stacks from docs/LABS.md: the shop Postgres (with the vector extension you enabled in the embeddings chapter) for storage, Ollama with nomic-embed-text for embeddings, and either llama3.2:3b through Ollama or the Anthropic API for generation.
The tool lives in labs/ai/docqa/ and you create these files:
labs/ai/docqa/
corpus/ # a frozen copy of five docs/ files; every run here and in module A3 uses it
ingest.py # walk a folder, chunk each file, embed, store in Postgres
qa.py # retrieve top-k, build the prompt, answer with citations, CLI loop
questions.json # ten questions with known answers and the file that holds each
evaluate.py # run every question, mark retrieval hit/miss, print a table
RESULTS.md # your baseline: the score, the failures, and why each one failed
Four design choices are fixed, and three of them are deliberately bad. You will replace them in module A3, and you need to feel what each costs first.
Chunking is fixed-size with overlap. 800 characters per chunk, 200 characters of overlap, cut wherever the count lands. No respect for headings, paragraphs, sentences or code blocks. A table row, a list, or a sentence will sometimes be split so that neither half carries the fact. The overlap is the one concession: a fact near a boundary gets a second chance in the next chunk.
Retrieval is top-k by cosine, nothing else. Five chunks, ranked by <=> distance to the embedded question, with the search_query: and search_document: prefixes nomic requires. No keyword matching, no reranker, no filtering by file. A question whose answer is a number will find the chunk with the most similar words, which may be the chunk about the other port.
The prompt is minimal. The model gets the five chunks, numbered, and the question, and is told to answer from the passages only, cite passage numbers in square brackets, and say when the passages do not contain the answer. That last instruction is the one safety feature you keep, because an answer invented from nothing is worse than no answer.
Generation defaults to the local model. llama3.2:3b through Ollama costs nothing and is good enough to show you where retrieval fails. It is not good at following the citation format or at declining to answer. The lab has you run the evaluation a second time against the Anthropic API with claude-opus-5-5, so you can separate failures the small model causes from failures retrieval causes. One evaluation run of ten questions sends about 15,000 input tokens and receives about 2,000 output tokens, which at $4 and $20 per million is roughly $0.10. Interactive questions cost about a cent each.
What good looks like
The CLI starts, reports how many chunks are indexed, and loops: read a question, print the answer with citations, print the cited chunks’ source file and chunk number underneath so a reader can check, repeat. quit exits. Ingest is idempotent: running it twice does not double the index, and running it after a document changes replaces that document’s chunks. Each stored vector carries the model name, so a model change fails loudly rather than mixing spaces.
The evaluation is the deliverable that matters. Ten questions, each with a gold answer and the file it comes from. For each, the script retrieves, records whether the gold answer string appears in any retrieved chunk (a retrieval hit), generates an answer, and prints question, gold, answer and hit side by side. You mark each answer right or wrong by reading it, then classify every wrong one: a retrieval miss (gold not in the top five), a generation miss (gold was in the top five and the model still got it wrong or did not cite it), or a question that was ambiguous. RESULTS.md records the score for each model, the classification of each failure, and one sentence per failure about why, naming the mechanism from the embeddings chapter where it applies: a numeric confusion, a chunk boundary, a heading that outscored its paragraph.
Expect six to eight out of ten with the local model and seven to nine with the API. Expect at least one retrieval miss on a question whose answer is a number, because 5432 and 5433 are one point in embedding space. That is the baseline, and the point of writing it down is that module A3 has to beat it.
Reading the failures
When you classify the failures, you are doing the single most useful thing in applied retrieval work, so do it slowly. A retrieval miss means no prompt change will help; the information never reached the model. Look at what was retrieved instead and ask why it outscored the right chunk. The usual answers are: the right chunk was split at the boundary and neither half looked like the question; the question shares vocabulary with a different section; or the distinguishing detail was a number or a code the embedding cannot see. A generation miss with the small model is often a formatting or instruction-following failure that a stronger model fixes for free. A generation miss with the strong model is interesting: the chunk was there and the model still went wrong, so read the chunk and see whether the fact is actually present whole, or whether the overlap gave you a fragment that looks relevant but is incomplete.
Keep the two numbers separate. ‘Retrieval recall at 5’ (how often the gold answer is in the top five) and ‘answer accuracy’ move for different reasons, and the whole of module A3 is organised around which one you are trying to move.
Build each file, run it, and compare with the expected output before moving on. The reference sketch at the end of the chapter has the key functions if you get stuck; write your own first.
1. Project and table.
mkdir -p labs/ai/docqa && cd labs/ai/docqa # from the root of your checkout
uv add ollama "psycopg[binary]" anthropic # already in labs/ai/pyproject.toml if you did the earlier labs
ollama pull nomic-embed-text && ollama pull llama3.2:3b
docker compose -f ../../databases/compose.yaml exec -T db psql -U atlas shop <<'SQL'
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE IF NOT EXISTS doc_chunks (
id bigserial PRIMARY KEY,
source text NOT NULL,
chunk_no int NOT NULL,
content text NOT NULL,
model text NOT NULL,
embedding vector(768) NOT NULL,
UNIQUE (source, chunk_no)
);
SQLCREATE EXTENSION (or a notice that it exists) and CREATE TABLE. The UNIQUE (source, chunk_no) constraint plus a delete-then-insert per file is what makes ingest idempotent. vector(768) is nomic’s width; a different model fails on insert, which is what you want.2. Ingest: chunk, embed, store.
Write ingest.py. It takes a folder path, finds every .md file (add .pdf through pypdf if you want the stretch goal), splits each file’s text into 800-character chunks with 200 characters of overlap, embeds each batch with the search_document: prefix, deletes that file’s old chunks, and inserts the new ones with the model name. Print one line per file with its chunk count.
Ingest a frozen copy of the five files, not the live docs/ folder:
mkdir -p corpus
cp ../../../docs/{LABS,AUTHORING,COURSES,DESIGN,DEPLOY}.md corpus/
uv run ingest.py corpusCOURSES.md: 70 chunks, LABS.md: 10 chunks, and a total of about 120 chunks (a little more or less if the docs have changed since this was written). Embedding takes 10 to 40 seconds locally. Run it again: the same counts, and SELECT count(*) FROM doc_chunks has not grown. Then SELECT source, chunk_no, left(content, 60) FROM doc_chunks WHERE source LIKE '%LABS.md' ORDER BY chunk_no LIMIT 5; shows the cuts landing mid-sentence and mid-table. That is the naive chunker working as specified.3. Retrieve.
Write the retrieve(question, k=5) function in qa.py: embed the question with the search_query: prefix, run the ORDER BY embedding <=> %s::vector LIMIT %s query, return rows of (id, source, chunk_no, content, similarity). Add a --show mode that prints the retrieved chunks for a question without answering.
uv run qa.py --show "What port does Grafana listen on in the observability lab?"LABS.md. The chunk containing Grafana 3000 should be in the list; note its rank. Now try --show "Which port does the observability stack use for Postgres?". The chunk with Postgres 5433 (so it does not clash with the shop) and the chunk with the shop’s localhost:5432 connection string are both likely to appear, in either order. Embeddings cannot tell the ports apart; the model is going to have to, from the text.4. Answer with citations, and the loop.
Add answer(question, chunks, backend) to qa.py. Number the chunks [1] to [5], put them in the user message above the question, and use a system prompt that says: answer only from the passages, cite passage numbers in square brackets after each claim, and if the passages do not contain the answer say exactly that. The ollama backend calls ollama.chat(model="llama3.2:3b", messages=[...]) and reads response["message"]["content"]. Then the loop: print the chunk count, read a line, retrieve, answer, print the answer, then print [n] source#chunk_no for each cited number so the reader can check.
uv run qa.pyAsk: What port does Grafana listen on in the observability lab? and then What is the connection string for the shop database?
Grafana listens on port 3000 [2]. followed by [2] LABS.md#7. The small model sometimes cites every passage, cites nothing, or wraps the answer in chatter; that is a generation problem, not a retrieval problem, and you will quantify it next. For the connection string it should reproduce postgres://atlas:atlas@localhost:5432/shop exactly, because the chunk contains it verbatim; if it alters a character, write that down as a generation failure.5. The Anthropic backend.
Add an anthropic backend behind a --backend anthropic flag. Use the model id claude-opus-5-5, max_tokens=1024 (the answers are short by design), output_config={"effort": "low"} so the model does not over-think a lookup, and the server-side fallback so a classifier false positive on a benign question retries on another model instead of failing: call client.beta.messages.create with betas=["server-side-fallback-2026-07-01"] and fallbacks="default". Check response.stop_reason == "refusal" before reading content, and read text from blocks whose type == "text". Cost: a question with five 800-character chunks is about 1,500 input tokens and 200 output tokens, about one cent.
ANTHROPIC_API_KEY=... uv run qa.py --backend anthropicThe passages do not contain the answer. when you ask something the docs do not cover (try Who is the CEO?). The small model will often invent an answer to that question; the strong one declines. Both are answering from the same five chunks, which is the point of having two backends: the difference between them is generation quality, and nothing else.6. Ten questions with known answers.
Create questions.json: a list of objects with q, answer (a short string that must appear in the right chunk) and source. Use these ten, all answerable from corpus/LABS.md and corpus/AUTHORING.md, and chosen so that several hinge on a number. Each gold answer is a stable fact those files state word for word: ports, the connection string, row counts, the authoring rules.
[
{"q": "What port does Grafana listen on in the observability lab?", "answer": "3000", "source": "LABS.md"},
{"q": "What is the connection string for the shop database?", "answer": "postgres://atlas:atlas@localhost:5432/shop", "source": "LABS.md"},
{"q": "How many rows does the orders table have at scale 1?", "answer": "2 000 000", "source": "LABS.md"},
{"q": "What does the FAULT_N_PLUS_ONE variable do?", "answer": "one query per item", "source": "LABS.md"},
{"q": "Which five countries account for 70% of customers?", "answer": "DE, NG, US, JP, GB", "source": "LABS.md"},
{"q": "Which local model do the AI labs use by default?", "answer": "llama3.2:3b", "source": "LABS.md"},
{"q": "Which port does the observability stack's Postgres use, and why?", "answer": "5433", "source": "LABS.md"},
{"q": "Which users are VIP in the observability lab?", "answer": "divisible by 97", "source": "LABS.md"},
{"q": "How many options must a Decide block in a chapter have?", "answer": "3–4", "source": "AUTHORING.md"},
{"q": "Which indexes exist after schema.sql runs?", "answer": "primary keys and the two unique constraints", "source": "LABS.md"}
]Check that your snapshot contains every gold answer before you measure anything:
uv run python -c "
import json, pathlib
for x in json.load(open('questions.json')):
if x['answer'] not in pathlib.Path('corpus', x['source']).read_text():
print('not in corpus:', x['q'])
print('checked')"checked and nothing else. If a question is listed, the docs changed before you copied them: replace it with another fact stated verbatim in the same file. The evaluation is only meaningful when every answer is known to be in the corpus.Write evaluate.py: for each question, retrieve five chunks, set hit to whether answer (compare case-insensitively, after collapsing whitespace) appears in any chunk, generate with the chosen backend, and print a table with the question, hit, the gold answer and the first 120 characters of the generated answer. Finish with retrieval hits: n/10.
uv run evaluate.py --backend ollama
ANTHROPIC_API_KEY=... uv run evaluate.py --backend anthropic5433 question or the 3–4 options question (the Decide rule sits in a numbered list that the 800-character cut splits). Answer accuracy, which you judge by reading, is typically 6 to 8 with llama3.2:3b and 7 to 9 with claude-opus-5-5. Every question that is a retrieval hit but a wrong answer on the small model and a right answer on the strong one is a generation failure; every question wrong on both with hit = False is a retrieval failure. Write the classification into RESULTS.md with one sentence per failure naming the cause.one query per item phrase separates from the variable name it explains, so the chunk that matches the question no longer contains the answer. Then set it back to 800 and raise k from 5 to 15. Hits recover and may gain one, but read the answers: the small model gets worse with fifteen passages, because the right one is now diluted by fourteen near-misses, and a model that cannot tell 5432 from 5433 in a paragraph will not do better with three paragraphs about ports. More context is not more accuracy. That trade-off, between recall at retrieval and precision at generation, is what reranking in module A3 is for.Template
# Pilot release note: <tool name>, <version or date>
Owner: <name or role>. Approver: <role>. Date: <date>. Pilot group: <who, how many>.
## 1. What it is
<One paragraph: what it reads, who may ask, which model answers.>
## 2. What it answers well
<Question types with a measured score, for example "ten questions, <n> retrieval hits".>
## 3. Where it fails
| Question | What it returned | Cause (retrieval or generation) | What to do instead |
## 4. Reporting a wrong answer
<Where to send it, what to include: question, answer, passage cited, time.>
<Who reads reports, and how fast they reply.>
## 5. Cost and limits
<Cost per question, cost per eval run, what is assumed.>
## 6. Decision: wider pilot, go or no-go
Decision needed: <what, from whom, by when>. Go if <measurable condition>. No-go if <condition>.
Out of scope: <what this tool must not be used for>. Switch-off: <who, how>.
## 7. How this could be wrong
<One way, and what would show it.> WORKED EXAMPLE
An engineer on the docs team writes this note and the head of engineering approves it. The setting is the lab’s own: the Q&A CLI over five ATLAS docs, about 120 chunks. Figures marked (assumed) are invented to sit inside the lab’s expected ranges, because no real run exists yet; in your own note, use your measured scores.
Owner: docs-team engineer. Approver: head of engineering. Date: 20 November 2026. Pilot group: ten docs users.
What it answers. Facts the docs state in words: ports, the shop connection string, which local model the AI labs use. Ten graded questions: 8 retrieval hits of 10 (assumed, the lab expects 8 or 9). Answers right: 8 of 10 on the API backend (assumed, the lab expects 7 to 9), 6 of 10 on llama3.2:3b (assumed, the lab expects 6 to 8).
Where it fails.
| Question | Cause | Instead |
|---|---|---|
| Which port does the observability stack’s Postgres use? | Retrieval: 5432 and 5433 sit close together, so the shop chunk can outrank the right one |
Read LABS.md |
| How many options must a Decide block have? | Retrieval: the 800-character cut splits the numbered list | Read AUTHORING.md |
| Who is the CEO? (a probe outside the ten) | The small model invents an answer; the API model declines | Use the API backend |
The small model’s two other misses (assumed) are citation slips.
Reporting. Post the question, the answer and the [n] source#chunk_no line in the docs channel. The owner replies within two working days.
Cost. An eval run is roughly $0.10; a question about a cent.
Decision. Needed from the head of engineering by 4 December 2026. Go for ten users on the API backend only; no-go for wider use until retrieval hits reach 9 of 10 on a rerun. Out of scope: anything outside those five files. Switch-off: the owner removes the tool.
Could be wrong. Ten questions are few and the builder chose them. If more than 10 of the pilot’s first 50 answers are marked wrong, 8 of 10 overstates it.
Now you
You work at Northmere Bank Plc, a bank with 4,800 staff and 9.2 million retail customers. The head of retail operations wants to try a Q&A tool over the bank’s internal policy documents, so branch staff can ask it a question and see which passage it cited. Take the CLI you built and your RESULTS.md: your scores for both backends, your failures and their causes, and the cost lines the lab prints are the evidence you have. You have no scores for the policy documents themselves, so say that, and say what you would measure before widening. Write the release note for a pilot with a small group of branch staff, and choose its size. Cover what the tool answers, two of your own failures in plain words, how a staff member reports a wrong answer, and the go or no-go for extending it to other branches. The head of retail operations owns the pilot and the head of technology approves any wider rollout.
Self-check
Rubric
Mark yourself honestly; the baseline is only useful if it is true.
| criterion | points | what earns them |
|---|---|---|
| Ingest is correct and idempotent | 3 | Fixed-size chunks with overlap as specified; running twice does not duplicate; a changed file replaces its chunks; model name stored per row |
| Retrieval uses the model correctly | 3 | search_document: on chunks, search_query: on questions; cosine via <=>; --show prints source, chunk number and similarity |
| Answers cite real chunks | 3 | Citations map to stored rows and are printed as source#chunk_no; the prompt forbids answering outside the passages |
| The ‘not in the passages’ path exists and is tested | 2 | A question the docs do not answer gets a refusal, not an invention, on the strong backend |
| Two backends, same retrieval | 2 | Switching the generator changes nothing about which chunks are retrieved |
| Evaluation script and ten questions | 3 | evaluate.py reports retrieval hits automatically and prints gold against generated for manual marking |
RESULTS.md baseline |
4 | Scores for both backends, each failure classified as retrieval or generation, one sentence per failure naming the mechanism |
Eighteen or more of twenty means you have a baseline worth improving. Fewer than twelve usually means the evaluation step was skipped; go back and do it, because module A3 assumes the number exists.
Reference sketch
Write your own before opening this. It is the key functions, not a complete program; error handling, argument parsing and the PDF path are left to you.
Key functions for ingest.py and qa.py
# ingest.py
import os, sys, pathlib, ollama, psycopg
MODEL = "nomic-embed-text"
DSN = os.environ.get("SHOP_DSN", "postgres://atlas:atlas@localhost:5432/shop")
SIZE, OVERLAP = 800, 200
def chunk(text, size=SIZE, overlap=OVERLAP):
step = size - overlap
return [text[i:i + size] for i in range(0, max(len(text) - overlap, 1), step)]
def to_vec(v):
return "[" + ",".join(f"{x:.7f}" for x in v) + "]"
def embed(texts, prefix):
out = []
for i in range(0, len(texts), 32):
out += ollama.embed(model=MODEL, input=[prefix + t for t in texts[i:i + 32]])["embeddings"]
return out
def ingest(folder):
with psycopg.connect(DSN) as conn:
for path in sorted(pathlib.Path(folder).rglob("*.md")):
chunks = chunk(path.read_text())
vecs = embed(chunks, "search_document: ")
conn.execute("DELETE FROM doc_chunks WHERE source = %s", (path.name,))
conn.cursor().executemany(
"INSERT INTO doc_chunks (source, chunk_no, content, model, embedding) "
"VALUES (%s, %s, %s, %s, %s::vector)",
[(path.name, n, c, MODEL, to_vec(v)) for n, (c, v) in enumerate(zip(chunks, vecs))])
conn.commit()
print(f"{path.name}: {len(chunks)} chunks")
if __name__ == "__main__":
ingest(sys.argv[1])# qa.py
import os, re, sys, ollama, psycopg, anthropic
from ingest import DSN, MODEL, to_vec
SYSTEM = ("Answer the question using only the numbered passages. After each claim, cite the "
"passage number in square brackets, like [2]. If the passages do not contain the "
"answer, reply exactly: The passages do not contain the answer.")
def retrieve(question, k=5):
vec = to_vec(ollama.embed(model=MODEL, input=["search_query: " + question])["embeddings"][0])
with psycopg.connect(DSN) as conn:
return conn.execute(
"SELECT id, source, chunk_no, content, 1 - (embedding <=> %s::vector) "
"FROM doc_chunks ORDER BY embedding <=> %s::vector LIMIT %s", (vec, vec, k)).fetchall()
def build_prompt(question, chunks):
passages = "\n\n".join(f"[{i + 1}] ({src}#{n})\n{text}" for i, (_, src, n, text, _) in enumerate(chunks))
return f"{passages}\n\nQuestion: {question}"
def answer_ollama(question, chunks):
r = ollama.chat(model="llama3.2:3b", messages=[
{"role": "system", "content": SYSTEM},
{"role": "user", "content": build_prompt(question, chunks)}])
return r["message"]["content"]
def answer_anthropic(question, chunks):
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY
r = client.beta.messages.create(
model="claude-opus-5-5", max_tokens=1024,
output_config={"effort": "low"},
betas=["server-side-fallback-2026-07-01"], fallbacks="default",
system=SYSTEM,
messages=[{"role": "user", "content": build_prompt(question, chunks)}])
if r.stop_reason == "refusal":
return "(the model declined to answer)"
return "".join(b.text for b in r.content if b.type == "text")
def main(backend):
answer = answer_anthropic if backend == "anthropic" else answer_ollama
with psycopg.connect(DSN) as conn:
print(conn.execute("SELECT count(*) FROM doc_chunks").fetchone()[0], "chunks indexed")
while (q := input("\n? ").strip()) not in ("quit", "exit"):
chunks = retrieve(q)
text = answer(q, chunks)
print("\n" + text)
for n in sorted({int(m) for m in re.findall(r"\[(\d+)\]", text)} & set(range(1, len(chunks) + 1))):
_, src, no, _, sim = chunks[n - 1]
print(f" [{n}] {src}#{no} (similarity {sim:.3f})")
if __name__ == "__main__":
main("anthropic" if "--backend" in sys.argv and "anthropic" in sys.argv else "ollama")The evaluation script is a loop over questions.json that calls retrieve, computes hit = any(norm(answer) in norm(text) for ...) with norm = lambda s: re.sub(r"\s+", " ", s).lower(), calls the chosen answer function, and prints the table. Keep it under forty lines.
All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.