Chapter 9

Exercises, resources, glossary

Reading builds understanding; changing the code and measuring the result builds skill. These exercises are ordered from "an evening" to "a weekend", and each one ends with a number you can compare.

Exercises

1 · Predict, then look 30 min

Open the Retrieval Lab. For 10 questions of your own, write down before searching whether BM25 or semantic search will rank the right chunk higher. Score your predictions. You'll build an intuition for when each retriever wins faster than any explanation could give you.

2 · An answer-level eval an evening

Create evals/answers.jsonl: 15 questions with a short reference answer, plus 5 questions the portfolio can't answer ("What's his salary expectation?", "Does he know Rust?") whose reference is "I don't know". Write evals/answers.py that runs each through ChatService, then asks the LLM as a judge: "Does the candidate agree with the reference? Does it contain any claim not supported by the sources? Answer in JSON". Report accuracy and the hallucination rate. Files: app/chat.py, evals/.

3 · Add a reranker an evening

A cross-encoder reads the question and a chunk together and outputs a relevance score. It's much more accurate than comparing two separately computed vectors, but too slow to run on every chunk. So: retrieve 20 with hybrid search, rerank those 20, keep the top 5. fastembed includes rerankers (TextCrossEncoder("Xenova/ms-marco-MiniLM-L-6-v2")). Add RERANK=true in config and compare hit@1 and MRR. Files: app/rag/index.py.

4 · concat vs. LLM query rewriting an evening

Write 10 two-turn cases where the second question needs the first ("How did the scheduler work?" → "What did it replace?"), including topic changes. Measure retrieval for QUERY_REWRITE=concat and =llm, plus the latency each adds. Is the extra LLM call worth it?

5 · The boring baseline an evening

Make a RETRIEVAL=off mode that puts all documents in the prompt (~9k tokens). Run exercise 2's eval on both modes and record answer quality, time to first token, and tokens per request. Write down when you'd choose each. (Chapter 3 argued for RAG; this is where you check that argument.)

6 · Break the first provider 30 min

Put a model that can't work at the front of LLM_MODELS (a misspelled name, or mistral/mistral-small-latest with MISTRAL_API_KEY=wrong), restart, ask two questions and read the logs: the first should show "Falling back to … order 2", the second shouldn't even try the broken model (cooldown). Then add a provider of your own (Mistral, NVIDIA, or ollama/qwen3:8b on your machine) and run python -m evals.models to decide where it belongs in the order.

7 · Contextual retrieval a weekend

For each chunk, ask the LLM once (at index time) for one sentence situating it within its document, and prepend it before embedding and BM25 indexing, as in Anthropic's article. Cache the sentences (it's the costly part). Re-run the retrieval eval.

8 · pgvector a weekend

Implement the index on Postgres + pgvector (embeddings) + Postgres full-text search (in place of BM25), keeping search()'s signature. Your existing eval tells you whether you broke anything. That's exactly the refactor you'd do when the corpus outgrows memory.

9 · Better voice a weekend

Pick a row from chapter 7's latency table and attack it: Silero VAD in the browser (vad-web), Groq's Whisper for STT, or streaming Kokoro audio (create_stream) so playback starts before the sentence is fully synthesized. Measure time-to-first-sound before and after with performance.now() in the browser.

10 · Speech-to-speech a weekend

Build a separate prototype on the Gemini Live API, giving it your retrieval as a tool it can call. Compare latency and naturalness with the cascade, and think about what tool access means for prompt-injection risk (chapter 3).

11 · Close the feedback loop ongoing

Once the site is live, read GET /api/admin/feedback every week or two. For each 👎, decide (chapter 4): retrieval problem, generation problem, or a question the portfolio simply can't answer. Add each one to evals/questions.jsonl (or a refusal test), fix, re-run the eval. Bonus: chart the 👍/👎 ratio over time.

12 · Filter by kind an evening

