AI Engineer
Interview Questions.

All 566 questions and 6 core concepts across the 15 sections of Amit Shekhar’s repository. Choose English, Japanese or Vietnamese for both questions and answers.

AI Engineering Interview Questions · Amit Shekhar ↗
~/notes/interview

The original order.
Every source question.

15 sections · 566 questions · 6 concepts

Open a question for a concise answer focused on the key points. Translations and answers are prepared for this blog; source materials are listed under Further reading.

Complete question bank

572 items · 15 sections

Must Know

6 concepts
01LLM

LLM is a model that learns from large amounts of text to predict the next token. It can generate, classify and summarize content but does not guarantee the information is always correct.

Further reading

Learn about the LLM, RAG, MCP, Agent, Fine-tuning & Quantization: AI Engineering Explained: LLM, RAG, MCP, Agent, Fine-Tuning, Quantization

Link to this question
02RAG

RAG retrieves relevant documents and then puts them into context for LLM to respond. Appropriate updated data, source should be cited; Quality depends on both retrieval and generation.

Further reading

Learn about the LLM, RAG, MCP, Agent, Fine-tuning & Quantization: AI Engineering Explained: LLM, RAG, MCP, Agent, Fine-Tuning, Quantization

Link to this question
03MCP

MCP standardizes how AI applications connect to tools, resources, and prompts through a host-client-server architecture. Authentication, authorization, and action approval remain controlled by the application.

Further reading

Learn about the LLM, RAG, MCP, Agent, Fine-tuning & Quantization: AI Engineering Explained: LLM, RAG, MCP, Agent, Fine-Tuning, Quantization

Link to this question
04Agent

Agents combine models, tools, states, and control loops to perform multiple steps. Need clear goals, step/cost limits and stopping conditions.

Further reading

Learn about the LLM, RAG, MCP, Agent, Fine-tuning & Quantization: AI Engineering Explained: LLM, RAG, MCP, Agent, Fine-Tuning, Quantization

Link to this question
05Fine-tuning

Fine-tuning updates weights using task data to improve specific behaviors or abilities. Use when prompt is not enough; Do not substitute retrieval for constantly changing knowledge.

Further reading

Learn about the LLM, RAG, MCP, Agent, Fine-tuning & Quantization: AI Engineering Explained: LLM, RAG, MCP, Agent, Fine-Tuning, Quantization

Link to this question
06Quantization

Quantization reduces the accuracy of representing weights or activations, for example BF16 to INT8/INT4. Saves memory and can speed up if the hardware supports it; quality deterioration assessment is required.

Further reading

Learn about the LLM, RAG, MCP, Agent, Fine-tuning & Quantization: AI Engineering Explained: LLM, RAG, MCP, Agent, Fine-Tuning, Quantization

Link to this question
View this section in the original repository ↗

LLM Fundamentals

80 questions
01What are foundation models, and how have they changed AI engineering?

The Foundation model is pre-trained on extensive data and reused for many tasks. AI engineering shifts the focus to adaptation, integration, evaluation and operation instead of training each model from scratch.

Link to this question
02What is a Large Language Model (LLM), and how does it work?

LLM maps tokens to embedding, processes it using multiple network layers, and then predicts the next token distribution. Generate text by iteratively sampling and appending tokens to the context.

Link to this question
03Inside ChatGPT: What Happens After You Hit Enter?

Essential flow: encapsulate dialogue and instructions, tokenize, prefill, decode each token, then stream the results. Products can add retrieval, tools and filters; ChatGPT internal details are not fully disclosed.

Link to this question
04What is the Transformer architecture and how does it work?

The transformer uses attention to combine information between locations and a feed-forward network to transform the representation. Residual, normalization and location information help with deep training, handling order and distance relations.

Link to this question
05What are the key components of the Transformer architecture?

Main components: embedding, positional representation, attention, feed-forward, residual connection, normalization and vocabulary output. The decoder that generates text also uses a causal mask.

Link to this question
06Walk me through what happens, step by step, in one forward pass of a decoder-only Transformer.

Token embedding goes through each block: normalization, creating Q/K/V, attention with causal mask, adding residual, feed-forward and then adding residual. End normalization and LM head generate logits; The exact layout depends on the architecture.

Link to this question
07What is tokenization in LLMs?

Tokenization breaks text into tokens and maps them to IDs. Tokens can be characters, bytes, or word fragments; The number of tokens affects the cost, context, and ability to handle each language.

Link to this question
08Explain BPE (Byte Pair Encoding).

BPE starts with small symbols and then repeats common pairs to create vocabulary. When encoding, apply learned aggregation operations; Process rare words using smaller pieces.

Further reading

Byte Pair Encoding

Link to this question
09Explain WordPiece and SentencePiece.

WordPiece selects word fragments according to statistical/likelihood criteria, often distinguishing between consecutive fragments. SentencePiece is a raw text tokenization toolkit, supporting BPE or Unigram; not a single algorithm.

Link to this question
10What is positional encoding, and why is it needed in Transformers?

Attention itself does not know the token order. Positional encoding/embedding or RoPE injects positional information into the model to distinguish strings with the same token but different order.

Link to this question
11What are embeddings?

Embedding is an arithmetic vector representing a token, sentence, or object. Useful relationships are learned through targeted training; Vector distance only has meaning according to the specific model and task.

Link to this question
12Explain the Query(Q), Key(K), and Value(V) in attention.

A query represents what the current token is looking for; keys determine relevance; values carry the information to aggregate. Attention computes softmax(QKᵀ/√dₖ)V.

Link to this question
13What is self-attention, and how does it work in Transformers?

Self-attention takes Q, K and V from the same string. Each token aggregates the value of positions according to similarity weights, within the allowable mask range.

Link to this question
14What is Cross Attention in Transformers?

Cross-attention takes query from one string and key/value from another string. For example, the decoder accesses the encoder's representation, or the language model retrieves information from the image.

Link to this question
15Why do we scale the dot product attention by √dₖ in the Transformer architecture?

As dₖ increases, the dot product variance usually increases, causing the softmax to saturate and the gradient to become small. Dividing by √dₖ keeps the logits scale more stable, under the assumption that the components have appropriate variances.

Link to this question
16What is causal masking?

Causal mask covers future positions with negative infinity before softmax. Thanks to that, the current token only relies on the prefix, matching autoregressive generation when reasoning.

Link to this question
17What are multi-head attention mechanisms? Why use multiple attention heads?

Multi-head attention learns multiple Q/K/V projections, calculates attention in parallel and then combines the results. Heads can capture different relationships instead of forcing all information through one attention operation.

Link to this question
18What are Feed-Forward Networks in LLMs?

The FFN independently transforms the representation at each location by projections and nonlinearities, often expanding and then contracting dimensionally. It adds characteristic transformation capacity after the information exchange step of attention.

Link to this question
19What is Generative AI?

Generative AI learns to distribute data to create new content such as text, photos, audio or code. Model-appropriate output does not necessarily mean it is true or has the right to use.

Further reading

What is Generative AI?

Link to this question
20What is the context window in LLMs, and why does it matter?

Context window is the limit of tokens the model can process in one request, usually including input and generation. It determines the amount of history/documents that can be used and affects memory and latency.

Further reading

Context Window in LLMs

Link to this question
21Why is the context window limited in LLMs?

The limit comes from the KV cache, attention cost, positional representation, and trained length. Extending technical limits does not by itself ensure that the model effectively uses the entire context.

Link to this question
22What is temperature in the context of LLMs, and how does it affect output?

Temperature divides logits before softmax: lower values concentrate probability; higher values increase diversity. It controls randomness, not correctness; low temperature can still produce hallucinations.

Link to this question
23Why is the first token slower than the rest in an LLM?

Before the first token, the model needs to process all prompts in the prefill step, adding queue and network time. The following tokens reuse the KV cache and only process the new generation.

Link to this question
24Explain Top-p (nucleus) sampling and Top-k sampling. How do they differ?

Top-k holds the k highest probability tokens; top-p holds the smallest set with a total probability of reaching p. Top-p adapts to the distribution; both remove the tail before sampling.

Link to this question
25Compare greedy decoding, beam search, top-k, top-p, and temperature sampling. When does each fail?

Greedy is susceptible to local selection and repetition; Beam search can favor general or short sentences. Top-k/top-p and temperature increase widely but may result in poor token matching; Choose by evaluation according to the task.

Link to this question
26What are logits, and how are they used in text generation?

Logits are unstandardized scores on vocabulary. After adjusting temperature, mask and sampling filter, softmax converts them into probability to choose the next token.

Link to this question
27What are stop tokens in LLMs, and how does an LLM know when to stop generating?

A stop token is a special ID the model can generate to indicate the end of a turn or sequence. The system also stops when the token limit is reached, a stop sequence is encountered, or the request is canceled.

Further reading

Stop Tokens in LLMs

Link to this question
28What is the difference between a stop token and a stop sequence?

Stop token is a special token in vocabulary. Stop sequence is an application-specified sequence that can consist of multiple tokens; The backend detects the matching sequence to stop generation.

Further reading

Stop Tokens in LLMs

Link to this question
29What are skip connections (residual connections) in Transformers?

Residual connection adds input x to output F(x): y = x + F(x). It creates gradient paths and holds information, helping to train multi-layer networks more stably.

Link to this question
30What is the difference between open-source and closed-source LLMs? When would you choose one over the other?

Weighted open model allows for self-hosting and customization; need to check the license because open-weight is not always open-source. Closed APIs are generally easy to operate; Choose based on quality, data rights, latency, and total cost.

Link to this question
31What is the difference between encoder-only, decoder-only, and encoder-decoder Transformer architectures?

Encoder-only uses two-dimensional context, suitable for representation/classification; decoder-only uses causal attention to generate. Encoder-decoder encodes the input and then generates it via cross-attention, suitable for string conversion tasks.

Link to this question
32What is KV cache, and how does it speed up inference?

KV cache stores the key/value of the processed token at each layer. When generating new tokens, reuse the cache instead of recalculating the entire prefix; Trade speed for memory that increases with length.

Link to this question
33Estimate the KV cache memory needed to serve a large model. How does it constrain batch size and context length?

KV memory is approximately 2 × layers × batch × tokens × KV_heads × head_dim × bytes_per_value. It grows linearly with batch size and context length; reserve VRAM for weights, activations, workspace and allocator overhead.

Further reading

KV Cache Compression

Link to this question
34KV Cache Compression

KV compression can use quantization, head sharing, selective token retention or cache compression architecture. The trade-off is precision, long recall, and decompression cost; Need to measure on actual long tasks.

Further reading

KV Cache Compression

Link to this question
35What is model distillation, and how is it used with LLMs?

Distillation trains students to learn the teacher's output, distribution, or processing traces. Reduce inference cost; student may lose capacity if its architecture or data are not sufficiently representative.

Link to this question
36What is Mixture of Experts (MoE), and how does it work in models like Mixtral?

MoE has many experts and the router chooses several experts for each token. The total parameters are large but only partially activated; still need expert memory and load balancing/communication handling.

Link to this question
37What is the difference between dense and sparse models?

Dense activates the majority of parameters for each token; sparse, like MoE, only activates a subset. Sparse saves compute per token but has additional routing, memory, and load distribution costs.

Link to this question
38How does DeepSeek-V4 work?

DeepSeek-V4 combines MoE with hybrid CSA/HCA attention to compress and access long KV histories efficiently, alongside a local sliding-window branch. mHC changes residual connections, aiming to preserve capability while reducing long-context cost.

Link to this question
39What is Flash Attention?

FlashAttention computes exact attention in tiles, minimizing data transfers between SRAM and HBM without materializing the full attention matrix. It reduces intermediate memory and IO; dense attention still has quadratic arithmetic complexity in sequence length.

Link to this question
40What is Cross-Entropy Loss?

Cross-entropy measures the level at which the model assigns probability to the correct label/token: for a label is -log p(correct token). Next-token training averages this loss across loss-weighted positions.

Link to this question
41What is Grouped-Query Attention (GQA), and how does it differ from Multi-Head Attention (MHA)?

GQA divides query heads into groups that share a key/value head. It reduces KV cache size compared to MHA; MQA is the case where there is only one KV head for every query head.

Link to this question
42How does Sliding Window Attention work?

Sliding-window attention only looks at a token area near the current location. Reduce compute/cache by window but may lose long-distance relationships; Multiple layers or global branches help spread information more widely.

Link to this question
43How do Attention Sinks work?

Attention sink is a position that receives a lot of attention even though the content is not important, usually at the beginning of the chain. Keeping a few sink tokens close to the window can help keep streaming stable; Sink should not be considered semantic evidence.

Link to this question
44How does Rotary Position Embedding (RoPE) work, and why is it preferred over learned positional embeddings?

RoPE rotates the Q/K component pairs according to position, making the dot product dependent on relative position. No need for a separate study position embedding table; Extrapolating long contexts still requires appropriate techniques and validation.

Link to this question
45Explain Layer Normalization

LayerNorm normalizes the characteristic dimensions of each token by mean and variance, then applies the learned scale/bias. It stabilizes activation magnitude, independent of batch size.

Link to this question
46Explain RMSNorm (Root Mean Square Layer Normalization)

RMSNorm divides the vector by the root mean square and then multiplies the learned scale. Does not subtract mean like LayerNorm, so it is simpler and often reduces some computational costs.

Link to this question
47Why do modern Transformers use Pre-LayerNorm (Pre-Norm) instead of Post-LayerNorm?

Pre-Norm normalizes before attention/FFN, keeping the residual curve favorable for the gradient in the deep network. Post-Norm normalization after addition; Stability also depends on initialization, optimizer and architecture.

Link to this question
48What are scaling laws (Chinchilla), and how do they guide model size vs training data decisions?

Scaling laws relate loss to parameters, data, and compute. Chinchilla shows that under a fixed training budget it is necessary to balance the model with the amount of tokens; The optimal ratio also changes if long-term service costs are considered.

Link to this question
49Your LLM keeps ignoring your instructions. How do you make it follow structured output formats?

Use a constrained schema if the backend supports it, the examples are valid, and the instructions do not conflict. Validate syntax and operations in the application; Limited retry and clear error return when not responding.

Link to this question
50Your LLM-powered tool hits the context window limit on long documents. How do you handle it?

Split documents, retrieve related parts or process them hierarchically and then synthesize. Leave output budget, keep source/ID through steps; Only switch to long context when the quality benefits justify the cost.

Link to this question
51Your LLM does not admit when it does not know the answer. How do you make it say "I don't know"?

Train/give examples for situations where evidence is lacking, adding retrieval and denial rules. Adjusting the threshold with eval has unanswerable questions; Do not rely on self-declared model confidence.

Link to this question
52Your LLM generates responses that are too verbose. How do you control response length?

State the limit on the number of ideas, length and desired output examples; The token limit is only the final barrier because it can cut the sentence in half. Measure the rate at which requirements are met while retaining sufficient information.

Link to this question
53Your LLM memorized proprietary training data and leaks it in responses. How do you prevent this?

Remove or de-identify sensitive data before training, limit access, and test data extraction. With a leaked model, isolate/rollback and then retrain or unlearn has been verified; The output filter is not secure enough.

Link to this question
54Your LLM coding assistant generates outdated code using deprecated libraries. How do you fix it?

Pin the library version, bring the current documentation/API into context, and run the test/lint in a live environment. Verify the function name using the tool; Don't just ask the model to remember the new version.

Link to this question
55Your tokenizer splits important domain terms into meaningless subword pieces. How do you fix it?

First measure the actual impact on token budget and quality. Can use specialized data, change tokenizer/model; Adding new tokens requires related embedding training, not just editing the vocabulary list.

Link to this question
56Your Transformer's KV cache grows too large during long sequence generation. How do you manage memory?

Limit context and batch, use GQA/MQA or quantized KV when supported; sliding window/eviction needs to evaluate information loss. PagedAttention reduces allocation fragmentation, but does not itself reduce the number of useful KV bytes.

Link to this question
57Your Transformer runs out of memory on long documents due to quadratic self-attention. How do you scale it?

Use FlashAttention to reduce intermediate memory, chunking/retrieval or sparse/sliding-window architecture for very long strings. Reduce batches and use checkpointing when training; Distinguish activation memory from KV cache.

Link to this question
58Your distilled student model fails on the complex reasoning that the teacher model handled. How do you close the gap?

Added difficult task data, verified solution steps and easy to difficult curriculum. Increase student capacity if necessary; Compare teacher/student errors and avoid distilling questions that teacher answers incorrectly.

Link to this question
59After RLHF alignment, your LLM became safer but lost capability on hard tasks. How do you manage the alignment tax?

Measure safety and capacity for each task group, adjust preference data and regularization/KL intensity. Mix capacity data and choose checkpoints on both criteria instead of optimizing a total safety score.

Link to this question
60Your RLHF-trained LLM is gaming the reward model instead of being genuinely helpful. How do you fix reward hacking?

Find high reward but low quality examples, edit the rubric/data and check with independent judges or humans. Limit the optimal reward level, add regularization and keep eval out of the reward model.

Link to this question
61Your chatbot loses context after 10 turns in a conversation. How do you maintain a long conversation context?

Keep turns close, summarize status, and retrieve relevant memories. Save important events with source and privacy; Do not connect infinitely every time because it wastes context and increases noise.

Further reading

AI Agent Memory

Link to this question
62Your chatbot fails when users switch topics mid-conversation. How do you handle topic switches?

Track topics/intent and separate status by task; Retrieve only relevant history. When changing an unclear topic, ask for clarification instead of dragging over all the assumptions of the previous task.

Link to this question
63Your QA system always generates an answer even when no answer exists in the context. How do you detect unanswerable questions?

Evaluate answerability from the evidence and allow abstain. Check question coverage, cite each conclusion, and use an eval set of sentences without answers in context.

Link to this question
64Your summarization system hallucinated facts not in the original article. How do you fix it?

Summarize according to the evidence, keep separate figures/names attached to the source paragraph and check each important statement. Detail type not supported by source; with ambiguous information, keeping the original's level of uncertainty.

Link to this question
65Your text generation repeats phrases in long outputs. How do you fix repetition?

