AI Engineering NotesRohit’s interview study guide
Chapter 14

Review Questions

Rapid revision before an interview: short questions with model answers you can say out loud in a minute, each linked to the topic that explains it in depth.

13 topics

#How LLMs work questions

Added

This page is for the last few days before an interview, when you no longer need to learn a topic but need to say it well, quickly. Every question here is one an interviewer might ask about building with language models, or one you should be able to answer for yourself in the middle of a design. The first paragraph of each answer is the version you'd say out loud: 30 to 90 seconds, with the decision first and the reason straight after. The walkthrough under it is the reasoning you need when the follow-up is "why?", and the link at the end goes to the topic that teaches it properly.

Think of it as a deck of flashcards with the working shown. Read the question, close your eyes, answer it in your own words, then open the answer and compare: did you name the mechanism, the number or limit that drives the decision, and what goes wrong in production? If one of the three is missing, that's the card to go back to. The cost and sizing questions have small runnable models; their output was produced on Node 26 and is re-checked every time the site is validated, so you can trust the arithmetic and concentrate on the reasoning. Prices in them are Anthropic's published API prices as listed in December 2026.

This first group covers what a model does with a prompt: tokens, the generation loop, sampling, context, training, reasoning and hallucination.

What happens between sending a prompt and getting a reply?
Show answer

The model predicts one token at a time, in a loop. "My system prompt and messages are flattened into one token sequence. The model maps that sequence to a probability for every token in its vocabulary; the server picks one, appends it, and runs the model again, until an end-of-turn token or max_tokens. That's why replies can be streamed, why the model has no memory between calls, and why everything it knows is either in its weights or in the context I send."

What’s happening
  1. Tokenise: text becomes integer token ids. The model never sees letters or words, only ids.
  2. One forward pass gives a probability distribution over the whole vocabulary for the next position.
  3. Pick, append, repeat: generation is autoregressive. Each new token depends on all the earlier ones, so output is produced strictly left to right.
  4. Stop: the model emits its end-of-turn token, or the server stops at max_tokens, which cuts the reply off mid-thought.
  5. The follow-up is usually "so where's the memory?" There isn't any: each API call starts from the tokens in that request, which is why your application resends the conversation every turn.

Learn more: What a large language model is and Next-token prediction and the generation loop.

Why can't a model reliably count the r's in "strawberry"?
Show answer

Because it never sees the letters. "The tokenizer turns the word into a token id before the model runs, so the model gets an integer, not ten characters. To answer it has to recall the spelling from training text and count, which is error-prone. In an application I don't ask a language model to do character-level work: I do it in code or give the model a tool. The same thing explains weak arithmetic on long numbers, because digits are grouped into chunks."

What’s happening
  1. Tokenizers are built by merging frequent byte sequences, so a common word is often one token, and a rare word is several pieces.
  2. The model's input is that id sequence. Nothing about the id for a word says which letters it contains.
  3. Models often get famous examples right, by reasoning it through or because the question appeared in training. That isn't the same as being able to do it.
  4. The engineering answer is the important part: counting, exact string operations and arithmetic belong in code or a tool call, with the model deciding when to use them.
  5. Tokens are also the unit of billing and of context size, so the same concept answers "why is my bill in tokens?".

Learn more: Tokens and tokenizers.

Why do output tokens cost more than input tokens, and what does that mean for latency?
Show answer

Input is processed in one parallel pass; output is generated one token at a time. "The whole prompt goes through the model at once, but each output token needs its own pass that depends on the previous one, so it ties up the hardware for far longer per token. Claude's output price is five times its input price on every current model. For latency: time to first token grows with the prompt, total time grows with output length. So the biggest latency lever is usually a shorter output."

What’s happening
  1. Prefill handles all input tokens together; decode is sequential by construction.
  2. Pricing reflects that: on Claude Opus 5.5, $4 per million input tokens against $20 per million output.
  3. Even so, most applications spend more on input, because there's so much more of it: long context in, short answer out. Check the split before optimising.
  4. Latency has two parts with different fixes: time to first token (prompt size, model size, caching) and generation time (output tokens divided by tokens per second).
  5. Streaming doesn't make generation faster. It lets the user start reading at the first token.

Learn more: Next-token prediction and the generation loop.

The same prompt gives different answers each time. How do you make a feature consistent?
Show answer

By making the task well-specified, not by turning a knob. "Current Claude models don't accept temperature, top_p or top_k at all, and even greedy decoding isn't guaranteed repeatable on a serving cluster. So I specify the task clearly, give examples, use structured outputs when the result is data, ground facts in retrieved documents, and then measure consistency with an eval that runs each case several times. Where an answer must be identical every time, I cache it in my own system."

What’s happening
  1. Sampling picks from the model's distribution; temperature, top-p and top-k reshape that distribution. They still exist on open-weight models.
  2. On current Claude models those parameters are rejected. The controls are the prompt, the output format and effort.
  3. A schema-constrained output removes most format variation: the enum can only be one of your values.
  4. Variation that remains is information: a case that passes three times in five is an under-specified prompt or a retrieval problem.
  5. Identical-every-time is a storage requirement. Generate once, store the result, serve the stored copy.

Learn more: Sampling: temperature, top-p and top-k.

Why is a very long prompt slow and expensive to serve? Put a number on the memory.

Use a 72-billion-parameter model shaped like Qwen2.5-72B: 80 layers, 8 key-value heads of size 128, 16-bit numbers.

Show answer

Every token in the context costs money, prefill time and KV-cache memory: about 320 KiB per token on a model that size, so 100,000 tokens is roughly 30 GiB for one conversation. "Input is billed per token on every call. Prefill runs every token through every layer, so time to first token rises. And while generating, the server keeps each earlier token's keys and values in memory, per layer, so it doesn't recompute them. That cache is why long contexts are expensive to serve, and it's on top of the quality problem: models use the middle of very long contexts less reliably."

rq-kv-cache.mjsPlayground ↗
// KV cache: each layer keeps one key and one value vector per KV head, for every token in the context.
const bytesPerToken = ({ layers, kvHeads, headDim, bytes }) => 2 * layers * kvHeads * headDim * bytes;
// The shape in Qwen2.5-72B-Instruct's published config: 80 layers, 8 KV heads of size 128, served in 16-bit.
const perToken = bytesPerToken({ layers: 80, kvHeads: 8, headDim: 128, bytes: 2 });
console.log(`per token: ${perToken / 1024} KiB`);
for (const tokens of [8_000, 100_000, 1_000_000]) {
  console.log(`${tokens.toLocaleString("en-US").padStart(9)} tokens: ${((perToken * tokens) / 2 ** 30).toFixed(1).padStart(5)} GiB for one conversation`);
}
Result
per token: 320 KiB
    8,000 tokens:   2.4 GiB for one conversation
  100,000 tokens:  30.5 GiB for one conversation
1,000,000 tokens: 305.2 GiB for one conversation
What’s happening
  1. Per token: a key and a value (×2), in each of 80 layers, for 8 heads of 128 numbers, at 2 bytes: 320 KiB.
  2. An 8,000-token chat needs about 2.4 GiB. A 100,000-token context needs about 30.5 GiB, a large slice of one accelerator for a single user.
  3. A million tokens would be about 305 GiB with this plain arithmetic, which is why providers of million-token windows invest in cache-saving techniques, and why long prompts are priced and rate-limited the way they are.
  4. The cache is also what makes generation affordable at all: without it, every new token would re-process the whole sequence.
  5. The practical conclusion is the same from all three angles: keep contexts lean, retrieve what's relevant, and use prompt caching when a large prefix really is reused.

Learn more: Transformers and attention, just enough.

We have a 1M-token context window. Why do we still need retrieval?
Show answer

Because fitting isn't the same as working well or cheaply. "Sending a whole knowledge base on every request costs its full token count every time and slows the first token. Long contexts also dilute attention: the 'Lost in the Middle' results showed accuracy dropping when the relevant passage sat in the middle. Retrieval sends the few chunks that matter: cheaper, faster, usually more accurate, and it handles per-user permissions and corpora bigger than any window. Long context is right for one-off analysis of a big document, or with prompt caching when the same context is reused."

What’s happening
  1. Count what's in the window: system prompt, tool definitions, history, documents, and room for the output. It all counts.
  2. Money and latency scale with the tokens sent, on every call.
  3. Quality doesn't scale with them: position matters, and irrelevant text competes for attention.
  4. A corpus that changes, is large, or has access rules needs retrieval whatever the window size.
  5. The real skill is context engineering: deciding what goes into the window for this request, and in what order.

Learn more: Context windows.

Why do models hallucinate, and what do you do about it in a product?
Show answer

Training rewards plausible text, not true text, and nothing in it teaches "I don't know" by default. "Pre-training optimises for likely continuations, and preference tuning rewards confident, agreeable answers. So in an application I give the model the facts by retrieving them into the context, make abstaining legitimate in the prompt and the schema, make claims checkable with citations or tool calls my code can verify, and measure with an eval that includes unanswerable questions."

What’s happening
  1. Ground: retrieved documents in the context, with an instruction to answer only from them.
  2. Allow abstention: "I don't know" in the prompt, null in the schema, and evals that reward it when the answer isn't in the sources.
  3. Verify: quotes checked against the source, prices and dates from tools, fields validated in code.
  4. Measure: track both accuracy and the rate of unsupported answers; a model that answers everything looks good on accuracy alone.
  5. Reasoning models hallucinate less on many tasks. That's a help, not a design.

Learn more: Why models hallucinate and How models are trained: pre-training, fine-tuning and RL.

When do you turn effort up, and when down?
Show answer

Effort trades quality for tokens and time within one model, so I set it per route, from evals. "Simple tasks where someone is waiting, like classification, extraction, routing and casual chat, get low effort, sometimes on a smaller model. Hard reasoning, code generation and multi-step agents get high or xhigh, because they measurably improve and cost per completed task can fall when fewer retries are needed. Thinking tokens are billed as output, so effort is a cost setting too. And budget_tokens is gone on current Claude models: adaptive thinking plus effort replaced it."

What’s happening
  1. Current Claude models use adaptive thinking: the model decides how much to think; output_config.effort is the depth control.
  2. Set effort explicitly per route, because defaults differ between models.
  3. Thinking tokens count as output tokens and count towards max_tokens.
  4. If users watch the stream, ask for summarised thinking, or the pause before the first visible token looks like a hang.
  5. Pass thinking blocks back unchanged on later turns.

Learn more: Reasoning models and thinking.

How do you choose a model for a new feature?
Show answer

With an eval on my own task, stepping down in cost until quality drops below the bar. "I build a small eval set from real inputs with a way to grade them. I try the strongest model to see what's achievable, then step down, a smaller model or the same model at lower effort, until it fails the bar. I compare latency at real prompt sizes and estimate monthly cost from real token counts, then check the constraints: context size, modalities, tools, data retention and region. I pick the cheapest option that passes, pin the model id, and re-run the eval when a new model appears."

What’s happening
  1. Public benchmarks shortlist candidates. They don't tell you how a model does on your task.
  2. Start from the top so you know whether the task is achievable at all.
  3. Cost and latency are measured, at real prompt and output sizes, not read off a leaderboard.
  4. Different routes can use different models: a small one to classify, a large one for the hard path.
  5. Pinning the id and keeping the eval is what makes the next model upgrade a one-day job.

Learn more: The model landscape and choosing a model.

#Calling models questions

Added

Questions about the API itself: the request and response, streaming, errors, cost, stop reasons and batch work.

Walk me through one call to a model API.
Show answer

One stateless POST: the model, a cap on output, and the whole conversation go in; typed content blocks, a stop reason and usage come out. "On Claude's Messages API the request names the model, sets max_tokens as a hard cap, and sends messages, optionally with a system prompt and tools. The response is one assistant message whose content is a list of typed blocks, plus a stop_reason I always check and usage that drives the bill. Nothing is stored server-side, so my application owns the history and resends it each turn."

What’s happening
  1. content is a list, not a string: text, thinking and tool-call blocks. Pick blocks by type, never by position.
  2. stop_reason says why generation ended: end_turn, max_tokens, tool_use, pause_turn, refusal.
  3. usage reports input, output and cache tokens. Log it with the request id on every call.
  4. Statelessness is the design fact everything else follows from: conversation storage, cost that grows with history, prompt caching.
  5. Use the official SDK: typed errors, automatic retries and streaming helpers come with it.

Learn more: The Messages API: request and response and System prompts and multi-turn conversations.

What does your code do with each stop reason?
Show answer

It branches on stop_reason before reading the content. "end_turn: use the text. max_tokens: the output is incomplete, so I never parse or act on it; I raise the cap or ask for less. tool_use: run the tools and send all the results back in one user message. pause_turn: send the response back so a server-tool turn continues. refusal: an HTTP 200 with no usable answer, so I show a designed message or fall back. Anything unknown is logged as unhandled, never treated as success."

What’s happening
  1. max_tokens is the quiet one: the reply looks fine until you notice it stops mid-sentence, or the JSON doesn't close.
  2. tool_use means the model is waiting. Every requested call needs a result, even a failed one.
  3. refusal arrives with status 200, so error handling that only looks at HTTP status misses it.
  4. With structured outputs, max_tokens and refusal are the two cases where the body doesn't match your schema.
  5. Logging the distribution of stop reasons per route is a cheap health metric: a jump in max_tokens means a cap is wrong.

Learn more: Stop reasons and refusals.

How do you handle 429s and overloaded errors?
Show answer

Let the SDK retry, don't wrap it in another loop, and fix sustained limits upstream. "The SDK already retries 429, 5xx including 529 overloaded, timeouts and connection errors with backoff, and honours retry-after. Permanent errors like 400, 401, 403 and 404 are bugs to fix, not to retry. If 429s persist, the fix is in my design: a queue or token bucket sized to my tokens-per-minute limit, prompt caching to cut input tokens, and the Batch API for anything that isn't interactive. For 529s on an interactive path I'd add a fallback model."

What’s happening
  1. Retrying around a client that already retries multiplies attempts: three around three is nine.
  2. Separate transient (retry with backoff and jitter) from permanent (fix the request).
  3. Rate limits are in requests and tokens per minute. A few huge requests can hit the token limit at a low request rate.
  4. Set a timeout on purpose, and an overall deadline for the operation, because a timeout is itself retried.
  5. Watch the rate-limit headers and your own usage, so you see the limit coming instead of discovering it from errors.

Learn more: Errors, retries and rate limits.

Estimate the monthly cost of a feature, and name the first two savings.

20,000 requests a day on Claude Opus 5.5 ($4 and $20 per million input and output tokens; cached input read at $0.20 per million). Each request sends 8,000 input tokens, 6,000 of them an identical prefix, and gets 500 output tokens.

Show answer

About $25,200 a month as described; about $11,500 with prompt caching on the prefix; and half price through the Batch API for whatever doesn't need an immediate answer. "I'd build the estimate from requests per day and measured tokens per request, state the assumptions, and then apply the levers in order: caching first because it doesn't touch quality, batch for offline work, and only then a smaller model, which needs an eval."

rq-request-cost.mjsPlayground ↗
// Claude Opus 5.5, dollars per million tokens (Anthropic's published prices, December 2026).
const PRICE = { input: 4, output: 20, cacheRead: 0.2 };
const requestsPerDay = 20_000, inputTokens = 8_000, stablePrefix = 6_000, outputTokens = 500;
const usd = (n) => `$${Math.round(n).toLocaleString("en-US")}`;