Page awareness filters by url. Add a second metadata filter on kind: when a question says "project(s)", search only project documents first. Detect it with a keyword rule, then with an LLM call that outputs a filter (that's called self-querying). Does hit@1 move on the project questions?

What about blockchain?

Your original idea mentioned RAG and blockchain. Honestly, blockchain doesn't fit this feature. A blockchain solves one specific problem: agreeing on shared state among parties who don't trust each other, without a central operator. A portfolio assistant has one operator (you) and no such problem, so adding a chain would be decoration that recruiters with blockchain experience would see through. If you want to learn it, a separate, honest project works better. For example, verifiable credentials: issue signed, tamper-evident attestations (a certificate, a contest result) that anyone can verify without contacting the issuer. That teaches signatures, hashes and smart contracts, with a real reason to exist.

Where to learn more

  • bookChip Huyen: AI Engineering (O'Reilly, 2025). The best single book on building with foundation models: RAG, evals, latency, cost.
  • bookJay Alammar & Maarten Grootendorst: Hands-On Large Language Models. Very visual; embeddings, retrieval and fine-tuning with code.
  • courseKarpathy: Neural Networks, Zero to Hero From backprop to GPT, by hand. Matches your learn-ai-engineering mission.
  • courseHugging Face Learn Free courses on LLMs, audio models and more.
  • articleAnthropic: Building effective agents The natural next step after RAG: models that use tools.
  • blogSimon Willison Practical, honest, daily notes on LLMs, including prompt injection.
  • blogEugene Yan RecSys/LLM systems in production; great on evals.
  • blogHamel Husain Evals, evals, evals.

Glossary

TermMeaning
TokenThe unit models read and write: a word or piece of one (~¾ of an English word on average).
Context windowThe maximum number of tokens (prompt + answer) a model can handle in one request.
System promptStanding instructions at the start of the conversation: identity, rules, format.
TemperatureRandomness of token choice. 0 = always the most likely token.
Reasoning / thinkingHidden tokens some models generate before answering. Better on hard tasks, slower to first token.
HallucinationFluent, confident output that isn't true or isn't supported by the sources.
Grounding / faithfulnessEvery claim in the answer is supported by the provided sources.
RAGRetrieval-Augmented Generation: search your data, put the results in the prompt, then generate.
EmbeddingA fixed-length vector representing a text's meaning; similar meanings point in similar directions.
Cosine similarityCosine of the angle between two vectors; with unit vectors, just their dot product.
ChunkA piece of a document; the unit that is indexed, retrieved and shown to the model.
Metadata filteringRestricting a search with facts about chunks (page URL, kind, date, access rights) rather than their text.
User feedback loopCollecting 👍/👎 on answers, diagnosing the bad ones, and turning them into eval cases.
Schema migrationA change to an existing database's structure (e.g. adding a column) applied without losing its data.
BM25Keyword ranking function: term frequency (saturating) × IDF, with length normalization.
IDFInverse document frequency: rarer words carry more weight.
Hybrid searchCombining keyword and semantic retrieval.
RRFReciprocal Rank Fusion: merge rankings by summing 1/(k + rank).
Top-kHow many retrieved chunks go into the prompt (5 here).
Reranker / cross-encoderA model that scores (question, chunk) pairs jointly; accurate but slow, so used on a shortlist.
ANN / HNSWApproximate nearest-neighbour search; HNSW is the graph index most vector DBs use.
hit@k, MRRRetrieval metrics: right result in the top k; mean of 1/rank of the first right result.
LLM-as-judgeUsing a model to grade another model's outputs against a rubric or reference.
Prompt injectionText that tries to override the model's instructions (from a user or from retrieved content).
OpenAI-compatible APIThe de-facto standard request format for chat, embeddings and audio endpoints.
FallbackAnother provider/model tried when the first fails (here: the next entry of LLM_MODELS).
CooldownA period during which a model that just failed is skipped, so visitors don't wait for an error we can predict.
Retry-AfterAn HTTP header a server sends with a 429 or 503: "try again in N seconds". LiteLLM uses it as the cooldown.
LiteLLMOpen-source library: one function for 100+ LLM providers, plus a Router for failover and load balancing.
TPM / RPM / RPDTokens per minute, requests per minute, requests per day: the three usual free-tier limits.
SSEServer-Sent Events: a simple text format for streaming events over one HTTP response.
CORSBrowser rule controlling which origins may read a server's responses.
Rate limitA cap on requests per client per time window.
STT / ASRSpeech-to-text / automatic speech recognition (Whisper).
TTSText-to-speech (Kokoro).
VADVoice-activity detection: is someone speaking right now?
PCM, sample rateRaw audio as numbers; how many per second (16k, 24k, 48k).
CodecAudio compression format (Opus, AAC); WAV is uncompressed PCM.
RTFReal-time factor: compute time ÷ audio duration. Below 1 = faster than real time.
PhonemeA unit of pronunciation; TTS converts text to phonemes before audio.
Quantization (int8)Storing weights at lower precision: smaller and faster, slightly less accurate.
ONNX / ONNX RuntimeA portable model format / a lean engine that runs it on CPU or GPU.
InferenceRunning a trained model (as opposed to training it).
Barge-inInterrupting a voice assistant while it's speaking.
Cascaded vs. speech-to-speechSTT → LLM → TTS pipeline vs. one model that hears and speaks.