Check prompt/history for repetition, stop condition and sampling. Can adjust repetition penalty or loop detection; evaluated to not penalize terms that force repetition in code or data.

Link to this question
66Transformers work on text, so can they also understand images?

Yes. Vision Transformer divides the image into patches and then processes it with the Transformer; VLM connects the vision encoder to the language model via projector or cross-attention. Need training data for image and language association.

Link to this question
67Small Language Models (SLMs)

SLM is a relatively small language model, suitable for low latency, limited devices, or narrow tasks. Choose eval, because fewer parameters does not by itself guarantee better quality and cost in any case.

Link to this question
68Large Reasoning Models (LRMs)

LRM is optimized for multi-step inference and often uses additional compute during inference. Can solve difficult tasks better but slower/more token-consuming; need to limit budget and verify results.

Link to this question
69Jev and System One Models

Jev is a System One model for decisions like: choosing answers, scoring rubrics or estimating probabilities, instead of generating free text. Suitable for routing/fast checking; It is still necessary to calibrate the threshold according to actual data.

Link to this question
70What are Autoregressive Models?

The autoregressive model decomposes the sequence probability into the probability of each element conditional on the prefix. Sequential generation by predicting the next element and appending it to the history.

Further reading

Autoregressive Models

Link to this question
71Explain the difference between autoregressive and masked language modeling.

Autoregressive learning predicts the next token with causal context, conveniently generating text. Masked language modeling recovers masked tokens from a two-dimensional context, often using representation learning such as BERT.

Link to this question
72Proximal Policy Optimization (PPO)

PPO is a policy-gradient algorithm that limits the level of policy changes by a clipped surrogate target. In RLHF, it optimizes reward and often adds KL with reference policy to avoid too strong deviation.

Link to this question
73Direct Preference Optimization (DPO)

The DPO learns directly from the liked/disliked response pair using the objective with the referenced policy. There is no need to train a separate reward model or RL rollout round like PPO in the standard DPO formula.

Link to this question
74Group Relative Policy Optimization (GRPO)

GRPO takes multiple responses to the same prompt, calculates relative superiority in the group and then updates the policy. It avoids separate criticism/value models; Quality depends on reward and sample group diversity.

Link to this question
75Recursive Language Models (RLMs)

RLM considers long prompts as data in the external environment, tells the model to write operations to read/split and call recursively on the parts. This is an inference strategy, not simply increasing the context window.

Link to this question
76Continual Learning in LLMs

Continuous learning updates the model through new batches of data/tasks while trying to maintain old capabilities. Use replay, regularization or adapter; Evaluate both new data and previous performance test sets.

Link to this question
77What is Recursive Self-Improvement (RSI)?

RSI is the idea that the system improves the process/model itself creating the possibility for further improvement. Need to measure independent benefits, resource limitations and change control; This process cannot be automatically accelerated indefinitely.

Link to this question
78How do Diffusion Language Models (DLMs) work?

Diffusion language model learns to recover strings from noisy states or masked tokens through multiple steps. Multiple locations can be updated at the same time; Speed/quality depends on denoise schedule and architecture, not automatically faster than autoregressive.

Link to this question
79How Does LLM Watermarking Work?

Watermark text that creates a keyed statistical bias in the token selection for later inspection by the detector. Paraphrase and short text reduce credibility; need to measure false positives, do not consider findings as absolute proof.

Link to this question
80How do RNNs and Transformers differ?

RNN processes states sequentially, is difficult to parallelize over time, and easily loses long-distance relationships. Transformer uses attention to link positions directly, parallelizing training better but attention/cache can consume memory.

Link to this question
View this section in the original repository ↗

Prompt Engineering

30 questions
01What is prompt engineering, and why is it critical for AI applications?

Prompt engineering designs instructions, context, examples, and output formats so that the model performs the task correctly. It directly affects quality, cost and testability, but does not replace backend control.

Link to this question
02Explain zero-shot, one-shot, and few-shot prompting with examples.

Zero-shot: stating classification requirements without examples; one-shot: add a sample; few-shot: add a few representative samples. Choose examples with label boundaries and hard cases, not just similar samples.

Link to this question
03What is chain-of-thought (CoT) prompting, and when should you use it?

CoT encourages multi-step solving, useful for math or structured reasoning. Not guaranteed correct; With a reasoning model, you should prioritize the goal and verify the answer, not by default requiring all internal thinking to be made public.

Link to this question
04Explain self-consistency prompting and how it improves reasoning.

Generate multiple independent solutions and then synthesize the answers, often by voting, to reduce the error of a line of reasoning. Increases costs and doesn't help much if the models have the same systematic error.

Link to this question
05What is tree-of-thought prompting?

Tree-of-thought extends multiple solutions, evaluates intermediate states, and chooses which branch to continue/backtrack from. Useful when structured searches are needed; Need budget and reliable status criteria.

Link to this question
06What is ReAct (Reasoning + Acting) prompting, and how does it work?

ReAct interleaves action selection with tool execution and observation reception. The application controls the loop, validates tool calls and stop conditions; The solution must be based on real tool results.

Further reading

ReAct Agent

Link to this question
07What is a system prompt, and how does it influence model behavior?

System prompt sets roles, rules, and constraints as high priority in the conversation. It affects behavior but is not a secret place or security boundary against all prompt injection.

Link to this question
08How do you structure prompts for consistent structured output (JSON, XML)?

Specify the schema, data types, required fields and how to represent missing data; Use constrained output if supported. Parse, validate schema and check business before use; Limit the number of edits/retries.

Link to this question
09What is prompt injection, and how do you defend against it?

Prompt injection is an untrusted instruction that attempts to override the system's target. Separate data from instructions, limit permissions/tools, validate parameters, and control actions outside the model.

Link to this question
10What is jailbreaking in LLMs, and what are common jailbreak techniques?

Jailbreaks attempt to circumvent the policy by role-switching, context camouflage, encryption, or multiple exploits. Defend with counter-testing, policy enforcement, and impact limiting, not just keyword blacklisting.

Link to this question
11How do you optimize prompts for cost and latency?

Remove redundant context, choose valid examples, limit output, and use cache prefixes when appropriate. Measure quality, TTFT and cost on successful tasks before shortening or changing models.

Link to this question
12What is the difference between prompt engineering and prompt tuning?

Prompt engineering changes the input text without updating the weights. Prompt tuning learns prompt vectors continuously using gradients, often freezing the background model; need data and training.

Link to this question
13What is a prompt template, and how do you design one for production use?

A prompt template is a template with input variables and a fixed output format. Versioning, validating variables, distinguishing instructions from untrusted data, and testing with representative examples before deployment.

Link to this question
14How do you handle multi-turn conversations with LLMs?

Keep message role and task status; Use close window, summary and retrieval for long history. Preserve key decisions, access, and token budgets.

Link to this question
15What is role prompting, and when is it effective?

Role prompting assigns perspective or style, such as code reviewer. It is useful to clarify criteria; Self-proclaimed experts do not make models with more knowledge or accuracy.

Link to this question
16What is prompt chaining, and how do you design a chain of prompts for complex tasks?

Divide the task into steps with clear inputs/outputs: extract, test, then synthesize. Validate each step, pass structured data, and avoid unnecessarily long strings as errors can accumulate.

Link to this question
17How do you evaluate and iterate on prompt quality?

Create a baseline and keep the eval set private, replace each element and compare according to the rubric. Pin the prompt/model version, analyze each error group and check cost, latency and quality.

Link to this question
18What are meta-prompts, and how can they be used to generate prompts?

Meta-prompt is a prompt that instructs the model to create or improve another prompt. Only see the results as candidates; evaluated on independent data to avoid over-optimization of some examples.

Link to this question
19What are the common failure modes in prompting, and how do you debug them?

Common errors: conflicting instructions, misleading examples, missing context, wrong format and injection. Recreate the actual input, check the last prompt and zoom out each section to find the cause.

Link to this question
20How do you handle edge cases and adversarial inputs in prompt design?

Prepare examples of missing data, strange characters, too long input, and conflicting instructions. Set denial/clarification behavior; Validate in the application and measure the hurdle rate on a separate test set.

Link to this question
21What is the "lost in the middle" problem in long-context prompting?

The model can use information in the middle of a long context less than information at the beginning/end. Noise reduction, retrieval/reranking and disposition of critical evidence; Test swap positions to measure the effect.

Link to this question
22What are output parsers, and why are they needed for production applications?

Output parser converts model text into application data types and detects structural errors. Parser must clearly report errors and validate schema; Do not silently guess or accept incorrect business data.

Link to this question
23How do you handle multi-language prompting effectively?

Specify the output language, use local examples, and test multilingual tokenizer/retrieval. Maintain proper names, units and necessary terminology; Evaluate each language separately.

Link to this question
24Your few-shot prompting gives inconsistent results across similar inputs. How do you stabilize it?

Fix label definitions, choose representative examples, and be consistent in order/format. Reduce randomness where appropriate, test sensitivity by example, and add cases close to label boundaries.

Link to this question
25Your LLM classification system is too sensitive to prompt wording changes. How do you reduce prompt sensitivity?

Use clear rubrics, fixed label schemas and paraphrase sets for stable measurements. If the error is still significant, consider a classification/fine-tuning model with appropriate data instead of continuing to patch the text.

Link to this question
26Your chatbot's system prompt containing proprietary business logic is being leaked by users. How do you prevent it?

Put secrets and logic that need to be protected into a decentralized backend; Consider that the system prompt may be exposed. Block access to sensitive data and test extraction; Asking for confidentiality with a prompt is not enough.

Link to this question
27Your LLM agent is vulnerable to prompt injection that reveals the system prompt. How do you defend it?

Do not place keys or secret data in the prompt. Limit tools, control output and egress, authenticate server permissions; Test injection directly and in documents that the agent reads.

Link to this question
28Your chain-of-thought prompting is not improving LLM accuracy on reasoning tasks. What do you fix?

Analyze whether the error is due to lack of knowledge, calculation or problem. Provide evidence/calculators, divide tasks appropriately and grade real answers; Adding an inference step doesn't help if the premises or intermediate result are false.

Link to this question
29Your AI system works in English but fails for other languages. How do you add multilingual support?

Choose a model that supports the target language, adding local examples and appropriate retrieval/embedding. Evaluate on local user data, both code-switching and cultural differences; Don't just translate the test into English.

Link to this question
30Your zero-shot cross-lingual transfer from English fails on other languages. How do you fix it?

Identify translation errors, tokenizers, local knowledge or embedding. Add few-shot native or fine-tune quality data; Compare the translation pipeline with the multilingual model on the same eval set.

Link to this question
View this section in the original repository ↗

Retrieval-Augmented Generation (RAG)

42 questions
01What is Retrieval-Augmented Generation (RAG), and why is it important?

RAG finds relevant documents and then puts the evidence into context for the model to answer. It helps update knowledge and extract sources without retraining; does not eliminate hallucination on its own.

Link to this question
02Explain the architecture of a basic RAG system.

Offline: parse documents, split chunks, create embedding and index with metadata. Online: handle query, retrieve, rerank, combine context and then generate answers with quotes.

Link to this question
03What are the key components of a RAG pipeline?

Components: ingestion/parser, chunker, embedding model, search index, retriever, reranker options, prompt/LLM and evaluation. Need to add versioning, ACL, logging and data update/delete mechanism.

Link to this question
04What are chunking strategies, and how do you choose the right chunk size?

Divided by size, structure or meaning; Balances context preservation with noise reduction. Choose chunk size/overlap based on recall and answer quality on real questions, not a fixed number.

Link to this question
05Compare fixed-size chunking, semantic chunking, and recursive chunking.

Fixed-size is simple but easy to cut; recursive prioritizes boundaries such as paragraphs/sentences before splitting. Semantic chunking gathers meaning, requires more processing, and requires better verification than the baseline.

Link to this question
06What is Contextual Retrieval, and how does it improve RAG?

Contextual Retrieval adds a contextual description of the document to each chunk before indexing. It helps separate paragraphs make enough sense for embedding/keyword search, in return increasing ingestion and token costs.

Link to this question
07What are embedding models, and how do they convert text to vectors?

Embedding model encodes text into vector via appropriate encoder and pooling/projector. Training to make related query-document pairs close together; Need to use the correct query/document format of the model.

Further reading

What are Embeddings?

Link to this question
08How do you choose an embedding model for your RAG system?

Evaluate language, data domain, length, recall/ranking, latency, and vector storage costs. Select on the system's query-document set; General benchmark scores are not enough to ensure domain-specific performance.

Link to this question
09Explain Agentic RAG.

Agentic RAG uses a control loop to select the source, transform the query, or retrieve multiple passes according to the results. Helpful with complex questions; Need stop condition and budget to avoid infinite search.

Further reading

Agentic RAG

Link to this question
10What is hybrid search, and why is it better than pure vector search?

Hybrid search combines lexical search like BM25 with dense retrieval. It often improves proper name/code accuracy and semantic relationships; mix with RRF or weights and measure again, it's always better not to default.

Link to this question
11What is re-ranking, and how does it improve RAG retrieval quality?

Reranking re-scores a set of candidates using a model that understands the query-document more deeply and then selects the top results. It increases context precision but adds latency; Initial recall still has to be good enough.

Link to this question
12What is ColBERT, and how does late interaction retrieval work?

ColBERT keeps embedding each token instead of a full segment vector. Late interaction matches token query with token document using MaxSim and then aggregates, balancing quality with pre-indexing capabilities.

Link to this question
13Compare reranker architectures: cross-encoder, ColBERT, and LLM-based rerankers.

Cross-encoder reads the query-document together, accurately, but must be run in pairs. ColBERT reuses embedding tokens to reduce costs; LLM reranker is flexible but slow/costs tokens and needs bias/order control.

Link to this question
14How do you handle multi-document and multi-hop questions in RAG?

Decompose the question into subqueries, retrieve evidence for each step, then connect events via ID/entity. Check all links and sources; Do not synthesize when an important step has no evidence.

Further reading

Agentic RAG and GraphRAG

Link to this question
15What is the "lost in the middle" problem in RAG systems?

Evidence located in the middle of a long context may be ignored by the model. Rerank, reduce noise chunks and arrange important sources properly; Test the location change to distinguish this error from missing retrieval.

Link to this question
16How do you evaluate a RAG system? Explain faithfulness, relevance, and context precision/recall.

Faithfulness: conclusion supported by context; relevance: answer the question correctly. Context precision measures the proportion/quality of useful segments in the result; recall measures the level of finding enough necessary evidence according to the eval set definition.

Further reading

LLM Evaluation

Link to this question
17Explain Self-RAG. How does the model decide when to retrieve?

Self-RAG trains the model to use reflection tokens to decide retrieval and self-assess the relevance/support of the paragraph/answer. This is a specific learning mechanism, it does not mean that every agent that calls retrieval is Self-RAG.

Further reading

Agentic RAG

Link to this question
18What is GraphRAG, and when would you use it over traditional RAG?

GraphRAG exploits entity/relationship or community summaries on graphs for retrieval and aggregation. Suitable for questions linking multiple entities/entire data sets; expensive to build and maintain graph.

Further reading

GraphRAG

Link to this question
19Vectorless RAG

Vectorless RAG retrieves by keyword, tree structure, metadata, graph or document navigation instead of vector index. Useful with structured documents; Recall and latency must still be measured, without eliminating the need for retrieval.

Further reading

Vectorless RAG

Link to this question
20How do you handle structured data (tables, SQL databases) in a RAG pipeline?

Keep schema, column headers, units and table links in ingestion; Use SQL/tool ​​for structured data. Validate queries, assign permissions, and include source/version instead of just embedding every cell as text.

Link to this question
21What are the common failure modes of RAG systems, and how do you debug them?

Errors can be in parse, chunk, embedding, retrieval, rerank or generation. Trace the entire pipeline, measure recall on the correct source and then check the final context; Fix the floor causing the error instead of just changing the prompt.

Link to this question
22How do you handle document updates and maintain freshness in a RAG system?

Track changes using CDC/webhooks or periodic crawls; upsert by ID and delete obsolete chunks. Versionize documents/indexes, handle tombstones, and only switch versions after consistent updates.

Link to this question
23How do you optimize RAG for latency in production?

Measure latency step by step, secure cache by permission/version, parallel search and reasonable rerank candidate reduction. Limit context/output; Don't sacrifice recall or ditch ACLs just to reduce time.

Link to this question
24What is the role of metadata filtering in RAG systems?

Metadata filters by tenant, permission, time, document type or version before putting data into context. Design index/filter for efficiency; Top-k post-filtering that is too narrow can cause loss of recall.

Link to this question
25Compare RAG vs fine-tuning. When would you use each?

RAG adds external knowledge at the time of inference, matching changed data and source needs. Fine-tuning changes behavior/task habits; The two methods can be combined and do not completely replace each other.

Link to this question
26Long context windows keep getting cheaper. When should you use retrieval (RAG) vs putting everything in the context window?

The overall context is suitable for a small volume, needs to be read at the same time and is within budget. RAG integrates large warehouses, updates/ACLs are complex or noisy; Compare quality and total cost on real workloads.

Link to this question
27What is query transformation in RAG (HyDE, query decomposition, step-back prompting)?

HyDE creates mock documents for retrieval; decomposition divides the question into parts; step-back creates general questions. Use the birth section to find the real source, do not consider hypothetical documents as evidence.

Link to this question
28How do you implement citation and source attribution in RAG?

Assign persistent IDs to chunks and page/fragment metadata, asking the model to extract the provided IDs. Check that sources exist and actually support each conclusion, then show location-specific links.

Link to this question
29How do you scale a RAG system to millions of documents?

Use incremental ingestion, ANN index, sharding by tenant/domain and versioned cache. Benchmark simultaneous recall, ACL filter and p95 latency; rerank small files instead of scanning the entire inventory with LLM.

Link to this question
30What is parent-child chunking, and how does it improve retrieval?

Index the small child chunk to find the exact one, then get the larger parent to preserve context. Save parent-child relationships, eliminate duplicate parents, and limit the amount of context returned.

Link to this question
31Your RAG system is hallucinating despite having the right context. How do you fix it?