const plain = (inputTokens * PRICE.input + outputTokens * PRICE.output) / 1e6;
const cached = (stablePrefix * PRICE.cacheRead + (inputTokens - stablePrefix) * PRICE.input + outputTokens * PRICE.output) / 1e6;
const perMonth = (perRequest) => perRequest * requestsPerDay * 30;
console.log(`per request: $${plain.toFixed(4)} (input is ${Math.round((inputTokens * PRICE.input) / (plain * 1e6) * 100)}% of it)`);
console.log(`per month: ${usd(perMonth(plain))}`);
console.log(`with the prefix read from cache: $${cached.toFixed(4)} per request, ${usd(perMonth(cached))} a month (${Math.round((1 - cached / plain) * 100)}% less)`);
console.log(`through the Batch API at 50%: ${usd(perMonth(plain) * 0.5)} a month`);
Result
per request: $0.0420 (input is 76% of it)
per month: $25,200
with the prefix read from cache: $0.0192 per request, $11,520 a month (54% less)
through the Batch API at 50%: $12,600 a month
What’s happening
  1. Per request: 8,000 × $4 + 500 × $20, per million, is $0.042. Input is 76% of that, even though output is five times the price per token.
  2. Times 20,000 a day and 30 days: $25,200 a month.
  3. With the 6,000-token prefix read from cache at $0.20 per million, a request costs $0.0192: $11,520 a month, 54% less. (Cache writes on the occasional miss add a little; steady traffic keeps the prefix warm.)
  4. The Batch API halves the price of every token, $12,600 here, but results arrive later, so it's for offline work: classification runs, backfills, evals.
  5. After launch, log usage per request and compare the real numbers with the estimate. Output length is usually the assumption that was wrong.

Learn more: Counting tokens and estimating cost and Batch processing.

Does streaming make the model faster?
Show answer

No. It makes the wait feel shorter by showing the first token as soon as it exists. "Generation takes the same time. Streaming changes perceived latency from 'time to the whole answer' to 'time to first token', which for chat is what users notice. The API sends server-sent events; the SDK's stream helper gives me text deltas and a final assembled message. I use it for anything a person waits on, and for long outputs generally, since it also avoids HTTP timeouts on long requests."

What’s happening
  1. The event sequence is: message start, content block start, a series of deltas, content block stop, a message delta with the stop reason and usage, message stop.
  2. Take the final message from the SDK helper for logging and storage; don't rebuild it by hand from deltas.
  3. Once output has started, a failure can't be silently retried: the user has seen text. Keep what arrived and offer to continue.
  4. Wire cancellation through, so a user who leaves stops the generation and the bill.
  5. Large max_tokens values effectively require streaming, because a non-streamed request would sit open for minutes.

Learn more: Streaming responses.

You need to classify two million product descriptions. How?
Show answer

With the Message Batches API, a small model, structured output and a custom_id per item. "I wouldn't make two million synchronous calls. I'd split the work into batches, give each request a custom_id equal to the product id, submit, poll until each batch ends, and write the results to the database keyed by custom_id, because results come back in any order. It's half price on every token. I'd choose the smallest model that passes an eval on a labelled sample, use structured output so every label parses, and run one small batch end to end first to check cost and quality."

What’s happening
  1. Nobody is waiting, so latency is free to trade for price: that's the definition of a batch workload.
  2. custom_id is the join key. Never rely on result order.
  3. Each result has its own status: succeeded, errored, expired. Resubmit only the failures.
  4. The eval comes before the two million, not after: a labelled sample of a few hundred decides the model and the prompt.
  5. A cached system prompt and a small model compound with the batch discount.

Learn more: Batch processing.

How would you support more than one model provider?
Show answer

A thin interface of my own, an adapter per provider, and the same eval run against each. "My code talks to an interface with generate, stream and maybe a structured-output call, using my own types for messages, tool calls, usage and stop reasons. Each provider gets an adapter on its official SDK. A library like the AI SDK can be that layer for the common features. Provider-specific features, like prompt caching, citations and thinking, stay behind optional capabilities, and I run the eval set per provider before moving traffic, because prompts don't transfer perfectly between models."

What’s happening
  1. The shapes differ: where the system prompt goes, how tool calls and results are represented, what the usage fields are called.
  2. A neutral layer costs you the newest features of each provider until the layer exposes them.
  3. "OpenAI-compatible" endpoints make local servers such as Ollama and LM Studio easy to plug in for development.
  4. Switching providers is a model change, and a model change is an eval run, not a config edit.
  5. Decide what you need neutrality for: a fallback, price negotiation, or a customer's cloud requirement. Each implies a different amount of abstraction.

Learn more: OpenAI and the OpenAI-compatible shape and Provider-neutral code with the AI SDK.

#Prompt engineering questions

Added

Questions about writing, structuring, caching and debugging the prompts an application sends.

How do you manage prompts in a production codebase?
Show answer

As code: versioned, reviewed, and gated by an eval. "Each prompt is a versioned module with its system prompt, its template and the model it was tested with, and changes go through pull requests. Every prompt has an eval set of real and edge-case inputs, and CI runs it on any change to the prompt or the pinned model. Every model call logs the prompt id and version, so a quality change in production can be tied to a change. Significant edits roll out like features, behind a flag to a slice of traffic."

What’s happening
  1. A prompt edit changes behaviour like a code edit does, with less visibility. An unreviewed edit in a dashboard is an untested deploy.
  2. A fingerprint of the rendered prompt in CI catches edits that skipped the process.
  3. The eval set is the test suite. Without it, "it looked fine on two examples" is the whole review.
  4. Logging the version with each call is what makes "what changed?" answerable later.
  5. Keep the static part of the prompt byte-stable, or prompt caching silently stops working.

Learn more: Prompts are code.

What makes a good system prompt?
Show answer

It reads like a good onboarding document. "One line of role, then the context the model can't know, then the task, then rules, each with the reason behind it so the model can generalise, then the exact output format. I keep it plain: no capital-letter shouting, which newer models over-react to, and no contradictory rules. I structure it with XML tags, keep the static part first and byte-stable for caching, and test every change against an eval set."

What’s happening
  1. Context the model can't know: the product, the users, and per-request facts such as the user's plan.
  2. A rule with its reason ("no refunds over €200 because those need finance approval") covers cases the rule's wording didn't anticipate.
  3. Static content first, per-user content last, ideally in the user turn: that order is also what caching needs.
  4. Prompts rot: incident patches pile up and contradict each other. After a model upgrade, try deleting rules and keep each deletion the evals survive.
  5. Tags such as <instructions>, <document> and <example> make it unambiguous which text is which.

Learn more: Writing a system prompt that works and Structuring prompts with XML tags.

When do you use few-shot examples, and how do you choose them?
Show answer

When the format or the judgement is easier to show than to describe. "A classification with fuzzy boundaries, or a house tone. I pick three to five examples from real inputs, covering the edge cases and balanced across labels, because the model picks up everything about them, including label frequency and length. I wrap them in example tags so they're never mistaken for instructions, put them in the cached part of the prompt since they're paid for on every call, and check with an eval that they actually help."

What’s happening
  1. Examples are a sequence, not a set: order affects the result, so test it rather than assume.
  2. A skewed set teaches the skew: four positive examples and one negative biases the labels.
  3. Examples are input tokens on every request. That's the cost side of the trade.
  4. Diverse examples beat many similar ones.
  5. An eval decides. Examples can fix some cases and break others.

Learn more: Few-shot examples.

Should you still tell a model to "think step by step"?
Show answer

On current Claude models, no: thinking is built in, and I ask for evidence, not for reasoning. "Adaptive thinking reasons in separate thinking blocks before the answer, so the classic chain-of-thought prompt is redundant there. Anthropic's migration guide also says a prompt that asks the model to write out its internal reasoning in the response may be declined as reasoning extraction. If I want to see the reasoning, I set the thinking display to summarized. If my code needs something checkable, I ask for it explicitly: the clauses or quotes the answer relies on, in tags."

What’s happening
  1. Thinking is scratch paper you're billed for. The answer is what you grade.
  2. Thinking tokens are output tokens: effort controls how many.
  3. On models without built-in thinking (many open-weight ones), "reason in tags, then answer in tags" still works, with your code stripping the reasoning.
  4. Asking for evidence gives you something to verify against the source, which a paragraph of reasoning doesn't.
  5. When streaming, hide whatever isn't the answer until the answer begins.

Learn more: Letting the model think.

How do you put user input, or a long document, into a prompt?
Show answer

As clearly delimited data in the user turn, with the question after it. "User text never goes in the system prompt. It goes inside a named tag, escaped so it can't close the tag, with an instruction after it that the block is data, then the task. I cap its length before the call. Long documents go at the top with the question at the end, and I ask the model to quote the passages it relies on, which my code checks against the source. None of that is a complete defence against prompt injection, so I also limit what the model can do."

What’s happening
  1. Escaping matters: input containing your closing tag would otherwise end the data block early.
  2. Use a replacement function when templating in JavaScript: String.replace treats $& and friends in the inserted text specially.
  3. Documents first, question last is Anthropic's long-context guidance.
  4. A quote that doesn't appear in the document is a red flag for an invented answer. That check is plain code.
  5. Delimiters reduce injection; least privilege and confirmation bound the damage.

Learn more: Prompt templates and user input and Long documents in prompts.

How does prompt caching work, when does it pay off, and how do you know it's working?
Show answer

It's an exact prefix match up to a breakpoint: written once at a premium, read afterwards at a fraction. It pays off from the second request on the 5-minute cache. "The prefix is rendered as tools, then system, then messages. The first request writes it at 1.25 times the input price for a 5-minute entry, or 2 times for an hour; identical later requests read it at 0.05 times on Opus 5.5 and Sonnet 5.5. So stable content goes first, the breakpoint at the end of the shared part, per-request content after it. I verify with usage.cache_read_input_tokens, because the usual failure is silent."

rq-cache-breakeven.mjsPlayground ↗
// Cost of the shared prefix, in units of "one uncached read of it". Opus 5.5 / Sonnet 5.5 multipliers.
const read = 0.05, write5min = 1.25, write1hour = 2;
console.log("requests  uncached  5-min cache  1-hour cache");
for (const n of [1, 2, 3, 10, 100]) {
  const row = [n, n, write5min + read * (n - 1), write1hour + read * (n - 1)];
  console.log(row.map((v, i) => (i === 0 ? String(v).padStart(8) : v.toFixed(2).padStart(i === 1 ? 10 : 13))).join(""));
}
Result
requests  uncached  5-min cache  1-hour cache
       1      1.00         1.25         2.00
       2      2.00         1.30         2.05
       3      3.00         1.35         2.10
      10     10.00         1.70         2.45
     100    100.00         6.20         6.95
What’s happening
  1. One request: caching costs more (1.25 against 1.00). A prefix used once shouldn't be cached.
  2. Two requests: 1.30 against 2.00. The 5-minute cache has paid for itself. The 1-hour cache (2.05) hasn't yet; it does at three (2.10 against 3.00).
  3. A hundred requests: 6.20 against 100. For a busy endpoint the prefix becomes almost free.
  4. Any byte that changes in the prefix, a timestamp, a per-user value, tools in a different order, invalidates everything after it. The hit rate drops to zero and nothing errors.
  5. So add a test that a repeated request reads from cache, and watch the cache-read share in production.

Learn more: Prompt caching.

When would you split one prompt into a chain?
Show answer

When I need control between the steps; otherwise I keep one prompt. "If a single prompt passes my evals, it stays: chains add latency, cost and hand-off errors. I chain when an intermediate result must be validated in code before going on, when steps want different models or effort levels, when I need to see which stage fails, or for a generate, review, revise loop against explicit criteria. Each step has a narrow prompt, a typed output, a stop-reason check and a cap on retries."

What’s happening
  1. A chain's value is the gate between steps: code that checks, not a model that hopes.
  2. Errors carry forward: step three treats step one's mistake as a fact.
  3. Log every intermediate result so each step can be evaluated alone.
  4. Map-reduce over a long document is a chain with a parallel middle.
  5. Chaining is a workflow pattern; an agent is what you reach for only when the steps can't be fixed in advance.

Learn more: Prompt chaining.

Your new prompt scores 83% on the eval and the old one 78%. Ship it?

The eval set has 100 cases.

Show answer

Not on that evidence: on 100 cases the two results' confidence intervals overlap. "With 100 cases, 83% has a 95% interval of roughly 74% to 89%, and 78% sits inside it. I'd look at which cases changed rather than only the totals, grow the set, and change one thing at a time. A prompt that worked last month and doesn't now gets the same treatment: find what changed, group the failures by cause, add them to the eval set, fix the biggest group."

rq-wilson.mjsPlayground ↗
// Wilson score interval: a 95% confidence interval for a pass rate measured on n cases.
function wilson(passed, n, z = 1.96) {
  const p = passed / n, denom = 1 + (z * z) / n;
  const centre = (p + (z * z) / (2 * n)) / denom;
  const half = (z * Math.sqrt((p * (1 - p)) / n + (z * z) / (4 * n * n))) / denom;
  return [centre - half, centre + half];
}
const pct = (x) => `${Math.round(x * 100)}%`;
for (const [passed, n] of [[83, 100], [78, 100], [830, 1000], [780, 1000]]) {
  const [low, high] = wilson(passed, n);
  console.log(`${String(passed).padStart(3)}/${String(n).padEnd(4)} = ${pct(passed / n)}  95% interval ${pct(low)} to ${pct(high)}`);
}
Result
 83/100  = 83%  95% interval 74% to 89%
 78/100  = 78%  95% interval 69% to 85%
830/1000 = 83%  95% interval 81% to 85%
780/1000 = 78%  95% interval 75% to 80%
What’s happening
  1. 83 of 100 gives an interval of about 74% to 89%. 78 of 100 gives about 69% to 85%. They overlap heavily: the gap could be noise.
  2. On 1,000 cases the same rates give 81% to 85% and 75% to 80%. Those don't overlap, and now the difference means something.
  3. So the size of the eval set decides how small an improvement you can detect.
  4. Look at the flips: five cases fixed and none broken is different from fifteen fixed and ten broken, at the same total.
  5. For a regression: check the logged prompt version, model id, effort and input mix first, and keep the old model pinned until the evals pass.

Learn more: Debugging a prompt.

#Structured output and tool calling questions

Added

Questions about getting data out of a model and letting it call your code.

Why isn't "reply in JSON" in the prompt enough?
Show answer

Because it fails rarely enough to pass a demo and often enough to page someone. "Without a constraint the model is still predicting likely text, so on unusual inputs it adds a sentence before the JSON, wraps it in a code fence, drops a field or invents an enum value. I use the API's structured outputs, which constrain decoding to a JSON schema so the reply always parses and has the required fields, and I still validate business rules in my own code, because a schema can say 'amount is a number' but not 'no more than the customer paid'."

What’s happening
  1. Three levels: ask nicely (no guarantee), schema-constrained (shape guaranteed), schema plus your validation (shape and business rules).
  2. Constrained decoding compiles the schema into a grammar and masks every token that would break it.
  3. It guarantees shape, not truth: a valid object can still hold a wrong value.
  4. Two cases break even the shape guarantee: a reply cut off by max_tokens, and a refusal.
  5. Make "unknown" representable with nullable fields, or the model must invent a value to satisfy the schema.

Learn more: Why applications need structured output and Structured outputs with a JSON schema.

