14B.6 Interview Prep I: Coding and Fundamentals

Ship & get hiredLesson 6 of 919,052 wordsOptional7 parts
Module 14B Β· all lessons optional
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9

The AI-engineer interview is a strange hybrid: part software-engineering screen, part LLM-domain quiz, part system-design conversation, and increasingly part judgement test about how you work with AI tools rather than without them. This lesson covers the first half of that loop β€” what the rounds actually look like, how to prepare for them on a realistic schedule, the Python coding patterns interviewers probe, a set of LLM-flavoured coding drills you can run with no API keys, and the fundamentals question bank that separates candidates who memorised vocabulary from candidates who understand the systems. 14B.7 owns the system-design round; 14B.8 owns take-homes, behavioural rounds and offers. This lesson assumes you've worked through Modules 00–13 and are preparing to be assessed on that knowledge, not to learn it for the first time.

What you'll learn

  • What AI-engineer interview loops actually contain β€” recruiter screen through final loop β€” with sourced, dated examples from company-published processes and clearly flagged variation
  • How AI-assisted coding is handled in interviews in 2026: the policies genuinely differ by company and even by round, and the only safe default is to ask before you assume
  • A preparation strategy that survives contact with reality: time-boxed 2-, 6- and 12-week plans, spaced repetition, mock interviews, recording yourself, tracking weak areas and rest
  • The Python coding canon interviewers test β€” the pattern catalogue from two pointers to dynamic programming β€” plus the Python-specific pitfalls that sink otherwise good candidates
  • A repeatable problem-solving routine you can run out loud in any shared editor
  • Seventeen LLM-flavoured coding drills β€” token buckets, bounded concurrency, SSE parsing, chunking, cosine top-k, BM25, RRF, prompt templates, JSON repair, a tool-call loop, retrieval metrics, an LRU cache with TTL and single-flight, a token budget packer, eval-run diffing, a mini BPE tokenizer and pure-Python attention β€” each with a complete solution, complexity analysis, tests and extension questions, shipped as the career_kit/drills/ package
  • A 77-question ML/LLM fundamentals bank with concise model answers hidden in <details>, including nine scenario questions (debugging a regression, caching, outages, cost cuts, no-data evals), each tagged with the module lesson it comes from and a difficulty level
  • Rapid-review answers for software-engineering fundamentals (HTTP, async, SQL, caching, queues, idempotency, testing, debugging, git, security, concurrency, observability) and statistics-for-AI (precision/recall, confidence intervals, A/B tests, sample sizes, evaluation bias)

What you don't need

  • API keys or model access. Every drill is pure Python 3.11+ standard library β€” the same constraint as a real interview environment. The one optional dependency is pytest for the test suite; the demo runner needs nothing.
  • Interview experience. The preparation strategy in Part 2 is written for a first loop.
  • A job offer in hand. Everything here works whether your interview is next week or next year β€” the drills double as portfolio evidence of engineering depth.

Setup

The drills ship as a small package inside the module's career_kit project. Create the project and copy the files shown in Part 4:

bash
uv init career-prep --bare --python 3.13 && cd career-prep
mkdir -p career_kit/drills
uv add pytest        # optional: only needed to run the test suite
# or: pip install pytest

If uv is new, lesson 03.1, Part 4 walks through project setup. Then:

bash
uv run python career_kit/drills/run_all.py     # runs every drill, prints real output
uv run pytest career_kit/drills/test_drills.py  # the pytest suite (44 tests)
# without uv: python3 career_kit/drills/run_all.py  and  python3 -m pytest career_kit/drills/test_drills.py

Everything else in this lesson β€” the interview-format research, the preparation plans, the fundamentals Q&A β€” needs only a text editor and your own projects.


What you must be able to do after this lesson#

  • Describe the stages of an AI-engineer interview loop
  • Plan 2-, 6- or 12-week interview preparation with spaced repetition and mock interviews
  • Solve a standard Python coding problem aloud using a repeatable routine
  • Implement an LLM-flavoured drill such as a token bucket or cosine top-k
  • Explain core ML and LLM fundamentals in short, accurate answers

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"Our process has a coding screen and a system design round." Part 1: what the loop contains
"Can I use AI tools in the interview?" 1.3 AI-assisted coding
"How do I prepare in six weeks?" Part 2: preparation strategy
"Implement a rate limiter." 4.1 Token-bucket rate limiter
"Parse this SSE stream." 4.4 Streaming SSE parser
"Rank these documents with BM25." 4.7 BM25 from scratch
"What is RAG vs fine-tuning?" or "Answers got worse after a release β€” what do you do?" Part 5: ML/LLM fundamentals and scenario questions
"Explain the p95 latency vs cost trade-off." Part 6: engineering fundamentals and Part 7: statistics

Part 1: What AI-engineer interviews actually look like#

1.1 The honest answer: there is no single loop#

Ask five companies "what does your AI-engineer interview look like" and you'll get five different answers β€” and even the same company changes its loop by team, level and quarter. What is stable is the shape: nearly every technical hiring process moves from cheap-to-evaluate screens to expensive-to-run deep rounds, and AI-engineering roles add LLM-specific content to the middle of that funnel.

The most reliable way to know a specific company's process is to read what the company itself publishes, then confirm with candidates. Two frontier labs publish unusually detailed process descriptions, so they're worth studying as anchors β€” not because every company copies them, but because they show what "published process" looks like when it exists.

OpenAI's published interview guide (openai.com/interview-guide; the live page blocks scripted requests, so the quotes below were checked against the Internet Archive's snapshot of 9 October 2026 on 12 November 2026 β€” open the live page for the current text) describes:

  1. Application and rΓ©sumΓ© review β€” "typically takes the recruiting team one week".
  2. Introductory calls β€” a conversation with the hiring manager or recruiter about your work, motivations and goals.
  3. Skills-based assessment β€” "formats vary by team and may include: pair coding interviews, take-home projects, technical tests, etc." Candidates hear back "within a week".
  4. Final interviews β€” "typically 4–6 hours of final interviews with 4–6 people over 1–2 days", virtual by default with an SF onsite option. For engineering roles OpenAI says it looks for "well-designed solutions to the challenge, high-quality code, optimal performance, and good test coverage", plus "strong communication and collaboration skills". Decision expected "within one week of your final interviews".

Anthropic's careers page (anthropic.com/careers, checked November 2026) says all interviews are over Google Meet, technical roles use "live coding tools like Colab and CodeSignal", and β€” a detail worth noticing β€” "you can look things up β€” just be comfortable with basic syntax and standard libraries so it doesn't eat up your time". Their FAQ states they can't provide feedback on resumes or interviews, that candidates may re-apply after 12 months, and that recruiters only email from @anthropic.com addresses and never ask for money β€” practical scam-awareness guidance baked into the official page.

flowchart LR
    A["Application + rΓ©sumΓ© review<br/>(days to ~1 week)"] --> B["Recruiter / hiring-manager screen<br/>(30–45 min call)"]
    B --> C["Technical screen(s)<br/>coding Β· practical build Β· sometimes SD"]
    C --> D["Take-home or pairing round<br/>(some companies, some teams)"]
    D --> E["Onsite / final loop<br/>3–6 rounds over 1–2 days"]
    E --> F["Decision<br/>~1 week is common, not guaranteed"]
    C -.->|"LLM-flavoured variants:<br/>eval-aware coding, RAG/agent builds"| E

1.2 The round-by-round map#

However a given loop is arranged, the content clusters into a small set of round types. Learn to recognise each one, because each is prepared differently.

Round type What it usually contains What they're actually measuring Prepare with
Recruiter screen Background, motivation, logistics, salary range, notice period Communication, coherence of your story, whether you're real Your rΓ©sumΓ© aloud, three project narratives, honest answers on logistics
Technical screen (coding) 1–2 timed problems in a shared editor or assessment platform Pattern recognition, communication under time pressure, code quality Part 3 + drills
Technical screen (practical) Build something small and working β€” an API, a script, a mini RAG β€” or debug a broken one (a failing retrieval step, a bad prompt, a flaky tool call) Whether you can ship, not whether you can recite Your portfolio projects; redo one from memory
LLM/ML fundamentals Questions on tokens, embeddings, RAG, evals, hallucination, cost Whether you understand the systems you claim to build Part 5
System design Design an AI product in 45–60 min Structured thinking, trade-offs, LLM-specific concerns 14B.7
Take-home / pairing Async project or live pairing on real-ish code Unsupervised judgement, communication, code review skills 14B.8
Behavioural Past behaviour as evidence of future performance Ownership, conflict, ambiguity, ethics 14B.8, Part 2
Project deep-dive "Walk me through something you built" Whether the portfolio is yours, and whether you understand it Your capstone; 14B.8, Part 3

Two trends are worth naming honestly, with dates:

  • The practical-coding shift. Multiple published guides and company processes describe coding rounds that look more like "build a working thing and extend it" than "recite an algorithm". Anthropic's published example of live coding emphasises working syntax over recall; OpenAI's guide lists "well-designed solutions… optimal performance, and good test coverage" as the engineering bar. This doesn't mean algorithms are dead β€” it means the format increasingly rewards someone who can write clean, tested, extensible Python under time pressure, which is exactly what Part 3 and the drills train.
  • LLM-specific content is now standard. Questions about evals, retrieval, cost and hallucination appear even in generic "AI engineer" loops because they're the failure modes that distinguish a working system from a demo. Part 5 is built for exactly this.

1.3 AI-assisted coding in interviews: the honest answer#

This is the question candidates most want a yes/no on, and the truthful answer is: it depends on the company, the round, and sometimes the interviewer β€” so you must ask, and you must never assume.

What the verifiable record shows as of November 2026:

  • OpenAI's guide states plainly: "Expectations for AI and other tools vary by interview: some formats intentionally allow them, while others are designed to assess your independent problem-solving without AI tools. We'll explain what is allowed in your interview preparation materials. If you're unsure, please ask your recruiter before the interview."
  • Anthropic's candidate guidance (anthropic.com/candidate-ai-guidance, last updated July 10, 2025) gives a stage-by-stage policy: use Claude to refine your rΓ©sumΓ© draft but create the first draft yourself; complete take-homes without Claude unless they indicate otherwise; use AI freely for interview preparation; and during live interviews "this is all you β€” no AI assistance unless we indicate otherwise".
  • Meta's AI-assisted coding interview was reported by interviewing.io (a mock-interview platform; the post's author says they have conducted over 1,000 mock and real interviews) as an October 2025 pilot: a 60-minute CoderPad round with an AI assistant built in, replacing one of two onsite coding rounds, with a wider rollout expected in 2026 (the post's own wording on which roles differs between sections). Treat this as a reported trend, not a universal rule β€” but it's evidence the "AI-in-the-loop" format is real and spreading.
  • Assessment platforms are adapting too. Codility's own product pages and release notes (codility.com, checked November 2026) now describe live coding in a shared VS Code environment that shows Claude Code and Codex in the terminal, AI that can be switched on or off for each task, and every prompt and response saved to the candidate report when AI is allowed (vendor-stated, read 9 November 2026; the home page labels none of this preview, beta or generally available, and does not say the tools are preinstalled) β€” meaning some employers now want to see how you use agents, while others still run proctored, no-AI tests. The platform doesn't tell you which; the invitation does.

What to actually do:

Situation Action
Recruiter screen or any round where rules aren't stated Ask: "Are AI assistants permitted in the technical rounds?" β€” it's a normal logistics question, not a red flag
AI explicitly allowed Use it for well-defined subtasks (boilerplate, lookups, test generation) and narrate your reasoning β€” the skill being tested becomes orchestration and judgement, not recall
AI explicitly forbidden Treat autocomplete as forbidden too if the policy is strict; practise typing syntax from memory
Unclear / async assessment Default to no AI unless the instructions say otherwise, and disclose any AI use you did employ
Live interview, AI allowed, you freeze Fall back to thinking aloud and solving by hand β€” permitted AI is a tool, never an obligation

1.4 How to find your specific loop#

Because processes vary, the highest-leverage prep step is intelligence-gathering:

  1. Read the job posting carefully β€” level signals ("senior", "staff"), team (product vs platform vs research-adjacent), and any mention of take-homes or pairing.
  2. Check the company's own careers/culture pages β€” some publish interview guides (OpenAI and Anthropic do; Google's "how we hire" pages describe a general process but are JS-rendered and change often β€” verify at application time).
  3. Ask the recruiter directly β€” format, duration, tools, AI policy, what the loop emphasises. Recruiters expect this.
  4. Read recent candidate reports critically β€” sites like interviewing.io publish company process guides and interview-question write-ups; treat individual reports as anecdotes (one candidate's loop β‰  yours), but look for patterns across several.
  5. Prepare for the superset β€” you can't cover every possible round, but coding fundamentals + LLM fundamentals + one system-design rehearsal + a project narrative covers most of what a typical loop contains (the author's judgement; no survey backs a percentage).

1.5 How loops differ by company type and level#

Two questions recruiters' screens probe implicitly: "which kind of company is this?" and "which level are they hiring for?" Both change what the loop emphasises. Treat the tables below as typical patterns, not rules β€” the only authoritative answer comes from the company's own process page and the recruiter screen (1.4). The company-type taxonomy itself is 14B.1's job; this is just how it shows up in interviews.

By company type:

Company type Typical loop shape What gets weighted most
Big tech / large platform Standardised multi-round loop (often 4–6 rounds); heavy algorithms + system design + behavioural; some publish guides Pattern fluency under time pressure, large-scale system design, behavioural stories at scale
Startup / scale-up Fewer rounds, compressed timeline; a practical build or take-home weighted heavily; founder/executive chat common Shipping speed, ambiguity tolerance, communication β€” "can you own an unclear problem end to end?"
Enterprise / consultancy Hiring-manager + panel rounds; take-home or pairing heavy; scenario and domain questions Practical delivery, client-facing communication, judgement about constraints you don't control
Research-lab-adjacent Deeper fundamentals (training, evals, model behaviour); may include paper discussion or a research-taste conversation Breadth and honesty about uncertainty β€” "what would you measure?" beats confident guessing

By level:

Level What the loop probes What "strong" sounds like
Junior / new grad Fundamentals breadth, pattern recognition, ability to learn aloud Clean correct code, good clarifying questions, narrates reasoning without prompting
Mid-level Independent design trade-offs, production awareness (tests, failure modes, cost) Justifies choices with numbers, handles edge cases unprompted, knows what they don't know
Senior / staff Ambiguity, organisational constraints, mentoring signal, "what would you cut?" Scopes the problem before solving, names risks and dependencies, influences without authority, thinks in systems not tasks

Part 2: A preparation strategy that survives contact with reality#

2.1 The plan that matches your runway#

Interview prep fails in two opposite ways: cramming everything the week before (exhausting, shallow, forgettable) and drifting for months without structure (no measurable progress). The fix is a time-boxed plan scaled to your runway β€” the same sprint discipline 14A.8 applies to skill gaps, applied to interview readiness.