Check if the correct paragraph really goes into the final context and is enough to answer the question. Reduce noise, request source/reject when missing, check each claim; Adding retrieval does not fix model misinterpretation.

Link to this question
32Your RAG chunk overlap causes redundant results. How do you reduce redundancy?

Reduce overlap when safe enough, combine neighboring areas and eliminate duplicates according to document/span. Use diversity selection like MMR to avoid filling the context with many almost identical passages.

Link to this question
33Your RAG retrieval is too slow with a large knowledge base. How do you speed it up?

Profile filter/index/network first; Use appropriate ANN, partition and index metadata. Adjust search parameters according to target recall, reduce candidate reranking, and cache popular queries to the right permissions/versions.

Link to this question
34Your RAG system returns duplicate results. How do you deduplicate?

Dedupe when ingesting by content hash and when retrieving by document ID/area; For close matches, use similarity or MMR. Keep provenance to avoid mistakenly deleting versions or sources with different meanings.

Link to this question
35Your RAG system needs per-user access control on internal documents. How do you implement it?

Authenticate the user and apply the ACL/tenant filter in the retrieval, before the context. Cache must have permission and version attached; Check permissions when opening documents, test cross-tenant access.

Link to this question
36Your RAG system fails on domain-specific jargon. How do you fix it?

Add glossary, query expansion and hybrid keyword+dense for specific terms/codes. If fine-tune embedding is needed with specialized pairs; Measure recall before/after, not just add explanation to the prompt.

Link to this question
37Your text-only RAG system now needs to handle images and tables. How do you extend it?

Parse table keeps structure; save image, caption/OCR and page location. Use appropriate embedding/cross-modal retrieval, then pass the correct modality evidence to the model that can read the image/table.

Link to this question
38Your RAG knowledge base gets updated frequently and needs versioning. How do you manage it?

Save document_version, chunk_id and index_version; Create a new version, verify it, then alias it atomically. Support rollback, delete expired versions and disable cache by version.

Link to this question
39Your RAG system fails on multi-hop questions that require combining multiple facts. How do you fix it?

Use query decomposition or graph traversal to collect each link. Record intermediate evidence, check entity links, and stop/clarify when there are insufficient facts.

Further reading

Agentic RAG and GraphRAG

Link to this question
40Your enterprise RAG system returns contradictory answers from different source documents. How do you resolve conflicts?

Prioritize authoritative sources, date validity, and versions; Keep provenance for every passage. If there is no clear resolution rule, present the disagreement and the source instead of choosing an answer yourself.

Link to this question
41Your RAG system returns outdated answers from an evolving knowledge base. How do you keep it current?

Fix ingestion/update index first, apply time validity filter and invalidate cache when source changes. Displays date/version and detects orphaned chunks from deleted or replaced documents.

Link to this question
42Your RAG system struggles with PDF documents containing tables and layouts. How do you fix PDF parsing?

Use parser to understand layout, OCR when needed and table extractor to hold rows/columns, captions, pages. Checking PDF samples is difficult; save bounding box to compare sources and avoid cross-table chunking without context.

Link to this question
View this section in the original repository ↗

AI Agents and Agentic Systems

54 questions
01What is an AI agent, and how does it differ from a simple LLM call?

The agent has a control loop: the model selects the step, the application calls the tool, receives observations, and then updates the state. A single LLM call only produces output; agents need stop conditions and permission/resource limits.

Link to this question
02AI Agent Memory

Memory stores state or information for reuse across steps/sessions. Separate short-term history, long-term memories, and experiences; Retrieve according to relevance, source, deadline and right of deletion.

Further reading

AI Agent Memory

Link to this question
03Harness Engineering in AI

Harness engineering designs the environment around the model: tools, context, loops, tests, checkpoints, and permissions. Good Harness makes action verifiable and failure recoverable.

Link to this question
04What matters more for an agentic coding tool like Claude Code: the model or the harness?

Model determines reasoning ability; The harness determines the information, tools, and feedback the model receives. The two elements interact; compare ablation on the same task instead of claiming one factor is always more important.

Link to this question
05Explain the ReAct (Reasoning + Acting) agent architecture.

ReAct iteratively selects an action, calls the tool, and reads the observation results to decide on the next step. Loop executed by application; limit steps, validate inputs, and only synthesize from real results.

Further reading

ReAct Agent

Link to this question
06What is the Plan-and-Execute agent pattern?

Planner divides goals into plans; The executor goes through each step, checking the results and re-planning as needed. Multi-step task integration; Avoid hard plans when actual data has changed.

Further reading

Plan-and-Execute Agent

Link to this question
07What is tool use (function calling) in LLMs, and how does it enable agents?

Model suggests tool name and parameters; Backend validates, authorizes and executes then returns results. Thanks to that, the agent can retrieve data or perform external actions, but the model does not have the right to execute it.

Link to this question
08What is the difference between structured output and function calling?

Structured output constrains the structure of the content returned to the application. Function calling represents a request to call a tool with a name/parameter; The backend still has to decide whether to execute or not.

Link to this question
09How do you design and define tools for an AI agent?

Each tool should have a narrow purpose, a clear name/description, a tight schema, and structured errors. Limit permissions, timeouts, and idempotency handling for write operations; Do not issue excess tools.

Link to this question
10How does an agent decide when to call a tool versus answering from its own knowledge?

Call the tool when you need current data, precise calculations, or status changes. Pay directly when there is enough information and no external verification is required; Use policy/router and eval to control decisions.

Link to this question
11What is the difference between single-agent and multi-agent systems?

Single-agent holds control in one loop; multi-agent separates roles/contexts and coordinates via messages or state. Multi-agent can be parallelized but increases tokens, latency, and coordination errors.

Further reading

Multi-Agent Systems

Link to this question
12When do multi-agent systems break down, and when is a single agent the better choice?

Multi-agent is vulnerable when roles overlap, states are inconsistent, or no one is responsible for the results. Choose single-agent/workflow when the problem is compact enough and breaking it down does not create measurable benefits.

Further reading

Multi-Agent Systems

Link to this question
13What is Model Context Protocol (MCP), and how does it standardize tool integration?

MCP uses a common protocol for host/client to discover and use server-provided capabilities such as tools/resources/prompts. It reduces individual system integration, does not replace authentication and authorization mechanisms.

Link to this question
14How does MCP differ from traditional function calling?

Function calling is how the model proposes a structured call. MCP standardizes connection, discovery and exchange with tool/resource servers; The application can map MCP tools to the model's function calls.

Link to this question
15What are AI SubAgents?

Subagent is an agent assigned a child task, usually with its own context and permissions. The main actor synthesizes and checks the results; Decoupling should only occur when the benefits of centralization/parallelism exceed the costs of coordination.

Further reading

AI SubAgents

Link to this question
16What are the different types of agent memory (short-term, long-term, episodic)?

Short-term memory holds the current task context; long-term holds information that can be reused between sessions. Episodic memory stores specific events/experiences; It is necessary to distinguish verified facts from model speculation.

Further reading

AI Agent Memory

Link to this question
17How do you handle agent failures and implement error recovery?

Classify errors that can be retried and errors that need to be stopped; Limited retry with backoff/jitter. Checkpoint the state, use idempotent operations and switch handlers when capacity is exceeded, do not silently loop indefinitely.

Link to this question
18What is an agent loop, and how does it decide when to stop?

The agent loop receives the state, chooses an action, executes it, and observes until it meets the completion criteria. Stop even if budget/time runs out, unrecoverable error or user cancels; Don't just believe the model's self-declaration.

Further reading

AI Agent Loop

Link to this question
19Context Engineering

Context engineering selects, organizes, and updates the information the model needs: instructions, states, examples, tool output, and memory. The goal is to have enough evidence in the token budget, not to squeeze in maximum data.

Further reading

Context Engineering

Link to this question
20How does context compaction work?

Compaction reduces history to states/milestones, keeping turns close and referenced to the original data. Check goals, decisions and sources are not lost; The summary can also be wrong.

Link to this question
21Loop Engineering

Loop engineering designs action-response cycles, stop conditions, retries, and budgets. Measure actual progress after each step to prevent a loop of generating more tokens without solving the task.

Further reading

Loop Engineering

Link to this question
22Graph Engineering

Graph engineering models workflows using nodes, edges, states, and transition conditions. It clarifies branch/parallel flow, checkpoint and recovery; Choose graph when control structure is really needed.

Further reading

Graph Engineering

Link to this question
23How AI Agents Communicate?

Agents exchange messages, APIs, queues or shared state with a schema. Need task ID, source, version and data ownership rules; Use timeout and anti-duplication instead of just sending free text.

Link to this question
24What are Agent Skills?

Agent skills encapsulate instructions for a task, possibly with resources and scripts. Agent loads when appropriate for consistent work; Skills do not automatically grant additional permissions and must be verified by trusted sources.

Further reading

What are Agent Skills?

Link to this question
25How do you evaluate and test AI agents?

Evaluate task results, tool/argument accuracy, number of steps, costs, and permission violations. Use a sandbox environment with verifiable state, tool error sets, and multiple evals for randomness.

Further reading

AI Agent Evaluation

Link to this question
26What are the security risks of agentic systems, and how do you mitigate them?

Risks include injection, circumvention, data leakage, malicious code and irreversible actions. Using minimal permissions, sandboxing, egress policies, checking parameters, and approving operations has major consequences.

Link to this question
27Your agent reads untrusted content (emails, web pages, documents) and can call tools. How do you prevent indirect prompt injection and data exfiltration?

Treat email/web/documents as untrusted data, do not override policies. The backend restricts tools and data sending destinations, checks ACL/PII, and requires prior approval of sensitive actions.

Link to this question
28What is the difference between reactive and proactive agents?

Reactive agent acts upon request or event; proactive agent takes initiative based on goals/schedules/signals. Proactive needs clear authorization scope, frequency limits, and cancellation capabilities.

Link to this question
29How do you manage token consumption and cost in long-running agent workflows?

Track tokens/costs step by step, limit context and output, summarize tool output and secure cache. Use small models for simple steps, stop when no progress is made; budget must be implemented outside the model.

Link to this question
30What is the human-in-the-loop pattern for agents, and when is it needed?

Human-in-the-loop takes the user/expert into the review, correction or decision step. Used for actions that are difficult to reverse, low reliability or high impact; Displays specific content to browse.

Link to this question
31How do you implement guardrails for AI agents to prevent harmful actions?

Combine allowlist, schema validation, ACL, sandbox, budget and policy gate tools before taking action. The prompt/output filter is an additional layer; Do not use model prompts instead of server control.

Link to this question
32What is agent reflection, and how does it improve agent performance?

Reflection allows the agent to review the results and suggest corrections before finishing. Useful when having independent criteria/tests; Self-criticism without evidence may only repeat or reinforce errors.

Further reading

Reflection Agent

Link to this question
33What is the difference between code-generating agents and tool-calling agents?

Code-generating agent creates programs for execution, flexibility but increases the risk surface. Tool-calling agents use predefined interfaces, which are easier to limit and test, but less flexible.

Link to this question
34How do you handle multi-modal inputs and outputs in agentic systems?

Pass each modality through the appropriate encoder/parser, keeping the timestamp/position and source link. Tool/model must support the correct data types; Save/transfer only the necessary parts and apply rights to images, sounds, and text.

Link to this question
35How do you implement state management in complex agent workflows?

Use states with clear schema, task/run ID, checkpoint and transition. Handles concurrent updates, versions and idempotency; saves the verified tool results separate from the model interpretation.

Link to this question
36How do you build a customer support agent with escalation logic?

Classify the intent, retrieve knowledge, call the authorized business tool and check whether it can be resolved. Escalate when out of range, at risk or loop error; forward all necessary evidence/history to the employee.

Link to this question
37What is agent orchestration, and how do you implement it?

Orchestration coordinates the ordering, branching, parallelism, and communication between model/tool/agent. Use workflow/state machine, queue and checkpoint; assign dynamic selection to the model only when needed.

Further reading

AI Orchestration

Link to this question
38What is Sakana Fugu, and how does it orchestrate a team of AI models?

Sakana Fugu is an orchestration system trained to coordinate multiple models/tools for the task. It selects and coordinates steps instead of using a fixed model for everything, optimizing quality within cost/latency constraints.

Link to this question
39How do you build a code execution agent safely using sandboxed environments?

Run code in an isolated environment with CPU/RAM/time, filesystem, and network limitations. Do not mount secrets or production credentials; scan/check the results and request approval before pushing the impact out of the sandbox.

Link to this question
40Your AI agent is stuck in an infinite loop. How do you detect and break the cycle?

Keep track of duplicate tool/argument chains and steps that don't change useful state. Apply step/time/cost limits, limited retries and return incomplete results with reasons when stopping.

Link to this question
41Your AI agent gets conflicting answers from different tools. How does it reconcile them?

Compare the authority, time, reliability and conditions of each source. Can call standard source for verification; If it cannot be resolved, state the conflict or escalation and do not vote blindly.

Link to this question
42Your AI agent burns too many tokens per task. How do you reduce token consumption?

Eliminate redundant history and tool output, limit fan-out, cache, and use separate context for subtasks. Measure tokens step by step to optimize the most expensive space; Keep the information needed to avoid calling the tool again.

Link to this question
43Your AI agent keeps exceeding its budget per task. How do you enforce budget limits?

The backend tracks the actual budget, estimates costs before each step, and rejects when it's not enough. Apply the number of steps, time and output amount; Save status to continue when additional budget is granted.

Further reading

AI Agent Loop

Link to this question
44Your AI agent hallucinates tool capabilities and passes wrong inputs. How do you fix it?

Only provide registered tools, clear descriptions/schema, and validate both styles and operations. When wrong, return structured errors with correction instructions; Do not execute the tool/made-up model function name yourself.

Link to this question
45Your AI agent deleted a production database. How do you prevent irreversible actions?

Deprive the normal agent of destructive power, separate the environment, and use assertions for irreversible actions. Add backup/restore, policy gate and log; dry-run is not a substitute for genuine permission checks.

Link to this question
46Your AI agent has many tools, but keeps picking the wrong one. How do you improve tool selection?

Reduce the number of tools according to intent, change the name/description to make it easier to distinguish, and add examples close to the selection boundary. Measuring confusion matrix tool selection; separate tools too widely instead of adding many conflicting instructions.

Link to this question
47Your AI agent takes too long to complete a task. How do you speed it up?

Profile number of steps, latency tool/model and waiting time. Parallelize independent steps, cache, and use lightweight models when sufficient; Do not run dependent actions in parallel or cause duplicate effects.

Link to this question
48Your long-running agent drifts after hours and confidently works on the wrong thing. How do you diagnose and fix it?

Compare the trace with the original goal/completion criteria, find context points that are skewed or lost due to compaction. Keep task state outside the model, periodically checkpoint targets, and redirect with evidence.

Link to this question
49Your LLM selects the right tool but extracts the wrong parameters. How do you fix parameter extraction?

Schemaize the unit/format, get the ID from the real source, and check for existence/permissions. Using the example of distinguishing parameters is easy to confuse; Ask for clarification when information is missing instead of guessing the value.

Link to this question
50How do Computer-Use Agents work?

The computer-use agent observes the screen or UI tree, selects click/type/scroll, and receives the new state. Need to check after each action, adapting layout and gate changes specifically for sensitive operations.

Link to this question
51How do Browser Agents work?

The browser agent observes the DOM/accessibility tree or page image and then navigates, populates, and checks the results. Must handle page load, stale elements, and unreliable web content; Prioritize APIs when the task is appropriate.

Link to this question
52How does LangChain work?

LangChain provides abstractions/integrations for model, prompt, tool, retrieval and agent. It helps to connect components; Quality and reliability still require application workflow, validation and eval.

Link to this question
53How does LangGraph work?

LangGraph represents stateful workflows using graphs, supporting loops, checkpoints, and humans-in-the-loop. Node updates state, edge decides next step; Proper orchestration needs control and recovery.

Link to this question
54What is OKF (Open Knowledge Format)?

OKF represents knowledge using Markdown files with YAML frontmatter and links in bundles. The goal is to exchange knowledge that is easy to read for both humans and agents, independent of the model/framework; must comply with the consumer's spec version.

Link to this question
View this section in the original repository ↗

Fine-Tuning and Model Adaptation

32 questions
01What is fine-tuning, and when should you fine-tune an LLM?

Fine-tuning continues to train the weights on the target data. Used to improve behavior/format/task stability when prompt and retrieval are not enough, and have reliable data and eval.

Link to this question
02Explain the difference between full fine-tuning and parameter-efficient fine-tuning (PEFT).

Full fine-tuning updates all parameters, flexible but consumes memory/compute. PEFT only learns a fraction of what adapter/LoRA does, is cheaper and easier to manage but may limit adaptation.

Link to this question
03What is LoRA (Low-Rank Adaptation), and how does it work?

LoRA freezes W and learns low-rank updates ΔW = BA. The number of parameters decreases when the rank is small; Adapters can be served separately or included in the weighting as the architecture/number model allows.

Link to this question
04What is QLoRA, and how does it enable fine-tuning on consumer hardware?

QLoRA holds the quantized base model, typically 4-bit, and then learns the LoRA adapter with calculations at appropriate precision. Reduce weight memory; activation, gradient and optimizer still take up significant VRAM.

Link to this question
05How does fine-tuning work?

Prepare data and loss mask, forward calculates loss, backprop calculates gradient and then the optimizer updates the opened parameters. Monitor validation, save checkpoints, and test for performance degradation before deployment.

Link to this question
06Explain Prefix Tuning and Prompt Tuning. How are they different from LoRA?

Prompt tuning learns the prompt vector at input; prefix tuning learns prefix states, often affecting multiple layers of attention. LoRA learns low-rank updates for weight matrices; All three usually keep the base model fixed.

Link to this question
07What is adapter-based fine-tuning?

Adapter-based tuning inserts small modules with learned parameters into the network, freezing most of the base model. Each task can use its own adapter; Adding modules can increase latency if they cannot be merged.

Link to this question
08Explain the difference between pre-training, supervised fine-tuning (SFT), and preference optimization (RLHF/DPO).

Pre-training learns from extensive data; SFT learns the desired response by example; preference optimization adjusts according to choice/reward. They address different goals and are often combined in stages.