Your schema says a score is between 0 and 1. Does the API enforce that?
Show answer

No: the grammar enforces types, enums and required keys; ranges and lengths are enforced on my side. "The supported schema subset has no numeric limits or string lengths. The SDK's zod helper strips those from the schema it sends, writes them into the field's description so the model still sees them, and checks them when it validates the reply. In the SDK version this course uses, messages.parse() throws if that validation fails, so I catch it, or I call create, check the stop reason and validate myself."

What’s happening
  1. Enforced by the API: the JSON types, enum values, required properties, no extra keys.
  2. Not expressible in the grammar: minimum, maximum, minLength, maxLength, most array limits, recursive schemas.
  3. Client-side validation with the original zod schema covers the gap.
  4. A failed validation is a decision point: repair by sending the errors back, retry with a changed request, or give up with a typed failure.
  5. Cap repairs at one or two, and never pass an unvalidated value downstream.

Learn more: Structured outputs with a JSON schema and Validating and repairing model output.

What actually happens when a model "calls a function"?
Show answer

The model doesn't call anything. It writes a request, and my code decides whether to run it. "I send the conversation plus tool definitions: a name, a description and a JSON schema for the arguments. If a tool would help, the reply stops with stop_reason tool_use and a tool_use block containing an id, the name and the arguments. My code validates them, runs the real function, and sends a second request with the whole history plus a tool_result carrying the same id. The model then answers or asks for another tool. One tool call is two requests, and every side effect happens in my process."

What’s happening
  1. Tool definitions are prompt text: billed on every request, and the description is what the model decides from.
  2. The assistant message must go back with all its blocks intact, or the result has no call to refer to.
  3. Every tool_use needs a tool_result with the matching id in the very next user message.
  4. Arguments are model output: validate them, and authorise against the user's permissions in the handler.
  5. Results stay in the context and are resent every later turn, so keep them small.

Learn more: How tool calling works.

What makes a tool easy for a model to use correctly?
Show answer

Design it for a reader who only has the definition. "A verb-and-object name. A description that says what it does, when to call it, what it returns and which neighbouring tool to use otherwise. Full parameter names with descriptions and examples, enums wherever the values are fixed, and strict so arguments always match the schema. Results that are trimmed and bounded. Errors written as instructions for what to try next. And when the model misuses a tool, I fix the tool before I touch the prompt."

What’s happening
  1. Anthropic's best-known example: a file tool that took relative paths kept failing until it required absolute paths. The fix was in the interface.
  2. Size tools by task, not by endpoint: merge calls that always happen together, split reads from writes so writes can be gated.
  3. An error like "No order A-1042; ids look like A-10422; call search_orders" lets the model recover. "400" doesn't.
  4. Internal errors go to your logs; the model gets "failed, don't retry".
  5. The handler, not the model, is the security boundary: identity comes from the session.

Learn more: Designing tools a model can use.

Write the tool loop. What does it cost as it gets longer?

A loop starts with 3,000 tokens of system prompt and tools, and each step adds 500 tokens of history. Twelve steps on Claude Opus 5.5.

Show answer

Call the model; while the stop reason is tool_use, append its message, run every tool, append all results in one user message, repeat; stop on end_turn or a limit. Cost grows roughly with the square of the steps, because every request resends everything: 69,000 input tokens here for a conversation that ends at 9,000. "So I cap steps and total cost, return failed tools as error results, branch on the stop reason before running anything, and cache the prefix."

rq-loop-cost.mjsPlayground ↗
// Claude Opus 5.5, dollars per million tokens: input 4, cache write 5 (1.25x input), cache read 0.2.
const base = 3_000, perStep = 500, steps = 12;
let uncachedTokens = 0, cachedMicroDollars = 0;
for (let i = 0; i < steps; i++) {
  const sent = base + perStep * i; // the whole history so far goes out again
  uncachedTokens += sent;
  const alreadyCached = i === 0 ? 0 : base + perStep * (i - 1);
  cachedMicroDollars += alreadyCached * 0.2 + (sent - alreadyCached) * 5; // read the old part, write the new part
}
console.log(`history after ${steps} steps: ${(base + perStep * steps).toLocaleString("en-US")} tokens`);
console.log(`input tokens billed without caching: ${uncachedTokens.toLocaleString("en-US")} = $${((uncachedTokens * 4) / 1e6).toFixed(3)}`);
console.log(`with prompt caching: $${(cachedMicroDollars / 1e6).toFixed(3)} (${Math.round((1 - cachedMicroDollars / (uncachedTokens * 4)) * 100)}% less)`);
Result
history after 12 steps: 9,000 tokens
input tokens billed without caching: 69,000 = $0.276
with prompt caching: $0.055 (80% less)
What’s happening
  1. Request 1 sends 3,000 tokens, request 2 sends 3,500, and request 12 sends 8,500. The sum is 69,000 tokens, $0.276 of input on Opus 5.5.
  2. The history itself only reaches 9,000 tokens. You paid for nearly eight times that, because of resending.
  3. With caching, each request reads the part it has sent before at $0.20 per million and writes only the new 500 tokens: about $0.055, 80% less.
  4. The loop's correctness rules: whole assistant content appended, every call answered, all results in one message, is_error for failures.
  5. Its safety rules: a step limit, a budget, a deadline, and never executing tools from a reply that ended with max_tokens or refusal.

Learn more: Writing the tool loop yourself and The SDK tool runner.

The model asks for three tools in one reply and one of them fails. What do you send back?
Show answer

All three results in one user message: two normal ones, and one with is_error: true that says what went wrong and what to try. "I run the calls concurrently with each one wrapped so a failure becomes a result, not an exception. The API requires every tool_use to be answered in the next message, so I can't send two now and one later. The model then works with what it has, and can ask for the failed call again."

What’s happening
  1. Parallel tool use is on by default; one reply can carry several tool_use blocks.
  2. Results are matched by tool_use_id, so order doesn't matter.
  3. A dropped result makes the next request invalid; a thrown exception loses the two that succeeded.
  4. Run reads concurrently. Be careful with writes: make them idempotent or run them in sequence.
  5. Give each call a timeout, and report a timeout as an error result.

Learn more: Parallel tool calls and tool errors.

What's the difference between a client tool and a server tool?
Show answer

Who runs it. "A client tool is mine: the model returns a tool_use block, my code executes it and sends the result back. A server tool, like Anthropic's web search, web fetch or code execution, runs on the provider's side during the same request: I declare it by type, and the response already contains the call, its result and the cited answer. I don't write a loop for it, though I handle pause_turn by sending the content back. Server tools for generic capabilities; client tools for anything touching my data or needing my permission checks."

What’s happening
  1. Server-tool errors arrive as data in a 200 response: a result block whose content is an error object. Branch on the shape.
  2. Web search results carry citations, which belong in the UI.
  3. Web content is untrusted input. A model with web access and a tool that acts is the classic injection setup.
  4. Server tools are billed on top of tokens, and their results are input tokens.
  5. Availability differs across the cloud platforms that host the models; check before designing around one.

Learn more: Server tools: web search, web fetch and code execution.

Forced tool choice is rejected on the newest Claude models. How do you make sure a tool gets called?
Show answer

First ask what the forced call was for. "On Claude Opus 5.5, Sonnet 5.5 and Fable 5.2, tool_choice any and tool return a 400. If I was forcing a fake tool just to get JSON, that's structured outputs now. If the call is a fixed first step, I call the function myself and put the result in the prompt. If I want the model to choose but strongly prefer a tool, I keep auto, state the rule in the prompt and the tool description, set strict, and check in code that a call came back, with one corrective re-prompt."

What’s happening
  1. auto and none still work everywhere. none keeps the tools in the request, so the prompt cache survives.
  2. auto never guarantees a call. The check afterwards is part of the pattern.
  3. Steps you can predict belong in code: that's the workflow-versus-agent distinction.
  4. The tool list is the strongest control. A model can't call a tool it wasn't given.
  5. Older models still accept forced choice, so this shows up as a migration bug: the only change was the model id.

Learn more: Controlling tool use.

#Embeddings and vector search questions

Added

Questions about turning text into vectors and searching them.

What is an embedding, and why use one for search?
Show answer

A fixed-length vector for a piece of text, trained so that similar meanings end up close together. "Once documents and queries are vectors, retrieval is nearest-neighbour search: embed the question, find the closest document vectors. That finds matches that share meaning but not words, like 'forgot my login' for 'reset my password'. I'd add the limits straight away: embeddings blur exact identifiers, numbers and negation, so production search combines them with keyword search and a reranker, and the model is chosen with an eval on our own queries."

What’s happening
  1. The model is an encoder: text in, a few hundred to a few thousand numbers out.
  2. "Close" is measured with cosine similarity or a dot product.
  3. Semantic match is the strength; exact-token match is the weakness.
  4. Embeddings are derived data: store the model version with every vector, because a new model means re-embedding everything.
  5. Anthropic doesn't offer an embedding model and points to Voyage AI.

Learn more: What embeddings are.

Cosine similarity or dot product?
Show answer

If the vectors are normalised to length 1, they rank identically, so I use the dot product because it's cheapest. "For unit vectors the dot product equals the cosine, and Euclidean distance orders results the same way. If the vectors aren't normalised, I normalise at write time or use cosine, because a raw dot product favours long vectors regardless of relevance. And the index's operator class has to match the operator in the query, or the index isn't used."

What’s happening
  1. Cosine measures the angle; the dot product is the angle scaled by both lengths.
  2. Normalise once, at write time, and the three metrics agree on ranking.
  3. A mismatch between index and query operator shows up as a correct but slow query: check the plan.
  4. Similarity scores aren't calibrated across models. A threshold tuned for one model means nothing for another.
  5. Compare ranks, not raw scores, when combining with keyword search.

Learn more: Measuring similarity: cosine, dot product and distance.

When do you need an approximate nearest neighbour index, and how do you know it's good enough?

Four test queries are shown with their relevant documents and what the index returned. What's recall@1, @3 and @5?

Show answer

When exact search no longer fits the latency or memory budget; and by measuring recall@k against exact search on real queries. "Exact search is linear in the collection size, simple and always correct, so I start there for thousands or low hundreds of thousands of vectors, or when a filter narrows the set. Past that, HNSW or IVF look at a small fraction of the vectors and occasionally miss a true neighbour. Recall@k is the share of the true results that appear in the top k; I tune the index until recall meets the target at acceptable latency."

rq-recall.mjsPlayground ↗
// For each query: the documents that should come back, and what the system returned, best first.
const queries = [
  { relevant: ["a", "b"], returned: ["a", "x", "b", "y", "z"] },
  { relevant: ["c"], returned: ["x", "y", "c", "z", "w"] },
  { relevant: ["d", "e"], returned: ["x", "d", "y", "z", "w"] },
  { relevant: ["f"], returned: ["x", "y", "z", "w", "v"] },
];
const recallAt = (k, q) => q.relevant.filter((doc) => q.returned.slice(0, k).includes(doc)).length / q.relevant.length;
for (const k of [1, 3, 5]) {
  const perQuery = queries.map((q) => recallAt(k, q));
  console.log(`recall@${k}: ${perQuery.map((r) => r.toFixed(2)).join(", ")} -> mean ${(perQuery.reduce((a, b) => a + b, 0) / queries.length).toFixed(3)}`);
}
Result
recall@1: 0.50, 0.00, 0.00, 0.00 -> mean 0.125
recall@3: 1.00, 1.00, 0.50, 0.00 -> mean 0.625
recall@5: 1.00, 1.00, 0.50, 0.00 -> mean 0.625
What’s happening
  1. Recall@k for one query is: relevant documents found in the top k, divided by relevant documents that exist.
  2. At k = 1 only the first query finds anything (one of its two documents): the mean is 0.125.
  3. At k = 3 the first two queries are complete and the third has one of two: 0.625.
  4. Going to k = 5 changes nothing. The third query's second document and the fourth query's only document were never returned: those are retrieval misses that no amount of reranking can fix.
  5. For an ANN index, the "relevant" set is what exact search returns. Raise ef_search (HNSW) or the probe count (IVF) until recall hits the target.

Learn more: Brute-force search and why it stops scaling and Approximate nearest neighbour indexes: HNSW and IVF.

How does HNSW work, and what do you tune?
Show answer

A layered graph you walk greedily from sparse top layers to the dense bottom one. "Every vector is in the bottom layer, linked to its near neighbours; a shrinking random subset also appears in higher layers with longer links. A search enters at the top, moves to the neighbour closest to the query, drops a layer when it can't improve, and at the bottom explores a candidate list of size ef_search to collect the top k. At build time, m sets links per node and ef_construction how thoroughly neighbours are searched. At query time, ef_search is the recall-versus-latency dial."

What’s happening
  1. Higher layers are an express network: long hops to get near the right region quickly.
  2. Larger m and ef_construction: better recall, more memory, slower builds.
  3. Larger ef_search: better recall, slower queries, no rebuild needed.
  4. Compared with IVF: better recall and latency and no retraining on inserts, at the cost of memory and build time.
  5. Always quote recall measured on your own held-out queries, not a default.

Learn more: Approximate nearest neighbour indexes: HNSW and IVF.

pgvector or a dedicated vector database?
Show answer

If we already run PostgreSQL, start with pgvector; move when the vector workload outgrows what we want the primary database doing. "pgvector keeps vectors next to the data they describe: one system to operate and back up, transactions that update a row and its embedding together, joins with users and permissions, and plain WHERE clauses for filters. It has HNSW and IVFFlat indexes and compressed types. I'd move to a dedicated store at hundreds of millions of vectors, very high query rates, or for built-in hybrid search and tiered storage."

What’s happening
  1. Size it first: vectors × dimensions × bytes, plus index overhead. HNSW indexes should fit in memory.
  2. Measure recall and latency at the expected size before deciding anything.
  3. A second system means a sync pipeline and a new way for data to be inconsistent.
  4. If Elasticsearch or OpenSearch already serves keyword search, its vector support is the natural hybrid option.
  5. Whatever the store, design ingestion so the whole index can be rebuilt from the source of truth.

Learn more: pgvector: vectors in PostgreSQL and Vector databases compared.

How do you combine vector search with a filter such as "this tenant only"?
Show answer

It depends on how selective the filter is, and for tenancy I enforce it structurally. "An approximate index explores a fixed candidate list, so filtering afterwards can leave too few results, or none. For a selective filter I pre-filter: an exact scan over the matching rows is cheap and perfectly accurate. For broad filters, post-filtering works. In between, filter-aware search: in pgvector, iterative index scans keep walking the graph until enough rows pass. For tenants, row-level security or per-tenant partitions, with a test that one tenant can never retrieve another's data."

What’s happening
  1. Post-filtering fails quietly: fewer results, not an error.
  2. Selectivity decides the plan, so know the distribution of your filters.
  3. Permissions are a filter too, and the one where a mistake is a security incident.
  4. Updates and deletes must reach the index promptly: a deleted document that still surfaces is a quality and a compliance problem.
  5. In a design interview, say "filter, then rank" and explain why the other order starves results.

Learn more: Filtering, multi-tenancy and updates.

We have embeddings. Why keep keyword search?
Show answer

Because they fail in opposite places. "Embeddings capture meaning and find paraphrases, but blur exact tokens: two different error codes can look almost identical to an embedding model. BM25 is exact about rare terms like error codes, SKUs, names and version numbers, and can't match a description in different words. So I run both, merge the rankings with reciprocal rank fusion, and rerank the top results with a cross-encoder."

