AI engineer interview questions (2026): 20 answers on LLMs, RAG, evals and agents
AI engineer interviews in 2026 test whether you can ship reliable systems on foundation models: sizing KV caches, combining lexical and vector search, gating prompts in CI, and bounding agents against cost spikes and indirect prompt injection. Below are 20 speakable answers and Python snippets grounded in Attention Is All You Need, OpenAI Structured Outputs, Anthropic tool use, and the OWASP Top 10 for LLM Applications.
On this page
How AI engineer interviews differ from classical ML rounds
Classical machine learning engineer interview questions test feature pipelines, class imbalance, and training loops. AI engineering rounds assume a pretrained model exists and probe inference latency, schema-constrained APIs, hybrid retrieval, evals, and safe tool orchestration.
Expect an applied Python coding round (async retries, streaming, or an eval script), a RAG debugging dive, and architecture rounds where a system design interview framework keeps you structured. In AI system design interviews, state your baseline, quality metric, p95 latency, and cost budget first.
Junior AI engineer interview questions
1. How does scaled dot-product attention work, and why is long context expensive?
In Vaswani et al.’s Transformer, tokens project into Q, K, and V for softmax((Q @ K.T) / sqrt(d_k)) @ V. Dividing by sqrt(d_k) keeps large logits out of flat softmax saturation. Prefill scales as O(n^2 * d); FlashAttention tiles in GPU SRAM so the n x n matrix never hits HBM.
2. How do you compute KV-cache memory, and what does Grouped-Query Attention change?
Caching past keys and values avoids quadratic decode recomputation, costing 2 * batch * seq_len * n_layers * n_kv_heads * head_dim * bytes_per_elem. Grouped-Query Attention (GQA) shares each KV head across query heads to cut memory and HBM bandwidth, while PagedAttention prevents fragmentation.
def kv_cache_gb(batch: int, seq: int, layers: int = 80,
kv_heads: int = 8, dim: int = 128, bpe: int = 2) -> float:
return round(2 * batch * seq * layers * kv_heads * dim * bpe / (1024 ** 3), 2)
print(kv_cache_gb(batch=16, seq=32768, bpe=2)) # 16.0 GB BF16 (8.0 GB in FP8)3. How do prefill and decode differ, and how do they map to TTFT and TPOT?
Prefill runs prompt tokens in parallel (compute-bound) and sets Time to First Token (TTFT). Decode emits one token per step while reading weights and KV cache from HBM (memory-bandwidth-bound) and sets Time Per Output Token (TPOT). Continuous batching and chunked prefill prevent head-of-line stalls.
4. How do tokenization, temperature, top-p, and logprobs affect reliability?
BPE tokenizers split non-Latin scripts, numbers, and verbose JSON into extra tokens, raising TTFT and cost. Temperature scales logits and top_p trims tail probabilities, yet even temperature=0 can vary across GPU batches from floating-point non-associativity. Token logprobs calibrate label confidence.
5. Why use constrained structured outputs instead of prompt-only JSON?
Prompted JSON breaks on Markdown fences, unescaped quotes, or max_tokens cutoffs. Grammar-constrained decoding in OpenAI Structured Outputs masks invalid tokens so completed non-refusal outputs match your JSON Schema; code still checks refusals, cutoffs, and domain rules.
from typing import Literal
from openai import OpenAI
from pydantic import BaseModel
class Triage(BaseModel):
severity: Literal["low", "medium", "high", "critical"]
requires_human: bool
resp = OpenAI().responses.parse(model="gpt-5.3-codex",
input="Checkout returns 502 after deploy 481.", text_format=Triage)
if resp.status != "completed" or resp.output_parsed is None:
raise RuntimeError(f"Incomplete or refused: {resp.status}")6. Where do standalone dense embeddings fail?
Bi-encoders handle paraphrases well, but miss exact SKUs, error codes, versions, and negations. Because vector spaces are model-specific, upgrading an embedding model requires re-indexing into a shadow namespace.
Fine-tuning vs RAG vs long-context prompting
Start with long-context prompting plus prefix caching, add RAG when scale, freshness, or permissions demand retrieval, and fine-tune for tone, compact schemas, or small-model latency once evals exist.
| Dimension | Long-context prompting | RAG | Fine-tuning (SFT / DPO) |
|---|---|---|---|
| Freshness | Immediate per call | Seconds via index updates | Static until retrained |
| Citations & ACLs | Citations possible; must fit window | Per-user ACL filters + citations | Cannot enforce ACLs in weights |
| Latency & cost | High uncached TTFT; cheap cached | 30–120 ms search + rerank + short prompt | Lowest cost when distilling to 8B |
| Best fit | Bounded docs (<100k tokens) | Large, changing grounded corpora | Style, compact syntax, distillation |
| Main risk | Middle-context dilution, cost spikes | Missed chunks or noisy retrieval | Forgetting, hallucinated facts |
Mid-level AI engineer interview questions
7. How do you choose RAG chunk sizes, boundaries, and metadata?
Tiny chunks lose context; huge chunks dilute vectors. Split on structure (headings, AST functions, intact tables) at 300–600 tokens with 10–15% overlap, prepend a title/section header before embedding, and index filter metadata like tenant_id, acl_groups, and updated_at.
8. Why combine dense vectors and BM25 with Reciprocal Rank Fusion (RRF)?
Dense search catches synonyms while BM25 matches exact identifiers. Because cosine and BM25 scores use incompatible scales, RRF merges ranked lists via sum(1 / (k + rank)) (k = 60) without brittle weight tuning.
from collections import defaultdict
def rrf_fuse(runs: list[list[str]], k: int = 60, top_n: int = 8) -> list[str]:
scores: dict[str, float] = defaultdict(float)
for run in runs:
for rank, doc_id in enumerate(run, start=1):
scores[doc_id] += 1.0 / (k + rank)
return [d for d, _ in sorted(scores.items(), key=lambda x: -x[1])[:top_n]]9. What does a cross-encoder reranker add, and how do you budget its latency?
Bi-encoders never cross-attend between query and passage tokens. A cross-encoder scores [query, chunk] jointly, catching negations and multi-clause constraints. Fetch top 50–100 hybrid hits in ~20 ms, then GPU-rerank them in ~50 ms down to top 5–8 chunks.
10. How do you separate retrieval failures from generation failures?
Score both stages independently: Context Recall@k and Context Precision check whether relevant spans ranked near the top; Faithfulness (entailment to retrieved text) and Answer Relevance check generation and abstention.
11. How do you build and maintain a golden evaluation dataset?
Curate 100–300 stratified cases across core intents, follow-ups, adversarial inputs, empty-retrieval abstentions, and scrubbed incidents. Version cases, expected chunk IDs, and rubrics in Git so every bug becomes a regression test.
12. When do you use deterministic checks vs LLM-as-a-judge, and how do you curb judge bias?
Run deterministic checks first for JSON Schema, SQL/AST syntax, valid citations, PII, and latency. Reserve LLM judges for faithfulness, curbing the biases in Judging LLM-as-a-Judge — position, verbosity, and self-enhancement bias — via binary rubrics, swapped A/B order, and human calibration.
def debiased_pair_judge(judge, prompt: str, a: str, b: str) -> str:
r1, r2 = judge(prompt, a, b), judge(prompt, b, a) # returns "1", "2", or "tie"
if r1 == "1" and r2 == "2": return "a"
if r1 == "2" and r2 == "1": return "b"
return "tie"13. How do you run LLM regression gates in CI without flaky builds?
On PRs, run fixture unit tests plus a 30–50 case smoke eval at temperature=0, blocking merges on schema/safety breaks or recall drops. Run the 300+ case suite, red-team prompts, and cost/latency percentiles pre-release behind feature flags.
Senior AI engineer interview questions
14. How do tool-calling APIs work, and how should you design agent tools?
Per Anthropic’s tool-use guide, client tools pause on a typed tool_use block until host code validates, runs, and returns a tool_result. Expose 5–15 coarse domain tools with strict enums and clear errors rather than dozens of raw REST endpoints.
15. How do you keep an agent loop bounded, retry-safe, and idempotent?
Enforce a hard max_steps cap, wall-clock timeout, duplicate-call cycle detection, and deterministic idempotency keys on mutating tools so retries never double-charge or duplicate writes.
import hashlib, json
def run_agent(client, messages: list[dict], tools: list[dict], run_id: str) -> str:
for step in range(6):
resp = client.messages.create(model="claude-sonnet-5", max_tokens=1024,
tools=tools, messages=messages)
messages.append({"role": "assistant", "content": resp.content})
if resp.stop_reason != "tool_use":
return "".join(b.text for b in resp.content if b.type == "text")
out = []
for b in (x for x in resp.content if x.type == "tool_use"):
idem = hashlib.sha256(f"{run_id}:{step}:{b.name}:{json.dumps(b.input, sort_keys=True)}".encode()).hexdigest()[:20]
out.append({"type": "tool_result", "tool_use_id": b.id, "content": json.dumps(call_tool(b.name, b.input, idem))})
messages.append({"role": "user", "content": out})
raise TimeoutError("Exceeded step budget")16. Where do human-in-the-loop approvals and permissions belong?
Enforce authorization in middleware with caller-scoped RBAC tokens, never system prompts. Auto-run reads, but checkpoint state and verify human approval in host code before destructive, financial, or external-email actions.
17. How do you defend RAG and agents against indirect prompt injection?
Prompt injection tops the OWASP Top 10 for LLM Applications: untrusted docs or tickets try to hijack tools or exfiltrate secrets via URLs. Isolate untrusted data in delimiters, scope minimal tools, enforce outbound domain allowlists and strict image CSP, and require human approval whenever untrusted input precedes a write or egress call.
18. How does prompt caching work, and what silently breaks cache hits?
Per Anthropic’s prompt caching docs, KV reuse requires exact byte-for-byte prefixes. Putting datetime.now(), random UUIDs, or unsorted JSON keys in system prompts busts the prefix; keep static rules and sorted tools first and volatile user state last.
def cached_payload(static_rules: str, query: str, now_iso: str) -> dict:
return {
"model": "claude-sonnet-5", "max_tokens": 800,
"system": [{"type": "text", "text": static_rules, "cache_control": {"type": "ephemeral"}}],
"messages": [{"role": "user", "content": f"[Time: {now_iso}]\n{query}"}],
}19. How do semantic routing and model cascading cut latency and cost?
Route simple classification, extraction, and FAQ traffic to compact fast models while reserving frontier models for multi-step synthesis, and run retrieval plus guardrails concurrently via asyncio.gather. Avoid naive vector response caching on tenant-scoped or transactional queries where status of order 9 and cancel order 9 collide.
20. How do you monitor LLM quality in production when HTTP status stays 200?
Log distributed traces per run with prompt version, exact model snapshot, retrieved chunk IDs and rerank scores, tool errors, cache hit rate, TTFT, TPOT, dollar cost, and user signals (accepts, edits, re-asks). Run sampled async faithfulness graders on live traffic and shadow-test model upgrades before cutover.
Where Interview Copilot fits
Disclosure: we build Interview Copilot, a desktop assistant for rehearsing spoken system-design and AI trade-off answers under realistic timing, or surfacing structured notes in rounds where outside tools are allowed. The free tier needs no card and includes 5 minutes of live recognition and 3 screenshot solutions, while Pro costs $25 for one month as a one-time payment with no auto-renewal.
Before any interview, ask the recruiter in writing about AI rules for each stage: policies differ widely across employers, as covered in which companies allow AI in interviews, the Anthropic software engineer interview, and the OpenAI interview process.
Sources
- Vaswani et al., “Attention Is All You Need” (arXiv:1706.03762)
- OpenAI Documentation: Structured Outputs
- Anthropic Documentation: Tool use with Claude
- Anthropic Documentation: Prompt caching
- Zheng et al., “Judging LLM-as-a-Judge with MT-Bench and Chatbot Arena” (arXiv:2306.05685)
- OWASP GenAI Security Project: Top 10 for LLM Applications
Checked 21 November 2026.
FAQ
How do AI engineer interviews differ from machine learning engineer interviews?
Machine learning engineer interviews focus heavily on training models from scratch, feature engineering, classical validation, and PyTorch or scikit-learn internals. AI engineer interviews focus on building production systems around pretrained foundation models: KV-cache and latency math, structured outputs, hybrid RAG with reranking, automated evaluation pipelines, prompt injection defenses, and bounded tool-calling agents.
Should you propose RAG or fine-tuning first in an AI system design interview?
Default to long-context prompting or RAG first whenever facts change frequently, answers require source citations, or documents must respect per-user access controls. Propose fine-tuning when you need consistent output formatting, domain-specific tone, or latency and cost distillation from a large teacher model into a smaller model, and note that production systems often combine fine-tuned small models with RAG.
What do coding rounds look like for AI engineers in 2026?
Alongside standard Python data structures, many 2026 teams run practical applied coding rounds: building an async API client with retries, rate-limit backoff, and schema validation, implementing chunking and Reciprocal Rank Fusion over sample documents, or writing an offline evaluation harness that scores model outputs against a golden dataset.
How should you talk about LLM evaluations in an interview?
Show a layered evaluation pipeline rather than naming a library. Start with fast deterministic checks (JSON Schema compliance, valid citations, latency and cost limits), separate RAG retrieval metrics (context recall and precision) from generation faithfulness, and explain how you calibrate LLM-as-a-judge rubrics against human labels while mitigating position and verbosity bias.
What separates a senior answer on AI agents from a junior one?
Junior candidates describe chaining prompts and tools until the task finishes. Senior candidates define hard failure boundaries: strict step and dollar caps, deterministic idempotency keys on write tools, caller-scoped RBAC permissions in middleware rather than prompts, human-in-the-loop approval gates for irreversible actions, and containment against indirect prompt injection.
What kind of AI engineering portfolio project actually impresses interviewers?
Avoid thin chat wrappers around a single API call. Interviewers look for a scoped system with measurable engineering rigour: a 100-example golden eval set in CI, an ablation table showing why hybrid BM25 + vector search + reranking beat naive cosine search on your data, p95 latency and per-query cost numbers, and explicit handling of refusals, timeouts, and missing context.
More guides
Related articles
Read next
Use cases
Interview Copilot is a desktop app
It's a desktop app for macOS, Windows and Linux — a phone cannot capture the interviewer's audio or hide a window from screen share. Open this page on your computer to install it.
And during the interview this phone can be your screen: scan the QR code in the laptop app and the answers appear right here. How phone mode works →