Further reading

Decoding InstructGPT

Link to this question
09What is RLHF (Reinforcement Learning from Human Feedback), and how is it used to align LLMs?

RLHF collects human preferences, often learns the reward model and then optimizes the policy using RL with regularization. The goal is useful/appropriate behavior; Biased preferences or wrong rewards can lead to reward hacking.

Link to this question
10What is Deep RL from Human Preferences, the paper that started RLHF?

The Deep RL from Human Preferences work learns reward from comparing segments of human-rated behavior. Agents use learned rewards to optimize policies, reducing the need to handwrite the full reward function.

Link to this question
11Why did DPO displace PPO-based RLHF at many labs? When is online RL still better?

DPO simplifies the pipeline because it learns from offline preferences, without needing a separate critique/reward model in the standard formula. Online RL is useful when it comes to discovering new behavior and having a reliable reward/verifier; DPO does not replace every situation.

Link to this question
12What is instruction tuning, and why is it important for chat models?

Instruction tuning is SFT on diverse instruction-response pairs so that the model knows what to do as requested. It improves interactivity but does not by itself guarantee factuality, safety or usability of the tool.

Further reading

Decoding InstructGPT

Link to this question
13How do you prepare a dataset for fine-tuning an LLM?

Collect data properly, have usage rights, consistently label and eliminate errors/duplicates/PII. Split train/validation/test to avoid source leaks, standardize chat templates and check length/label distribution.

Link to this question
14What is catastrophic forgetting, and how do you prevent it during fine-tuning?

Catastrophic forgetting is the loss of old abilities when learning new tasks. Reduce learning rate, use PEFT, mix old data/replay or regularization; Measure general capacity eval in parallel with new tasks.

Link to this question
15When should you choose fine-tuning over RAG over prompt engineering?

Start prompting when just clarifying the request; Use RAG when external/updated knowledge is lacking; fine-tune when learning stable iterative behavior is needed. Decide by observed error and eval, not by technological complexity.

Link to this question
16How do you evaluate a fine-tuned model's performance?

Compare with the base model on confidential testing, production data and difficult situation groups. Measure task goals, hallucination, safety, latency/cost, and overall capacity to detect regression.

Further reading

LLM Evaluation

Link to this question
17What is synthetic data generation, and how do you use it for fine-tuning?

Synthetic data is data created by model or simulation, used to expand rare examples/cases. Filter and verify labels/answers, control diversity and keep tests independent to avoid repeating teacher errors.

Link to this question
18What are the key hyperparameters for fine-tuning (learning rate, epochs, batch size, LoRA rank)?

Learning rate determines the update size; epochs is the number of passes through the data; batch gradient/memory noise effects; LoRA rank is the adapter capacity. Choose by validation and budget, there is no universal optimal configuration.

Link to this question
19Do the GPU memory math for full fine-tuning a 7B model in bf16 with Adam. Now with LoRA and QLoRA.

For 7B parameters, bf16 weights and gradients plus two fp32 Adam moments need about 84 GB; fp32 master weights raise this to about 112 GB, excluding activations/workspace. LoRA retains roughly 14 GB of base weights; QLoRA reduces the theoretical base to 3.5 GB, plus metadata and training memory.

Link to this question
20How do you fine-tune a model for a specific domain (legal, medical, finance)?

Use cleaned, authorized and expert-verified specialized data; Choose SFT or continuous pretraining depending on the behavior or domain language. Assess factuality and risk according to real cases, keep retrieval for information that needs updating.

Link to this question
21What is continual pre-training, and when would you use it?

Continuous pre-training continues the language objective on the new corpus to learn domain distribution/terminology. Suitable when there are many unlabeled documents; then usually requires SFT and a forgetting test.

Link to this question
22How do you merge multiple LoRA adapters?

LoRA updates can be added together with weights or using a merge technique with collision handling. Needs the same base/shape and appropriate scale; validate each task because merge does not preserve the quality of each adapter.

Link to this question
23What is the difference between SFT (Supervised Fine-Tuning) and alignment training?

SFT learns from the target response provided by the data; Alignment training directs behavior according to preferences, rewards, or principles. SFT can be partly aligned; alignment is not specific to RLHF.

Further reading

Decoding InstructGPT

Link to this question
24What is RLAIF (RL from AI Feedback), and how does it differ from RLHF?

RLAIF uses AI-generated feedback to learn preferences/rewards instead of human ratings. Expansion is cheaper but inherits judge bias, so it needs to be calibrated with human data and independent testing.

Link to this question
25What is Constitutional AI, and how does it differ from RLHF?

Constitutional AI uses a set of principles for the model to self-criticize/correct and create preferences for training. SFT/RLAIF combination possible; reduces the need for human labels but the quality depends on the set of rules and judges.

Link to this question
26What is RLVR (Reinforcement Learning with Verifiable Rewards), and when does it beat a learned reward model?

RLVR uses verifiable rewards like unit tests or math answers instead of reward model learning. Suitable for the task with a good verifier; Verifiers lack exploitable coverage and do not measure all aspects of quality.

Link to this question
27What is knowledge distillation for fine-tuning, and what are the legal considerations?

Students learn from output/logits or teacher's examples. Check model license, API terms, data and output permissions; Teacher access does not default to distill permission to distribute.

Link to this question
28Your fine-tuned LLM produces factually wrong outputs due to training data quality issues. How do you fix it?

Trace errors back to the sample/source, eliminate or correct erroneous data, and add counterfactuals. Retrain from clean checkpoints, keep assessments private, and increase quality control before ingestion.

Link to this question
29You must choose between LoRA and full fine-tuning for a domain-specific assistant. How do you decide?

Run baseline LoRA on the same data/eval first; Choose full tuning if the adapter fails and compensates for the compute benefit/forgetting risk. Compare quality, stability and service costs, not just training costs.

Link to this question
30Your fine-tuned model memorized training data verbatim instead of learning patterns. How do you fix overfitting?

Eliminate duplication and leakage, increase data diversity, reduce epochs/LR and use early stopping/regularization. Check for exact-match leakage on sensitive data, not just for low training loss.

Link to this question
31Your fine-tuned LLM forgot its general capabilities after domain-specific fine-tuning. How do you fix catastrophic forgetting?

Rollback checkpoint before degradation, reduce update level and mix replays of general data. PEFT or specialized adapters can reduce base interference; Always use the old capacity eval set to select checkpoint.

Link to this question
32Your RLHF preference data has low annotator agreement. How do you ensure data quality?

Clarifying rubrics, training labelers, and analyzing disagreement groups. Allows for uncertain labels/expert switching, eliminates error samples, and preserves multiple perspectives when preferences truly differ instead of forcing every sample into false consensus.

Link to this question
View this section in the original repository ↗

Vector Databases and Embeddings

26 questions
01What are embeddings in the context of AI engineering?

Embedding turns data into learned vectors for search, clustering, recommendation, or classification. It represents the relationship according to the training objective, not a full encoding of all meanings.

Link to this question
02How do embedding models convert text to vectors?

Tokenizer converts text into tokens; The encoder creates hidden states and then pools/projects the sentence/paragraph vector. Query and document must use the same embedding space and the correct model input instructions.

Further reading

What are Embeddings?

Link to this question
03What is Contrastive Learning, and how is it used to train embedding models?

Contrastive learning pulls related pairs close together, pushes unrelated pairs apart with loss like InfoNCE. Hard negatives help distinguish cases of close meaning but wrong answers; Wrong labels can reduce quality.

Link to this question
04What is the difference between sparse and dense embeddings?

Sparse vectors have many zero elements, are often associated with words/features, and are strong at exact matching. Dense vector shorter,semantic learning; Hybrid combines to take advantage of two strengths.

Link to this question
05Explain cosine similarity, dot product, and Euclidean distance for vector search.

Cosine measures angle: dot(x,y)/(||x||||y||); dot product also depends on the magnitude; Euclidean measures geometric distances. With the L2 normalization vector, the three rankings have appropriate equivalence relations; Always use the metric model trained for.

Link to this question
06What is a vector database, and how does it differ from a traditional database?

Optimized vector database for storing/querying closest vectors, ANN and metadata filtering. Traditional databases are strong in transactions/relations; Many systems today support both, so choose based on workload instead of product label.

Link to this question
07How does Approximate Nearest Neighbor (ANN) search work?

ANN finds close neighbors with approximate accuracy using graph, partition or quantization instead of full scan. Exchange partial recall for better latency/memory; need to compare with ground truth exact search.

Link to this question
08Compare HNSW, IVF, and flat indexes. How do you pick one, and what does recall@k cost in latency?

Flat searches accurately but scans a lot; HNSW is fast and often consumes RAM; IVF narrows to clusters. Increasing efSearch/nprobe often increases both recall and latency; Choose by actual size, update and filter.

Link to this question
09How does an Embedding Cache work?

Embedding cache stores vectors by keys including standardized content, model/version and configuration. Cache hit avoids re-encoding; Need TTL/eviction, authorization and invalidate when model or preprocessor rules change.

Link to this question
10How do you choose the right embedding model for your use case?

Evaluate on query-document pair of domain, language and actual length. Balance recall/nDCG, speed, vector size, license and servicing costs; Don't choose just because the vector is longer.

Link to this question
11What is embedding dimensionality, and how does it affect performance and cost?

Dimensionality is the number of vector components; Increasing dimension usually increases capacity and distance/index cost. Height does not guarantee betterment; dimensionality reduction only if the model supports or has evaluated the transformation.

Link to this question
12How do you handle embedding drift when the embedding model is updated?

Do not mix vectors from two models into the same space even if they have the same number of dimensions. Create new index, re-embed document, run shadow/dual query, pass alias after eval and keep rollback capability.

Link to this question
13What are multi-modal embeddings, and how are they generated?

Multimodal embedding places data types into compatible spaces using associative training, such as image-caption pairs. Query text can find images; Not all image/text encoders are compatible with each other.

Further reading

Multimodal AI

Link to this question
14How do you index and query multi-tenant data in a vector database?

Attach tenant/ACL to metadata and require filtering on the server; Isolate index/collection when needed. Cache and query key must contain permission scope; benchmark recall with real filters.

Link to this question
15What is quantization of embeddings, and how does it reduce storage costs?

Quantization of vector representation in fewer bits or burst codes like PQ to reduce RAM/disk. It causes distance errors; You can use the original vector to rerank the top candidates and measure the recall reduction.

Link to this question
16How do you benchmark and evaluate embedding model quality?

Use a query set with relevance labels, calculate recall@k, MRR or nDCG along with latency/cost. Compared to baseline lexical and exact vector search; reports by language, query group, and document type.

Link to this question
17What is the role of metadata in vector databases?

Metadata stores source, ID, tenant, ACL, time, version and document type. It supports filtering, updating/deleting, quoting, and auditing; must be synchronized with the vector instead of being stored externally without control.

Link to this question
18How do you handle large-scale vector search with billions of vectors?

Partition/shard, ANN and compression help reduce search/memory scope. Use hot-cold floors, small reranks and fan-out/network evaluation; Make sure the tenant filter does not perform a full system scan.

Link to this question
19What is hybrid search (combining keyword search with vector search)?

Hybrid search runs lexical and vector retrieval and then merges using RRF or calibrated weights. Useful for both proper names/product codes and semantic expressions; need to dedupe and check the final ranking.

Link to this question
20How do you fine-tune an embedding model for a specific domain?

Fine-tune with related query-document pairs and quality negatives, especially hard negatives in the right domain. Separate testing to avoid leakage and re-embed the warehouse when changing models; compared to pre-implementation baseline.

Link to this question
21Your vector database for RAG is consuming too much memory. How do you reduce it?

Dedupe, reduce unnecessary vectors, use quantization/PQ or verified dimension reduction. Fine-tune index configuration and move cold data to disk; Measure recall and p95 latency again.

Link to this question
22Your vector database cannot scale to millions of embeddings. How do you fix the bottleneck?

Profile RAM, index build, filtering, IO and sharding first. Use appropriate ANN/partition, batch ingestion and load dispersion; Adding machines does not solve the wrong metric or the query requires scanning the entire warehouse.

Link to this question
23Your new embedding model has different dimensions from the existing vectors in production. How do you handle the mismatch?

Create a new collection/index with the new dimensional schema, fully re-embed and then change the alias after testing. Do not arbitrarily pad/cut vectors to force joints; keep the encoder and index pair in the same version.

Link to this question
24Your vector search returns irrelevant results despite high similarity scores. How do you fix it?

High Similarity is representational similarity, not correct probability. Check metrics, normalization, model/query format, chunk quality; Add hybrid search, reranking and threshold correction on real labels.

Link to this question
25You deployed a new embedding model, and search quality crashed overnight. How do you handle embedding drift?

Rollback the encoder/index to the compatible pair, determining if there is version mixing or incorrect preprocessing. Rebuild new index, shadow evaluation and gradual migration; Track relevance by query group.

Link to this question
26Your semantic search fails for short queries. How do you improve it?

Use hybrid lexical search, query expansion with glossary/context, and clarify intent when needed. Train/eval with really short queries; Avoid over-extension that changes the user's mind.

Link to this question
View this section in the original repository ↗

AI System Design

49 questions
01Design a Real-Time Voice AI Agent

Main stream: audio streaming → VAD/turn detection → ASR → LLM/tool → TTS streaming. Measure latency each hop, support interrupt/cancel audio, keep conversation state and limit tool permissions.

Link to this question
02Design ChatGPT: Training to Serving (End to End)

General flow: data acquisition/cleaning → pre-training → SFT/alignment → eval → serving with batching/KV cache → monitoring. This is a reference design; ChatGPT's internal infrastructure and data are not fully disclosed.

Link to this question
03Design a RAG System (Chat with Your Documents)

Ingest the document with ACL/version, parse-chunk-embed then index. Query goes through retrieval/rerank, LLM summarizes with citation; Measure recall and faithfulness, support deleting documents/cache when source changes.

Link to this question
04Design an enterprise RAG assistant over 10M documents with per-user permissions.

Use incremental ingestion, sharding/ANN and server-side ACLs by user/group. Rerank allowed candidates, cached by permission/index version; Measure tail latency and test for data leaks between users before expanding.

Link to this question
05Design Memory for a Personal AI Assistant

Separate memory for events, preferences, and task states, each record has source/time/permissions. Retrieve by relevance, check for conflicts and let users view/edit/delete; Don't write down all speculations as facts.

Link to this question
06Design a Deep Research Agent

Planner divides the question, searches/retrieval collects evidence, reads/analyzes and then synthesizes with sources. Track claim-source, avoid loops and source dependencies; limit time/token and state the unverified part.

Link to this question
07Design a Multi-Agent Customer Support System

The router assigns the case to a knowledge/business agent with narrow permissions, sharing state with a schema. Check results before responding; Transfer employees when uncertain or have a major impact, save traces across agents.

Further reading

Multi-Agent Systems

Link to this question
08Design an On-Device AI Assistant

Use a small/quantized model, local retrieval, and handle sensitive data on the device. Memory/battery management, streaming and offline; fallback cloud only when user allows and data permissions meet.

Link to this question
09Design a Multimodal Search System (Text, Image, Video)

Index images, text and video keyframes with compatible embedding, including metadata/timestamp. Cross-modal query, merge/rerank results; Measure relevance according to modality and avoid losing important scenes due to sparse sampling.

Link to this question
10Design an LLM Inference Platform (vLLM-as-a-Service)

Authentication API layer/quotas, scheduler/queue, and GPU worker running batching/KV cache. Model registry, autoscaling and admission control by token/VRAM; Track TTFT, TPOT, throughput and costs per tenant.

Link to this question
11Design an LLM Evaluation Platform

Save dataset/rubric version, run candidate according to fixed configuration and score with code/judge/person. Report slice, uncertainty, cost; Protect tests from leakage and use gate/rollback when quality drops.

Further reading

LLM Evaluation

Link to this question
12Design a Text-to-Image Generation Service (Midjourney-like)

API receives prompt, checks content and then queues GPU job; Generate an image, check the output, and save it to object storage. Limit resolution/steps, quota and idempotent retry; save seed/model to reproduce in backend capabilities.

Link to this question
13Design a Music Generation Service (Suno-like)

Separate prompt receiving, music/audio performance generation, decoding and post-processing into asynchronous jobs. Manage GPU, duration and data/voice permissions; Measures quality, structural consistency, and similarity to copyrighted content.

Link to this question
14Design a Video Generation Service (Sora-like)

Queue job generates video according to duration/resolution, uses spatiotemporal model and saves the result to object storage. Check security/permissions, frame consistency, costs and job cancellations; Does not promise synchronization time for long jobs.

Link to this question
15Design an AI Coding Agent.

The agent reads the repo and requests, makes minimal changes in the isolated workspace, runs tests and then submits the diff. Limit shell/network/secrets; checkpoint, impact testing, and pre-approval for deployment or irreversible changes.

Link to this question
16Design a code generation and review system.

Generate patch in branch/sandbox, run compiler/test/static analysis, then review with relevant context. Reviewers must verify with code/test, not just agree with the generated model; The reviewer decides to merge.

Link to this question
17Design a content moderation system using AI.

Pipeline combines rules, multilingual/modal classifiers and reviewers for difficult cases. Set harm thresholds, log decisions, allow complaints, and monitor false positives by market.

Link to this question
18Design a real-time AI recommendation system.

Collect consent events, update feature and candidate retrieval, ranking and then apply business rules. Cache/backup hint for cold start; Measure long-term goals, diversity, latency and bias instead of just CTR.

Link to this question
19Design an AI-powered email assistant.

Decentralize mailboxes, retrieve relevant emails, summarize/categorize and draft with sources. Treat email content as unreliable; User browses recipient/content before sending or deleting.

Link to this question
20Design a medical diagnosis assistant using AI.

Designed as expert support, using proven medical data/knowledge and clinical validation. Protect records, raise uncertainties and refer to professionals; Do not self-diagnose/decide on unsupervised treatment.

Link to this question
21Design a fraud detection system powered by LLMs.

Use rules and transaction/graph models for key findings; LLM supports interpretation or analysis of records. Keep latency tight, control false positives and have reviewers/appeals before having a big impact on customers.