What’s happening
  1. BM25 weights a term by how rare it is across the corpus and how often it appears in the document.
  2. Vocabulary mismatch is keyword search's failure; identifier blur is the embedding's.
  3. Fuse on ranks, because a BM25 score and a cosine similarity aren't on a common scale.
  4. The reranker fixes shallow agreement between the two lists, at a cost that's affordable for the top few dozen.
  5. Hybrid is cheap to add and usually the largest single improvement to a vector-only search.

Learn more: Keyword search still matters: BM25.

Ten million vectors at 1,024 dimensions. How much memory, and how do you cut it?
Show answer

About 41 GB as float32, before index overhead; half that at half precision, a quarter as int8, and about 1.3 GB as binary with rescoring. "The arithmetic is vectors × dimensions × bytes, so I look at all three factors: fewer dimensions if the model supports truncation, fewer bytes with quantisation, and I measure recall@k against exact search before and after, on real queries, because models differ in how well they quantise."

rq-vector-memory.mjsPlayground ↗
const vectors = 10e6, dims = 1024;
const formats = { "float32 (4 bytes)": 4, "half precision (2 bytes)": 2, "int8 (1 byte)": 1, "binary (1 bit)": 1 / 8 };
for (const [name, bytesPerDim] of Object.entries(formats)) {
  console.log(`${name.padEnd(25)} ${((vectors * dims * bytesPerDim) / 1e9).toFixed(1).padStart(5)} GB`);
}
console.log(`256 dimensions as float32 ${((vectors * 256 * 4) / 1e9).toFixed(1).padStart(5)} GB`);
Result
float32 (4 bytes)          41.0 GB
half precision (2 bytes)   20.5 GB
int8 (1 byte)              10.2 GB
binary (1 bit)              1.3 GB
256 dimensions as float32  10.2 GB
What’s happening
  1. 10 million × 1,024 × 4 bytes is 41.0 GB of raw vectors. An HNSW index adds its graph on top.
  2. Half precision halves it for almost no loss. int8 is a 4× saving with very little recall loss.
  3. Binary is 32× smaller, 1.3 GB, but coarse: use the bits to shortlist candidates and re-rank them with fuller vectors (rescoring).
  4. Shortening to 256 dimensions also gives 4× (10.2 GB), if the model was trained to be truncated.
  5. The savings multiply (shorter and quantised), and so do the recall losses. Measure each step.

Learn more: Quantization and the cost of vectors and Choosing an embedding model.

#RAG questions

Added

Questions about retrieval-augmented generation: the pipeline, its stages, and how to tell whether it works.

What is RAG, and why use it rather than fine-tuning?
Show answer

Retrieve relevant passages from your own data at request time and put them in the prompt, so the model answers from them, ideally with citations. "It's the default for knowledge problems because the data stays outside the model: updating it is a re-index, not a training run; answers can cite sources; per-user permissions apply at retrieval time; and one base model serves many knowledge bases. Fine-tuning changes behaviour, like tone, format or a narrow skill, and is a poor way to add facts. And if the corpus is small and stable, putting it all in a cached prompt can beat both."

What’s happening
  1. Ask what has to change. Facts the model lacks: context or retrieval. Behaviour: prompting first, fine-tuning second.
  2. Small, stable knowledge that fits comfortably: a cached prompt is simplest and can't miss anything.
  3. Large, changing, permissioned or citable knowledge: RAG.
  4. They combine: RAG over a big corpus with a cached system prompt, or a small tuned model answering from retrieved chunks.
  5. Decide with numbers: cost per request for each option with caching included, latency, and the same eval run on both.

Learn more: What RAG is and when to use it and RAG, long context or fine-tuning?.

Walk me through a RAG system you'd build.
Show answer

Two paths: ingest, and query. "Ingest: load documents, split them along their structure into chunks of a few hundred tokens, keep each chunk's source, title and permissions, and index both embeddings and keywords. Query: rewrite follow-ups into standalone questions, run vector and keyword search in parallel and fuse them with reciprocal rank fusion, filter by the user's permissions, rerank the top thirty or so with a cross-encoder, and put the best five to ten chunks in the prompt with instructions to answer only from them, cite sources and say 'I don't know' otherwise."

What’s happening
  1. Each stage exists to fix a specific failure: chunking for precision, hybrid for recall, reranking for order, the prompt for faithfulness.
  2. Log the retrieved chunks with every answer. Without them a bad answer can't be diagnosed.
  3. Measure retrieval and answers separately, before tuning anything.
  4. Start simple: structure-aware chunks, one embedding model, top-k. Add stages when the eval shows which one is missing.
  5. Permissions are a filter in the retrieval query, never an instruction to the model.

Learn more: The RAG pipeline end to end.

How do you choose a chunking strategy and a chunk size?
Show answer

Start from the content's structure, then treat size as a parameter you measure. "For docs and help centres I split by headings and paragraphs, keep the heading path as a prefix, split oversized sections and merge tiny ones, and never break code blocks or tables. For unstructured text, fixed-size chunks with overlap. A few hundred tokens with some overlap is a common start. Then I build a labelled set of questions with the chunks that answer them, try two or three variants, and keep the one with the best recall@k."

What’s happening
  1. Too large: the chunk covers several topics, its embedding is an average of them, and it wastes prompt tokens.
  2. Too small: the chunk loses the context that gives it meaning ("this is not permitted" without the "this").
  3. A heading-path prefix is the free way to give a chunk its context.
  4. Parent-child retrieval: search small chunks, send the surrounding section to the model.
  5. There's no universal right size. It depends on the embedding model's limit, the answers' length and how many chunks you send.

Learn more: Chunking strategies.

How does reciprocal rank fusion work? Work one example.

One chunk is ranked 2nd by BM25 and 4th by dense retrieval. Another is 1st by dense and missing from BM25's list. Which wins, with k = 60?

Show answer

Each list gives a document 1 / (k + rank); the scores are added. The chunk that appears in both lists wins, by almost two to one. "RRF ignores raw scores, which matters because a cosine similarity and a BM25 score aren't on comparable scales, and it rewards documents that rank well in several lists. It needs no training or normalisation. In practice hybrid with RRF raises recall at k but doesn't always improve the top result, so I put a reranker after it."

rq-rrf.mjsPlayground ↗
const K = 60;
const rrf = (ranks) => ranks.reduce((sum, rank) => sum + 1 / (K + rank), 0);
const both = rrf([2, 4]); // 2nd by BM25, 4th by dense
const denseOnly = rrf([1]); // 1st by dense, absent from BM25
console.log(`in both lists (2nd and 4th): ${both.toFixed(5)}`);
console.log(`top of one list only:        ${denseOnly.toFixed(5)}`);
console.log(`winner: ${both > denseOnly ? "the chunk in both lists" : "the dense-only chunk"} (${(both / denseOnly).toFixed(2)}x)`);
Result
in both lists (2nd and 4th): 0.03175
top of one list only:        0.01639
winner: the chunk in both lists (1.94x)
What’s happening
  1. The chunk in both lists scores 1/62 + 1/64 = 0.03175.
  2. The dense-only chunk scores 1/61 = 0.01639, even though it was ranked first by one retriever.
  3. So agreement between retrievers beats one retriever's top pick. That's usually right, and it's also the weakness: a shallow keyword match can lift a mediocre result above a strong semantic one.
  4. k = 60 flattens the difference between neighbouring ranks, so no single list dominates.
  5. The same formula merges the results of several query rewrites, or any number of lists.

Learn more: Hybrid search and reciprocal rank fusion.

What does a reranker add, and how do you measure it?

On a 20-question test set, the first relevant chunk is ranked 1, 1, 2, 3 and "not found" for five of the questions. What's the MRR for those five?

Show answer

It fixes the order of a candidate list by scoring each query-document pair jointly; I measure it with MRR and recall at the k I actually send. "First-stage retrieval embeds query and documents separately, so it's fast and never sees them together. A cross-encoder reads both at once: more accurate, much slower. So I retrieve generously, rerank, and keep a handful. On this course's Meadowlark corpus, reranking lifted MRR from 0.800 for dense retrieval to 0.907, while hybrid search had the best recall@5 at 1.000: hybrid is the best candidate generator, the reranker the best orderer."

rq-mrr.mjsPlayground ↗
// Rank of the first relevant chunk for each question (null = not in the results).
const firstRelevantRank = [1, 1, 2, 3, null];
const mrr = firstRelevantRank.reduce((sum, rank) => sum + (rank ? 1 / rank : 0), 0) / firstRelevantRank.length;
const recallAt = (k) => firstRelevantRank.filter((rank) => rank && rank <= k).length / firstRelevantRank.length;
console.log(`MRR ${mrr.toFixed(3)}, recall@1 ${recallAt(1).toFixed(2)}, recall@3 ${recallAt(3).toFixed(2)}`);
// How much is one question worth on a test set of n questions?
for (const n of [20, 100, 500]) console.log(`n = ${n}: one question changes recall by ${(1 / n).toFixed(3)}`);
Result
MRR 0.567, recall@1 0.40, recall@3 0.80
n = 20: one question changes recall by 0.050
n = 100: one question changes recall by 0.010
n = 500: one question changes recall by 0.002
What’s happening
  1. MRR is the mean of 1 / rank of the first relevant result: (1 + 1 + 0.5 + 0.333 + 0) / 5 = 0.567.
  2. Recall@1 is 0.40 (two of five at rank 1); recall@3 is 0.80. The fifth question is a retrieval miss that no reranker can fix.
  3. Recall@k at the k you send caps answer quality: the model can't use a passage it wasn't given.
  4. With 20 questions, one question is 0.05 of recall. The course's own comparison of two reranked setups differed by a single question, which is noise, not a result.
  5. The robust conclusions from a small set are the big ones: "reranking clearly helps", "keywords alone are weak on this traffic".

Learn more: Reranking and Evaluating retrieval: recall@k, MRR and nDCG.

In a RAG chat, the user asks "and what about the yearly one?". What goes wrong, and how do you fix it?
Show answer

The retriever searches for a fragment that means nothing alone. Rewrite it into a standalone query first. "Before retrieval, a small fast model gets the recent conversation and the latest message and returns a standalone search query, such as 'refund policy for yearly plans'. Retrieval runs on the rewrite; the answering prompt still gets the original message and the conversation. For vague questions I can use HyDE, embedding a hypothetical answer, or multi-query with RRF. Each adds latency and cost, so I measure them and skip them when the message is already a clear query."

What’s happening
  1. Retrieval is stateless: it sees only the string you search with.
  2. The rewrite is a cheap call with a tiny output.
  3. HyDE works because an answer-shaped text sits closer to answer passages than a short question does.
  4. Multi-query covers several readings of an ambiguous question and raises recall.
  5. Put follow-ups and vague questions in the labelled set, or you'll never see this failure in an eval.

Learn more: Query rewriting, HyDE and multi-query.

How do you stop a RAG system making things up?
Show answer

Retrieval first, then a prompt that makes "I don't know" a real option, then citations my code can check. "If the right passage isn't retrieved, no prompt saves the answer, so I measure recall. Then: sources in clear delimiters, an instruction to answer only from them, an exact 'I don't know' sentence the code can detect and route to a human, and a citation for every claim. I use the API's citations where I can, or verify cited ids in code, and reject answers that cite something we didn't send. And I keep unanswerable questions in the eval set and track the abstention rate."

What’s happening
  1. A system that never says "I don't know" is guessing some of the time.
  2. Citations serve the user, who can check, and your code, which can verify.
  3. For high-stakes answers, add a check that each claim is supported by its cited passage.
  4. Fewer, better chunks beat many: irrelevant passages are material for wrong answers.
  5. Diagnose by stage: low recall is a retrieval fix; good recall with unfaithful answers is a prompt or model fix.

Learn more: Building the prompt: context, citations and "I don't know".

What is contextual retrieval?
Show answer

Adding a short, generated description of where a chunk sits in its document, before embedding and keyword indexing. "It's Anthropic's technique for chunks that lose meaning when cut out. At ingest time a model reads the whole document and writes 50 to 100 tokens of context for each chunk, which is prepended to it. In Anthropic's tests it cut retrieval failures by 35% with embeddings alone, 49% with BM25 as well, and 67% with reranking on top. It's affordable because every chunk of a document reuses the same cached document. I'd try the free version first, heading-path prefixes, and measure both."

What’s happening
  1. The failure it targets: "revenue grew 3%" with no company or quarter in the chunk.
  2. The cost is at ingest, once per chunk, and prompt caching makes the repeated document cheap.
  3. It helps most for contracts, manuals and reports with parallel sections.
  4. Those percentages are Anthropic's results on its benchmark. Your corpus needs its own measurement.
  5. It stacks with hybrid search and reranking rather than replacing them.

Learn more: Contextual retrieval.

When would you let the model drive retrieval, instead of a fixed pipeline?
Show answer

When a question needs more than one lookup, or the right second search depends on the first result. "Comparisons, multi-part questions, investigations across several sources. I'd give the model a well-described search tool that returns a few results with sources, let it search, read and search again, and cap the loop with a step and token budget. It costs more latency and tokens and is less predictable, so simple lookups keep the fixed pipeline, and I'd route between the two."

What’s happening
  1. A fixed pipeline retrieves once, with the user's words. That's enough for most questions.
  2. Agentic RAG is the agent loop with a search tool: everything about limits and trajectories applies.
  3. Evaluate the trajectory as well as the answer: did it search for the right things, in how many steps?
  4. The final answer must still be supported by what was found.
  5. Use the simplest shape that passes the eval.

Learn more: Agentic RAG and GraphRAG.

#Agents questions

Added

Questions about workflows, the agent loop and keeping agents reliable.

What's the difference between a workflow and an agent?
Show answer

Who decides the next step. "In a workflow my code owns the control flow: the steps are fixed and the model does the work inside each. In an agent the model owns it: given a goal and tools, it decides at each step what to do, in a loop, from what the last tool returned. I use a workflow whenever I can write the steps down, because it's predictable, cheaper and testable. I use an agent when the steps can't be predicted, the outcome is worth many model calls, and mistakes can be caught or undone."

What’s happening
  1. An agent is a model, tools and a loop. The definition most interviewers know is Anthropic's: LLMs using tools based on environmental feedback in a loop.
  2. The test: can you draw the flowchart? If yes, build the flowchart.
  3. Four checks before building an agent: hard to specify, valuable enough, within the model's ability, and recoverable when wrong.
  4. Most production "agents" are one or two workflow patterns with a small agentic step.
  5. Start with the simplest thing; add autonomy when an eval shows it's needed.

Learn more: What an agent is.

Name the common workflow patterns and when each fits.
Show answer

Chaining, routing, parallelisation, orchestrator-workers and evaluator-optimiser. "Chaining is a fixed sequence with code checks between steps, for tasks with clean stages. Routing classifies the input and sends it to a specialised prompt or model. Parallelisation runs calls at once: sectioning for different aspects, voting for the same question several times. Orchestrator-workers lets a model decide the subtasks at run time. Evaluator-optimiser loops a generator against a critic until the output passes. They're from Anthropic's 'Building effective agents', and I'd reach for them before a free-running agent."

What’s happening
  1. Chaining: gate between steps with code; errors otherwise carry forward as if they were facts.
  2. Routing: a small model with an enum output; always have a fallback route for low confidence.
  3. Parallelisation: latency is the slowest call; cost is the sum.
  4. Orchestrator-workers: the plan is model output, so validate it and cap the fan-out in code.
  5. Evaluator-optimiser: needs explicit criteria and a round limit; a code check beats a model check whenever one exists.

