0 day streak

INTERVIEW PREP · AI ENGINEER

AI engineer interview questions and process

For software engineers moving into AI engineering (also called LLM engineer, applied AI engineer or GenAI engineer). How the interviews usually run, what each round scores, the skills behind them, and 322+ questions with answers from the AI Engineering track.

New to AI engineering? Start with the free AI Engineering track.Python for AI engineers, how LLMs, RAG and agents work, 14 hands-on labs and 4 capstone projects. →

The rounds, and what each one scores

A typical loop. Companies combine or skip rounds, so check the company's own page when you have one; this is the shape most AI engineer loops follow.

  1. 1

    Recruiter and hiring manager screen

    Why AI engineering, what you have built with LLMs, and whether the role is product engineering (building features on models) or closer to ML research. Expect "walk me through an LLM feature you shipped".

    What is scored

    • A clear 2-minute story of one AI project, with a number you measured
    • Knowing the difference between using models and training them

    Prepare with

  2. 2

    Coding round

    Usually a data structures and algorithms problem at medium level, sometimes a practical Python task instead: parse and aggregate logs, implement a rate limiter or an LRU cache, chunk a document, or compute cosine similarity and top-k with NumPy.

    What is scored

    • Correct, tested code in Python (most AI teams expect Python)
    • Talking through complexity and edge cases
    • Clean, idiomatic Python: comprehensions, dataclasses, type hints

    Prepare with

  3. 3

    LLM and ML fundamentals

    A conversation that checks you understand the tools: tokens and context windows, embeddings, attention at a high level, sampling and temperature, RAG, fine-tuning versus prompting, evals, and classic ML basics such as precision and recall or overfitting.

    What is scored

    • Plain explanations with a concrete example
    • Knowing the trade-offs: cost, latency, quality, privacy
    • Saying "I would measure it" and how

    Prepare with

  4. 4

    AI system design

    Design an LLM product end to end: a RAG chatbot over company documents, a support agent, semantic search, a coding assistant or an LLM gateway. Same shape as a system design round, plus model choice, retrieval, evals, guardrails, cost and latency.

    What is scored

    • Requirements first, including quality targets and a budget
    • Retrieval and prompt design with failure modes
    • How you evaluate it before and after launch
    • Cost per request and latency, with numbers

    Prepare with

  5. 5

    Practical build (pairing or take-home)

    Build a small feature in 60 to 90 minutes, or a take-home over a few days: call a model, add retrieval or a tool, return structured output, and test it. Interviewers watch how you handle a model that does not behave.

    What is scored

    • Working code with tests that do not need the model
    • Handling errors, timeouts and bad model output
    • Reading the output critically instead of trusting it

    Prepare with

  6. 6

    Project deep dive

    One project you built, in depth: the architecture, why you chose each piece, what broke, what you measured and what you would change. Senior candidates are pushed on evals, cost and production incidents.

    What is scored

    • Decisions with reasons and alternatives
    • Numbers: recall, latency, cost, error rate
    • Honest failures and what you learned

    Prepare with

  7. 7

    Behavioral

    The usual themes (ownership, conflict, ambiguity, impact), often with an AI angle: shipping under uncertainty, saying no to a feature that was not safe, or explaining model limits to a stakeholder.

    What is scored

    • STAR stories with your own actions and a result
    • Judgement about risk and users

    Prepare with

The skills behind the rounds

SkillWhy it comes upLearn it
Python, properlyMost AI tooling is Python; interviews and take-homes expect it.Python Part A
Serving and testingFastAPI, async, HTTP clients and tests without a model.Python Part B
How LLMs workTokens, context, embeddings, attention, sampling: needed to reason about cost and failures.LLM foundations
Prompting and structured outputReliable JSON, few-shot examples, prompt injection.Prompting, Lab 3
RAGChunking, vector search, hybrid search, reranking, citations.Labs 5 to 8
Agents and toolsTool calling, agent loops, approvals, MCP.Labs 4, 9 and 11
Evals and observabilityGolden sets, LLM judges you have calibrated, tracing, cost per request.Labs 12 and 13
ShippingDocker, health checks, rate limits, serving open models.Lab 14
ML basicsMetrics, overfitting, a training loop, fine-tuning and LoRA.Python Part C
Java with Spring AIMany enterprise teams build AI features on the JVM.Lab 10

LLM concept questions

Three per topic here; each topic page has all 288 with an animated walkthrough. Try to answer before you open one.

LLM foundations

How large language models work 8 questions

At a high level, how does a large language model generate text?

It takes the text so far as tokens and outputs a probability for every token in its vocabulary. A sampler picks one, it is appended to the input, and the model runs again, repeating until an end token or a length limit.

What are the main training stages of a modern chat model?

Pretraining on trillions of tokens to predict the next token, which builds a base model; instruction tuning on prompt and answer examples so it follows requests; and preference tuning (RLHF, DPO or similar) so it produces the kinds of answers people prefer.

What is the difference between a base model and an instruction-tuned model?

A base model only continues documents, so a question may be followed by more questions. An instruction-tuned model has been trained on request and response pairs, so it answers the request in the style of an assistant.

Tokens and context windows 8 questions

What is a token in an LLM?

A token is a piece of text, often a subword, that the tokenizer maps to an integer id from a fixed vocabulary. The model reads and predicts token ids, not characters or words. In English a token averages about four characters, or three quarters of a word.

How does byte pair encoding work?

Start with text split into bytes or characters, repeatedly find the most frequent adjacent pair in the training corpus and merge it into a new token, and stop when the vocabulary reaches a target size. Common words end up as single tokens; rare words are spelled from a few pieces, and byte-level BPE means no input is ever unknown.

Why do non-English text and code cost more tokens?

Tokenizer vocabularies are learned mostly from English text, so other languages are split into smaller, more numerous pieces, often 1.5 to 3 times as many for the same meaning. Code and JSON spend tokens on whitespace, brackets and quotes.

Embeddings 8 questions

What is an embedding?

A fixed-length vector of numbers produced by a model so that texts with similar meaning are close together in the vector space. It lets software compare meaning with simple math instead of matching keywords.

How is cosine similarity calculated and why use it?

Take the dot product of the two vectors and divide by the product of their lengths. It measures the angle between them, from -1 to 1, ignoring magnitude, which is what matters for comparing meaning. For normalised vectors it equals the dot product.

Why do texts with similar meaning get similar embeddings?

Embedding models are trained contrastively on large sets of related pairs, such as questions and their answers, pulling each pair's vectors together and pushing unrelated texts apart. Closeness in the space becomes a learned proxy for semantic similarity.

Sampling: temperature and top-p 8 questions

How does an LLM turn its output into a chosen token?

The model outputs a logit for every vocabulary token. The sampler optionally divides the logits by a temperature, applies softmax to get probabilities, optionally truncates the tail with top-k or top-p, renormalises, and either takes the top token (greedy) or draws one at random.