Link to this question
22Design an AI-powered data extraction pipeline from unstructured documents.

Receive document → check format/OCR/layout → extract by schema → validate by rule/source. Save provenance to page/region, pass uncertainty field to reviewer and process job idempotent.

Link to this question
23Design a Text-to-SQL system over a data warehouse with thousands of tables.

Retrieve related schema and semantic layer, generate SQL with constraints and then parse/check permissions. Only run read-only with timeout/row limit; clarify ambiguous terminology and compare results with the question.

Link to this question
24Design a personalized learning assistant.

Build competency profiles with consent, retrieve content at the right level, and create exercises with verifiable answers. Tracks progress, allowing teachers/learners to correct goals; Don't infer ability from just one chat.

Link to this question
25Design an AI system for automated code migration.

Inventory old/new API, classify patterns and create patches in small modules. Run regression/typecheck, canary and rollback; Use rules/codemod for the specified change, LLM for the part that needs interpretation.

Link to this question
26Design an AI-powered legal document review system.

Parse contracts to keep terms/versions, retrieve laws/policies in the right jurisdiction, and extract risks from sources. The lawyer approves the conclusion; keep documents confidential and avoid considering the output model as final legal advice.

Link to this question
27Design a conversational AI system with memory across sessions.

Save history with permissions, state summary and long-term memory with source/time. Each session retrieves the relevant part; allows deletion/editing and conflict handling instead of concatenating the entire history indefinitely.

Link to this question
28How do you design for latency vs quality trade-offs in AI systems?

Determine SLOs and quality thresholds, measure each component, then use routing/small model/cache when sufficient. Enable fast/deep mode if user needs; evaluated on cost/task success and p95 latency.

Link to this question
29How do you implement caching strategies for LLM applications?

Use exact cache or semantic cache with keys including tenant/permission, model, prompt and data version. TTL/invalidation according to newness; Avoid caching impactful results or sensitive data outside the allowed range.

Link to this question
30How do you design rate limiting and cost management for AI APIs?

Apply request/token quotas, concurrency limits and cost budget by tenant. Estimate output, queue/backpressure and track actual costs; Return errors/retry-after explicitly instead of overloading the GPU.

Link to this question
31How do you handle failover and fallback strategies for AI systems?

Timeout/circuit breaker, limited retry and backup provider/model are eval compatible. With write operations must be idempotent; report degradation and return partial results reliably instead of making it up when the source runs out.

Link to this question
32How do you design an AI system for high availability and fault tolerance?

Deploy appropriate multi-region replicas, health checks, persistent queues, and rehearsed backups and failovers. Avoid single points of failure in auth, index and model gateway; Measure RTO/RPO and check data permissions when roaming.

Link to this question
33How do you design an AI system that gracefully degrades when the model is unavailable?

Fallback to search, template, or manual flow for minimal functionality. Holds data and status, explains current limits; Don't replace the model with feedback that seems correct but hasn't been verified.

Link to this question
34What are the key considerations for multi-region deployment of AI systems?

Balance latency, data residency, replication lag, cost and GPU capacity for each region. Choose consistency for state/ACL, routing with failover and cache isolation; Trouble testing the entire area.

Link to this question
35Design an AI-powered search engine for an e-commerce platform.

Combines lexical/vector retrieval, inventory/permission filtering, and reranking by relevance. Synchronize catalogs/prices, support short queries/product codes; Measure conversion, zero-result rate and latency with relevance.

Link to this question
36Design an AI gateway/proxy for managing LLM access across an organization.

Gateway centralizes auth, routing, quotas, secret management, logging and policy. Standardize the interface but keep capacity information for each model; Controlled retry/fallback and without exposing payload between tenants.

Link to this question
37How do you design a RAG system that handles conflicting information across sources?

Save source, version and validity period, apply authority order when retrieval/rerank. The model must state the conflict with a citation; Do not mix provisions of different timing or scope into one conclusion.

Link to this question
38How do you approach capacity planning for an AI system?

Estimate arrival rate, input/output token, concurrency and context length. Load test real workload, calculate KV/VRAM and headroom; Use queue/admission control, don't extrapolate from a short request.

Link to this question
39Design a multi-tenant AI chatbot platform where each business gets a custom chatbot.

Separate configuration, data, and keys by tenant; Requires ACL in retrieval/cache. Use a worker pool with quotas, template version and eval for each configuration; Support deleting/exporting tenant data.

Link to this question
40Design an AI meeting summarizer system for thousands of meetings daily.

Audio upload/stream → ASR/diarization → segment → summary/action with timestamp → save/distribute by permission. Queue handles large-scale processing, holds consent, and checks who is responsible/action item.

Link to this question
41Design an AI notification system that prioritizes instead of broadcasting.

Score urgency/relevance from events and preferences with consent; bundling, scheduling, and frequency capping. Allows users to edit priorities, use rules for mandatory alerts, and measure omissions and notification fatigue.

Link to this question
42Design an AI-powered anomaly detection system for cloud infrastructure.

Collect metrics/logs/traces, detect anomalies using baseline/time-series and then group events. LLM supports explanation from evidence; Warning, you need a clear threshold/triage and do not edit the production yourself without permission.

Link to this question
43Design an AI-powered document processing pipeline for financial institutions.

Pipeline OCR/layout, extract according to schema and compare amount/unit/account with source. Save audit trail, encryption/ACL, reviewer for important fields; retention and operating procedures must comply with applicable legal requirements.

Link to this question
44Design an AI dynamic pricing engine.

Forecast demand and cost/inventory constraints, propose prices within approved margins. Check impact, fairness and competition regulations; Limited rollout, monitoring and rollback before revenue optimization.

Link to this question
45Design an AI resume screening system that handles 100K applications per week.

Use business-related criteria, permissioned data, and asynchronous pipelines to process records. Check bias by group/group assignment, explain criteria, human review and appeal; Do not disqualify candidates using sensitive proxies.

Link to this question
46Design an AI voice assistant architecture.

Separate audio receiver layer, turn manager, ASR/realtime model, execution tool and TTS. Two-way streaming, cancellation, conversation status and network outage handling; Measure the time to the first sound.

Link to this question
47Design a multi-agent workflow system where agents collaborate on complex tasks.

Orchestrator assigns tasks with clear input/output, checkpoints and permissions; agents communicate using schema. Parallel independent steps, synthesize/verify results and stop according to budget; Avoid multiple agents recording the same uncontrolled state.

Further reading

Multi-Agent Systems

Link to this question
48Design a real-time AI transcription system for concurrent audio streams.

Receive session audio, VAD/chunk and ASR streaming with partial/final transcript. Manage GPU batching, backpressure, reconnect and timestamp; Monitor WER by accent/noise and end-of-sentence latency.

Link to this question
49Design an AI-powered live streaming content moderation system.

Combine sample frame, ASR/OCR and classifier according to stream segment, keeping timestamp for fast processing. Escalate difficult cases, control false positives according to culture and have reviewers; Optimize detection latency versus sampling cost.

Link to this question
View this section in the original repository ↗

LLMOps and Production AI

53 questions
01How does Prompt Caching work?

Prompt caching reuses the same prefix's computational state, usually the KV cache, to reduce prefill. Need to cache key/version and isolate tenants; It's different from the full cache answer and doesn't eliminate the cost of generating output.

Link to this question
02Prefill vs Decode

Prefill handles token prompts to create hidden states/KV; decode generates each new token based on the cache. The two stages have different compute/bandwidth profiles and need a balanced scheduler.

Link to this question
03Why is prefill compute-bound and decode memory-bandwidth-bound?

Prefill gathers many tokens into a large matrix multiplication, so it often makes good use of compute. Small batch decode must read many weights/KV for few calculations, often limited bandwidth; Conclusion depends on batch and hardware.

Link to this question
04What is chunked prefill, and why does it improve tail latency under mixed traffic?

Chunked prefill breaks the long prompt into sections interspersed with running decode. It avoids a large prefill blocking all requests, improving tail latency but needs to choose the chunk size to not reduce throughput too much.

Link to this question
05What is Prefill-Decode Disaggregation, and when does it pay off?

Disaggregation separates worker prefill and decode for separate scaling/optimization. It is beneficial when the two workloads are very different and the KV transmission is fast enough; Network/cache transfer overhead may negate the benefit at small loads.

Link to this question
06Explain the AI product lifecycle from ideation to production.

Determine needs/KPIs, create baseline, prepare data, develop and eval before limited rollout. Operations require monitoring, feedback, versioning and rollback; Iterate improvements based on real user errors.

Link to this question
07What is LLMOps, and how does it differ from traditional MLOps?

LLMOps manages the LLM application lifecycle: prompt/context, retrieval, tool, model and evaluation. Compared to traditional MLOps, there is added risk of open output, token cost, injection, and changing API/model dependencies.

Link to this question
08How do you serve LLMs in production?

Choose API or self-host according to data quality/authority, implement appropriate auth, batching, quotas and cache. Load test, autoscale by token/concurrency, monitor tail latency and keep model/prompt version for rollback.

Link to this question
09What is model quantization?

Quantization reduces the numerical precision of weights, activations or KV to save memory/compute. Actual speed depends on kernel/hardware; Always measure the quality and workload that needs to be served.

Link to this question
10Explain post-training quantization (PTQ) vs quantization-aware training (QAT). What breaks when you push weights to 2-4 bits?

PTQ quantizes the trained model, often requiring calibration; QAT simulates quantization error at training. 2-4 bits can damage the outlier, sensitivity layer or reasoning; Use mixed precision and eval according to the task.

Link to this question
11How do you monitor LLM applications in production?

Track task success, errors, sampled hallucination, p50/p95 latency, tokens and costs. Attach prompt/model/index version, alert by user group and redact sensitive data in log.

Further reading

AI Agent Observability

Link to this question
12What is LLM observability?

Observability is the ability to understand behavior from traces, metrics, logs and evaluation. Trace needs to connect query, retrieval, model and tool to distinguish data, orchestration and model errors.

Further reading

AI Agent Observability

Link to this question
13What are guardrails for LLMs, and how do you implement them?

Guardrails includes schema, rule/classifier, ACL, policy tool and output inspection. Placed at input boundaries, before action and output; The self-assessment model is just a layer, not a guarantee of safety.

Link to this question
14How do you implement content filtering for AI outputs?

Incorporate policies, classifiers, and sensitive information checks per language/modality. Route ambiguous cases to reviewers, measure false positive/negative and have a complaint mechanism.

Link to this question
15How do you estimate the cost of running an AI-powered feature in production?

Estimate volume × token input/output × unit price, plus embedding, retrieval, GPU, storage, network, and operations. Calculated by successful tasks, including retries, cache hits and peak workload.

Link to this question
16How do you optimize LLM inference costs in production?

Step-by-step cost profile; Reduce redundant context/output, cache and use a model that matches the difficulty level. Batching/quantization helps self-host; Only accept the optimal after eval confirms no required quality loss.

Link to this question
17How do you implement A/B testing for LLM systems?

Split consistent user/session into variants, keeping prompt/model version and guardrail fixed apart from the test variable. Measure KPIs, quality, cost and safety; Use the full sample and stop early if there is significant harm.

Link to this question
18What is CI/CD for AI applications, and how does it differ from traditional CI/CD?

In addition to unit/integration testing, CI/CD must check whether dataset/prompt/model/index and evaluation are random. Use quality threshold, canary, artifact version and rollback; Don't just check for a successful build.

Link to this question
19How do you version and manage prompts in production?

Save prompt/template with version and model configuration, review as source code. Attach version to trace/eval, roll out via feature flag and have rollback; Do not edit prompt production silently.

Link to this question
20What is model versioning, and how do you handle model rollbacks?

Version weight/model ID along with tokenizer, runtime and generation configuration. Keep the old artifact, switch routing/alias atomically, and check cache/index compatibility before rollback.

Link to this question
21How do you implement rate limiting and throttling for LLM APIs?

Limit requests, tokens and concurrencies by tenant/API key. Use token bucket/queue, backpressure and retry-after; Distinguish between shared supplier quotas and individual customer quotas.

Link to this question
22How do you handle model updates and migrations without downtime?

Run the new version in parallel, shadow/eval, canary and then gradually transfer traffic. Ensure schema/tool/tokenizer is compatible and has fast rollback; Don't delete the old worker/artefact before confirming it's stable.

Link to this question
23What is the role of feature flags in AI deployments?

Feature flag enables/disables model, prompt or pipeline according to cohort without redeployment. It supports canary and kill switches; must manage permissions to change flags and check configuration combinations.

Link to this question
24How do you implement logging and tracing for LLM applications?

Use trace/run ID across gateway, retrieval, LLM and tools; log timing, status and version. Sensitive payloads need clear redact, retention/ACL, and appropriate sampling; The error must retain enough data to reproduce.

Further reading

AI Agent Observability

Link to this question
25How do you handle PII and sensitive data in LLM inputs and outputs?

Reduce data sent, redact/tokenize PII and apply encryption/ACL/retention. Check the provider's storage/training terms, data paths, and deletion mechanisms; PII filters do not detect all cases perfectly.

Link to this question
26What is a gateway pattern for LLM API management?

AI gateway is an intermediate layer that manages auth, keys, quotas, routing, retries and observability for many providers/models. It centralizes policy but must have HA, timeout and does not hide backend capacity differences.

Link to this question
27How does Token Streaming work?

The model generates tokens step by step and the server transfers small chunks to the client as soon as it is ready. Network chunks do not always correspond to a token; The client needs to concatenate the delta and handle the end/error message.

Link to this question
28How do you implement streaming responses for real-time AI applications?

Use SSE or WebSocket, propagate cancel/disconnect, flush according to proxy capabilities, and manage backpressure. Parse partial events within the correct boundaries, only consider complete when receiving the last signal and save the error state mid-stream.

Link to this question
29How does vLLM work?

vLLM is an LLM engine, featuring page-based KV management and continuous batching to take advantage of the GPU. Efficiency depends on model, kernel, length and scheduler; benchmark on real workloads.

Link to this question
30How does SGLang work?

SGLang provides optimized runtime/serving for LLM workloads, including radix cache prefix reuse and scheduling/batching. There are clear benefits to having many shared prefixes; Specific features depend on version/model.

Link to this question
31How does TensorRT-LLM work?

TensorRT-LLM optimizes inference on NVIDIA GPUs through specialized kernels, quantization and parallelism. Choose when hardware/model support and optimization are beneficial; Consider build/runtime processes and operating costs.

Link to this question
32How does llama.cpp run LLMs on everyday hardware?

llama.cpp runs the model via a C/C++ backend, supporting CPU and multiple GPU/backends with quantized GGUF weights. It takes advantage of the appropriate kernel and offload; The ability to run does not mean that every model can reach interactive speeds.

Link to this question
33How does Ollama work?

Ollama provides local model management, loading, and serving via convenient API/configuration. It uses inference backends depending on model/version; memory control, API permissions, and load limits are still needed.

Further reading

How does Ollama work?

Link to this question
34When would you choose vLLM vs SGLang vs TensorRT-LLM?

Compare vLLM/SGLang for flexible serving and cache/agent workloads; TensorRT-LLM when you want to deeply optimize NVIDIA GPUs. Choose by model support, throughput, TTFT/TPOT and actual operating level, not by other workload benchmarks.

Link to this question
35What are the key SLAs and metrics for production AI systems (latency, throughput, availability)?

SLA/SLO should include availability, true completion rate, p95/p99 latency, TTFT, TPOT and cost limits. High throughput is not enough if important requests are slow or the quality is reduced.

Link to this question
36Cloud vs on-device Model Deployment for AI applications.

Cloud has large compute, centralized updates but depends on network/data rights and transmission costs. On-device supports offline/privacy and close latency, in exchange for limited RAM/battery/model; hybrid can be used with user permission.

Link to this question
37How do you implement fallback strategies when the primary model is unavailable or rate-limited?

Use timeouts, circuit breakers, limited retries, and proven backup providers/models. Guaranteed idempotency for write actions; If there is no fallback of sufficient quality, return a clearly degraded state.

Link to this question
38How do you implement structured output from LLMs reliably in production?

Use schema-constrained output if supported; still parse and validate the business/ID/permissions on the server. Limited retry/correction, structured error response upon failure; Correct JSON syntax does not mean correct data.

Link to this question
39How do you handle long contexts efficiently in production (context compression, prefix caching)?

Combine retrieval, sourced summarization, and prefix caching to avoid reprocessing. Keep output/KV limits and evaluate information loss; cache doesn't help when prefix changes or permissions/versions are different.

Link to this question
40What is semantic routing, and how do you implement it in a multi-model system?

Semantic router classifies queries according to intent/difficulty to choose model or workflow. Set criteria, thresholds and fallbacks; eval both routing errors and model quality after routing.

Further reading

LLM Routing

Link to this question
41How do you manage secrets and API keys securely in LLM applications?

Save secrets in secret manager, grant minimum permissions, rotate and audit access. Do not include the key in the prompt, repo or log; Separate keys by environment/tenant and apply egress/quota to reduce damage.

Link to this question
42Your LLM API has latency spikes during peak hours. How do you stabilize it?

Measure queue time, token length, prefill/decode and provider throttling. Add admission control, batching/replica and cache; Context limit is too long, prioritizing requests according to SLO instead of receiving unlimited downloads.

Link to this question
43Your LLM endpoint's p99 latency doubled after a deploy with no model change. How do you diagnose it?

Compare traces before/after: longer prompt/context, cache miss, scheduler, dependency, network or runtime configuration. Reproduce peak workload, determine p99 increase stage and then roll back related changes if necessary.

Link to this question
44Your LLM costs are too high in production. How do you reduce costs without degrading quality?

Measure the cost of each successful task, find redundant retries/context/output and cache misses. Try routing/small modeling, batching or quantization via eval; Avoid lowering prices by increasing errors or making users ask again.

Link to this question
45Your application is hitting LLM provider rate limits during peak hours. How do you handle it?

Apply token bucket and concurrency limit, queue with backoff/jitter according to retry-after. Pool/cache tasks appropriately, request quotas or use backup providers; Continuous retry only makes the blockage worse.

