Interview preparation
AI Interview Questions and Answers
66 questions that come up in AI engineer, machine learning engineer and prompt engineer interviews, each with a sample answer you can adapt. Try answering out loud first, then tap a question to compare with the sample answer.
AI and Machine Learning Fundamentals
The basics nearly every AI interview opens with.
What is the difference between AI, machine learning and deep learning?
AI is the broad goal of making machines perform tasks that normally need human intelligence. Machine learning is one way to get there: instead of writing every rule by hand, the system learns patterns from data.
Deep learning is a subset of machine learning that uses neural networks with many layers. It powers modern image recognition, speech and large language models.
Interview tip: Draw three nested circles: AI contains ML, and ML contains deep learning.
Explain supervised, unsupervised and reinforcement learning.
Supervised learning trains on labelled examples, such as emails marked spam or not spam, and learns to predict the label for new inputs.
Unsupervised learning finds structure in unlabelled data, for example clustering customers into segments.
Reinforcement learning trains an agent by trial and error: it takes actions in an environment and learns from rewards and penalties.
What is overfitting, and how do you prevent it?
Overfitting happens when a model memorises the training data, including its noise, so it scores well in training but poorly on new data.
You prevent it with more or better data, regularisation (such as L2 or dropout), simpler models, early stopping, and by always checking performance on a separate validation set.
Interview tip: Mention the signal you would look for: training accuracy keeps rising while validation accuracy flattens or drops.
What is the bias-variance trade-off?
Bias is error from overly simple assumptions, which leads to underfitting. Variance is error from being too sensitive to the training data, which leads to overfitting.
Making a model more complex usually lowers bias but raises variance. The goal is the balance that gives the lowest error on unseen data.
When would you use precision, recall or F1 score instead of accuracy?
Accuracy is misleading when classes are imbalanced. If 1% of transactions are fraud, a model that always says 'not fraud' is 99% accurate and useless.
Use precision when false positives are costly, such as flagging legitimate payments. Use recall when false negatives are costly, such as missing a disease. F1 is the harmonic mean of the two and is useful when you need a balance.
Why do we split data into training, validation and test sets?
The training set fits the model. The validation set is used to tune choices such as hyperparameters and prompts. The test set is kept untouched until the end to give an honest estimate of real-world performance.
If you tune on the test set, its score stops being a fair measure because you have indirectly fitted to it.
Large Language Models and Prompt Engineering
How LLMs work and how to get reliable output from them.
How does a large language model generate text?
An LLM is a transformer trained on huge amounts of text to predict the next token. At generation time it repeatedly predicts a probability distribution over the next token, picks one, appends it and repeats.
Settings such as temperature control how the next token is chosen: low temperature picks the most likely tokens, higher temperature allows more variety.
What are tokens and the context window, and why do they matter?
Tokens are the chunks of text a model reads and writes, often parts of words. The context window is the maximum number of tokens the model can handle in one request, counting both the input and the output.
They matter for cost (APIs bill per token), latency, and design: long documents may not fit, so you need retrieval, summarisation or chunking.
What is self-attention in a transformer?
Self-attention lets every token look at every other token in the sequence and decide how much each one matters for its own meaning. For example, in 'the trophy didn't fit in the suitcase because it was too big', attention helps link 'it' to 'trophy'.
Because attention is computed in parallel rather than word by word, transformers train efficiently on very large datasets.
What prompt engineering techniques do you use most?
Clear, specific instructions with context about the goal and audience; a defined output format; few-shot examples when the pattern is hard to describe; delimiters such as XML tags to separate instructions from data; and asking the model to reason step by step on complex problems.
For production, I keep prompts in version control and test changes against a fixed set of example inputs rather than judging from a single try.
Interview tip: Interviewers like hearing that you evaluate prompts, not just write them.
What are hallucinations, and how do you reduce them?
A hallucination is when the model states something false or unsupported with confidence.
To reduce them: ground the model in source documents (RAG), tell it to answer only from the provided context and to say when it doesn't know, ask for citations, lower the temperature for factual tasks, and add automated checks or human review for high-stakes output.
When would you fine-tune a model instead of using prompting or RAG?
Start with prompting because it is cheapest and fastest to change. Add RAG when the model needs knowledge it lacks, especially private or frequently changing information.
Fine-tune when you need consistent behaviour that prompting can't reliably achieve, such as a strict output style, a specialised classification task at scale, or a smaller, cheaper model that matches a larger one on a narrow task.
RAG and Vector Search
Retrieval-augmented generation is the most common pattern in AI engineering roles.
What is retrieval-augmented generation (RAG)?
RAG retrieves relevant pieces of your own documents and adds them to the prompt so the model answers from that context.
It lets the model use private or up-to-date knowledge without retraining, and makes answers easier to verify because you can cite the sources.
Walk me through the components of a RAG pipeline.
Ingestion: load documents, clean them, split them into chunks, create embeddings and store them in a vector database with metadata.
Query time: embed the user's question, retrieve the most similar chunks (often with hybrid keyword and vector search plus a reranker), build a prompt with those chunks and generate the answer, ideally with citations.
Interview tip: Sketching the two phases, ingestion and query, on a whiteboard makes this answer much stronger.
How do you choose a chunk size?
Chunks that are too small lose the context needed to answer; chunks that are too large dilute relevance and waste the context window. A few hundred tokens with a small overlap is a common starting point.
The right answer comes from testing: build a set of real questions, try different chunk sizes and splitting strategies (by headings or paragraphs instead of fixed length), and measure retrieval quality.
What is hybrid search, and why use a reranker?
Hybrid search combines keyword search such as BM25, which is good at exact terms like product codes and names, with vector search, which is good at meaning. Results are merged, for example with reciprocal rank fusion.
A reranker is a slower but more accurate model that re-scores the top candidates against the query, so the best chunks reach the prompt.
How do you evaluate a RAG system?
Evaluate retrieval and generation separately. For retrieval, measure whether the right chunks appear in the top results (recall@k, MRR). For generation, check faithfulness (is the answer supported by the retrieved context?), relevance and correctness.
Use a test set of real questions with expected answers or sources, and combine automated LLM-as-judge scoring with human spot checks.
Your RAG chatbot gives wrong answers. How do you debug it?
First look at what was retrieved for the failing questions. If the right information was never retrieved, fix ingestion and retrieval: parsing, chunking, embeddings, filters or search settings.
If the right chunks were retrieved but the answer is still wrong, fix the generation step: the prompt, the order and amount of context, or the model choice.
Interview tip: Saying 'retrieval first, then generation' shows a structured debugging approach.
AI Agents and Tool Use
Agentic AI questions are increasingly common for AI engineer roles.
What is an AI agent, and how is it different from a chatbot?
A chatbot answers in one turn. An agent works toward a goal over several steps: the model decides which tool to call, the application runs it, the result goes back to the model, and the loop continues until the task is done.
Agents can search, read files, call APIs or write code, which makes them more capable but also harder to control and test.
How does tool calling (function calling) work?
You describe each tool to the model with a name, a description and a JSON schema for its parameters. When the model wants to use one, it returns a structured tool call with arguments.
Your application validates the arguments, runs the function and sends the result back to the model. The model never executes anything itself, which is where you add permission checks and logging.
When should you not use an agent?
When the steps are known in advance. A fixed workflow, such as extract then summarise then classify, is cheaper, faster, easier to test and more predictable than letting a model decide each step.
Use an agent when the path genuinely depends on what the model discovers along the way, such as open-ended research or multi-step troubleshooting.
Interview tip: This question tests judgement. Showing you would pick the simplest option that works is the right answer.
How do agents handle memory?
Short-term memory is the conversation and tool results in the current context window. Long-term memory is information saved to an external store, such as a database or vector index, and retrieved when relevant.
Long runs also need context management, such as summarising or dropping old tool output, so the context window doesn't fill up.
How would you make an agent safe to run in production?
Give tools the least privilege they need, validate every tool argument, require human approval for irreversible or high-impact actions such as payments or sending email, and set limits on steps, time and cost.
Treat content from web pages, emails and documents as untrusted data to defend against prompt injection, and trace every step so failures can be investigated.
What frameworks and protocols have you used for building agents?
Common choices are LangChain for building blocks, LangGraph for stateful agent workflows modelled as graphs, and provider SDKs that support tool calling directly. The Model Context Protocol (MCP) is an open standard for connecting AI applications to tools and data sources.
Be ready to explain why you picked one: for example, LangGraph when you need explicit control over loops, branching and human-in-the-loop checkpoints.
Interview tip: Answer with a real project: what you built, which framework, and one problem you hit.
Production, Evaluation and Responsible AI
Questions that separate demo builders from engineers who ship.
How do you evaluate an LLM application?
Build an evaluation set of realistic inputs with expected outputs or grading criteria. Score outputs with code-based checks where possible (format, exact match), an LLM-as-judge with a clear rubric for open-ended answers, and regular human review.
Run the evaluation on every prompt or model change so you catch regressions before users do.
How do you reduce latency and cost in an LLM app?
Use the smallest model that meets the quality bar, route easy requests to cheaper models, shorten prompts, use prompt caching for repeated context, cache full responses where appropriate, and stream output so users see text sooner.
Batch non-urgent work, and measure token usage per feature so you know where the money goes.
What is prompt injection, and how do you defend against it?
Prompt injection is when untrusted text, such as a web page, email or user input, contains instructions that try to override your application's instructions.
Defences include clearly separating instructions from data, never giving the model more permissions than the task needs, requiring confirmation for sensitive actions, filtering inputs and outputs, and monitoring for unusual behaviour. No single defence is complete, so layer them.
What do you monitor once an AI feature is live?
Latency, error rates, token usage and cost; quality signals such as user feedback, thumbs up or down, and sampled human review; and safety signals such as refusals and flagged content.
Tracing tools such as LangSmith or Langfuse record each step and tool call, which makes it possible to debug individual bad answers.
How do you handle bias and fairness in AI systems?
Check training and evaluation data for gaps in who and what is represented, test outputs across different user groups, and measure whether error rates differ between them.
Keep humans in the loop for decisions that affect people's lives, document known limitations, and give users a way to report problems.
Deep Learning
Neural network fundamentals that ML and AI engineer interviews still test.
What is backpropagation?
Backpropagation is how a neural network works out how much each weight contributed to the error. After a forward pass produces a prediction and a loss, it applies the chain rule from the output layer backwards to compute the gradient of the loss with respect to every weight.
An optimiser such as SGD or Adam then uses those gradients to adjust the weights a small step in the direction that reduces the loss.
Why do neural networks need activation functions, and why is ReLU so common?
Without a non-linear activation, stacking layers just produces another linear function, so the network could not learn complex patterns.
ReLU is cheap to compute and, unlike sigmoid or tanh, does not squash large inputs, which reduces vanishing gradients. Its weakness is 'dead' units that output zero for every input; variants such as Leaky ReLU and GELU (used in most transformers) address that.
What are vanishing and exploding gradients, and how do you deal with them?
In deep networks, gradients are multiplied through many layers, so they can shrink towards zero (early layers stop learning) or grow uncontrollably (training becomes unstable).
Common fixes are ReLU-family activations, sensible weight initialisation (He or Xavier), normalisation layers, residual connections, and gradient clipping, which is especially common when training recurrent networks and transformers.
Explain dropout and batch normalisation.
Dropout randomly switches off a fraction of activations during training, so the network cannot rely on any single path and generalises better. It is turned off at inference time.
Batch normalisation rescales each layer's inputs using statistics from the current batch, which stabilises and speeds up training. Transformers usually use layer normalisation instead, which normalises across features for each example and does not depend on batch size.
Compare CNNs, RNNs and transformers.
CNNs use convolution filters to detect local patterns and are a natural fit for images. RNNs process sequences one step at a time with a hidden state, but struggle with long-range dependencies and are hard to parallelise.
Transformers use self-attention to relate every position to every other position at once, which parallelises well on GPUs and handles long context. They now dominate language tasks and are widely used for vision (Vision Transformers) and audio too.
Interview tip: Mention trade-offs, not just definitions: transformers cost more memory as sequences get longer.
What is transfer learning?
Transfer learning reuses a model trained on a large general dataset as the starting point for a new task. You then fine-tune it on a smaller, task-specific dataset, sometimes freezing the early layers.
It works because early layers learn general features, such as edges in images or grammar in text, that are useful across many tasks. It cuts the data and compute you need dramatically.
How do you choose a learning rate?
Too high and the loss jumps around or diverges; too low and training is slow or gets stuck. A learning-rate range test, where you increase the rate over a short run and watch the loss, is a quick way to find a sensible range.
Most modern training uses a schedule: a short warm-up, then decay such as cosine. Fine-tuning a pre-trained transformer typically uses a much smaller learning rate than training from scratch.
Python and Coding for AI
Practical coding questions for AI engineering roles.
What is the difference between a list, a tuple, a set and a dictionary in Python?
A list is an ordered, changeable sequence. A tuple is ordered but immutable, so it can be used as a dictionary key. A set stores unique items with fast membership checks. A dictionary maps keys to values with fast lookup by key.
Choosing well matters for performance: checking whether an item is in a set or dict is on average constant time, while checking a list means scanning it.
What are generators, and why are they useful for large datasets?
A generator produces values one at a time with yield, instead of building a whole list in memory. Nothing is computed until the next value is requested.
That makes generators ideal for streaming large files, reading data in batches for training, or processing documents for a RAG index without loading everything at once.
How would you make thousands of LLM API calls efficiently?
Use asynchronous requests (asyncio with an async HTTP client or the provider's async SDK) so calls overlap instead of waiting one by one, and cap concurrency with a semaphore to stay within rate limits.
Add retries with exponential backoff for rate-limit and server errors, cache repeated requests, and use the provider's batch API for work that doesn't need an immediate answer, since it is usually cheaper.
Interview tip: Interviewers like hearing about rate limits and retries, because that is what breaks in production.
What is vectorisation in NumPy, and why is it faster?
Vectorisation means applying an operation to a whole array at once, for example a * 2 or a + b, instead of looping in Python. The work runs in optimised C code over contiguous memory.
Broadcasting extends this to arrays of different shapes. The result is often tens to hundreds of times faster than an equivalent Python loop.
How do you test code that calls an LLM?
Separate concerns. Unit-test your own logic, such as prompt building, parsing and validation, with the model client mocked so tests are fast and deterministic.
Test model behaviour separately with an evaluation set of real inputs and expected properties, and validate structured outputs against a schema. Run the evaluations whenever you change a prompt or model.
How do you handle API keys and configuration in an AI application?
Keep secrets out of code and version control: load them from environment variables or a secrets manager, and add local .env files to .gitignore.
Use separate keys for development and production, give each key the least access it needs, and rotate keys if one may have leaked.
Data, Statistics and Features
The data questions that catch many candidates out.
How do you handle missing data?
First find out why it is missing, because data missing at random needs different treatment from data missing for a reason. If very few rows are affected, dropping them may be fine.
Otherwise, impute with the mean, median or most common value, or with a model, and consider adding an indicator column that marks the value as missing. Calculate imputation values from the training set only to avoid leakage.
What is data leakage?
Data leakage is when information that would not be available at prediction time gets into training, so the model looks better in evaluation than it will be in real use.
Common causes are scaling or imputing using the whole dataset before splitting, features that are derived from the target, and random splits of time-series data. Split first, use pipelines, and split time series by date.
Interview tip: A model that seems too good to be true is a classic leakage warning sign. Say that you would investigate.
How do you deal with an imbalanced dataset?
Start with the right metrics, such as precision, recall and the precision-recall curve, because accuracy hides the problem. Then try class weights, resampling (oversampling the minority class or undersampling the majority), and tuning the decision threshold.
Often the most effective fix is collecting more examples of the rare class.
Explain cross-validation.
In k-fold cross-validation, the data is split into k parts. The model is trained k times, each time holding out a different part for validation, and the scores are averaged. This gives a more reliable estimate than a single split.
Use stratified folds for classification so each fold keeps the class balance, and use time-based splits for time series so you never validate on the past using the future.
What does a p-value tell you in an A/B test?
A p-value is the probability of seeing a difference at least as large as the one observed if there were really no difference. A small p-value suggests the result is unlikely to be chance alone. It is not the probability that the new version is better.
Decide the sample size and test duration in advance, and avoid stopping the test as soon as the result looks significant, because repeated peeking inflates false positives.
When is feature scaling needed?
Scaling, such as standardising to mean zero and unit variance, matters for models that use distances or gradients: k-nearest neighbours, support vector machines, linear models with regularisation, and neural networks.
Tree-based models such as random forests and gradient boosting split on thresholds, so they generally do not need scaling.
What is the difference between correlation and causation?
Correlation means two variables move together; causation means changing one changes the other. A third factor, a confounder, can create a correlation without any causal link.
Randomised experiments such as A/B tests are the most reliable way to establish causation, because random assignment balances out confounders.
ML System Design
Open-ended design questions for mid-level and senior roles.
How would you design a spam detection system?
Clarify the goal first: it matters more not to block real messages, so precision on the spam label is critical. Labels can come from user reports and moderators.
Start with a simple, fast baseline such as logistic regression on text features, then try a fine-tuned transformer if it is worth the extra cost. Set the threshold based on the cost of each kind of mistake, retrain regularly because spammers adapt, and monitor for drift.
Interview tip: Structure every design answer the same way: requirements, data, model, serving, evaluation, monitoring.
How would you design a recommendation system?
Use stages. Candidate generation narrows millions of items to hundreds, using collaborative filtering or embedding models. A ranking model then scores those candidates with richer features, and a final step re-ranks for diversity and business rules.
Handle new users and items (the cold-start problem) with content features and popularity. Measure offline with metrics such as recall@k and NDCG, then confirm with an online A/B test.
What is model drift, and how do you detect it?
Data drift is when the inputs change, for example new customer groups. Concept drift is when the relationship between inputs and the right answer changes, for example new fraud tactics.
Monitor input and prediction distributions with statistics such as the population stability index, track performance whenever fresh labels arrive, and retrain on a schedule or when monitoring raises an alert.
When would you use batch inference instead of real-time inference?
Batch inference computes predictions in bulk on a schedule, for example nightly recommendations. It is cheaper and simpler, but results can be out of date.
Real-time inference answers each request as it arrives, which is needed when the input is only known at that moment, such as fraud checks on a payment. Many systems combine both.
How would you design an LLM-powered customer support assistant?
Ground answers in the help-centre content with RAG, add tools for account-specific questions (such as order status) behind proper authentication, and hand off to a human when the assistant is unsure or the customer asks.
Add guardrails for off-topic and unsafe requests, build an evaluation set from real tickets, log conversations for review, and track resolution rate, escalation rate, cost and customer satisfaction.
How do you safely roll out a new model?
Run it in shadow mode first, where it makes predictions on live traffic without affecting users, and compare it with the current model. Then send a small, randomised share of traffic to it in an A/B test.
Agree the main success metric and guardrail metrics in advance, run the test long enough, check important user segments, and keep a quick way to roll back.
Generative AI in Depth
Advanced LLM questions for AI engineer and research-adjacent roles.
What is LoRA, and why is it popular for fine-tuning?
LoRA (low-rank adaptation) freezes the original model weights and trains small additional matrices that are added to some layers. Only a tiny fraction of parameters is trained, so it needs far less GPU memory.
The resulting adapters are small files that can be swapped in and out of the same base model. QLoRA goes further by keeping the frozen base model in 4-bit precision during training.
What is quantisation?
Quantisation stores model weights, and sometimes activations, in lower precision, such as 8-bit or 4-bit numbers instead of 16-bit. This cuts memory use and often speeds up inference.
The trade-off is a usually small drop in quality, so you should evaluate a quantised model on your own task before relying on it.
What is the difference between RLHF and DPO?
Both align a model with human preferences using pairs of responses where one is preferred. RLHF first trains a separate reward model on those comparisons, then optimises the language model against it with reinforcement learning.
DPO (direct preference optimisation) skips the separate reward model and the reinforcement-learning loop, training directly on the preference pairs. It is simpler and often more stable to run.
How are embedding models different from chat models?
An embedding model turns text into a fixed-length vector so that similar meanings end up close together. It is used for search, clustering and recommendations, not for generating text.
Choose one based on retrieval benchmarks for your language and domain, the vector size (which affects storage and speed), cost, and whether queries and documents need different instructions.
What is the difference between temperature and top-p sampling?
Temperature reshapes the probability distribution over the next token: lower values make likely tokens even more likely, and higher values flatten it. Top-p (nucleus) sampling only samples from the smallest set of tokens whose probabilities add up to p.
Both control randomness, so the usual advice is to adjust one and leave the other at its default.
What are the main risks of putting an LLM into production, and how do you reduce them?
Key risks are hallucinations, prompt injection, leaking private data, biased or unsafe output, and unpredictable cost and latency.
Mitigations include grounding answers in trusted sources, separating instructions from untrusted content, redacting personal data, content filters, human review for high-stakes output, evaluation before each release, rate limits, and a fallback when the model is unavailable.
What is a multimodal model, and where is it useful?
A multimodal model accepts more than one kind of input, such as images and text, and sometimes audio. You can ask questions about a photo, a chart or a scanned document.
Typical uses are extracting fields from invoices and receipts, describing images for accessibility, and answering questions about diagrams. As with text, evaluate accuracy on your own documents before trusting the output.
Project and Behavioural Questions
How to talk about your own work with confidence.
Tell me about an AI project you built.
Use a clear structure: the problem and who it was for, your approach and why you chose it, the technical challenges, how you measured success, and what you would do differently.
Give numbers where you can, for example 'retrieval recall went from 60% to 85% after switching to heading-based chunking and adding a reranker'.
Interview tip: Prepare two projects in depth. A smaller project you can explain fully beats a big one you only partly understand.
How do you keep up with fast-moving AI developments?
Name specific habits: following model release notes and documentation from major providers, reading a few trusted newsletters or papers, and, most importantly, building small experiments with new techniques.
Interviewers want to hear that you test new ideas yourself rather than only reading headlines.
Describe a time an AI model or feature did not work as expected.
Pick a real example and use the STAR format: situation, task, action, result. Focus on how you diagnosed the issue, for example by looking at traces or building a small evaluation set, and what you changed.
End with what you learned and how you now prevent similar problems.
How would you explain a technical AI concept to a non-technical stakeholder?
Start from the business outcome, use a simple analogy (RAG is like giving the model an open-book exam with the right pages bookmarked), avoid jargon, and be honest about limitations and risks.
Offer to show a short demo, because seeing the system work is often clearer than any explanation.
How to use these answers
- Don't memorise word for word. Interviewers notice scripted answers.
- Add one real example from your own projects to every answer.
- Practise out loud, and keep most answers under two minutes.
- Check your understanding with the AI Skills practice tests.