Learn more: Workflow patterns: chaining, routing and parallelisation and Orchestrator-workers and evaluator-optimiser.

How do you stop an agent running forever or spending too much?
Show answer

With limits enforced in my code, outside the model. "The model's own decision to stop is the one thing I can't rely on. So I cap loop iterations, keep a running total of tokens and cost from every response's usage and stop past a budget, pass a deadline as an abort signal to the model call and every tool, and detect repetition by hashing each tool call's name and arguments. When a limit fires I return a distinct status with the partial trajectory, so nobody mistakes it for success."

What’s happening
  1. Each limit catches a different failure: steps for wandering, budget for a few huge steps, repeat detection for identical calls.
  2. The repeat key must include the arguments, or legitimate refinement gets stopped.
  3. Tools need their own bounds: timeouts and result size limits.
  4. end_turn means the model stopped, not that the task succeeded. Verify completion with something other than the agent's word.
  5. Set the numbers from traces of real runs, and alert when runs hit them.

Learn more: The agent loop in code.

Each step of your agent is right 95% of the time. Is that good enough?
Show answer

For a five-step task, maybe; for a twenty-step task, no: it succeeds about 36% of the time. "An agent is a chain of decisions, and success multiplies. There are three ways to improve a product of probabilities, and every reliability technique is one of them: make each step more reliable, mostly through tool design; make the chain shorter, by doing predictable steps in code; or catch and repair errors, with checks against real feedback like tests and validators."

rq-compounding.mjsPlayground ↗
const success = (perStep, steps) => perStep ** steps;
const pct = (x) => `${(x * 100).toFixed(1)}%`;
for (const p of [0.95, 0.99]) {
  console.log(`${pct(p)} per step: ${[5, 10, 20, 50].map((n) => `${n} steps ${pct(success(p, n))}`).join(", ")}`);
}
// A check after each step that catches 90% of errors and allows one retry.
const withCheck = (p, caught) => 1 - (1 - p) * ((1 - caught) + caught * (1 - p));
console.log(`95% steps with such a check: ${pct(withCheck(0.95, 0.9))} per step, ${pct(success(withCheck(0.95, 0.9), 20))} over 20 steps`);
Result
95.0% per step: 5 steps 77.4%, 10 steps 59.9%, 20 steps 35.8%, 50 steps 7.7%
99.0% per step: 5 steps 95.1%, 10 steps 90.4%, 20 steps 81.8%, 50 steps 60.5%
95% steps with such a check: 99.3% per step, 86.5% over 20 steps
What’s happening
  1. At 95% per step: 77.4% over 5 steps, 59.9% over 10, 35.8% over 20, 7.7% over 50.
  2. At 99% per step, 20 steps succeed 81.8% of the time. Each extra "nine" per step is worth far more end to end than it looks.
  3. A check that catches 90% of errors and allows one retry lifts a 95% step to about 99.3%, and the 20-step task to about 86.5%.
  4. That's why agents work best where the environment pushes back: compilers, tests, schema validators.
  5. And why the highest-value work is usually on the tools: clear names, enums, mistake-proof arguments.

Learn more: Why agents fail and how to make them reliable.

An agent's conversation is outgrowing the context window. What do you do?
Show answer

Treat the context as a budget and manage it before it's full. "First keep big things out: tools return trimmed, bounded results. Second, clear what's stale: old tool results replaced by placeholders, which the Claude API can do server-side with context editing. Third, compact: summarise older turns into a short state description that keeps the goal, the facts, the decisions and what's left; there's a server-side version of that too. Fourth, anything that must survive the session goes to external memory. Every edit of history is a prompt-cache miss, so I compact rarely and in bulk."

What’s happening
  1. Clearing keeps the conversation's structure and loses raw outputs. Compaction keeps the gist and loses detail.
  2. With server-side compaction, append the whole response content, or the compaction block is lost.
  3. A summary can drop the one detail that mattered, so critical state is written down explicitly.
  4. Long-term memory is storage outside the context: files, a database or a vector store, per user.
  5. Memory is an injection surface and personal data: decide what may be saved and who can see it.

Learn more: Memory and context management.

When would you use several agents instead of one?
Show answer

When the task is broad and parallel, and the limit is context. "A single agent researching many sources fills its window with pages it needed once. Subagents each get a fresh context, do the reading there and return a short report, so the lead stays small; they can run in parallel and on a cheaper model. Anthropic reported about a 90% improvement on its internal research eval from this design, at roughly fifteen times the tokens of a chat. I wouldn't use it where the pieces share context or depend on each other, which is most coding work."

What’s happening
  1. The benefit is clean contexts, not extra intelligence.
  2. The brief is the subagent's whole world: objective, output format, sources and boundaries.
  3. Errors arrive at the lead as confident sentences with the evidence left behind. Ask for sources.
  4. Cap the fan-out in code, and scale effort to the question.
  5. The default remains one agent with good tools and context management.

Learn more: Multi-agent systems.

How do you add human approval to an agent that can issue refunds?
Show answer

Classify tools by risk in code, pause before the risky call, persist the state, and resume with a decision. "Reads run automatically. When the model requests the refund, the loop doesn't execute it: it saves the messages array, including the assistant message with the pending call, and returns a needs-approval status with the tool name and exact arguments. A human approves, edits or declines. On resume I run the tool, or build a result saying a human declined and what to do instead, append all results in one message and continue. The state is plain JSON, so the wait can be days."

What’s happening
  1. Policy lives in code. A prompt rule can be talked around; an if can't.
  2. Show the real arguments, not the model's description of its intent.
  3. Bind each approval to one tool call id and its arguments. An approval for €49 isn't one for €4,900.
  4. A declined call is still answered with a tool result, so the conversation stays valid.
  5. Ask rarely enough that people still read what they approve.

Learn more: Human in the loop.

Which agent framework would you pick?
Show answer

Whichever supplies what I'd otherwise have to build. "For tool calling inside my own backend, the provider SDK: a manual loop or its tool runner. If the agent needs a filesystem and a shell, I won't build that sandbox: Claude Managed Agents if Anthropic can host the loop and the container, the Claude Agent SDK if it must run on my machines. For durable, resumable workflows with explicit structure, LangGraph. To stay provider-neutral and stream into a React UI, the AI SDK. Whatever I pick, I need to see the raw prompts, set my own limits and intercept tool calls."

What’s happening
  1. Two questions sort the options: who supplies the harness, and who supplies the compute.
  2. Frameworks help you start and can hide the prompts you'll need when debugging.
  3. Write the loop by hand once. Every framework contains it.
  4. Keep tools as plain functions with schemas, or as MCP servers, so they outlive the framework choice.
  5. MCP standardises how tools are connected. Approval, permissions and result trimming stay in your harness.

Learn more: Agent frameworks and platforms and Giving agents tools with MCP.

#Full-stack AI questions

Added

Questions about putting a model behind a real web application.

Why can't the front end call the model API directly?
Show answer

The API key, first; and then everything else the server is for. "Anything shipped to the browser is public, so a key there is in every user's dev tools. But I'd want my server in the middle anyway: it authenticates the user and enforces quotas, owns the system prompt, tools, model and token limits so a client can't change them, runs tools with the user's permissions, stores the conversation because the API is stateless, and handles retries, timeouts and logging. The browser sends the user's words and a conversation id. The server builds the request."

What’s happening
  1. An environment variable read by front-end code is compiled into the bundle. It isn't secret.
  2. A client that can send its own system prompt or model has turned your endpoint into a free general-purpose model.
  3. History sent by the client can be forged, including what the "assistant" said. Load it from your database.
  4. The one number that decides where the server code runs: how long can a single request take?
  5. Reduce what goes back to the browser too: the text and what the UI needs, not the raw provider response.

Learn more: The architecture of an AI feature.

How do you stream a model's answer to the browser?
Show answer

Two hops, both streaming: model to my server with the SDK, my server to the browser over server-sent events. "The response has content type text/event-stream and stays open; I write one small event per text delta, then a final event with the stop reason and usage, or an error event. I translate into my own minimal format so the client isn't tied to the provider's. In the browser I read response.body with fetch, a streaming TextDecoder and a split on blank lines, because EventSource can't POST."

What’s happening
  1. Chunk boundaries are arbitrary: buffer until a complete event, and decode with one decoder in streaming mode so split characters survive.
  2. "Works locally, arrives in one lump in production" is buffering in between: a reverse proxy, compression, or a platform that buffers responses.
  3. Send keep-alive comments so idle timeouts don't cut a slow first token.
  4. Respect backpressure when writing, and abort the model call when the client disconnects.
  5. In React, the AI SDK's streamText and useChat are these same two halves with a defined protocol.

Learn more: Streaming from the server to the browser and A chat UI in React with the AI SDK.

How would you build the chat UI itself, in React or in Angular?
Show answer

A list of messages made of typed parts, a status that drives the controls, and a stream that updates the last message. "In React I'd use the AI SDK's useChat: it posts the message, reads the stream, updates state as deltas arrive, and exposes a status of ready, submitted, streaming or error. In Angular I'd read the stream with fetch in a service and write each delta into a signal, which re-renders only the bindings that read it. Either way: a thinking indicator before the first token, Stop while streaming, an error with retry, and model text rendered as text or sanitised Markdown."

What’s happening
  1. A message isn't a string. One assistant turn can hold text, a tool call with its result, and more text, in order.
  2. submitted to streaming is the time to first token. Give that state its own indicator.
  3. Stop aborts the fetch; the route must pass that through to the model call.
  4. Stopping isn't an error: keep the partial text.
  5. Never bind model output to raw HTML.

Learn more: A chat UI in React with the AI SDK and Streaming in Angular.

What is generative UI?
Show answer

Letting the model choose which component to show, not only which words. "The model is given tools; when it calls one, the front end renders a component for that tool's result: an order card, a chart, a confirmation dialog. The model supplies structured data validated against a schema, and my code owns the rendering, so nothing the model writes is executed as markup. A tool call arrives as a typed part of the message with states for input streaming, input available, output available and error, and each state gets its own UI."

What’s happening
  1. The model picks from a menu of components. It never writes HTML.
  2. Every state is something a user sees: a skeleton, the component, or an error.
  3. Validate data before rendering it, especially when it came from the model's arguments.
  4. What the model can refer to later is the tool result, not your pixels.
  5. A chat endpoint with tools is an agent loop: cap the steps.

Learn more: Tool calls and generative UI.

How do you store conversations, and what do you send to the model on turn twenty?

A chat has a 1,000-token system prompt and grows by 300 tokens per turn. Compare sending everything with trimming history to 2,500 tokens.

Show answer

Store every message as an append-only row with its full content blocks; send a view: the system prompt, maybe a summary, and the recent turns that fit a token budget. "Over twenty turns, sending everything bills 77,000 input tokens; trimming history to 2,500 bills 58,300, and the gap widens every turn. I trim on turn boundaries so a tool call is never separated from its result, and in steps so the prompt-cache prefix stays stable."

rq-history-cost.mjsPlayground ↗
const system = 1_000, perTurn = 300, turns = 20, historyBudget = 2_500;
let everything = 0, trimmed = 0;
for (let turn = 0; turn < turns; turn++) {
  const history = perTurn * turn;
  everything += system + history;
  trimmed += system + Math.min(history, historyBudget);
}
console.log(`sending everything: ${everything.toLocaleString("en-US")} input tokens over ${turns} turns`);
console.log(`history trimmed to ${historyBudget.toLocaleString("en-US")} tokens: ${trimmed.toLocaleString("en-US")} (${Math.round((1 - trimmed / everything) * 100)}% less)`);
console.log(`last turn alone: ${(system + perTurn * (turns - 1)).toLocaleString("en-US")} vs ${(system + historyBudget).toLocaleString("en-US")} tokens`);
Result
sending everything: 77,000 input tokens over 20 turns
history trimmed to 2,500 tokens: 58,300 (24% less)
last turn alone: 6,700 vs 3,500 tokens
What’s happening
  1. Without trimming, turn n sends the system prompt plus 300 × n tokens: 77,000 in total by turn twenty.
  2. With a 2,500-token budget, growth stops after the ninth turn: 58,300 in total, 24% less, and every later turn is capped at 3,500 tokens where the untrimmed one has reached 6,700.
  3. Store the content blocks as JSON, not just text: tool calls and results must be replayed exactly.
  4. The owner comes from the session, and every query checks it.
  5. What trimming forgets, a rolling summary can keep. Update it in the background.

Learn more: Storing conversations.

A user clicks Stop mid-answer. What should happen, end to end?
Show answer

The abort has to travel the whole chain: browser, my server, the model provider. "The browser aborts its fetch, which closes the connection; the UI keeps the partial text. My server notices the client is gone, through the response's close event or the request's abort signal, and aborts its streaming call to the model, which is where the saving is, because output tokens stop being generated. The same signal goes to any running tool. Then I save the partial message, marked as stopped by the user."

What’s happening
  1. The classic bug is a Stop that only stops the UI while the server keeps consuming the model stream.
  2. Verify cancellation where it counts: the upstream request was aborted.
  3. Timeouts are the same mechanism with your code pressing Stop: one timeout per attempt, one deadline for the whole operation.
  4. The SDK retries timeouts, so a 30-second timeout with two retries can hold a request for over 90 seconds.
  5. Never retry silently after output has been shown, and never retry a step whose tools had side effects unless they're idempotent.

Learn more: Cancellation, timeouts and retries end to end.

How do you rate limit an AI feature?
Show answer

In tokens and money, not request counts. "Requests vary in cost by orders of magnitude. Every request is authenticated, and the server sets the model and max_tokens. Per user I keep a token bucket, tokens per minute with a burst, in shared storage, and a daily or monthly spending quota tied to their plan. Before the call I reserve a worst-case estimate; after it I settle against the real usage from the response. Around that: input size limits, a global budget with alerts, and limits that add up to less than my own provider rate limit."

What’s happening
  1. An unauthenticated AI endpoint is an open tap on your account.
  2. A bucket stops bursts. Only a budget stops a steady drain.
  3. Reserve then settle, because the cost isn't known until the model has answered.
  4. Charge for what was generated even when the user stopped.
  5. Make limits visible: "80% of today's allowance used" is a feature; a bare 429 is a support ticket.

Learn more: Auth, quotas and per-user rate limits.

How would you build "chat with your PDF"?
Show answer

Give the model the document directly if it fits, with citations and caching; build retrieval only when it doesn't. "The file goes from the browser to object storage through a pre-signed URL after an auth and quota check. A worker validates it by its real bytes, size and page count. For one document that fits the context, I send it as a document block before the question, referenced by a provider file id uploaded once, with citations on so the UI shows the page behind each claim, and a cache breakpoint after it so follow-ups are cheap. Too large, or many documents: extract, chunk, embed, retrieve."

What’s happening
  1. Identify the file from its first bytes, not its name or the content type the browser claimed.
  2. A file's tokens are billed on every request that includes it. Caching turns twelve full reads into one write and eleven cheap reads.
  3. Count tokens before sending a large document, and show the cost against the quota.
  4. The document is untrusted input: no tools that act, or tools that need confirmation.
  5. Files are private data, including the copy at the provider. Plan deletion.

Learn more: File uploads and multimodal features and UX patterns for AI features.

#Evals questions

