AI Engineer interview question bank: RAG, agents, evals, system design
Problem. “AI Engineer” interviews are unusually broad: one loop tests Transformer trivia, the next asks you to design a production support bot, the next is plain Python concurrency. This bank organizes real candidate-reported questions (OpenAI, Anthropic, Google, Meta, Sierra, xAI, Databricks, Perplexity) by round, with what a good answer contains.
Four flavors keep recurring: applied LLM/product sense, agents, LLM system design, and practical coding. Everything below maps to one of them.
LLM fundamentals
1. What does temperature control, and when would you set it near zero? (reported widely)
Temperature rescales logits before softmax: near zero the distribution sharpens onto the top token (deterministic, reproducible), high values flatten it (diverse, risky).
\begin{tikzpicture}[scale=0.9]
\draw[->] (0,0) -- (4.4,0);
\draw[->] (0,0) -- (0,3);
\draw[thick] plot[smooth] coordinates {(0.2,0.4) (1,1.2) (2,1.8) (3,1.2) (3.9,0.4)};
\draw[thick,dashed] plot[smooth] coordinates {(0.2,0.1) (1,0.3) (2,2.6) (3,0.3) (3.9,0.1)};
\node[font=\scriptsize] at (2,-0.45) {solid: T=1, dashed: T=0.1};
\end{tikzpicture}
Rule of thumb. Set temperature near zero for extraction, classification, evals, and anything graded — you want the same answer twice. Raise it for brainstorming and creative writing. Note top-p/top-k shape which tokens are candidates; temperature shapes how sharply the model prefers among them.
2. What is a context window, and what breaks when you exceed it?
The maximum tokens per request (input + output). Overflow used to error; today most APIs silently truncate — usually the middle or the start, which quietly deletes your instructions or evidence.
What to say. KV-cache memory grows with tokens, and attention is quadratic, so long context costs latency and money on every call. Defenses: retrieve instead of stuffing (RAG), sliding windows, map-reduce summarization, and reserving output budget. Always ask what happens at 10× the expected document size.
3. What is quantization, and what do you trade away?
Storing weights (and sometimes activations) in fewer bits: FP16 → INT8/INT4.
The trade. You gain smaller checkpoints, less memory bandwidth, and faster/cheaper inference — often 2–4×. You pay precision: possible accuracy loss (worst on small models and math), plus calibration effort. Reach for it when serving is memory- or latency-bound, e.g. on-device or high-QPS endpoints.
4. Why is attention quadratic, and what breaks at long context?
Every token scores every other token: \(O(n^2)\) time and memory in sequence length, plus a KV cache that grows linearly per generated token.
Fixes interviewers want to hear. FlashAttention (IO-aware tiling, same math, far less memory traffic), sliding-window or sparse attention, and multi-query/grouped-query attention (fewer KV heads). Say which changes the math (sparse) versus only the implementation (FlashAttention).
5. Why do models fail at “how many r’s in strawberry”? (tokenization, reported)
Byte-pair tokenizers split text into subword tokens, so the model never sees
individual characters — strawberry might be two opaque tokens.
Follow-through. Counting, spelling, and character edits are inherently unreliable; ask the model to spell the word out first, or do string ops in code, not in prose. General lesson: the model reasons over tokens, not characters or bytes.
Prompting
6. When does chain-of-thought help, and what does it cost?
Asking for intermediate reasoning before the answer.
When it helps. Multi-step tasks (math, logic, planning); it hurts everywhere else via tokens, latency, and more surface for errors. Few-shot examples fix format; self-consistency (sample several chains, majority vote) trades 3–5× cost for accuracy on hard reasoning. Never CoT where a lookup suffices.
7. Agent vs chain — what’s the difference? (reported across companies)
A chain is a fixed sequence of steps; an agent loops: reason, act with a tool, observe the result, repeat until done.
The one-liner plus judgment. Chains for workflows you can enumerate; agents when the steps depend on intermediate results (debugging, research, multi-hop QA). Agents cost openness: loops, tool failures, and nondeterminism — which is why the agent questions below exist.
8. How do you get reliable structured output?
JSON mode or response schemas, function-calling interfaces, or grammar-constrained decoding — then validate and retry on schema failure.
Production add-ons. Validate with a real schema (pydantic/zod), retry with the validation error appended, and keep a deterministic fallback (template or default) so one bad object never breaks the pipeline.
RAG
9. Explain how RAG works, and why use it over fine-tuning. (Sierra, reported)
Retrieval-augmented generation gives the model facts it wasn’t trained on by fetching them at query time, in four stages.
flowchart TB
subgraph Ingest
D[Docs] --> C[Chunk]
C --> E[Embed]
E --> V[(Vector DB)]
end
subgraph Serve
Q[Query] --> QE[Embed query]
QE --> R[Top-k retrieve]
V -.-> R
R --> P[Augment prompt]
P --> L[LLM answers with citations]
end
Why not fine-tune. Freshness: update knowledge by re-indexing, not retraining. Citations: answers point at sources, which fine-tuned weights can’t. Cost: no training run. Fine-tuning wins for behavior/style/format, RAG wins for facts that change.
10. How do you chunk documents?
Splitting long docs into retrievable units — the highest-leverage RAG knob after the embedding model.
Practical ladder. Start fixed-size (256–512 tokens, 10–20% overlap). Upgrade to sentence-aware splits so ideas don’t straddle boundaries; add metadata (title, section, date) as filters. Parent-child retrieval (fetch small, expand to the big chunk for context) fixes “right chunk, cut off”. Judge chunking by retrieval metrics on real queries, never by inspection.
11. Cosine top-k isn’t enough — how do you improve retrieval?
Pure dense retrieval misses exact terms and buries the best chunk at rank 8.
The standard stack. Hybrid search (BM25 sparse + dense, fused with reciprocal rank fusion), query rewriting/HyDE (retrieve with a hypothetical answer, not the raw question), metadata filters, then a cross-encoder reranker over the top 20–50 to pick the final context. Each layer is measurable: ablate one at a time.
12. How do you evaluate a RAG system?
Split it: retrieval quality and generation quality fail independently.
| Layer | Metrics | How |
|---|---|---|
| Retrieval | hit@k, MRR, recall@k | golden Q/A pairs, known relevant docs |
| Generation | faithfulness, answer relevance | LLM judge with rubric + references |
| End-to-end | task success, thumbs up/down | blinded A/B, human spot checks |
What good looks like. Golden sets versioned with the index; retrieval and generation gated separately in CI; LLM judges blinded, rubric-scored, and calibrated against human labels (they have position, length, and self-preference biases — never trust absolute scores, only rankings).
Agents
13. Walk me through the ReAct loop.
Reason → Act → Observe, repeated until the model answers.
flowchart LR
T[Thought] --> A[Action: call tool]
A --> O[Observation]
O -->|need more info| T
O -->|answer ready| F[Final answer]
Why it works. Interleaving reasoning with tool calls grounds each step in fresh evidence instead of one giant leap. The loop needs three guards (next question): a step cap, action validation, and a way to shrink what it has seen.
14. How does tool/function calling work under the hood?
JSON schemas for each tool go in the prompt; the model emits a name plus arguments; your executor runs it and feeds the result back as an observation.
Production details. Validate arguments against the schema before executing, time out and retry tools like any RPC, make mutating tools idempotent (at-least-once delivery is the norm), and sandbox side effects — the model will eventually call something with surprising arguments.
15. Name three agent failure modes and their fixes. (reported)
Loops (repeating the same failing action), tool-error cascades, and context blowup from stuffing every observation into history.
The fix list. Step caps plus progress detection (“no new information in 3 steps → stop”); validate/parse tool outputs before they re-enter context; compact history (summarize scratchpad, keep only final artifacts); treat tool output as untrusted input — it is a prompt-injection channel. Evaluate on traces, not just final answers: step count, tool error rate, recovery rate.
16. How do agents remember across sessions?
Short-term memory is the context window (scratchpad, recent turns); long-term memory is an external store of facts, preferences, and summaries.
Trade-offs. Retrieve-then-write: pull relevant memories into context, write back new facts after the session. Staleness is the enemy — timestamp memories, let users inspect/delete them, and never let a memory override fresh tool output silently.
MCP and tool infrastructure
17. What is MCP, and what problem does it solve?
The Model Context Protocol (Anthropic, open standard): one protocol connecting AI apps to tools and data — USB-C for agent integrations. Without it every app wires every tool bespoke; with it, apps speak MCP once and tools expose MCP once.
The one-liner. Standardized discovery (what can I call?), invocation (JSON-RPC), and data access — a new tool works in every MCP host without custom glue. Reach for it when tools outgrow hand-rolled function calling.
18. Explain the MCP architecture: hosts, clients, servers?
The host is the AI app orchestrating (an agent, an IDE); it spawns one client per server; each client holds a 1:1 connection; servers expose tools, resources, and prompts.
flowchart LR
H[Host app] --> C1[Client A]
H --> C2[Client B]
C1 --> S1[Server: Postgres]
C2 --> S2[Server: GitHub]
S1 --> T1[(Tools and data)]
S2 --> T2[(Tools and data)]
Why 1:1 clients. Isolation: auth, sessions, and failure domains stay per-server. The host multiplexes; a dead server kills one client, not the app.
19. Tools vs resources vs prompts — plus sampling, roots, elicitation?
Tools are model-invoked functions with schemas; resources are app-attached data (files, rows) the model reads; prompts are reusable server-side templates.
The rest of the vocabulary. Sampling: the server asks the model to complete something mid-flow (human-in-the-loop by design). Roots: advertised workspace boundaries — don’t leave this directory. Elicitation: the server requests structured user input through the client. Interviewers use these as have-you-built-one shibboleths.
20. Transports: stdio vs Streamable HTTP?
stdio spawns a local subprocess (dev tools, desktop apps); Streamable HTTP is the remote transport — one endpoint, JSON-RPC post plus optional SSE stream — replacing the old SSE transport.
Stateful or not. Servers can be stateless per request or hold sessions; say which the design needs (progress notifications and sampling need the session). Wrapping a REST API? The adapter must add discovery, schemas, sessions, and auth — a bare HTTP relay is not MCP.
21. How do you secure dangerous tools like drop_database? (reported)
MCP servers execute on client request — descriptions are an injection channel and similar names confuse models.
The checklist. Least-privilege credentials per server, human approval for mutating tools, allowlists over blocklists, descriptions treated as untrusted input (same rule as agent tool output), OAuth on remote servers, audit logs of every invocation. Plus tool-spam control: too many tools bloat context and confuse selection — scope servers per task, don’t mount the world.
22. MCP vs plain function calling?
Function calling is per-app bespoke wiring; MCP is standard discovery plus transport shared across hosts.
The trade. Generality and reuse against control and overhead: adopt MCP at the boundary where tools are shared or third-party; keep tight hand-rolled calls inside a single latency-critical loop.
Fine-tuning vs RAG vs prompting
23. Prompting vs RAG vs fine-tuning — how do you choose?
Match the tool to what changes — behavior or knowledge.
| Signal | Choice |
|---|---|
| New facts, changing weekly | RAG (re-index, don’t retrain) |
| Style, format, domain behavior | Fine-tune (100s–1000s examples) |
| One-off task, stable model | Prompt (+ few-shot, CoT) |
| Facts AND behavior | RAG + fine-tune together |
Cost framing. Prompting costs tokens forever; RAG costs retrieval infra; fine-tuning costs data + training + a model you now own (versioning, evals, hosting). Say the ongoing price of each, not just the setup.
24. What are LoRA and QLoRA?
Parameter-efficient fine-tuning: freeze the base model, train small low-rank adapter matrices; QLoRA does it on a 4-bit quantized base.
When. Style/format/domain adaptation on one GPU with hundreds to low thousands of examples. It won’t teach genuinely new facts as well as RAG serves them.
25. What is RLHF? Give me the three stages.
Supervised fine-tuning on demonstrations, then a reward model trained on human pairwise preferences, then policy optimization against that reward.
Stage by stage. (1) SFT: imitate good responses. (2) Reward model: learn \(P(y_w \succ y_l) = \sigma(r(x, y_w) - r(x, y_l))\) from pairs where humans picked a winner (Bradley-Terry). (3) RL: tune the policy to score highly under the reward model, with a KL penalty keeping it near the SFT model so it doesn’t degenerate into reward-hacking gibberish. Purpose: align helpfulness and harmlessness, which next-token prediction alone doesn’t teach.
26. Where does PPO fit in — why not vanilla policy gradients?
PPO is the optimizer for stage 3: it maximizes a clipped surrogate, \(L = \mathbb{E}[\min(r\hat{A},\, \mathrm{clip}(r, 1-\epsilon, 1+\epsilon)\hat{A})]\), where \(r\) is the new-over-old probability ratio and \(\hat{A}\) the estimated advantage.
flowchart LR
SFT[SFT model] --> RM[Reward model]
SFT --> PPO[PPO loop]
RM -.->|scores| PPO
PPO --> AL[Aligned model]
Why clipping. Vanilla policy gradients take one oversized step on a noisy batch and the policy collapses; the clip bounds each update (a cheap trust region, no second-order math). In practice add the KL penalty, a value loss, and an entropy bonus — and expect fiddly hyperparameters, which is exactly the complaint DPO answers.
27. How does DPO skip the reward model entirely?
Key insight: the optimal RLHF policy has closed form in terms of the reward, so invert it — express the reward through the policy and plug straight into Bradley-Terry: \(\mathcal{L} = -\mathbb{E}[\log \sigma(\beta \log \frac{\pi(y_w)}{\pi_{ref}(y_w)} - \beta \log \frac{\pi(y_l)}{\pi_{ref}(y_l)})]\).
The trade. No reward model to train, no PPO loop to babysit — one stable supervised-style loss directly on preference pairs. Price: it leans harder on preference-data quality (garbage pairs teach garbage confidently) and can overfit; variants like IPO, KTO, and ORPO patch specific failure modes. Reach for DPO first in 2026 unless you need online exploration.
Evaluation and safety
28. How do you use LLMs as judges without fooling yourself? (reported)
Rubric + reference answer, blinded candidates, randomized order.
Bias checklist. Position bias (first answer wins), length bias (longer wins), self-preference (judge likes its own family). Mitigate: swap positions and average, cap length or penalize it, calibrate against human labels, and use judges for ranking candidates — never for absolute grades.
29. Offline evals vs online signals?
Offline: golden sets gating deploys in CI. Online: what users actually do.
Both, different jobs. Offline gates regressions cheaply; online (thumbs, rewrite/correction rate, task completion, shadow deploys, canary with guardrail tripwires) catches what goldens miss. Log prompts, retrieved context, and outputs together — unevaluable traces are undebuggable incidents.
30. How do you approach GenAI safety in consumer products? (OpenAI, Anthropic, Google)
Assume adversarial users: red-team with jailbreak probes, then layer input and output guardrails (PII, toxicity, policy), sandbox tool actions with least privilege, and audit-log everything.
Depth, not one filter. No single filter holds: combine prompt-level instructions, dedicated classifiers on the way in and out, structured tool permissions, rate limits, and human review queues for the risky tail. Measure attack success rate on a held-out probe set like any other metric.
System design
31. Design a support chatbot over company docs.
The canonical AI system-design question: requirements, capacity, then the boxes-and-arrows below. Talk through it, don’t just draw it.
flowchart LR
U[User] --> GI[Guardrails in]
GI --> RT[Router]
RT --> RW[Rewrite query]
RW --> HR[Hybrid retrieve]
V[(Vector DB)] -.-> HR
HR --> RR[Rerank]
RR --> LLM[LLM plus citations]
SC[Semantic cache] -.->|hit| LLM
LLM --> GO[Guardrails out]
GO --> U
GO -.->|log| EV[Eval plus traces]
Hitting the rubric. Functional: answer from docs with citations, escalate when unsure. Non-functional: p99 latency, freshness SLA, cost per chat. Capacity: QPS from DAU, tokens per turn × turns, cache hit ratio from repeat rate. Deep dives: semantic cache (embed query, similarity threshold, TTL), streaming (SSE) for perceived latency, small-model triage with big-model fallback, eval loop on logged traces. Say what you’d cut under a deadline.
32. What is a semantic cache, and when does it hurt?
Cache keyed by meaning: embed the query, return a stored answer past a similarity threshold.
The catch. Hit ratio follows query repetition (support bots: high; open chat: low). It hurts with paraphrase drift (wrong answer, high confidence) and stale facts — TTLs plus invalidation on re-index, and never cache personalized or access-controlled answers under shared keys.
33. Your LLM bill 10×’d overnight — what do you check?
Cost is tokens × price, so find which factor moved: traffic spike, longer contexts (retrieval pulling more chunks?), a model upgrade, retry storms from failures, or an abuse/billing attack.
Levers, in order. Cap max tokens and top-k first (instant), add the semantic cache, route easy turns to a smaller model, batch offline work, fix retry/backoff bugs, then rate-limit per key. Instrument cost per endpoint before the incident, not during it.
Coding round
34. What does the coding round actually test? (Anthropic, Meta, OpenAI reports)
Practical engineering over puzzles: in-memory databases, rate limiters and caches, bank/ledger systems with concurrency, async I/O pipelines.
How to prepare. Python asyncio fluency (never block the loop, semaphores for fan-out, timeouts on everything), thread-safety basics for shared state, and testing edge cases out loud. The skeleton below is half of these rounds:
import asyncio
async def run_all(items, worker, limit=10):
sem = asyncio.Semaphore(limit)
async def one(item):
async with sem: # bounded fan-out
return await asyncio.wait_for(worker(item), timeout=30)
return await asyncio.gather(*(one(i) for i in items),
return_exceptions=True)
Edge cases for interview day
- Say the evaluation plan for every design — candidates who can’t measure their system lose to ones who can, even with a weaker architecture.
- Name the failure modes unprompted — loops, prompt injection via tool output, stale caches, eval bias. Interviewers score this as seniority.
- Costs are a feature — tokens × price on every estimate; “small model first, big model on fallback” is almost always the right instinct.