What does temperature do, mathematically?

It divides every logit by T before softmax. T below 1 widens the gaps so the top tokens get more probability; T above 1 narrows them so the distribution flattens; T approaching 0 is equivalent to greedy decoding.

What is the difference between top-k and top-p sampling?

Top-k keeps a fixed number of the most likely tokens. Top-p keeps the smallest set whose cumulative probability reaches p, so it keeps few tokens when the model is confident and many when it is unsure. Both renormalise the survivors before drawing.

Attention and transformers 8 questions

What is attention in a transformer, in plain terms?

For each token, the model scores how relevant every earlier token is, turns the scores into weights with softmax, and replaces the token's vector with a weighted mix of those tokens' information. It is how "it" picks up the meaning of "the cat".

What are queries, keys and values?

Three vectors computed from each token by learned weight matrices. The query says what the token is looking for, the key says what a token offers to be matched on, and the value is what it passes on. Scores come from query-key dot products; the output is a weighted sum of values.

Why use multiple attention heads?

One head produces one set of weights, so it can only focus on one kind of relationship at a time. Many heads with their own weights can track different things in parallel, such as coreference, the previous word or syntax, and their outputs are combined.

Choosing a model 8 questions

How would you choose an LLM for a new feature?

Filter candidates on hard requirements (context window, modalities, tool use, structured output, data rules), shortlist a few models of different sizes, run them on an eval set built from real cases, and pick the cheapest one that clears the quality and latency bar.

What is the quality, cost and latency trade-off?

Larger models usually answer better but cost more per token and respond more slowly; smaller models are cheaper and faster but fail more on hard tasks. You choose the point on that triangle the task needs, not the strongest model available.

What is the difference between time to first token and tokens per second?

Time to first token is the delay before any output appears and grows with prompt length; tokens per second is the generation speed after that. Total time is roughly TTFT plus output tokens divided by speed, and with streaming the user mostly feels TTFT.

Prompting and structured output

Prompt engineering basics 8 questions

What are the main parts of a good prompt?

A role and goal, the context the model needs, one clearly stated task, constraints such as length and what to do when unsure, an exact output format, and optionally a few examples. Simple questions need only some of these; production prompts usually need all.

What is the difference between the system prompt and the user message?

The system prompt is written by the developer and stays the same across calls: role, rules, format, tone. The user message carries the request of the moment. Models weight system instructions more heavily, but that is not a security boundary.

Why wrap documents in tags or delimiters?

So the model can tell instructions apart from data, and so you can refer to each document by name. It reduces confusion with long or multiple documents and makes injected instructions easier to spot, though it is not a complete defence.

Few-shot prompting and reasoning 8 questions

What is the difference between zero-shot and few-shot prompting?

Zero-shot gives only instructions and the input. Few-shot also includes a handful of input and output examples, which shows the model the exact format, the allowed labels and how to handle borderline cases.

Does few-shot prompting train the model?

No. It is in-context learning: the examples are tokens in the prompt and no weights change. The effect lasts only for that call, and the examples cost tokens every time they are sent.

How do you choose few-shot examples?

Cover every label in a roughly balanced way, vary length and wording, use real production inputs, spend examples on the boundary cases you get wrong, keep the format identical, and never reuse eval cases as examples.

Structured output 8 questions

What is the difference between JSON mode and schema-enforced structured output?

JSON mode guarantees the reply parses as JSON but not which keys or types it has. Schema-enforced output takes a JSON Schema and guarantees the reply matches it, with required fields, types and enums all respected.

How does constrained decoding work?

The schema is compiled into a grammar or state machine. At each generation step the model scores all tokens as usual, then every token that would make the output invalid is masked to zero probability and the rest are renormalised before sampling, so the result always fits the grammar.

If the output matches the schema, can you trust it?

No. The schema guarantees shape, not truth. Validate values in code: ranges, dates, cross-field rules such as line items plus tax equal the total, and lookups such as the vendor existing. Reject or retry when a rule fails.

Prompt caching 8 questions

What is prompt caching?

The provider saves the attention state (KV cache) computed for the start of a prompt. When a later request begins with exactly the same tokens, it reuses that state and only processes the new tokens, so the call is cheaper and the first token arrives sooner.

Does prompt caching change the model's output?

No. The keys and values for a prefix depend only on the tokens in it, so reusing them gives the same result as recomputing them. The model still generates a fresh answer on every call.

How should you order a prompt to get good cache hits?

Stable content first: tool definitions, system prompt, examples and reference documents, then conversation history, then the new user message. Anything that varies per request, such as timestamps or ids, goes at the end.

Prompt injection 8 questions

What is prompt injection?

An attack where text the model processes contains instructions that override the developer's intended behaviour. It works because instructions and data reach the model in the same token stream, with no hard boundary between them.

What is the difference between direct and indirect prompt injection?

In direct injection the user types the malicious instructions themselves. In indirect injection the attacker plants them in content the model reads later, such as a web page, email, document or tool result, so the attack runs with an innocent user's permissions.

How is a jailbreak different from prompt injection?

A jailbreak tries to bypass the model's own safety training to get content it would normally refuse. Prompt injection tries to override the application's instructions to make it take unintended actions. They often use similar tricks and overlap in practice.

Agents

What is an AI agent 8 questions

What is the difference between a chatbot and an AI agent?

A chatbot maps a message to a reply in one model call. An agent runs the model in a loop where it can call tools, observe the results and decide the next step, so it can act on outside systems and finish multi-step tasks.

What are the core components of an agent?

A language model that decides the next action, tools that the runtime executes on its behalf, memory (the current transcript plus any long-term store), and a control loop with a stopping rule. Guardrails and logging wrap all of it.

When would you choose a fixed workflow over an agent?

When the steps are known in advance, when latency or cost must be tightly bounded, or when every step must run in an audited order. A workflow is cheaper, faster and easier to test; add model-driven decisions only where the path truly varies.

Tool calling 9 questions

How does tool calling work with a language model?

You send tool definitions (name, description, JSON schema for inputs) with the messages. The model may reply with a structured request naming a tool and arguments. Your code runs the function and returns the output as a tool result tagged with the same id, and the model continues.

Does the model execute the tool itself?

No. The model only produces the request. The application parses it, validates the arguments and permissions, runs the real function and decides what to send back. That gap is where you enforce safety.

Why does the tool description matter so much?

The model chooses tools and fills arguments by reading the descriptions. A vague description leads to wrong tool choices and bad arguments; a precise one that says when to use the tool, the input format and what it returns fixes most tool-use errors.

The agent loop 8 questions

What is the ReAct pattern?

Reason and act: the model alternates between reasoning about what to do, taking an action through a tool call, and observing the result, which is appended to the context before the next round. It lets each observation shape the next decision.

How do you decide when an agent loop should stop?

Stop on a final answer, ideally confirmed by an automatic check, and also on hard limits for steps, time and cost, on detected lack of progress, or when the model needs input from a person. Always return the reason it stopped.