Link to this question
46Your application depends on one LLM provider. How do you switch providers without downtime?

Use the adapter class to clearly differentiate the provider's schema/tool/stream, eval the replacement version and then shadow/canary routing. Separate secrets/config and keep rollback; Check data permissions before switching to a new provider.

Link to this question
47Your AI system handles 100 requests/sec but crashes at 5000. How do you scale for concurrent requests?

Load testing to identify bottlenecks and capacity by token, not just requests/second. Use autoscale worker/index, queue/backpressure and quotas; Protect the database/network to not bring down the rest.

Link to this question
48A traffic spike brings down your AI system. How do you handle peak traffic?

Limit admission/concurrency, queue length/deadline and priority according to SLO. Scale before full, cache and degrade secondary functions; Quick error response has better retry-after so that every request timeout.

Link to this question
49One LLM provider outage took down your entire system. How do you eliminate single points of failure?

There are multiple provider/zone checks, health checks and circuit breakers at the gateway. Single point of failure type in auth/config/index; failover drills, monitor quality, and check data is allowed to be transferred.

Link to this question
50Your multi-LLM pipeline fails when one model in the chain breaks. How do you handle orchestration failure?

Checkpoint each step, limit timeout/retry and save completed output. Separate temporary errors from operational errors; Use compensation/idempotency for external effects, return partial results or transfer people when needed.

Further reading

AI Orchestration

Link to this question
51Your AI pipeline has zero visibility into which step is failing. How do you add observability?

Add trace ID across pipeline and span for retrieval, prompt, model, parser, tools. Attach latency/token/version/status, redact payload and build staged dashboard/alerts with task success.

Further reading

AI Agent Observability

Link to this question
52You quantized your LLM, but accuracy dropped significantly. How do you minimize quantization loss?

Identify sensitive layers/tasks, use representative calibration, increase bits or keep some layers at high precision. Consider QAT and kernel support; Compare original checkpoint on pre-release eval.

Link to this question
53One failing AI component can take down your entire platform. How do you design graceful degradation?

Isolate with timeout, bulkhead, circuit breaker and separate queue; Avoid retry cascade. Has minimal proven fallback, limited tenant/component impact, and degraded functionality notifications.

Link to this question
View this section in the original repository ↗

Evaluation and Testing

36 questions
01AI Agent Evaluation

Evaluate agents by correct end state, quality of tool calls, number of steps, cost, and permission violations. Use tasks with validation criteria, simulate errors and run iteratively to measure stability.

Further reading

AI Agent Evaluation

Link to this question
02LLM Evaluation

LLM evaluation combines automated metrics, rubric/judge, and human evaluation on representative data. Report by task group, same cost/latency; Do not use an average score to conclude the entire quality.

Further reading

LLM Evaluation

Link to this question
03AI Agent Observability

Agent observability connects each decision, tool call, result, and state transition with a trace. Record version, time, token/cost and errors, and mask sensitive data so it can be investigated without causing a leak.

Further reading

AI Agent Observability

Link to this question
04What is evaluation-driven development for AI applications?

Evaluation-driven development determines criteria and test suites first, using observed errors to select changes. Each new prompt/model/pipeline must exceed baseline and not cause significant group regression.

Link to this question
05Why is AI only as good as our definition of done?

The model can only be optimized according to what we measure and define success. If done simply generates an answer, the system may ignore correctness, safety, or user value.

Link to this question
06How do you evaluate LLM outputs? What metrics do you use?

For extraction use exact match/F1 by field; with retrieval use recall/nDCG; With generation use factuality, relevance and rubric. Includes task success, safety, latency/cost; Choose metric according to actual requirements.

Further reading

LLM Evaluation

Link to this question
07Explain BLEU, ROUGE, and BERTScore. When would you use each?

BLEU is more about n-gram precision, often using translation; ROUGE tends to overlap/recall, often using summary. BERTScore compares embedding tokens; All three do not replace testing for factuality or real quality.

Further reading

LLM Evaluation

Link to this question
08What is G-Eval, and how does it use LLMs for evaluation?

G-Eval uses LLM for rubric/criteria assessment with a structured scoring process. Need to calibrate with the examiner; The score is also influenced by the judge's model, prompt and bias.

Further reading

LLM as a Judge

Link to this question
09What is LLM-as-a-judge evaluation, and what are its limitations?

LLM-as-judge scores or compares pairs of responses according to a rubric, helping to expand evaluation. Limitations include position/length bias, stylistic preferences, and factuality errors; Reverse the order and check for consensus with others.

Further reading

LLM as a Judge

Link to this question
10How do you conduct human evaluation for AI systems?

Use clear instructions/rubrics, anonymized samples, and random order. Train raters, measure inter-rater agreement, adjudicate cases of disagreement, and monitor label quality over time.

Further reading

LLM Evaluation

Link to this question
11What is red teaming, and how do you red team an LLM application?

Red teaming proactively looks for corrupt behavior such as injection, data leaks, tool abuse and harmful content. Based on the threat model, test multiple passes/data sources and record evidence of impact, not just shocking sentence sets.

Link to this question
12How do you detect and measure hallucinations in LLM outputs?

Separate the output into claims, compare them to standard evidence/sources, and score support. Measure false claim rate/no source, check samples by people; The model's confidence or self-checking is not enough for ground truth.

Link to this question
13What is adversarial testing for AI systems?

Adversarial testing uses input designed to exploit weaknesses: paraphrase, injection, noisy data, and buggy tools. Measure the policy bypass/task failure rate and add the found cases to the regression suite.

Link to this question
14How do you build a regression test suite for AI applications?

Save representative production cases, error cases, and version expectations/rubrics. Rerun when prompt/model/index changes, score by slice and use threshold for random results instead of absolute string comparison in all cases.

Link to this question
15What are benchmark suites (MMLU, HumanEval, GSM8K), and how do you interpret them?

MMLU measures multi-domain knowledge/reasoning; HumanEval measures code generation by test; GSM8K measures math with text. Score depends on setup, contamination and sampling, so it does not directly infer production capacity.

Further reading

LLM Evaluation

Link to this question
16What is benchmark contamination, and how do you guard against it?

Contamination occurs when eval data or near duplicates appear in training. Dedupe by source/content, keep separate/new tests and check overlap; With closed models, it is often impossible to prove complete freedom from infection.

Further reading

LLM Evaluation

Link to this question
17Your new model version scores higher on every benchmark, but users say it got worse. Why does this happen, and how do you find the problem?

Benchmarks may differ from distribution, rubrics may not match needs, or the model may change style/latency. Parse feedback into slices, create eval from real cases and test pipeline/routing, not just change models.

Link to this question
18How do you evaluate a RAG system end-to-end?

Measure recall/precision, reranking and faithfulness/correctness of answers in the same case. Add unanswerable statements, ACLs, old documents, and conflicting sources to check the entire flow.

Further reading

LLM Evaluation

Link to this question
19How do you evaluate the quality of AI agents?

Check task results and impacts outside the system, not just what the agent said was done. Score tool/arguments, recovery, budget, safety and success rate over multiple runs.

Further reading

AI Agent Evaluation

Link to this question
20How would you evaluate an autonomous coding agent? Why can SWE-bench pass rates be misleading?

Use fixed repo and environment, blind/regression testing, compute limits and valid patch testing. SWE-bench pass rate depends on harness, number of tests, leakage and test coverage; The test pass is not sure to fix the correct idea or not cause a regression.

Further reading

AI Agent Evaluation

Link to this question
21What is the difference between offline and online evaluation for AI systems?

Offline eval runs on a fixed dataset, making it easy to reproduce and diagnose. Online eval measures the impact on real traffic via rollout/A-B, but has noise and risks; need both pre and post release.

Link to this question
22How do you measure factual consistency in LLM outputs?

Link each claim to the reference source/context and then check entailment, data and timing. Report claim supported/contradicted/unsupported and check the model manually; semantic similarity is not enough to confirm the truth.

Link to this question
23How do you evaluate multi-turn conversation quality?

Use targeted multi-turn conversations, change topics, correct information and missing facts. Remember correctly, don't make wrong assumptions, task success, privacy, and the ability to recover from misunderstandings.

Link to this question
24What is the role of golden datasets in AI evaluation?

The Golden dataset is a set of high-quality examples/labels or rubrics that serve as a stable benchmark. Versioning, testing labels and adding new cases but keeping testing independent from the optimization process.

Link to this question
25How do you build an eval set when there is no labelled ground truth and domain experts are expensive?

Start with a small set of verification experts on important cases, use weak labels/synthetics to expand and then take test samples. Prioritize experts for high disagreement/influence models; Don't call the label generated by the model a solid ground truth.

Link to this question
26How do you implement continuous evaluation for production AI systems?

Run regression before deploying, take controlled production samples, and add failure cases to the eval. Track by version/slice, drift/quality warnings and rollback when risk thresholds are exceeded.

Link to this question
27How do you evaluate bias in AI model outputs?

Legal/appropriate grouping, error comparison, calibration and manipulation, not just output scaling. Test for intersecting groups, representative data, and counterfactual samples; Choose a metric associated with the type of harm that needs to be avoided.

Link to this question
28How do you compare two models or prompts in a statistically rigorous way?

Using the same case, blind/random scoring and paired comparisons. Report effect size, confidence interval using bootstrap or appropriate testing; controls for multiple comparisons and between-run variability.

Link to this question
29How do you evaluate the robustness of an LLM application across input variations?

Create variations that preserve ideas such as paraphrase, typo, order, language, and context noise. Measure the resulting variability for each group and verify that the variation actually does not change the desired label.

Link to this question
30What are the key differences between evaluating traditional ML vs LLM applications?

Traditional ML often has a fixed target and clear metrics; LLM has many valid answers, open output and context/tool ​​dependency. Therefore, we need rubric, multi-step eval, judge with calibration and safety checks in addition to standard metrics.

Link to this question
31How do you set up an evaluation framework from scratch for a new LLM application?

Identify tasks/risks, build a baseline and set of representative cases with rubrics. Create a runner that saves version/trace, combines code/person/judge scoring, sets rollout thresholds, and production error adding process.

Further reading

LLM Evaluation

Link to this question
32Your model passes one fairness metric but fails another. How do you handle conflicting audit results?

Fairness metrics can conflict when distributions/conditions are different. Identify the type of harm and obligations applicable to related parties, report trade-offs transparently; do not choose the most beautiful index to cover the bias.

Link to this question
33Your model was fair at deployment, but became biased 6 months later. How do you monitor continuously?

Monitor input distribution, error, and group effects in the presence of delayed labels. Set alarms, take test samples, correct data/models and re-evaluate; save version to distinguish drift from system changes.

Link to this question
34An external auditor cannot reproduce your model's results. How do you ensure audit reproducibility?

Save model/prompt/data/index version, sampling configuration, runtime and environment, and permission-controlled input. With a non-deterministic backend, providing multiple runs and variable ranges, no bit-for-bit reproduction is promised.

Link to this question
35How do you structure red teaming for an LLM chatbot before launch?

Establish threat model, multiple jailbreak attempts, indirect injection, PII leakage and tool actions. Use a sandbox with decoy data, rate the impact, fix the cause, then run again with the attack suite.

Link to this question
36How do you red team a multimodal model where text-only safety tests miss cross-modal attacks?

Try hidden instructions in images, OCR, audio and combine many antonym modality. Check if the model misses the attack source and if the policy runs on all input/output paths; evaluates both false positive and normal content.

Link to this question
View this section in the original repository ↗

AI Safety, Ethics, and Responsible AI

45 questions
01What are hallucinations in LLMs, and how do you mitigate them?

Hallucination is content that is false or not supported by evidence but is presented as true. Reduced by retrieval, claim verification, appropriate tools and rejection mechanisms; There is no prompt for complete removal.

Link to this question
02What is prompt injection, and what are the different types (direct, indirect)?

Direct injection is in the user request; indirect injection is in the document/web/email being read. Both tried to change their behavior; separate trust boundaries and control permissions/actions outside the model.

Link to this question
03How do you implement input and output guardrails for AI systems?

Validate input, size/format and permissions; Check output against schema, policy and sensitive data. Before the tool action there must be a separate gate; Combine rule/classifier with logging and escalation for difficult cases.

Link to this question
04What is AI alignment, and why is it important?

Alignment aligns AI behavior with defined goals, values, and constraints. It helps reduce unintended behavior but does not prove the system is secure in all deployment contexts.

Link to this question
05How do you detect and mitigate bias in AI systems?

Measure bias and group/cross-group effects, check data and proxies. Edit sampling/label/target, calibrate or human review; Reassess efficiency and fairness after each change.

Link to this question
06What are the key data privacy considerations (GDPR, CCPA) when building AI applications?

Establish the processing purpose and lawful basis, minimize data, provide transparency, and support access/deletion rights where applicable. Manage retention, processors and transfers; have the legal team assess each use case rather than relying on blanket consent.

Link to this question
07How do you handle PII in LLM inputs and outputs?

Collect only necessary data, detect/redact PII before logging/sending the model, and protect with encryption/ACL. Check output and provider retention; Pseudonymized data can still be personal data.

Link to this question
08What is explainability in AI, and why does it matter?

Explainability helps users understand the rationale, limitations, and how to verify decisions. Use reasons to attach real evidence/features; the explanation generated by LLM does not itself reflect the correct model mechanism.

Link to this question
09What is the difference between interpretability and explainability?

Interpretability often refers to understanding the mechanism inside the model; explainability refers to the method of explaining behavior/output. The two concepts overlap; A posteriori explanations are not necessarily true causal descriptions.

Link to this question
10What is mechanistic interpretability, and why do AI labs invest in it?

Mechanistic interpretability finds circuits/features and computational mechanisms within the network by analysis and intervention. It can support error/safety research; A found circuit does not guarantee understanding of the entire model.

Link to this question
11How do you build trust with users in AI-powered applications?

Transparent system is AI, state limitations, provide sources and how to correct/complain. Track real reliability, keep data promises, and give people control over key decisions.

Link to this question
12What are adversarial attacks on AI systems, and how do you defend against them?

Adversarial attacks attempt to cause errors using perturbation, prompts, data, or tools. Defense by threat model: validation, training/eval antagonism, isolation and minimum permissions; Do not assume a filter will block all attacks.

Link to this question
13What is data poisoning, and how can it affect AI models?

Data poisoning injects false/poisonous data into training or knowledge stores to change model behavior. Use sources with provenance, change moderation, outlier/trigger checking, and data/index rollback capabilities.

Link to this question
14How do you implement content safety filters for AI-generated content?

Combine classifier/rule and check according to policy for each modality/language. Set thresholds according to harm level, ambiguous escalation cases and appeal; Monitor false positives to avoid blocking the wrong community.

Link to this question
15What is responsible AI, and what frameworks exist for implementing it?

Responsible AI brings governance, impact assessment, safety, fairness, transparency and accountability into the product lifecycle. NIST AI RMF or appropriate standard/regulation may be used; The framework does not self-certify compliance.

Link to this question
16How do you handle copyright and intellectual property concerns with AI-generated content?

Check training source license/terms, model and output; save provenance and limit unauthorized verbatim reproduction. Copyright depends on content and authority; Legal review before sensitive commercial use.

Link to this question
17What is the EU AI Act, and how does it affect AI engineering?

The EU AI Act governs risk levels and provider/deployer roles, including transparency requirements and obligations for high-risk/GPAI systems. Classify use cases and check the current application schedule; There is no universal deadline for all obligations.

Link to this question
18How do you implement audit trails and logging for AI decisions?

Save events with time, model/prompt/data version, minimum input, decision and approver. Use anti-edit logs, ACL/retention and trace links; Do not overwrite personal data in exchange for audit capabilities.

Link to this question
19What is model card documentation, and why is it important?

Model card records purpose, data, evaluation, limitations, affected groups and usage/non-usage. It helps implementers make appropriate assessments; does not replace testing in a real environment.

Link to this question
20How do you handle misuse and abuse of AI systems in production?

Define policies, authentication, quotas, and detect abusive patterns by account/behavior. Limited tools/permissions, leveled responses and appeals; save the minimum necessary evidence.

Link to this question
21What is differential privacy, and how can it be applied during model training?

Differential privacy limits an individual's influence on statistical/training results. DP-SGD clip gradient and add noise, monitor epsilon/delta budget; Ensures assumed dependencies and correct implementation.

Link to this question
22How would you design an AI incident response plan?

Prepare the incident level, responsible person, kill switch and communication procedures. When it happens: isolate, keep evidence of rights, harm reduction/rollback, investigate the cause and then check measures before recovery.

Link to this question
23What is the NIST AI Risk Management Framework (AI RMF)?

NIST AI RMF is a voluntary framework for managing AI risks through Govern, Map, Measure and Manage. It helps organizations identify, measure and treat risk across the lifecycle, not operating licenses or legal certifications.

Link to this question
24Your healthcare chatbot gives medical diagnoses it should not make. How do you add safety guardrails?

Clearly limit the scope of support, check input/output according to use cases and refer to experts when required for diagnosis. Use approved sources, escalation and clinical validation; Adding a disclaimer alone does not fix dangerous behavior.

Link to this question
25Your AI system is reproducing copyrighted material verbatim. How do you prevent this?

Disallowed data types, dedupe and extraction/memorization testing; Detect output similarity in sensitive content. If you have learned incorrectly, you need to retrain/unlearn to verify; Just blocking the exact sequence is not enough.

Link to this question
26Your resume screening AI rejects more female candidates for engineering roles. How do you fix gender bias?

Verify employment criteria, labels and sampling, measure error/decision rate by group. Inappropriate proxy type, correct process and human review/appeal; Just deleting the gender field does not eliminate bias.

Link to this question
27Your AI model passes bias checks by gender and race separately, but fails for intersectional groups. How do you handle it?

Evaluate intersectional groups such as gender/age or background combination, sufficient sample, and uncertainty range. Correct the source of bias in the harmed group; A good GPA doesn't compensate for serious hidden errors.

Link to this question
28Your AI denied a loan, and the customer demands a GDPR explanation. How do you provide one?

Provide meaningful information about the logic, data and main factors behind the decision, together with objection or human-review rights where applicable. Have legal specialists determine the specific GDPR obligations; do not invent explanations with an LLM.

