Chapter
LLM Foundations
Prompting, context windows, embeddings, and model selection — the primitives every AI systems interview starts with.
Prompting Fundamentals
A prompt is the full control surface you expose to a pretrained model at inference time: system instructions, few-shot exemplars, retrieved context, tool schemas, and the user turn. Interviewers expect you to treat prompting as engineering — versioned, evaluated, and constrained — not as one-off copywriting.
| Technique | What it does | When to use | Risk |
|---|---|---|---|
| System prompt | Sets role, tone, hard rules | Always for products | Brittleness across model upgrades |
| Few-shot | Shows format via examples | Structured outputs, style lock | Token cost; example leakage |
| Chain-of-thought | Asks for stepwise reasoning | Math, multi-hop logic | Exposes reasoning; latency |
| Self-consistency | Sample N paths, vote | High-stakes answers | Cost multiplies by N |
| Constrained decode | JSON/schema / grammar | APIs, tool calls | Needs model support |
- Separate instructions (stable) from data (untrusted) — never concatenate raw docs into the system role without labeling
- Prefer explicit output contracts: field names, enums, refusal behavior, citation format
- Put the most critical constraints first and last (primacy/recency); middle of long prompts is a dead zone
- Version prompts like code: hash, owner, eval suite, rollback path
┌─────────────────────────────────────┐
│ System: role, safety, output schema │
├─────────────────────────────────────┤
│ Developer: product rules, tools │
├─────────────────────────────────────┤
│ Retrieved context (ACL-filtered) │
├─────────────────────────────────────┤
│ Few-shot exemplars (optional) │
├─────────────────────────────────────┤
│ User message + conversation memory │
└─────────────────────────────────────┘
↓
Tokenizer → LLM → decodeInterview signal
Say you measure prompt changes with a golden set and regression gate — not vibes. Mention injection: treat retrieved text and user content as untrusted data that can override instructions unless you isolate and sanitize.
Minimal viable prompt
Start with: role + task + constraints + output schema + one worked example. Add CoT only if evals show a clear lift for the failure class you care about.
Context Windows & Packing
Context window size is a hard budget of tokens across system prompt, history, retrieval, tools, and generation headroom. Interviews dig into how you allocate that budget under latency and cost constraints — not just quoting a model's advertised max tokens.
| Budget slice | Typical share | Failure if starved |
|---|---|---|
| System + tool schemas | 5–15% | Broken tool calls, policy drift |
| Conversation history | 10–30% | Lost intent, repeated questions |
| Retrieved chunks | 30–60% | Hallucinated facts, weak grounding |
| Generation reserve | 10–25% | Truncated answers, cut JSON |
- Count tokens with the model's tokenizer (or a close proxy) — never estimate from characters alone for code
- Reserve max_output_tokens before packing inputs; leave a safety margin
- Summarize or drop oldest turns when history balloons; keep user goal + last decisions
- Rank-and-truncate retrieval: score chunks, pack highest until budget, never silent overflow
Window = W tokens 1. Lock system + tools + schema (immutable) 2. Reserve G for generation 3. Pack ranked retrieval until budget 4. Pack recent history (newest first) 5. Drop / summarize remainder If query critical: retrieval > history If multi-turn task: keep last tool results
Lost-in-the-middle
Long contexts often under-attend middle evidence. Put must-use facts near the edges, or use multi-hop retrieval / map-reduce rather than dumping 50 chunks into one call.
What interviewers probe
How you handle 128k vs 8k models, whether you measure effective usable context (not marketing max), and what breaks when a PDF dump exceeds the window mid-demo.
Embeddings & Similarity
Embeddings map text (or multimodal inputs) to dense vectors so semantic similarity becomes a distance or score. In interviews, embeddings show up as the backbone of retrieval, clustering, dedup, and semantic caching — not as a magic black box.
| Concept | Interview takeaway |
|---|---|
| Bi-encoder | Encode query & doc independently; fast ANN search |
| Cross-encoder | Joint score of (query, doc); accurate, slow — use to rerank top-k |
| Cosine vs L2 | Cosine on normalized vectors ≈ inner product; pick one and stay consistent |
| Dimensionality | Higher dims can help until cost/latency dominate; Matryoshka lets you truncate |
| Domain shift | General embeds fail on jargon; fine-tune or use domain models |
- Never mix embedding model versions in one index without a re-embed migration plan
- Chunk text before embedding — one vector for a 50-page PDF collapses local meaning
- Normalize vectors if your store assumes cosine/IP scoring
- Watch for asymmetric retrieval: query and document may need different prefixes or models
Query ──► Embed(q) ──► ANN (HNSW/IVF) ──► top-k ids
Docs ──► Embed(d) ──► Vector index ────────────┘
│
Optional:
Cross-encoder rerank → top-nEval embedding quality
Use retrieval metrics (Recall@k, nDCG, MRR) on labeled query→doc pairs. A cheaper embed that wins on your corpus beats a trendy model that loses.
Interview signal
Distinguish embedding similarity from lexical match. Mention hybrid (BM25 + dense), and that similarity ≠ truth — retrieval can surface plausible but wrong passages.
Tokenization & Cost Basics
Tokens are the billing and latency unit. English prose is roughly 1.3 tokens per word; code, JSON, and non-English scripts are denser. Capacity planning in interviews starts from QPS × (input + output tokens) × price.
| Workload | Token profile | Cost lever |
|---|---|---|
| Short Q&A | Small in, small out | Cache + smaller model |
| RAG answer | Large in (chunks), medium out | Chunk budget, rerank then pack |
| Agent loop | Repeated tool I/O | Cap steps, summarize tool results |
| Summarization | Huge in, small out | Map-reduce / hierarchical summary |
| Code gen | Dense tokens | Prefer models good at code; constrain length |
- Always leave headroom for completion — truncated JSON is a production incident
- Output tokens often dominate latency and cost more than input on generative tasks
- Prompt caching (when available) amortizes large stable prefixes across requests
- Estimate daily $ = QPS × 86400 × (in+out)/1e6 × $/1M tokens
Hidden token burn
System prompts, tool schemas, and conversation history quietly consume the window. Log token breakdown by component in staging before you declare a cost model.
Back-of-envelope
Interviewers want a 30-second estimate: e.g. 10 QPS × 2k in + 500 out × $3/$15 per 1M → rough daily spend. State assumptions out loud.
Model Selection Tradeoffs
Model choice is a multi-objective decision: quality on your evals, p99 latency, $/query, context size, tool-calling reliability, data residency, and rate limits. Strong candidates propose a routing strategy, not a single forever model.
| Axis | Smaller / cheaper | Larger / frontier |
|---|---|---|
| Quality | Good for classification, rewrite | Hard reasoning, nuance, coding |
| Latency | Often faster TTFT | Slower; needs streaming UX |
| Cost | Order-of-magnitude cheaper | Dominates bill at scale |
| Reliability | May fail schema/tools | Better instruction following |
| Privacy | Easier to self-host | Often API-only / vendor lock |
- Define the task class and success metric before picking a model
- Build a golden eval set; compare models on that — not Twitter benchmarks
- Prototype with a strong model; distill/route down once quality floor is clear
- Plan fallbacks: primary → secondary provider → smaller model with degraded features
Request → Classifier / heuristics
│
┌────────┼────────┐
▼ ▼ ▼
Cache hit Small Large
(return) (FAQ, (complex,
extract) agents)
│
└──► Escalation if low confidenceCascade pattern
Try a cheap model first; escalate when confidence is low, tools fail, or the user retries. Measure escalation rate — it is your real cost multiplier.
Interview signal
Refuse the false dichotomy of "always GPT-4" or "always open source." Tie the pick to SLOs, eval scores, and compliance constraints.
Fine-Tuning vs Prompting
Prompting and RAG change behavior at inference without weight updates. Fine-tuning (full, LoRA, preference/RLHF-style) changes weights. Interviews expect a clear decision tree: start with prompt + retrieval; fine-tune when format, tone, or domain language is stable and high-volume.
| Approach | Best for | Avoid when |
|---|---|---|
| Prompt + tools | New products, fast iteration | Need proprietary knowledge only |
| RAG | Fresh / private docs | Knowledge is style, not facts |
| SFT / LoRA | Consistent format, domain jargon | Facts change weekly |
| Preference tuning | Align with human rankings | No reliable preference data |
- Fine-tuning does not replace retrieval for up-to-date factual knowledge
- Data quality > data quantity; noisy labels lock in bad behavior
- Budget for eval, safety regression, and model versioning ops
- LoRA adapters can be swapped per tenant/task with lower storage cost
Catastrophic forgetting & drift
Fine-tuned models can lose general capability or overfit to training prompts. Keep a general benchmarks suite and a production shadow eval before cutover.
Default answer
"I'd ship prompt+RAG first, measure failure modes, then fine-tune only for systematic style/format gaps that survive good prompting."
Multimodal & Structured I/O
Modern interviews expand beyond chat: vision inputs, audio, and structured outputs (JSON Schema, tool calls, grammars). Treat modalities as different latency and safety surfaces with the same need for contracts and evals.
| I/O type | Design note | Failure mode |
|---|---|---|
| JSON / schema | Validate server-side; repair once | Partial JSON, hallucinated keys |
| Tool call args | Strict types + allowlists | Injection via free-text args |
| Vision | Resolution vs token cost | OCR errors treated as facts |
| Tables / CSV | Prefer structured extract first | Misaligned columns |
- Never trust model JSON without schema validation and typed parsing
- For vision+RAG: OCR or caption into text, then retrieve — or use native multimodal carefully
- Prefer constrained decoding when available over "please return JSON" alone
- Log raw vs parsed outputs for debugging schema regressions after model upgrades
LLM → raw tokens
│
Schema / grammar decode
│
Validate (zod/jsonschema)
│
┌────┴────┐
OK Fail → retry w/ error
│ or fallback path
▼
Typed object → business logicInterview signal
Mention validation, idempotent retries, and that structured output is an API contract — not a prompt hope.
Staff depth layer
LLM Foundations — Staff Depth
Treat the model as a stochastic component with a controllable interface, not a brain. Your job in the interview is to show you can allocate context budget, choose models by failure mode and unit economics, version prompts like code, and prove quality with evals — without romanticizing 'better prompting' as a substitute for retrieval, tools, or product constraints.
Anti-patterns → say instead
✕ Prompt-as-product
A 2,000-token system prompt that encodes business rules will drift across model upgrades, is untestable as a unit, and hides policy in English instead of code.
Say instead: Keep the system prompt thin: role, safety, output schema. Encode refunds, entitlements, and routing in deterministic policy + tools; validate with structured outputs and golden cases.
✕ Max-context maximalism
Stuffing 100k tokens of history and docs raises cost, latency, and mid-context blind spots; quality often drops after a sweet spot.
Say instead: Budget tokens explicitly: system+tools 5–15%, history 10–30%, retrieval 30–60%, generation reserve 10–25%. Summarize or retrieve instead of dumping.
✕ Embedding as magic memory
Assuming cosine similarity equals semantic truth ignores domain jargon, ACL boundaries, and the fact that embed quality is a first-class eval target.
Say instead: Pick embedding models with a labeled pair set; hybrid BM25+vector; measure recall@k before you touch the generator.
✕ One model for everything
Routing a FAQ and a multi-hop legal analysis to the same frontier model burns money and still fails structured tasks without schemas.
Say instead: Cascade: classifier/small model for intent → mid-tier for grounded Q&A → large only for hard cases; gate by confidence and eval lift.
Product wants chat with 20-turn history, top-8 RAG chunks, 4 tools, and room for a 800-token JSON reply. Model window is 32,768 tokens.
- Reserve generation: 1,000 tokens (schema + margin) → usable input ≈ 31,768.
- System + tool schemas: measure ≈ 2,400 tokens → remaining 29,368.
- Top-8 chunks at ~600 tokens each = 4,800; add 400 for citation formatting → 5,200. Remaining 24,168.
- History: keep last N turns under 8,000 tokens; older turns → rolling summary ≤ 1,200 tokens.
- If a single ticket paste is 12k tokens, truncate with structure-aware cut (headers, last error stack) and retrieve the rest via ticket_id tool — never paste raw into system role.
- 32,768 window − 1,000 gen = 31,768 input budget
- System+tools ≈ 2,400; RAG ≈ 5,200; summary ≈ 1,200; live history cap ≈ 8,000; slack ≈ 15k for unexpected tool results
- At $3/1M input + $15/1M output, 2k in + 400 out ≈ $0.012/call; 50k calls/day ≈ $600/day before cache
Staff candidates narrate the budget as a hard resource allocation problem and name what gets cut first under pressure (history before ACL-filtered retrieval).
Cheat sheet
- Tokens ≈ words × 1.3 (English); code denser — tokenize for real budgets
- Primacy/recency: critical constraints first and last
- Untrusted data ≠ system instructions — label and isolate
- Version prompts: hash, owner, golden suite, rollback
- Model pick: latency SLO × quality on your eval × $/1M × data residency
- Structured output / grammar for APIs; free text for UX summaries
- Few-shot for format lock; not for encoding secret business logic