Why does the cost of an agent run grow faster than the number of steps?

The model is stateless, so each turn resends the whole history, which grows every turn. Total tokens grow roughly with the square of the step count unless you trim results, clear old ones, summarise and use prompt caching.

Agent memory 8 questions

Do language models remember previous conversations?

No. Each API call is stateless; the model only sees what is in that request. Any memory is built by the application, which resends the conversation and injects stored facts into the prompt.

What is the difference between short-term and long-term memory in an agent?

Short-term memory is the current conversation held in the context window and resent on every call. Long-term memory is stored outside the model, survives across sessions, and is retrieved and injected into the prompt when relevant.

How do you handle a conversation that no longer fits the context window?

Drop or trim the oldest turns (a sliding window), shrink large tool results, and replace old turns with a running summary once history passes a threshold such as 80 percent of the budget. Never drop the system prompt, and keep each tool call with its result.

Model Context Protocol (MCP) 9 questions

What problem does MCP solve?

The N times M integration problem: without a standard, every AI app writes custom glue for every tool. With MCP each app implements a client once and each tool provider writes a server once, so the work grows as N plus M.

What are the host, client and server in MCP?

The host is the AI application the user interacts with; it owns the model, UI and security policy. It runs one client per server connection, and each server is a program exposing one system's tools, resources and prompts.

What is the difference between tools, resources and prompts?

Tools are actions the model chooses to call. Resources are read-only data addressed by URI that the application chooses to include as context. Prompts are reusable templates the user selects, often as slash commands.

Retrieval-augmented generation (RAG) 9 questions

What is retrieval-augmented generation?

A pattern where the system first retrieves passages relevant to the question from your own data, adds them to the prompt, and asks the model to answer only from them, usually with citations. It grounds answers in current, private knowledge without retraining.

How do you choose a chunk size?

Aim for one idea per chunk, often a few hundred tokens with a little overlap, split on headings and sections first. Large chunks produce blurry embeddings; tiny ones lack context. Tune it by measuring retrieval recall on real questions.

What is an embedding and why does it enable semantic search?

An embedding is a vector produced by a model so that texts with similar meaning are close together. Searching for nearest vectors finds passages that match the meaning of the question even when they share no words.

Multi-agent systems 9 questions

What is a multi-agent system?

Several agent loops, each with its own prompt, tools and context window, that cooperate on one task by passing results to each other. Common shapes are an orchestrator with workers, a fixed pipeline, handoffs between specialists, and critic or judge loops.

When would you split a task across several agents?

When you can measure a reason: one context grows so large that quality drops, one prompt holds conflicting instructions or too many tools, or subtasks are independent and running them in parallel cuts latency. Otherwise a single agent is cheaper, simpler and easier to debug.

What are the downsides of multi-agent designs?

Token cost multiplies because each agent pays for its own prompt, tools and exploration; every hop is another failure point, so reliability compounds downward; and coordination adds overhead such as misread briefs, duplicated work and conflicting results. Debugging also needs cross-agent tracing.

Browser and computer-use agents 8 questions

What is a browser or computer-use agent?

An agent whose tools are user-interface actions: open a page, click, type, scroll, observe. It runs the usual agent loop but acts through the screen, which lets it use websites and desktop apps that have no API.

Accessibility tree or screenshots: how do you choose?

The accessibility tree gives exact element targets in few tokens and is the default for web pages. Screenshots with coordinate clicks work on anything visible, such as canvas apps, PDFs and desktop programs, but cost more tokens and can misclick. Many agents combine them, for example with set-of-marks labels on a screenshot.

Describe the perceive, decide, act loop.

Perceive: capture the page as a tree, screenshot or both. Decide: the model picks one action from the goal, recent history and the view. Act: the runtime performs it, waits for the page to settle, then perceives again to confirm the effect. Cap the steps.

Guardrails and evals 8 questions

What are guardrails in an LLM application?

Checks around the model that limit what goes in, what it can do and what comes out: input validation and masking, scope and injection classifiers, least-privilege tool policies, output schema and leak checks, and human approval for risky actions.

What is prompt injection and how do you defend against it?

It is when instructions hidden in user input or in content the agent reads take over its behaviour. Defend in layers: least-privilege tools, scoped credentials, approval on writes, output checks, and never giving one agent untrusted input, private data and outbound reach together.

Why are evals necessary for LLM systems?

Outputs are non-deterministic and a change that fixes one case can break others. A fixed eval set scored on every change replaces impressions with comparable numbers and catches regressions before release.

Retrieval and RAG in depth

Chunking documents 8 questions

Why do RAG systems split documents into chunks before embedding?

An embedding model produces one vector per input, so a whole document becomes a blurry average that matches no specific question well. Embedding models also cap input length, and the LLM prompt has a budget, so you want to retrieve and send focused passages rather than entire files.

How many chunks does a 2,000-token document produce with 512-token chunks and 64 tokens of overlap?

The stride is 512 minus 64, which is 448. Chunks start at 0, 448, 896, 1344 and 1792, so there are five, the last holding 208 tokens. In general it is ceil((N minus overlap) / stride), and here about 13 percent extra tokens get embedded.

What is recursive character or text splitting?

It splits on the largest natural separator first (headings, then paragraphs, lines, sentences, words) and recurses with smaller separators only for pieces still over the size limit, then merges small neighbours. It respects document structure and rarely cuts mid-sentence.

Vector databases and HNSW 8 questions

What does a vector database store and what query does it answer?

Records of an id, an embedding vector, metadata for filtering and usually the source text. Its core query is: given a query vector and an optional filter, return the k records whose vectors are nearest by cosine, dot product or Euclidean distance.

Why not just compare the query with every vector?

Exact search costs O(n·d) per query. For 1M vectors of 1024 dimensions that is about a billion multiply-adds and 4 GB read per query, hundreds of milliseconds. It is fine below roughly 100k vectors or on small filtered subsets, but not at millions with real traffic.

How does HNSW search work?

HNSW is a stack of proximity graphs: the bottom layer holds every vector and each higher layer a random ~1/M subset. A query starts at an entry point on the top layer, greedily hops to closer neighbours, drops a layer when none is closer, and on the bottom layer runs a beam search of width efsearch to return the top k.

Hybrid search and reranking 8 questions

Why is pure vector search not enough for RAG?

Embeddings capture meaning, not exact strings, so error codes, ids, part numbers, version strings and rare names get blurred together. Keyword search matches them exactly, which is why production systems usually add a BM25 index alongside the vector index.

How does BM25 score a document?

It sums, over the query terms, a rarity weight (inverse document frequency) times a saturating term-frequency factor, discounted for long documents. Repeated terms help with diminishing returns, rare terms count far more than common ones, and short documents are favoured.

What is reciprocal rank fusion and why use it?

RRF merges ranked lists by giving each document the sum of 1 / (k + rank) over the lists it appears in, with k usually 60. It ignores raw scores, so it works even though BM25 and cosine scores live on different scales, and it needs no tuning.

