Skip to content

AI Engineer interview questions

100 real questions with model answers and explanations for Middle candidates.

See a AI Engineer resume example

Practice with flashcards

Spaced repetition · Hunter Pass

Questions

raggroundednessarchitecture

A RAG system indexes source content, retrieves relevant evidence for a query, and gives that evidence to a generator.

  • The ingestion path parses documents, splits them into chunks, creates embeddings, and stores vectors with text and metadata.
  • At query time, the system transforms the user query into a search representation and retrieves candidate chunks from the index.
  • An optional reranker orders the candidates more precisely, after which context assembly selects and formats the best evidence.
  • The language model receives the query and assembled context, generates an answer, and can attach citations back to the stored sources.

Why interviewers ask this: The interviewer is checking whether you understand RAG as an end-to-end retrieval and generation pipeline rather than a single vector search call.

ragretrievalsystem-design

Chunk size and overlap balance semantic completeness, retrieval precision, and context cost.

  • Smaller chunks usually match focused questions more precisely, but they can split an explanation and remove context needed to interpret a fact.
  • Larger chunks preserve more local context, but their embeddings may represent several topics and they consume more of the model's context window.
  • Overlap protects information near chunk boundaries, but too much overlap creates duplicate results, a larger index, and repeated prompt content.
  • Choose token-aware values by document type, then compare recall and answer quality on a representative evaluation set.

Why interviewers ask this: A strong answer identifies both retrieval and generation trade-offs and proposes measurement instead of treating one chunk size as universally correct.

chunking

Use structure-aware chunking when document boundaries carry meaning, and semantic chunking when topic transitions are more informative than formatting.

  • Structure-aware chunking follows headings, paragraphs, lists, tables, or code blocks, preserving hierarchy and source traceability.
  • Semantic chunking groups nearby sentences by meaning and splits around topic shifts, which suits transcripts or loosely formatted prose.
  • Structural units can be uneven, so large sections may need token-based subdivision and tiny sections may need merging.
  • Semantic chunking costs more, is less deterministic, and can separate content that belongs to one structural unit, so a hybrid of both is often practical.

Why interviewers ask this: The interviewer wants to see whether you can match chunking boundaries to document semantics while recognizing the limitations of each method.

retrieval

Parent-child retrieval searches precise small chunks but supplies their broader parent sections to the model.

  • Each child chunk is embedded with a parent identifier, while the larger parent text is stored separately.
  • Search runs over children because their focused embeddings usually match specific queries better than large sections do.
  • The system deduplicates matched parent identifiers and fetches the corresponding parents, or selected neighboring children, for context assembly.
  • This combines retrieval precision with readable context, but oversized parents can add unrelated text and consume too many prompt tokens.

Why interviewers ask this: The interviewer is evaluating whether you understand how separating retrieval units from context units resolves the precision versus completeness trade-off.

retrieval

Dense retrieval matches meaning, sparse retrieval matches terms, and hybrid retrieval combines both signals.

  • Dense retrieval compares learned embeddings, so it handles paraphrases and conceptual similarity but may miss rare names or exact identifiers.
  • Sparse retrieval, such as BM25, rewards shared tokens and term rarity, making it strong for product codes, names, and exact technical phrases.
  • Hybrid retrieval runs both methods and combines their rankings with a technique such as reciprocal rank fusion or calibrated score weighting.
  • Select the approach on labeled queries, with hybrid retrieval often fitting corpora that mix natural-language concepts with exact terminology.

Why interviewers ask this: A strong answer explains the failure modes of lexical and semantic matching and how score fusion can make them complementary.

retrievalqueries

They improve retrieval in different ways by clarifying one query, broadening its vocabulary, or splitting it into simpler searches.

  • Rewriting produces a clearer standalone query, for example by resolving pronouns or conversational context while preserving the original intent.
  • Expansion creates related formulations, synonyms, or likely terms so relevant documents using different wording can be found.
  • Decomposition turns a compound or multi-hop question into subquestions whose evidence can be retrieved and combined.
  • Each method can introduce intent drift and extra cost, so retain the original query, preserve its constraints, and evaluate the merged results.