Link to this question
29A user invokes the right to be forgotten, but their data is in your model weights. How do you comply?

Determine the scope and exceptions of the right to delete, deprecate/delete data at the source, index and copy according to the policy. Retraining/unlearning assessment and validation; Deleting the source record does not guarantee that the model has forgotten the information in weights.

Link to this question
30The EU AI Act may classify your AI system as high-risk. How do you comply?

Determine legal classification and roles, then plan for risk management, data, documentation, logging, human oversight and appropriate assessments as needed. Check the updated regulations/application schedule with the law.

Link to this question
31Your differentially private model lost significant accuracy. How do you balance privacy and utility?

Re-evaluate epsilon/delta, clipping, noise and data size according to risk. Improve data/model before relaxing budget; Every privacy change must be recorded and approved, not just to optimize accuracy.

Link to this question
32One malicious participant is poisoning your federated learning model. How do you defend against it?

Authenticate clients, limit/norm-clip updates, and use robust aggregation/detection by threat model. Test the global model on clean data; secure aggregation protects updated content but does not prevent poisoning itself.

Link to this question
33Your AI hiring model uses proxy features for protected attributes. How do you eliminate proxy discrimination?

Check the correlation and counterfactual effects of features such as address/school, non-work related factors. Hold group audits when legal; It is not possible to guarantee removal of all proxies by simply deleting a few columns.

Link to this question
34Your predictive model creates a feedback loop of biased outcomes. How do you break it?

Track how to decide the model to change future label data, add less skewed data and evaluate independently. Use controlled exploration/human review to avoid the cycle of only learning from people who have been prioritized by the system.

Link to this question
35Your AI generates fake news images. How do you implement watermarking for AI-generated content?

Combine model-appropriate persistent watermarks with signed metadata/provenance such as Content Credentials. Watermark can be edited/deleted; Need clear disclosure and do not consider technical traces as proof of correct content.

Link to this question
36Your AI denies a service, and the user has no way to challenge it. How do you design an appeals process?

Let users know the decision and criteria, and provide a review request channel with clear deadlines. The reviewer has the right to edit and view proofs; Error tracking is resolved to improve the system.

Link to this question
37An auditor asks why your AI rejected a request 6 months ago, and you have no logs. How do you build audit trails?

It is impossible to reliably reconstruct a decision in the absence of original evidence. Now save model/prompt/data version, input according to policy, decision and approval in audit log to prevent editing; truthfully reporting historical gaps.

Link to this question
38You removed PII, but users were re-identified from anonymized data. How do you prevent re-identification?

Evaluate the ability to link quasi-identifiers and external data; Reduce granularity, limit sharing, and check re-identification. Pseudonymization is not the same as anonymization; Consider DP for appropriate statistics.

Link to this question
39A pre-trained model from an open-source repo may contain a hidden backdoor. How do you detect it?

Check source, hash/license and run in sandbox; eval trigger/backdoor with unusual behavior. Compare with clean model and analyze data/weights when available; Test pass does not prove for sure that there is no backdoor.

Link to this question
40Your LLM's training data was deliberately poisoned by an adversary. How do you respond?

Isolate the affected checkpoint/data, determine the source and time of intrusion, then rollback. Clean corpus, retrain from trust markers and add provenance and data review; Check the implicit behavior according to the trigger.

Link to this question
41Your AI mental health chatbot gave harmful advice to a user in crisis. How do you mitigate harm?

Stop or limit the harmful flow, refer to qualified personnel and provide appropriate local emergency assistance lines. Expert safety checks, escalation updates and recurrence monitoring; don't just fix the reminder.

Link to this question
42Your AI system caused incorrect critical decisions. How do you run a blameless post-mortem?

Keep timeline and evidence, focus on system/process conditions instead of blaming individuals. Determine the root cause, level of impact, take appropriate action, and test to prevent recurrence before closing the incident.

Link to this question
43Radiologists agree with AI 98% of the time, even when it is wrong. How do you prevent human over-reliance on AI?

Measure automation bias with blind assessments and disagreement cases, showing evidence/limitations instead of misleading confidence scores. Retain decision-making authority for the physician and independently examine high-impact cases.

Link to this question
44Your content moderation flags normal cultural expressions as offensive in other markets. How do you adapt cross-culturally?

Collect cases and labels from someone who understands the local language/culture, edit taxonomy/threshold according to context. Measure false positives according to the market, give appeal and avoid using machine translation as the only ground truth.

Link to this question
45Your AI training produces massive carbon emissions. How do you reduce environmental impact?

Measure energy and emissions by workload, reduce overtraining, use the right model/precision, and improve utilization. Choose efficient infrastructure/running schedules when possible; reporting the calculation method instead of just advertising the number of tokens saved.

Link to this question
View this section in the original repository ↗

Multimodal AI

30 questions
01What are Multimodal AI models, and how do they process different types of data?

Multimodal model handles multiple types of data such as text, images, audio and video using appropriate encoders/representations. Modality is linked through common space, cross-attention or combined token chain.

Further reading

Multimodal AI

Link to this question
02How do vision-language models process images?

Vision encoder converts image patches/features into representations; projector or cross-attention feeds them into the language model. Text prompts are task-oriented; Resolution and number of visual tokens affect details/cost.

Further reading

Multimodal AI

Link to this question
03How do Image Embeddings work?

Image embedding is a global image vector or patches learned from the visual/image-text target. Used for searching, sorting or retrieval; Must use an encoder that is compatible with the query and properly normalized.

Link to this question
04How does CLIP work, and why is it important for multi-modal AI?

CLIP learns two image/text encoders using contrastive loss on image-caption pairs. It creates a common space for zero-shot classification and text-image retrieval; does not automatically read and understand every small detail like specialized OCR.

Link to this question
05What are the key architectures for multi-modal models?

Common architectures include dual-encoder, encoder-projector-LLM, cross-attention and decoder handling multi-modality tokens. Dual-encoder integrated retrieval; Unified/cross-attention architecture suitable for interaction and content generation.

Further reading

Multimodal AI

Link to this question
06How does image generation work with diffusion models (Stable Diffusion, DALL-E, Flux)?

Diffusion reverses the process of adding noise, often in latent space; Text conditioning directs the generative process. Many models use Transformer/flow matching; Details vary by version, not all DALL-E systems have the same architecture.

Further reading

Diffusion Models

Link to this question
07What is text-to-speech (TTS), and what models are used for it?

TTS turns text into sound, usually through an acoustic model and then a vocoder or directly generates an audio token. Choose by language, voice quality, streaming/latency and voice permissions; Families include VITS and the codec-token model.

Link to this question
08How does speech-to-text (Whisper) work?

Whisper is an encoder-decoder Transformer: encodes log-Mel characteristics of audio and decodes text/timestamp/task tokens. Evaluate WER by language/noise; Do not assume that the text produced in the silent passage is true speech.

Link to this question
09Budget the end-to-end latency for a real-time voice agent (VAD, ASR, LLM, TTS, network). Where does the time go?

Example target after end of turn: VAD 150 ms + ASR 150 + LLM 300 + TTS 150 + life 100 ≈ 850 ms. This is an illustrative budget; streaming overlaps the steps and must measure actual p95.

Link to this question
10How do you handle barge-in (user interruptions) in a voice agent?

VAD/turn manager detects user interruption, cancels generation and audio playback is running. Synchronize the transcript with the actual audio played, discard the old chunk, and continue from the state the user actually listened to.

Link to this question
11Cascaded ASR + LLM + TTS vs native speech-to-speech models: what are the trade-offs?

Cascade is easy to debug, change each model and control the transcript but has more latency and loses sound nuance. Native speech-to-speech can preserve prosody and reduce concatenation steps; more difficult to observe/control and depends on backend capacity.

Link to this question
12What is multi-modal RAG, and how does it differ from text-only RAG?

Multimodal RAG retrieves evidence including images, tables, audio/video in addition to text. Need compatible parser/embedding and keep page/timestamp; The generated model must receive the correct modality instead of just a caption with missing information.

Link to this question
13How do you build a system that processes both images and text?

Parse text and images with location, choose VLM or two encoders with combined layers depending on the task. Keeping the source ID, size limit, and eval on the case requires both types of data.

Further reading

Multimodal AI

Link to this question
14What are multi-modal embeddings, and how are they used for cross-modal search?

Multi-modality embedding is learned from linked data so that text/image/audio can be compared in the appropriate space. Use text to find images or vice versa; need to check the model's specific cross-modal capabilities.

Further reading

Multimodal AI

Link to this question
15How do you evaluate multi-modal AI systems?

Measure quality by task such as VQA accuracy, retrieval recall, ASR WER or photo/audio rubric. Check groundedness, synchronization of modality, latency/cost and cases of missing or conflicting data.

Link to this question
16What are the challenges of real-time multi-modal AI processing?

Difficulty in synchronizing time, bandwidth, token/frame budget and total latency across multiple stages. Needs streaming/backpressure, proper sampling, and lossy handling; Taking just a few frames can cause you to miss important events.

Link to this question
17How do you handle video understanding with AI?

Split video into clips/keyframes, keep timestamp and can add audio transcript/OCR. Use temporal model or aggregate by segment; Check events between frames, time relationships and context constraints.

Link to this question
18What is visual question answering (VQA)?

VQA answers questions based on photos and language. Need to connect the correct image area to the question, counting/reading as needed; Fluent output but not image based is grounding error.

Link to this question
19What is document understanding, and how do models parse documents with layouts?

Document understanding uses OCR, layout and page/table structure to understand documents. Holds coordinates, reading order, header/units; check parser before blaming LLM synthesis.

Link to this question
20How do you fine-tune a vision-language model?

Prepare quality image-text/instruction pairs, choose train projector/LoRA or full model according to budget. Use correct image preprocessing, keeping modality distribution and eval grounding, OCR, hallucination and language capabilities.

Link to this question
21What are the latency and cost considerations for multi-modal AI in production?

Cost depends on resolution, number of frames, audio length and token output, not just number of requests. Task-based payload reduction, secure encoder cache and stream; Measure quality before downsample/compression.

Link to this question
22How do you handle multi-modal content moderation?

Combines OCR/ASR, image/audio/video classifiers, and inter-modality context understanding. Save timestamps/flagged regions, ambiguous escalation cases, and evals by language/culture; a text filter does not provide enough coverage.

Link to this question
23What is text-to-video generation, and what are the current state-of-the-art approaches?

The main directions include latent video diffusion, diffusion Transformer and flow matching with attention in space-time. The difficult problem is object/motion consistency and long-term costs; There is no one model that leads in all criteria.

Link to this question
24Explain Multimodal Fusion Techniques: Early Fusion vs Late Fusion.

Early fusion combines early features/tokens for deep interactive learning but is computationally intensive and requires associated data. Late fusion combines separate encoder points/outputs, easy to modularize but may lose detailed interaction.

Link to this question
25Your vision-language model generates factually incorrect image descriptions. How do you fix it?

Check input/resolution and image areas containing evidence; Use grounding data and request only visible details. Eval claim according to image area, allowing for uncertainty; Don't just add a longer prompt.

Link to this question
26Your VLM answers single-image questions but fails on multi-page documents. How do you fix it?

Keep page order, layout, table header and page ID; retrieval by page/region before aggregation. Check visual token budget, split multiple passes with source and eval relationships between pages.

Link to this question
27Your multimodal LLM ignores the image and generates descriptions from text alone. How do you fix it?

Try ablation to remove/change images to measure whether the model uses real images. Fix visual tokens/projector pipeline or text data, add examples that require photographic evidence and test grounding instead of just text quality.

Link to this question
28Your diffusion model ignores precise control requirements in text prompts. How do you improve controllability?

Use additional conditioning such as mask/inpainting, pose/depth/edge conditioning or ControlNet as appropriate. A good descriptive prompt helps but does not guarantee correct layout; check geometric constraints in output.

Link to this question
29Your diffusion model generates sharp but repetitive images. How do you balance quality vs diversity?

Evaluate collapse mode/dataset overlap, seeding, guidance and sampling. Reduce excessive guidance or increase data/conditioning variety; Measure both quality and diversity instead of choosing the best photo alone.

Link to this question
30Your diffusion model takes too long per image. How do you speed up sampling?

Reduce the number of steps with a suitable sampler or distiller/consistency model, optimize kernel/precision and batch. Resolution can be reduced if the mission allows; Benchmark quality by speedup level and avoid the default of few steps to always maintain quality.

Link to this question
View this section in the original repository ↗

AI Infrastructure and Scalability

35 questions
01How do you improve inference speed in production LLM deployments?

Profile prefill/decode/queue first; Optimize batching, KV cache, kernel, quantization and parallelism accordingly. Reduce unnecessary tokens, cache prefixes and preserve latency/quality SLO; Add GPU only if bottleneck is in compute/memory.

Link to this question
02LLM optimization techniques

Main groups: reduce compute by small model/distillation, reduce precision, optimize attention/KV, batching and speculative decoding. Each way has hardware conditions and trade-offs; measure both quality and performance.

Link to this question
03How do you select GPUs for LLM inference?

Calculate VRAM for weights/KV/activation and see bandwidth, compute at required precision, interconnect and kernel support. Choose according to real throughput and tail latency workload, not just peak FLOPS or RAM capacity.

Link to this question
04How does a GPU work for Deep Learning?

GPUs have many parallel processing units and high memory bandwidth; tensor cores accelerate matrix multiplication in supported numeric types. Efficiency depends on large enough workloads and data circulation, not all code is automatically faster.

Link to this question
05How do CUDA Kernels work?

CUDA kernel is a function that runs in parallel on the GPU via grid/block/thread. Optimize coalesced memory, shared memory, occupancy and reduce synchronization/launch; Check correctness before benchmarking.

Link to this question
06How does a Google TPU work?

TPU is Google's accelerator that optimizes tensor/matrix operations, featuring a dedicated systolic and compiler/runtime array. Efficiency depends on model, precision and how data/compute is distributed between chips.

Link to this question
07How does an LPU work?

Groq's LPU drives inference with multiple SRAMs on the chip and execution schedules set by the compiler to reduce latency fluctuations. Large models are distributed across many chips; Must measure cost/throughput according to specific deployment.

Further reading

How does an LPU work?

Link to this question
08Estimate the GPU memory needed to serve a 70B model (weights, KV cache, activations). Does it fit on a single 80 GB GPU?

70B weights bf16 requires about 140 GB so it won't fit an 80 GB GPU even before KV/activation. INT8 is about 70 GB which is very tight; 4-bit is about 35 GB before metadata, need to add KV, workspace and headroom to reach a reasonable conclusion.

Link to this question
09Do the roofline math: how many tokens/sec can one H100 produce for a 70B model at batch size 1?

For example, H100 SXM has a bandwidth of about 3.35 TB/s: with dense 70B bf16 ≈140 GB weights, batch-1 bandwidth ceiling is about 3350/140 ≈24 tokens/s. Just the ideal roofline; an 80 GB GPU does not contain enough bf16 weights, in fact needs to shard/quantize and recalculate.

Link to this question
10What is model parallelism vs data parallelism in distributed training?

Data parallel duplicates the model, splits the batch and then synchronizes the gradient. Parallel model divides parameters/calculations across devices to accommodate large models; often combines many types of parallelism according to memory and interconnect.

Link to this question
11What is tensor parallelism, and how does it help serve large models?

Tensor parallel divides matrices/layers on multiple GPUs, calculating the same forward pass. Reduces weights per GPU but increases collective communication, so interconnect is fast and batch/shape efficient enough.

Link to this question
12What is pipeline parallelism?

Pipeline parallel divides layers into stages on other devices, transmitting activation through the stage. Microbatch helps with overlap but has pipeline bubbles and is difficult to balance stages; Increase the delay of a request if coordination is poor.

Link to this question
13How does continuous batching improve LLM inference throughput?

Continuous batching for newly joined requests and completed requests leave the batch at the scheduling boundary. It increases utilization compared to waiting for the entire batch to finish; The scheduler still has to balance the long prompt and the running decode.

Link to this question
14What is speculative decoding, and how does it speed up inference?

Draft model/algorithm proposes multiple tokens, target model checks in blocks. The right acceptance mechanism can keep target delivery; Benefits depend on acceptance rate, overhead and hardware parallelism.

Further reading

Speculative Decoding

Link to this question
15How does Medusa (multi-head speculative decoding) work?

Medusa adds many prediction heads to predict future tokens, combine them into a candidate tree and then target them to test in parallel. Need to train heads and choose acceptance scheme; Not all sampling variations preserve the exact target distribution.

Link to this question
16How does EAGLE (feature-level speculative decoding) work?

EAGLE predicts the target's autoregressive feature for fast drafting, and has conditioning tokens to handle uncertainty. Target verifies candidate trees; Speed ​​depends on draft accuracy and overhead, not a fixed speed level.

Link to this question
17What is N-gram Speculation in LLMs, and how does it speed up generation?

N-gram speculation takes the continuation sequence from the n-gram already in prompt/history as a draft, no need for a separate draft model. Target still checks; Compatible with many duplicate/copy segments but low efficiency if there are no duplicate samples.

Link to this question
18What is KV cache, and how do you manage memory for it?

The KV cache stores the K/V per layer for the processed token, avoiding recalculating the prefix when decoding. Managed by paging, prefix sharing with permissions, context/batch limits and precision; clear cache when request ends/cancels.

Link to this question
19What is Paged Attention?

PagedAttention divides KV into physical blocks and logical block mapping, reduces fragmentation and supports cache sharing. It optimizes allocation/serving; Do not automatically compress KV content or change dense attention to sparse.

Link to this question
20How does GGUF work?

GGUF is a format that contains tensors, quantization types, and metadata needed for inference. Backend like llama.cpp reads/memory-map and runs the appropriate kernel; GGUF is not an acceleration algorithm or model architecture per se.

Further reading

How does GGUF work?

Link to this question
21How do you optimize inference for edge and mobile deployment?

Choose a small/quantized model, limit the context, use backend/kernel to optimize the device and consider GPU/NPU offload. Measure RAM, battery, heat and long-term latency; Offline support and permission before fallback cloud.