Advanced RAG 8 questions

What is query rewriting in RAG and when do you need it?

A small model turns the user message, plus recent chat history, into a standalone search query, for example "and per seat?" into "Pro plan price per seat". You need it in any conversational product, and the rewrite must preserve ids, names and dates exactly.

What is multi-query retrieval?

The model generates several phrasings of the question, each is searched (in parallel), and the result lists are merged with reciprocal rank fusion and reranked. It raises recall on vague questions for the cost of one extra model call.

What is HyDE?

Hypothetical document embeddings: the model writes a plausible answer without sources, you embed that draft and search with it, because answer-shaped text sits closer to real answers than the question does. The draft is discarded; it costs a generation and can mislead on private topics.

Evaluating RAG 9 questions

Why evaluate retrieval and generation separately in a RAG system?

They fail for different reasons and have different fixes. Retrieval metrics on labelled passage ids tell you whether the answer ever reached the prompt; generation metrics on fixed chunks tell you whether the model used it well. One end-to-end score cannot say which half broke.

Define recall at k, precision at k and MRR.

Recall at k is the share of gold passages found in the top k. Precision at k is the share of the top k that are gold. MRR is the mean over queries of one divided by the rank of the first gold result, counting zero when none is found.

Which retrieval metric matters most for RAG, and why?

Recall at the k you send to the model, because a passage that is not retrieved can never be used. Also track recall before a reranker, and use precision or MRR to manage noise, cost and ordering.

Fine-tuning and adaptation

Prompt, RAG or fine-tune? 8 questions

How do you decide between prompting, RAG and fine-tuning?

Ask what the model is missing. Start with prompting to set a baseline; add RAG when it lacks knowledge such as private or changing facts; fine-tune when it lacks a behaviour, format or narrow skill that instructions cannot reliably produce, or to make a small model do one task cheaply.

Can fine-tuning teach a model new facts?

Not reliably. Facts seen a few times are learned weakly, can blend into confident errors, cannot be cited, go stale and are hard to remove. Put facts in the context with retrieval and use fine-tuning for behaviour.

When is RAG the right choice?

When answers depend on information the model was not trained on or that changes: internal documents, prices, policies, tickets. It also gives citations, per-user access control and updates by re-indexing instead of retraining.

Fine-tuning and LoRA 9 questions

What is supervised fine-tuning?

Continuing to train a pretrained model on input and ideal-output pairs, with next-token cross-entropy loss usually computed only on the output tokens. It is best for teaching a format, style or narrow task, not for adding facts.

How much data do you need to fine-tune an LLM?

Usually hundreds to a few thousand high-quality examples. Consistency, coverage of real inputs and correct labels matter far more than volume, because the model learns the noise along with the signal.

How do you detect overfitting during fine-tuning?

Hold out a validation set and track its loss alongside training loss. When training loss keeps falling but validation loss starts rising, the model is memorising; keep the best checkpoint and reduce epochs or learning rate, or add data.

Distillation 8 questions

What is model distillation?

Training a small student model to imitate a larger teacher model on a task, using the teacher's outputs or probabilities as training targets. You then serve the student, which is much cheaper and faster.

Where should the prompts for a distillation set come from?

From real production traffic, deduplicated and stripped of personal data, plus deliberately added rare cases. The student only learns the distribution it trains on, so invented prompts leave gaps. Hold out a test set before training.

How do you stop the student learning the teacher's mistakes?

Filter the teacher's outputs before training: cheap programmatic checks such as schema validity, allowed labels, compiling code or agreement with trusted labels, then an LLM judge with a rubric. Sampling several teacher answers and keeping the best also helps.

RLHF and DPO 8 questions

Why is a pretrained language model not automatically a good assistant?

Pretraining only teaches it to predict likely internet text, which can be another question, a confident error or something harmful. Helpfulness, honesty and safety need an extra training signal: demonstrations (SFT) and preferences (RLHF or DPO).

What are the three steps of RLHF?

First, supervised fine-tuning on demonstrations. Second, train a reward model on preference pairs so the chosen answer scores higher than the rejected one. Third, use reinforcement learning (classically PPO) to make high-scoring answers more likely, with a KL penalty that keeps the policy close to the frozen SFT reference.

Why does RLHF include a KL penalty?

Without it the policy drifts wherever the reward model gives high scores, including odd text that exploits its flaws, and loses general ability. Penalising divergence from the reference model keeps outputs fluent and limits reward hacking.

LLMs in production

LLM evals in practice 9 questions

How do you build an eval set for an LLM feature?

Sample real traffic, tickets, escalations and thumbs-down cases, add expert edge cases and a few attacks, and stratify to match the real category mix while oversampling rare, risky cases. For each case write what must and must not happen before looking at outputs, and add every production failure as a new case.

What order should you prefer graders in?

Code checks first (exact match, schema, tool and arguments, length), because they are deterministic and free. Then a rubric-based model judge for qualities code cannot see. Human review for gold labels, judge calibration and ambiguous or high-stakes cases.

How do you make an LLM judge reliable?

One narrow criterion per call, a binary pass or fail verdict, the policy and a reference answer in the prompt, brief reasoning before the verdict, and a pinned judge model version. Measure agreement against human labels, especially on failures, before trusting it.

Tracing and observability 8 questions

Why are logs alone not enough for an LLM application?

LLM apps fail quietly: a wrong answer still returns 200, and one request spans retrieval, several model calls and tool calls. You need those steps tied together under one id, with the exact inputs, outputs, tokens and timings of each, which is what a trace gives you.

What is the difference between a trace and a span?

A trace is one end-to-end request, identified by a trace id. A span is one timed step inside it, with a name, start, duration, parent span and attributes. Parent links let you rebuild the request as a tree or a timeline.

What would you record on a model-call span?

Model and version, sampling settings, prompt template version, the rendered input and the output, input and output token counts, latency and time to first token, computed cost, and the finish reason. Tool spans add arguments, results and errors; retrieval spans add the query and returned chunk ids and scores.

Cost and latency 8 questions

What drives the cost of an LLM feature?

Input tokens, output tokens and the number of calls. The whole context is resent on every call, output tokens cost roughly 3-5x more than input, and agents, chains and retries multiply the number of calls, so long-prompt apps are often dominated by input cost.

What makes an LLM response slow?

Time to first token (which grows with prompt length and queueing), plus output length divided by generation speed, summed over every call that must wait for the previous one, plus tool and network time. Long answers and sequential chains are the usual culprits.

How would you cut the monthly bill of an LLM feature?

Measure cost per feature first, then trim the prompt, cache the stable prefix, cap output length, route easy requests to a smaller model, cache repeat answers and move offline work to a batch API. Re-run evals after each change so quality does not silently drop.

Serving and inference 8 questions

What is the difference between prefill and decode?