Why interviewers ask this: The interviewer is checking whether you distinguish three query transformation strategies and can control the recall gains against semantic drift.

vector-db

Pre-filtering restricts the searchable candidates first, while post-filtering removes results after similarity search.

  • Pre-filtering enforces hard constraints such as tenant, language, document type, or date before irrelevant vectors can enter the result set.
  • Very selective pre-filters can reduce ANN recall or efficiency if the vector index does not handle filtered search well.
  • Post-filtering is simpler for flexible criteria, but it can return fewer than top-k valid results and waste retrieval capacity on discarded candidates.
  • Use supported pre-filtering for authorization and other mandatory constraints, while post-filtering or an expanded candidate set can serve soft preferences.

Why interviewers ask this: A strong answer connects filter placement to correctness, result count, and the behavior of approximate vector indexes.

retrieval

Choose the smallest top-k that meets the required recall while staying within the latency and downstream processing budget.

  • A small top-k is faster and cheaper, but a relevant passage just below the cutoff cannot be recovered by later stages.
  • A larger top-k improves the chance of finding relevant evidence, but increases result transfer, reranking work, and context selection cost.
  • Top-k does not replace ANN search-breadth settings such as efSearch or nprobe, which also control how thoroughly the index explores candidates.
  • Measure recall@k and latency on labeled queries, and keep retrieval top-k larger than the final number of chunks passed to the model.

Why interviewers ask this: The interviewer wants evidence that you tune ANN retrieval empirically and understand the distinction between candidate recall and final context size.

retrievalreranking

A bi-encoder retrieves candidates efficiently, while a cross-encoder reranks a smaller set with richer query-document interactions.

  • A bi-encoder encodes queries and documents independently, allowing document vectors to be precomputed and searched with an ANN index.
  • A cross-encoder processes each query-document pair jointly, capturing token-level relationships more accurately but requiring a separate model pass per pair.
  • A common pipeline retrieves tens or hundreds of candidates with a bi-encoder and reranks them to a much smaller final set with a cross-encoder.
  • Reranking cannot recover a relevant document omitted by the first stage, so evaluate retriever recall before judging reranker quality.

Why interviewers ask this: A strong answer explains why the two models occupy different stages and identifies first-stage recall as the ceiling for reranking.

retrievalcss

Multi-stage retrieval narrows a broad candidate pool with increasingly precise methods, while MMR reduces redundancy among the final results.

  • An initial sparse, dense, or hybrid search retrieves enough candidates to favor recall over precision.
  • Metadata checks, deduplication, and a stronger reranker then reduce that pool before context assembly.
  • MMR selects each next chunk by balancing its relevance to the query against its similarity to already selected chunks.
  • More diversity can improve topic coverage but admit weaker matches, so tune the relevance-diversity balance against coverage and answer quality.

Why interviewers ask this: The interviewer is evaluating whether you can combine retrieval stages and control redundancy rather than filling context with near-duplicate passages.

nlpembeddings

Text embeddings encode learned features that help place related inputs near one another, not a complete or literal representation of meaning.

  • Their relative geometry is shaped by the training data and objective and can capture semantic or syntactic associations, while individual dimensions usually have no stable human-readable meaning.
  • A high score indicates proximity in that learned space, but it does not establish entailment, factual agreement, or identical intent.
  • Negation, numbers, rare entities, truncation, and domain shift can make apparently similar vectors hide important differences.
  • Retrieval quality should be measured on labeled task examples, with exact filters or a reranker handling distinctions that embeddings miss.

Why interviewers ask this: The interviewer is checking whether the candidate understands both the useful abstraction provided by embeddings and the limits of treating similarity as meaning or truth.

nlpembeddings