Added

Questions about measuring whether an AI feature works, before and after launch.

How do you know your LLM feature works?
Show answer

I don't trust spot checks. I build an eval. "A set of realistic inputs, from logs where possible, each with an agreed expected outcome. Graders that score each output: code checks first, and an LLM judge calibrated against human labels for what code can't check. A harness that runs the set, ideally several times per case, and reports scores, cost and latency. I run it on every prompt or model change and compare case by case, so I see regressions as well as fixes. Every production failure becomes a new case."

What’s happening
  1. Trying three prompts by hand is a demo. An eval is what lets you change things with confidence.
  2. Compare case by case: the same headline score can hide five fixes and five new failures.
  3. Keep a held-out split you don't tune on.
  4. Evaluate more than correctness: format, safety, cost and latency are properties too.
  5. After launch, the eval continues online, on real traffic.

Learn more: Why evals are the core skill.

How do you build an eval set, and how big should it be?
Show answer

From real data first, with edge cases added on purpose, sized by the decision it has to support. "Sample production or beta traffic, anonymise it, and have domain experts label the right outcome against a written guide. Add known failure modes: other languages, multiple requests, empty or adversarial inputs, questions that should get 'I don't know'. Fill gaps with model-generated cases a person reviews. The noise is about one over the square root of cases times runs, so 25 cases finds big problems and a few hundred are needed for small differences."

rq-noise-floor.mjsPlayground ↗
// Rule of thumb from the evals chapter: noise floor in percentage points is about 100 / sqrt(cases x runs).
for (const [cases, runs] of [[12, 1], [25, 1], [50, 2], [100, 2], [400, 2]]) {
  console.log(`${String(cases).padStart(3)} cases x ${runs} run${runs > 1 ? "s" : " "}: differences under about ±${Math.round(100 / Math.sqrt(cases * runs))} points are noise`);
}
Result
 12 cases x 1 run : differences under about ±29 points are noise
 25 cases x 1 run : differences under about ±20 points are noise
 50 cases x 2 runs: differences under about ±10 points are noise
100 cases x 2 runs: differences under about ±7 points are noise
400 cases x 2 runs: differences under about ±4 points are noise
What’s happening
  1. Twelve cases, one run each: about ±29 points. A two-case difference tells you nothing.
  2. Fifty cases run twice: about ±10. A hundred run twice: about ±7. Four hundred run twice: about ±4.
  3. So a set of a few dozen is for finding big problems, which is what early development needs.
  4. Tag cases by category and source, and split off a stratified held-out set.
  5. The set keeps growing: every production failure is a case you didn't have to invent.

Learn more: Building an eval set.

When do you use a code grader, and when an LLM judge?
Show answer

Code first, whenever the property is checkable. "Labels, extracted fields, JSON schemas, formats, numeric tolerances, generated code run against tests, SQL against a fixture database, an agent's end state. It's free, fast, deterministic and doesn't drift. I use an LLM judge for what code can't see: whether an answer is faithful to its sources, helpful or complete. Even then I split it into specific yes-or-no criteria with a rubric and structured output. And I test my graders with known-bad outputs, because a lenient grader produces great-looking numbers that mean nothing."

What’s happening
  1. Exact match is right for labels and wrong for prose.
  2. Running generated code against tests is the strongest grader there is.
  3. A judge costs money and time on every run, and its verdicts vary.
  4. Break "is it good?" into criteria a person could apply consistently.
  5. A grader is code that needs its own tests: feed it answers you know are wrong.

Learn more: Code-graded evals.

Your LLM judge agrees with human labels 80% of the time. Is that good?

Both the judge and the person passed 6 of the 10 answers.

Show answer

It's moderate: Cohen's kappa is 0.58, because a lot of that agreement would happen by chance. "I treat the judge like any other model component and evaluate it. The prompt has concrete, separately scored yes-or-no criteria, uses structured output, wraps the graded text in tags as data, and says not to reward length. For comparisons I run both orders and count a disagreement as a tie, because judges have position bias. Then I calibrate against people, and if kappa is low I fix the rubric before trusting the scores."

rq-kappa.mjsPlayground ↗
// Cohen's kappa: agreement beyond what chance alone would give.
function kappa(agreement, judgePassRate, humanPassRate) {
  const chance = judgePassRate * humanPassRate + (1 - judgePassRate) * (1 - humanPassRate);
  return chance === 1 ? 0 : (agreement - chance) / (1 - chance);
}
console.log(`80% agreement, both pass 60%: chance ${(0.6 * 0.6 + 0.4 * 0.4).toFixed(2)}, kappa ${kappa(0.8, 0.6, 0.6).toFixed(2)}`);
// A judge that always says "pass", on a set where people pass 90% of answers.
console.log(`a judge that passes everything, people pass 90%: agreement 90%, kappa ${kappa(0.9, 1, 0.9).toFixed(2)}`);
Result
80% agreement, both pass 60%: chance 0.52, kappa 0.58
a judge that passes everything, people pass 90%: agreement 90%, kappa 0.00
What’s happening
  1. If both sides say "pass" 60% of the time, they'd agree by chance on 0.6 × 0.6 + 0.4 × 0.4 = 0.52 of cases.
  2. Kappa is the agreement above that, scaled: (0.80 − 0.52) / (1 − 0.52) = 0.58. Moderate, not strong.
  3. A judge that passes everything agrees with people 90% of the time on a set that's 90% good, and its kappa is 0: it can't detect a single bad answer.
  4. So the calibration set must contain real failures, and you report kappa or agreement on the failures.
  5. Position bias shows up when the judge picks whichever answer is shown first, in both orders. Count that as a tie.

Learn more: LLM-as-judge.

How do you evaluate a RAG system, and why not score answers by embedding similarity to a reference?
Show answer

Retrieval and generation separately; and similarity measures topic overlap, not correctness. "Retrieval: a labelled set, recall at the k I send, plus precision and MRR. Generation: faithfulness, by splitting answers into claims and having a calibrated judge check each against the retrieved context; answer relevance; and correctness against references, checked by facts. In this course's RAG eval, the one answer that contradicted its source scored 0.00 on faithfulness and the highest similarity to the reference, 0.85, while a correct but incomplete answer scored the lowest, 0.65."

What’s happening
  1. Separate scores tell you what to fix: low recall is retrieval; good recall with low faithfulness is the prompt or the model.
  2. "Yes, there's an Android app" and "No, use the browser on Android" are about the same topic, so their embeddings are close.
  3. Faithfulness asks a different question: is each claim supported by the passages that were retrieved?
  4. Include unanswerable questions and track the "I don't know" rate.
  5. In production, run the faithfulness check on a sample of live answers.

Learn more: Evaluating RAG: faithfulness, relevance and context recall.

An agent succeeds on a task in 3 of 4 runs. How reliable is it?
Show answer

pass@1 is 0.75, but the chance that two runs both succeed is 0.50, and that all four do is zero. "Agents are inconsistent, so I run each task several times and report pass^k, the chance that all k runs succeed, alongside the average. I grade outcomes first: run the task in a disposable environment and check the end state in code, like the refund issued once for the right amount. Then a few hard trajectory rules, such as never refunding without looking up the order, without requiring one exact path."

rq-pass-k.mjsPlayground ↗
// From n recorded runs with c successes: pass@k = at least one of k runs succeeds; pass^k = all k succeed.
const choose = (n, k) => (k > n ? 0 : [...Array(k).keys()].reduce((acc, i) => (acc * (n - i)) / (i + 1), 1));
const passAt = (n, c, k) => 1 - choose(n - c, k) / choose(n, k);
const passAll = (n, c, k) => choose(c, k) / choose(n, k);
const n = 4, c = 3;
console.log(`${c}/${n} runs succeeded`);
for (const k of [1, 2, 4]) console.log(`k = ${k}: pass@${k} ${passAt(n, c, k).toFixed(2)}, pass^${k} ${passAll(n, c, k).toFixed(2)}`);
Result
3/4 runs succeeded
k = 1: pass@1 0.75, pass^1 0.75
k = 2: pass@2 1.00, pass^2 0.50
k = 4: pass@4 1.00, pass^4 0.00
What’s happening
  1. With one run, both measures are the plain success rate: 0.75.
  2. pass@4 is 1.00: at least one of four runs worked. That's the right measure when a user can retry and pick, like code generation with tests.
  3. pass^2 is 0.50 and pass^4 is 0.00: the right measure when every run must be right, like bookings and refunds. Nobody gets to choose the better of two refunds.
  4. The same agent looks reliable or unusable depending on which number you quote, so say which one the product needs.
  5. Failures go to error analysis through the recorded traces, and each becomes a regression task.

Learn more: Evaluating agents.

How do you test LLM features in CI?
Show answer

In layers: mocked unit tests on every push, and the real-model eval suite as a gate. "Unit tests mock the model, with the AI SDK's mock model or an injected fetch for the Anthropic SDK, and cover my code: the request it sends, parsing clean, messy and malformed replies, refusals, max_tokens cut-offs, retries and streaming. They're fast and free. A prompt snapshot test makes prompt changes visible in review. The eval suite runs when prompts, models or retrieval change, and nightly: if the score drops below the baseline beyond the noise floor, the change doesn't merge."

What’s happening
  1. Mocked tests check your code, not the model. Both are needed.
  2. Assert properties, not exact text: "valid JSON with these fields", not a string comparison.
  3. For flaky cases, require a pass rate over several runs.
  4. The gate's threshold comes from the measured noise floor, or it blocks good changes and lets bad ones through.
  5. The scripted-reply examples throughout this course are this technique.

Learn more: Testing AI code in CI.

How do you evaluate a feature after it has launched?
Show answer

On real users: experiments, implicit signals and daily monitoring. "I A/B test meaningful changes with a metric and sample size fixed in advance, randomised by user, and check guardrails like cost, latency and escalation rate. I collect explicit feedback and, more importantly, implicit signals: retries, heavy edits, copies, abandonments, escalations. And a sample of live traffic is graded every day with code checks and a calibrated judge, tracked over time, with alerts set from measured variance. Low-scoring conversations go into error analysis."

What’s happening
  1. Offline evals say it's good on your cases. Online says whether those cases resemble reality.
  2. Few users click a thumb. Almost all of them retry, edit or leave, and that behaviour is the signal.
  3. Decide the metric and the sample size before looking, or you'll find a win in the noise.
  4. Monitoring catches drift: inputs change even when your code doesn't.
  5. The interesting live failures become eval cases, closing the loop.

Learn more: Online evaluation: A/B tests, feedback and monitoring.

Quality is "not great". How do you improve it systematically?
Show answer

Error analysis: read the failures, group them, fix the biggest group, re-run everything. "I run the eval, then actually read the failures, writing a short note on each, and group the notes into a handful of categories. I count them, pick the biggest or most severe, and make one change aimed at it: a prompt fix, a retrieval change, a tool, sometimes a product change. Then I re-run the whole set to confirm the fix and catch regressions. Each category becomes permanent eval cases and often a new automated grader."

What’s happening
  1. A score says how many failed. Only reading says why.
  2. Categories turn fifty individual failures into three problems with sizes.
  3. One change at a time, or you can't tell which one helped.
  4. Re-run the whole set: fixes for one category routinely break another.
  5. It feels slow and it's faster than tweaking prompts by intuition, because effort goes to failures that actually happen.

Learn more: The improvement loop: error analysis.

#Production questions

Added

Questions about running an AI feature: latency, cost, caching, routing, limits, observability and rollouts.

Users say the AI feature is slow. What do you do?
Show answer

Measure where the time goes, then work the levers in order of payoff. "Time to first token against generation time, per request, at p50 and p95, plus how many sequential model calls each user action makes. Then: stream, so users see text at the first token. Shorten the output, because generation usually dominates. Run independent calls in parallel. Cut time to first token with prompt caching and a smaller prompt. Lower effort or route simple requests to a smaller, faster model, checked with evals. And show progress while the model is thinking."

What’s happening
  1. Two different delays with different fixes: a long prompt delays the first word; a long answer delays the last.
  2. Three sequential two-second calls are six seconds. In parallel they're two.
  3. Fast mode on Opus 5.5 trades price for output speed, for premium paths.
  4. Alert against a rolling baseline, per route, so a longer prompt or a model change shows up as a regression.
  5. Check that every latency win kept quality, on the eval set.

Learn more: Latency: time to first token and throughput.

Cut this feature's cost in half without hurting quality. Where do you start?
Show answer

With metering, then the free wins, then the trade-offs, each checked against an eval. "Cost per feature split into uncached input, cache writes, cache reads and output. Free wins: prompt caching on the static prefix, the Batch API for anything offline at half price, and shorter outputs, since output is five times the input price. Then trade-offs: lower effort per route, fewer retrieved chunks, a smaller model where quality holds. And I report cost per completed task, not per request."

rq-cost-per-task.mjsPlayground ↗
// If a task is retried until it succeeds, cost per completed task = cost per attempt / success rate.
const options = [
  { name: "large model", perAttempt: 0.012, successRate: 0.95 },
  { name: "small model", perAttempt: 0.004, successRate: 0.3 },
  { name: "small model, better prompt", perAttempt: 0.004, successRate: 0.8 },
];
for (const o of options) {
  console.log(`${o.name.padEnd(27)} $${o.perAttempt.toFixed(4)} per attempt, ${(1 / o.successRate).toFixed(1)} attempts per success, $${(o.perAttempt / o.successRate).toFixed(4)} per completed task`);
}
Result
large model                 $0.0120 per attempt, 1.1 attempts per success, $0.0126 per completed task
small model                 $0.0040 per attempt, 3.3 attempts per success, $0.0133 per completed task
small model, better prompt  $0.0040 per attempt, 1.3 attempts per success, $0.0050 per completed task
What’s happening
  1. Per attempt, the small model is a third of the price. That's the number a per-request dashboard shows.
  2. At a 30% success rate it needs 3.3 attempts per success: $0.0133 per completed task, more than the large model's $0.0126.
  3. With a prompt that lifts it to 80%, it's $0.0050 per completed task, and the saving is real.
  4. This simple model leaves out what failures cost elsewhere: latency for the user and human time to catch and fix them, which often outweigh the tokens.
  5. So the unit to report is the completed task, and the success rate comes from the eval.

Learn more: Controlling cost.

Would you put a semantic cache in front of the model?
Show answer

Carefully, and only for the right traffic; an exact cache first. "An exact cache keyed on prompt version, model and normalised input is always safe. A semantic cache returns a stored answer for anything similar enough, so 'cancel my order' can get the answer to 'cancel my subscription'. I'd use it only for non-personal, slowly changing answers such as an FAQ, pick the similarity threshold from labelled query pairs, scope entries by tenant, add a TTL and invalidate when the source changes. For personalised or high-stakes answers I'd skip it."

What’s happening
  1. Don't confuse it with prompt caching: that caches the provider's processing of a prefix, and the model still generates a fresh answer.
  2. A false hit is a confidently wrong answer served instantly.
  3. The threshold is a measured trade between hit rate and false hits, not a default.
  4. A cache keyed without tenant or user is a data leak.
  5. Watch negative feedback on cached answers separately.

Learn more: Caching responses: exact and semantic caching.

How do you design model routing and fallbacks?
Show answer