Prefill processes the whole prompt in one parallel pass and is compute bound; it determines time to first token. Decode generates one token per forward pass and is memory-bandwidth bound, because every step rereads all the weights; it determines tokens per second.

What is the KV cache and why does it matter?

It stores the key and value vectors of every past token in every layer so they are not recomputed at each decode step. It saves a lot of compute but grows linearly with context length and batch size, and is often what limits how many users a GPU can serve.

Estimate the KV cache for a 7B model with 32 layers and width 4,096.

Per token: 2 (key and value) × 32 layers × 4,096 × 2 bytes ≈ 0.5 MB at 16-bit. An 8,000-token conversation needs about 4 GB; grouped-query attention with 8 KV heads instead of 32 cuts that about four times.

Safety and red-teaming 9 questions

What kinds of harm should you consider for an LLM feature?

Harmful content, false or invented content, data leaks (other users, the system prompt, secrets), unsafe actions through tools, biased behaviour across groups, and off-brand or off-topic replies. Rank them by severity and likelihood, and treat any critical one as release-blocking.

What makes a good safety policy for an LLM product?

It is specific and testable: what the feature allows, refuses, redirects to a person, and must never do. It also states what must still be answered, because over-refusal is a product failure, and it becomes the grading rubric for red-teaming.

Why layer defences instead of relying on a good system prompt?

Every layer misses some attacks, and misses multiply when layers fail for different reasons. A prompt can be talked round, so pair it with classifiers, human review and especially hard limits in code, like tools scoped to the session user, that hold whatever the model believes.

Privacy and compliance 8 questions

What data does a model provider see, and what might it keep?

Everything in the request: the user message, system prompt, retrieved documents, tool results and files. Depending on the terms it may retain inputs and outputs for a period (often around 30 days for abuse monitoring), and consumer products may train on them; business APIs usually do not, and zero-retention options exist by agreement.

How would you remove personal data from prompts?

First send only the fields the task needs. Then detect personal data with regex for structured values (emails, phones, cards) plus an entity recogniser for names and addresses, replace each with a consistent placeholder like [NAME1], keep the mapping in your app for that call, and restore the real values in the reply.

How do you stop one user seeing another user's data in a RAG system?

Tag every chunk with tenant, owner and allowed groups and filter inside the vector search using the identity from the authenticated session. Never rely on prompt instructions for access control, and use per-tenant namespaces when isolation must be strong.

Machine learning basics

The ML questions AI engineer interviews still ask, from Python Part C. Each lesson has code you run in the browser.

What is the difference between a parameter and a hyperparameter?

Parameters are the numbers training learns, such as the weights and bias of a model. Hyperparameters are the settings you choose before training, such as the learning rate, the number of steps, or the model type, and you choose them by comparing scores on the validation set.

From How machine learning works

Explain gradient descent.

Start with any parameters, compute the loss on the training data, compute the gradient (how the loss changes with each parameter), move every parameter a small step in the opposite direction, scaled by the learning rate, and repeat until the loss stops falling. Neural networks train the same way, with the gradients computed by backpropagation.

From How machine learning works

What is the difference between an estimator and a transformer in scikit-learn?

An estimator is anything with fit. A predictor (a model) also has predict (and usually score), and a transformer has transform to turn data into new data, such as StandardScaler or TfidfVectorizer. A Pipeline chains transformers and a final model into one estimator, so fit and predict run every step in order.

From Classic models with scikit-learn

Why do you scale features, and which models need it?

Models based on distances or on weight penalties (k-NN, SVMs, regularised linear and logistic regression, neural networks) are dominated by the features with the biggest numbers. StandardScaler gives every column mean 0 and standard deviation 1. Tree-based models (decision trees, random forests, gradient boosting) split on one feature at a time and do not need it. Fit the scaler on the training data only.

From Classic models with scikit-learn

Why is accuracy a bad metric for imbalanced data?

When one class dominates, a model that always predicts it gets a high accuracy while never finding the rare class. With 2% attacks, "always safe" scores 98%. Use precision, recall and F1 for the rare class, PR AUC, and always compare with the majority-class baseline.

From Metrics: precision, recall, F1 and AUC

Explain precision and recall, and when you would favour each.

Precision is TP / (TP + FP): of what the model flagged, how much was right. Recall is TP / (TP + FN): of the real positives, how many it found. Favour recall when misses are costly (safety guardrails, fraud, retrieval for RAG) and precision when false alarms are costly (auto-blocking users, automatic actions). Moving the threshold trades one for the other.

From Metrics: precision, recall, F1 and AUC

What is the difference between underfitting and overfitting, and how do you spot each?

Underfitting: the model is too simple, so both training and validation error are high. Overfitting: the model memorises the training data, noise included, so training error is low but validation error is much higher. Compare the two scores side by side; the size of the gap is the signal.

From Overfitting and data leakage

Explain the bias-variance trade-off.

Bias is error from a model that is too simple: it is wrong in the same way whatever data it sees. Variance is error from a model that is too flexible: its predictions change a lot with small changes in the training data. Making a model more flexible lowers bias and raises variance. You pick the complexity (and regularization strength) where validation error is lowest. More data lowers variance but not bias.

From Overfitting and data leakage

What is the difference between a PyTorch tensor and a NumPy array?

Both are n-dimensional arrays with a shape and a dtype, and they share indexing and broadcasting rules. A tensor can also live on a GPU (cuda, mps) and can record operations for autograd. PyTorch defaults to float32 where NumPy uses float64, and torch.fromnumpy / .numpy() convert between them without copying.

From PyTorch basics

How does autograd work?

Tensors with requiresgrad=True record every operation applied to them in a graph. Calling backward() on a scalar loss walks the graph in reverse, applying the chain rule, and stores d(loss)/d(tensor) in each leaf tensor's .grad. Gradients accumulate, so they are zeroed before each step.

From PyTorch basics

Walk me through a PyTorch training loop.

For each epoch, put the model in train mode and loop over batches from a DataLoader. For each batch: optimizer.zerograd() to clear old gradients, a forward pass to get logits, the loss (for example CrossEntropyLoss(logits, labels)), loss.backward() to compute a gradient for every parameter, and optimizer.step() to update them. After each epoch, evaluate on a validation set under model.eval() and torch.nograd().

From Your first neural network

Why do neural networks need activation functions?

A stack of linear layers is still one linear function, so it can only draw straight decision boundaries. A non-linear activation such as ReLU between layers lets the network represent curved boundaries and, with enough units, approximate almost any function.

From Your first neural network

Write scaled dot-product attention and explain each step.

softmax(Q Kᵀ / √d) V. Each token has a query, key and value (learned projections of its embedding). Q Kᵀ scores every query against every key, dividing by √d keeps the scores from growing with the width, softmax along each row turns scores into weights that sum to 1, and multiplying by V gives each token a weighted average of the value vectors.

From Embeddings and attention in code

Why divide by the square root of d?