I would benchmark candidate models on representative queries and documents while balancing relevance against dimension, throughput, and total cost.

  • The training data and multilingual evaluation should cover the domain terminology, languages, and cross-language retrieval patterns the task requires.
  • Higher dimension can preserve more signal, but it increases vector storage, memory bandwidth, and index work without guaranteeing better task quality.
  • Maximum input length, tokenization, batching throughput, licensing, and per-token or compute cost affect whether a model fits the constraints.
  • Recall@k or nDCG on a labeled set should drive the final choice, followed by an end-to-end check with the intended retrieval pipeline.

Why interviewers ask this: A strong answer treats model selection as an empirical trade-off rather than assuming that the largest or newest embedding model is best.

nlpembeddingsqueries

Asymmetric embeddings encode queries and documents for different roles while mapping both into a shared space where relevant pairs score highly.

  • The query encoder or instruction emphasizes a short information need, while the document side represents richer evidence that can satisfy it.
  • The two sides may use shared weights with different prefixes or separate encoders trained together with a contrastive objective.
  • They are useful when query and document distributions differ, such as a short question retrieving a long passage.
  • Each side must use the model's prescribed query and document mode because symmetric encoding can reduce retrieval quality.

Why interviewers ask this: The interviewer wants the candidate to distinguish role-aware retrieval encoding from simply applying one generic sentence encoder to every text.

vector-db

These metrics rank vectors differently unless vector norms are controlled, so the search metric must match the model's training objective and normalization.

  • Cosine similarity compares direction and ignores magnitude by dividing the dot product by both vector norms.
  • Dot product includes both direction and magnitude, which matters when the model has learned useful information in vector length.
  • Euclidean distance measures straight-line separation, with smaller values indicating closer vectors.
  • For unit-normalized vectors, dot product equals cosine similarity and squared Euclidean distance equals 2 minus 2 times cosine similarity.

Why interviewers ask this: The interviewer is evaluating whether the candidate can connect metric choice, normalization, and ranking behavior instead of treating all vector distances as interchangeable.

nlpembeddingsfine-tuning

I would fine-tune only after a measured baseline shows recurring domain distinctions that a general model fails to capture and suitable training pairs are available.

  • Error analysis should first rule out simpler causes such as poor chunking, weak labels, or a mismatched similarity metric.
  • Training examples should pair realistic queries with relevant items and include informative negatives under a contrastive or ranking loss.
  • The train and validation split should separate related documents, entities, or users so near-duplicates cannot inflate retrieval scores.
  • I would compare against the original model on domain recall and broader validation data, then keep the tuned model only if the gain justifies its added cost.

Why interviewers ask this: A strong answer shows that fine-tuning is a data-driven response to a specific retrieval gap, not the default first step.

nlpembeddingsbatch

Both provide non-relevant examples that shape the embedding boundary, but hard negatives are deliberately confusing while in-batch negatives are reused for efficiency.

  • Hard negatives are close to the query yet incorrect, and they can be mined with lexical search, an earlier model, or human judgments.
  • In-batch training treats the positive documents for other queries in the same batch as negatives, creating many comparisons without extra encoding.
  • False negatives must be masked because another query's positive may also be relevant to the current query, especially in duplicate or multi-answer data.
  • Diverse batches, an appropriate loss temperature, and a mix of easy and hard negatives usually produce more stable learning than only extreme negatives.

Why interviewers ask this: The interviewer is checking whether the candidate understands how negative sampling improves discrimination and how careless sampling can teach the model incorrect relationships.

indexes

HNSW organizes vectors as a multilayer proximity graph and performs an approximate greedy search from sparse upper layers to a dense base layer.

  • Each inserted vector receives a random maximum layer and connects to nearby neighbors, with M limiting roughly how many links each node keeps.
  • Search descends through upper layers to find a promising region, then explores a candidate queue on the base layer.
  • Larger M and efConstruction generally improve graph connectivity and recall, but increase memory, index build time, and insertion work.
  • Larger efSearch examines more candidates and usually improves recall at the cost of query latency, and it must be at least as large as the requested result count.

Why interviewers ask this: A strong answer explains the graph mechanics and separates build-time parameters from the query-time recall and latency control.

vector-db