Route by task to the cheapest model that passes that route's eval, and give each route an ordered fallback chain. "Rules first, a small classifier where rules aren't enough. On Opus 5.5, Sonnet 5.5 or Fable 5.2 I'd enable server-side refusal fallbacks, so a classifier false positive is answered by another model in the same call. In my own code I fall back on transient failures after the SDK's retries, never on 400s, which are bugs. A circuit breaker stops an outage adding a timeout to every request."

What’s happening
  1. A router is a classifier: measure its accuracy, and what a misroute costs.
  2. Run the eval set on the fallback models too. Prompts don't transfer perfectly.
  3. Prompt caches are per model, so a switch brings a cost and latency spike.
  4. Log every attempt, so the fallback rate is a visible metric.
  5. A refusal is an HTTP 200: fallback logic keyed on status codes never sees it.

Learn more: Model routing and fallbacks.

How do you keep a busy service inside the provider's rate limits?
Show answer

Know the limits in every dimension and shape traffic to them. "Requests, input tokens and output tokens per minute, per model. Interactive traffic goes through a token bucket sized below the input-token limit, with per-tenant buckets and a priority queue so chat beats background work. Bulk work goes to a durable queue with a concurrency limit, or to the Batch API. Prompt caching raises effective throughput, and I watch the rate-limit headers to slow down before the 429s. When the queue is too long, I shed low-priority work early."

What’s happening
  1. Token limits bite before request limits when prompts are long.
  2. Per-tenant buckets stop one customer starving the rest.
  3. Backpressure means refusing or deferring early, instead of letting everything time out late.
  4. Ramp new traffic gradually; sudden jumps hit limits that steady traffic doesn't.
  5. A 429 that's really a spend cap won't clear by waiting. Read the error detail.

Learn more: Rate limits, queues and backpressure.

What goes into observability for an LLM feature?
Show answer

A trace per user action, with a span for every model call and tool call, and quality signals on top. "I'd use OpenTelemetry's GenAI conventions so any backend understands the spans. On model spans: requested and served model, prompt name and version, effort, input, output and cache tokens, cost, time to first token and total latency, stop reason, retries, fallbacks and the request id. Content is opt-in under our data policy. Dashboards for cost and latency percentiles per feature, refusal and fallback rates, cache hit rate, and thumbs-down rate. I keep every trace with an error, refusal or negative feedback, since those feed the eval set."

What’s happening
  1. Classic monitoring says the request succeeded. It can't say the answer was wrong.
  2. For agents, the trace tree is the debugger: what the model knew at each decision.
  3. Prompts contain user data, so traces need redaction, access control and retention.
  4. Alert on outliers: a few runs at fifty times the median cost.
  5. Sampled traces reviewed by people are how failure categories get found.

Learn more: Observability: tracing LLM calls.

What guardrails go around a customer-facing assistant?
Show answer

Layers of deterministic checks around a probabilistic model. "Input: length limits, PII redaction for what the model doesn't need, blocking clearly disallowed requests. Output: schema validation, policy rules for things the assistant must never do, a canary to catch system-prompt leaks, an allow-list for links, escaping before rendering. A small classifier model for nuanced policy, run in parallel to save latency. Anything with side effects goes through code-level authorisation and, for high-risk actions, human confirmation. Every guard fails safe and logs a reason."

What’s happening
  1. The system prompt states the rules; the guardrails enforce them.
  2. With streaming, either check as text arrives or hold back what hasn't been checked.
  3. Measure each guard's false positives: a guard that blocks good answers is its own outage.
  4. Block rates are metrics. A spike means an attack or a broken guard.
  5. Fail safe means a handoff or no action, never an unchecked pass.

Learn more: Guardrails in production.

How do you roll out a new prompt or a new model?
Show answer

As a versioned config change with two gates: an offline eval, then a gradual rollout. "The candidate must not regress on our eval set for quality, cost per task and latency. Then optionally shadow traffic, then a sticky canary to a few percent of users, watching thumbs-down rate, escalations, refusals, latency and cost against thresholds with automatic rollback. Model ids are pinned exactly, every call logs the prompt version and model, and I track deprecation dates so a retirement is a planned migration."

What’s happening
  1. An alias that moves to a new model is an unreviewed deploy. Pin the exact id.
  2. Shadow mode compares outputs before any user sees them.
  3. Sticky assignment keeps one user on one variant, so their experience is consistent and the comparison is clean.
  4. Check that a canary's difference is statistically real before acting on it.
  5. A new model usually needs prompt changes: read the provider's migration notes, then re-run the eval.

Learn more: Shipping changes safely: prompts, models and versions.

#Security and safety questions

Added

Questions about what goes wrong when a model reads untrusted text and can act.

What are the main security risks of an LLM feature?
Show answer

Prompt injection is the root; the OWASP Top 10 for LLM applications is the checklist. "The model can't reliably tell instructions from data, so any text it reads, from users, documents, web pages or tool results, can steer it. That makes the other risks worse: sensitive information disclosure and system-prompt leakage, excessive agency when it has tools, improper output handling when its output is rendered or executed. Then supply-chain and poisoning risks, cross-tenant retrieval, misinformation and unbounded consumption. My response is to assume the model can be fooled and limit what a fooled model can do."

What’s happening
  1. In a design review, draw the data flow: mark every place untrusted text enters and every place the system acts or emits output.
  2. For each path from one to the other, require a control that doesn't depend on the model behaving.
  3. Least privilege, authorisation in code, confirmation for risky actions, output treated as untrusted.
  4. Unbounded consumption is a security issue too: limits on tokens, steps and spend.
  5. Each control gets a test or an eval case that proves it.

Learn more: The OWASP Top 10 for LLM applications.

What is prompt injection, and why can't you just fix it?
Show answer

Text the model reads, rather than the developer, changes what the model does; and there's no separate channel for instructions. "Direct injection is typed by the user. Indirect injection is hidden in content the model processes for a user, a web page, an email, a document, a tool result, so the victim never sees it. System prompt, user input and retrieved content are all tokens in one sequence, and the model was trained to follow instructions. Delimiters and 'ignore instructions in documents' reduce it but guarantee nothing, because they rely on the same judgement the attacker is targeting."

What’s happening
  1. SQL injection was fixed by separating code from data with parameters. A model has no such separation.
  2. Every new input channel is a new injection surface: a file upload, a web fetch, an MCP server, memory.
  3. "Tell it to ignore instructions" is itself just more text in the same sequence.
  4. So the question shifts from "can it be fooled?" to "what can it do when it is?".
  5. That reframing is the answer interviewers are listening for.

Learn more: Prompt injection: direct and indirect.

How would you defend an email assistant against prompt injection?
Show answer

In code, by breaking the lethal trifecta. "The dangerous combination is private data, untrusted content and a way to send data out, in one session. So once a session has read untrusted email content, it loses outbound capabilities such as sending email or fetching arbitrary URLs, or those happen only through explicit user actions. Every tool authorises the action for that user in code, recipients are allow-listed, and anything with side effects needs a confirmation showing exactly what will be sent. I don't render external images or unapproved links, which are classic exfiltration channels."

What’s happening
  1. Remove any one leg and the attack has nowhere to go. The exfiltration leg is usually the easiest to remove.
  2. Tainting: track that a session has seen untrusted content, and gate tools on it.
  3. For higher assurance, a dual-LLM design: the model that plans and holds tools never sees the untrusted text.
  4. Delimiting untrusted content is a cheap extra layer, not the defence.
  5. Red-team continuously, and turn successful attacks into eval cases.

Learn more: Defending against prompt injection.

How do you stop an LLM feature leaking data?
Show answer

The model only ever sees what the current user may see, enforced in code before the prompt is built. "Retrieval is filtered by tenant and permissions at query time. Tools act with the user's identity and check authorisation themselves. Nothing secret goes in the system prompt, because system prompts get extracted; keys live server-side behind tools. I assume any context can be repeated back to the user. Response caches are keyed by tenant and user. Logs keep ids and metrics, with content redacted or stored separately under retention rules. And I test for it: extraction attempts and cross-tenant queries are in the eval set."

What’s happening
  1. A model can't leak what it was never shown. Filtering after retrieval is the bug to look for.
  2. A Markdown image whose URL carries data is a zero-click exfiltration channel: don't render external images.
  3. A canary string in the system prompt lets an output check detect a leak.
  4. Check the provider's retention and training terms, and which features fall outside zero data retention.
  5. "Don't reveal this" in a prompt is not a control.

Learn more: Data leakage and privacy.

The model returns Markdown, JSON or SQL. How do you use it safely?
Show answer

As untrusted input, like anything from the internet. "For display: escaped text by default; for Markdown, a renderer with raw HTML disabled, sanitised output, images dropped or proxied, and links only to approved hosts. For structured output: parse against a schema and validate values before acting, never eval. For text-to-SQL: read-only statements on approved tables, run under a read-only role with limits, so the database enforces it. Shell commands are built from fixed programs with validated arguments, server-side fetches are allow-listed, and generated code runs only in an isolated sandbox."

What’s happening
  1. Model output can contain whatever an attacker put in something the model read.
  2. Enforce at the lowest layer you can: a database role beats a regular expression on the query.
  3. A fetch tool with a model-chosen URL is a server-side request forgery risk: allow-list hosts.
  4. A sandbox for generated code has no credentials and no network.
  5. Arguments to tools are model output too.

Learn more: Insecure output handling.

How do you decide which tools and permissions an agent gets?
Show answer

Start from the task and give the minimum. "Narrow, purpose-built tools rather than raw SQL or a shell, and no tool the task never needs, because a model can ask for anything and the executor shouldn't have a path for it. Every tool runs with the end user's identity, not a service account, and authorises the specific resource in code. Read-only by default; anything that changes state is reversible where possible and needs explicit confirmation showing exactly what will happen. Plus budgets: step limits, cost caps, per-tool rate limits and timeouts, and a log of every call."

What’s happening
  1. Excessive agency has three forms: too many tools, too much permission, too much autonomy.
  2. The test: what's the worst outcome if the model is fully manipulated?
  3. Tool descriptions are part of the attack surface: assume attackers can read them.
  4. A budget that stops a runaway agent is also the defence against unbounded consumption.
  5. Policy lives in the handler. The prompt explains it; the code enforces it.

Learn more: Excessive agency and tool permissions.

How do you handle jailbreaks and content moderation in a product?
Show answer

Separate the provider's safety layer from my own policy. "The model's training and classifiers handle broadly harmful content, and on Claude a decline comes back as stop_reason refusal, which my code handles before reading content. My product policy, like no medical advice in a support bot, is enforced by my own moderation step: a fast, cheap classifier with a strict output schema, on input and where it matters on output, ideally in parallel with the main call. It fails closed for high-risk features. And I red-team regularly."

What’s happening
  1. A jailbreak targets the model's rules; prompt injection targets your application's. The defences overlap but aren't the same.
  2. Moderate the conversation, not only the last message: intent can be split across turns.
  3. The system prompt's rules stay, but they aren't the enforcement.
  4. Watch block and refusal rates for spikes.
  5. Successful attacks become eval cases.

Learn more: Jailbreaks and content moderation.

What does supply-chain security mean for an AI application?
Show answer

Models, datasets, indexes, prompts and MCP servers are dependencies, alongside packages. "Download models from trusted publishers, pin exact revisions and verify hashes, and prefer safetensors or ONNX over pickle-based formats, which can execute code on load. Track dataset provenance, review fine-tuning data for poisoning, and control who can write to anything indexed for retrieval. Pin and review MCP servers, run them with least privilege and treat their output as untrusted. And verify AI-suggested package names before installing, because models invent names that attackers can register."

What’s happening
  1. An MCP tool's description can change after you approved it. Pin versions and detect changes.
  2. Anyone who can write to the retrieval index can write to your prompts.
  3. Loading a model file can run code, depending on the format.
  4. The usual controls still apply: lockfiles, scanning, provenance, and an inventory that includes the models.
  5. A hallucinated package name is a supply-chain attack waiting for someone to register it.

Learn more: The AI supply chain.

#Fine-tuning and open models questions

Added

Questions about changing a model's weights, and about running models yourself.

When would you fine-tune instead of prompting or using RAG?
Show answer

Last, because fine-tuning changes behaviour, not knowledge. "If the model lacks information, that's retrieval: updatable and citable. If format or tone is off, a better prompt, examples or structured output usually fixes it. I'd fine-tune when prompting can't make a behaviour reliable across thousands of outputs, when a narrow, high-volume task works on a frontier model but costs too much, so a small tuned model can match it cheaply, or when data must stay in our infrastructure on an open-weight model. I'd need hundreds to thousands of good examples and an eval set first."

What’s happening
  1. Four questions in order: is the gap knowledge? Has prompting really been exhausted? Is there enough labelled data? Do volume, latency, cost or data rules justify owning a model?
  2. Knowledge changes weekly; weights don't. That's why knowledge goes in retrieval.
  3. The ongoing cost is the part people forget: versioning, serving, monitoring, retraining when better base models arrive.
  4. Fine-tuning can cause forgetting of capabilities the training data didn't cover.
  5. Keep the large model as a fallback for low-confidence cases.

Learn more: When to fine-tune and when not to.

Explain LoRA. How many parameters does it train?

Take one 4,096 × 4,096 weight matrix and rank 16.

Show answer

LoRA freezes the base weights and learns a small low-rank update beside chosen matrices: here 131,072 trainable numbers against 16.8 million, under 1%. "For a weight matrix W it trains two small matrices, B and A, of rank r, so the layer computes Wx plus a scaled BAx. B starts at zero, so training begins from the original model. Only a fraction of a percent of the parameters are trained, which cuts memory dramatically and produces adapters of tens of megabytes. Afterwards the update can be merged into W, with no inference overhead, or kept separate and swapped per request. QLoRA does the same over a base stored in 4-bit."

rq-lora.mjsPlayground ↗
// One weight matrix W (dOut x dIn), and its LoRA update B (dOut x r) times A (r x dIn).
const dIn = 4096, dOut = 4096;
const full = dIn * dOut;
console.log(`full matrix: ${full.toLocaleString("en-US")} parameters`);
for (const r of [8, 16, 64]) {
  const lora = r * (dIn + dOut);
  console.log(`rank ${String(r).padStart(2)}: ${lora.toLocaleString("en-US").padStart(7)} trainable (${((lora / full) * 100).toFixed(2)}% of the matrix), adapter ${((lora * 2) / 1024).toFixed(0)} KiB at 16-bit`);
}
Result
full matrix: 16,777,216 parameters
rank  8:  65,536 trainable (0.39% of the matrix), adapter 128 KiB at 16-bit
rank 16: 131,072 trainable (0.78% of the matrix), adapter 256 KiB at 16-bit
rank 64: 524,288 trainable (3.13% of the matrix), adapter 1024 KiB at 16-bit
What’s happening
  1. The full matrix has 4,096 × 4,096 = 16,777,216 weights. Full fine-tuning would update all of them, with gradients and optimiser state for each.
  2. At rank 16, B is 4,096 × 16 and A is 16 × 4,096: 131,072 numbers, 0.78% of the matrix.
  3. Rank is the capacity dial: rank 8 halves that, rank 64 quadruples it, still only about 3%.
  4. Because B starts at zero, BA is zero at the start, and the model's behaviour is unchanged until training moves it.
  5. Small adapters mean one base model can serve many fine-tunes, loaded per request.

Learn more: How fine-tuning works: SFT, LoRA and QLoRA.

What's the difference between SFT, RLHF and DPO?
Show answer