The dot product of two random vectors of width d has a spread of about √d. Without scaling, large widths push scores so far apart that softmax becomes almost one-hot, so the gradients for all other tokens are near zero and training slows or stalls. Dividing by √d keeps the variance around 1.

From Embeddings and attention in code

What do AutoTokenizer and AutoModel do?

They are factories. frompretrained(name) reads the model's config from the Hub (or the local cache) and builds the right tokenizer or model class with its trained weights, so the same code works for BERT, Llama or any other architecture. Task variants such as AutoModelForCausalLM add the right output head.

From Pretrained models and fine-tuning

How do you get one embedding for a sentence from a transformer encoder?

Run the tokenized batch through the model to get one vector per token, then pool them, usually a mean over the positions where the attention mask is 1, and normalize to length 1 so cosine similarity is a dot product. The model card says which pooling the model was trained with.

From Pretrained models and fine-tuning

Practical questions: explain what you built

The questions a practical round or a project deep dive asks, one per lab and capstone, with an answer you can say out loud after building it.

Walk me through what happens when your app calls an LLM API.

My server sends one HTTPS POST to the chat completions endpoint with the model name and the message list: a system message with the rules, then the user turn. The provider tokenizes it, runs the model and returns JSON with the answer and the token usage. I wrap it in one function with a timeout, a couple of retries for 429 and 5xx, and I log the usage so I can attribute cost. Settings come from the environment, so the same code runs against a local model in development and a hosted one in production.

Build it: Your first LLM call: raw HTTP, the SDK, and Spring AI

How would you stream LLM responses to a web client, and what can go wrong?

I call the model with streaming on and relay each delta to the client over Server-Sent Events from my own server, so the key never reaches the browser. SSE fits because the answer flows one way and it is plain HTTP, so proxies and auth just work; I encode each token as JSON so spaces and newlines survive. The client reads the body with fetch and a stream reader, since it needs a POST. Three things need care. Cancellation: when the client disconnects I cancel the upstream call, otherwise I keep paying for tokens. Errors after the 200 is sent: I send a typed error event and keep the partial answer. And buffering: proxies and compression can hold the stream back, so I turn buffering off for that route and send keep-alive comments if the first token can be slow. I test it with a fake streamer injected into the endpoint, including one that fails halfway.

Build it: Build a streaming chat: SDK streaming, FastAPI and Server-Sent Events

How do you get reliable structured data out of an LLM?

I define the target as a typed model (Pydantic in Python, a record in Java) and generate a JSON Schema from it, so there is one source of truth. I send the schema with the request (responseformat jsonschema, or format on Ollama), which uses constrained decoding so the reply is JSON in the right shape. I still validate every reply, because not every rule is enforced and replies can be cut off. On a validation error I retry at most twice, sending the exact errors back as feedback. After that, business rules check what a schema cannot, like totals adding up, and failures go to a human review queue rather than being retried. The parsing and retry logic is unit tested with a fake client; extraction quality is measured separately with an eval set.

Build it: LLM structured output in Python: JSON Schema, Pydantic validation and retries

How does LLM tool calling work under the hood, and what can go wrong?

The model never executes anything. I send a list of tools with the request: a name, a description and a JSON Schema for the arguments, which I generate from typed functions. When the model wants a tool, it replies with tool calls instead of text: an id, the tool name and the arguments as a JSON string. My code validates the arguments, runs the function, and appends the assistant message plus one tool message per call with the matching tool call id, then sends the whole conversation again. That repeats until the model answers in text, with a cap on the number of rounds. What goes wrong: invalid or invented arguments, unknown tool names, tools that fail, endless loops, and prompt injection through tool results. So every call is validated, errors go back to the model as tool results so it can correct itself, side effects need confirmation, and every call is logged and limited.

Build it: LLM tool calling from scratch in Python: schemas, the agent loop and errors

How does semantic search work, and how do you know it is any good?

An embedding model turns each document into a fixed-length vector, trained so that texts with similar meaning point in similar directions. I embed the documents once, in batches, with a content-hash cache so unchanged documents are never re-embedded, and store the vectors with the model name. At query time I embed the query with the same model (with the query instruction the model expects, like searchquery: for nomic-embed-text), score every document by cosine similarity, which is a plain dot product when the vectors are normalized, and return the top k. Brute force is fine up to large collections; beyond that, or with filters, I use an approximate index like HNSW in pgvector. To know it is good I keep a test set of real queries with the expected document and track recall@k, and I read the misses. I compare against keyword search, because exact terms like codes and names are where embeddings are weak, and that usually leads to hybrid search.

Build it: Semantic search from scratch in Python: embeddings, cosine similarity and recall@k

Walk me through how you would build RAG over company documents, and how you keep it from making things up.

Ingest offline: load the documents, chunk them along their structure (headings) at a few hundred tokens with a little overlap, keep metadata like source and section, embed each chunk with the heading in front, and store vectors and metadata together; I would start with Postgres and pgvector with an HNSW index on cosine distance, behind a small vector store interface. At query time I embed the question with the same model, take the top k by cosine similarity, and drop anything under a calibrated threshold; if nothing is left I refuse without calling the model. Otherwise the prompt has strict rules, answer only from the numbered sources, cite them, and use a fixed sentence when the answer is missing, with the sources in the user message as data. I parse the citations and flag answers that cite nothing. Then I measure: unit tests with fakes for the logic, and an evaluation set of real questions for retrieval recall and answer faithfulness, run on every change.

Build it: RAG from scratch in Python: chunking, embeddings, pgvector and answers with citations

Users say search misses exact error codes but works for normal questions. How do you improve retrieval, and how do you know it worked?

Embeddings capture meaning, so they are weak on exact strings like error codes, part numbers and rare names, while keyword search like BM25 is precise on those but blind to paraphrases. So I run both, take the top 20 or so from each, and merge them with Reciprocal Rank Fusion: each list contributes 1 over 60 plus the rank, which needs no score normalisation and rewards documents both searches agree on. Then I rerank the merged candidates with a cross-encoder, which reads the query and each candidate together and orders them far better, at the cost of one small model run per candidate, so I rerank only a few dozen and fall back to the fused order if it is slow. To know it worked, I build a labelled query set from real searches, especially the failing ones, and compare recall at k, MRR and p50 or p95 latency for keyword, vector, hybrid and hybrid plus rerank, then choose the candidate count where recall stops improving.

Build it: Hybrid search and reranking in Python: BM25, vectors, Reciprocal Rank Fusion and a cross-encoder

Would you use LangChain for a RAG feature? What does it give you, and what do you watch out for?

I would use it for the plumbing and keep the rules in my own code. It gives me one interface per job: chat models and embeddings I can swap through configuration, loaders and splitters for many formats, vector stores behind one API, and LCEL chains that stream, batch and trace without extra code. What I watch: defaults made for OpenAI (the embeddings class sends token ids, which other servers reject), what a score means in each vector store (similarity in one, distance in another), embedding-model details like task prefixes, and version churn, so I pin versions and test before upgrading. The minimum-score refusal and the citation check stay plain functions with unit tests, run inside the chain, and I compare retrieval against a simple from-scratch baseline or an evaluation set to make sure the framework is doing what I think.

