Skip to main content
HS
HiSETSuccess
LeetCode Prep

AI & FDE Interview Room

Role paths, mocks, cost studio, chapters, cases, and staff-level depth.

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.

TechniqueWhat it doesWhen to useRisk
System promptSets role, tone, hard rulesAlways for productsBrittleness across model upgrades
Few-shotShows format via examplesStructured outputs, style lockToken cost; example leakage
Chain-of-thoughtAsks for stepwise reasoningMath, multi-hop logicExposes reasoning; latency
Self-consistencySample N paths, voteHigh-stakes answersCost multiplies by N
Constrained decodeJSON/schema / grammarAPIs, tool callsNeeds 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
Prompt stack in production
┌─────────────────────────────────────┐
│ System: role, safety, output schema │
├─────────────────────────────────────┤
│ Developer: product rules, tools     │
├─────────────────────────────────────┤
│ Retrieved context (ACL-filtered)    │
├─────────────────────────────────────┤
│ Few-shot exemplars (optional)       │
├─────────────────────────────────────┤
│ User message + conversation memory  │
└─────────────────────────────────────┘
              ↓
         Tokenizer → LLM → decode

Interview 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 sliceTypical shareFailure if starved
System + tool schemas5–15%Broken tool calls, policy drift
Conversation history10–30%Lost intent, repeated questions
Retrieved chunks30–60%Hallucinated facts, weak grounding
Generation reserve10–25%Truncated answers, cut JSON
  1. Count tokens with the model's tokenizer (or a close proxy) — never estimate from characters alone for code
  2. Reserve max_output_tokens before packing inputs; leave a safety margin
  3. Summarize or drop oldest turns when history balloons; keep user goal + last decisions
  4. Rank-and-truncate retrieval: score chunks, pack highest until budget, never silent overflow
Packing order under a fixed window
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.

ConceptInterview takeaway
Bi-encoderEncode query & doc independently; fast ANN search
Cross-encoderJoint score of (query, doc); accurate, slow — use to rerank top-k
Cosine vs L2Cosine on normalized vectors ≈ inner product; pick one and stay consistent
DimensionalityHigher dims can help until cost/latency dominate; Matryoshka lets you truncate
Domain shiftGeneral 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
Bi-encoder retrieval path
Query ──► Embed(q) ──► ANN (HNSW/IVF) ──► top-k ids
Docs  ──► Embed(d) ──► Vector index ────────────┘
                              │
                         Optional:
                    Cross-encoder rerank → top-n

Eval 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.

WorkloadToken profileCost lever
Short Q&ASmall in, small outCache + smaller model
RAG answerLarge in (chunks), medium outChunk budget, rerank then pack
Agent loopRepeated tool I/OCap steps, summarize tool results
SummarizationHuge in, small outMap-reduce / hierarchical summary
Code genDense tokensPrefer 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.

AxisSmaller / cheaperLarger / frontier
QualityGood for classification, rewriteHard reasoning, nuance, coding
LatencyOften faster TTFTSlower; needs streaming UX
CostOrder-of-magnitude cheaperDominates bill at scale
ReliabilityMay fail schema/toolsBetter instruction following
PrivacyEasier to self-hostOften API-only / vendor lock
  1. Define the task class and success metric before picking a model
  2. Build a golden eval set; compare models on that — not Twitter benchmarks
  3. Prototype with a strong model; distill/route down once quality floor is clear
  4. Plan fallbacks: primary → secondary provider → smaller model with degraded features
Simple model router
Request → Classifier / heuristics
              │
     ┌────────┼────────┐
     ▼        ▼        ▼
  Cache hit  Small     Large
  (return)   (FAQ,     (complex,
              extract)   agents)
                 │
                 └──► Escalation if low confidence

Cascade 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.

ApproachBest forAvoid when
Prompt + toolsNew products, fast iterationNeed proprietary knowledge only
RAGFresh / private docsKnowledge is style, not facts
SFT / LoRAConsistent format, domain jargonFacts change weekly
Preference tuningAlign with human rankingsNo 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 typeDesign noteFailure mode
JSON / schemaValidate server-side; repair oncePartial JSON, hallucinated keys
Tool call argsStrict types + allowlistsInjection via free-text args
VisionResolution vs token costOCR errors treated as facts
Tables / CSVPrefer structured extract firstMisaligned 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
Structured output pipeline
LLM → raw tokens
        │
   Schema / grammar decode
        │
   Validate (zod/jsonschema)
        │
   ┌────┴────┐
   OK        Fail → retry w/ error
   │              or fallback path
   ▼
Typed object → business logic

Interview 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.

  1. Reserve generation: 1,000 tokens (schema + margin) → usable input ≈ 31,768.
  2. System + tool schemas: measure ≈ 2,400 tokens → remaining 29,368.
  3. Top-8 chunks at ~600 tokens each = 4,800; add 400 for citation formatting → 5,200. Remaining 24,168.
  4. History: keep last N turns under 8,000 tokens; older turns → rolling summary ≤ 1,200 tokens.
  5. 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