SFT imitates demonstrations; RLHF and DPO learn from preferences between outputs. "SFT trains on prompt and ideal-response pairs with ordinary next-token loss. RLHF has people rank outputs, trains a reward model on those rankings, and optimises the model with reinforcement learning to maximise reward while a penalty keeps it near the SFT model. DPO reaches a similar goal with a simple loss on chosen and rejected pairs, with no reward model and no RL loop. In practice: SFT first, then DPO on preference data."

What’s happening
  1. Demonstrations teach what a good answer looks like. Preferences teach which of two answers is better, which is easier for people to judge.
  2. RLHF works and is complex and can be unstable. DPO is a classification-style loss.
  3. The risk is reward hacking: the model learns whatever the signal measures. If raters favour long, confident, agreeable answers, training amplifies verbosity and sycophancy.
  4. Defences are in the data and the evaluation: check preference data for length and style bias, and evaluate with judges that weren't part of training.
  5. Product feedback (thumbs up and down, edits) is a source of preference pairs.

Learn more: Preference tuning: RLHF and DPO.

A frontier model does a narrow task well but costs too much at your volume. What do you do?
Show answer

Distil it into a small model. "Use the large model to label a big, representative sample of real inputs, filter the outputs for quality with checks or a judge, and fine-tune a small model on those pairs, often with LoRA. Hold out an eval set that's human-labelled or carefully reviewed, and switch traffic only when the small model matches on it. Keep routing hard or uncertain cases to the large model. And check the provider's terms, since some restrict using outputs to train competing models."

What’s happening
  1. The teacher's labels are the training data, so filtering them is where quality is decided.
  2. The eval set must not be labelled by the teacher alone, or you only measure agreement with the teacher.
  3. With an open-weight teacher you can train on full probability distributions, which carry more information than single answers.
  4. Before distilling, try the cheaper levers: a smaller hosted model, lower effort, caching, batch.
  5. The distilled model is now yours to version, serve and retrain.

Learn more: Distillation: a big model teaches a small one.

How do you size hardware to run an 8B model locally with a 32K context?

Use Llama 3.1 8B: 8.03 billion parameters, 32 layers, 8 key-value heads of size 128; the Q4_K_M quantisation averages 4.89 bits per weight.

Show answer

Two sums: weights plus KV cache for memory, and memory bandwidth over model size for a speed ceiling. Here about 4.6 GiB of weights plus 4 GiB of cache. "Weights are parameters times bits per weight over eight. The KV cache is two times layers times KV heads times head size times bytes, per token of context. Generation on a dense model is roughly memory-bandwidth bound, so bandwidth divided by model size bounds tokens per second. Then I pick the largest model that fits with the context I need and still streams fast enough, and confirm quality with evals."

rq-local-sizing.mjsPlayground ↗
const GiB = 2 ** 30;
const params = 8.03e9, bitsPerWeight = { "Q4_K_M": 4.89, "F16": 16 };
for (const [name, bits] of Object.entries(bitsPerWeight)) console.log(`weights at ${name.padEnd(6)}: ${((params * bits) / 8 / GiB).toFixed(1)} GiB`);

const kvPerToken = 2 * 32 * 8 * 128 * 2; // key + value, 32 layers, 8 KV heads of 128, 16-bit
console.log(`KV cache: ${kvPerToken / 1024} KiB per token`);
for (const context of [8_192, 32_768]) console.log(`  ${context} tokens of context: ${((kvPerToken * context) / GiB).toFixed(1)} GiB`);

const weightBytes = (params * bitsPerWeight.Q4_K_M) / 8, bandwidth = 307e9; // bytes per second of memory bandwidth
console.log(`total for Q4_K_M with 32K context: ${((weightBytes + kvPerToken * 32_768) / GiB).toFixed(1)} GiB`);
console.log(`speed ceiling at 307 GB/s: about ${Math.round(bandwidth / weightBytes)} tokens/s`);
Result
weights at Q4_K_M: 4.6 GiB
weights at F16   : 15.0 GiB
KV cache: 128 KiB per token
  8192 tokens of context: 1.0 GiB
  32768 tokens of context: 4.0 GiB
total for Q4_K_M with 32K context: 8.6 GiB
speed ceiling at 307 GB/s: about 63 tokens/s
What’s happening
  1. Weights: 8.03 billion × 4.89 bits ÷ 8 is about 4.6 GiB at Q4_K_M, against about 15 GiB unquantised at 16-bit.
  2. KV cache: 2 × 32 × 8 × 128 × 2 bytes is 128 KiB per token. 8K tokens is 1 GiB; 32K tokens is 4 GiB.
  3. Together, about 8.6 GiB, which must fit in the memory the GPU can use, with headroom.
  4. Each generated token reads every weight once, so 307 GB/s of bandwidth over a 4.9 GB model gives a ceiling of roughly 60 tokens a second. A 70B model on the same machine would be about a tenth of that.
  5. Fitting isn't the same as good enough: a quantised small model is much weaker than a frontier API on hard tasks, so the eval set decides.

Learn more: Open-weight models and running them locally.

When would you run an open-weight model instead of calling an API?
Show answer

When data can't leave our infrastructure, when it must work offline or on a device, when volume is high and steady enough that owning GPUs beats per-token prices, or when we need to fine-tune deeply and pin a version forever. "Locally I'd use Ollama or LM Studio, which run GGUF models through llama.cpp and expose OpenAI-compatible APIs, so application code barely changes. In production, a serving engine like vLLM. And I'd run our eval set first."

What’s happening
  1. The cost comparison is cost per million tokens at your real utilisation: a GPU that sits idle half the day costs the same.
  2. An API bill becomes an operations burden: capacity, upgrades, monitoring, on-call.
  3. The compatible API shape makes it easy to develop against a local model and a hosted one with the same code.
  4. Quantisation is what makes local models fit, at some cost in quality.
  5. Hybrid is common: small, private or instant tasks locally, hard reasoning on a hosted model.

Learn more: Open-weight models and running them locally and Small models in the browser.

How do you serve an open-weight model to thousands of users, and why does latency spike in the afternoon?
Show answer

With an engine built for batching, sized by KV-cache memory; and the spike is usually that cache filling up. "vLLM: continuous batching so requests join and leave the batch at every step, PagedAttention so the KV cache is allocated in small blocks rather than reserved at maximum length, prefix caching for shared prompts, and an OpenAI-compatible API. Memory, not compute, usually caps concurrency: weights plus KV cache for all the concurrent tokens. When concurrency rises until the cache is full, requests queue or are pre-empted, time to first token climbs, clients time out and retry, and load rises further."

What’s happening
  1. Static batching waits for a batch to finish. Continuous batching fills free slots immediately.
  2. Look at the engine's own metrics first: KV-cache utilisation, running and waiting sequences, pre-emptions, time to first token.
  3. Fixes: autoscale on queue depth with warm capacity before the peak, cap prompt lengths, enable prefix caching for the shared system prompt.
  4. Clients must back off with jitter, or timeouts turn into a retry storm.
  5. Load-test with the peak's real mix of prompt lengths.

Learn more: Serving models yourself: vLLM and throughput.

#AI system design questions

Added

Questions from the design round itself, and the five designs worked through in the course.

How is an AI system design interview different from a classic one?
Show answer

The core component is probabilistic, slow and priced per token, so I'm managing four budgets at once: quality, latency, cost and risk. "I start with the quality bar: what a wrong answer costs and how I'd measure correctness, because that decides how much grounding, verification and human oversight the design needs. Then the simplest shape that could meet it, and an estimate of tokens per request, cost per month and time to first token. The architecture discussion is about what goes into the context and where it comes from. And evals are part of the design, not an afterthought."

What’s happening
  1. Classic designs are anchored by QPS and storage. AI designs are anchored by cost and latency per request.
  2. The prompt, the retrieved context and the eval plan are the architecture.
  3. Name each trade with a number: a bigger model buys quality with cost and latency.
  4. Scale is usually the easy part. The provider handles inference capacity.
  5. The most common omission is "how do you know it's good?". Answer it before you're asked.

Learn more: How the AI system design interview works.

Should every request go to the largest model? Put numbers on it.

A support assistant where 70% of messages can be answered by a small model with retrieved passages at about $0.0006 each, and 30% need a tool-using path on a large model at about $0.03 each.

Show answer

No: route. The blended cost here is under a cent a message, about a third of sending everything to the large path. "A cheap classifier and a retrieval score decide the path in code. The easy majority goes to a small model that reads retrieved passages well; the hard minority gets the large model and tools. Then I look at where the money is: the large path is nearly all of it, so that's where caching and better tools pay."

rq-routing-cost.mjsPlayground ↗
const small = { share: 0.7, cost: 0.0006 }, large = { share: 0.3, cost: 0.03 };
const blended = small.share * small.cost + large.share * large.cost;
console.log(`blended: $${blended.toFixed(5)} per message`);
console.log(`everything on the large path: $${large.cost.toFixed(5)} per message (${(large.cost / blended).toFixed(1)}x)`);
console.log(`the large path is ${large.share * 100}% of messages and ${Math.round(((large.share * large.cost) / blended) * 100)}% of the cost`);
console.log(`at 80,000 messages a day: $${Math.round(blended * 80_000 * 30).toLocaleString("en-US")} a month routed, $${Math.round(large.cost * 80_000 * 30).toLocaleString("en-US")} unrouted`);
Result
blended: $0.00942 per message
everything on the large path: $0.03000 per message (3.2x)
the large path is 30% of messages and 96% of the cost
at 80,000 messages a day: $22,608 a month routed, $72,000 unrouted
What’s happening
  1. Blended: 0.7 × $0.0006 + 0.3 × $0.03 = $0.00942 per message.
  2. Unrouted, every message costs $0.03: 3.2 times as much, with no benefit on the 70% a small model handles well.
  3. The large path is 30% of the traffic and 96% of the cost. Optimise there first.
  4. At 80,000 messages a day the difference is about $22,600 against $72,000 a month.
  5. The routing decision uses signals outside the answering model, a classifier label and a retrieval score, because a model's own confidence isn't reliable.

Learn more: Case study: a customer support assistant.

Design a customer support assistant. What's the one decision the rest hangs on?
Show answer

Triage in code: who handles each message. "A small classifier labels the intent and a knowledge-base search returns a relevance score. Rules send policy questions with good retrieval to a small model that answers only from the passages, with citations; requests that need lookups or actions to a larger model with a few narrowly scoped tools; and anything sensitive, poorly covered, unresolved after several turns, or where the customer asks, to a human with a summary. Refund limits and approvals are enforced in the tool handlers, not in the prompt."

What’s happening
  1. A wrong policy answer is a broken promise. A fluent answer with nothing behind it is the worst failure, so low retrieval scores go to a person.
  2. Every tool is scoped to the signed-in customer in its handler.
  3. Ask: what's the worst the model can do if it's fully manipulated? Here: propose a refund a human declines.
  4. Measure containment together with satisfaction and re-contact rate, never alone.
  5. Roll out in shadow mode first, then a small share of traffic.

Learn more: Case study: a customer support assistant.

"Add AI search to our product catalogue." What do you build?
Show answer

Hybrid search: keyword and vector in parallel, the same filters on both, fused by rank, then reranked. Not a replacement of keyword search. "Keyword search is exact for codes, brands and model names and blind to meaning; embeddings are the reverse. Filters like in-stock apply before ranking so a selective filter can't starve the results. Reciprocal rank fusion merges the lists, a cross-encoder reranks the top fifty, and there's no large language model on the query path, because search has a budget of a couple of hundred milliseconds."

What’s happening
  1. Embed what's stable and descriptive. Price and stock are plain fields, updated without touching the vector.
  2. Re-embed a product only when its text changes.
  3. Fusion can still rank a shallow match first. That's what the reranker is for.
  4. Evaluate each stage on a labelled query set: recall for retrieval, a ranking metric for the final order.
  5. Keyword-only search is the degraded mode if the vector side fails.

Learn more: Case study: semantic search for a product catalogue.

Design an AI code review bot. What does it optimise for, and what stops a malicious pull request?
Show answer

Precision, and credentials that make a hijacked model harmless. "Developers mute a noisy bot, so three solid comments beat twenty doubtful ones. It's a fixed workflow: plan in code (skip lockfiles and generated files, batch under a token budget), review calls in parallel with read-only tools to open surrounding code, a separate verification call per finding, then code filters for changed lines, severity, duplicates and a cap. The PR is untrusted text, so the worker has a read-only, repository-scoped token, never runs PR code and never sees secrets."

What’s happening
  1. Webhook to queue, keyed by repository, PR and commit: retries are idempotent and bursts are absorbed.
  2. A workflow with one small agentic step, not a free-running agent: predictable cost and coverage.
  3. A second, neutral call removes many false alarms that the finding-seeking call produces.
  4. Dismissed comments are labelled data. Store the findings you didn't post, with the reason.
  5. Write access would change the threat model: prefer suggestions a developer applies.

Learn more: Case study: a pull request review agent.

In a document Q&A product for many companies, where are permissions enforced?
Show answer

At retrieval, as a filter before ranking; never by instructing the model. "A model can't leak what it never saw. Every chunk is stored with its tenant and the groups allowed to read its document. At query time the tenant and user come from the token, and the search is filtered by tenant and groups before ranking, because filtering after top-k starves results and no filter leaks. I then re-check the final handful of passages against the live source of truth, to close the window where synced permissions are stale."

What’s happening
  1. Three failures to name: no filter (leak), filter after ranking (starvation), stale permissions.
  2. Tenant isolation is enforced below application code, so a forgotten filter fails closed.
  3. Other leak paths: answer caches, conversation history, citations, logs.
  4. Permission changes and deletions sync on a priority path.
  5. Read and answer only. Documents are untrusted, and tools that act would let a planted page do damage.

Learn more: Case study: question answering over private documents.

Inline writing suggestions must appear within about half a second. What does that do to the design?
Show answer

It moves most of the design into the client and rules out anything heavy. "Each keystroke resets a debounce timer of about 250 milliseconds and aborts any request in flight. When it fires, cheap rules decide whether to ask at all. The request sends only the text around the cursor to a service near the user, which calls the smallest fast model with streaming and an output cap of about a sentence. The response is shown only if it's still current. No retrieval, no second model call. And because a heavy writer triggers over a thousand requests a day, the model tier decides whether the feature is affordable."

What’s happening
  1. Without a debounce, most requests arrive after the user has typed on.
  2. The cheapest request is the one never sent: suppress mid-word, after deletions, after repeated dismissals.
  3. Input dominates the cost of each request, so a short context matters as much as cancellation.
  4. Measure acceptance with coverage and retention, and watch that typing speed doesn't fall.
  5. Bigger edits are a separate, explicit mode with its own budget and model.

Learn more: Case study: an AI writing assistant inside an editor.

Written fresh for AI engineering interviews (there was no Google Doc for this one). Examples were run on Node 26 with @anthropic-ai/sdk 1.17.0, the AI SDK 7.1 and transformers.js 4.3; API facts were checked against Anthropic’s documentation in December 2026.

RohitDownloads · All chapters

Sync progress across devices

Type the same private phrase on your Mac and your phone, and your Learned ticks follow you between them — on every study site.

The phrase never leaves this device: only a fingerprint of it is sent, and the server stores a fingerprint of that. Anyone who knows the phrase could see or change your ticks, so pick something you don’t use elsewhere.

Sync is on in this browser.

Sync ID

This ID must be the same on every device. If another device shows a different one, its phrase is different (capital letters count): tap “Turn off here” on it and type the phrase again exactly.