Build it: RAG with LangChain in Python: loaders, splitters, vector stores, LCEL chains and streaming

How would you build an agent that can issue refunds, and keep it safe?

I would model it as a graph: a state holding the messages, a model node that calls the LLM with the tools bound, a tool node that runs the requested tools and appends their results, and a conditional edge that loops back to the model until it answers. The tools are typed functions; the refund policy is plain code that the refund tool re-checks itself, so the model cannot skip it. The refund tool pauses the graph with an interrupt before any money moves; the state is saved by a checkpointer, a person sees the order, amount and reason, and the graph resumes with their decision. I cap the steps with a recursion limit, keep side effects after the approval and idempotent, use a database checkpointer with a thread id per conversation, and log every step. Unit tests use a scripted fake model; whether the model picks the right tools is measured separately with evals.

Build it: Build an AI agent with LangGraph in Python: state, tools, memory and human approval

How would you add an LLM feature with RAG to an existing Spring Boot service?

I would add Spring AI with one model starter, so the chat model, embedding model and a ChatClient.Builder come from configuration, and the provider can change by properties. Endpoints use ChatClient: .call() for normal answers, .stream() returning a Flux as Server-Sent Events for chat UIs, and .entity() with a record when I need typed data, plus validation and a retry. For RAG I ingest documents in a separate job: split them, embed them and store them in a VectorStore such as PGVector; at request time a QuestionAnswerAdvisor retrieves the top matches and adds them to the prompt with an instruction to answer only from them. Chat memory is an advisor keyed by a conversation id from the user's session. Tools are @Tool methods with tight descriptions and validated arguments. I test the wiring with @SpringBootTest against a fake OpenAI-compatible server, measure quality with an eval set, and watch token usage and latency through Micrometer.

Build it: Spring AI tutorial: chat, streaming, structured output, tools, RAG and memory in one Spring Boot app

What is MCP, and how would you build and secure an MCP server?

MCP, the Model Context Protocol, is a standard way for AI apps (hosts) to connect to external capabilities. A server exposes tools, which the model decides to call, resources, which the application loads as context, and prompts, which the user picks. Messages are JSON-RPC over stdio for local servers or Streamable HTTP for remote ones. In Python I use the official SDK: a function with type hints and a docstring becomes a tool, and the SDK generates the JSON Schema and validates every call before my code runs. For security I treat every argument as untrusted: allow-list validation (for example note names that cannot contain path separators), size limits, narrow tools scoped to one folder or API, no shell, separate read and write tools, and errors the model can read via ToolError without leaking internals. Over HTTP I add authentication, TLS and the host allow-list. I test in memory with the SDK client, plus one stdio test, and connect it to an agent by mapping each MCP tool to the chat API's tool format.

Build it: Build an MCP server in Python: tools, resources, prompts, tests and a local agent

How would you evaluate a RAG system before shipping a change to it?

I keep a versioned golden dataset: real questions with the facts and the source document a correct answer needs, plus questions the system must refuse. I measure retrieval on its own with recall@k and MRR, because a wrong answer is either a retrieval miss or a generation problem and I want to know which. Then cheap deterministic checks on the answers: is there a citation, is it the right source, are the required facts present, did it refuse off-topic questions. For meaning I use an LLM judge with a strict yes/no rubric for faithfulness and relevance, JSON output validated with Pydantic, and I calibrate it against hand labels before trusting it. Every run writes a report with the settings that produced it, and a regression gate in CI fails when a metric drops below the stored baseline. Unit tests with fakes cover the pipeline code itself.

Build it: Build an LLM evals pipeline in Python: golden dataset, retrieval metrics, LLM-as-judge and a CI gate

How would you make an LLM feature observable and keep its cost under control?

I trace every request with OpenTelemetry: a root span per request with child spans for retrieval, prompt building, each model call and each tool call. The model spans follow the GenAI semantic conventions, so they carry the operation, the provider, the requested and returned model, finish reasons and input and output tokens, and any backend can read them. I export over OTLP to a Collector that samples and strips sensitive data. From the token counts I compute cost per request from a price table, attached to the span and to a structured JSON log line with the request id and trace id, so support tickets, logs and traces link up. I watch p50 and p95 latency rather than averages, and cost per request per feature. To cap spend, a per-user daily token budget checks an estimate before the model call and records the real usage after it, in a shared store like Redis. The instrumentation itself is unit tested with an in-memory span exporter and a fake model server.

Build it: LLM tracing and cost tracking in Python with OpenTelemetry: spans, GenAI attributes, p95 latency and token budgets

How would you take an LLM chat service to production, and when would you self-host the model?

I package the API as a multi-stage Docker image: dependencies from a lockfile in a build stage, then only the virtual environment and code in a slim runtime stage, running as a non-root user, with no secrets inside. Every setting comes from environment variables and is validated at startup. The service exposes a liveness check that never touches the model and a readiness check that does, enforces per-request limits (body size, maxtokens, a deadline for the whole answer) and a per-client rate limit returning 429 with Retry-After, and shuts down gracefully so rollouts do not cut streams. For the model, the client speaks the OpenAI-compatible API, so Ollama, vLLM or a hosted provider is a configuration choice. I start with a hosted API, because idle GPUs cost money; I move to vLLM when traffic is steady enough to keep GPUs busy, since continuous batching and PagedAttention give far higher throughput per GPU, or when data must stay on our servers.

Build it: Deploy an LLM app with Docker, and serve your own model with vLLM

Walk me through the docs assistant you built. How do you know it does not make things up?

It is a RAG service in Python. Ingestion parses Markdown, HTML and PDF into sections with their heading path, so each chunk carries context and a link target, and an index embeds only chunks whose content hash changed. Retrieval is hybrid: BM25 for exact terms like error codes, vectors for paraphrases, merged with Reciprocal Rank Fusion, with an optional cross-encoder reranker. For grounding I do not trust the prompt alone: the code refuses before calling the model when retrieval is weak, validates every [n] citation after it answers, nudges once when an answer has no valid citation, and refuses if it still does not. It streams from FastAPI over Server-Sent Events, and the final event carries the checked answer. To know it works I keep 25 labelled questions, five of which must be refused, including traps that share words with the docs. I track recall@5, MRR, right-source citations, facts and refusals, and a CI gate fails any pull request that drops a score by more than 0.05. Then I quote my own numbers from the report, and the trade-offs: the reranker costs latency per question, and thresholds come from the measured score ranges, not from guesses.

Build it: Build a RAG docs assistant that cites its sources: hybrid search, streaming FastAPI and an eval gate in CI

Walk me through an AI agent you built that can take actions with real consequences.