Link to this question
22What is model quantization (INT8, INT4, FP16, BF16), and how does it affect quality?

INT8/INT4 represent fewer bits, while FP16/BF16 are 16-bit floats with different value/precision ranges. Low quantization reduces memory but may lose quality; Needs kernel support and appropriate calibration/eval.

Link to this question
23How do you implement auto-scaling for AI workloads?

Scale by queued tokens, concurrency, KV pressure and SLO instead of just CPU. Use warm pool, hysteresis and admission control; The GPU/model loads slowly so it must be provisioned before the load peak.

Link to this question
24What is the role of load balancing in AI serving infrastructure?

The load balancer distributes requests to workers according to health, load, and model/cache characteristics. You can route according to the locality prefix to increase cache hits, but must balance avoiding hotspots and keeping tenant isolation.

Link to this question
25How do you manage GPU memory for serving multiple models?

Calculate weights/KV/workspace for each model, using quotas and memory admission control. Can divide worker pool, offload or unload cold models; Avoid oversubscribing which causes OOM and crashes all requests on the GPU.

Link to this question
26What is model sharding, and when would you use it?

Model sharding divides weights across GPU/machine using tensor, pipeline or expert parallelism. Used when the model/cache does not fit or needs to increase compute; Communication overhead can limit speed.

Link to this question
27How do you implement request queuing and priority scheduling for AI services?

Queue has deadline, priority/fairness by tenant and length limit; token/concurrency management scheduler. Use backpressure and anti-starvation; Separate long batch jobs from interactive requests with short SLOs.

Link to this question
28What are the cost trade-offs between self-hosted and API-based AI inference?

API reduces operating and load fluctuations; Self-hosting can be cheap when utilization is high and data control is needed. Include idle GPUs, spares, staffing, network and equivalent quality, not just listed price/token.

Link to this question
29How do you handle cold start latency for serverless AI deployments?

Keep the pool warm, cache weights on nearby storage and use artifacts/small images, preload predictively. Queue has timeout and fallback; scale-to-zero is economical but must accept or hide model loading latency.

Link to this question
30How do you implement model caching to reduce redundant computations?

Separate the loaded cache weights, prefix/KV cache and response cache according to the type of computation you want to avoid. Cache key contains model/prompt/data version and permissions; eviction/TTL needs to match freshness and memory limits.

Link to this question
31What is the difference between synchronous and asynchronous inference, and when do you use each?

Synchronous wait for result in request, short/interactive collaboration; asynchronous returns job ID and processes via queue, batch/long combination. Need job status, idempotent retry, cancellation and completion notification.

Link to this question
32What is FSDP (Fully Sharded Data Parallel), and how does it differ from DeepSpeed ZeRO?

FSDP shard parameters, gradient and optimizer state, collect parameters when needed. DeepSpeed ​​ZeRO has shard stages that gradually optimizer/gradient/weights; Comparison also depends on offload, wrapping and runtime, not just name.

Link to this question
33What are TTFT, TPOT, and throughput, and how do they trade against each other?

TTFT is the time to the first token; TPOT is the time each token outputs; throughput is the amount of tokens/requests processed over time. Large batches increase throughput but can increase latency and TPOT; need to lock in optimal SLO first.

Link to this question
34How do you monitor and profile LLM inference in production (TTFT, inter-token latency, GPU utilization)?

Record queue/prefill/decode time, TTFT/TPOT by distribution, token length, KV usage, utilization and bandwidth. Use profiler for kernel/communication; High utilization does not mean the request reaches the target latency.

Link to this question
35What is model routing at the infrastructure level, and how do you route requests based on complexity and cost?

The router selects workers/models based on difficulty, budget, capabilities, and cache locality. Use rules/classifier with eval, fallback and load limit; Routing is cheap but incorrect routing can increase retries and overall costs.

Further reading

LLM Routing

Link to this question
View this section in the original repository ↗

Coding and Practical Implementation

32 questions
01Implement a basic RAG pipeline using an embedding model and a vector database.

Implementation direction: parse → chunk with ID/source → embed → upsert index; query → embed → retrieve with ACL → merge context → LLM returns with citation. Test retrieval of correct sources and sentences lacking evidence.

Link to this question
02Build a simple AI agent with tool use (e.g., calculator, web search).

Creating registry tools with schema, model calls, and dispatch tools is allowed after validation. Loop results until final answer or budget runs out; calculator must parse expressions safely, not eval arbitrarily.

Further reading

ReAct Agent

Link to this question
03Implement semantic search using embeddings and cosine similarity.

Encode document/query with the same model, normalize L2 and calculate scores = D @ q then get top-k. With cosine, treat norm as 0; save ID to return original document and check rankings with small data.

Link to this question
04Write code for different text chunking strategies (fixed-size, recursive, semantic).

Fixed-size: slide according to tokens with overlap; recursive: separate headings/paragraphs/sentences before chopping; semantic: divided by semantic changes. Keep metadata and check that no content is lost/no empty chunks are created.

Link to this question
05Implement a prompt template system with variable substitution.

Declare required variables, validate before formatting the template and versioning the template. Separate instructions from user data; Escaping helps correct structure but does not prevent prompt injection on its own.

Link to this question
06Build an evaluation pipeline for LLM outputs using LLM-as-a-judge.

The runner reads the dataset/rubric, generates a candidate, then asks the judge to score with the schema, saves the score and reasons for attaching evidence. Reverse order when comparing pairs, correct for person labels and report by slice/version.

Further reading

LLM as a Judge

Link to this question
07Implement streaming responses for an LLM API.

The backend transfers delta from the model to SSE/WebSocket, transmitting termination and error signals. Client uses parser streaming, supports cancellation/backpressure; Do not consider each network chunk as a token or a complete JSON.

Link to this question
08Build a simple vector similarity search from scratch.

Save the vector matrix, calculate the cosine/dot product for the query and select the top-k using sort or partial selection. This is an exact O(Nd) search, good for small baselines; Check metric/normalization before switching to ANN.

Link to this question
09Implement a conversation memory system for a chatbot (sliding window, summary, buffer).

Keep a buffer of recent passes according to token budget, summarizing old parts and recalling related memory when needed. Save source/time and delete; Test that important information is not missummarized or overwritten.

Further reading

AI Agent Memory

Link to this question
10Write code to detect and handle hallucinations in LLM outputs.

Split output into claim, retrieve evidence and then check entailment/source; The claim is not supported and needs to be removed, edited or marked as uncertain. There is no heuristic function that detects every hallucination; Measure precision/recall on labeled case.

Link to this question
11Implement a retry mechanism with exponential backoff for LLM API calls.

Temporary error retry equals delay = min(cap, base × 2^attempt) plus jitter, respecting retry-after. Time limit/deadline, no retry for permission/validation errors; Operations with side effects require an idempotency key.

Link to this question
12Write a function calling (tool use) handler for an LLM API.

Map the tool name to the callable permissionlist, parse the JSON and validate the schema/permissions before running with timeout. Return structured results/errors to the model; Do not call getattr/eval by name or arbitrary code generated by the model.

Link to this question
13Implement a simple re-ranker for search results.

Retrieve top-N, score each query-document pair with cross-encoder then sort descending and get top-k. Batch to save time, keep ID/source and measure nDCG and latency compared to not reranking.

Link to this question
14Build a basic document parser that extracts text from PDFs and splits it into chunks.

Distinguish between PDF text and scan, use parser/OCR to preserve pages, layout and tables. Divide by structure/token, save page/span and check the sample against the render to detect incorrect reading orders.

Link to this question
15Implement cosine similarity, dot product, and Euclidean distance functions from scratch.

Dot = Σxᵢyᵢ; cosine = dot/(sqrt(Σxᵢ²) × sqrt(Σyᵢ²)); L2 = sqrt(Σ(xᵢ-yᵢ)²). Validate equal dimensions, finite values and nonzero norms for cosine; test identical, opposite and orthogonal vectors.

Link to this question
16Write code to implement token counting and context window management.

Use the correct tokenizer/chat template of the model to count both system, history and tool schema. Budget input = context_limit - output_reserve; trim/retrieve/summary before sending and multilingual character testing.

Link to this question
17Build a simple prompt versioning system.

Save template, model config, schema and eval result in immutable version/hash; deployment points to a specific version. Attach version to trace, review changes and keep rolling back instead of directly editing the serving prompt.

Link to this question
18Implement a caching layer for LLM responses.

Cache key includes input, model/sampling, prompt, tenant/permission and data version. Use TTL/invalidation, size limit and anti-cache stampede; Do not share private feedback between users.

Link to this question
19Implement semantic caching for LLM queries (cache responses for semantically similar queries).

Save query embedding with response and permission/version scope; Only reuse when similarity exceeds the adjusted threshold and the answer's meaning is equivalent. Do not use for time/price questions or sensitive actions without verification.

Link to this question
20Write code to detect prompt injection attempts in user inputs.

Use rules/classifier to flag suspicious instructions and test for obfuscation/indirect injection as well. This is a supporting finding; Still need ACL, allowlist tool and egress control because regex is not guaranteed to block completely.

Link to this question
21Implement an LLM output guardrails system that checks for off-topic responses and PII leakage.

Run schema, topic relevance and PII checks before returning output, combining rules/classifiers with policies. If violated, redact, refuse or escalate; Save safety reasons and false positive/negative measurements.

Link to this question
22Build a multi-agent system where agents have different roles and collaborate on a task.

Divide the actual task into roles with narrow permissions, communicate via message/state schema, and the orchestrator checks the results. Just parallel independent steps, set timeout/budget and test for errors/overwrites between agents.

Further reading

Multi-Agent Systems

Link to this question
23Implement scaled dot-product attention with a causal mask from scratch (NumPy or PyTorch).

Calculate S = QKᵀ/√dₖ, masked_fill future position with -∞ then softmax according to key and multiply V. Check shape, numerical stability and test future tokens do not affect past output.

Link to this question
24Implement multi-head attention, then convert it to grouped-query attention.

MHA reshape Q/K/V according to head, attention separately then concat/project. GQA reduces KV_heads and maps each query group to a KV head; Check shape, mask and condition query_heads is divisible by KV_heads.

Link to this question
25Implement a KV cache and single-step decode for causal multi-head attention.

Cache K/V by layer and position; The new step is append K/V and then attention Q to access all allowed caches. Use absolute position/RoPE correctly; so output cached with full forward in tolerance and memory limit.

Link to this question
26Implement BPE (Byte Pair Encoding) training and encoding from scratch.

Start the base vocabulary, count adjacent pairs, combine the best pair, and save merge ranks iterating to the limit. Encode using learned merges; Test round-trip, Unicode and byte fallback if supported by the design.

Further reading

Byte Pair Encoding

Link to this question
27Implement top-k, top-p, and temperature sampling over a logits vector.

Divide logits by positive temperature, mask top-k or sort/cumulative probability to keep top-p then normalize/sample. Temperature 0 processed with argmax; validate k/p, NaN and always keep at least one token.

Link to this question
28Implement an LRU cache with O(1) get/put, then add per-entry TTL.

Use hashmap to point the node of doubly linked list: get/put brings the node to the beginning, over capacity delete the tail. TTL stores expires_at and clears on access; Expiration cleanup in the correct order requires additional mechanisms, it is not possible to default to all operations being O(1).

Link to this question
29Implement a token-bucket rate limiter for an LLM API where cost scales with tokens, then make it distributed.

Save tokens and last_refill, add min(capacity, tokens + elapsed × rate), subtract by cost if enough. When distributed needs atomic updates like Redis Lua and unified clock; reserve input/output and then check actual costs.

Link to this question
30Write an async batch processor that runs an LLM call over 50,000 documents with a concurrency limit, retries with jitter, and error isolation.

Use queue/async iterator and worker pool with concurrency limit, timeout, retry backoff+jitter according to error type. Checkpoint each ID, save individual errors and idempotent resume; Avoid creating 50,000 concurrent tasks that consume RAM/quota.

Link to this question
31Write a streaming SSE parser for LLM token streams that handles arbitrary chunk boundaries.

Decode UTF-8 incrementally, keep buffer between chunks and concatenate events on empty lines, support LF/CRLF. Merge data lines before parsing the payload, handle comments/[DONE]/EOF and test all chunking positions, including between Unicode characters.

Link to this question
32Implement a minimal agent loop with tool dispatch, error handling, and a step budget.

Minimum loop: check budget → call model → if final then end; If tool then validate/execute → record observation → repeat. Limit retry/steps/time, persist state and return clear error when not completed.

Further reading

AI Agent Loop

Link to this question
View this section in the original repository ↗

Behavioral and Scenario-Based Questions

22 questions
01What is AI Engineering, and how does it differ from Machine Learning Engineering?

AI engineering focuses on turning AI capabilities into products: data, orchestration, evaluation and operations. ML engineering often goes deep into the model/training/serving lifecycle; Boundaries overlap depending on the organization.

Link to this question
02How do you decide whether a problem needs AI or a traditional software solution?

Start request and deterministic baseline. Use AI when input is ambiguous/diverse or pattern learning produces measurable benefits, and errors are acceptable; Choose traditional rules/software when the logic is clear and absolute accuracy is needed.

Link to this question
03How do you measure the ROI of an AI feature?

Measure the revenue increase/time reduction/error reduction benefit compared to the baseline, minus all implementation and operating costs. Use A-B or appropriate measurement design; including reviews, retries and losses due to errors.

Link to this question
04How do you handle hallucinations when they occur in a production AI system?

Reduce impact now, keep trace and identify errors at source/retrieval/model/policy. Fix cause, add eval and limited rollout; Notify affected people when appropriate instead of just fixing silent output.

Link to this question
05How do you decide between using an LLM API vs self-hosting an open-source model?

Compare equivalent quality, data residency/privacy, latency, volume, total cost and operating capacity. API accommodates fluctuating load; self-host is suitable for deep control/high utilization; pre-commit benchmark.

Link to this question
06How do you manage stakeholder expectations for AI projects?

Unify use cases, success criteria and limitations with demo/real cases. Report quality by group with uncertainty, roll out milestones and explain how to handle wrong models.

Link to this question
07Describe your approach to debugging a poor-performing RAG system.

Reproduce query errors, check parser/chunk and measure retrieval recall first. See last context, rerank, prompt and citations; correct stage and add cases to regression instead of unconditionally increasing top-k.

Link to this question
08How do you stay current with the rapidly evolving AI landscape?

Monitor main documents/papers, select changes related to workload and small tests with eval. Document conditions, benefits and limitations; Don't change your stack just because of a new benchmark.

Link to this question
09How do you balance innovation with reliability in AI systems?

Maintain a reliable baseline, test improvements after feature flag with test/risk gate. Only expand when user benefits are measurable and have observability/rollback, without sacrificing required control.

Link to this question
10Tell me about a challenging AI project you worked on. What was the problem? What approach did you take? What trade-offs did you make? What was the outcome?

Answer with real projects according to STAR: context, goals, your decisions, trade-offs, evidenced results and lessons. Do not fabricate data or take credit for someone else's work; State how to measure when exact numbers are not available.

Link to this question
11How would you handle a situation where an AI model produces biased or harmful outputs in production?

Stop/limit the harmful flow, assess the impact and bring the case to the responsible person. Data group investigation, root correction, independent testing, and post-rollout tracking; keep the appeal line.

Link to this question
12How do you approach cost optimization for an AI system that's exceeding budget?

Decompose costs by stage and successful task, identify context/retry/model/traffic causing increase. Try caching, routing and reducing excess tokens via eval; Take into account the cost of moderation and errors before choosing the optimal one.

Link to this question
13Describe a time when you had to choose between model accuracy and latency. How did you make the decision?

Use a real situation: state the SLO, measured options and minimum quality threshold. Explain why the point on the trade-off line was chosen and the results after the rollout; Don't make up experiences if you've only done testing.

Link to this question
14How would you handle a situation where your AI system's quality degrades over time?

Compare versions, input drift, data sources and feedback by group to find the cause. Rollback as needed, add new labels/evals, update pipelines/models, and redeploy with control.

Link to this question
15How do you communicate AI limitations to non-technical stakeholders?

Using a success/failure example, explain the prediction model in terms of sample, with no guarantee of truth. Speaking in terms of business impact, scope of use and route of transfer of people; Avoid covering limits with terminology.

Link to this question
16How would you approach building an AI feature with limited labeled data?

Start with stock models, few-shot or RAG, get specialist labels for critical cases. Use validated active learning/synthetics to scale, keep tests real, and prioritize changes with measurable benefits.

Link to this question
17Describe your experience working with cross-functional teams on AI projects.

Give a real example of product/domain/data/engineering coordination: responsibilities, interfaces, disagreements and how to unify criteria. Present individual contributions and overall results; Do not use sample answers based on past experience.

Link to this question
18Where do you see AI engineering heading in the next 3-5 years?

We can expect increased focus on evaluation, agent/tool reliability, inference optimization, and data management. Here is the forecast; When answering, connect the capacity you are building with organizational needs, avoid making certain long-term trends.

Link to this question
19Why are you interested in this AI engineering role?

Relate the company's problem/product to your real experience and learning goals. State a specific contribution that can be made, instead of just saying you like AI or using general praise.

Link to this question
20Your PM wants to ship an AI feature with a 15% hallucination rate on edge cases. How do you communicate the risk?

Clarify which group the 15% is calculated on, the type of error and the level of impact, then convert it into the expected number of users/incidents. Scope narrowing recommendations, guardrail/human review and rollout criteria; Decisions require responsible people to accept specific risks.

Link to this question
21A non-technical executive asks why your AI feature cannot be 100% accurate. How do you explain LLM limitations?

Explain AI predicts from finite data and encounters new inputs, so it cannot be guaranteed to be correct in every situation. Commitment to quality within the measured scope, error detection and transfer mechanism, no general 100% promise.

Link to this question
22You need to choose between a complex agentic system that scores 15% better on benchmarks, or a simpler RAG pipeline that is easier to maintain. How do you decide?

Check if the 15% increase is absolute or relative and does it translate into KPI/user risk. Compare total cost, tail latency, failure mode and performance; Choose agentic only if the benefits outweigh the added complexity.

Link to this question
View this section in the original repository ↗