Runway Strategy Weekly shape
2 weeks (interview already scheduled) Triage, don't learn. Identify the 2–3 weakest high-yield areas from 14A.8's matrix, drill them daily, run one full mock, polish stories and logistics ~60% drills + fundamentals Q&A, ~25% mock/rehearsal, ~15% rest
6 weeks (typical notice period or application-to-loop gap) Balanced build. Weeks 1–2: Python fundamentals patterns + start drills. Weeks 3–4: LLM drills + fundamentals Q&A + one system-design rehearsal (14B.7). Weeks 5–6: mocks, weak-area iteration, logistics ~50% deliberate practice, ~30% mocks/feedback, ~20% fundamentals breadth
12 weeks (targeting roles, no date set) Deep build. Treat prep as a portfolio project: work through all 17 drills and write tests for them (that's evidence), build the question bank into flashcards, run mocks biweekly, do one take-home dry run (14B.8) ~40% drills/projects, ~30% spaced fundamentals, ~20% mocks, ~10% rest and reflection

2.2 Deliberate practice, not volume#

Research on learning (deliberate practice, the testing effect, spaced repetition) broadly supports the same conclusion: focused practice with feedback beats raw volume. The effect sizes depend on the task, so treat this as a sensible default rather than a guarantee. For interview prep that means:

  • Time-boxed drills. Give yourself 25–35 minutes per problem β€” the length of a real interview question β€” then stop, even mid-solution. Write down where you got stuck. This mimics the pressure and teaches triage.
  • Spaced repetition. Re-solve a problem you failed 3 days later, then a week later. The forgetting curve is your friend here β€” struggling to recall is what builds retention. Tools like Anki or a plain Markdown flashcard file both work; the LLM fundamentals bank in Part 5 is designed to be converted into cards.
  • Interleaving. Don't do 20 array problems in a row. Mix patterns β€” a hash-map problem, then a tree, then an LLM-flavoured one β€” because real interviews mix topics and recognising which pattern applies is itself a skill.
  • Retrieval practice. Close the lesson, then write what you remember. Explain a concept to a rubber duck or a peer. The 14B.8 project-narrative technique applies here too.

2.3 Mock interviews: how to run a good one#

A mock interview is only useful if it reproduces the pressure and feedback of a real one. Here's the protocol that works:

Find a partner. Options, verified as of November 2026:

Platform What it offers Cost Best for
Peer mock (a friend, colleague, study group) Free, flexible, immediate feedback Free High volume, early reps
Pramp (its footer credits Exponent Labs, and its banner says that since July 2024 new Pramp sessions are hosted on "Aced Practice" β€” checked 11 November 2026; branding changes, so check the site for what is offered today) Peer matching, collaborative editor, roughly 30–45 min each way The site's FAQ says it is free (checked November 2026); terms change, so confirm Regular practice, video format
interviewing.io Anonymous audio-and-chat mocks with Senior/Staff/Principal-level engineers and managers who hire at FAANG-scale companies; also a free AI Interviewer for coding and system design (homepage, checked November 2026) Human sessions are paid; the homepage lists no prices, so check before you book. The AI Interviewer has free problems Calibrating before a real loop
Study group / community Async question review, mutual drills Free Fundamentals Q&A, accountability

Run the mock properly:

  1. Pick one round type β€” don't try to mock the whole loop at once. Coding, system design and behavioural each need different prep.
  2. Use a real-ish prompt. For coding, pull from NeetCode 150 or write an LLM-flavoured variant (see Part 4). For fundamentals, draw from the Part 5 bank.
  3. Record or take notes. The single most valuable mock artefact is a record of where you hesitated, what you forgot, and what the interviewer had to clarify. Review it within 24 hours.
  4. Get specific feedback. "How was that?" yields nothing. "Where did my reasoning break down?" yields a study plan.
  5. Rotate roles. Interviewing others teaches you what interviewers look for β€” and reveals your own gaps faster than being interviewed does.

2.4 Recording yourself, tracking weak areas, and rest#

Record yourself. Use your phone or any screen recorder to capture one mock per week. Watch it back with sound off first β€” body language and hesitation are visible without audio β€” then with sound to catch verbal tics ("um", "like", apologising for thinking). Many people are surprised by the gap between how they think they sound and how they actually sound.

Track weak areas explicitly. Keep a running list β€” a Markdown file is enough β€” with three columns: area, evidence (the problem/question that exposed it), next action. Review it weekly. Patterns emerge fast: "I always freeze on graph problems" or "I can't explain cost trade-offs without notes". Those patterns are your study plan.

Rest is part of the plan. Interview performance is substantially cognitive endurance β€” 4–6 hours of final rounds (OpenAI's published figure) is a marathon. Sleep, exercise and breaks aren't soft extras; they're what let you think clearly at hour five. A prep plan with no recovery built in produces a candidate who knows the material and can't access it under pressure.

2.5 The day before and the day of#

Day before:

  • Re-read your project narratives and the Part 5 questions you flagged as weak β€” retrieval practice, not re-learning.
  • Prepare logistics: links, code editor or platform tested, water, notebook, quiet room.
  • Prepare your questions for the interviewer (14B.8, 4.1 has a good list).
  • Sleep. Seriously. A well-rested candidate who knows 80% of the material beats an exhausted candidate who knows 95%.

Day of:

  • Remote setup: test camera, microphone, screen share and internet 30 minutes before. Close notifications, silence your phone, tell housemates. Have a backup hotspot or phone tethering option ready.
  • In the room (or on the call): arrive/ dial in 5 minutes early. Have water and a notebook. For coding rounds, don't wear headphones unless the platform requires them β€” you need to hear the interviewer.
  • The routine: when given a problem, don't start coding immediately. Follow the routine in 3.1 β€” clarify, examples, approach, code, test. Interviewers score the process, not just the answer.
  • When stuck: say so. "I'm stuck on the approach β€” let me think about whether there's a simpler version" is a good interview answer. Silent flailing is not.
  • When you don't know: "I don't know X, but here's how I'd find out" is a senior-level answer. Guessing confidently is a junior-level mistake.

Handling nerves:

  • Try reframing nerves as readiness: racing heart and fast breathing are the same physiology as excitement. Some studies suggest relabelling helps some people; the evidence is mixed, so treat it as a technique to test in mocks, not a guarantee.
  • Use the first 60 seconds to breathe and listen before speaking β€” it also makes you sound more thoughtful.
  • Remember: the interviewer wants you to succeed. They're not trying to trick you; they're trying to see how you think.
  • If you blank on something you knew, say "I knew this β€” let me reconstruct it" and talk through what you remember. Partial recall with good reasoning beats silent panic.

2.6 The mock-interview scoring rubric#

Score every mock on the same rubric a real interviewer uses β€” this turns "how did that go?" into a number you can track. Rate each dimension 1–4 (1 = harmful, 2 = weak, 3 = solid, 4 = excellent):

Dimension What 4 looks like What 1 looks like
Problem understanding Restated accurately, asked the right clarifying questions, found edge cases unprompted Started coding on a misread problem, never clarified
Approach & complexity Named the pattern, stated naive→optimal path, justified time/space Jumped to code, no complexity reasoning, brute force without noticing
Code quality Clean, idiomatic Python, good names, no bugs, handles edge cases Works but ugly, or buggy, or wouldn't survive review
Communication Narrated reasoning, flagged uncertainty, responded to hints well Silent 10 minutes, or talked without structure
Testing & verification Walked examples by hand, named edge cases, stated invariants Declared "done" without testing, or tests were an afterthought
Composure Recovered from mistakes calmly, used hints, stayed within time Panicked, spiralled, or ran out of time with nothing to show

How to use it: after each mock, both interviewer and candidate score independently, then compare β€” the gap between self-perception and observer perception is itself diagnostic (a common pattern in mock sessions, in the author's experience, is over-rating communication and under-rating code quality). Track total score across mocks; you're ready when you're consistently β‰₯3 on every dimension, not just when problems feel easy.


Part 3: Python coding fundamentals β€” the interview canon#

3.1 The problem-solving routine (think-aloud checklist)#

The single highest-leverage interview skill isn't knowing the algorithms β€” it's running a consistent, visible problem-solving process. Interviewers can't see your brain; they can only hear you think. This routine, used every time, turns silent struggle into scored signal:

text
1. CLARIFY   β€” restate the problem, ask about constraints, edge cases, examples
2. BRUTE     β€” describe the naive O(nΒ²) or O(nΒ·m) approach first (shows you understand the problem)
3. OPTIMIZE  β€” identify the pattern, propose the better approach with complexity
4. CODE      β€” write clean Python, narrating as you go
5. TEST      β€” walk through an example by hand, then edge cases, then complexity
6. EXTEND    β€” if time remains, discuss variations or optimizations

What "thinking aloud" actually sounds like:

"So I need to find pairs of numbers that sum to a target. The naive approach is nested loops β€” O(nΒ²). But I notice we can sort the array and use two pointers β€” that's O(n log n) for the sort plus O(n) for the scan. Let me think about whether sorting is worth it versus a hash map which would be O(n) time but O(n) space… I'll go with the hash map since space isn't constrained here."

That narration shows pattern recognition, complexity reasoning and trade-off judgement β€” three things interviewers score.

3.2 The pattern catalogue#

Interview problems cluster into a small set of patterns. Learn to recognise the pattern from the problem description β€” that's the skill being tested, not memorising solutions.

Pattern Signal words Canonical problem Complexity
Hash map / dictionary "find pairs", "count frequencies", "seen before", "first duplicate" Two Sum, Group Anagrams O(n) time, O(n) space
Two pointers "sorted array", "pair in sorted order", "in-place" Two Sum II, 3Sum O(n) after sort
Sliding window "longest/shortest substring/subarray", "contiguous" Longest Substring Without Repeating, Max Sum Subarray (Kadane) O(n)
Stack "matching", "balanced", "next greater", "undo" Valid Parentheses, Daily Temperatures O(n)
Queue / deque "level by level", "first in first out", "sliding window max" BFS levels, Sliding Window Maximum O(n)
Heap "k largest/smallest", "top k", "median of stream" Kth Largest, Merge K Sorted Lists O(n log k) or O(n log n)
Sorting + binary search "sorted", "search in rotated", "median of two arrays" Binary Search, Search in Rotated O(log n)
Recursion / backtracking "all combinations", "permutations", "subsets", "N-Queens" Subsets, Permutations, Word Search O(2ⁿ)–O(n!) typical
Trees (DFS/BFS) "binary tree", "path sum", "lowest common ancestor", "level order" Inorder Traversal, LCA, Diameter O(n)
Graphs (BFS/DFS) "grid", "matrix", "islands", "shortest path", "dependencies" Number of Islands, Course Schedule O(V+E)
Intervals "meeting rooms", "merge intervals", "non-overlapping" Merge Intervals, Meeting Rooms II O(n log n)
Dynamic programming "number of ways", "minimum cost", "longest…ending at", "coin change" Climbing Stairs, Coin Change, LCS O(nΒ·m) typical
Greedy "minimum/maximum", "activity selection", "jump game" Jump Game, Coin Change (greedy fails) varies
Bit manipulation "single number", "power of two", "missing number" Single Number, Counting Bits O(1) space tricks
Iterators / generators "lazy", "infinite", "stream", "yield" Flatten nested list, merge sorted streams O(1) amortised

3.3 Worked examples: the canon in Python#

These aren't the drills package β€” they're the patterns you'll see in any coding screen. Each is complete enough to run; complexity noted.

Two pointers (sorted array):

python
def two_sum_sorted(nums: list[int], target: int) -> list[int] | None:
    """Return 1-based indices of two numbers summing to target. O(n) time, O(1) space."""
    lo, hi = 0, len(nums) - 1
    while lo < hi:
        s = nums[lo] + nums[hi]
        if s == target:
            return [lo + 1, hi + 1]
        if s < target:
            lo += 1
        else:
            hi -= 1
    return None
Output4 lines
>>> two_sum_sorted([2, 7, 11, 15], 9)
[1, 2]
>>> two_sum_sorted([1, 2, 3, 4], 7)
[3, 4]

Sliding window (longest substring without repeating):

python
def length_of_longest_substring(s: str) -> int:
    """Longest substring with all unique chars. O(n) time, O(min(n, alphabet)) space."""
    seen: dict[str, int] = {}
    left = best = 0
    for right, ch in enumerate(s):
        if ch in seen and seen[ch] >= left:
            left = seen[ch] + 1
        seen[ch] = right
        best = max(best, right - left + 1)
    return best
Output6 lines
>>> length_of_longest_substring("abcabcbb")
3
>>> length_of_longest_substring("bbbbb")
1
>>> length_of_longest_substring("pwwkew")
3

Hash map (two sum, unsorted):

python
def two_sum(nums: list[int], target: int) -> list[int] | None:
    """Return 0-based indices of two numbers summing to target. O(n) time, O(n) space."""
    seen: dict[int, int] = {}
    for i, num in enumerate(nums):
        complement = target - num
        if complement in seen:
            return [seen[complement], i]
        seen[num] = i
    return None
Output4 lines
>>> two_sum([2, 7, 11, 15], 9)
[0, 1]
>>> two_sum([3, 2, 4], 6)
[1, 2]

Heap (kth largest):

python
import heapq

def kth_largest(nums: list[int], k: int) -> int:
    """Kth largest element. O(n log k) time, O(k) space."""
    heap = nums[:k]
    heapq.heapify(heap)          # min-heap of the k largest seen so far
    for num in nums[k:]:
        if num > heap[0]:
            heapq.heapreplace(heap, num)
    return heap[0]
Output4 lines
>>> kth_largest([3, 2, 1, 5, 6, 4], 2)
5
>>> kth_largest([3, 2, 3, 1, 2, 4, 5, 5, 6], 4)
4

BFS on a grid (number of islands):

python
from collections import deque


def num_islands(grid: list[list[str]]) -> int:
    """Count connected '1' regions (4-directional). O(mΒ·n) time, O(mΒ·n) worst-case space.

    Mutates `grid` (visited cells become "0"); copy it first if the caller needs it intact.
    """
    if not grid:
        return 0
    rows, cols = len(grid), len(grid[0])
    islands = 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == "1":
                islands += 1
                # BFS flood-fill this island
                queue = deque([(r, c)])
                grid[r][c] = "0"
                while queue:
                    i, j = queue.popleft()
                    for di, dj in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                        ni, nj = i + di, j + dj
                        if 0 <= ni < rows and 0 <= nj < cols and grid[ni][nj] == "1":
                            grid[ni][nj] = "0"
                            queue.append((ni, nj))
    return islands
Output7 lines
>>> num_islands([
...     ["1","1","1","1","0"],
...     ["1","1","0","1","0"],
...     ["1","1","0","0","0"],
...     ["0","0","0","0","0"],
... ])
1

Simple DP (climbing stairs):

python
def climb_stairs(n: int) -> int:
    """Distinct ways to climb n stairs taking 1 or 2 steps. O(n) time, O(1) space."""
    a, b = 1, 1
    for _ in range(n):
        a, b = b, a + b
    return a
Output4 lines
>>> climb_stairs(2)
2
>>> climb_stairs(5)
8

Backtracking (subsets):

python
def subsets(nums: list[int]) -> list[list[int]]:
    """All subsets (power set). O(2^n) time and space β€” unavoidable for the output."""
    out: list[list[int]] = []

    def backtrack(start: int, path: list[int]) -> None:
        out.append(path.copy())
        for i in range(start, len(nums)):
            path.append(nums[i])
            backtrack(i + 1, path)
            path.pop()

    backtrack(0, [])
    return out
Output2 lines
>>> subsets([1, 2, 3])
[[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]

Intervals (merge intervals):

python
def merge_intervals(intervals: list[list[int]]) -> list[list[int]]:
    """Merge overlapping intervals. O(n log n) time for the sort. Leaves the input untouched."""
    if not intervals:
        return []
    ordered = sorted(intervals, key=lambda x: x[0])
    merged = [list(ordered[0])]  # copy, so extending merged[-1] below never edits the caller's list
    for start, end in ordered[1:]:
        if start <= merged[-1][1]:
            merged[-1][1] = max(merged[-1][1], end)
        else:
            merged.append([start, end])
    return merged
Output2 lines
>>> merge_intervals([[1,3],[2,6],[8,10],[15,18]])
[[1, 6], [8, 10], [15, 18]]

Iterator/generator (flatten nested list):

python
def flatten(nested: list) -> list:
    """Flatten arbitrarily nested lists. Iterative with an explicit stack."""
    out = []
    stack = [nested]
    while stack:
        node = stack.pop()
        if isinstance(node, list):
            stack.extend(reversed(node))
        else:
            out.append(node)
    return out
Output2 lines
>>> flatten([1, [2, [3, 4], 5], 6])
[1, 2, 3, 4, 5, 6]

3.4 Python-specific pitfalls that sink candidates#

These are the bugs that appear in every coding interview and separate "knows Python" from "has been burned by Python":

Pitfall The bug The fix
Mutable default argument def f(x, acc=[]) shares one list across calls def f(x, acc=None): if acc is None: acc = [] (not acc or [], which also replaces an empty list the caller passed in)
Late binding in closures fns = [lambda: i for i in range(3)] all return 2 Bind at definition: lambda i=i: i
Shallow vs deep copy copy.copy shares nested objects; b = a[:] shares them too copy.deepcopy for nested structures
Integer/float surprises 0.1 + 0.2 == 0.3 is False Use math.isclose or Decimal for money
Dictionary ordering Pre-3.7 dicts unordered; now guaranteed insertion order Safe to rely on since 3.7, but don't sort expecting it
is vs == is compares identity, not value == for value equality; is only for None, True, False
String immutability s += ch in a loop can be O(nΒ²) (CPython sometimes optimises it, but you can't rely on that) Use "".join(parts) or a list
range vs xrange Py2 memory issues; Py3 range is lazy Fine in Py3, but know it's a sequence not a list
Recursion limit RecursionError at ~1000 frames Convert to iterative, or sys.setrecursionlimit (rarely the right fix)
global/nonlocal confusion Assigning in nested scope creates a new local Use nonlocal explicitly

3.5 Complexity reasoning: the Big-O vocabulary#

You must be able to state time and space complexity for every solution β€” and defend them. The vocabulary:

Notation Name Example
O(1) Constant Hash map lookup, list index
O(log n) Logarithmic Binary search, balanced BST ops
O(n) Linear Single pass through a list
O(n log n) Linearithmic Sorting (Timsort), heap operations
O(nΒ²) Quadratic Nested loops over the same data
O(2ⁿ) Exponential Subsets, naive recursion without memoisation
O(n!) Factorial Permutations

How to reason about it out loud:

"This is O(n) time because I make one pass through the array and each hash map operation is O(1) average case. Space is O(n) worst case because the hash map could store every element. If space were constrained, I'd consider sorting + two pointers for O(1) space at O(n log n) time β€” the classic time-space trade-off."

3.6 When you can't solve it: the recovery protocol#

Not every problem gets solved in 45 minutes. What you do next is itself scored:

  1. State what you know. "I can see this needs a hash map for the lookup, but I'm stuck on the ordering constraint."
  2. Propose a simpler version. "If I ignore the ordering, it's two-sum. The ordering makes it harder because…"
  3. Ask for a hint β€” specifically. "Would it help to see an example?" or "Is there a constraint I'm missing?" Interviewers give hints; taking them well is a skill.
  4. If truly stuck, say so and move on. "I've spent 15 minutes and I'm not converging. Can we move to the next problem or discuss the approach?" This preserves the rest of the round.
  5. After the interview, write it up. The problem you couldn't solve is the most valuable study item you have β€” add it to your drill rotation.

Part 4: LLM-flavoured coding drills β€” the career_kit/drills package#

Deep-dive

4.0 Why these drills and how to use them#

Traditional coding interviews test algorithms. AI-engineer interviews increasingly test small systems problems that look like the work you'll actually do: rate limiting API calls, parsing streams, chunking documents, scoring retrieval, validating model output, running a tool loop under a budget. These are the drills β€” seventeen self-contained modules, each pure Python 3.11+ standard library, each with a demo you can run and a pytest suite.

How to use them:

  1. Read the problem statement first β€” each subsection poses it as an interviewer would.
  2. Write your own solution before looking β€” time-box 30 minutes. The drill's value is in the gap between your attempt and the reference.
  3. Run run_all.py to see real output, then run the tests (uv run pytest career_kit/drills/test_drills.py) to see what's asserted.
  4. Answer the extension questions out loud β€” that's what the interviewer will do next.

The package layout:

text
career_kit/drills/
β”œβ”€β”€ __init__.py
β”œβ”€β”€ rate_limit.py        # 4.1 token-bucket rate limiter
β”œβ”€β”€ bounded.py           # 4.2 async bounded-concurrency runner
β”œβ”€β”€ retry.py             # 4.3 retry with backoff + jitter
β”œβ”€β”€ sse_parse.py         # 4.4 streaming SSE parser
β”œβ”€β”€ chunker.py           # 4.5 sentence-aware chunker with overlap
β”œβ”€β”€ vectors.py           # 4.6 cosine top-k search
β”œβ”€β”€ bm25.py              # 4.7 BM25 from scratch
β”œβ”€β”€ fusion.py            # 4.8 reciprocal rank fusion
β”œβ”€β”€ templates.py         # 4.9 prompt template renderer
β”œβ”€β”€ json_repair.py       # 4.10 JSON repair/validation with retries
β”œβ”€β”€ tool_loop.py         # 4.11 tool-call loop with budgets
β”œβ”€β”€ metrics.py           # 4.12 retrieval metrics (recall@k, MRR, nDCG)
β”œβ”€β”€ lru.py               # 4.13 LRU cache with TTL + single-flight
β”œβ”€β”€ budget.py            # 4.14 token-counting budget packer
β”œβ”€β”€ eval_diff.py         # 4.15 diffing two eval runs
β”œβ”€β”€ bpe.py               # 4.16 mini BPE tokenizer
β”œβ”€β”€ attention.py         # 4.17 softmax + scaled dot-product attention
β”œβ”€β”€ run_all.py           # executes every demo, fixed seed
└── test_drills.py       # pytest suite (44 tests)

4.1 Token-bucket rate limiter#

Problem: "Implement a rate limiter allowing capacity immediate requests, refilling at refill_per_second. It must never exceed the bucket and must tell callers how long to wait."

python
# career_kit/drills/rate_limit.py
"""rate_limit.py β€” a token-bucket rate limiter.

Interview framing: "Design a rate limiter that allows `capacity` requests
immediately, then refills at `refill_per_second`. It must be thread-safe
conceptually and must never grant more than the bucket holds."

The clock is injected so tests and demos are deterministic β€” no sleeps.
"""

from __future__ import annotations


class TokenBucket:
    """Token bucket: starts full, refills continuously, spends 1 token/call."""

    def __init__(self, capacity: int, refill_per_second: float) -> None:
        if capacity <= 0:
            raise ValueError("capacity must be positive")
        if refill_per_second <= 0:
            raise ValueError("refill_per_second must be positive")
        self.capacity = capacity
        self.refill_per_second = refill_per_second
        self._tokens = float(capacity)
        self._last = 0.0  # caller supplies `now`; 0.0 is a fine epoch for demos

    def _refill(self, now: float) -> None:
        elapsed = max(0.0, now - self._last)
        self._tokens = min(self.capacity, self._tokens + elapsed * self.refill_per_second)
        self._last = now

    def allow(self, now: float = 0.0) -> bool:
        """True if a token was available (and consumed); False otherwise."""
        self._refill(now)
        if self._tokens >= 1.0:
            self._tokens -= 1.0
            return True
        return False

    def time_until_next(self, now: float = 0.0) -> float:
        """Seconds until one token is available (0.0 if one is ready now)."""
        self._refill(now)
        if self._tokens >= 1.0:
            return 0.0
        return (1.0 - self._tokens) / self.refill_per_second


def demo() -> None:
    bucket = TokenBucket(capacity=4, refill_per_second=2.0)
    requests = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.9, 1.4, 2.0, 3.0]
    print("time  allow?  wait_next")
    for t in requests:
        ok = bucket.allow(now=t)
        print(f"{t:4.1f}  {str(ok):5}  {bucket.time_until_next(now=t):6.2f}")

Complexity: O(1) per call β€” the refill is lazy (computed on access, not on a timer). Space O(1).

Tests: test_token_bucket_allows_burst_then_refills, test_token_bucket_caps_at_capacity.

Extension questions:

  • How do you make it thread-safe? (A threading.Lock around _refill/allow β€” the check-and-spend must be atomic.)
  • How do you do per-user rate limits? (A dict of buckets keyed by user ID, with eviction β€” that's where the LRU cache in 4.13 becomes relevant.)
  • Token bucket vs leaky bucket vs fixed window β€” when does each win? (Token bucket allows bursts; leaky bucket smooths; fixed window is simplest but has boundary bursts. Provider rate limits are usually token-bucket-shaped β€” see 03.8 for how API rate limits actually behave.)

4.2 Async bounded-concurrency runner#

Problem: "You have N items to process concurrently (fetch URLs, call an API). Run at most limit at once, preserve input order in results, don't let one failure kill the batch."

python
# career_kit/drills/bounded.py
"""bounded.py β€” run async work with bounded concurrency.

Interview framing: "You have 1,000 URLs to fetch. Fetching all at once
melts the server and the socket pool; fetching one at a time is too slow.
Run them with at most `limit` in flight, preserve result order, and let one
failure not kill the batch."

`asyncio` is the standard answer; the semaphore is the whole trick. Results
keep input order because `asyncio.gather` does β€” we never rely on
completion order.
"""

from __future__ import annotations

import asyncio
from typing import Awaitable, Callable, TypeVar

T = TypeVar("T")


async def run_bounded(
    items: list[T],
    worker: Callable[[T], Awaitable[object]],
    *,
    limit: int = 8,
    return_exceptions: bool = False,
) -> list[object]:
    """Run `worker(item)` for each item with at most `limit` in flight.

    Returns results in input order. By default the first exception propagates
    to the caller (the other tasks keep running). With
    `return_exceptions=True` a failed item's slot holds its exception instead,
    so one failure never kills the batch.
    """
    sem = asyncio.Semaphore(limit)

    async def guarded(item: T) -> object:
        async with sem:
            return await worker(item)

    return list(await asyncio.gather(*(guarded(i) for i in items), return_exceptions=return_exceptions))


# --- demo -----------------------------------------------------------------

async def _demo_worker(item: int) -> dict[str, object]:
    """Pretend to be an HTTP fetch: a deterministic 'latency' sleep."""
    await asyncio.sleep(0.01 * ((item * 7) % 5 + 1))
    return {"id": item, "status": 200 if item % 11 else 500}


async def demo_async() -> None:
    items = list(range(20))
    results = await run_bounded(items, _demo_worker, limit=4)
    ok = sum(1 for r in results if isinstance(r, dict) and r["status"] == 200)
    print(f"items={len(items)} limit=4 ok={ok} sample={results[:3]}")


def demo() -> None:
    asyncio.run(demo_async())

Complexity: O(n) total work, O(limit) memory for in-flight tasks, O(n) for results.

Tests: test_run_bounded_preserves_order_and_limits.

Extension questions:

  • What happens if the worker raises? (With the default gather, the first exception propagates to the caller at once, but the sibling tasks are not cancelled β€” they keep running in the background, which is a classic leak. For per-item resilience pass return_exceptions=True (each failed item's slot then holds its exception, which you must check for) or wrap the worker to return an error sentinel; for "one failure cancels everything" use asyncio.TaskGroup (Python 3.11+).)
  • How do you add a timeout per item? (asyncio.wait_for inside the worker.)
  • How does this relate to LLM API calls? (03.9 covers async/batch patterns; the semaphore pattern is the same one used to bound provider concurrency.)

4.3 Retry with exponential backoff and jitter#

Problem: "Implement retry for a flaky dependency. Retry only retryable errors, back off exponentially, add jitter, cap attempts and total wait."

python
# career_kit/drills/retry.py
"""retry.py β€” retry with exponential backoff and jitter.

Interview framing: "Implement retry for a flaky dependency. Requirements:
retry only retryable errors, back off exponentially, add jitter so many
clients don't retry in lock-step, cap the attempts and the total wait."

`sleep` is injected so the demo never actually waits.
"""

from __future__ import annotations

import random
import time
from typing import Callable, TypeVar

T = TypeVar("T")


class RetryableError(Exception):
    """Marker for errors worth retrying (timeouts, 429/5xx, connection resets)."""


def retry_with_backoff(
    fn: Callable[[], T],
    *,
    max_attempts: int = 5,
    base_delay: float = 0.5,
    max_delay: float = 30.0,
    jitter: float = 0.5,
    retryable: tuple[type[BaseException], ...] = (RetryableError,),
    sleep: Callable[[float], None] = time.sleep,
    rng: random.Random | None = None,
) -> T:
    """Call `fn` until it succeeds or attempts run out.

    After failed attempt n (counting from 0) the sleep is
    `cap * uniform(1 - jitter, 1 + jitter)` where
    `cap = min(max_delay, base_delay * 2**n)`. This is 'equal-ish' jitter
    around the capped delay. AWS-style 'full jitter' is `uniform(0, cap)`,
    which this function does not implement: `jitter=1.0` here gives
    `uniform(0, 2 * cap)`, with the same mean as no jitter.
    """
    if max_attempts < 1:
        raise ValueError("max_attempts must be at least 1")
    if rng is None:
        rng = random.Random()
    last_exc: BaseException | None = None
    for attempt in range(max_attempts):
        try:
            return fn()
        except retryable as exc:  # noqa: BLE001 - only the configured types retry
            last_exc = exc
            if attempt == max_attempts - 1:
                break
            cap = min(max_delay, base_delay * 2**attempt)
            delay = cap * (1.0 - jitter + 2.0 * jitter * rng.random())
            sleep(delay)
    assert last_exc is not None
    raise last_exc


def demo() -> None:
    calls = {"n": 0}

    def flaky() -> str:
        calls["n"] += 1
        if calls["n"] < 4:
            raise RetryableError(f"transient failure #{calls['n']}")
        return "ok"

    waits: list[float] = []
    result = retry_with_backoff(
        flaky,
        max_attempts=5,
        base_delay=0.5,
        max_delay=8.0,
        jitter=0.4,
        sleep=waits.append,
        rng=random.Random(7),
    )
    print(f"result={result!r} attempts={calls['n']} waits={[round(w, 3) for w in waits]}")

Complexity: O(max_attempts) calls, O(1) space. There are at most max_attempts βˆ’ 1 sleeps, so total wait is bounded by (max_attempts βˆ’ 1) Γ— max_delay Γ— (1 + jitter) (jitter can push one sleep above max_delay).

Tests: test_retry_succeeds_after_failures, test_retry_gives_up_and_raises_last, test_retry_does_not_retry_other_errors, test_retry_rejects_zero_attempts.

Extension questions:

  • How would you implement AWS-style full jitter and enforce a hard ceiling on total elapsed time? (Use delay = rng.uniform(0, cap), and track a deadline with a monotonic clock: stop retrying if now + delay would pass it. Whether jitter should be full or partial is a trade-off between spreading load and keeping a minimum back-off.)
  • Why jitter? (Without it, thousands of clients retry in lock-step and re-create the thundering herd that caused the failure. Jitter decorrelates them.)
  • When do you not retry? (Non-idempotent operations, 4xx errors that won't change, when the cost of a duplicate exceeds the benefit.)
  • How does this relate to LLM APIs? (03.8 and 01B.9 own the full treatment; this is the interview-sized version.)

4.4 Streaming SSE parser#

Problem: "The provider streams Server-Sent Events. Parse the byte stream into events, accumulate the assistant's text, and know when it's finished. Handle events split across TCP chunks."

python
# career_kit/drills/sse_parse.py
"""sse_parse.py β€” turn a streaming SSE response into typed events.

Interview framing: "The provider streams Server-Sent Events. Parse the byte
stream into events, then accumulate the assistant's text and know when the
stream is finished. Handle events split across TCP chunks."

This is a deliberately small parser β€” the spec-faithful one lives in
lesson 03.3, Part 2 (docs/source/03-llm-apis/03-streaming.md) as `SSEParser`.
Ours yields `(event_name, data_str)` pairs and stops at `[DONE]`.
"""

from __future__ import annotations

import json
from dataclasses import dataclass, field
from typing import Iterator


@dataclass
class StreamEvent:
    """One SSE event: a name and the joined `data:` payload."""

    event: str
    data: str


def iter_sse_events(chunks: list[bytes]) -> Iterator[StreamEvent]:
    r"""Feed raw byte chunks; yield each complete SSE event.

    Handles \n, \r\n and \r line endings, `event:`/`data:` fields, comments
    (keep-alives starting with ':'), multi-line data, and events split across
    chunk boundaries. A trailing event without a blank line is dropped, per
    the WHATWG spec.
    """
    buf = ""
    event_name = "message"
    data_lines: list[str] = []

    def dispatch() -> StreamEvent | None:
        nonlocal event_name, data_lines
        if not data_lines:
            event_name, data_lines = "message", []
            return None
        ev = StreamEvent(event=event_name, data="\n".join(data_lines))
        event_name, data_lines = "message", []
        return ev

    for chunk in chunks:
        buf += chunk.decode("utf-8", errors="replace")
        while "\n" in buf or "\r" in buf:
            # find earliest line break
            i_nl, i_cr = buf.find("\n"), buf.find("\r")
            candidates = [i for i in (i_nl, i_cr) if i != -1]
            if not candidates:
                break
            i = min(candidates)
            # a lone \r at buffer end might be half of \r\n β€” wait for more
            if buf[i] == "\r" and i == len(buf) - 1:
                break
            line = buf[:i]
            step = 2 if buf.startswith("\r\n", i) else 1
            buf = buf[i + step:]
            if line == "":
                ev = dispatch()
                if ev is not None:
                    yield ev
            elif line.startswith(":"):
                continue  # comment / keep-alive
            else:
                field_name, _, value = line.partition(":")
                if value.startswith(" "):
                    value = value[1:]
                if field_name == "event":
                    event_name = value
                elif field_name == "data":
                    data_lines.append(value)
    # leftover partial line at EOF is discarded (spec behaviour)


@dataclass
class ChatDelta:
    """Accumulated view of an OpenAI-style chat.completion.chunk stream."""

    text: str = ""
    finish_reason: str | None = None
    usage: dict | None = None
    raw_events: int = 0
    extras: dict = field(default_factory=dict)


def accumulate_chat_stream(chunks: list[bytes]) -> ChatDelta:
    """Parse an SSE stream of `chat.completion.chunk` JSON into one message.

    This mirrors what the SDKs' stream helpers do internally: concatenate
    `choices[0].delta.content`, keep the last `finish_reason`, and pick up
    `usage` when the provider sends a final usage-only chunk.
    """
    out = ChatDelta()
    for ev in iter_sse_events(chunks):
        if ev.data.strip() == "[DONE]":
            break
        payload = json.loads(ev.data)
        out.raw_events += 1
        if payload.get("usage"):
            out.usage = payload["usage"]
        for choice in payload.get("choices", []):
            delta = choice.get("delta", {})
            if isinstance(delta.get("content"), str):
                out.text += delta["content"]
            if choice.get("finish_reason"):
                out.finish_reason = choice["finish_reason"]
    return out


def demo() -> None:
    # A synthetic OpenAI-style chat.completion.chunk stream, split mid-JSON
    # on purpose β€” real TCP delivers arbitrary byte boundaries.
    events = [
        'data: {"id":"chatcmpl-x","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]}\n\n',
        'data: {"id":"chatcmpl-x","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"Hello"},"finish_reason":null}]}\n\n',
        'data: {"id":"chatcmpl-x","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":", wor"},"finish_reason":null}]}\n\n',
        'data: {"id":"chatcmpl-x","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"ld!"},"finish_reason":null}]}\n\n',
        'data: {"id":"chatcmpl-x","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":9,"completion_tokens":3,"total_tokens":12}}\n\n',
        "data: [DONE]\n\n",
    ]
    wire = "".join(events).encode("utf-8")
    # split at awkward byte offsets, including inside a UTF-8-safe ASCII stream
    chunks = [wire[:37], wire[37:91], wire[91:200], wire[200:]]
    result = accumulate_chat_stream(chunks)
    print(f"events={result.raw_events} text={result.text!r}")
    print(f"finish_reason={result.finish_reason} usage={result.usage}")

Complexity: O(bytes) time, O(event size) space β€” bounded by the largest single event.

Tests: test_sse_events_split_across_chunks, test_sse_comments_and_done, test_accumulate_chat_stream.

Extension questions:

  • What if a multi-byte UTF-8 character is split across chunks? (The incremental decoder in 03.3's parser handles this; this drill uses errors="replace" for simplicity β€” know the difference.)
  • How do you handle provider-specific event types? (OpenAI Responses uses semantic events like response.output_text.delta; Anthropic uses content_block_delta; the parser is generic, the accumulator is provider-specific β€” see 03.3, Part 3.)
  • What does [DONE] mean vs a stream that just ends? (03.3, 2.3 covers the per-provider end-of-stream conventions.)

4.5 Text chunker with sentence-boundary overlap#

Problem: "Split a document into chunks for embeddings/RAG. Never split mid-sentence when avoidable, respect a max size, carry overlap characters of trailing context so a fact split across a boundary is still fully present."

python
# career_kit/drills/chunker.py
"""chunker.py β€” chunk text on sentence boundaries with overlap.

Interview framing: "Split a document into chunks for embeddings/RAG. Rules:
never split mid-sentence when avoidable, respect a max size, carry
`overlap` characters of trailing context into the next chunk so a fact split
across a boundary is still fully present in one chunk."

Depth lives in lesson 05.6 (docs/source/05-data-engineering-for-ai/06-chunking-strategies.md);
this is the interview-sized version: sentence-aware, character-budgeted,
deterministic.
"""

from __future__ import annotations

import re

_SENTENCE_END = re.compile(r"(?<=[.!?])\s+")


def split_sentences(text: str) -> list[str]:
    """Split on whitespace that follows sentence-ending punctuation.

    Abbreviations ("Dr.", "e.g.") will occasionally split wrongly β€” the real
    lesson (05.6, Part 5) covers boundary rules for that. For an interview
    this heuristic is the right first answer, stated honestly.
    """
    parts = [p.strip() for p in _SENTENCE_END.split(text.strip()) if p.strip()]
    return parts


def chunk_text(text: str, max_chars: int = 400, overlap_chars: int = 80) -> list[str]:
    """Greedy sentence packing into chunks of at most `max_chars`.

    A sentence longer than `max_chars` is hard-split on whitespace so no
    chunk ever exceeds the budget. Overlap is best-effort: each new chunk
    starts with trailing whole sentences of the previous chunk (up to
    `overlap_chars`), but the budget always wins β€” if the seed plus the next
    sentence would overflow, the seed is dropped and the chunk starts clean.
    """
    if max_chars <= 0:
        raise ValueError("max_chars must be positive")
    if overlap_chars < 0 or overlap_chars >= max_chars:
        raise ValueError("overlap_chars must be in [0, max_chars)")

    def emit() -> list[str]:
        """Return the overlap seed (trailing sentences) for the next chunk."""
        kept: list[str] = []
        kept_len = 0
        for s in reversed(current):
            if kept_len + len(s) + 1 <= overlap_chars:
                kept.insert(0, s)
                kept_len += len(s) + 1
            else:
                break
        return kept

    sentences = split_sentences(text)
    chunks: list[str] = []
    current: list[str] = []
    current_len = 0

    for sent in sentences:
        # hard-split oversized sentences on word boundaries
        pieces = [sent]
        while len(pieces[-1]) > max_chars:
            head = pieces.pop()
            cut = head.rfind(" ", 0, max_chars)
            cut = cut if cut > 0 else max_chars
            pieces.extend([head[:cut].strip(), head[cut:].strip()])
        for piece in pieces:
            cost = len(piece) + (1 if current else 0)
            if current and current_len + cost > max_chars:
                chunks.append(" ".join(current))
                current = emit()
                current_len = sum(len(s) for s in current) + max(0, len(current) - 1)
                cost = len(piece) + (1 if current else 0)
                if current and current_len + cost > max_chars:
                    current, current_len = [], 0
                    cost = len(piece)
            current.append(piece)
            current_len += cost
    if current:
        chunks.append(" ".join(current))
    return chunks


def demo() -> None:
    text = (
        "Refunds are issued within 5 business days of approval. "
        "You must return the item in its original packaging. "
        "Final-sale items are not eligible for a refund. "
        "Gift cards never expire and cannot be exchanged for cash. "
        "To start a return, open the order page and choose Return item. "
        "Damaged-on-arrival claims need photos within 48 hours."
    )
    for i, c in enumerate(chunk_text(text, max_chars=140, overlap_chars=60), 1):
        print(f"--- chunk {i} ({len(c)} chars) ---")
        print(c)

Complexity: O(n) where n = text length, plus O(sΒ²) worst case for sentence counting β€” fine for documents.

Tests: test_chunk_text_respects_max_and_overlap, test_chunk_text_no_sentence_split.

Extension questions:

  • Why sentence boundaries and not fixed-size? (Fixed-size splits can cut a fact in half β€” "the refund window is 30" | "days" β€” and the embedding loses meaning. Sentence-aware chunking preserves semantic units. 05.6 covers the full strategy space.)
  • What about documents without sentences (JSON, code, tables)? (Different chunkers β€” structure-aware, fixed-size with overlap, or semantic. The interview answer is "it depends on the document type", not one-size-fits-all.)
  • How do you choose max_chars vs max_tokens? (Tokens are the real constraint for embeddings β€” max_chars is a proxy. In production you'd count tokens with the embedding model's tokenizer. See 05.6, 2.1.)

Problem: "Given a query vector and document vectors, find the k most similar. Then tell me how you'd do it at scale."

python
# career_kit/drills/vectors.py
"""vectors.py β€” cosine similarity and top-k search, pure Python.

Interview framing: "Given query and document embeddings as lists of floats,
find the k most similar documents. Then tell me how you'd do it at
1M docs Γ— 768 dimensions β€” answer: you wouldn't brute-force it, you'd use an index (lesson 06.4);
but the math is the same dot product everywhere."

`numpy` version is described in the lesson, not required here β€” this file is
stdlib-only so it runs anywhere.
"""

from __future__ import annotations

import math


def dot(a: list[float], b: list[float]) -> float:
    if len(a) != len(b):
        raise ValueError("vectors must have equal length")
    return sum(x * y for x, y in zip(a, b))


def norm(v: list[float]) -> float:
    return math.sqrt(dot(v, v))


def cosine_similarity(a: list[float], b: list[float]) -> float:
    na, nb = norm(a), norm(b)
    if na == 0.0 or nb == 0.0:
        return 0.0  # zero vector has no direction; define similarity as 0
    return dot(a, b) / (na * nb)


def top_k(
    query: list[float],
    docs: list[tuple[str, list[float]]],
    k: int = 3,
) -> list[tuple[str, float]]:
    """Return the k (doc_id, score) pairs with highest cosine similarity."""
    scored = [(doc_id, cosine_similarity(query, vec)) for doc_id, vec in docs]
    scored.sort(key=lambda x: x[1], reverse=True)
    return scored[:k]


def demo() -> None:
    docs = [
        ("refund-policy", [0.9, 0.1, 0.0]),
        ("shipping-times", [0.0, 0.8, 0.2]),
        ("password-reset", [0.1, 0.0, 0.9]),
        ("damaged-goods", [0.7, 0.3, 0.1]),
    ]
    query = [0.8, 0.2, 0.0]
    for doc_id, score in top_k(query, docs, k=3):
        print(f"{doc_id:16} {score:.4f}")

Complexity: O(dΒ·n) where d = dimensions, n = docs β€” brute force. For 1M docs Γ— 768 dims that's ~768M multiply-adds per query β€” fine for a demo, far too slow in pure Python for interactive latency, and wasteful even with numpy when an index exists.

The scale answer: at scale you don't brute-force β€” you use an approximate nearest-neighbour index (HNSW, IVF, PQ) that trades a little recall for orders-of-magnitude speed. 06.4 owns index internals; 06.3 owns the similarity metrics.

Tests: test_cosine_identical_is_one, test_cosine_orthogonal_is_zero, test_top_k_orders_by_similarity.

Extension questions:

  • Why cosine and not Euclidean distance? (Cosine measures direction, ignoring magnitude β€” two documents about "refunds" should be similar even if one is twice as long. Embedding models are trained so direction carries meaning.)
  • How do you handle the "curse of dimensionality"? (Approximate indexes, dimensionality reduction, or hybrid search with BM25 β€” 06.8.)
  • What's the numpy version? (scores = (doc_matrix @ query) / (norms * q_norm) β€” one matrix multiply instead of a Python loop. Described here, not required.)

4.7 BM25 scoring from scratch#

Problem: "Implement BM25 so I can rank documents for a query. Explain term-frequency saturation and length normalisation. What are k1 and b?"

python
# career_kit/drills/bm25.py
"""bm25.py β€” Okapi BM25 keyword scoring from scratch.

Interview framing: "Implement BM25 so I can rank documents for a query.
Explain tf saturation and length normalisation. What are k1 and b?"

The canonical implementation lives in lesson 06.7, Part 3
(docs/source/06-embeddings-vector-search/07-keyword-search-and-bm25.md);
this is the compact interview version β€” same formula, Robertson+1 IDF.
"""

from __future__ import annotations

import math
import re
from collections import defaultdict

TOKEN_RE = re.compile(r"[a-z0-9]+")


def tokenize(text: str) -> list[str]:
    return TOKEN_RE.findall(text.lower())


class BM25:
    """Okapi BM25 with Robertson+1 IDF (Lucene/Elasticsearch variant)."""

    def __init__(
        self,
        docs_tokens: list[list[str]],
        k1: float = 1.2,
        b: float = 0.75,
    ) -> None:
        self.k1, self.b = k1, b
        self.N = len(docs_tokens)
        self.postings: dict[str, dict[int, int]] = defaultdict(lambda: defaultdict(int))
        self.doc_len: list[int] = []
        for i, toks in enumerate(docs_tokens):
            self.doc_len.append(len(toks))
            for t in toks:
                self.postings[t][i] += 1
        self.avgdl = sum(self.doc_len) / self.N
        self.df = {t: len(d) for t, d in self.postings.items()}

    def idf(self, term: str) -> float:
        n = self.df.get(term, 0)
        if n == 0:
            return 0.0
        return math.log(1 + (self.N - n + 0.5) / (n + 0.5))

    def score(self, query: str, doc_id: int) -> float:
        total = 0.0
        for term in set(tokenize(query)):
            tf = self.postings.get(term, {}).get(doc_id, 0)
            if tf == 0:
                continue
            norm = 1 - self.b + self.b * self.doc_len[doc_id] / self.avgdl
            total += self.idf(term) * (tf * (self.k1 + 1)) / (tf + self.k1 * norm)
        return total

    def search(self, query: str, k: int = 10) -> list[tuple[float, int]]:
        scored = sorted(
            ((self.score(query, i), i) for i in range(self.N)),
            key=lambda x: -x[0],
        )
        return [(s, i) for s, i in scored if s > 0][:k]


def demo() -> None:
    docs = [
        "damaged refund policy proof of purchase receipt",
        "package arrived damaged, request a refund",
        "shipping times and delivery estimates",
        "damaged goods and shipping delay complaint refund",
        "password reset link expires in fifteen minutes",
    ]
    bm = BM25([tokenize(d) for d in docs])
    print("query: 'damaged refund'")
    for score, i in bm.search("damaged refund"):
        print(f"  doc{i + 1} score={score:.4f}  {docs[i][:50]}")

Complexity: Build O(total tokens); query O(query_terms Γ— N) naive, or O(query_terms) with an inverted index (which postings already is β€” the search loop over all docs is the naive part; production BM25 uses the postings directly).

Tests: test_bm25_ranks_relevant_first, test_bm25_unknown_term_scores_zero.

Extension questions:

  • What do k1 and b control? (k1 = term-frequency saturation β€” how much a term said 5Γ— beats said 1Γ—; b = length normalisation strength β€” how much long docs are penalised. Defaults 1.2/0.75 from Robertson & Zaragoza.)
  • Why IDF? (Rare terms are more informative. In the demo corpus "refund" and "damaged" each appear in 3 of 5 documents, so neither discriminates strongly; a term found in only one document, such as "password", gets a much higher IDF and dominates the score for queries that contain it.)
  • How does this relate to dense retrieval? (BM25 is lexical β€” exact term matching; dense is semantic β€” meaning matching. They're complementary; 06.8 fuses them.)

4.8 Reciprocal rank fusion#

Problem: "Dense and BM25 retrievers return incomparable scores. Merge their ranked lists into one. Why ranks and not scores?"

python
# career_kit/drills/fusion.py
"""fusion.py β€” reciprocal rank fusion (RRF) for hybrid search.

Interview framing: "Dense and BM25 retrievers return incomparable scores.
Merge their ranked lists into one. Why ranks and not scores?"

RRF needs no score normalisation β€” each list contributes 1/(k + rank).
The canonical treatment is lesson 06.8, Part 2
(docs/source/06-embeddings-vector-search/08-hybrid-search.md).
"""

from __future__ import annotations

RankedList = list[tuple[str, float]]  # (doc_id, score), best first


def rrf(rankings: list[RankedList], k: float = 60.0) -> list[tuple[str, float]]:
    """Reciprocal Rank Fusion: sum 1/(k + rank) across every ranking.

    A doc absent from a list contributes nothing from that list β€” no
    normalisation needed, which is why RRF is the standard default when you
    have no labelled set to tune score weights on.
    """
    scores: dict[str, float] = {}
    for ranking in rankings:
        for rank, (doc_id, _) in enumerate(ranking, start=1):
            scores[doc_id] = scores.get(doc_id, 0.0) + 1.0 / (k + rank)
    fused = sorted(scores.items(), key=lambda x: x[1], reverse=True)
    return fused


def demo() -> None:
    dense = [("a", 0.91), ("b", 0.88), ("c", 0.70), ("d", 0.40)]
    lexical = [("c", 12.5), ("a", 9.1), ("e", 7.0), ("b", 3.3)]
    print("dense top:", [d for d, _ in dense])
    print("bm25  top:", [d for d, _ in lexical])
    print("fused    :", [(d, round(s, 4)) for d, s in rrf([dense, lexical])])

Complexity: O(total ranked items) β€” trivially fast.

Tests: test_rrf_consensus_doc_wins, test_rrf_single_ranking_preserves_order.

Extension questions:

  • Why k=60? (The 2009 RRF paper by Cormack, Clarke and BΓΌttcher, SIGIR '09, says "k = 60 was fixed during a pilot investigation and not altered during subsequent validation", and that its pilot experiments showed 60 "was near-optimal, but that the choice was not critical" (paper read 9 November 2026). Lower k = more top-heavy; higher k = more consensus-weighted. 06.8, 2.2 covers the theory and per-engine defaults.)
  • What if scores matter, not just ranks? (Score fusion with min-max or z-score normalisation β€” 06.8, 2.3. RRF is the no-eval-set default; score fusion needs tuning.)
  • What about weighted RRF? (Multiply each retriever's contribution by a trust weight β€” the standard way to say "dense is better for conceptual queries, BM25 for exact-match".)

4.9 Prompt template renderer with validation#

Problem: "Render a prompt from a template with {{placeholders}}, validate that every required variable is present and no unknown variables sneak in, fail loudly rather than shipping a half-rendered prompt."

python
# career_kit/drills/templates.py
"""templates.py β€” a prompt template renderer with validation.

Interview framing: "Render a prompt from a template with {{placeholders}},
validate that every required variable is present and that no unknown
variables sneak in, and fail loudly rather than shipping a half-rendered
prompt to a model."

This is the *interview-sized* version of what 04.10 teaches as versioned
template libraries β€” same idea, minus the file loading and changelog.
"""

from __future__ import annotations

import re
from dataclasses import dataclass, field

_VAR = re.compile(r"\{\{\s*(\w+)\s*\}\}")


class TemplateError(ValueError):
    pass


@dataclass
class PromptTemplate:
    name: str
    text: str
    required: frozenset[str] = field(default_factory=frozenset)

    @classmethod
    def from_text(cls, name: str, text: str, required: list[str] | None = None) -> "PromptTemplate":
        return cls(name=name, text=text, required=frozenset(required or []))

    @property
    def variables(self) -> set[str]:
        return set(_VAR.findall(self.text))

    def render(self, context: dict[str, str]) -> str:
        """Render, or raise TemplateError listing every problem at once."""
        problems: list[str] = []
        missing = self.variables - set(context)
        extra = set(context) - self.variables
        if missing:
            problems.append(f"missing variables: {sorted(missing)}")
        if extra:
            problems.append(f"unused context keys: {sorted(extra)}")
        absent_required = self.required - set(context)
        if absent_required:
            problems.append(f"required but absent: {sorted(absent_required)}")
        if problems:
            raise TemplateError("; ".join(problems))
        return _VAR.sub(lambda m: str(context[m.group(1)]), self.text)


def demo() -> None:
    tpl = PromptTemplate.from_text(
        "support-reply",
        "You are a support agent for {{company}}.\n"
        "Customer wrote: {{ticket}}\n"
        "Answer in {{tone}} tone, under {{max_words}} words.",
        required=["company", "ticket", "tone", "max_words"],
    )
    print(tpl.render({
        "company": "Acme",
        "ticket": "Where is my order #4471?",
        "tone": "calm",
        "max_words": "80",
    }))
    print("---")
    try:
        tpl.render({"company": "Acme", "tone": "calm"})
    except TemplateError as e:
        print("TemplateError:", e)

Complexity: O(template length + context size).

Tests: test_template_render_ok, test_template_missing_raises, test_template_extra_key_raises.

Extension questions:

  • Why validate before rendering? (A missing variable silently produces "Answer in words." β€” a prompt that looks fine but confuses the model. Failing loudly is cheaper than debugging a bad output.)
  • How does this relate to prompt versioning? (04.10 owns template libraries, versioning and changelogs; this is the rendering primitive.)
  • What about escaping/encoding? (This renderer substitutes in a single regex pass over the template, so a user value containing {{secret}} is inserted literally and is never re-expanded. A multi-pass engine, or one that evaluates expressions, would not be safe like that, so say which kind you are building. The bigger risk is not template syntax but user text carrying instructions: delimit untrusted values and treat them as data. 04.4 covers injection-aware structuring.)

4.10 JSON repair/validation of model output with retries#

Problem: "The model returned JSON wrapped in prose and maybe a markdown fence. Get me a validated object, retrying with feedback when it fails β€” but never 'repair' a truncated answer by guessing."

python
# career_kit/drills/json_repair.py
"""json_repair.py β€” extract, validate and retry model JSON output.

Interview framing: "The model returned JSON wrapped in prose and maybe a
markdown fence. Get me a validated object, retrying with feedback when it
fails β€” but never 'repair' a truncated answer by guessing."

Depth: lesson 03.4 (docs/source/03-llm-apis/04-structured-output.md) owns the
provider ladder (prompt β†’ JSON mode β†’ schema-constrained β†’ strict tools).
This drill is the rung-1/2 reality: parse, validate, retry.
"""

from __future__ import annotations

import json
import re
from typing import Any, Callable

_FENCE = re.compile(r"```(?:json)?\s*(.*?)```", re.DOTALL)


def _balanced_spans(text: str) -> list[tuple[int, int]]:
    """Every balanced {...} or [...] span as (start, end) offsets.

    The scanner tracks only the *same-type* bracket depth and skips quoted
    strings, so `{"a": [1, {"b": 2}]}` yields its outer span correctly. A
    `{` inside a `[...]` span is still reported β€” callers try candidates in
    position order and let `json.loads` decide.
    """
    spans: list[tuple[int, int]] = []
    for opener, closer in (("{", "}"), ("[", "]")):
        start = text.find(opener)
        while start != -1:
            depth = 0
            in_str = False
            esc = False
            end = -1
            for i in range(start, len(text)):
                c = text[i]
                if in_str:
                    if esc:
                        esc = False
                    elif c == "\\":
                        esc = True
                    elif c == '"':
                        in_str = False
                elif c == '"':
                    in_str = True
                elif c == opener:
                    depth += 1
                elif c == closer:
                    depth -= 1
                    if depth == 0:
                        end = i
                        break
            if end != -1:
                spans.append((start, end))
            start = text.find(opener, start + 1)
    return sorted(spans)


def extract_json(text: str) -> Any:
    """Pull the first parseable JSON value out of model text.

    Order: whole text β†’ fenced block β†’ balanced {...} or [...] candidates in
    position order, first one that `json.loads` accepts. Raises ValueError
    when nothing parses β€” callers decide whether to retry.
    """
    text = text.strip()
    try:
        return json.loads(text)
    except json.JSONDecodeError:
        pass
    fence = _FENCE.search(text)
    if fence:
        try:
            return json.loads(fence.group(1).strip())
        except json.JSONDecodeError:
            pass
    for start, end in _balanced_spans(text):
        try:
            return json.loads(text[start : end + 1])
        except json.JSONDecodeError:
            continue
    raise ValueError("no parseable JSON found")


def validate(obj: Any, schema: dict[str, type]) -> list[str]:
    """Tiny validator: schema maps required key β†’ expected type."""
    errors = []
    if not isinstance(obj, dict):
        return [f"expected object, got {type(obj).__name__}"]
    for key, typ in schema.items():
        if key not in obj:
            errors.append(f"missing key {key!r}")
        elif not isinstance(obj[key], typ):
            errors.append(f"{key!r} should be {typ.__name__}, got {type(obj[key]).__name__}")
    return errors


def call_with_repair(
    model_call: Callable[[str], str],
    prompt: str,
    schema: dict[str, type],
    *,
    max_retries: int = 2,
) -> Any:
    """Call the model, extract+validate JSON, feed errors back on retry.

    `model_call(prompt) -> raw text` is injected, so this works with any
    provider β€” or a scripted fake in tests. Truncated output is NOT repaired:
    it fails validation/extraction and the retry asks for the complete JSON.
    """
    messages = [prompt]
    last_errors: list[str] = []
    for attempt in range(max_retries + 1):
        raw = model_call("\n\n".join(messages))
        try:
            obj = extract_json(raw)
        except ValueError as e:
            last_errors = [str(e)]
        else:
            last_errors = validate(obj, schema)
            if not last_errors:
                return obj
        if attempt < max_retries:
            messages.append(
                "Your previous reply was not valid for the required schema. "
                f"Errors: {'; '.join(last_errors)}. "
                "Reply with ONLY the JSON object, no prose, no markdown fence."
            )
    raise ValueError(f"model never produced valid JSON: {'; '.join(last_errors)}")


def demo() -> None:
    replies = iter([
        "Sure! Here is the result:\n```json\n{\"name\": \"Ada\", \"score\": \"high\"}\n```",
        '{"name": "Ada", "score": 87}',
    ])
    schema = {"name": str, "score": int}
    out = call_with_repair(lambda p: next(replies), "Extract the person.", schema)
    print("validated:", out)

Complexity: O(text length) extraction, O(retries Γ— call cost).

Tests: test_extract_json_from_fence, test_extract_json_prose_wrapped, test_call_with_repair_retries, test_call_with_repair_gives_up.

Extension questions:

  • Why not just regex for JSON? (Regex fails on nested objects, escaped quotes, strings containing braces. The balanced-brace scanner handles nesting; json.loads handles the rest.)
  • What's the difference between repair and retry? (Repair = guessing what the model meant and fixing syntax β€” dangerous, produces plausible-but-wrong data. Retry = asking the model again with error feedback β€” safe, uses the model's own capability. 03.4 covers when structured output makes this unnecessary.)
  • When is this the wrong approach? (When the provider offers schema-constrained output β€” use that instead. This drill is for the rung-1/2 reality where you can't constrain the model.)

4.11 Tool-call loop with scripted model and budgets#

Problem: "Implement the tool-calling loop: the model asks for a tool, you run it, feed the result back, until it answers or a budget stops it. Prove it works without an API β€” with a scripted fake." (A scripted fake proves the plumbing: budgets, error handling, message flow. It says nothing about how well a real model chooses tools; that needs an eval against a real model, as in Module 10A.)

sequenceDiagram
    participant U as User
    participant L as Loop
    participant M as Model
    participant T as Tool
    U->>L: user_message
    loop until final answer or budget
        L->>M: full transcript (stateless API)
        alt model requests tool(s)
            M-->>L: tool_calls + partial text
            L->>T: execute each tool(args)
            T-->>L: result or error string
            L->>L: append assistant + tool messages
        else model answers
            M-->>L: final text
        end
    end
    L-->>U: LoopResult(text, steps, calls, stop_reason)
python
# career_kit/drills/tool_loop.py
"""tool_loop.py β€” an agent loop with a scripted model and hard budgets.

Interview framing: "Implement the tool-calling loop: the model asks for a
tool, you run it, feed the result back, until it answers or a budget stops
it. Then prove it works without an API β€” with a scripted fake."

This is the interview-sized version of lesson 08A.2's canonical loop
(docs/source/08-tools-and-agents/01-the-tool-loop.md)
(`ChatAdapter`, the `REGISTRY`/`ToolSpec` pair, `ScriptedModel` live there). Same seams,
smaller surface.
"""

from __future__ import annotations

import json
from dataclasses import dataclass, field
from typing import Any, Callable


@dataclass
class ModelTurn:
    """What a model returns in one step: text, tool calls, or both."""

    text: str = ""
    tool_calls: list[dict[str, Any]] = field(default_factory=list)


@dataclass
class LoopResult:
    text: str
    steps: int
    tool_calls_made: int
    stop_reason: str  # "final" | "max_steps" | "max_tool_calls"


def run_tool_loop(
    model_call: Callable[[list[dict[str, Any]]], ModelTurn],
    tools: dict[str, Callable[[dict[str, Any]], str]],
    user_message: str,
    *,
    max_steps: int = 6,
    max_tool_calls: int = 8,
) -> LoopResult:
    """Drive model↔tool rounds until the model answers or a budget stops it.

    `model_call(messages)` sees the full transcript each step (stateless API β€”
    we re-send history, same as the real thing). `tools` maps name β†’ fn(args).
    """
    messages: list[dict[str, Any]] = [{"role": "user", "content": user_message}]
    tool_calls_made = 0
    for step in range(1, max_steps + 1):
        turn = model_call(messages)
        if not turn.tool_calls:
            return LoopResult(turn.text, step, tool_calls_made, "final")
        for call in turn.tool_calls:
            if tool_calls_made >= max_tool_calls:
                return LoopResult("", step, tool_calls_made, "max_tool_calls")
            name = call["name"]
            args = call.get("args", {})
            if name not in tools:
                result = f"error: unknown tool {name!r}"
            else:
                try:
                    result = tools[name](args)
                except Exception as e:  # tool errors go back to the model
                    result = f"error: {e}"
            tool_calls_made += 1
            # NOTE: real provider APIs batch ALL tool_calls of a turn into ONE
            # assistant message, then append one tool message per result. We
            # append per-call here only because the scripted model ignores
            # message shape β€” don't copy this into production code.
            messages.append({
                "role": "assistant",
                "content": turn.text or None,
                "tool_calls": [{"name": name, "args": args}],
            })
            messages.append({"role": "tool", "name": name, "content": result})
    return LoopResult("", max_steps, tool_calls_made, "max_steps")


class ScriptedModel:
    """Fake model: replays canned turns, records what it was sent.

    Not the same class as 08A.2's `ScriptedModel` β€” different seam: ours is a
    synchronous callable returning `ModelTurn`; theirs is an async
    `ChatAdapter` with `initial_history`/`call`. Same idea, smaller surface.
    """

    def __init__(self, turns: list[ModelTurn]) -> None:
        self._turns = list(turns)
        self.seen: list[list[dict[str, Any]]] = []

    def __call__(self, messages: list[dict[str, Any]]) -> ModelTurn:
        self.seen.append([dict(m) for m in messages])
        if not self._turns:
            raise AssertionError("scripted model ran out of turns")
        return self._turns.pop(0)


def demo() -> None:
    def lookup_order(args: dict[str, Any]) -> str:
        return json.dumps({"order_id": args["order_id"], "status": "shipped"})

    model = ScriptedModel([
        ModelTurn(tool_calls=[{"name": "lookup_order", "args": {"order_id": "A17"}}]),
        ModelTurn(text="Order A17 has shipped."),
    ])
    result = run_tool_loop(
        model,
        {"lookup_order": lookup_order},
        "Where is order A17?",
        max_steps=4,
    )
    print(f"text={result.text!r} steps={result.steps} "
          f"tool_calls={result.tool_calls_made} stop={result.stop_reason}")

Complexity: O(steps Γ— transcript size) β€” the transcript grows each step, which is the real cost (context window pressure, 08A.2, 6.1).

Tests: test_tool_loop_runs_and_finishes, test_tool_loop_budget_stops, test_tool_loop_unknown_tool_returns_error_to_model.

Extension questions:

  • Why budgets? (A model that can't answer will loop forever β€” each step costs tokens and latency. max_steps and max_tool_calls are the circuit breakers. 08A.2, 1.4 covers why they're non-negotiable.)
  • Why does the model see the full transcript? (LLM APIs are stateless β€” you re-send history each call. The loop is the state management.)
  • How do you detect loops? (Same tool + same args repeatedly β†’ break. 08A.2, 3.4 covers loop detection.)

4.12 Retrieval metrics: recall@k, MRR, nDCG#

Problem: "Given qrels (query β†’ relevant doc ids) and a ranked retriever, compute recall@k, MRR and nDCG. What does each one punish?"

python
# career_kit/drills/metrics.py
"""metrics.py β€” retrieval metrics: recall@k, MRR, nDCG.

Interview framing: "Given qrels (query β†’ relevant doc ids) and a ranked
retriever, compute recall@k, MRR and nDCG. What does each one punish?"

Canonical definitions and the eval-set format live in
lesson 06.10, Part 3 (docs/source/06-embeddings-vector-search/10-evaluating-and-tuning-retrieval.md);
lesson 10A.6 (docs/source/10a-evaluation-foundations/06-evaluating-rag.md) owns the RAG-eval
methodology. These are the formulas, implemented once.
"""

from __future__ import annotations

import math

Qrels = dict[str, set[str]]  # query_id -> relevant doc ids (binary)


def recall_at_k(ranked: list[str], relevant: set[str], k: int) -> float:
    """Fraction of relevant docs found in the top k."""
    if not relevant:
        return 0.0
    hits = len(set(ranked[:k]) & relevant)
    return hits / len(relevant)


def reciprocal_rank(ranked: list[str], relevant: set[str]) -> float:
    """1 / rank of the first relevant doc; 0 if none appears."""
    for i, doc in enumerate(ranked, start=1):
        if doc in relevant:
            return 1.0 / i
    return 0.0


def mrr(results: list[tuple[str, list[str]]], qrels: Qrels) -> float:
    """Mean reciprocal rank over queries."""
    vals = [reciprocal_rank(ranked, qrels[qid]) for qid, ranked in results]
    return sum(vals) / len(vals) if vals else 0.0


def dcg_at_k(ranked: list[str], gains: dict[str, float], k: int) -> float:
    """Discounted cumulative gain: sum gain / log2(rank + 1)."""
    return sum(
        gains.get(doc, 0.0) / math.log2(i + 2)  # i is 0-based; rank = i+1
        for i, doc in enumerate(ranked[:k])
    )


def ndcg_at_k(ranked: list[str], gains: dict[str, float], k: int) -> float:
    """nDCG = DCG / ideal DCG (best possible ordering by gain)."""
    ideal = sorted(gains.values(), reverse=True)[:k]
    idcg = sum(g / math.log2(i + 2) for i, g in enumerate(ideal))
    if idcg == 0.0:
        return 0.0
    return dcg_at_k(ranked, gains, k) / idcg


def evaluate(
    results: list[tuple[str, list[str]]],
    qrels: Qrels,
    graded: dict[str, dict[str, float]] | None = None,
    k: int = 5,
) -> dict[str, float]:
    """One call β†’ recall@k, MRR and mean nDCG for a set of queries."""
    graded = graded or {}
    rec = [recall_at_k(ranked, qrels[qid], k) for qid, ranked in results]
    nd = [ndcg_at_k(ranked, graded.get(qid, {d: 1.0 for d in qrels[qid]}), k)
          for qid, ranked in results]
    return {
        "recall@k": sum(rec) / len(rec),
        "mrr": mrr(results, qrels),
        "ndcg@k": sum(nd) / len(nd),
    }


def demo() -> None:
    qrels = {
        "q1": {"d2", "d5"},
        "q2": {"d1"},
    }
    results = [
        ("q1", ["d1", "d2", "d3", "d4", "d5"]),   # both relevant in top-5
        ("q2", ["d9", "d8", "d1", "d7", "d6"]),   # relevant at rank 3
    ]
    scores = evaluate(results, qrels, k=5)
    for key, val in scores.items():
        print(f"{key:9} {val:.4f}")

Complexity: O(queries Γ— k) for recall/MRR, O(queries Γ— k log k) for nDCG (sorting ideal gains).

Tests: test_recall_at_k, test_mrr_first_hit_rank, test_ndcg_perfect_is_one, test_evaluate_smoke.

Extension questions:

  • What does each metric punish? (Recall@k punishes missing relevant docs; MRR punishes late first hits; nDCG punishes bad ordering of graded relevance. Use the right one for the question β€” 06.10, 3.10.)
  • Binary vs graded relevance? (Binary = relevant/not; graded = 0–3 scale. nDCG shows its value with graded labels (it also works with binary ones, as evaluate does by default); recall and MRR are defined on binary relevance. 06.10, 2.5.)
  • How does this connect to RAG eval? (10A.6 uses these for the retrieval stage, then adds faithfulness/citation metrics for generation.)

4.13 LRU cache with TTL and single-flight#

Problem: "Build an LRU cache. Add a TTL. Make sure that when 50 concurrent requests miss the same key, your loader runs once β€” single-flight."

python
# career_kit/drills/lru.py
"""lru.py β€” an LRU cache with TTL and single-flight.

Interview framing: "Build an LRU cache. Now add a TTL. Now make sure that
when 50 concurrent requests miss the same key, your loader runs once β€”
single-flight."""

from __future__ import annotations

import threading
import time
from collections import OrderedDict
from typing import Any, Callable, Hashable, TypeVar

T = TypeVar("T")

# What the loading thread publishes for its waiters: ("ok", value) or
# ("err", exception). The box list is shared by reference, so waiters can
# read it after the owner has already removed the key from `_inflight`.
Outcome = tuple[str, Any]


class LRUCache:
    """LRU + TTL + single-flight, thread-safe.

    `clock` is injectable for deterministic tests. `loader` is called on a
    miss; while one thread loads key K, others wait on K's event rather than
    starting a second load (single-flight / request coalescing). If the
    loader raises, the exception is published to every waiter β€” nobody
    blocks forever.
    """

    def __init__(
        self,
        capacity: int,
        ttl_seconds: float,
        loader: Callable[[Hashable], T],
        clock: Callable[[], float] = time.monotonic,
    ) -> None:
        self.capacity = capacity
        self.ttl = ttl_seconds
        self.loader = loader
        self.clock = clock
        self._data: OrderedDict[Hashable, tuple[float, T]] = OrderedDict()
        self._inflight: dict[Hashable, tuple[threading.Event, list[Outcome]]] = {}
        self._lock = threading.Lock()
        self.loads = 0  # observable for tests/demos

    def _fresh(self, key: Hashable) -> bool:
        if key not in self._data:
            return False
        ts, _ = self._data[key]
        return self.clock() - ts < self.ttl

    def get(self, key: Hashable) -> T:
        with self._lock:
            if self._fresh(key):
                self._data.move_to_end(key)
                return self._data[key][1]
            entry = self._inflight.get(key)
            if entry is None:
                entry = (threading.Event(), [])
                self._inflight[key] = entry
                owner = True
            else:
                owner = False
        ev, box = entry
        if not owner:
            ev.wait()
            status, payload = box[0]
            if status == "err":
                raise payload
            return payload
        try:
            try:
                value = self.loader(key)
            except BaseException as exc:
                # Publish the failure BEFORE waking waiters, or they hang.
                with self._lock:
                    box.append(("err", exc))
                    ev.set()
                raise
            with self._lock:
                self.loads += 1
                self._data[key] = (self.clock(), value)
                self._data.move_to_end(key)
                while len(self._data) > self.capacity:
                    self._data.popitem(last=False)
                box.append(("ok", value))
                ev.set()
            return value
        finally:
            with self._lock:
                self._inflight.pop(key, None)


def demo() -> None:
    now = [1000.0]
    calls = {"n": 0}

    def loader(key: str) -> str:
        calls["n"] += 1
        return f"value-for-{key}"

    cache = LRUCache(capacity=2, ttl_seconds=10.0, loader=loader, clock=lambda: now[0])
    print(cache.get("a"), "|", cache.get("a"), "| loads:", cache.loads)
    now[0] += 11  # TTL expires
    print(cache.get("a"), "| loads:", cache.loads)
    cache.get("b"); cache.get("c")  # evicts 'a' (LRU)
    print(cache.get("a"), "| loads:", cache.loads, "(reloaded after eviction)")

Complexity: O(1) get/put β€” OrderedDict gives O(1) move-to-end and eviction.

Tests: test_lru_eviction_and_ttl, test_lru_loader_error_wakes_waiters.

Extension questions:

  • Why single-flight? (Without it, 50 concurrent misses on the same key trigger 50 identical expensive loads β€” a thundering herd on your database or API. Single-flight collapses them to one.)
  • What happens when the loader raises? (Every waiter must see the failure β€” the owner publishes the exception through the shared outcome box before setting the event, so waiters re-raise it instead of hanging. The error is not cached: the next caller becomes the owner and retries the load.)
  • LRU vs LFU vs FIFO? (LRU evicts least-recently-used; LFU evicts least-frequently-used; FIFO is simplest. LRU is the standard default β€” 11B.3 covers caching strategy.)
  • How does TTL interact with LRU? (TTL handles staleness β€” data that expires; LRU handles capacity β€” data that must be evicted. They're orthogonal; you need both.)

4.14 Token-counting budget packer#

Problem: "You have retrieved 50 chunks but the context window fits ~2,000 tokens. Pack as many as fit, in order, and tell me what you dropped."

python
# career_kit/drills/budget.py
"""budget.py β€” pack items into a token budget, preserving order.

Interview framing: "You have retrieved 50 chunks but the context window
fits ~2,000 tokens. Pack as many as fit, in order, and tell me what you
dropped. Now make it respect per-item metadata budgets too."

`count_tokens` is injected β€” in production it's the provider's counter
(02.2 / 03.7); the demo uses a deterministic approximation.
"""

from __future__ import annotations

import re
from typing import Callable, TypeVar

T = TypeVar("T")

_WORDISH = re.compile(r"\w+|[^\w\s]")


def approx_tokens(text: str) -> int:
    """Deterministic stand-in for a real tokenizer: ~1 token per word/punct."""
    return max(1, len(_WORDISH.findall(text)))


def pack_items(
    items: list[T],
    budget: int,
    count_tokens: Callable[[T], int],
    *,
    reserve: int = 0,
) -> tuple[list[T], list[T], int]:
    """Greedy in-order packing with skip-and-continue.

    Returns (packed, skipped, tokens_used). `reserve` holds tokens back for
    the system prompt / question / answer β€” pack only into budget-reserve.
    An item that does not fit is skipped, but later (smaller) items are still
    tried, so a short low-ranked chunk can fill leftover room. Packed items
    keep their original relative order. If you would rather stop at the first
    miss (strict relevance order), `break` instead of skipping β€” see the
    extension questions.
    """
    limit = budget - reserve
    if limit < 0:
        raise ValueError("reserve exceeds budget")
    packed: list[T] = []
    skipped: list[T] = []
    used = 0
    for item in items:
        cost = count_tokens(item)
        if used + cost <= limit:
            packed.append(item)
            used += cost
        else:
            skipped.append(item)
    return packed, skipped, used


def demo() -> None:
    chunks = [
        "Refunds are processed within five business days.",
        "You must return items in original packaging.",
        "Final-sale items cannot be refunded or exchanged.",
        "Gift cards never expire and have no fees.",
        "Damaged-on-arrival claims require photos within 48 hours.",
    ]
    packed, skipped, used = pack_items(
        chunks, budget=30, count_tokens=approx_tokens, reserve=5
    )
    print(f"budget=30 reserve=5 used={used}")
    print("packed:")
    for c in packed:
        print("  +", c)
    print("skipped:")
    for c in skipped:
        print("  -", c)

Complexity: O(n) where n = items.

Tests: test_pack_items_reserve_and_order.

Extension questions:

  • Should a skipped item stop the packing, or should smaller later items still be tried? (This drill tries them: a short item 5 can fit where a long item 4 did not, which uses the budget better. The cost is that a lower-ranked chunk may enter the context only because it was short, which can add noise. The strict alternative is to break at the first miss so the context is always a prefix of the ranking. Neither is universally right; say which you chose and why, and measure answer quality with your eval set.)
  • What if items have different "costs" beyond tokens? (Metadata, images, tool definitions all consume context β€” the budget is holistic, not just text tokens. 02.7 covers context budgeting.)
  • How does this relate to prompt caching? (03.7 and 11B.3 β€” packing order affects cache hit rates; stable prefixes cache better.)

4.15 Diffing/regression-comparing two eval runs#

Problem: "Two eval runs, same cases, different scores. Tell me what got worse, what got better, and whether the delta is bigger than noise."

python
# career_kit/drills/eval_diff.py
"""eval_diff.py β€” diff two eval runs to find regressions.

Interview framing: "Two eval runs, same cases, different scores. Tell me
what got worse, what got better, and whether the delta is bigger than noise."

The paired-difference methodology lives in
lesson 06.10, 4.5 (docs/source/06-embeddings-vector-search/10-evaluating-and-tuning-retrieval.md);
this is the deterministic core: per-case deltas plus a bootstrap CI.
"""

from __future__ import annotations

import random
import statistics

CaseResult = dict[str, float]  # case_id -> score in [0, 1]


def diff_runs(
    before: CaseResult,
    after: CaseResult,
    *,
    regression_threshold: float = 0.0,
) -> dict[str, list[str]]:
    """Classify per-case changes between two runs of the same eval set.

    A case present in only one run is not comparable, so it is listed under
    "added" or "removed" instead of being counted as an improvement or a
    regression. If those lists are non-empty, the eval set itself changed.
    """
    regressions, improvements, unchanged = [], [], []
    added, removed = [], []
    for case_id in sorted(set(before) | set(after)):
        b, a = before.get(case_id), after.get(case_id)
        if b is None or a is None:
            (added if b is None else removed).append(case_id)
            continue
        delta = a - b
        if delta < -regression_threshold:
            regressions.append(f"{case_id}: {b:.2f} -> {a:.2f} ({delta:+.2f})")
        elif delta > regression_threshold:
            improvements.append(f"{case_id}: {b:.2f} -> {a:.2f} ({delta:+.2f})")
        else:
            unchanged.append(case_id)
    return {
        "regressions": regressions,
        "improvements": improvements,
        "unchanged": unchanged,
        "added": added,
        "removed": removed,
    }


def bootstrap_ci(deltas: list[float], *, iters: int = 2000, seed: int = 0) -> tuple[float, float]:
    """95% CI for the mean delta via bootstrap resampling (deterministic seed)."""
    if not deltas:
        return (0.0, 0.0)
    rng = random.Random(seed)
    n = len(deltas)
    means = sorted(
        statistics.fmean(rng.choices(deltas, k=n)) for _ in range(iters)
    )
    return means[int(0.025 * iters)], means[int(0.975 * iters)]


def demo() -> None:
    before = {"c1": 1.0, "c2": 0.8, "c3": 0.5, "c4": 0.9, "c5": 0.7}
    after = {"c1": 1.0, "c2": 0.4, "c3": 0.6, "c4": 0.9, "c5": 0.7}
    report = diff_runs(before, after)
    for key in ("regressions", "improvements", "unchanged"):
        print(f"{key}: {report[key]}")
    deltas = [after[c] - before[c] for c in before]
    lo, hi = bootstrap_ci(deltas, iters=500)
    print(f"mean delta={statistics.fmean(deltas):+.3f} 95% CI=({lo:+.3f}, {hi:+.3f})")

Complexity: O(cases) for diff, O(iters Γ— cases) for bootstrap.

Tests: test_diff_runs_finds_regression, test_bootstrap_ci_deterministic.

Extension questions:

  • Why bootstrap and not a t-test? (Eval scores aren't necessarily normal β€” bootstrap makes fewer assumptions. 06.10, 4.5 covers the methodology.)
  • What counts as "noise"? (If the confidence interval for the mean delta includes zero, you can't distinguish the change from run-to-run and case-sampling variance. With only a handful of cases, as in the demo, the interval is very wide, which is the point: small eval sets need repeats and statistical thinking β€” 10A.8.)
  • How does this relate to CI gates? (10A.8 and 11C.2 β€” the diff is the primitive; the gate is the policy.)

4.16 Mini BPE tokenizer#

Problem: "LLMs don't see words β€” they see tokens from a BPE vocabulary. Implement the merge step: given a corpus, learn the most frequent adjacent pair, merge it, repeat. Then tokenize new text."

python
# career_kit/drills/bpe.py
"""bpe.py β€” a minimal byte-pair-encoding trainer and tokenizer.

Interview framing: "LLMs don't see words, they see tokens from a BPE
vocabulary. Implement the merge step: given a corpus, learn the most frequent
adjacent pair, merge it, repeat. Then tokenize new text."

Depth: lesson 02.2 (docs/source/02-how-llms-work/02-tokens-and-tokenization.md)
owns pre-tokenization, byte-level BPE and real vocab sizes. This is the
algorithmic core in ~60 lines.
"""

from __future__ import annotations

import re
from collections import Counter

_WORD = re.compile(r"\w+|[^\w\s]", re.UNICODE)


def _init_words(text: str) -> list[list[str]]:
    """Each word becomes a list of characters (our 'bytes')."""
    return [[c for c in m.group(0)] for m in _WORD.finditer(text)]


def learn_merges(text: str, num_merges: int) -> list[tuple[str, str]]:
    """Learn `num_merges` BPE merge rules, most-frequent-pair first."""
    words = _init_words(text)
    merges: list[tuple[str, str]] = []
    for _ in range(num_merges):
        pairs = Counter()
        for w in words:
            pairs.update(zip(w, w[1:]))
        if not pairs:
            break
        (a, b), _ = pairs.most_common(1)[0]
        merges.append((a, b))
        words = [_merge_word(w, a, b) for w in words]
    return merges


def _merge_word(word: list[str], a: str, b: str) -> list[str]:
    out: list[str] = []
    i = 0
    while i < len(word):
        if i + 1 < len(word) and word[i] == a and word[i + 1] == b:
            out.append(a + b)
            i += 2
        else:
            out.append(word[i])
            i += 1
    return out


def tokenize(text: str, merges: list[tuple[str, str]]) -> list[str]:
    """Apply learned merges in order to new text."""
    words = _init_words(text)
    for a, b in merges:
        words = [_merge_word(w, a, b) for w in words]
    return [tok for w in words for tok in w]


def demo() -> None:
    corpus = (
        "the cat sat on the mat the cat ate the rat "
        "the dog sat on the log the cat and the dog"
    )
    merges = learn_merges(corpus, num_merges=8)
    print("merges:", merges)
    print("tokens:", tokenize("the cat sat", merges))

Complexity: O(merges Γ— corpus size) for learning; O(merges Γ— text length) for tokenizing.

Tests: test_bpe_merges_and_tokenizes, test_bpe_frequent_pair_first.

Extension questions:

  • Why merge most-frequent pairs first? (BPE builds vocabulary bottom-up: frequent pairs become single tokens, compressing common words/phrases. Rare pairs stay as characters β€” that's why rare words tokenize into more pieces.)
  • What's pre-tokenization? (Splitting text into words before BPE β€” punctuation, whitespace, case handling. 02.2, 2.5 covers it.)
  • Why does this matter for cost? (Token count = cost. Understanding tokenization helps you estimate API costs and context usage β€” 03.7.)

4.17 Softmax and scaled dot-product attention#

Problem: "Implement attention(Q, K, V) = softmax(QK^T / sqrt(d))V on small matrices, with a causal mask. Explain why divide by sqrt(d)."

python
# career_kit/drills/attention.py
"""attention.py β€” softmax and scaled dot-product attention in pure Python.

Interview framing: "Implement attention(Q, K, V) = softmax(QK^T / sqrt(d))V
on small matrices, with a causal mask. Explain why divide by sqrt(d)."

Depth: lesson 02.4 (docs/source/02-how-llms-work/04-attention-and-transformers.md)
owns the intuition, multi-head and where Q/K/V come from. This is the math,
~50 lines, lists only.
"""

from __future__ import annotations

import math

Matrix = list[list[float]]


def matmul(a: Matrix, b: Matrix) -> Matrix:
    """a @ b for plain lists of lists."""
    if not a or not b:
        return []
    n, k, m = len(a), len(b), len(b[0])
    bt = list(zip(*b))
    return [[sum(a[i][x] * bt[j][x] for x in range(k)) for j in range(m)] for i in range(n)]


def transpose(a: Matrix) -> Matrix:
    return [list(row) for row in zip(*a)]


def softmax(row: list[float]) -> list[float]:
    """Numerically stable softmax: subtract max before exp.

    A fully masked row (every score -inf) has no distribution β€” max is -inf,
    x - m is NaN and the weights silently become NaN. Raise instead; a causal
    mask always leaves row 0 unmasked, so hitting this means the caller's
    mask is wrong.
    """
    m = max(row)
    if m == float("-inf"):
        raise ValueError("softmax of a fully masked row is undefined")
    exps = [math.exp(x - m) for x in row]
    total = sum(exps)
    return [e / total for e in exps]


def scaled_dot_product_attention(
    Q: Matrix, K: Matrix, V: Matrix, mask: Matrix | None = None
) -> tuple[Matrix, Matrix]:
    """Return (attention_weights, output). mask=1 keeps, mask=0 blocks (-inf)."""
    d = len(Q[0])
    scores = matmul(Q, transpose(K))
    scores = [[s / math.sqrt(d) for s in row] for row in scores]
    if mask is not None:
        scores = [[s if mask[i][j] else float("-inf") for j, s in enumerate(row)]
                  for i, row in enumerate(scores)]
    weights = [softmax(row) for row in scores]
    return weights, matmul(weights, V)


def demo() -> None:
    # 3 tokens, d=2 β€” small enough to print every number.
    Q = [[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]]
    K = [[1.0, 0.0], [0.0, 1.0], [1.0, 1.0]]
    V = [[10.0, 0.0], [0.0, 10.0], [5.0, 5.0]]
    # causal mask: token i may only attend to tokens <= i
    mask = [[1 if j <= i else 0 for j in range(3)] for i in range(3)]
    weights, out = scaled_dot_product_attention(Q, K, V, mask)
    print("attention weights (causal):")
    for row in weights:
        print("  ", [round(x, 4) for x in row])
    print("output:")
    for row in out:
        print("  ", [round(x, 4) for x in row])

Complexity: O(nΒ²Β·d) for n tokens, d dimensions β€” the quadratic term is why long contexts are expensive (02.4, 2.5).

Tests: test_softmax_sums_to_one, test_attention_weights_row_sums_to_one, test_causal_mask_blocks_future, test_softmax_fully_masked_raises.

Extension questions:

  • Why divide by √d? (Without it, dot products grow with dimension, pushing softmax into saturation β€” gradients vanish. √d keeps the variance stable. 02.4, 2.5.)
  • What does the causal mask do? (Prevents token i from attending to tokens > i β€” essential for autoregressive generation, where the model must not "see" future tokens. 02.4, Part 3.)
  • What's multi-head attention? (Multiple attention "heads" with different learned projections capture different relationship types β€” syntax, coreference, position. 02.4, Part 4.)

4.18 The package glue and running everything#

The seventeen drill modules above are the solutions; four small files make them a runnable package. First the two package markers (they make career_kit.drills.* importable):

python
# career_kit/__init__.py
"""career_kit β€” shared package for the AI-engineer career module (14.x)."""
python
# career_kit/drills/__init__.py
"""LLM-flavoured interview drills β€” pure stdlib, deterministic."""

Then the runner β€” it imports every drill, calls its demo() under a fixed seed and prints a labelled header:

python
# career_kit/drills/run_all.py
"""run_all.py β€” execute every drill's demo() with a fixed seed.

Run from the project root:  uv run python career_kit/drills/run_all.py
(the script's own directory lands on sys.path, so we add the project root
to make `career_kit.drills.*` importable as a package).

Deterministic: fixed seed, injected clocks, scripted fakes β€” no network,
no API keys. The only real delay is bounded.py's sub-second simulated
fetch latency.
"""

from __future__ import annotations

import random
import sys
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

from career_kit.drills import (  # noqa: E402
    attention,
    bm25,
    bounded,
    bpe,
    budget,
    chunker,
    eval_diff,
    fusion,
    json_repair,
    lru,
    metrics,
    rate_limit,
    retry,
    sse_parse,
    templates,
    tool_loop,
    vectors,
)

DEMOS = [
    ("rate_limit", "TokenBucket", rate_limit.demo),
    ("retry", "retry_with_backoff", retry.demo),
    ("bounded", "run_bounded", bounded.demo),
    ("sse_parse", "accumulate_chat_stream", sse_parse.demo),
    ("chunker", "chunk_text", chunker.demo),
    ("vectors", "top_k", vectors.demo),
    ("bm25", "BM25", bm25.demo),
    ("fusion", "rrf", fusion.demo),
    ("templates", "PromptTemplate", templates.demo),
    ("json_repair", "call_with_repair", json_repair.demo),
    ("tool_loop", "run_tool_loop", tool_loop.demo),
    ("metrics", "evaluate", metrics.demo),
    ("lru", "LRUCache", lru.demo),
    ("budget", "pack_items", budget.demo),
    ("eval_diff", "diff_runs", eval_diff.demo),
    ("bpe", "learn_merges", bpe.demo),
    ("attention", "scaled_dot_product_attention", attention.demo),
]


def main() -> None:
    random.seed(20261107)  # fixed seed: the whole run is deterministic
    for i, (module_name, label, demo) in enumerate(DEMOS):
        if i:
            print()
        print(f"===== {module_name}.{label} =====")
        demo()


if __name__ == "__main__":
    main()

And the pytest suite β€” 44 tests covering every drill's edge cases, including the single-flight loader-error regression from 4.13:

python
# career_kit/drills/test_drills.py
"""test_drills.py β€” pytest suite for the career_kit drills (44 tests).

Every test is deterministic: injected clocks, scripted fakes, fixed seeds.
Run from the project root:  uv run pytest career_kit/drills/test_drills.py
"""

from __future__ import annotations

import asyncio
import json
import random
import threading

import pytest

from career_kit.drills import attention, bm25, bounded, bpe, budget, chunker
from career_kit.drills import eval_diff, fusion, json_repair, lru, metrics
from career_kit.drills import rate_limit, retry, sse_parse, templates
from career_kit.drills import tool_loop, vectors


# --- 4.1 rate_limit ---------------------------------------------------------

def test_token_bucket_allows_burst_then_refills():
    b = rate_limit.TokenBucket(capacity=3, refill_per_second=1.0)
    assert [b.allow(now=t) for t in (0.0, 0.1, 0.2)] == [True, True, True]
    assert b.allow(now=0.3) is False           # bucket empty
    assert b.allow(now=1.3) is True            # one token refilled
    assert b.time_until_next(now=1.3) == pytest.approx(0.7)


def test_token_bucket_caps_at_capacity():
    b = rate_limit.TokenBucket(capacity=2, refill_per_second=100.0)
    b.allow(now=0.0); b.allow(now=0.0)
    b.allow(now=100.0)                          # huge gap: still capped at 2
    assert b.allow(now=100.0) is True
    assert b.allow(now=100.0) is False


# --- 4.2 bounded ------------------------------------------------------------

def test_run_bounded_preserves_order_and_limits():
    in_flight = {"n": 0, "max": 0}

    async def worker(item: int) -> int:
        in_flight["n"] += 1
        in_flight["max"] = max(in_flight["max"], in_flight["n"])
        await asyncio.sleep(0.001)
        in_flight["n"] -= 1
        return item * 10

    results = asyncio.run(bounded.run_bounded(list(range(10)), worker, limit=3))
    assert results == [i * 10 for i in range(10)]   # input order preserved
    assert in_flight["max"] <= 3                    # bound respected

    async def flaky(item: int) -> int:
        if item == 2:
            raise RuntimeError("boom")
        return item

    mixed = asyncio.run(bounded.run_bounded([1, 2, 3], flaky, limit=2, return_exceptions=True))
    assert mixed[0] == 1 and mixed[2] == 3          # one failure does not kill the batch
    assert isinstance(mixed[1], RuntimeError)


# --- 4.3 retry --------------------------------------------------------------

def test_retry_succeeds_after_failures():
    calls = {"n": 0}

    def flaky():
        calls["n"] += 1
        if calls["n"] < 3:
            raise retry.RetryableError("transient")
        return "ok"

    waits: list[float] = []
    out = retry.retry_with_backoff(
        flaky, max_attempts=5, base_delay=0.1, sleep=waits.append,
        rng=random.Random(1),
    )
    assert out == "ok" and calls["n"] == 3 and waits


def test_retry_gives_up_and_raises_last():
    def always():
        raise retry.RetryableError("down")

    with pytest.raises(retry.RetryableError):
        retry.retry_with_backoff(
            always, max_attempts=3, base_delay=0.01,
            sleep=lambda s: None, rng=random.Random(1),
        )


def test_retry_does_not_retry_other_errors():
    calls = {"n": 0}

    def boom():
        calls["n"] += 1
        raise ValueError("permanent")

    with pytest.raises(ValueError):
        retry.retry_with_backoff(boom, sleep=lambda s: None)
    assert calls["n"] == 1                        # no retry on non-retryable


def test_retry_rejects_zero_attempts():
    with pytest.raises(ValueError):
        retry.retry_with_backoff(lambda: "x", max_attempts=0)


# --- 4.4 sse_parse ----------------------------------------------------------

def _sse(lines: list[str]) -> list[bytes]:
    return [ln.encode() for ln in lines]


def test_sse_events_split_across_chunks():
    payload = 'data: {"choices":[{"delta":{"content":"Hi"}}]}\n\n'
    wire = payload.encode()
    # split mid-line and mid-event
    chunks = [wire[:10], wire[10:25], wire[25:]]
    events = list(sse_parse.iter_sse_events(chunks))
    assert len(events) == 1
    assert events[0].data == '{"choices":[{"delta":{"content":"Hi"}}]}'


def test_sse_comments_and_done():
    chunks = _sse([
        ": keep-alive\n",
        "event: message\n",
        'data: {"a": 1}\n',
        "\n",
        "data: [DONE]\n",
        "\n",
    ])
    events = list(sse_parse.iter_sse_events(chunks))
    assert [(e.event, e.data) for e in events] == [
        ("message", '{"a": 1}'), ("message", "[DONE]")
    ]


def test_accumulate_chat_stream():
    chunks = [
        b'data: {"choices":[{"delta":{"content":"Hel"},"finish_reason":null}]}\n\n',
        b'data: {"choices":[{"delta":{"content":"lo"},"finish_reason":"stop"}],"usage":{"total_tokens":5}}\n\n',
        b"data: [DONE]\n\n",
    ]
    out = sse_parse.accumulate_chat_stream(chunks)
    assert out.text == "Hello"
    assert out.finish_reason == "stop"
    assert out.usage == {"total_tokens": 5}


# --- 4.5 chunker ------------------------------------------------------------

def test_chunk_text_respects_max_and_overlap():
    text = ("One two three four five. " * 30).strip()
    chunks = chunker.chunk_text(text, max_chars=120, overlap_chars=30)
    assert len(chunks) > 1
    assert all(len(c) <= 120 for c in chunks)
    # overlap: some trailing text of chunk i reappears at the start of i+1
    assert chunks[1].split()[0] in chunks[0].split()


def test_chunk_text_no_sentence_split():
    text = "Short one. Another sentence here. Third one follows."
    chunks = chunker.chunk_text(text, max_chars=200, overlap_chars=0)
    assert len(chunks) == 1
    # with a tight budget each chunk still ends on a sentence boundary
    chunks = chunker.chunk_text(text, max_chars=45, overlap_chars=0)
    assert all(c.endswith((".", "!", "?")) for c in chunks)


# --- 4.6 vectors ------------------------------------------------------------

def test_cosine_identical_is_one():
    v = [1.0, 2.0, 3.0]
    assert vectors.cosine_similarity(v, v) == pytest.approx(1.0)


def test_cosine_orthogonal_is_zero():
    assert vectors.cosine_similarity([1.0, 0.0], [0.0, 1.0]) == pytest.approx(0.0)


def test_top_k_orders_by_similarity():
    docs = [("a", [1.0, 0.0]), ("b", [0.0, 1.0]), ("c", [0.9, 0.1])]
    top = vectors.top_k([1.0, 0.0], docs, k=2)
    assert [d for d, _ in top] == ["a", "c"]
    assert top[0][1] >= top[1][1]


# --- 4.7 bm25 ---------------------------------------------------------------

def test_bm25_ranks_relevant_first():
    docs = [
        "the quick brown fox",
        "lazy dogs sleep all day",
        "quick fox jumps over",
    ]
    bm = bm25.BM25([bm25.tokenize(d) for d in docs])
    ranked = bm.search("quick fox", k=3)
    assert len(ranked) == 2                    # doc1 has neither term
    assert all(i in (0, 2) for _, i in ranked) # only docs with both terms


def test_bm25_unknown_term_scores_zero():
    bm = bm25.BM25([["hello", "world"]])
    assert bm.score("xyzzy", 0) == 0.0
    assert bm.search("xyzzy") == []


# --- 4.8 fusion -------------------------------------------------------------

def test_rrf_consensus_doc_wins():
    dense = [("a", 0.9), ("b", 0.8), ("c", 0.1)]
    lexical = [("c", 9.0), ("a", 8.0), ("b", 1.0)]
    fused = fusion.rrf([dense, lexical])
    ids = [d for d, _ in fused]
    assert ids[0] in ("a", "c")               # consensus beats single-list wins
    assert set(ids) == {"a", "b", "c"}


def test_rrf_single_ranking_preserves_order():
    fused = fusion.rrf([[("x", 1.0), ("y", 0.5), ("z", 0.1)]])
    assert [d for d, _ in fused] == ["x", "y", "z"]


# --- 4.9 templates ----------------------------------------------------------

def test_template_render_ok():
    tpl = templates.PromptTemplate.from_text("t", "Hi {{name}}, ref {{ref}}.")
    assert tpl.render({"name": "Ada", "ref": "A1"}) == "Hi Ada, ref A1."


def test_template_missing_raises():
    tpl = templates.PromptTemplate.from_text("t", "Hi {{name}}.")
    with pytest.raises(templates.TemplateError):
        tpl.render({})


def test_template_extra_key_raises():
    tpl = templates.PromptTemplate.from_text("t", "Hi {{name}}.")
    with pytest.raises(templates.TemplateError):
        tpl.render({"name": "Ada", "surprise": "x"})


# --- 4.10 json_repair -------------------------------------------------------

def test_extract_json_from_fence():
    text = 'Here you go:\n```json\n{"a": 1}\n```\nDone.'
    assert json_repair.extract_json(text) == {"a": 1}


def test_extract_json_prose_wrapped():
    assert json_repair.extract_json('Sure! The answer is {"a": [1, 2]} β€” hope that helps') == {"a": [1, 2]}
    # a non-JSON brace first, valid JSON later: still finds the parseable one
    assert json_repair.extract_json('use {x} then {"a": 1}') == {"a": 1}


def test_call_with_repair_retries():
    replies = iter(['not json at all', '{"name": "Ada", "score": 87}'])
    out = json_repair.call_with_repair(
        lambda p: next(replies), "extract", {"name": str, "score": int},
    )
    assert out == {"name": "Ada", "score": 87}


def test_call_with_repair_gives_up():
    with pytest.raises(ValueError):
        json_repair.call_with_repair(
            lambda p: "still not json", "extract", {"name": str}, max_retries=1,
        )


# --- 4.11 tool_loop ---------------------------------------------------------

def _loop_tools():
    def lookup(args):
        return json.dumps({"id": args["id"], "status": "ok"})
    return {"lookup": lookup}


def test_tool_loop_runs_and_finishes():
    model = tool_loop.ScriptedModel([
        tool_loop.ModelTurn(tool_calls=[{"name": "lookup", "args": {"id": "A1"}}]),
        tool_loop.ModelTurn(text="Done."),
    ])
    res = tool_loop.run_tool_loop(model, _loop_tools(), "find A1")
    assert res.text == "Done." and res.stop_reason == "final"
    assert res.tool_calls_made == 1


def test_tool_loop_budget_stops():
    model = tool_loop.ScriptedModel([
        tool_loop.ModelTurn(tool_calls=[{"name": "lookup", "args": {"id": "A1"}}])
        for _ in range(10)
    ])
    res = tool_loop.run_tool_loop(
        model, _loop_tools(), "loop forever", max_steps=3, max_tool_calls=2,
    )
    assert res.stop_reason == "max_tool_calls"
    assert res.tool_calls_made == 2


def test_tool_loop_unknown_tool_returns_error_to_model():
    model = tool_loop.ScriptedModel([
        tool_loop.ModelTurn(tool_calls=[{"name": "nope", "args": {}}]),
        tool_loop.ModelTurn(text="recovered"),
    ])
    res = tool_loop.run_tool_loop(model, _loop_tools(), "hi", max_steps=3)
    assert res.text == "recovered"
    # the model saw the tool error fed back
    last_seen = model.seen[-1]
    assert any(m.get("role") == "tool" and "unknown tool" in m.get("content", "")
               for m in last_seen)


# --- 4.12 metrics -----------------------------------------------------------

def test_recall_at_k():
    assert metrics.recall_at_k(["d1", "d2", "d3"], {"d2", "d5"}, k=3) == pytest.approx(0.5)
    assert metrics.recall_at_k([], {"d1"}, k=5) == 0.0


def test_mrr_first_hit_rank():
    qrels = {"q": {"d3"}}
    res = [("q", ["d1", "d2", "d3"])]
    assert metrics.mrr(res, qrels) == pytest.approx(1 / 3)


def test_ndcg_perfect_is_one():
    gains = {"d1": 3.0, "d2": 2.0, "d3": 1.0}
    assert metrics.ndcg_at_k(["d1", "d2", "d3"], gains, k=3) == pytest.approx(1.0)


def test_evaluate_smoke():
    qrels = {"q1": {"d1"}}
    out = metrics.evaluate([("q1", ["d1", "d2"])], qrels, k=5)
    assert out["recall@k"] == pytest.approx(1.0)
    assert out["mrr"] == pytest.approx(1.0)
    assert 0.0 < out["ndcg@k"] <= 1.0


# --- 4.13 lru ----------------------------------------------------------------

def test_lru_eviction_and_ttl():
    now = [0.0]
    cache = lru.LRUCache(2, 10.0, lambda k: f"v-{k}", clock=lambda: now[0])
    assert cache.get("a") == "v-a" and cache.loads == 1
    assert cache.get("a") == "v-a" and cache.loads == 1      # hit, no reload
    cache.get("b"); cache.get("c")                            # evicts 'a'
    assert cache.loads == 3
    assert cache.get("a") == "v-a" and cache.loads == 4       # reloaded, evicts 'b'
    now[0] += 11                                               # TTL expires
    assert cache.get("c") == "v-c" and cache.loads == 5       # 'c' also expired


def test_lru_loader_error_wakes_waiters():
    entered = threading.Event()
    release = threading.Event()

    def loader(key):
        entered.set()
        release.wait(timeout=5)
        raise RuntimeError("loader boom")

    cache = lru.LRUCache(4, 60.0, loader)
    errors: list[BaseException] = []

    def worker():
        try:
            cache.get("k")
        except RuntimeError as e:
            errors.append(e)

    t1 = threading.Thread(target=worker)
    t1.start()
    assert entered.wait(timeout=5)               # owner is inside loader
    t2 = threading.Thread(target=worker)
    t2.start()
    import time as _t
    _t.sleep(0.1)                                # let t2 block on the event
    release.set()
    t1.join(timeout=5)
    t2.join(timeout=5)
    assert not t1.is_alive() and not t2.is_alive()   # nobody deadlocked
    assert len(errors) == 2
    assert all(str(e) == "loader boom" for e in errors)


# --- 4.14 budget ------------------------------------------------------------

def test_pack_items_reserve_and_order():
    items = ["aaaa bbbb", "cc", "dddd eeee", "ff", "gg hh"]
    packed, skipped, used = budget.pack_items(
        items, budget=6, count_tokens=budget.approx_tokens, reserve=2,
    )
    # limit = 6 - 2 = 4 tokens; "dddd eeee" (2) can't fit after 3 used
    assert packed == ["aaaa bbbb", "cc", "ff"]
    assert skipped == ["dddd eeee", "gg hh"]
    assert used == 4
    assert sorted(packed + skipped) == sorted(items)  # nothing lost or duplicated


# --- 4.15 eval_diff ---------------------------------------------------------

def test_diff_runs_finds_regression():
    before = {"c1": 1.0, "c2": 0.8, "c3": 0.5}
    after = {"c1": 1.0, "c2": 0.4, "c3": 0.6}
    rep = eval_diff.diff_runs(before, after)
    assert any("c2" in r for r in rep["regressions"])
    assert any("c3" in r for r in rep["improvements"])
    assert rep["unchanged"] == ["c1"]
    # a case that exists in only one run is reported, not scored
    rep2 = eval_diff.diff_runs({"c1": 1.0, "c9": 0.5}, {"c1": 1.0, "c8": 0.5})
    assert rep2["added"] == ["c8"] and rep2["removed"] == ["c9"]
    assert rep2["regressions"] == [] and rep2["improvements"] == []


def test_bootstrap_ci_deterministic():
    deltas = [0.1, -0.2, 0.3, 0.0, 0.15]
    a = eval_diff.bootstrap_ci(deltas, iters=200, seed=42)
    b = eval_diff.bootstrap_ci(deltas, iters=200, seed=42)
    assert a == b
    assert a[0] <= a[1]


# --- 4.16 bpe ----------------------------------------------------------------

def test_bpe_merges_and_tokenizes():
    corpus = "the cat sat the cat"
    merges = bpe.learn_merges(corpus, num_merges=3)
    assert merges                                   # learned at least one rule
    toks = bpe.tokenize("the cat", merges)
    assert isinstance(toks, list) and toks


def test_bpe_frequent_pair_first():
    corpus = "aa bb aa bb aa bb"                     # 'aa' and 'bb' equally frequent
    merges = bpe.learn_merges(corpus, num_merges=1)
    assert len(merges) == 1
    a, b = merges[0]
    assert a in ("a", "b") and b == a                # merged a doubled char pair


# --- 4.17 attention ---------------------------------------------------------

def test_softmax_sums_to_one():
    out = attention.softmax([1.0, 2.0, 3.0])
    assert sum(out) == pytest.approx(1.0)
    assert out[2] > out[0]                           # higher logit β†’ higher prob


def test_attention_weights_row_sums_to_one():
    Q = [[1.0, 0.0], [0.0, 1.0]]
    K = [[1.0, 0.0], [0.0, 1.0]]
    V = [[1.0, 0.0], [0.0, 1.0]]
    weights, _ = attention.scaled_dot_product_attention(Q, K, V)
    for row in weights:
        assert sum(row) == pytest.approx(1.0)


def test_causal_mask_blocks_future():
    Q = [[1.0, 0.0], [1.0, 0.0]]
    K = [[1.0, 0.0], [0.0, 1.0]]
    V = [[10.0, 0.0], [0.0, 10.0]]
    mask = [[1, 0], [1, 1]]                          # row 0 sees only key 0
    weights, _ = attention.scaled_dot_product_attention(Q, K, V, mask)
    assert weights[0][1] == 0.0                      # future token blocked
    assert weights[0][0] == pytest.approx(1.0)


def test_softmax_fully_masked_raises():
    with pytest.raises(ValueError):
        attention.softmax([float("-inf"), float("-inf")])

Once all files are in place, from the project root:

bash
uv run python career_kit/drills/run_all.py     # every demo, fixed seed 20261107
uv run pytest career_kit/drills/test_drills.py  # 44 tests, all deterministic

The run is deterministic (fixed seed 20261107, injected clocks, scripted fakes β€” the only real delay is bounded.py's sub-second simulated fetch latency; no network, no API keys). Output:

text
===== rate_limit.TokenBucket =====
time  allow?  wait_next
 0.0  True     0.00
 0.1  True     0.00
 0.2  True     0.00
 0.3  True     0.20
 0.4  False    0.10
 0.5  True     0.50
 0.9  False    0.10
 1.4  True     0.10
 2.0  True     0.00
 3.0  True     0.00

===== retry.retry_with_backoff =====
result='ok' attempts=4 waits=[0.43, 0.721, 2.241]

===== bounded.run_bounded =====
items=20 limit=4 ok=18 sample=[{'id': 0, 'status': 500}, {'id': 1, 'status': 200}, {'id': 2, 'status': 200}]

===== sse_parse.accumulate_chat_stream =====
events=5 text='Hello, world!'
finish_reason=stop usage={'prompt_tokens': 9, 'completion_tokens': 3, 'total_tokens': 12}

===== chunker.chunk_text =====
--- chunk 1 (106 chars) ---
Refunds are issued within 5 business days of approval. You must return the item in its original packaging.
--- chunk 2 (99 chars) ---
You must return the item in its original packaging. Final-sale items are not eligible for a refund.
--- chunk 3 (105 chars) ---
Final-sale items are not eligible for a refund. Gift cards never expire and cannot be exchanged for cash.
--- chunk 4 (120 chars) ---
Gift cards never expire and cannot be exchanged for cash. To start a return, open the order page and choose Return item.
--- chunk 5 (54 chars) ---
Damaged-on-arrival claims need photos within 48 hours.

===== vectors.top_k =====
refund-policy    0.9910
damaged-goods    0.9788
shipping-times   0.2353

===== bm25.BM25 =====
query: 'damaged refund'
  doc2 score=1.1063  package arrived damaged, request a refund
  doc1 score=1.0382  damaged refund policy proof of purchase receipt
  doc4 score=1.0382  damaged goods and shipping delay complaint refund

===== fusion.rrf =====
dense top: ['a', 'b', 'c', 'd']
bm25  top: ['c', 'a', 'e', 'b']
fused    : [('a', 0.0325), ('c', 0.0323), ('b', 0.0318), ('e', 0.0159), ('d', 0.0156)]

===== templates.PromptTemplate =====
You are a support agent for Acme.
Customer wrote: Where is my order #4471?
Answer in calm tone, under 80 words.
---
TemplateError: missing variables: ['max_words', 'ticket']; required but absent: ['max_words', 'ticket']

===== json_repair.call_with_repair =====
validated: {'name': 'Ada', 'score': 87}

===== tool_loop.run_tool_loop =====
text='Order A17 has shipped.' steps=2 tool_calls=1 stop=final

===== metrics.evaluate =====
recall@k  1.0000
mrr       0.4167
ndcg@k    0.5620

===== lru.LRUCache =====
value-for-a | value-for-a | loads: 1
value-for-a | loads: 2
value-for-a | loads: 5 (reloaded after eviction)

===== budget.pack_items =====
budget=30 reserve=5 used=25
packed:
  + Refunds are processed within five business days.
  + You must return items in original packaging.
  + Gift cards never expire and have no fees.
skipped:
  - Final-sale items cannot be refunded or exchanged.
  - Damaged-on-arrival claims require photos within 48 hours.

===== eval_diff.diff_runs =====
regressions: ['c2: 0.80 -> 0.40 (-0.40)']
improvements: ['c3: 0.50 -> 0.60 (+0.10)']
unchanged: ['c1', 'c4', 'c5']
mean delta=-0.060 95% CI=(-0.220, +0.060)

===== bpe.learn_merges =====
merges: [('t', 'h'), ('th', 'e'), ('a', 't'), ('c', 'at'), ('o', 'g'), ('s', 'at'), ('o', 'n'), ('d', 'og')]
tokens: ['the', 'cat', 'sat']

===== attention.scaled_dot_product_attention =====
attention weights (causal):
   [1.0, 0.0, 0.0]
   [0.3302, 0.6698, 0.0]
   [0.2483, 0.2483, 0.5035]
output:
   [10.0, 0.0]
   [3.3024, 6.6976]
   [5.0, 5.0]

The career_kit package so far:

text
career-prep/
β”œβ”€β”€ career_kit/
β”‚   β”œβ”€β”€ __init__.py
β”‚   └── drills/
β”‚       β”œβ”€β”€ __init__.py
β”‚       β”œβ”€β”€ attention.py        # 4.17 softmax + scaled dot-product attention
β”‚       β”œβ”€β”€ bm25.py             # 4.7 BM25 from scratch
β”‚       β”œβ”€β”€ bounded.py          # 4.2 async bounded-concurrency runner
β”‚       β”œβ”€β”€ bpe.py              # 4.16 mini BPE tokenizer
β”‚       β”œβ”€β”€ budget.py           # 4.14 token-counting budget packer
β”‚       β”œβ”€β”€ chunker.py          # 4.5 sentence-aware chunker with overlap
β”‚       β”œβ”€β”€ eval_diff.py        # 4.15 diffing two eval runs
β”‚       β”œβ”€β”€ fusion.py           # 4.8 reciprocal rank fusion
β”‚       β”œβ”€β”€ json_repair.py      # 4.10 JSON repair/validation with retries
β”‚       β”œβ”€β”€ lru.py              # 4.13 LRU cache with TTL + single-flight
β”‚       β”œβ”€β”€ metrics.py          # 4.12 retrieval metrics
β”‚       β”œβ”€β”€ rate_limit.py       # 4.1 token-bucket rate limiter
β”‚       β”œβ”€β”€ retry.py            # 4.3 retry with backoff + jitter
β”‚       β”œβ”€β”€ run_all.py          # runs every demo, fixed seed
β”‚       β”œβ”€β”€ sse_parse.py        # 4.4 streaming SSE parser
β”‚       β”œβ”€β”€ templates.py        # 4.9 prompt template renderer
β”‚       β”œβ”€β”€ test_drills.py      # pytest suite (44 tests)
β”‚       β”œβ”€β”€ tool_loop.py        # 4.11 tool-call loop with budgets
β”‚       └── vectors.py          # 4.6 cosine top-k search
└── pyproject.toml              # created by uv init

Part 5: ML/LLM fundamentals β€” the question bank#

Reference

5.0 How to use this bank#

Seventy-seven questions, grouped by topic, each with a concise model answer hidden in a <details> block β€” the level of detail a strong candidate gives in 60–90 seconds β€” plus the module lesson that owns the depth and a difficulty tag (🟒 core, 🟑 intermediate, πŸ”΄ advanced) kept visible so you can filter before revealing. Don't memorise answers; learn the shape of each answer β€” definition β†’ mechanism β†’ trade-off β†’ example. Convert weak ones into flashcards (Part 2.2).

5.1 LLM basics (10 questions)#

1. What is a large language model? 🟒 (02.1)

Answer

A neural network trained on vast text to predict the next token, producing a probability distribution over vocabulary each step. Sampling from that distribution generates text. It is learned statistical prediction rather than a database lookup, and it can be wrong while sounding certain. Reasoning-style behaviour does emerge, and current "reasoning models" are trained to spend extra tokens thinking before they answer (02.8), but the interface is still next-token generation.

2. What is a token, and why does it matter? 🟒 (02.2)

Answer

The unit the model reads and bills: subword pieces (BPE), roughly 4 chars or ~0.75 words in English. Cost, latency, context limits and "lost in the middle" all scale with tokens, not words.

3. What's the difference between pre-training and fine-tuning? 🟒 (02.6, 13A.8)

Answer

Pre-training teaches language and world knowledge on huge corpora; fine-tuning adapts behaviour on narrower data. You almost never pre-train; fine-tuning is for style/format/domain, not knowledge injection.

4. What are embeddings? 🟒 (02.3, 06.1)

Answer

Dense vectors where semantic similarity β‰ˆ geometric proximity, produced by an encoder model. They're the retrieval substrate β€” search, clustering, dedup.

5. What is a context window? 🟒 (02.7)

Answer

The max tokens a model sees in one call, including prompt + retrieved docs + tool results + its own output. Everything outside is invisible; exceeding it errors or truncates.

6. What are logits and temperature? 🟑 (02.5)

Answer

Logits are raw scores per next token; softmax turns them into probabilities. Temperature divides logits before softmax: <1 sharpens (more deterministic), >1 flattens (more varied), 0 β‰ˆ greedy. Add the 2026 caveat: many current frontier APIs reject or ignore temperature and top_p (02.5 Part 6), so check what your provider allows rather than assuming the knob exists.

7. What is a transformer? 🟒 (02.4)

Answer

The architecture: stacked blocks of attention (tokens weigh each other) + feed-forward layers, with positional info. Attention is the core mechanism.

8. What does "the model hallucinate" mean technically? 🟒 (02.10, 07.4)

Answer

It produces fluent text that isn't grounded in truth or provided context β€” because it's optimised for plausible continuation, not truth. Mitigations: grounding (RAG), constraints (structured output), verification (evals/critics), and abstention ("I don't know") behaviour that you test for. Lowering temperature, where the provider still exposes it, reduces variation but does not make a model truthful.

9. What's the difference between open-weight and API models? 🟑 (02.9, 11C.6)

Answer

Open weights (Llama, Mistral, Qwen) you can self-host/fine-tune but own ops cost; API models (frontier proprietary) you call but don't control. Trade-off: cost/privacy/control vs capability and zero ops.

10. What is a system prompt? 🟒 (04.5, 12.2)

Answer

Instructions setting role, rules and output format, sent each call. It shapes behaviour but isn't a security boundary β€” prompt injection can override weak ones.

5.2 Prompting and context (10 questions)#

11. What makes a good prompt? 🟒 (04.1)

Answer

Clear task, relevant context, explicit constraints, output format, examples when ambiguity is costly. Structure beats verbosity; the prompt is an API contract.

12. What is few-shot prompting? 🟑 (04.2)

Answer

Including input→output examples in the prompt to teach format/behaviour without weight updates. Powerful for classification/extraction; costs tokens and can bias toward example distribution.

13. What is chain-of-thought? 🟑 (04.3, 02.8)

Answer

Asking the model to show reasoning steps before the answer. Improves multi-step accuracy; costs tokens; can produce plausible-but-wrong rationales (don't trust the trace as ground truth).

14. What is prompt injection? πŸ”΄ (02.10, 12.2)

Answer

Malicious instructions embedded in data the model processes (a web page, a user message, a tool result) that hijack its behaviour. Defence is architectural: least-privilege tools, input/output separation, instruction hierarchy where supported, human approval for consequential actions.

15. What's "lost in the middle"? 🟑 (02.7, 04.6)

Answer

Models, especially on long inputs, often use information near the start and end of the context better than the middle (a finding from 2023 research; newer models are better, but it is not eliminated, so test on your own data). Mitigate: put critical instructions early, retrieved docs structured, relevant info repeated or re-ranked to the edges.

16. What is context engineering? 🟒 (04.6, 02.7)

Answer

Deliberately designing what goes into the context window: system prompt, retrieved chunks, tool results, history β€” within budget. It's the production skill behind "the model only knows what you put in front of it."

17. How do you handle long documents? 🟑 (05.6, 07.2)

Answer

Chunk + retrieve relevant pieces (RAG), summarise hierarchically, or use long-context natively with awareness of the middle-attention problem. Choice depends on doc count, query type and budget.

18. What's the difference between zero-shot and few-shot? 🟒 (04.2)

Answer

No examples vs examples in prompt. Zero-shot relies on instruction-following; few-shot teaches format. Few-shot usually wins on structure-sensitive tasks.

19. How do you version and test prompts? 🟑 (04.10, 10A.8)

Answer

Treat prompts as code: versioned files, eval suites before/after changes, changelog. A prompt change is a behaviour change β€” it needs regression testing like any deploy.

20. What are delimiters/structured sections for? 🟒 (04.4)

Answer

Marking boundaries between instructions, context and user data so the model can distinguish "what I'm told" from "what I'm shown" β€” a basic injection defence and clarity aid.

5.3 RAG and retrieval (12 questions)#

21. What is RAG? 🟒 (07.1)

Answer

Retrieval-Augmented Generation: retrieve relevant documents, put them in context, generate grounded answers. Grounds the model in your data without retraining.

22. Why not just fine-tune on your documents? 🟑 (13A.8, 07.1)

Answer

Fine-tuning teaches style/format; it doesn't reliably inject large, changing corpora as retrievable facts, and it can't cite sources or update without retraining. RAG gives freshness, citations, and per-source control.

23. How do you chunk documents? 🟑 (05.6, drill 4.5)

Answer

By structure (headers, sections) when available, else sentence/paragraph windows with overlap. Chunk size trades specificity vs context; there's no universal optimum β€” eval it.

24. What is an embedding model and how is it different from the LLM? 🟒 (06.1)

Answer

An encoder that maps text to a vector for similarity search; the LLM generates. Different models, different jobs β€” you embed queries/docs for retrieval, then the LLM reads the results.

25. What is cosine similarity? 🟒 (06.3, drill 4.6)

Answer

Cosine of the angle between vectors; 1 = same direction, 0 = orthogonal, βˆ’1 = opposite. Standard for comparing embeddings because it ignores magnitude.

26. What is BM25 and when do you need it? 🟑 (06.7, drill 4.7)

Answer

A lexical ranking function (term frequency Γ— inverse document frequency Γ— length normalisation). Needed for exact-match queries β€” SKUs, error codes, names β€” where dense retrieval misses. Hybrid search combines both.

27. What is hybrid search and RRF? 🟑 (06.8, drill 4.8)

Answer

Running dense + lexical retrievers and fusing their ranked lists β€” RRF (reciprocal rank fusion) is the standard no-tuning method: sum 1/(k+rank). Beats either alone on mixed query types.

28. What is a vector index (HNSW/IVF)? πŸ”΄ (06.4)

Answer

An approximate-nearest-neighbour structure trading a little recall for massive speed on millions of vectors. HNSW = graph-based, high recall, more memory; IVF = inverted lists, faster build, needs tuning.

29. How do you evaluate retrieval quality? 🟑 (06.10, drill 4.12)

Answer

Labelled qrels β†’ recall@k, precision@k, MRR, nDCG. Each measures a different thing; you need them before tuning.

30. What is a reranker? 🟑 (06.9)

Answer

A second-stage model that scores the top-k retrieved docs more precisely than the cheap first stage. Buys accuracy at extra latency/cost β€” apply to top 20–50, not the whole corpus.

31. What causes retrieval failure? 🟑 (07.10, 06.10)

Answer

Bad chunks (split mid-fact), query/document vocabulary mismatch, embedding model mismatch to domain, index staleness, or the answer simply not being in the corpus. Diagnose before tuning β€” measure first.

32. What's the difference between naive, advanced and modular RAG? πŸ”΄ (07.1, 07.8)

Answer

Naive = retrieve→stuff→generate. Advanced = query rewriting, reranking, iterative retrieval. Modular = decomposed components (router, multiple retrievers, self-RAG). Escalate complexity only when evals justify it.

5.4 Evals and quality (10 questions)#

33. Why are evals the bottleneck in LLM work? 🟒 (10A.1)

Answer

Models are probabilistic; "it worked in the demo" means nothing at scale. Evals are how you know a prompt/model/pipeline change helped or hurt β€” they're the regression suite for non-deterministic software.

34. What's the difference between offline and online evals? 🟑 (10A.9)

Answer

Offline = curated test sets run before deploy (fast, controlled, may not match production). Online = production traffic signals β€” user feedback, A/B tests, sampled LLM-judge scores (realistic, slower, noisier). You need both.

35. What is an LLM-as-judge? 🟑 (10A.4, 10A.5)

Answer

Using a model to score another model's output against a rubric. Scales human judgement; risks: position bias, verbosity bias, self-preference, rubric drift. Mitigate with calibrated rubrics, pairwise comparison, human spot-checks.

36. What metrics matter for a RAG system? 🟑 (10A.6)

Answer

Retrieval: recall@k, nDCG. Generation: faithfulness (is the answer grounded in retrieved docs?), answer relevance, citation accuracy. End-to-end: task success. Measure each stage separately or you can't localise failures.

37. How do you build an eval set? 🟑 (10A.2)

Answer

Start with real user queries (production logs), add adversarial/edge cases, label expected behaviour. Small and representative beats large and synthetic. Version it like code.

38. What's regression testing for prompts? 🟑 (10A.8, 11C.2)

Answer

Running the eval suite on every prompt/model/pipeline change; a score drop blocks deploy. Same CI discipline as code β€” the prompt is code.

39. How do you handle non-determinism in evals? 🟑 (10A.1, 06.10)

Answer

Run each case N times, report meanΒ±variance; reduce sampling variation where the provider allows it (many current models do not expose temperature); pairwise comparisons reduce variance; bootstrap CIs for deltas. A single run's score is noise.

40. What is a "good enough" eval threshold? πŸ”΄ (10A.1, 13A.6)

Answer

Domain-dependent; set by business cost of failure. A support bot tolerates lower faithfulness than a medical one. Define acceptable error rate with stakeholders, then engineer to it. There's no universal number.

41. How do you detect hallucination systematically? 🟑 (10A.4, 07.5)

Answer

Groundedness checks: does each claim trace to retrieved context? NLI-style entailment, citation verification, or judge-with-evidence. Plus user-report channels in production.

42. What is a red-team / adversarial eval? πŸ”΄ (12.8, 12.1)

Answer

Deliberately attacking the system: prompt injection, jailbreaks, edge-case inputs, distribution shift. Different from correctness evals β€” tests robustness, not accuracy.

5.5 Agents and tool use (10 questions)#

43. What is an agent vs a chain? 🟒 (08A.9)

Answer

A chain has a fixed sequence of steps; an agent decides its own steps at runtime based on observations. Agents are more flexible, less predictable, harder to eval and debug. Use the simplest thing that works.

44. What is a tool/function call? 🟒 (08A.2)

Answer

A structured way for the model to request an action: it emits JSON {name, args}, your code executes it, result goes back into context, loop continues. The model never executes anything β€” it requests.

45. Why do agents need budgets? 🟒 (08A.2, drill 4.11)

Answer

Without max_steps/max_tokens/max_cost, a confused agent loops forever burning money. Budgets are circuit breakers β€” non-negotiable in production.

46. What is the tool-call loop? 🟒 (08A.2, drill 4.11)

Answer

Model β†’ tool request β†’ execute β†’ result β†’ model β†’ … until final answer or budget. The transcript grows each round β€” context management is the hard part.

47. How do you keep agents safe? πŸ”΄ (12.6, 08A.14)

Answer

Least-privilege tools (read-only by default), human approval for writes/consequential actions, input validation on tool args, output filtering, sandboxed execution for code tools. Assume the model will try things you didn't intend.

48. What is MCP? 🟑 (08E.1)

Answer

Model Context Protocol: a standard for exposing tools/resources to models via a uniform interface. Like USB-C for tool integrations β€” one server, many clients.

49. How do you evaluate an agent? πŸ”΄ (10A.7)

Answer

Trajectory evals (did it take reasonable steps?), task success (did it achieve the goal?), efficiency (steps/cost vs optimal). Single-answer metrics miss agent-specific failures like loops and unnecessary tool calls.

50. What makes a good tool description? 🟑 (08A.6)

Answer

Clear name, what it does, when to use it, argument schema with descriptions, example call. The model chooses tools by description β€” vague descriptions cause wrong tool selection.

51. What is ReAct and why does it matter? 🟑 (08A.10)

Answer

Reasoning + Acting: interleave thought and action steps. The reasoning trace helps the model plan; it's also your debug window when the agent fails.

52. When should you NOT use an agent? 🟒 (08A.9)

Answer

When the task is deterministic (use code), when a single well-crafted prompt suffices, or when reliability requirements exceed what non-deterministic planning can deliver. Agents are a tool, not a default.

5.6 Fine-tuning, safety and production (8 questions)#

53. When is fine-tuning worth it? πŸ”΄ (13A.8)

Answer

When you need consistent style/format at scale, domain vocabulary the base model lacks, or behaviour that prompting can't reliably produce. NOT for knowledge injection (that's RAG) or small datasets (prompting wins). Cost: data, evals, maintenance.

54. What's the difference between SFT and RLHF/DPO? πŸ”΄ (02.6)

Answer

SFT = supervised fine-tuning on input→output pairs (imitation). RLHF = human preference optimisation (rewards). DPO = direct preference optimisation — simpler RLHF alternative. SFT is cheapest and most common for format/style.

55. What are guardrails? 🟒 (12.5)

Answer

Input/output filters: PII detection, topic restrictions, jailbreak detection, format enforcement. Layers around the model, not inside it β€” defence in depth.

56. What is prompt injection vs jailbreak? 🟑 (12.2, 12.3)

Answer

Injection = instructions in data hijack behaviour (data→instruction confusion). Jailbreak = user-crafted inputs bypass safety training (instruction→policy override). Different vectors, different defences — both need layered mitigation.

57. How do you handle PII in LLM systems? 🟑 (12.4)

Answer

Detect and redact before sending to API, use enterprise/API agreements with no-training clauses, local models for sensitive data, audit logs without content. Know your provider's data policy.

58. What's the latency/cost trade-off in model choice? 🟑 (11B.1, 11B.5)

Answer

Frontier models: best quality, highest cost/latency. Small/fast models: cheaper, higher throughput, lower ceiling. Route by task difficulty β€” easy queries to small model, hard ones to frontier. Measure, don't assume.

59. What is model drift / versioning? 🟑 (02.9, 10A.8)

Answer

Providers update models; behaviour can change silently. Pin versions where possible, re-run evals on version change, maintain fallback models. Your eval suite is your drift detector.

60. How do you estimate LLM API costs? 🟑 (03.7)

Answer

tokens_in Γ— input_price + tokens_out Γ— output_price + retries/overhead. Output tokens usually cost more, and reasoning ("thinking") tokens are normally billed as output, so they count; cached input tokens are usually discounted. Cache aggressively, batch where possible, monitor per-feature spend, and read the usage object rather than estimating (02.2, 03.7).

5.7 Reasoning and advanced (8 questions)#

61. What is a reasoning/thinking model? 🟑 (02.8)

Answer

A model trained to generate extended internal reasoning (chain-of-thought as native behaviour) before answering β€” better at math, code, multi-step logic, at higher latency/cost.

62. What is test-time compute? πŸ”΄ (02.8)

Answer

Spending more compute at inference (longer reasoning, sampling multiple candidates, self-verification) to improve quality on hard problems β€” the "slow thinking" knob alongside model size.

63. What are MoE models? πŸ”΄ (02.1, 02.4)

Answer

Mixture-of-Experts: many specialist sub-networks, a router activates a few per token β€” large total capacity, manageable per-token cost. Many recent large open-weight models are MoE (check the model card).

64. What is quantization? πŸ”΄ (02.1, 11C.6)

Answer

Reducing weight precision (FP16β†’INT8β†’INT4) for smaller/faster inference with modest quality loss. Enables self-hosting big models on consumer hardware.

65. What is KV cache and why does it matter? πŸ”΄ (02.4, 11C.6)

Answer

Caching key/value tensors of processed tokens so generation doesn't recompute them β€” the main speedup for long contexts and the memory bottleneck for concurrency.

66. What is speculative decoding? πŸ”΄ (11B.1)

Answer

A small draft model proposes tokens, the big model verifies them in parallel β€” papers and serving frameworks commonly report roughly 2–3Γ— decoding speedups (workload-dependent) with the same output distribution as the big model alone. Production inference optimisation.

67. What is RL for LLMs (RLHF/PPO/GRPO)? πŸ”΄ (02.6, 02.8)

Answer

Reinforcement learning from human feedback or AI feedback to optimise for preferences/rewards beyond imitation. DPO simplified it; GRPO is the recent efficient variant. Research-level but interviewers probe awareness.

68. What's the difference between pre-training, mid-training and post-training? πŸ”΄ (02.6)

Answer

Pre-train = broad corpus next-token. Mid-training = continued training on targeted data (code, reasoning, domain) before alignment. Post-training = SFT/RLHF for instruction-following and safety. Modern pipelines use all three.

5.8 Scenario and practical questions (9 questions)#

Applied-AI loops increasingly replace "define X" with "here is a situation, what do you do?" These are the scenario shapes that recur in practical rounds and in the deep-dive halves of fundamentals rounds. Answer them as method first, then specifics: what you would measure, what you would change, how you would know it worked. 14B.7 Part 7 works full diagnosis examples.

69. Answer quality dropped after a release. What do you do in the first hour? 🟑 (14B.7 Part 7, 07.10, 10A.8)

Answer

Start with what changed: prompt version, model alias or version, chunking or embedding re-index, retriever settings, tool schemas, upstream data. Pull traces for a handful of failing queries and split each failure into retrieval (the right evidence was not in context) or generation (it was there and the answer ignored or distorted it). Re-run your regression eval on the old and new configurations to turn "feels worse" into a per-case diff. If the diff confirms a regression, roll back the single suspect change first, then fix forward behind an eval gate. Without an eval set, say so, and say you would build a small one from the failing traces before touching anything else.

70. How does prompt caching work, and when does it not help? 🟑 (03.7, 11.3)

Answer

Providers can reuse the work already done on an identical prefix of your prompt and bill repeated prefix tokens at a discount, and they usually cut latency too. It only helps if the stable material (system prompt, tool definitions, static reference documents) comes first and the variable material (the user's question, retrieved chunks, timestamps) comes last. It does not help when prompts are unique, when something variable (a timestamp, a request ID) sits at the top and breaks the prefix, or when calls are too infrequent for the cached entry to survive. Minimum prefix lengths, time-to-live and the way you opt in differ by provider and change often, so state that you would check the current provider docs.

71. Structured output: constrained decoding, or "ask for JSON" and validate? 🟑 (03.4, drill 4.10)

Answer

Prefer the provider's schema-constrained output (or strict tool schemas) when it is available: the shape is then guaranteed. Still validate meaning: a schema guarantees field names and types, not truth, so keep business-rule checks, handle refusals and truncated output (a cut-off response is not valid JSON however well it was constrained), and keep the validate-and-retry path for providers or modes where constraints are not available. Say what you would log on failure (the raw output, the schema version, the error).

72. Long context or RAG for a 2,000-page policy library? 🟑 (07.1, 02.7)

Answer

It depends on size, change rate, permissions and cost. Whole-corpus long context suits a small, stable set where the model needs cross-document reasoning; every call pays for every token (caching softens this) and answer quality can degrade as irrelevant text grows. RAG suits a large or frequently changing corpus, per-user permissions, and the need to cite sources. Hybrid designs are common: retrieve, then give the model whole relevant documents rather than tiny chunks. Whatever you pick, say you would compare the options on your own eval set rather than trusting a context-window number.

73. You are building a new LLM feature and have no data. How do you start evals? 🟑 (10A.2, 10.3)

Answer

Write 30–50 realistic cases by hand from the product spec and from stakeholders or support logs, including a few edge and adversarial ones, and write down what "pass" means for each. Use deterministic code checks wherever the output allows (schema valid, citation present, no forbidden content), and an LLM judge with a written rubric for the rest, validated against a sample of human labels before you trust it. Run it before launch, then grow the set from every production failure. Name the trap: an eval set written by the same person who wrote the prompt flatters the prompt.

74. An agent took an action it should not have (sent an email, changed a record). What do you change? πŸ”΄ (12.6, 08A.14)

Answer

Fix the system, not the prompt alone. Reduce privilege (read-only by default, narrow scopes per tool), put a human approval step in front of irreversible or external actions, add a dry-run or preview mode, make tools idempotent, and write an audit log of every call with its arguments. Treat tool outputs and retrieved text as untrusted data that may contain instructions. Add the incident as a regression case to your eval and red-team set, and say how you would detect the same class of failure in production traces.

75. Cut the LLM bill by half without hurting quality. How? 🟑 (11B.1, 11B.5, 03.7)

Answer

Measure first: cost per feature and per request, split into input, cached input, output and reasoning tokens. Then pull the levers in order of risk: stable-prefix prompt caching, shorter prompts and tighter retrieval, response caching where answers repeat, lower reasoning effort or output limits, a batch API for non-urgent work, then routing easy requests to a smaller model. Put a quality guardrail on every change (your eval set plus a production metric) and ship them one at a time so you know which lever paid off.

76. Your provider has an outage or starts returning rate-limit errors. What happens to your users? 🟑 (03.8, 11C.3)

Answer

Timeouts on every call; retries with exponential backoff and jitter only for retryable errors (429, 5xx, timeouts), honouring Retry-After; a circuit breaker so you stop hammering a failing dependency; a fallback model or second provider through a gateway for requests where it is acceptable; a queue for non-urgent work; and graceful degradation (cached or simpler answers, a clear message) for the rest. Say that you would rehearse the failover, because an untested fallback usually fails on the day.

77. How do you use AI coding assistants in your own work, and how do you verify what they produce? 🟒 (1.3, 14B.9 Part 4)

Answer

Give small, well-specified tasks with the relevant files and constraints; read every diff as you would a colleague's pull request; run the tests and add tests for the behaviour you care about; check anything that depends on a library version or API against the official docs because assistants can invent or outdate calls; keep secrets and customer data out of prompts unless your employer's policy allows it; and own the result, meaning you can explain every line you merge. Interviewers use this question to separate people who direct tools from people who paste output.


Part 6: Software-engineering fundamentals β€” rapid review#

Reference

These are the questions that appear in almost every engineering interview regardless of AI focus. The answers below are the shape a strong candidate gives β€” mechanism, trade-off, when-it-breaks. Depth lives in your own experience; this is the review checklist.

6.1 HTTP and APIs (8 questions)#

  1. GET vs POST vs PUT vs PATCH vs DELETE? 🟒 β€” GET reads (safe, idempotent, cacheable), POST creates/triggers (not idempotent), PUT replaces a resource wholesale (idempotent), PATCH partially updates (not necessarily idempotent), DELETE removes (idempotent). The verb encodes intent β€” servers and intermediaries rely on it.
  2. What are status codes that matter? 🟒 β€” 200 OK, 201 Created, 204 No Content, 301/302 redirects, 400 bad request, 401 unauthenticated, 403 forbidden, 404 not found, 409 conflict, 422 unprocessable, 429 rate limited, 500 server error, 502 bad gateway, 503 service unavailable, 504 gateway timeout. Know which are usually retryable (429, 503 and other transient 5xx, honouring Retry-After) vs permanent (most other 4xx).
  3. What is idempotency and why does it matter for APIs? 🟑 β€” An operation that produces the same result whether run once or N times. Critical for retries β€” clients retry on timeouts, and a non-idempotent POST can double-charge. Solve with idempotency keys, natural keys, or upserts.
  4. What are headers that matter? 🟒 β€” Authorization, Content-Type, Accept, User-Agent, X-Request-Id (tracing), Retry-After (rate limits), ETag/If-None-Match (caching/optimistic concurrency), Idempotency-Key.
  5. What's the difference between authentication and authorisation? 🟒 β€” AuthN = who are you (credentials β†’ identity). AuthZ = what may you do (permissions on that identity). Confusing them is a classic security bug β€” "logged in" β‰  "allowed".
  6. What is CORS? 🟑 β€” Browser-enforced rule: a server must explicitly allow cross-origin requests via headers. It's a browser mechanism that relaxes the same-origin policy under the server's control; it is not an authentication or server-side access-control mechanism (curl ignores it). The dangerous misconfiguration isn't Access-Control-Allow-Origin: * itself β€” browsers reject * on credentialed requests β€” but reflecting arbitrary Origin values while sending Access-Control-Allow-Credentials: true.
  7. How do you version an API? 🟑 β€” URL versioning (/v1/, /v2/) is simplest and explicit; header/media-type versioning is cleaner but subtler. Deprecate with sunset headers and overlap windows β€” never break clients silently.
  8. What is a webhook and what are its failure modes? 🟑 β€” Serverβ†’server HTTP callback for events. Failure modes: no retries guarantee, ordering, signature verification, endpoint downtime. Always verify signatures, make handlers idempotent, return fast and process async.

6.2 Async, concurrency and Python (8 questions)#

  1. sync vs async vs threads vs processes? 🟒 β€” sync = one thing at a time. threads = OS-scheduled parallelism, GIL limits CPU parallelism in CPython but I/O threads work. async = cooperative multitasking on one thread, great for I/O-bound concurrency (network calls), terrible for CPU-bound. processes = true parallelism for CPU work. Pick by workload: I/O β†’ async or threads; CPU β†’ processes or native extensions.
  2. What is the GIL? 🟑 β€” Global Interpreter Lock: only one thread executes Python bytecode at a time. Consequence: threads don't speed up CPU-bound Python; they do help I/O-bound (the lock releases during I/O). Workarounds: multiprocessing, C extensions, or just use async for I/O. Python 3.13+ also offers an optional free-threaded build with the GIL disabled (docs.python.org/3/howto/free-threading-python.html, checked November 2026); the default builds still have the GIL, and many libraries are still catching up.
  3. What is asyncio.gather vs asyncio.wait vs asyncio.TaskGroup? 🟑 β€” gather runs coroutines concurrently, returns all results, propagates the first exception (without cancelling the other awaitables, which keep running). wait gives fine-grained control (FIRST_COMPLETED etc). TaskGroup (3.11+) is structured concurrency β€” cancels siblings on failure, cleaner semantics. Prefer TaskGroup for new code.
  4. What is a race condition and how do you prevent it? 🟑 β€” Two threads/tasks interleave such that the outcome depends on timing. Prevent with locks, atomic operations, immutable data, or actor-style single-owner patterns. In async, await points are the interleaving hazards β€” audit what's shared across awaits.
  5. What is a deadlock vs livelock? 🟑 β€” Deadlock = circular wait, everyone stuck. Livelock = everyone busy but nobody progresses (retrying the same failed action). Prevention: consistent lock ordering, timeouts, backoff+jitter (drill 4.3).
  6. What does threading.Lock vs asyncio.Lock vs multiprocessing.Lock differ on? 🟑 β€” They guard different concurrency domains β€” don't mix them. threading for threads, asyncio for coroutines (must await acquire), multiprocessing for processes (shared memory needs Manager or shared types).
  7. What is backpressure? 🟑 β€” When a fast producer overwhelms a slow consumer. Solutions: bounded queues, dropping with metrics, rate limiting upstream, or async pull-based flows. Unbounded queues just move the failure to OOM.
  8. What is a generator and when do you use one? 🟒 β€” Lazy iteration β€” produces values on demand, constant memory. Use for streams, large files, pipelines. yield makes any function a generator; yield from delegates.

6.3 Data and SQL (8 questions)#

SQL fundamentals live in 00.7 β€” these are the interview-shaped review questions.

  1. What is the difference between SQL and NoSQL? 🟒 β€” SQL = relational, schema-enforced, ACID, joins, mature. NoSQL = varied (document, key-value, wide-column, graph) β€” flexible schema, horizontal scale, weaker consistency guarantees. Choose by access patterns and consistency needs, not hype.
  2. What is an index and what are the trade-offs? 🟒 β€” A data structure (usually B-tree) making lookups fast. Trade-off: faster reads, slower writes + storage. Index columns you filter/sort/join on; too many indexes hurt write throughput.
  3. What is N+1 and how do you fix it? 🟑 β€” Fetching a list then one query per item β€” 101 queries for 100 rows. Fix: JOIN, IN clause batch fetch, ORM eager loading (select_related/prefetch_related), or dataloader pattern.
  4. What are transaction isolation levels? πŸ”΄ β€” Read Uncommitted β†’ Read Committed β†’ Repeatable Read β†’ Serializable, increasing isolation and decreasing concurrency. Default (usually Read Committed) allows anomalies like non-repeatable reads; Serializable prevents them at cost. Know which anomalies each prevents.
  5. What is a migration and why do they matter? 🟒 β€” Versioned schema changes applied in order β€” the difference between "it works on my machine" and reproducible deploys. Always write reversible migrations, test on realistic data volume, never hand-edit production schema.
  6. What is eventual consistency? 🟑 β€” Replicas converge to the same state asynchronously β€” reads may be stale briefly. Fine for feeds/counters; wrong for balances/permissions. Know which of your data needs strong consistency.
  7. What is a connection pool and why size it carefully? 🟑 β€” Reusing DB connections instead of opening per request β€” opening is expensive. Too small = queueing; too large = DB memory/connection exhaustion. Size β‰ˆ (cores Γ— 2) + spindles is a classic heuristic; measure under load.
  8. What is normalisation and when do you denormalise? 🟒 β€” Structuring tables to remove redundancy via keys β€” eliminates update anomalies. Denormalise deliberately for read performance (counters, materialised aggregates) when you can manage the consistency cost.

6.4 Caching, queues and reliability (8 questions)#

  1. What is caching and what are the strategies? 🟒 β€” Storing computed results to avoid recompute. Strategies: cache-aside (app checks cache first), read-through, write-through, write-behind. Key decisions: TTL, invalidation, stampede protection, what NOT to cache.
  2. What is a cache stampede / thundering herd? 🟑 β€” Many requests miss simultaneously and all recompute the same expensive value. Fixes: request coalescing/single-flight (drill 4.13), early expiry with jitter, stale-while-revalidate, locks.
  3. What is a message queue and when do you need one? 🟒 β€” Durable buffer decoupling producers from consumers β€” smooths bursts, enables retries, isolates failures. Use when work is async, bursty, or needs guaranteed delivery. Cost: operational complexity + at-least-once semantics.
  4. What is at-least-once vs exactly-once delivery? πŸ”΄ β€” At-least-once = message may be delivered more than once (duplicates possible); exactly-once is effectively impossible over a network β€” "effectively-once" via idempotent consumers + dedup. Design consumers to be idempotent.
  5. What is a circuit breaker? 🟑 β€” Stop calling a failing dependency for a cooldown period instead of retrying into a dead service. States: closed (normal), open (failing fast), half-open (probing recovery). Prevents cascading failure.
  6. What is a health check and what makes a good one? 🟑 β€” Endpoint reporting service liveness/readiness. Liveness = "am I alive" (restart if not); readiness = "can I serve traffic" (pull from rotation if not). Check dependencies carefully β€” a health check that hits the DB can kill the service when the DB hiccups.
  7. What is graceful degradation? 🟑 β€” Continuing to serve reduced functionality when dependencies fail β€” cached results, simpler model, fewer features β€” rather than hard-failing. Design for partial availability.
  8. What is observability and the three pillars? 🟒 β€” Metrics (aggregated numbers β€” latency, error rate), logs (event records), traces (request flow across services). You can't debug what you can't see β€” instrument before you need it.

6.5 Testing, debugging and code quality (9 questions)#

  1. What's the difference between unit, integration and e2e tests? 🟒 β€” Unit = one function/class, mocked deps, fast. Integration = components together, real-ish deps (test DB). E2E = full system, real deps, slow, brittle. Pyramid: many unit, fewer integration, few e2e.
  2. What makes a good test? 🟒 β€” Tests behaviour not implementation, one assertion concept per test, deterministic, fast, named for what it verifies. A test that breaks on refactor-without-behaviour-change is testing implementation.
  3. What's test-driven development and when is it worth it? 🟑 β€” Write failing test β†’ implement β†’ refactor. Worth it for well-understood requirements and bug fixes (write the failing test first); overhead for exploratory work. The discipline matters more than dogma.
  4. How do you debug a production issue? 🟑 β€” Reproduce β†’ isolate (bisect, logs, metrics) β†’ hypothesise β†’ fix β†’ verify β†’ postmortem. Resist the urge to guess-and-deploy; form a hypothesis and test it. The fix isn't done until you've confirmed it in prod.
  5. What is a code review and what do you look for? 🟒 β€” Peer review before merge: correctness, edge cases, security, readability, tests, performance. Review the code, not the person. "Why" questions catch more bugs than style nits.
  6. What is technical debt and how do you manage it? 🟑 β€” Deliberate shortcuts with future cost. Manage by making it visible (tickets, metrics), paying it down incrementally, and distinguishing "deliberate debt" from "accidental mess" β€” the latter compounds invisibly.
  7. What is a linter/formatter and why enforce it? 🟒 β€” Automated style/correctness checks (ruff, black, mypy). Consistency removes bikeshedding; type checkers catch whole classes of bugs before runtime. Enforce in CI, not by convention.
  8. What is a monorepo vs polyrepo? 🟑 β€” One repo for all code vs repo-per-service. Monorepo: atomic cross-service changes, shared tooling, simpler deps β€” harder access control and CI scaling. Polyrepo: isolation, independent deploys β€” version drift and coordination cost. Neither is universally better; the right answer depends on team size, tooling and release cadence.
  9. How do you use git when debugging a regression? 🟑 β€” git bisect binary-searches history to find the breaking commit automatically β€” git bisect run <script> runs your test at each step; then git show/git log -p on the culprit. Know rebase vs merge (rebase = linear history but rewrites commits; merge = preserves topology), why --force-with-lease exists (safer than --force β€” it fails if someone else pushed), and that a pull request is a reviewable unit: small, focused, describing why not just what. 00.3 and 00.4 own the full treatment.

6.6 Security and operations (6 questions)#

  1. What is the principle of least privilege? 🟒 β€” Grant only the minimum access needed for the task β€” for users, services, API keys, DB users. Reduces blast radius when credentials leak or code is compromised.
  2. What is a secret and how do you handle it? 🟒 β€” API keys, tokens, passwords β€” never in code, never in logs, never in git history. Use secret managers/env vars injected at runtime, rotate regularly, audit access.
  3. What is SQL injection and how do you prevent it? 🟒 β€” Untrusted input concatenated into SQL lets attackers run arbitrary queries. Prevent: parameterised queries/prepared statements always β€” never string-interpolate user input. ORMs don't save you if you use raw SQL carelessly.
  4. What is SSRF? 🟑 β€” Server-Side Request Forgery: the server fetches attacker-controlled URLs, reaching internal services. Prevent: URL allowlists, block private IP ranges, validate redirects, don't fetch user-supplied URLs blindly.
  5. What is a dependency and what's a supply-chain risk? 🟑 β€” Third-party code you depend on. Risks: malicious packages, compromised maintainers, typosquatting, unmaintained deps with known CVEs. Mitigate: pin versions, audit (pip-audit, npm audit), minimise deps, review new ones.
  6. What is a runbook and why write one? 🟑 β€” Documented procedure for common incidents β€” symptoms, diagnosis, mitigation, escalation. Turns 3am panic into a checklist; the person who wrote it probably isn't the person on call.

Part 7: Statistics and experiments β€” basics for AI engineers#

Reference

You will not be asked to derive the Central Limit Theorem. You will be asked "is this eval difference real or noise?", "how big a sample do you need?", and "how do you know the new prompt is better?" These are the questions behind every "the score went up 2%" claim.

7.1 The vocabulary that matters (10 questions)#

  1. What's the difference between mean, median and mode? 🟒 β€” Mean = arithmetic average (sensitive to outliers), median = middle value (robust), mode = most frequent. For skewed data β€” latencies, token counts β€” median beats mean every time.
  2. What's a percentile and why p95? 🟒 β€” The value below which X% of observations fall. p50 = median, p95 = "95% of requests were faster than this". p95/p99 matter for SLOs because they capture the tail users actually feel β€” the mean hides it.
  3. What's a confidence interval? 🟑 β€” A range the true value plausibly lies in given your sample, e.g. "accuracy 87% Β± 3% (95% CI)". Wider CI = less data or more variance. Overlapping CIs for two separate estimates do not by themselves prove there is no difference; for comparing two runs, compute a CI on the paired difference instead (drill 4.15).
  4. What's statistical significance and a p-value? 🟑 β€” Significance = the observed difference is unlikely under the null hypothesis (no real effect). p-value = the probability of seeing a result at least this extreme if the null hypothesis were true β€” not the probability that the null is true. p < 0.05 is convention, not magic β€” effect size and business impact matter more.
  5. What's a Type I vs Type II error? 🟑 β€” Type I = false positive (claiming an effect that isn't there β€” ship a "better" prompt that's actually worse). Type II = false negative (missing a real improvement). Which is worse depends on cost β€” in evals, Type I ships regressions.
  6. What's the difference between precision and recall? 🟒 β€” Precision = of what you retrieved/flagged, how much was relevant. Recall = of all relevant items, how much you found. They're in tension β€” tune the threshold to the cost of each error. (06.10)
  7. What's an A/B test and when is it overkill? 🟑 β€” Randomly split traffic between variants, measure the metric difference. Overkill when: traffic is too low for power, effect is obviously large, or you can answer cheaper with offline evals first. 13A.6 owns experimentation for LLM features β€” randomisation, holdouts, AI-specific traps.
  8. What is sample size / statistical power? πŸ”΄ β€” How many observations you need to detect a given effect size at a given confidence. Small effects need huge samples; big effects need few. Before an A/B test, compute required N β€” otherwise you'll run an underpowered test that can't answer the question.
  9. What's selection bias and survivorship bias? 🟑 β€” Selection bias = your sample isn't representative (only measuring completed queries, not abandoned ones). Survivorship = only seeing the things that "survived" (analysing successful sessions, ignoring failures). Both silently corrupt evals.
  10. What's the difference between correlation and causation? 🟒 β€” Correlation = two things move together; causation = one causes the other. Confounders (a third variable) create false correlations. "Prompt length correlates with quality" doesn't mean shortening prompts hurts β€” something else may drive both.

7.2 Applied to LLM evals (8 questions)#

  1. How do you know an eval score improvement is real? 🟑 β€” Paired per-case differences + confidence interval on the mean delta (drill 4.15). If the CI excludes zero, the improvement is probably real; if it includes zero, it's noise until proven otherwise.
  2. Why do you run evals multiple times? 🟑 β€” LLM outputs are non-deterministic β€” sampling randomness (and, for hosted models, silent backend changes) means the same input can score differently. N runs give you the distribution, not a point estimate. Report mean Β± spread, not a single number.
  3. What's a good eval set size? 🟑 β€” Smallest set that covers your failure modes β€” a few hundred well-chosen cases often beats 10,000 random ones (a rule of thumb, not a law; the number depends on how small a difference you must detect). Stratify by query type, difficulty, edge cases. Add cases for every production failure you find.
  4. How do you detect eval overfitting? πŸ”΄ β€” If you tune to your eval set and it keeps rising while production doesn't, you're overfitting β€” like training accuracy vs test accuracy. Hold out a separate validation set, rotate eval cases, watch for memorised answers.
  5. What's inter-annotator agreement and why care? πŸ”΄ β€” When humans label eval data, do they agree? Low agreement = your "ground truth" is noisy β€” you can't measure a model against a ruler that wobbles. Measure with Cohen's kappa before trusting labels.
  6. What's a confusion matrix? 🟒 β€” TP/FP/FN/TN counts β€” the foundation for precision/recall/F1. For multi-class, one-vs-rest or per-class matrices. Know which cell matters for your cost model.
  7. How do you handle class imbalance in evals? 🟑 β€” Rare events (jailbreaks, PII leaks) need oversampling in the eval set or weighted metrics β€” a 99% accuracy on 1% positives is meaningless. Report per-class metrics, not just accuracy.
  8. What's a good stopping rule for eval tuning? 🟑 β€” Stop when: eval gains plateau, production metrics disagree with eval (overfitting), or marginal improvement < cost of the change. Evals guide, they don't decide β€” business metrics do.

7.3 Thinking like a data person (6 questions)#

  1. What's the difference between descriptive, diagnostic, predictive and prescriptive analytics? 🟒 β€” What happened β†’ why β†’ what will happen β†’ what should we do. LLM evals are mostly diagnostic (why did it fail?) feeding prescriptive (what to change).
  2. What is a funnel and where does LLM quality fit? 🟑 β€” User journey stages with conversion rates. LLM quality affects specific stages β€” retrieval failure kills before generation; bad answers kill at trust/retention. Map your metric to the stage it affects.
  3. What's cohort analysis? 🟑 β€” Comparing groups over time (users by signup week, by feature flag). Reveals whether changes help new vs existing users differently β€” essential for rollout decisions.
  4. What is a leading vs lagging indicator? 🟑 β€” Leading = predicts future (eval scores predict user satisfaction); lagging = confirms past (retention, revenue). You want leading indicators for fast iteration, lagging for validation.
  5. What's the difference between a metric and a proxy? 🟑 β€” A metric measures what you care about; a proxy correlates with it. "LLM-judge score" is a proxy for "user satisfaction" β€” useful but imperfect. Know what your proxy actually measures.
  6. How do you communicate uncertainty to stakeholders? 🟒 β€” "The new prompt improved eval score by 3% Β± 2% (95% CI) β€” likely real but modest; production impact still to be confirmed by an A/B test" beats "it got better" every time. Numbers with error bars are credibility.

Real failure modes, each with the fix. These are the things that sink otherwise-qualified candidates.

Mistake Why it fails The fix
Starting to code before clarifying You solve the wrong problem beautifully Restate the problem, ask 2–3 clarifying questions, get an example β€” then code (3.1)
Silent problem-solving Interviewers score process, not just answers; silence reads as flailing Narrate: "I'm considering X because…, the trade-off is…"
Memorising solutions instead of patterns Interviewers vary the problem; recall fails, pattern-recognition survives Learn the 15 patterns, practise recognising them (3.2)
Ignoring edge cases Empty input, single element, duplicates, negatives, unicode β€” the classics Name them during clarify; test them explicitly before declaring done
No complexity analysis "It works" isn't enough; O(n²) on 10⁡ items times out in production State time+space for every solution, justify the trade-offs
Assuming AI tools are allowed Using AI in a no-AI round is misrepresentation β€” detectable and offer-ending Ask the recruiter; when unclear, assume forbidden (1.3)
Cramming the night before Shallow, forgettable, anxiety-producing Spaced repetition over weeks; the day before is retrieval, not learning (2.1)
Practising only alone No pressure, no feedback, no calibration Mock interviews with peers and stronger candidates (2.3)
Skipping fundamentals to drill algorithms LLM-specific questions are the core of the role, not a soft extra Balance coding drills with the Part 5 bank
Treating evals as optional "It worked in the demo" doesn't scale; you can't defend a number you didn't measure Build eval habits early β€” they're the engineering rigor that distinguishes seniors
Writing clever code Interviewers can't debug what they can't read; cleverness is a liability Optimise for clarity first, then performance β€” the routine in 3.1 enforces this
Not asking questions at the end Signals disinterest; wastes a chance to assess fit Prepare 2–3 questions about team, challenges, success metrics (14B.8)

Common misconceptions#

Misconception Reality
"AI engineers don't need to code." They code constantly β€” the difference is what they code (evals, pipelines, retrieval, agents) and that they must also understand the models. The drills in Part 4 are exactly this work.
"LeetCode-hard is the bar." Most AI-engineer loops weight practical Python, system thinking and LLM fundamentals above exotic algorithms. Patterns matter; the 200th hard problem rarely does.
"I can use AI in the interview." Sometimes β€” policies genuinely differ by company and round. The only safe answer is to ask (1.3).
"A take-home means working alone for days." Many are timed (2–4 hours) or paired; AI use is often restricted. Read the instructions β€” they tell you the rules. (14B.8)
"Knowing the material is enough." Performance under pressure is a separate skill β€” communication, composure, time management. Mocks and the rubric in 2.6 train this explicitly.
"The interviewer is judging me." They're assessing evidence β€” your process, reasoning and communication are the evidence. A well-run failure beats a lucky pass.
"I should memorise model answers." Interviewers hear memorised answers instantly. Learn the shape β€” mechanism, trade-off, example β€” and adapt it live.

Key takeaways#

  • There is no single AI-engineer interview loop β€” processes vary by company, team and level. Read the company's published process, ask the recruiter, and prepare for the superset (Part 1).
  • AI-tool policies differ by company and round β€” the only safe default is to ask before assuming (1.3).
  • Preparation is a system, not an event β€” time-boxed plans, deliberate practice, spaced repetition, mocks with feedback, tracked weak areas and rest (Part 2).
  • The problem-solving routine matters more than any single algorithm β€” clarify, brute-force, optimise, code, test, extend β€” run it out loud every time (3.1).
  • The pattern catalogue is small and learnable β€” ~15 patterns cover most problems; recognise them under pressure, don't memorise solutions (3.2).
  • Python pitfalls are predictable β€” mutable defaults, late binding, is vs ==, recursion limits β€” know them cold (3.4).
  • LLM-flavoured drills are the differentiator β€” seventeen pure-stdlib modules covering rate limiting, concurrency, streaming, chunking, retrieval, evals, caching and the tool loop β€” the actual work of an AI engineer (Part 4).
  • Fundamentals are the floor β€” 77 ML/LLM questions, 47 SWE questions and 24 statistics questions cover the breadth every loop probes (Parts 5–7).
  • Evals and statistics are the senior signal β€” knowing how to measure whether something works is what separates engineers who ship demos from engineers who ship systems.

Terms introduced in this lesson#

Term One-line definition
Token bucket Rate-limiting algorithm allowing bursts up to capacity, refilling continuously
Bounded concurrency Running N tasks with at most limit in flight (semaphore pattern)
Exponential backoff + jitter Retry strategy with growing delays randomised to prevent thundering herds
SSE (Server-Sent Events) One-way streaming protocol used by LLM APIs
BM25 Lexical ranking function combining term frequency, inverse document frequency and length normalisation
RRF (Reciprocal Rank Fusion) Score-free method for merging ranked lists via 1/(k+rank)
Single-flight Collapsing concurrent identical requests into one execution
LRU cache Evicts least-recently-used items; combined with TTL for staleness
nDCG Normalised discounted cumulative gain; graded-relevance ranking metric
BPE (Byte-Pair Encoding) Subword tokenisation via iterative pair merging
Scaled dot-product attention The core transformer mechanism: softmax(QKα΅€/√d)V
Mock interview Practice interview with a peer or paid interviewer, scored on a rubric
Spaced repetition Reviewing material at increasing intervals to exploit the forgetting curve
Interleaving Mixing problem types rather than blocking by pattern
Retrieval practice Recalling information rather than re-reading it (stronger retention)

Exercises#

  1. Run the drills. uv run python career_kit/drills/run_all.py β€” verify the output matches 4.18. Then run uv run pytest career_kit/drills/test_drills.py β€” all 44 tests should pass. (15 min)
  2. Extend one drill. Pick the rate limiter (4.1) or the tool loop (4.11) and add one extension from its "Extension questions" list β€” write a test for it. (45 min)
  3. Solve one pattern problem cold. Pick a problem from 3.2 you haven't seen β€” time-box 30 minutes, narrate your reasoning aloud (record it), then compare to the pattern. (30 min + review)
  4. Solve eight drills timed. Pick eight drills (e.g. 4.1, 4.3, 4.4, 4.7, 4.8, 4.11, 4.12, 4.15), give each 30 minutes using the 3.1 routine, and narrate aloud β€” then compare against the reference and its tests. (4 hours across the week)
  5. Mock fundamentals. Have a peer ask you 10 random questions from Part 5 β€” answer in 60–90 seconds each, no notes, answers hidden until you've tried. Score yourself on completeness + accuracy. (30 min)
  6. Write five new LLM-flavoured problems. Author your own interview problems β€” problem statement, reference solution, pytest tests and complexity analysis β€” and swap them with a peer to solve under time pressure. This is the highest-signal prep there is: writing the question teaches you what interviewers probe. (ongoing)
  7. Build a flashcard deck. Convert your 10 weakest Part 5/6/7 answers into Anki cards or a Markdown file β€” review daily for a week. (ongoing)
  8. Scenario drill. Answer questions 69–77 (5.8) aloud in three minutes each, method first (what you would measure, what you would change, how you would know it worked), then check against the model answer. Rewrite any answer that gave a technique without a way to verify it. (45 min)

Check yourself#

  1. What are the four stages of OpenAI's published interview process, and what's the engineering bar for the final loop? (See 1.1)
  2. Why must you ask about AI-tool policy rather than assume? Give two examples of policies that differ. (See 1.3)
  3. What's the problem-solving routine, and why does it matter more than knowing the answer? (See 3.1)
  4. Name three Python pitfalls that appear in every coding interview. (See 3.4)
  5. What does the career_kit/drills package contain, and why is it pure standard library? (See 4.0)
  6. What's the difference between recall@k, MRR and nDCG? (See 4.12)
  7. Why does a tool-call loop need budgets? (See 4.11)
  8. What's the difference between precision and recall, and when do you tune toward each? (See 7.1)
  9. How do you know an eval improvement is real vs noise? (See 4.15 and 7.2)
  10. What's the mock-interview scoring rubric, and how do you use it? (See 2.6)
  11. Answer quality dropped after a release. What do you check first, and what do you avoid doing first? (See 5.8, question 69)
  12. Why does asyncio.gather with default settings leak work when one task fails, and what are two fixes? (See 4.2)

Further resources#

  • OpenAI Interview Guide β€” https://openai.com/interview-guide/ β€” published process, skills-assessment formats, AI-tool expectations vary by interview
  • Anthropic Careers β€” https://www.anthropic.com/careers β€” interview format, accommodations, scam awareness
  • Anthropic Candidate AI Guidance β€” https://www.anthropic.com/candidate-ai-guidance β€” stage-by-stage AI policy
  • Anthropic: Designing AI-resistant technical evaluations (Tristan Hume, 21 January 2026) β€” https://www.anthropic.com/research/AI-resistant-technical-evaluations β€” how one employer redesigned a take-home because models kept matching candidates
  • interviewing.io β€” https://interviewing.io/ β€” anonymous mocks with senior engineers, company process guides, free AI interviewer
  • Pramp β€” https://www.pramp.com/ β€” peer mock interviews (the site says sessions are hosted on Aced Practice and are free, checked 11 November 2026; check what is currently offered)
  • NeetCode β€” https://neetcode.io/ β€” NeetCode 150/250 problem lists, pattern-grouped, company-tagged
  • Cracking the Coding Interview (Gayle Laakmann McDowell) β€” the canonical coding-interview book; patterns and communication
  • Designing Data-Intensive Applications (Martin Kleppmann) β€” the systems fundamentals behind Part 6
  • 14B.7 β€” the system-design round this lesson doesn't cover
  • 14B.8 β€” take-homes, behavioural rounds, project deep-dives and offers

What to do this week#

  • Pick your runway (2/6/12 weeks) and write your prep plan using 2.1
  • Run career_kit/drills/run_all.py and uv run pytest career_kit/drills/test_drills.py β€” verify everything works
  • Do drill 4.1 (rate limiter) or 4.11 (tool loop) before reading the solution β€” time-box 30 minutes, narrate aloud
  • Ask 10 questions from Part 5 out loud, 60–90 seconds each, no notes
  • Book or schedule one mock interview this week (2.3)
  • Start a flashcard deck for your weakest fundamentals answers

← 14B.5 β€” RΓ©sumΓ©, LinkedIn and the Job Search | Module 14B overview | 14B.7 β€” Interview Prep II: LLM System Design β†’

Esc
02.2Tokens and TokenizationHow LLMs Work Β· 21k wordsLesson
02.3EmbeddingsHow LLMs Work Β· 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons Β· Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack β€” architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation β€” and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility Β· 12k wordsLesson
↑ ↓ navigate↡ openesc close