IVF limits search to selected coarse clusters, while product quantization stores compact codes and estimates distances instead of comparing every full vector exactly.

  • IVF trains centroids, assigns each vector to an inverted list, and probes only the nearest nprobe lists for a query.
  • Product quantization splits vectors or residuals into subvectors and represents each part by the index of a learned codeword.
  • Probing more lists improves IVF recall but adds latency, while stronger compression saves memory and bandwidth but increases distance error.
  • More centroids, subquantizers, or code bits can improve accuracy at additional training, storage, or lookup cost; exact reranking is possible only if full-precision vectors are retained or fetched, and it cannot recover candidates missing from the shortlist.

Why interviewers ask this: The interviewer is evaluating whether the candidate can explain both stages of compressed approximate search and tune them as explicit recall, latency, and memory trade-offs.

indexes

Mutable vector stores commonly represent an update as a new insertion and hide old entries with tombstones until compaction rebuilds cleaner index structures.

  • An update must replace or invalidate the previous vector for the same logical ID so only the newest live version is returned.
  • A delete can mark an entry with a tombstone immediately even when removing it from graph links or compressed segments in place is expensive.
  • Searches filter tombstoned records, but accumulated dead entries consume space and can increase candidate work or reduce graph quality.
  • Compaction rewrites segments or rebuilds the index from live records, reclaiming space while preserving ID mappings and a consistent view of the data.

Why interviewers ask this: The interviewer wants to see that the candidate understands why mutable vector indexes often separate logical deletion from physical reclamation.

databaseshardingreplication

Sharding partitions vectors across nodes to increase capacity, while replication keeps copies of each shard to improve availability and read throughput.

  • Hashing a high-cardinality key tends to balance data, while tenant-based sharding localizes ownership but can create skew or hot shards when tenants differ greatly in size.
  • A global nearest-neighbor query often requests local top results from every required shard and merges them into a final top-k; selective shard routing reduces fan-out but can reduce recall if routing is wrong.
  • Replicas must share compatible vectors and index settings, while the chosen consistency policy determines when recent writes become visible on each copy.
  • More shards add routing and merge overhead, and more replicas add storage and write work, so both counts should follow capacity, latency, and failure requirements.

Why interviewers ask this: A strong answer distinguishes partitioning from redundancy and recognizes the query and consistency costs introduced by distributing vector search.