A customer support agent for a shop, in Python. The shop data lives behind an MCP server with four tools: lookup, policy check and help search are read-only, and the refund tool enforces the refund policy itself. The agent is a LangGraph graph that reaches those tools through an MCP client: a model node, a tool node, and a third route for anything that moves money, to an approval node. That node checks the policy again, then pauses the graph with interrupt; the state is saved in SQLite, a person approves from a CLI or a REST endpoint, possibly from another process hours later, and the graph resumes. Small models skip tools, write tool calls as text and ignore search results, so code detects each case and nudges once, or answers with a fixed fallback. Guardrails are in code: an allowlist of tools, a step limit that ends the turn politely, card numbers scrubbed before the model, PII masked in JSON logs. Every turn is one OpenTelemetry trace, and token usage is part of the graph state, so cost is per conversation. 82 unit tests use a scripted fake model, and 18 scenario evals run in CI with a rule-based fake that replays the real model's mistakes, and locally against llama3.2:3b, where I track the pass rate as a baseline.

Build it: Build an AI customer support agent in Python: MCP tools, LangGraph, human approval, guardrails, tracing and evals

Walk me through the internal assistant you built in Spring AI. How do you keep it from doing the wrong thing?

It is a Spring Boot 3.5 service on Spring AI 1.1 for HR and IT questions and actions. At startup it splits a docs folder into sections with stable UUID ids, fingerprints the folder so unchanged docs are not embedded again, and stores the vectors in a SimpleVectorStore saved to a file, or in pgvector under a profile; the code only sees the VectorStore interface. Policy questions go through QuestionAnswerAdvisor with a threshold I chose from measured scores, because real embedding scores are bunched between about 0.45 and 0.8; a guard advisor refuses before any model call when nothing passes it, and every answer returns its sources. Actions are two @Tool methods; the user comes from Spring Security through the tool context, never from the model, and allow-lists and limits live in services that the structured-output endpoint uses too. Small models skip tools or claim actions they never took, so a server-side log is the only source of "what was done", a missed tool call gets one nudge, and a claimed but unlogged action is never shown. Memory is per user, the answer streams as typed SSE events, and Actuator shows readiness plus token and latency metrics from Spring AI's observations. 42 tests run the whole app against a fake OpenAI-compatible server, so CI needs no model. The trade-offs I would name: the nudge costs an extra call, the threshold has to be recalibrated per embedding model, and startup ingestion does not scale, which is why production ingests in a separate job.

Build it: Build an internal AI assistant with Spring AI: RAG with sources, tools, per-user memory, streaming and pgvector

Tell me about something you built that sits in front of LLM providers.

An OpenAI-compatible LLM gateway in Python with FastAPI. Apps keep the normal SDK and only change the base URL and the key; they ask for aliases like fast and smart, and a TOML config maps each alias to an ordered list of upstream targets, here Ollama and a hosted API. Keys are per team, random, stored as SHA-256 hashes in SQLite; each key has a token-bucket rate limit, and each team a daily token budget that reserves the worst case (prompt plus max tokens) before the call and releases it after, so concurrent requests cannot overshoot. Every request with a valid key writes exactly one usage row with tokens, cost from a price table and latency, also for streams that break or callers that hang up, and /admin/usage reports it per team. Failures that are not the caller's (timeouts, connection errors, 429 and 5xx) fall back to the next target, but only before the first byte, and a circuit breaker per target skips one that keeps failing. Deterministic requests at temperature 0 hit an exact-match cache scoped per team; I chose not to do semantic caching by default because near-duplicate prompts like two order numbers embed almost identically. Logs are JSON with keys never written and PII masked, and every upstream try is an OpenTelemetry span joined to the caller's trace. 80 tests run with fake upstreams behind httpx MockTransport and a fake clock. In a load test with repeated prompts the hit rate was 90%: p50 dropped to about 15 milliseconds while p95 was the model's seconds, which is why I report percentiles and not an average. To scale it out I would move the buckets, budgets and cache to Redis and the usage rows to a queue.

Build it: Build an LLM gateway in Python: an OpenAI-compatible proxy with API keys, rate limits, token budgets, fallback, caching and cost per team

AI system design questions

Answered step by step with the LADDER method: requirements, estimates, the design, retrieval and evals, cost and failure modes.

A 6-week plan

For a working developer, about an hour a day. Already strong in Python? Merge weeks 1 and 2.

  1. Week 1: Python and your first model call
    • Python Part A, lessons 1 to 10
    • Lab 1: your first LLM call
  2. Week 2: How LLMs work, and reliable output
    • LLM foundations and prompting episodes
    • Labs 2 to 4: streaming, structured output, tool calling
  3. Week 3: RAG
    • RAG episodes
    • Labs 5 to 8: embeddings, RAG from scratch, hybrid search, LangChain
  4. Week 4: Agents and production
    • Agents and production episodes
    • Labs 9 to 13: LangGraph, Spring AI, MCP, evals, tracing
  5. Week 5: One capstone, end to end
    • Pick the capstone closest to the role
    • Measure it: recall, latency, cost
  6. Week 6: Interview practice
    • Two AI system design problems out loud
    • The questions on this page, answered without notes
    • Coding practice and behavioral stories

Start the AI Engineering track →

Questions people ask

What does an AI engineer do?

An AI engineer builds products on top of language models: chat assistants, search over company documents, agents that call tools, and the evaluation, monitoring and cost controls that keep them reliable. It is closer to backend engineering than to ML research: most of the work is retrieval, prompts, APIs, tests and production, with enough ML to choose and evaluate models.

How is an AI engineer interview different from a software engineer interview?

The coding and behavioral rounds look much the same. The differences are an LLM and ML fundamentals round, a system design round about an AI product (with retrieval, evals, guardrails and cost), and often a practical build where you call a model and handle its mistakes. A project deep dive weighs more, because interviewers want to see something you shipped and measured.

Do AI engineer interviews ask data structures and algorithms?

Many do, usually one medium problem, and some replace it with a practical Python task such as parsing data, a rate limiter or a top-k search with NumPy. Prepare for both: the core coding patterns plus fluent, tested Python.

Do I need a machine learning degree to become an AI engineer?

No. Most AI engineer roles hire strong software engineers who can build reliable features on models. You need solid Python, a clear picture of how LLMs, RAG and agents work, evaluation skills, and projects that show it. The ML basics (metrics, overfitting, what fine-tuning does) come up, but not research-level maths.

What projects should I build for an AI engineer interview?

One or two complete projects you can measure, rather than many demos: for example a documents assistant with citations and an eval set, or a support agent with tools, approvals and tracing. Be ready to give the numbers (recall, latency, cost per request) and what you changed because of them.

Can I prepare for AI engineering in Java?

Yes. Spring AI covers chat, structured output, tools, RAG and memory in Spring Boot, and many enterprise teams use it. Python is still expected in most interviews and take-homes, so learn both: the concepts carry over one to one.

All companies · Senior engineer interviews · System Design · Build labs