Locked questions

  • 21

    How do you decide whether a knowledge-intensive LLM application needs RAG or fine-tuning?

    ragfine-tuningllm
  • 22

    When would you choose full fine-tuning over PEFT methods such as LoRA?

    fine-tuning
  • 23

    How do ordinary prompting, prompt tuning, and instruction fine-tuning differ?

    promptingfine-tuning
  • 24

    What is continued pretraining, and when is it useful for domain adaptation?

  • 25

    Why can fine-tuning cause catastrophic forgetting, and how does the training data mixture reduce it?

    fine-tuning
  • 26

    What makes a high-quality chat fine-tuning dataset, and why must its conversation format match the model?

    fine-tuning
  • 27

    How do you budget tokens within an LLM context window?

    contexttokensllm
  • 28

    How do context compression, summarization, and selective retrieval differ as ways to fit useful information into a context window?

    retrievalcontext
  • 29

    What is the lost-in-the-middle effect, and how should it influence evidence ordering?

  • 30

    What types of conversational memory can an LLM application use, and what are the trade-offs of summarized memory?

    llmmemory
  • 31

    How would you structure a layered evaluation for a RAG system?

    ragsystem-designllm-eval
  • 32

    How do Recall@k, MRR, and nDCG evaluate retrieval differently?

    retrievaldecision-makingllm-eval
  • 33

    What do groundedness, faithfulness, answer relevance, and completeness measure in RAG evaluation?

    raggroundednessllm-eval
  • 34

    What biases affect LLM-as-judge evaluation, and how would you calibrate the judge?

    llmllm-eval
  • 35

    How should golden, synthetic, and adversarial examples be used in an AI evaluation set?

    llm-eval
  • 36

    When would you use reference-based versus reference-free evaluation for LLM answers?

    llmllm-eval
  • 37

    How would you design a human evaluation rubric and assess inter-rater agreement?

    llm-evaldesign
  • 38

    How would you design a controlled experiment to compare two prompts or models?

    promptingdesignforms
  • 39

    What is a basic agent loop, and how does a planner-executor architecture extend it?

    agentsarchitecture
  • 40

    What makes a good function-calling schema and tool description for an LLM?

    llmschemaon-call
  • 41

    How should an agent decide which tool to call for a given step?

    agents
  • 42

    What is the difference between agent state, short-term memory, and long-term memory?

    agentsmemory
  • 43

    How would you define stopping conditions and budgets for an agent loop?

    agents
  • 44

    Why is structured function calling usually preferable to parsing free-form model text?

    tool-useforms
  • 45

    How should an AI agent be evaluated beyond judging whether its final answer sounds good?

    agentsdecision-makingllm-eval
  • 46

    What framework would you use to select a model for an AI feature?

  • 47

    How do open-weight models compare with hosted closed models?

  • 48

    When should you use a small model, a large model, or a cascade of both?

  • 49

    How do temperature and top-p affect language-model decoding?

    decoding
  • 50

    When would you choose a reasoning model over a standard instruction model?

  • 51

    A production RAG assistant often misses documents that clearly contain the answer. How would you diagnose and improve retrieval recall?

    ragretrieval
  • 52

    Your retriever usually includes the answer, but most returned chunks are irrelevant and degrade generation. What would you change?

  • 53

    How would you choose chunk size and overlap for a RAG corpus containing policies, manuals, and tables?

    rag
  • 54

    After adding metadata filters, some authorized users can no longer retrieve documents they should see. How would you find and fix the problem?

  • 55

    Dense retrieval handles paraphrases well but misses product codes and exact technical terms. How would you introduce hybrid dense and sparse search?

    retrieval
  • 56

    You want to add a cross-encoder reranker to RAG, but the endpoint already has a tight latency budget. How would you roll it out?

    ragrerankinglatency
  • 57

    Users receive answers from documents that were updated or deleted yesterday. How would you make the RAG index stay fresh?

    ragindexes
  • 58

    In a multi-turn support chat, follow-up questions such as 'Does it apply to Europe?' retrieve unrelated documents. How would you implement query rewriting?

    queries
  • 59

    How would you make a RAG assistant return citations that users can open and verify against the source?

    ragcitations
  • 60

    A multilingual RAG system performs well in English but poorly in Spanish and German. How would you diagnose and improve it?

    ragsystem-design
  • 61

    A RAG assistant invents a policy detail even though the correct document appears in the retrieved context. How would you diagnose and fix it?

    rag
  • 62

    How would you make a support assistant refuse to answer when the knowledge base does not provide enough evidence without causing excessive refusals?

  • 63

    A retrieved web page contains text telling the model to ignore its instructions and call an internal tool. What protections would you add?

  • 64

    Answer quality dropped after a small system prompt edit, but aggregate latency and error metrics look normal. How would you investigate the regression?

    latencysystem-designmonitoring
  • 65

    You can add only four few-shot examples to a ticket-classification prompt. How would you choose them?

    classificationprompting
  • 66

    An extraction endpoint returns valid JSON most of the time, but occasionally adds prose, omits required fields, or uses the wrong types. How would you stabilize it?

    endpoints
  • 67

    How would you version and release a prompt change for a production summarization feature so that failures are easy to trace and reverse?

    promptingtracing
  • 68

    A model answers correctly when a key passage is near the start of the context but misses it when the same passage is in the middle. What would you change?

  • 69

    A scheduling assistant chooses the right tool but sometimes sends an invalid date range or a customer ID from the conversation instead of the authenticated user. How would you fix this?

    jobs
  • 70

    A RAG answer receives two retrieved policy documents that disagree about the refund window. How should the system respond and how would you test the behavior?

    ragsystem-designconflict
  • 71

    How would you assemble the first golden evaluation set for an LLM feature that already has production traffic?

    llmllm-eval
  • 72

    Users leave thumbs-down feedback and support tickets about an LLM assistant; how do you turn that feedback into useful eval cases?

    llmfeedback
  • 73

    Before using an LLM as a judge in CI, how would you check whether its scores are reliable enough?

    llm
  • 74

    A provider releases a new model version and your eval score drops; how do you determine whether to adopt or block the update?

    decision-making
  • 75

    A RAG system's answer quality has fallen; how would you determine whether retrieval or generation is responsible?

    ragretrievalsystem-design
  • 76

    How would you build a practical red-team evaluation for the guardrails of an LLM agent that can call tools?

    agentsllmguardrails
  • 77

    How would you evaluate both factuality and citation correctness in answers produced by a RAG assistant?

    ragcitationsdecision-making
  • 78

    An LLM eval alternates between passing and failing on unchanged code; how do you diagnose and handle the flakiness?

    llm
  • 79

    The aggregate eval score is unchanged, but one customer cohort reports worse answers; how would you investigate the hidden regression?

    cohortsaggregation
  • 80

    How would you set acceptance thresholds for an LLM feature before evaluating a release candidate?

    llmllm-eval
  • 81

    An LLM feature has a p95 latency of nine seconds, but the team only measures total request time; how would you find and reduce the delay?

    latencyllm
  • 82

    Users wait several seconds before seeing an answer because your API buffers the full LLM response; what would you change to improve time to first token?

    tokensllmapi
  • 83

    A support assistant repeats many similar requests, and you want exact and semantic caching without serving stale or cross-customer answers; how would you implement it?

    caching
  • 84

    Most requests can use a cheap model, but difficult ones lose accuracy unless they reach a stronger model; how would you add routing?

  • 85

    Token spend doubled after adding retrieval and longer answers to an LLM feature; how would you reduce cost without blindly lowering model quality?

    retrievaltokensllm
  • 86

    During a traffic peak, your LLM provider starts returning rate-limit errors even though the service itself is healthy; how would you stabilize requests?

    llm
  • 87

    A reranking stage occasionally times out and causes the entire RAG request to fail; how would you preserve a useful partial response?

    ragreranking
  • 88

    Your primary model fails intermittently, but the fallback model produces different JSON fields and weaker answers; how would you make fallback safe?

  • 89

    A burst of document-analysis requests exhausts workers and makes interactive LLM calls time out; how would you introduce backpressure?

    llmbackpressure
  • 90

    Your LLM provider has a complete outage during business hours; what should the application do in the first minutes and during recovery?

    llm
  • 91

    A user reports one incorrect answer from an LLM application that uses retrieval and tools; how would you trace that request end to end?

    retrievalllm
  • 92

    How would you prevent personal data from leaking through prompts and application logs while preserving enough information to debug failures?

    promptingdiscovery
  • 93

    A newly enabled guardrail is blocking many harmless user requests; how would you reduce false positives without weakening protection blindly?

    guardrailsllm-safety
  • 94

    A customer receives a RAG answer citing another customer's document; what would you do to contain, diagnose, and fix the tenant leak?

    rag
  • 95

    How would you migrate a production RAG system to a new embedding model without breaking search for existing documents?

    nlpragembeddings
  • 96

    Documents in the source system are updated or deleted, but the vector database still returns old chunks; how would you repair and prevent this drift?

    vector-dbdatabasesystem-design
  • 97

    An asynchronous document ingestion job fails after creating some chunks, and retries sometimes create duplicates; how would you make reprocessing safe?

    async
  • 98

    Several production users complain that the assistant gives unhelpful answers, but their reports are vague; how would you turn those complaints into fixes and evaluations?

    llm-eval
  • 99

    A PM wants to launch an LLM feature next week and asks whether its quality is good enough; how would you agree on a realistic quality bar and limited rollout?

    llm
  • 100

    Answer quality drops sharply immediately after an LLM application release; how would you diagnose the regression end to end?

    llm