Free · Self-paced · No sign-up
Free Forward Deployed Engineer Course
This free forward deployed engineer course takes you through 15 self-paced steps and 174 short topics: customer discovery, machine learning, LLMs, prompts, RAG, agents, evaluation, AI safety, deployment, voice AI and FDE interviews. No sign-up, no fee.
What an FDE does. A forward deployed engineer works with the people using a product, translates their workflow into a technical problem and ships a system they can operate. The role spans software engineering, AI, customer discovery and the judgement to decide what should remain under human control.
- 00FDE foundations and customer discovery9
- 01Machine learning for customer decisions12
- 02How large language models work15
- 03Choosing a model for a customer10
- 04Prompt design and context engineering10
- 05Retrieval-augmented generation on customer data17
- 06Agents, tools and integration12
- 07Engineering with coding agents9
- 08Evaluation, tracing and customer value11
- 09AI safety, permissions and customer trust9
- 10Production inference, latency and unit economics13
- 11Fine-tuning and model customisation9
- 12System design, infrastructure and deployment13
- 13Real-time voice AI from audio to action16
- 14FDE interviews and technical judgement9
- 15steps
- 174topics
- ₹0free, no sign-up
- Self-pacedstart any time
How to use this course
How the 15 steps connect
A topic-by-topic guide to building AI systems inside customer organisations. Follow the main questions in order. Open the deeper questions when you want the mechanism, the trade-off or the failure mode behind a decision.
Start with one question. What does an FDE actually own? Each topic has a short explanation, a concrete example and a link to a concept that uses it. Each main-path note links directly to the next one. The check at the end of a step is a chance to predict an answer before revealing it. On a return visit, explain one earlier decision from memory.
Engineering prerequisites. You can start Step 0 without prior AI work. If Python, SQL or HTTP are unfamiliar, start with How do Python, SQL and HTTP fit into one AI request? and run its small example. The technical walkthroughs that use Python need only the standard library.
| Part of an FDE engagement | Steps | The decision you can make |
|---|---|---|
| Discover the customer problem | 0–1 | Which workflow, target and baseline would make a pilot meaningful? |
| Choose and instruct a model | 2–4 | Which model and context can handle the customer’s evidence and constraints? |
| Connect data and actions | 5–7 | How will the application retrieve the right record, call tools and verify changes? |
| Prove and improve the system | 8–11 | Which errors remain, what do they cost and which changes address them? |
| Deploy, operate and explain | 12–14 | Can another team run the service and defend its design under a changed constraint? |
The course
All 15 steps and 174 topic notes
Open a topic to read its explanation, example and further reading. Each step ends with a check: answer it before you compare.
Step 0 · 9 topics
FDE foundations and customer discovery
Start with one decision someone makes at work. Identify the information they use, the person authorised to act and what a better result would look like. The six terms in this step give you enough vocabulary to follow the rest of the map.
Start here
- What does an FDE actually own?
- How do you turn a vague request into a testable problem?
- What are LLMs, RAG, agents, MCP, fine-tuning and quantization?
- How do Python, SQL and HTTP fit into one AI request?
- How do you define a useful baseline?
Go deeper · 4 more questions
Check your understanding. A manager wants a chatbot for 200 daily enquiries. What two facts would change your first design?
Compare your answer
Ask what share can be resolved by a verified lookup and which replies commit the company to an action. A read-heavy queue and an approval-heavy queue need different designs.
Connection. Once the task is clear, you can define the input, label and baseline used to measure it.
Continue to Step 1 · Machine learning for customer decisions
Topic notes · Step 0
0.1What does an FDE actually own?
A forward deployed engineer works with the people using a product and writes the engineering changes that make it useful in their environment. Trace one real decision from the operator’s screen through the source systems to the person who can act on the result.
If ten customers need different wording but all need a citation tied to the source version, which part belongs in the shared product? The evidence component can travel. The wording can remain customer configuration.
0.2How do you turn a vague request into a testable problem?
Ask someone to demonstrate the last ordinary case and the last exception. Capture the trigger, information consulted, decision owner, time spent and consequence of an error. Ask for an example where the proposed tool would make work harder.
“Build us an assistant” becomes “Reduce the time a coordinator spends locating delivery exceptions while leaving dispatch approvals with the supervisor.” That sentence gives you a user, a boundary and something to measure.
0.3What are LLMs, RAG, agents, MCP, fine-tuning and quantization?
A large language model generates tokens. Retrieval-augmented generation (RAG) brings current evidence into its input. An agent can choose its next tool call. Model Context Protocol (MCP) defines how an application connects to tools and data. Fine-tuning changes learned behaviour. Quantization represents numerical values at lower precision.
Match each term to a problem. Yesterday’s policy changed: retrieve its current version. Two applications need the same lookup: consider a shared tool interface. A model exceeds the memory budget: investigate numerical precision.
0.4How do Python, SQL and HTTP fit into one AI request?
Python can receive a request, query rows in SQL, call a model over HTTP and return structured data. JSON carries field names and values across the boundary. A SQL join combines records by a key. A request ID ties the operations together in logs.
Draw a shipment lookup. Record the tracking ID, the trusted account and the verified dispatch date. If the database returns no visible row, there is no delivery date for the model to summarise.
Trace a record through the account boundary
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE shipment (account TEXT, ref TEXT, status TEXT)")
db.execute("INSERT INTO shipment VALUES ('north', 'S8', 'delivered')")
for account in ("north", "south"):
row = db.execute(
"SELECT status FROM shipment WHERE account = ? AND ref = ?",
(account, "S8"),
).fetchone()
print(account, row)The north lookup returns ('delivered',). The south lookup returns None. A deployed application derives the account from authenticated identity.
0.5How do you define a useful baseline?
Measure the existing workflow on a representative slice before changing it. Record active effort, elapsed time, outcome quality and exceptions separately. A person can save typing time yet spend longer checking the draft.
For ten cases write down how many minutes were spent finding evidence and how many were spent approving it. If approval dominates, better search alone has a limited effect on total turnaround.
0.6What belongs in an interface contract?
Specify the inputs, required fields, valid outputs, owner of each field and what happens on missing or stale data. Separate a confirmed database fact from a model suggestion. Define whether dates are local, UTC or subject to a business calendar.
A field called “delivery date” can mean promised, shipped or received. A precise contract might use delivered_at with timezone, source ID and observation time. Three plausible dates can otherwise produce three different decisions.
Next in this step. How do batch jobs, webhooks and polling differ?
0.7How do batch jobs, webhooks and polling differ?
A batch job processes a group on a schedule. A webhook sends an event when the publisher observes a change. Polling repeatedly asks for new state. Choose using the freshness the operator needs and the reliability guarantees of the source.
A daily catalogue can tolerate a nightly refresh. A cancellation before dispatch may require an event plus periodic reconciliation. Define what catches an event the consumer missed.
Next in this step. Where is customer-specific engineering worth doing?
0.8Where is customer-specific engineering worth doing?
Map identity, data ownership, approval paths and vocabulary before adding custom code. Record a reusable capability when several customers have the same underlying need. Keep local thresholds and routing policies versioned separately.
Two teams route high-value orders to different supervisors. A configurable approval rule scales better than a fork of the entire service for each team.
Next in this step. How do Git, a container and a service credential fit together?
0.9How do Git, a container and a service credential fit together?
Git records changes to source. A container packages the application and its runtime dependencies. A service credential supplies narrowly scoped access at runtime. Keep build inputs, configuration and secrets in their respective places and give operators a reproducible start command.
If a demo works only on the developer’s laptop, try the same commit and image with the test account. That isolates a packaging or configuration difference before anyone changes model code.
Step 1 · 12 topics
Machine learning for customer decisions
Learn what a model predicts and how a team knows whether the prediction helps. Use a business decision with a known outcome before studying the mechanics of training.
Start here
- What is the prediction target?
- How do features, labels and data leakage interact?
- How should you split customer data?
- What do precision and recall tell a customer?
- How do simple baselines expose false progress?
Go deeper · 7 more questions
- How do representations change what a model can learn?
- What do loss, gradient descent, batches and epochs do?
- How do nonlinear networks represent interactions?
- When does a confidence threshold deserve trust?
- How do distribution shift, bias and variance show up?
- How do you choose a threshold from the cost of an error?
- How does reinforcement learning differ from supervised prediction?
Check your understanding. A classifier flags 20 cases, of which 15 really need review. There are 30 true review cases. What do the two fractions mean?
Compare your answer
Precision is 15/20 or 75%. Recall is 15/30 or 50%. Half of the cases needing review still pass through. Choose an intervention with the review team.
Connection. The ideas of representation, training and error now apply to models that predict the next token.
Topic notes · Step 1
1.1What is the prediction target?
A supervised example pairs information available at decision time with a label. Classification selects a category. Regression estimates a quantity. Unsupervised learning can reveal structure when labels are unavailable. The target defines what counts as a correct prediction.
“Which invoices will be late?” requires a cutoff date and a definition of late. If accounting staff label according to different grace periods, higher model capacity cannot reconcile the disagreement.
1.2How do features, labels and data leakage interact?
A feature is an input available to the predictor. A label is the outcome you want it to learn. Leakage occurs when training or evaluation exposes information unavailable at the intended moment of use. Leakage can enter through a join or through preprocessing.
A collections model appears accurate after somebody adds final payment status. Rebuild the feature row using only events timestamped before the decision. Split the data before fitting any data-dependent preprocessing.
1.3How should you split customer data?
Training data fits parameters. Validation data guides choices. Keep a test set for the final comparison. Split on the unit that could otherwise repeat, such as an account, document family or time period. Different splits answer different deployment questions.
A random split puts near-identical invoices from the same supplier on both sides. Hold out entire suppliers to test a new-supplier launch. Use later dates to test next month’s workload.
1.4What do precision and recall tell a customer?
Precision asks what fraction of flagged cases were truly positive. Recall asks what fraction of all true positives were flagged. A confusion matrix records both kinds of error and the correct decisions. Choose which cost matters before choosing a threshold.
If 10 of 100 cases need escalation and the tool flags 12 including 8 true cases, precision is 8/12 and recall is 8/10. Ask the supervisor whether the missed two or the four unnecessary reviews cost more.
Change the threshold on the same examples
scores = [0.9, 0.8, 0.6, 0.4, 0.2]
labels = [1, 0, 1, 1, 0]
for threshold in (0.7, 0.5, 0.3):
calls = [score >= threshold for score in scores]
hits = sum(call and truth for call, truth in zip(calls, labels))
print(threshold, hits / sum(calls), hits / sum(labels))Precision and recall respectively are 1/2 and 1/3, then 2/3 and 2/3, then 3/4 and 1. On this tiny sample both can rise together. Which reviewed case explains each change?
1.5How do simple baselines expose false progress?
Compare against a common human shortcut, a deterministic rule and the majority class where applicable. Evaluate all candidates on the same records. A small group of expensive mistakes can be obscured by a high overall accuracy.
If 99 of 100 invoices are routine, predicting “routine” gives 99% accuracy and finds zero exceptions. Bring the exception count and review capacity to the next design discussion.
1.6How do representations change what a model can learn?
One-hot encoding assigns a separate position to each category. An embedding represents items with learned numeric coordinates. Standardisation rescales numeric inputs using training statistics. Missing values need an explicit interpretation when “unknown” differs from zero.
Encoding branch IDs as 1, 2 and 3 invents an ordering. For a linear model, a one-hot representation removes that implied distance. Check how the pipeline handles a new branch after launch.
Next in this step. What do loss, gradient descent, batches and epochs do?
1.7What do loss, gradient descent, batches and epochs do?
A loss scores how far predictions are from labels. Gradients indicate how parameters affect that loss locally. An optimiser updates weights using examples grouped in batches. An epoch is a pass through the training data. Validation behaviour helps select when to stop.
Training loss keeps dropping while validation error rises. Save the earlier checkpoint and inspect the errors by document family. More epochs may strengthen memorisation of the training examples.
Next in this step. How do nonlinear networks represent interactions?
1.8How do nonlinear networks represent interactions?
A layer combines weighted inputs and usually applies a nonlinear activation. Stacking nonlinear layers allows interactions a single linear transformation cannot express. Logits are the final unnormalised scores. Softmax maps them to a distribution over mutually exclusive classes.
An overdue amount may become urgent only for certain contract types. Compare a simple model that includes that interaction with a neural model before accepting the added maintenance burden.
Next in this step. When does a confidence threshold deserve trust?
1.9When does a confidence threshold deserve trust?
Calibration compares predicted probabilities with observed frequencies. A classifier assigning roughly 0.8 to many cases is well calibrated in that range if roughly 80% are positive. The decision threshold then needs to reflect error costs and review capacity.
Bin held-out predictions by score and compare observed rates by region. A good global calibration plot can conceal one region with few examples and much worse behaviour.
Next in this step. How do distribution shift, bias and variance show up?
1.10How do distribution shift, bias and variance show up?
High bias can leave both training and validation performance poor. High variance often appears as a gap between them. After deployment the mix of inputs can shift, or the relation between inputs and outcomes can change. Each points to a different intervention.
A new invoice template changes the input mix. A change to approval policy changes the correct label for familiar inputs. Check both the incoming features and a newly labelled sample.
Next in this step. How do you choose a threshold from the cost of an error?
1.11How do you choose a threshold from the cost of an error?
A calibrated probability becomes useful when paired with a decision rule. In a simple binary setting, compare the expected cost of acting with the expected cost of waiting. This calculation assumes known costs and a calibrated estimate for the population you serve.
If a false escalation costs ₹100 and a missed true escalation costs ₹900, act when 100 × (1 − p) is below 900 × p. The break-even probability is 0.10. A limited review queue can impose a further constraint.
Next in this step. How does reinforcement learning differ from supervised prediction?
1.12How does reinforcement learning differ from supervised prediction?
A policy chooses actions based on state and receives rewards. An action can change future states, so a sequence’s long-term outcome matters. A poorly chosen reward can encourage behaviour the customer dislikes. Many enterprise tasks already have labels or explicit rules that make simpler approaches practical.
Rewarding a support agent only for closing a ticket quickly encourages premature closure. Track reopens and customer resolution before treating a shorter interaction as a training signal.
Step 2 · 15 topics
How large language models work
Follow a sentence into a tokenizer, through a transformer and back out as a sequence of generated tokens. Then connect model behaviour to familiar symptoms such as an invented fact or a slow first response.
Start here
- How does text become tokens?
- What happens during autoregressive generation?
- What are embeddings and cosine similarity?
- How does attention use the context?
- How do pretraining and post-training shape an answer?
- Where do hallucinations come from?
Go deeper · 9 more questions
- How do temperature, top-k and top-p change decoding?
- What can token log probabilities tell you?
- Why can a long context lose a decisive detail?
- What are prefill, decode and the KV cache?
- When do greedy search, beam search and streaming help?
- How do language models handle images and tables?
- How does byte-pair encoding learn a vocabulary?
- What do Q, K and V compute in one attention head?
- Why do positional encodings and grouped-query attention matter?
Check your understanding. A model fluently quotes the wrong price. Which observation distinguishes missing evidence from failure to follow it?
Compare your answer
Inspect the exact input used for that output. If the correct price was absent, repair data access or context assembly. If the price was present, check competing passages, model behaviour and validation.
Connection. Once you know why a model can fail, you can choose representative tasks for comparing models.
Topic notes · Step 2
2.1How does text become tokens?
A tokenizer maps text to IDs in a fixed vocabulary. Subword schemes can represent unfamiliar strings by breaking them into pieces. Sequence length, latency and cost depend on the tokenizer. The same sentence can have different counts across models and languages.
Compare a short English address, a Hindi address and a long part number using the actual model tokenizer. Character count alone cannot tell you whether all three fit a fixed input budget.
2.2What happens during autoregressive generation?
A decoder predicts a distribution over the next token given the tokens it has seen. The selected token is appended and the process repeats until a stop condition or output limit. Early choices can change everything that follows.
An answer cut off midway through a closing brace may have hit its output cap. Inspect the stop reason before changing the prompt or blaming the JSON parser.
2.3What are embeddings and cosine similarity?
An embedding maps an item to a numeric vector. Cosine similarity compares vector directions. Its usefulness depends on what the embedding model learned and how the input is represented. Keep query and document vectors in a compatible representation.
“Cancel my account” and “Do not cancel my account” can be close in semantic space. Similarity is useful for finding candidates. The downstream decision must still resolve negation.
Compare two vector directions
from math import sqrt
query = [1, 0]
for passage in ([3, 0], [1, 1], [0, 2]):
dot = sum(a * b for a, b in zip(query, passage))
magnitude = sqrt(sum(x*x for x in query) * sum(y*y for y in passage))
print(round(dot / magnitude, 3))The results are 1.0, 0.707 and 0.0. Scaling a nonzero vector by a positive constant preserves its direction. These toy vectors illustrate the geometry only.
2.4How does attention use the context?
Each position forms queries, keys and values. Query–key scores determine how strongly to mix values from available positions. A causal mask restricts a decoder position to earlier positions and itself. Position information helps distinguish sentences containing the same words in a different order.
Imagine “the second contract overrides the first.” The answer depends on the relationship between two passages and their order. A bag of words contains both clauses but loses the precedence signal.
2.5How do pretraining and post-training shape an answer?
Pretraining learns statistical patterns from large corpora. Instruction tuning teaches response patterns from demonstrations. Preference-based training can reward responses judged more useful. Deployment adds prompts, current context and tools that the training process never saw.
A model can phrase a convincing warranty answer without knowing this month’s customer contract. Identify which fact should come from a live source before considering a different model.
2.6How do temperature, top-k and top-p change decoding?
Temperature rescales logits before sampling. Top-k keeps a fixed number of candidate tokens. Top-p keeps enough of the highest-probability candidates to reach a probability-mass threshold. These settings affect variation and can interact.
Two candidate logits of 2 and 1 give the first token about 73% probability at temperature 1 and 88% at 0.5. Lower temperature increased preference for a token. It supplied no new evidence about the claim.
Next in this step. What can token log probabilities tell you?
2.7What can token log probabilities tell you?
A token log probability measures the probability of an emitted token under the model and decoding context. An answer’s factual correctness depends on the world and evidence. Calibrating a business decision requires outcomes on representative examples.
A product code seen frequently during training may be an easy continuation even if the order row lists a different code. Use an exact record check for that field.
Next in this step. Why can a long context lose a decisive detail?
2.8Why can a long context lose a decisive detail?
The context window limits tokens available for inputs and generated outputs under the model’s rules. Performance can also depend on where evidence sits among distractors. Treat usable context length as an empirical question about your tasks.
Place the same clause at the beginning, middle and end of an otherwise identical long input. Repeat on several questions. A positional drop suggests changing evidence selection or ordering before paying for a longer window.
Next in this step. Where do hallucinations come from?
2.9Where do hallucinations come from?
Text generation rewards plausible continuations. Missing evidence, conflicting versions, ambiguous questions and poor adherence can all yield an unsupported claim. Find the first point where the information required for a correct answer disappeared.
Compare the original source, retrieved passage, actual model input and final answer. If the effective date vanished during chunking, an instruction to be more accurate cannot restore it.
2.10What are prefill, decode and the KV cache?
Prefill processes the input tokens. Decode produces successive output tokens. The key–value cache retains attention states for earlier tokens so each new step can reuse work. More concurrent sequences and longer contexts typically increase cache memory.
If a long prompt delays the first token but the reply then streams quickly, investigate input processing. If the first token arrives promptly but the full answer takes ten seconds, inspect output length and decode rate.
Next in this step. When do greedy search, beam search and streaming help?
2.11When do greedy search, beam search and streaming help?
Greedy decoding picks the highest-scoring token at each step. Beam search keeps several candidate sequences for a while. Streaming delivers partial output as it becomes available. A partial sentence or partially formed tool argument may change what the application should do.
Stream draft text for readability. Hold a write request until arguments are complete, validated and authorised. Arrival of the first token is a display event.
Next in this step. How do language models handle images and tables?
2.12How do language models handle images and tables?
A multimodal model encodes inputs such as image patches alongside text representations. Fine print, reading order and table-cell boundaries can change extraction quality. Check the full input pipeline including resolution, cropping and any OCR stage.
Use an invoice where the right amount sits on the next row beside a different date. Score field association and evidence location. Reading every digit correctly still permits an incorrect total.
Next in this step. How does byte-pair encoding learn a vocabulary?
2.13How does byte-pair encoding learn a vocabulary?
Start with smaller units and repeatedly merge a frequent adjacent pair in the training corpus. The learned merge order is used when tokenizing new text. The exact base alphabet, normalisation and pre-tokenization depend on the tokenizer.
In a toy corpus with “low” twice and “lower” once, the pairs l–o and o–w both occur three times. If the first merge is l+o, both words now begin with the unit “lo.” A merge rule learns recurrence, not a dictionary definition.
Next in this step. What do Q, K and V compute in one attention head?
2.14What do Q, K and V compute in one attention head?
For one query vector q, score each key k by their dot product scaled by the square root of the key dimension. Apply the mask and a softmax across available keys. The resulting weights form a weighted sum of value vectors. Multiple heads learn different projections.
With scaled scores [0, 1.10], weights are approximately [0.25, 0.75]. If two scalar values are 4 and 12, the output is about 10. This small example explains why attention produces a mixture, not a copied passage.
Next in this step. Why do positional encodings and grouped-query attention matter?
2.15Why do positional encodings and grouped-query attention matter?
Rotary positional embeddings apply position-dependent rotations to queries and keys so their interactions encode positional relationships. Grouped-query attention lets several query heads share key and value heads, reducing KV storage relative to separate KV heads per query head.
When estimating serving memory, inspect the number of KV heads. A configuration with 32 query heads and 8 KV heads stores eight sets of keys and values per layer and token.
Step 3 · 10 topics
Choosing a model for a customer
Work from the deployment constraints and a set of customer examples. A public benchmark can help shortlist candidates. The customer’s workload determines which choice survives testing.
Start here
- What should you specify before shortlisting models?
- How do you run a fair model bake-off?
- When is a small model sufficient?
- How do hosted APIs and open-weight models compare?
Go deeper · 6 more questions
- When do reasoning models and multimodal models earn a place?
- What is a Pareto frontier for model choice?
- How do routing, fallback and abstention differ?
- What do dense and mixture-of-experts models imply for deployment?
- How do you handle model upgrades and deprecation?
- How do you evaluate a router’s break-even point?
Check your understanding. Model A passes 48 of 50 cases but takes six seconds. Model B passes 46 and takes one second. Which wins?
Compare your answer
You need the severity of the additional failures and the required waiting time. If six seconds violates a hard deadline and B’s errors are unacceptable, neither is ready for the full workflow.
Connection. Freeze a suitable baseline model. Now you can tell whether changing its instructions or evidence helps.
Topic notes · Step 3
3.1What should you specify before shortlisting models?
Name the task, input modality, language mix, output contract and unacceptable errors. Add service constraints such as latency, permitted hosting location and peak demand. Define clearance and evaluation requirements with the customer before constructing the shortlist.
A good English summariser can be unsuitable for bilingual receipt extraction. A verified inability to handle image input excludes a candidate before a lengthy comparison.
3.2How do you run a fair model bake-off?
Freeze a representative set of tasks and agree on scoring before inspecting results. Give each candidate equivalent evidence and a reasonable, documented configuration. Record exact versions, retries and output caps. Compare paired outcomes on the same inputs.
If one candidate sees OCR text and another sees the source image, you are comparing two systems. That can be a valuable experiment when the differences are explicit.
3.3When is a small model sufficient?
Start from the least expensive approach likely to satisfy the task. Narrow extraction with a stable schema may suit a compact model. Multi-document synthesis or ambiguous instructions may need a stronger model. Measure the actual failures for each slice.
If 90% of requests are simple status lookups, serve those from the system of record. A model may still be useful for explaining the exceptions in plain language.
3.4How do hosted APIs and open-weight models compare?
Hosted services shift much of the serving work to a provider. Open weights give a team deployment choices while adding hardware, operations and licence review. A model card documents intended uses and limitations. Check the actual licence and customer requirements for the intended deployment.
A low per-token figure can omit idle capacity, on-call cover and engineering time. Compare both approaches at the expected volume and at a quiet month.
3.5When do reasoning models and multimodal models earn a place?
Use harder tasks where deliberation, images or audio carry information a simpler input loses. Reasoning budgets can consume time or tokens. Examine observable answers, cited evidence and tool actions. A long explanation is a weak proxy for a correct decision.
Give the model two conflicting amendments and an effective date. Score which clause governs, which evidence it cites and whether it asks for a missing signature.
Next in this step. What is a Pareto frontier for model choice?
3.6What is a Pareto frontier for model choice?
A configuration is dominated if another measured option does at least as well on every chosen dimension and better on at least one. Plot task quality alongside latency and cost after applying hard constraints. The remaining frontier makes the customer’s trade-off visible.
A model that is cheaper and equally accurate may still miss a mandatory residency requirement. Remove ineligible options before comparing efficient alternatives.
Next in this step. How do routing, fallback and abstention differ?
3.7How do routing, fallback and abstention differ?
A router chooses a path before or during processing. A fallback takes over after an identified failure. Abstention sends an uncertain case to a person or requests clarification. Each additional branch changes latency, cost and the cases the reviewer sees.
Track false routing separately. Sending difficult cases to a cheap model saves money only if retries and human correction do not cancel the gain.
Estimate cost before moving the routing threshold
requests = 100
cheap_price, fallback_price = 0.10, 1.00
for escalations in (10, 20, 40):
spend = requests * cheap_price + escalations * fallback_price
print(escalations, round(spend / requests, 2))The model-only costs per request are ₹0.20, ₹0.30 and ₹0.50. Repeat with a quality label for the cases the router failed to escalate.
Next in this step. What do dense and mixture-of-experts models imply for deployment?
3.8What do dense and mixture-of-experts models imply for deployment?
A dense model generally uses its full relevant stack for each token. A mixture-of-experts layer routes tokens to a subset of experts. Total parameters, active computation and memory residency answer different capacity questions.
A model advertised with relatively few active parameters can still require memory for many experts. Ask how experts are placed and measure latency under representative concurrency.
Next in this step. How do you handle model upgrades and deprecation?
3.9How do you handle model upgrades and deprecation?
Keep model identifiers, prompt version, decoding settings and evaluation results together. Treat a provider upgrade like a dependency change. Run the previous challenge set and a recent sample before moving traffic.
A new version improves average quality but changes a tool argument name. A contract test can catch that even when a human scorer likes the prose.
Next in this step. How do you evaluate a router’s break-even point?
3.10How do you evaluate a router’s break-even point?
Estimate expected total cost across the actual mixture of paths. Include the router, the cheap call, escalation, retries and quality failures. Count each cost only on the paths where it is incurred. Hold the service-level and accuracy requirements constant.
Suppose every request costs ₹0.10 on a first model and 20% also need a ₹1.00 model. Expected model spend is ₹0.30 per request before router and review costs. Measure whether hard tasks are escalated reliably.
Step 4 · 10 topics
Prompt design and context engineering
Write down what the output must contain and which evidence the model may use. Then inspect what actually fits into its input when the conversation, examples and tools grow.
Start here
- What belongs in a prompt contract?
- When should you use zero-shot or few-shot examples?
- How does structured output differ from business validation?
- How should a model handle insufficient or conflicting evidence?
- How do you allocate a context budget?
Go deeper · 5 more questions
Check your understanding. A schema-valid answer gives a number from the wrong invoice. Which check should catch it?
Compare your answer
Resolve the citation to the authorised invoice and compare the amount, currency and record ID together. A numeric type check only establishes that the value can be represented as a number.
Connection. A prompt can only use available facts. The next step explains how to find the right facts in customer systems.
Continue to Step 5 · Retrieval-augmented generation on customer data
Topic notes · Step 4
4.1What belongs in a prompt contract?
Specify the task, audience, permitted evidence, expected output and behaviour when a required fact is unavailable. Make an ambiguous instruction observable by writing one passing and one failing response. Keep model instructions separate from records supplied as data.
“Summarise this” is hard to score. “Extract the delivery date, quote its source line and return null when missing” gives a reviewer three things to check.
4.2When should you use zero-shot or few-shot examples?
A zero-shot prompt describes the task without demonstrations. Few-shot prompting supplies examples of inputs and desired outputs. Select examples that clarify boundaries, especially unusual cases. Keep the test set independent from the demonstrations.
If all three examples contain an invoice date, a model may infer that every record must have one. Include an explicitly missing-date example and evaluate on unseen documents.
4.3How does structured output differ from business validation?
A schema describes field types, required keys and allowable values. Constrained decoding can restrict the generated form when supported. The application still needs semantic checks for facts, permissions, dates and relationships between fields.
A response can be perfectly valid JSON while pairing one customer’s amount with another customer’s invoice. Validate both fields against the same authorised record.
Inspect a minimal response contract
{
"type": "object",
"properties": {
"source_id": {"type": "string"},
"amount": {"type": ["number", "null"]},
"currency": {"type": ["string", "null"]}
},
"required": ["source_id", "amount", "currency"],
"additionalProperties": false
}An amount of 500 paired with the wrong currency still fits this schema. Which authoritative fields will your application compare after parsing?
4.4How should a model handle insufficient or conflicting evidence?
Define a small set of useful responses such as a sourced answer, a focused clarification or a referral. Mark evidence with identifiers and effective dates. Decide which conflicts can be resolved in code and which need a human owner.
Two clauses disagree and neither identifies which supersedes the other. Returning both source IDs with one precise question leaves the operator in a better position than guessing.
4.5How do you allocate a context budget?
Reserve capacity for instructions, user input, tools, selected evidence and output. Count using the deployed tokenizer and model’s limits. Order information so the relevant source and its constraints remain together when the input is trimmed.
For an illustrative shared budget of 16,000 tokens, reserving 2,000 for output and 3,000 for fixed inputs leaves 11,000 for history and evidence. A new tool schema uses some of that space.
4.6When should you split a task into stages?
Separate extraction, decision and drafting when they need different checks or evidence. Give each stage a typed contract. Additional calls create latency and additional failure points, so compare the chain with a single-call baseline.
A date extractor can be validated against source offsets before a deterministic eligibility rule runs. If the first stage fails, a polished downstream reply adds little value.
Next in this step. How do you use intermediate work without demanding hidden reasoning?
4.7How do you use intermediate work without demanding hidden reasoning?
Request verifiable intermediate artifacts such as selected record IDs, calculated totals and source passages. Programmatically check those artifacts. For some tasks several candidate answers or a verifier may help, but correlated mistakes limit the value of agreement.
Five answers generated from the same outdated policy can agree on the wrong deadline. Give the verifier access to the effective policy and score its ability to catch errors.
Next in this step. What should survive context compaction?
4.8What should survive context compaction?
Keep decisions, unresolved questions, verified facts and provenance in structured state. Summaries can reduce input length but can silently change obligations, units or names. Retrieve the original records again before an important action.
A summary reads “replacement approved” when the source says “replacement proposed.” Store approval as a typed status with owner and version so a summariser cannot promote it.
Next in this step. How do prompt caching and answer caching differ?
4.9How do prompt caching and answer caching differ?
Prefix caching reuses computation for a matching prompt prefix. An answer cache reuses the response itself. They have different validity conditions. Permissions, policy version and time-sensitive inputs can all change whether an old answer remains usable.
Two accounts ask exactly the same words about returns. They may share reusable computation for common instructions, subject to implementation isolation. Reusing the same final response needs an account-specific validity check.
Next in this step. How do you run a prompt ablation that teaches you something?
4.10How do you run a prompt ablation that teaches you something?
Freeze the model version, inputs and scoring method. Remove or change one element such as a demonstration, schema reminder or retrieval excerpt. Repeat when outputs vary. Report improvements and regressions by case instead of declaring a universal best prompt.
If adding demonstrations and doubling the context both happen in the same trial, either could explain the gain. A four-condition comparison measures each change and can reveal an interaction.
Step 5 · 17 topics
Retrieval-augmented generation on customer data
Learn the retrieval path in order. Start with one passage that should answer a question. See whether it survives parsing, indexing, permissions, ranking, context assembly and citation.
Start here
- How does a RAG request travel from source to answer?
- How should you choose chunk boundaries?
- When does keyword search beat semantic search?
- How do embeddings and dense retrieval work?
- How do you enforce access and effective dates during retrieval?
- How do you grade citations and handle missing evidence?
Go deeper · 11 more questions
- How do you preserve document structure during ingestion?
- How do hybrid retrieval and reciprocal rank fusion work?
- How do approximate indexes trade recall for speed?
- When should you add a reranker?
- How do query rewriting, decomposition and HyDE differ?
- When do late interaction and graph retrieval help?
- How do updates, deletions and reindexing work?
- How does retrieval evaluation differ from answer evaluation?
- When is SQL, hierarchical navigation or a long context sufficient?
- How do you tune HNSW and IVF with a fixed latency budget?
- When should the retriever take a second step?
Check your understanding. A general policy is ranked first. The signed amendment governing this account is ranked twelfth. Where do you investigate?
Compare your answer
If only ten candidates reach the reranker, it never saw the amendment. Check eligibility and first-stage candidate recall, then ranking. If the amendment entered the actual prompt, inspect precedence and generation.
Connection. Retrieval supplies evidence for an answer. The next step gives the application a controlled way to act on a verified result.
Topic notes · Step 5
5.1How does a RAG request travel from source to answer?
Separate ingestion from answering. Ingestion reads, parses, versions and indexes documents. A request identifies the authorised corpus, retrieves candidates, selects passages and supplies them to a generator. Citations point back to immutable passages the operator can inspect.
When an answer is wrong, write down the source ID at every boundary. The first boundary that lost the governing clause tells you where to start looking.
5.2How do you preserve document structure during ingestion?
Extract headings, tables, page or section identifiers, publication dates and tenant scope alongside text. OCR converts scanned images to text but can lose column associations and footnotes. Version each transformation so you can reproduce a citation.
A tariff table says ₹120 in the correct row and “per carton” in a merged header. Indexing the number alone creates a plausible but unusable answer.
Next in this step. How should you choose chunk boundaries?
5.3How should you choose chunk boundaries?
A chunk must fit the retrieval and context budget while keeping a decision-relevant unit intact. Compare fixed windows, sections, sentences and parent–child retrieval. Overlap helps at boundaries and can also fill the candidate list with near-duplicates.
A standard rule ends a page with “except as defined below.” Retrieve its child passage for ranking, then expand to the parent section so the exception reaches the reader.
5.4When does keyword search beat semantic search?
An inverted index maps terms to the passages containing them. BM25 scores matches using term rarity, frequency and document length with saturation. Rare product codes, clause IDs and literal errors often carry more signal than a paraphrase.
A query for AX-410B can easily retrieve AX-410A through semantic similarity. Keep exact identifiers as searchable fields and measure exact-ID queries separately.
5.5How do embeddings and dense retrieval work?
Encode queries and passages into compatible vectors. Rank by the similarity measure expected by the model. Dense retrieval can find related expressions with little literal overlap. Its quality depends on domain, language and how the passage was prepared.
“The pump won't prime” and “failure to establish suction” may refer to the same problem. Test that pair alongside a lookalike fault code before replacing lexical search.
5.6How do you enforce access and effective dates during retrieval?
Use authenticated scope and document metadata to restrict eligible candidates. Ensure the vector store’s filtering strategy returns enough eligible results and that unauthorised text cannot reach the model, logs or answer cache. Apply effective dates to the question’s intended time.
A global top ten may contain nine passages a user cannot see. Filtering them at the end leaves only one candidate and can distort recall. Check both eligibility and ranking quality under real filters.
5.7How do hybrid retrieval and reciprocal rank fusion work?
Run lexical and dense retrieval over permitted documents. Fuse the ranked lists or combine suitably calibrated scores. Reciprocal rank fusion gives an item a contribution of 1/(k + rank) from each list where it appears. Ranks start at one.
Lexical ranks A then B. Dense ranks B then C. With a toy k of 1, A gets 1/2 and B gets 1/3 + 1/2. B wins because both methods retrieved it. Check whether B actually answers the question.
Fuse two ranked candidate lists
from collections import defaultdict
scores = defaultdict(float)
for ranking in (["A", "B"], ["B", "C"]):
for rank, item in enumerate(ranking, start=1):
scores[item] += 1 / (1 + rank)
print(sorted(scores, key=scores.get, reverse=True))The order is B, A, C. Now remove B from the second list and rerun. A new top result shows how much the two retrievers’ agreement mattered.
Next in this step. How do approximate indexes trade recall for speed?
5.8How do approximate indexes trade recall for speed?
Exact search compares a query with every eligible vector. Approximate nearest-neighbour indexes reduce the work. HNSW navigates a graph. IVF searches selected groups of vectors. Build parameters, query parameters, updates and metadata filters affect the result.
Use exact search on a manageable sample as the reference. Measure neighbour recall, latency and memory for the approximate index, then separately measure whether the retrieved passages answer customer questions.
Next in this step. When should you add a reranker?
5.9When should you add a reranker?
A first-stage retriever prioritises recall over a large corpus. A second-stage reranker spends more computation on fewer query–passage pairs to improve ordering. It can rescue a relevant passage at rank 12 only if that passage entered its candidate pool.
Calculate recall over the top 30 before tuning a reranker that only sees those 30. If the target passage is absent, improve first-stage retrieval or ingestion.
Next in this step. How do query rewriting, decomposition and HyDE differ?
5.10How do query rewriting, decomposition and HyDE differ?
A rewrite expresses the same question in more searchable language. Decomposition creates subquestions that may need different sources. HyDE generates a hypothetical answer to form a retrieval representation. Generated text used for retrieval still needs corroboration from real sources.
A rewrite that drops “before renewal” can surface a term for the wrong contract stage. Store the original and rewritten queries so a reviewer can find the changed condition.
Next in this step. When do late interaction and graph retrieval help?
5.11When do late interaction and graph retrieval help?
Late-interaction models such as ColBERT score fine-grained token-level matches using precomputed representations. Graph-based retrieval can follow explicit connections among entities or documents. Both add index construction and maintenance costs.
“Which suppliers depend on a plant affected by this closure?” is a relationship question. Verify the successive edges and their dates. A semantic match to the plant name cannot establish the dependency.
Next in this step. How do you grade citations and handle missing evidence?
5.12How do you grade citations and handle missing evidence?
Check that the cited passage exists, was visible to the requester and supports the specific claim. Completeness asks whether every important claim has adequate support. Configure an explicit response when the supplied material cannot answer.
A citation proving delivery on Tuesday does not prove a refund was approved. Split the sentence into claims and inspect each one against the displayed passage.
5.13How do updates, deletions and reindexing work?
Separate business record IDs, document versions and chunk IDs. Index a replacement version, verify it, then switch reads. Propagate deletions to derived chunks, embeddings and caches. Record the active index so a bad refresh can be reversed.
If an updated PDF shrinks from 20 chunks to 16, overwriting only the first 16 leaves four obsolete chunks searchable. Compare the expected and actual set of chunk IDs.
Next in this step. How does retrieval evaluation differ from answer evaluation?
5.14How does retrieval evaluation differ from answer evaluation?
Recall@k measures how many relevant passages occur among the first k results. Hit@k asks whether at least one relevant item appears. Mean reciprocal rank rewards an early first relevant hit. Answer correctness also depends on context assembly and generation.
An answer needs both the base policy and an amendment. Retrieving one gives a hit but only half the required evidence. Label both passages and inspect source completeness separately.
Next in this step. When is SQL, hierarchical navigation or a long context sufficient?
5.15When is SQL, hierarchical navigation or a long context sufficient?
A structured current fact often belongs in a database query. A well-organised manual may be navigated through its table of contents. A short set of authoritative passages may fit directly in the prompt. Compare those baselines with the indexing pipeline.
“What is my latest balance?” should resolve to an account-scoped ledger value. “Why is this fee charged?” may require retrieval from a schedule. Many requests need both paths.
Next in this step. How do you tune HNSW and IVF with a fixed latency budget?
5.16How do you tune HNSW and IVF with a fixed latency budget?
HNSW builds a navigable graph with a memory/build-quality trade-off. A larger search candidate list usually improves recall at higher query cost. IVF partitions vectors and searches selected lists. Probing more lists increases coverage and work. Measure results with your actual metadata filters.
For k = 5 compare approximate results against exact search on 100 queries. If 430 of 500 exact neighbours are recovered, mean neighbour recall@5 is 86%. This is distinct from retrieving all business evidence a question requires.
Next in this step. When should the retriever take a second step?
5.17When should the retriever take a second step?
A fixed pipeline searches once. An agentic retrieval workflow can use the first result to formulate a subsequent lookup or discover a missing entity. Define which missing fact justifies another call and what happens when the budget expires.
“Which contract governed that shipment?” first needs the shipment’s contract ID, then its effective version. If the first lookup yields no contract ID, stop and refer the case rather than generating increasingly speculative queries.
Step 6 · 12 topics
Agents, tools and integration
Start with a read-only function. Trace what the model proposes, what the application verifies and what the external system actually records. Add autonomy only where the next action depends on the observation.
Start here
- When is an agent useful and when is a workflow enough?
- How does a tool call actually execute?
- How do you design a tool an agent can use reliably?
- How do approval and idempotency make writes reliable?
- What makes an agent loop terminate?
Go deeper · 7 more questions
- How do planning, reflection and verification differ?
- How should an agent store state and memory?
- How do MCP hosts, clients and servers fit together?
- When do multiple agents justify their coordination cost?
- How do durable execution and compensation handle partial work?
- What changes for browser and computer-use agents?
- When do parallel tool calls help?
Check your understanding. A tool request times out after a write. Which piece of evidence lets the application decide what to do?
Compare your answer
Check the operation record under the original idempotency key or reconcile with the target system. A timeout only describes what the caller observed.
Connection. The same tool-and-feedback pattern appears inside a coding assistant. Its workspace is a repository and its evidence includes tests and diffs.
Topic notes · Step 6
6.1When is an agent useful and when is a workflow enough?
In a workflow, code establishes which step runs next. In an agent, a model can choose among permitted actions based on observations. Use that flexibility where the correct sequence genuinely varies. Each extra decision needs a stopping condition and an observable result.
A balance lookup follows a known path. Investigating a failed shipment may require tracking, inventory and correspondence in a different order for each case. Compare both on the same investigations.
6.2How does a tool call actually execute?
The model proposes a tool name and structured arguments. The application validates them, authorises the operation, executes it and returns a result. The model can then use that result when responding. Keep a clear distinction between a proposed and a completed action.
A generated call to reserve a slot does not prove that the booking exists. Only an authoritative success record or read-back can establish the final state.
6.3How do you design a tool an agent can use reliably?
Use descriptive names, explicit types, bounded outputs and errors that distinguish a missing input from a temporary service failure. Keep authority-bearing values in trusted application context. Return the smallest useful result with provenance.
Define look_up_order(order_id) and derive the account from the session. Returning a full customer record to answer a delivery-date question unnecessarily expands exposure and context.
6.4How do approval and idempotency make writes reliable?
Bind approval to the exact payload and version. Attach a stable operation key to retries of the same intent. The receiving service must enforce that key alongside its write, or provide an equivalent atomic guarantee.
A payment request times out after submission. Reusing a stored key lets the processor identify the same intent. A new amount represents a new decision and needs a new approval.
Check the stable operation key
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("CREATE TABLE jobs (operation_key TEXT PRIMARY KEY, amount INTEGER)")
with db:
for attempt in range(2):
db.execute(
"INSERT INTO jobs VALUES (?, ?) ON CONFLICT(operation_key) DO NOTHING",
("approved-revision-4", 500),
)
print(db.execute("SELECT COUNT(*), SUM(amount) FROM jobs").fetchone())The result is (1, 500). This models one database write. A real service must also compare payloads on key reuse and coordinate external side effects with the target system.
6.5What makes an agent loop terminate?
Specify successful completion, maximum calls, elapsed time, spend and repeated-state conditions. Persist the observation that motivated each call. Distinguish an unreachable service from a valid “no results” response.
The same query sent three times returned the same empty list. Another identical call adds no information. Ask the operator for the missing reference or switch to a defined fallback.
6.6How do planning, reflection and verification differ?
Planning proposes the next actions. Reflection critiques a prior attempt. Verification checks a concrete claim against independent evidence, a test or an authoritative record. Additional model turns can increase cost without introducing independent information.
A shipping agent proposes a route and then praises the same route on reflection. A timetable lookup can actually verify the connection and departure time.
Next in this step. How should an agent store state and memory?
6.7How should an agent store state and memory?
Working state tracks the current task and confirmed intermediate results. Durable memory preserves approved facts or preferences across sessions. Define ownership, expiry and correction. Model-generated guesses should not silently become persistent customer facts.
A user provisions one order for a different delivery address. Store the override on that order. Updating the customer’s default address requires its own evidence and authority.
Next in this step. How do MCP hosts, clients and servers fit together?
6.8How do MCP hosts, clients and servers fit together?
The host is the application that coordinates the user experience. Its client connects to an MCP server that exposes capabilities such as tools or resources. The protocol enables discovery and exchange. Application identity, permissible actions and approval still need implementation.
Two products can reuse one read-only catalogue server. Each still needs to establish which account is making the call and which products the account may see.
Next in this step. When do multiple agents justify their coordination cost?
6.9When do multiple agents justify their coordination cost?
Parallel specialists can help with independent subtasks or distinct tool permissions. Give one component responsibility for reconciling results. Define the data each worker receives and the evidence the coordinator needs before accepting its conclusion.
Two workers checking supplier availability can run independently. Two workers both writing the same order create contention. Separate read tasks from the single owner of the final write.
Next in this step. How do durable execution and compensation handle partial work?
6.10How do durable execution and compensation handle partial work?
Checkpoint state around external calls and reconcile uncertain outcomes on restart. If several services cannot share one transaction, define compensating actions and a human recovery path. Some actions cannot be completely reversed.
A room is reserved but travel approval fails. Persist the reservation reference and cancellation deadline. A retry must resume from that evidence or the customer may acquire a second reservation.
Next in this step. What changes for browser and computer-use agents?
6.11What changes for browser and computer-use agents?
A user interface exposes visible controls, navigation and accessibility information. A UI action can fail after the screen changes or a session expires. Prefer a well-defined supported API when available. Constrain any UI automation to the authorised application and task.
For an approved form-entry workflow, verify the visible record and intended change before submission. Check the confirmation reference afterward and send ambiguity to the operator.
Next in this step. When do parallel tool calls help?
6.12When do parallel tool calls help?
Independent reads can run concurrently. A write that depends on a read must wait for the verified result. Represent dependencies explicitly, set individual deadlines and decide whether partial results suffice. Cancellation of a caller may leave remote work in progress.
Inventory can be looked up alongside delivery estimates. Committing a reservation must wait for the approved item and quantity. A faster but incorrectly parallelised write can create the wrong business record.
Step 7 · 9 topics
Engineering with coding agents
Use a coding agent for a bounded change in a real repository. The learnable skill is specifying the change, providing the right context and reviewing the result through the public entry point.
Start here
- What is a coding-agent harness?
- How do you give a coding agent enough repository context?
- How do fixtures, acceptance tests and regression tests work together?
- How should you review an AI-generated patch?
Go deeper · 5 more questions
Check your understanding. A coding agent says a pagination bug is fixed. Which three cases would you run?
Compare your answer
Use an ordinary full page with a next cursor, a final partial or empty page and a replayed cursor. Assert both the records imported and the resume position.
Connection. A test can prove a deterministic branch works. An AI system also needs evidence across varying inputs and outputs.
Topic notes · Step 7
7.1What is a coding-agent harness?
The harness gives a coding model access to a workspace, instructions, allowed tools, tests and feedback. The model proposes edits and the harness controls which operations are available. Define the working directory and evidence of success before delegating a change.
A repository-wide instruction to “fix imports” invites unrelated edits. Specify the package, the failing import and the test command whose result the reviewer will check.
7.2How do you give a coding agent enough repository context?
Identify the normal entry point, neighbouring implementation, public contract and existing tests. Provide a minimal example of the problem. Let repository structure and documented conventions guide implementation choices.
A helper returns an empty list while the public endpoint maps it to a specific status. Editing the helper without tracing the caller can change every client’s behaviour.
7.3How do fixtures, acceptance tests and regression tests work together?
A fixture supplies repeatable inputs or setup. An acceptance test captures an observable outcome the user needs. A regression test preserves a specific behaviour after a fix. Use targeted tests plus the existing suite to detect unintended changes.
Before fixing a CSV import, freeze examples with a missing column, a quoted comma and two identical rows. Each tests a different behaviour that a happy-path sample would miss.
Capture the boundary with a small regression test
def may_process(amount, limit):
return amount <= limit
for amount, expected in [(99, True), (100, True), (101, False)]:
assert may_process(amount, 100) == expected
print("three boundary checks passed")Change <= to < and rerun. The middle case fails. A coding agent now has a reproducible distinction between the intended rule and the proposed behaviour.
7.4How should you review an AI-generated patch?
Read the change as if another engineer wrote it. Trace input to output and inspect permission checks, error handling, state changes and compatibility. Run tests through the normal entry point. Ask for evidence where a claimed improvement depends on runtime behaviour.
A patch catches every exception and returns an empty result. The tests may pass while an outage becomes indistinguishable from “no records.” Test the failure contract explicitly.
7.5How do small diffs and reproducible environments help?
Pin dependencies where appropriate, document the start command and isolate an experiment from the customer’s working deployment. Small changes keep review and rollback tractable. Record the version that produced the observed output.
A demo works on the author’s laptop because a package is installed globally. Recreate it in a clean environment. Add the missing dependency and repeat the same end-to-end check.
Next in this step. How do you divide work across coding agents?
7.6How do you divide work across coding agents?
Parallelise independent tasks with explicit file ownership and shared interface contracts. Integrate changes through one review path. Ownership matters when a migration, its callers and its tests all change together.
One worker can write fixtures while another implements a parser against the same agreed schema. If both invent different column names, parallel work merely postpones the disagreement.
Next in this step. How do long-running tasks resume after context loss?
7.7How do long-running tasks resume after context loss?
Keep a short plan, decisions, completed checks and the next reproducible command in files under version control where appropriate. A fresh session should inspect the actual state before continuing. Distinguish an intention from a test result.
“Pagination implemented” is ambiguous. “First two pages verified, final empty page untested” allows the next engineer to resume at the real uncertainty.
Next in this step. When does a graph or orchestration framework help?
7.8When does a graph or orchestration framework help?
A graph expresses named states and transition conditions. A framework can add persistence, retry handling or visualisation. Compare its behaviour with a small explicit state machine before adopting it. The framework still needs defined side effects and failure paths.
If human approval can pause a job overnight, durable state and resumable transitions may be worth the dependency. A three-step read-only transformation may need only ordinary functions.
Next in this step. How do you isolate the change that introduced a regression?
7.9How do you isolate the change that introduced a regression?
Choose a known-good version, a known-bad version and one reproducible test that distinguishes them. A version-control bisect narrows the interval by testing intermediate revisions. Pin external dependencies and use fixtures so fluctuating model output does not confuse the result.
A schema field first disappears somewhere across 32 commits. With a reliable yes/no test, about five bisection decisions can isolate the change along a simple history. Reproduce once more on the neighbouring revisions.
Step 8 · 11 topics
Evaluation, tracing and customer value
Follow an individual failure through a trace. Then ask how frequently it occurs in the population the customer cares about. Pair the quality score with the operational outcome the pilot promised to change.
Start here
- What is a customer evaluation set?
- How do you score extraction, generation, retrieval and actions differently?
- How do traces reveal where a bad answer began?
- How do you compare two versions on the same cases?
- How does offline evaluation connect to a live pilot?
Go deeper · 6 more questions
Check your understanding. A model’s average improves, but one customer’s accuracy falls from 9/10 to 6/10. What goes in the release review?
Compare your answer
Show both the overall paired change and the account-specific misses. Inspect their severity and whether that account can be held back pending repair. Report the small denominators.
Connection. Quality scores identify observed failures. The next step defines boundaries that must hold even on a case you have never tested.
Continue to Step 9 · AI safety, permissions and customer trust
Topic notes · Step 8
8.1What is a customer evaluation set?
Choose representative inputs, expected outcomes, evidence and error severity with the people who do the work. Include common, rare, ambiguous and deliberately unanswerable cases. Record how each case entered the set and what population its results describe.
An evaluation made entirely from complaints can expose failure modes. Its error rate cannot directly estimate the error rate across all incoming work.
8.2How do you score extraction, generation, retrieval and actions differently?
Exact or normalised matching suits stable fields. Grounded prose needs claim-level judgement. Retrieval needs labelled relevant passages. A tool workflow needs correct final state and an authorised action history. Keep the scores individually meaningful.
A booking agent can write fluent text and choose the right date yet create two reservations. Evaluate the business record count and approval chain alongside wording.
8.3How do traces reveal where a bad answer began?
A trace links spans for retrieval, ranking, model calls and tools across one request. Record versions, timings, scoped identifiers, fallbacks and outcomes. Use redacted or referenced inputs only where necessary and permitted.
A slow “model request” may have spent most of its time waiting in a retrieval queue. Follow the critical path and inspect queue wait separately from execution time.
8.4How do you compare two versions on the same cases?
Run both versions against the same frozen inputs and score blind where practical. Count wins, losses and ties. Inspect changes in costly error classes and report the denominator. Small samples make apparently precise percentages unstable.
Out of 30 cases, the new version fixes four and breaks two. Its net gain is two cases. Identify whether either new failure violates an essential requirement before recommending release.
Count paired changes before discussing averages
old = [True, True, False, False, False, True]
new = [True, False, True, True, False, True]
wins = sum(b and not a for a, b in zip(old, new))
losses = sum(a and not b for a, b in zip(old, new))
print(wins, losses, len(old) - wins - losses)Two wins, one loss and three ties. Inspect the loss before approving the net gain.
8.5When should an LLM judge be trusted?
Give the judge a specific rubric, representative examples and access to relevant evidence. Calibrate it against independent human reviews and inspect disagreements by slice. Shuffle candidate order in pairwise comparisons to detect order sensitivity.
A judge may prefer a verbose explanation even when a short answer cites the correct clause. Include deliberately concise correct answers and polished incorrect ones in calibration.
Next in this step. How do you measure an agent with several valid paths?
8.6How do you measure an agent with several valid paths?
Distinguish mandatory constraints from optional routes. Score whether the goal was met and whether the agent stayed within budget, permission and approval limits. Record path efficiency without penalising a valid alternate sequence.
For a support case either stock lookup or courier lookup may come first. Requiring one exact trace would mark a correct solution wrong. An unauthorised write should fail either trace.
Next in this step. How does offline evaluation connect to a live pilot?
8.7How does offline evaluation connect to a live pilot?
Offline replay tests known inputs without affecting users. Shadowing generates suggestions alongside the current process. An assisted pilot exposes some users to the feature. Track exposure, use, overrides and downstream outcomes separately.
Thirty drafts were generated, twenty displayed and twelve accepted. Acceptance among displayed drafts is 12/20. End-to-end coverage is 12/30. Explain which denominator the sponsor asked for.
8.8What do drift and feedback loops look like after launch?
Monitor input mix, output patterns, missing fields, human overrides and delayed business outcomes. A system can influence the labels used to evaluate it. Periodically sample cases that received no intervention to reduce blind spots.
A classifier hides low-ranked tickets. Reviewers then label only the tickets they see. The apparent accuracy on reviewed cases says little about the hidden group.
Next in this step. How do you make release gates meaningful?
8.9How do you make release gates meaningful?
Use separate thresholds for utility, latency, cost and critical failure types. Agree in advance which outcomes require manual review or rollback. A passing score on a finite test suite bounds what you observed and leaves residual uncertainty.
Zero critical failures in 50 independent representative trials gives a rough 95% upper bound near 3/50 under the rule of three. A small synthetic suite provides weaker evidence for population risk.
Next in this step. What is the difference between correctness and value?
8.10What is the difference between correctness and value?
Correctness measures whether individual outputs meet the agreed contract. Value depends on how the whole workflow changes. Include editing time, waiting, escalation, adoption and operator trust. For causal claims, use a comparison that addresses selection and workload changes.
An assistant cuts first-draft time in half but adds two rounds of approvals. Measure total handling time and final resolution quality before claiming a productivity gain.
Next in this step. What can changes in the denominator hide?
8.11What can changes in the denominator hide?
An improvement can come from serving easier cases, exposing fewer difficult cases or dropping failures before scoring. Keep the eligibility, attempted, completed and reviewed counts. Compare common cohorts and show each slice’s weight in the overall number.
A system answers 80 of 100 cases and gets 76 right. Reporting 95% accuracy among answers hides the 20 abstentions. Show 80% coverage and 76 correct outcomes per 100 incoming cases alongside conditional accuracy.
Step 9 · 9 topics
AI safety, permissions and customer trust
Trace how a person’s authority follows a request into documents, tools, logs and background jobs. Treat the customer’s access policy as an application requirement that must survive model mistakes.
Start here
- Where are the trust boundaries in an AI application?
- How do tenant isolation and least privilege work?
- How do you design for untrusted documents and tool output?
- How do you minimise private data across the system?
- How should human approval be designed?
Go deeper · 4 more questions
Check your understanding. A document is revoked but an answer cache can still serve yesterday’s response. What needs to change?
Compare your answer
Include permission validity in cache use, invalidate affected entries and check the answer under the revoked identity. The source database update alone has not closed every path.
Connection. Once the permitted behaviour is clear, optimise its latency and cost without silently relaxing the boundary.
Continue to Step 10 · Production inference, latency and unit economics
Topic notes · Step 9
9.1Where are the trust boundaries in an AI application?
Sketch who supplies instructions, documents, identities and tool arguments. Identify who may read each item and who can approve an external effect. Treat generated output as a proposal that the application validates at the next boundary.
A retrieved document may describe a refund procedure. The application must still obtain a verified operator identity and permitted action before any refund is attempted.
9.2How do tenant isolation and least privilege work?
Partition or filter data by verified tenant and user permissions at every relevant boundary. Restrict tool credentials to what the current operation requires. Respect the same controls in caches, traces, exports and background jobs.
Two tenants request the same document title. Evaluate the permitted source IDs, retrieved content and cached answer for each identity before enabling a shared deployment.
Review this permission test
Given account North can read synthetic record N1
And account South cannot read N1
When each account asks the same question
Then North may receive a cited answer from N1
And South receives neither N1 text nor a cached North responseRun the cases in both orders, then revoke North’s access and repeat. Each path exercises a distinct part of the permission lifecycle.
9.3How do you design for untrusted documents and tool output?
Documents and third-party tool responses are data that can contain misleading instructions. Isolate them from trusted control logic. Use narrowly scoped tools, validated schemas and explicit approval for consequential actions. Track the origin of each piece of evidence.
A supplier PDF can describe a change of bank details. Route that change through the existing verified-account process. The source text alone has no authority to change payment configuration.
9.4How do you minimise private data across the system?
Identify the fields needed for each task and remove other personal information before sending data to a component. Define retention, deletion, support access and logging with the customer’s authorised owner. Consider derived copies such as chunks, caches and evaluation examples.
A ticket summariser may need a product serial number but no phone number. Inspect model input, trace and error output to confirm the phone number is absent from all three.
9.5How should human approval be designed?
Show the exact action, record, destination and consequence to a person who can approve it. Store the approver, payload version and expiry. Require a new decision if a material field changes. Provide a clear decline or manual path.
Approval for a correction of ₹500 cannot be reused for a revised correction of ₹5,000. Bind the approval to the original amount and record version.
9.6What do provenance and audit trails establish?
Provenance explains where information came from and which transformation created a derived result. An audit trail shows what happened, when and under whose authority. Collect the minimum needed to reconstruct important events and control access to it.
An operator disputes an approval. A log reading “success” is inadequate. A record linking actor, policy version, input reference and final transaction can settle the relevant questions.
Next in this step. How do you limit the effect of a failed component?
9.7How do you limit the effect of a failed component?
Separate read and write paths, impose budgets, minimise privileges and retain an operator fallback. Decide which functions must stop when evidence, authorisation or a dependency is missing. Practise recovery with benign fixtures and ordinary failure scenarios.
If the identity provider is unavailable, pause the protected lookup. A local health page can still report service status without returning customer records.
Next in this step. How do you assemble evidence for customer sign-off?
9.8How do you assemble evidence for customer sign-off?
Bring a data-flow map, roles, permission tests, deletion process, observed failure cases and recovery owners. Identify decisions requiring customer security, privacy or legal review. Record accepted scope and open questions in a change-controlled document.
A procurement team asking “does our data leave our region?” needs the path through inference, logging, backups and support access. A diagram showing only the model endpoint leaves the question unanswered.
Next in this step. How does document-level access survive permission changes?
9.9How does document-level access survive permission changes?
Make revocation part of the data lifecycle. A source permission update may need to invalidate cached answers, update indexed permissions and propagate to replicas. Ensure the serving path can deny access during propagation or consult a current authority.
Test a benign synthetic document with an authorised account, revoke that permission and repeat the same question. Record how long each permitted serving path takes to respect the change without logging the document contents.
Step 10 · 13 topics
Production inference, latency and unit economics
Follow wall-clock time and money through an entire request. Learn the user-facing measures first. Study cache allocation, batching and speculative decoding when measurement points to the serving layer.
Start here
- Which latency does the user actually feel?
- How do prefill and decode affect the latency budget?
- What does p95 mean and how should it be computed?
- What is cost per successfully completed task?
- How do batching and continuous batching affect serving?
Go deeper · 8 more questions
- How do KV memory and PagedAttention affect capacity?
- When do prefix caching and semantic caching pay off?
- What is quantization and what can it cost?
- How does speculative decoding preserve output quality?
- How do rate limits, backpressure and retry budgets interact?
- Which serving stack fits the workload?
- When does workload routing beat a faster model?
- How much memory does the KV cache need for one sequence?
Check your understanding. A faster configuration doubles throughput but p95 latency gets worse. Can both observations be true?
Compare your answer
Yes. Batching can increase useful work per second while some requests wait longer in the queue. Inspect queue delay and completed tasks under the same arrival pattern.
Connection. If serving costs or repeated behavioural errors remain excessive, model adaptation may be worth a controlled comparison.
Topic notes · Step 10
10.1Which latency does the user actually feel?
Measure queue wait, time to first useful output and time to completion separately. A streamed first token may be quick while the operator still waits for the essential value. Record end-to-end elapsed time per request before calculating percentiles.
For a dashboard assistant, the first verified figure may matter more than the greeting. Put a timestamp on that figure and compare it with total response time.
10.2How do prefill and decode affect the latency budget?
Long inputs can make prefill expensive. Long outputs require more decode steps. Measure both under the target hardware, model and load. A prompt-length reduction helps only if removed context was unnecessary and the affected stage is material.
A response streams at 40 output tokens per second after a one-second first-token delay. About 200 output tokens add roughly five seconds. Shortening the output may matter more than trimming a short input.
10.3What does p95 mean and how should it be computed?
A p95 is a threshold at or below which approximately 95% of observations fall. State the calculation method and sample size. Sum sequential stages per request or trace the critical path where work overlaps. Compute the percentile on those totals.
With nearest rank and 20 sorted durations, the p95 is observation 19. Adding the p95 of retrieval to the p95 of generation can invent a request that never occurred.
Calculate the end-to-end percentile
from math import ceil
requests = [(90, 10)] * 9 + [(10, 90)]
totals = sorted(retrieval + generation for retrieval, generation in requests)
p95 = totals[ceil(0.95 * len(totals)) - 1]
print(p95)Every total is 100 ms. The sum of the two stage p95 values would be 180 ms. Their slow events occurred on different requests.
10.4What is cost per successfully completed task?
Count model inputs, outputs, retries, tool calls, infrastructure and human review where relevant. Divide the chosen cost boundary by the number of tasks meeting the success criteria. State the currency and measurement period.
A batch costs ₹240 and produces 80 usable outcomes from 100 attempts. Cost per attempt is ₹2.40. Cost per usable outcome is ₹3. Compare systems using the denominator the customer cares about.
10.5How do batching and continuous batching affect serving?
Batching uses hardware across requests. Continuous batching admits or removes sequences as generation progresses. This can increase throughput, while waiting for capacity can worsen response time for individual users. Measure throughput and tail latency together.
A queue absorbs a lunchtime burst and keeps the GPU busy. If staff abandon responses after four seconds, more tokens per second may coincide with fewer completed customer tasks.
10.6How do KV memory and PagedAttention affect capacity?
Long sequences keep more key–value state. Paged memory management allocates that state in blocks to reduce waste and support more flexible serving. It does not remove the underlying cost of storing active context.
A service handles twenty short chats but struggles with five document reviews. Check active token counts and cache allocation alongside the number of concurrent users.
Next in this step. When do prefix caching and semantic caching pay off?
10.7When do prefix caching and semantic caching pay off?
A repeated prompt prefix can save prefill computation when cache hits occur. Semantic caching tries to reuse answers for similar requests and therefore needs stricter correctness and access checks. Track hit rate, saved work, invalidation and stale responses.
A long, stable instruction prefix is a plausible prefix-cache candidate. A question about today’s dispatch status needs a fresh record even if its wording matches yesterday’s request.
Next in this step. What is quantization and what can it cost?
10.8What is quantization and what can it cost?
Quantization lowers the precision used for some weights, activations or cache values. It can reduce memory and sometimes increase speed when supported by the hardware and kernels. Evaluate the exact configuration against difficult inputs and target load.
A three-billion-parameter model at four bits per weight has a theoretical raw weight payload of about 1.5 GB in decimal units. Runtime, metadata, buffers and KV memory still need space.
Next in this step. How does speculative decoding preserve output quality?
10.9How does speculative decoding preserve output quality?
In exact speculative decoding a cheaper proposer drafts several tokens and a target model verifies them using the algorithm’s acceptance and correction rules. Speedup depends on acceptance rate and implementation overhead. A casual two-model rewrite has different guarantees.
If the draft model often disagrees on specialist terminology, many candidate tokens are rejected. Measure accepted tokens per verification step on customer prompts before projecting savings.
Next in this step. How do rate limits, backpressure and retry budgets interact?
10.10How do rate limits, backpressure and retry budgets interact?
A service under load may reject or delay work. Use bounded retries, suitable backoff, cancellation and clear queue limits. Respect provider retry guidance. Repeated retries across multiple layers can amplify demand during an outage.
If a client retries three times and its gateway also retries each attempt, one request can generate many calls. Choose the layer responsible for retry and count total attempts per request.
Next in this step. Which serving stack fits the workload?
10.11Which serving stack fits the workload?
Compare runtimes by supported model format, hardware, batch behaviour, observability and operational ownership. A laptop trial with a GGUF-compatible runtime answers a different capacity question from a shared GPU serving system. Use an identical workload and warm-up protocol.
Run one short interactive request and a concurrent mixed-length batch. Mark cold starts separately. Record model quality as well as speed because a faster quantized variant may change outcomes.
Next in this step. When does workload routing beat a faster model?
10.12When does workload routing beat a faster model?
Route deterministic tasks to code and reserve expensive inference for tasks where it adds measured value. Size the system for bursts and fallback traffic. Monitor the customer cases that take each path.
If 70% of requests ask for a verified database field, answering those through a scoped read can cut cost and delay. Keep a separate evaluation for the ambiguous 30% sent to the model.
Next in this step. How much memory does the KV cache need for one sequence?
10.13How much memory does the KV cache need for one sequence?
A rough payload estimate is 2 × layers × cached tokens × KV heads × head dimension × bytes per element. The factor two accounts for keys and values. This excludes allocator overhead, model weights and architecture-specific optimisations. Shared prefixes or sliding windows can change actual usage.
For 32 layers, 4,096 tokens, 8 KV heads, 128 dimensions and 2-byte elements, the payload is 536,870,912 bytes, or 512 MiB. Eight independent sequences at that length would need roughly 4 GiB for this state alone.
Step 11 · 9 topics
Fine-tuning and model customisation
Use tuning for a demonstrated behaviour gap. Define independent test cases before choosing an adapter, collecting preference pairs or paying for a training run.
Start here
- Which failures are good candidates for fine-tuning?
- How do you prepare demonstrations and holdouts?
- What are supervised fine-tuning and instruction tuning?
- How does LoRA change the training budget?
Go deeper · 5 more questions
Check your understanding. A customer changes a fee weekly and requires a stable reply format. Which part might justify tuning?
Compare your answer
Fetch the fee from a current source. Try a schema or template for the stable format. Consider tuning only if a material behaviour gap remains on representative cases.
Connection. A tuned model adds another versioned component. The system design must govern its deployment and rollback with the rest of the application.
Continue to Step 12 · System design, infrastructure and deployment
Topic notes · Step 11
11.1Which failures are good candidates for fine-tuning?
Fine-tuning updates model parameters to improve learned behaviour on a task. Start from a stable, repeated error with trusted training examples. Try a deterministic rule, better context and a better prompt first. Compare the residual gap with the cost of training and maintaining a variant.
An assistant consistently omits a mandatory section despite receiving all the facts. That is a candidate for structured output, a template or tuning. An outdated price needs a current price source.
11.2How do you prepare demonstrations and holdouts?
Define a label policy and sample across tasks, languages, customers and difficult cases. Remove or properly authorise sensitive data. Keep near-duplicates and related records within one split. Reserve an independent set for capabilities you need to preserve.
Ten edited versions of a support reply can look like ten distinct examples. If one reaches the test set after nine were used for training, the measured gain may largely reflect memorisation.
11.3What are supervised fine-tuning and instruction tuning?
Supervised fine-tuning trains on desired outputs paired with inputs. Instruction tuning uses instruction–response examples to improve task following. Training objective, formatting and loss masking determine what the model is rewarded for predicting.
If all examples contain a definitive answer, the tuned model may answer more readily even when evidence is missing. Include well-labelled clarification and referral examples.
11.4How does LoRA change the training budget?
Low-rank adaptation keeps base weights frozen and learns smaller matrices whose product supplies a weight update. Rank, target layers and scaling influence trainable capacity. Deployment must track the adapter and the exact compatible base model.
For a 1,024 by 1,024 weight matrix, rank 8 adds two matrices with 8,192 parameters each. That is 16,384 trainable adapter parameters for that layer, excluding other trainable components.
Count the trainable update
rows, cols = 1024, 1024
for rank in (4, 8, 16):
parameters = rows * rank + rank * cols
print(rank, parameters, round(100 * parameters / (rows * cols), 2))The updates have 8,192, 16,384 and 32,768 parameters. Increasing rank doubles this term each time here. The measured quality gain still needs a held-out evaluation.
11.5What changes with QLoRA?
QLoRA trains low-rank adapters through a frozen, quantized base model. Quantization reduces memory for the base weights. Gradients, activations, the adapters and optimiser state still consume resources. Training memory and inference memory are different budgets.
A model fits in memory for inference but fails during adapter training on long sequences. Inspect activation memory and batch shape before assuming the quantized weights are the problem.
Next in this step. How do distillation and preference optimisation differ?
11.6How do distillation and preference optimisation differ?
Distillation trains a smaller or simpler model to imitate a teacher’s outputs or distribution. Preference optimisation uses comparisons between responses to shape behaviour. DPO directly optimises a preference objective from preferred and rejected examples relative to a reference policy.
A cheaper summariser can be distilled from a stronger teacher. To teach clearer escalation language, collect pairs rated by operators. In both cases test whether earlier factual and permission checks still pass.
Next in this step. How do you detect regressions and forgetting?
11.7How do you detect regressions and forgetting?
Evaluate the target task and a fixed set of previously working behaviours. Check different document types, languages and rare exceptions. Compare against the same base and prompt at the same inference settings. Keep an easy rollback to the known-good configuration.
A tuned extractor improves one vendor’s invoices yet begins filling unknown fields with guesses. Include missing-field cases from several vendors before approving the adapter.
Next in this step. How do you decide whether tuning is economically worthwhile?
11.8How do you decide whether tuning is economically worthwhile?
Compare incremental training, review, hosting, evaluation and retraining costs with measured per-task savings or quality improvements. State the workload volume and time horizon. A solution tuned for one customer can add ongoing support costs.
If adaptation costs ₹60,000 and saves ₹0.50 per successful task, the simple break-even volume is 120,000 tasks before ongoing costs. Revisit the decision if demand or supported base-model versions change.
Next in this step. How do RLHF, DPO and simple evaluation relate?
11.9How do RLHF, DPO and simple evaluation relate?
A typical RLHF pipeline collects preferences, learns a reward model and optimises the policy against that signal with constraints. DPO uses labelled response pairs in a direct training objective. Independent evaluation is necessary for both because a preference dataset can reward a superficial feature.
If reviewers prefer long answers, the learned policy may expand every reply. Compare correctness, operator time and verbosity on independent examples before interpreting preference gains as business improvements.
Step 12 · 13 topics
System design, infrastructure and deployment
Draw the complete service including the operator, the source of truth and the team that recovers it. Use workload and failure requirements to choose infrastructure.
Start here
- How do you draw an end-to-end AI service?
- When should an operation be synchronous or asynchronous?
- What should a model gateway own?
- How do you choose cloud, customer VPC, on-premises or edge?
- What should be versioned together?
- What do shadow, canary and rollback mean?
Go deeper · 7 more questions
- How do queues, concurrency and overload interact?
- What are SLOs, error budgets and recovery targets?
- How do you handle identity and configuration across customers?
- How do deployment, adoption and product feedback connect?
- What belongs in an operational handoff?
- How do you keep event-driven imports consistent?
- When should a circuit breaker open?
Check your understanding. An index upgrade damages retrieval while order writes remain healthy. What should be rolled back?
Compare your answer
Restore the compatible previous index and query encoder or route affected reads to a fallback. Keep committed orders intact and verify both a known-good lookup and an access-boundary case.
Connection. A live voice agent stress-tests the system design because dependencies must work within a conversational pause.
Continue to Step 13 · Real-time voice AI from audio to action
Topic notes · Step 12
12.1How do you draw an end-to-end AI service?
Separate the online request path from background ingestion and evaluation. Identify the source of truth, model gateway, serving process, tool gateway, persistent state and operator interface. Label the trust boundary and timeout at each external dependency.
If retrieval slows down, which requests can still be answered from a verified record? A diagram that shows data ownership and fallback behaviour can answer that operational question.
12.2When should an operation be synchronous or asynchronous?
Synchronous work keeps a requester waiting for a result. Asynchronous work acknowledges a job and completes it later. Define job IDs, progress, expiry, cancellation and final status. Separate accepting the job from completing it successfully.
A two-minute reconciliation job can return a job reference immediately. The UI must show “queued” until the worker completes and records the authoritative outcome.
12.3What should a model gateway own?
A gateway can centralise routing, budgets, rate limits, per-request version metadata and observability. Keep customer-specific business decisions in identifiable application logic. Document fallback compatibility for context size, tool schema and data handling.
A fallback provider that accepts text but does not support the required tool contract cannot safely take all traffic. Test capability compatibility before adding it to a route.
12.4How do you choose cloud, customer VPC, on-premises or edge?
Map where data may move, what hardware exists, when connectivity fails and who maintains each component. Compare total cost and recovery responsibilities. A private network arrangement and a contractual data-processing commitment answer different questions.
A factory cannot interrupt a safety-independent maintenance lookup when its wide-area link fails. An offline document index may solve that requirement even if model updates arrive centrally.
12.5How do queues, concurrency and overload interact?
Estimate arrival rate and time in the system to understand average in-flight work under stable conditions. Bound the queue and define a degraded mode. Measure burst behaviour because an average rate hides short periods of overload.
At eight requests per second and two seconds average residence time, Little’s law gives about sixteen in flight under stable conditions. That estimate alone does not size a server for peak traffic.
Make the queue assumption explicit
8 requests/second × 2 seconds in system = 16 requests in flight on average
8 requests/second × 5 seconds in system = 40 requests in flight on averageBoth statements assume stable long-run averages. With fixed capacity, an accumulating queue may stop the system reaching the second steady state.
Next in this step. What should be versioned together?
12.6What should be versioned together?
Record code, schemas, policies, prompts, model or adapter, embedding model, index and feature flags for a release. Some changes depend on others. A rollback should restore a compatible combination and preserve committed business records.
Changing the embedding model while keeping vectors from the previous representation can invalidate retrieval. Build a compatible index in parallel and switch query and index versions together.
12.7What do shadow, canary and rollback mean?
Shadow traffic tests a candidate alongside the existing system without exposing its effects to users. A canary serves a limited share of real work. A rollback returns to a known-good version. Prevent duplicate side effects when replaying or shadowing requests.
Send 5% of eligible read-only queries to a canary and compare error and latency slices. For writes, shadow a proposal or dry-run result so both versions cannot commit the same transaction.
12.8What are SLOs, error budgets and recovery targets?
A service-level indicator is a measurement. A service-level objective sets a target over a period. An error budget is the allowed shortfall. Recovery time and acceptable data loss require separate, explicit targets. Agree who responds when the service misses them.
A monthly availability target can be met while every answer cites stale data. Pair a service objective with a freshness or correctness indicator the operator cares about.
Next in this step. How do you handle identity and configuration across customers?
12.9How do you handle identity and configuration across customers?
Separate customer configuration from application code and maintain a trusted mapping from authenticated identity to permitted data. Carry scope through background workers, caches and exports. Test configurations independently and check isolation during upgrades.
A queued job must preserve the initiating tenant and scope. Reconstructing context from a user-supplied record ID after the worker starts invites cross-account mistakes.
Next in this step. How do deployment, adoption and product feedback connect?
12.10How do deployment, adoption and product feedback connect?
Name the sponsor, daily operator, service owner and product owner. Agree on training, override, escalation and feedback before expanding rollout. Preserve a route from repeated customer pain to a reproducible platform improvement.
Three teams repeatedly create their own citation UI. A product request with examples, frequency and a test for evidence visibility is easier to prioritise than “customers want more explainability.”
Next in this step. What belongs in an operational handoff?
12.11What belongs in an operational handoff?
Give the receiving team start, stop, health, fallback, incident and recovery procedures. Name a person or team for each dependency and record the last verified version. Have a new operator execute a recovery from the instructions.
A runbook says “rebuild the index.” During handoff the operator discovers they lack the required role. That failed rehearsal is valuable evidence of a missing ownership decision.
Next in this step. How do you keep event-driven imports consistent?
12.12How do you keep event-driven imports consistent?
Record a cursor or high-water mark only after the corresponding data is durably processed. Deduplicate by a stable source identifier and version. Reconcile out-of-order, late or deleted records and keep a way to replay a bounded interval.
A worker saves the cursor for page six, then fails before persisting those records. On restart it begins at page seven and silently loses data. Commit the imported records and checkpoint together when the store permits it.
Next in this step. When should a circuit breaker open?
12.13When should a circuit breaker open?
A circuit breaker temporarily stops repeated calls to a failing dependency after defined conditions are met. In a half-open state a limited probe tests recovery. Choose the fallback and recovery signals before enabling it. A breaker cannot make an unsafe fallback acceptable.
Repeated model timeouts can send drafting to a manual queue. Probe with a small authorised request before resuming traffic. Keep verified order lookup available if its dependency is healthy.
Step 13 · 16 topics
Real-time voice AI from audio to action
Use one conversation to connect streaming, recognition, context, tools, evaluation and system design. Understand the audio and turn boundaries before studying telephone signalling.
Start here
- How does a real-time voice request travel end to end?
- When do you choose a cascade or speech-to-speech?
- How do VAD, endpointing and turn-taking differ?
- What is the difference between interim and final transcripts?
- How should a voice agent handle barge-in?
- How do you set a voice latency budget?
Go deeper · 10 more questions
- Why do codecs, sample rates and jitter buffers matter?
- What are WebRTC, WebSocket, SIP, RTP and DTMF for?
- How do you stream speech without speaking an unsupported claim?
- How do you handle backchannels, pauses and repairs?
- How do multilingual speech and proper names change evaluation?
- How should a call transfer to a human?
- How do you evaluate and operate a voice service?
- How do concurrent calls affect cost and capacity?
- How do you calculate streaming recognition and playback lag?
- How do voicemail, keypad fallback and call termination affect state?
Check your understanding. A caller says the first three digits, pauses, then continues. The agent interrupts and confirms the wrong ID. Which two changes would you evaluate?
Compare your answer
Test endpointing on pauses inside identifiers. Require read-back or another suitable confirmation before the authoritative lookup or write. Score premature endpoints and exact-ID accuracy separately.
Connection. The voice system gives you a concrete design to explain under interview pressure. The same reasoning transfers to other customer deployments.
Continue to Step 14 · FDE interviews and technical judgement
Topic notes · Step 13
13.1How does a real-time voice request travel end to end?
Trace microphone or telephony audio through transport, turn detection, recognition, model processing, tools, synthesis and playback. Some stages can overlap. Mark where uncertainty enters, when text becomes final and when the caller actually hears an answer.
Keep a timestamp for the final spoken syllable and the first intelligible reply audio. Measuring from server receipt to text generation misses both capture and playback delay.
13.2When do you choose a cascade or speech-to-speech?
A cascade connects automatic speech recognition, an LLM and text-to-speech. It exposes intermediate text and allows independent component tuning. A speech-to-speech system can preserve additional audio cues while exposing different control and inspection points.
For reading a confirmation code, exact digit verification matters. For a conversational coach, timing and prosody may matter more. Compare architectures on both tasks using the same recordings.
13.3How do VAD, endpointing and turn-taking differ?
Voice activity detection estimates whether speech is present. Endpointing estimates when an utterance has ended. Turn-taking decides whether the system should speak. A pause can be part of an unfinished address, a natural handover or background noise.
A caller pauses for 600 ms midway through a serial number. Sweep the silence threshold and count premature replies against added delay after genuine ends. Pick a policy using both costs.
13.4What is the difference between interim and final transcripts?
Streaming recognition may revise interim words as more audio arrives. A final recognition segment and a complete user turn can have different boundaries. Build state so later corrections do not leave an obsolete identifier available for action.
The recogniser first shows “fifteen” and then finalises “fifty.” The UI can show provisional text, but a consequential write must wait for the required confirmation.
13.5How should a voice agent handle barge-in?
Barge-in lets the caller interrupt playback. Separate speech detection, decision to interrupt, stopping queued audio and cancelling downstream generation. Track how much audio was actually played so the next turn knows what the caller heard.
The assistant starts offering two dates. The caller interrupts after hearing only the first. Preserve the first offer in conversation state and avoid assuming the caller heard the second.
13.6How do you set a voice latency budget?
Break the path into endpoint wait, recognition finalisation, reasoning or tools, first audio generation and transport or playout. Count only work on the critical path where stages overlap. Look at distributions across accents, utterance lengths and network conditions.
In a simple sequential example, 350 ms endpointing, 120 ms recognition, 250 ms decision, 160 ms synthesis and 80 ms playout sum to 960 ms after speech ends. Shorten the dominant stage and recheck false interruptions.
13.7Why do codecs, sample rates and jitter buffers matter?
Digital audio is sampled, encoded, packetised and played on a clock. A jitter buffer smooths variable packet arrival at the cost of added delay. Format conversion and packet loss can affect recognition more than a change to the language model.
A recogniser performs well on clean files but poorly on phone calls. Test audio after the actual telephony encoding and resampling path before tuning the text prompt.
Next in this step. What are WebRTC, WebSocket, SIP, RTP and DTMF for?
13.8What are WebRTC, WebSocket, SIP, RTP and DTMF for?
WebRTC supports real-time media between endpoints. WebSocket provides a bidirectional message channel. SIP handles telephony session signalling and RTP carries real-time media. DTMF represents keypad input, with telephone events often transported over RTP.
For an inbound phone call, trace call setup separately from the audio path. A connected call with silence is a different failure from a call that never completed signalling.
Next in this step. How do you stream speech without speaking an unsupported claim?
13.9How do you stream speech without speaking an unsupported claim?
Chunk output at boundaries that sound natural and preserve meaning. Decide which statements may be spoken before a slow tool returns. Mark utterances that depend on a confirmed tool result. Earlier audio cannot be withdrawn from the caller’s memory.
The agent may say it is checking availability. It must wait for the calendar result before saying a slot is reserved. Timestamp the result and the first audio containing the confirmation.
Next in this step. How do you handle backchannels, pauses and repairs?
13.10How do you handle backchannels, pauses and repairs?
Sounds such as “mm-hmm” can signal acknowledgement while the other speaker retains the turn. An interruption may be a correction or ordinary noise. Combine timing, context and confidence, then offer a quick recovery after a false stop.
Replay short acknowledgements, long silences and a caller changing one digit. Count lost turns and repeated questions as well as premature interruptions.
Next in this step. How do multilingual speech and proper names change evaluation?
13.11How do multilingual speech and proper names change evaluation?
Evaluate accent, language switching, names, product codes and noisy lines separately. Phrase hints or pronunciation dictionaries may help known vocabulary but can bias other words. Validate the complete spoken answer with appropriate reviewers.
A caller gives an address in Hindi and a product code in English. General transcript accuracy may look acceptable while the one wrong code routes the request incorrectly.
Next in this step. How should a call transfer to a human?
13.12How should a call transfer to a human?
Define a transfer trigger, the receiving queue, caller consent where applicable and what happens if nobody answers. Transfer a minimal factual summary plus verified and unverified fields. Keep the caller informed of the current state.
An operator should see “customer corrected the last digit; order lookup still pending.” A summary that silently converts the pending lookup into a confirmed order can mislead the next person.
Next in this step. How do you evaluate and operate a voice service?
13.13How do you evaluate and operate a voice service?
Word error rate tracks insertions, deletions and substitutions relative to a reference transcript. Add entity accuracy, turn completion, interruption recovery, task success, handoff quality and time to first audio. Run synthetic calls for repeatability and separately review representative authorised recordings.
Three word errors in a 30-word reference give 10% word error rate. One error in a booking reference may matter more than all three filler-word errors. Give critical entities their own score.
Next in this step. How do concurrent calls affect cost and capacity?
13.14How do concurrent calls affect cost and capacity?
Track concurrent media sessions, audio duration, recognition and synthesis usage, model tokens, tool latency, telephony charges and transfer rates. Long silent calls may still occupy a connection. Define an admission and graceful-handoff policy at peak.
Compare cost per connected minute with cost per successfully resolved call. A system that talks faster may still cost more per resolution if callers repeatedly need operator assistance.
Next in this step. How do you calculate streaming recognition and playback lag?
13.15How do you calculate streaming recognition and playback lag?
Record separate clocks for audio capture, recognition updates, generated audio and device playback. Use a common time base or measured synchronisation for cross-device comparisons. Keep the last played audio offset when cancelling queued speech.
If 2.4 seconds of audio was generated but the caller heard 0.9 seconds before interrupting, 1.5 seconds was generated but unheard. Reconstruct conversation state from the played portion.
Reconstruct what the caller heard
0.00 s Agent playback begins
0.90 s Caller interrupts; last played audio offset is 0.90 s
2.40 s End offset of all audio that had been generatedCancel queued playback and retain the 0.90-second playback boundary. Review the alignment to the spoken words before treating an offer or instruction as heard.
Next in this step. How do voicemail, keypad fallback and call termination affect state?
13.16How do voicemail, keypad fallback and call termination affect state?
A telephone workflow needs explicit outcomes for human answer, voicemail, failed transfer, caller hang-up and keypad entry. Detection can be uncertain. Persist any confirmed business outcome separately from the telephony session state.
A caller hangs up just after confirming an appointment. Check whether an authoritative booking already exists before retrying or issuing any follow-up. A disconnected call does not prove the booking failed.
Step 14 · 9 topics
FDE interviews and technical judgement
Prepare for discovery, coding, architecture and customer communication. Use real evidence from work you can explain, including a failure that changed a design decision.
Start here
- How do you scope an ambiguous customer request live?
- How do you approach an FDE coding exercise?
- How do you run an AI system design interview?
- How do you debug a system you did not build?
- How do you explain trade-offs to a sponsor and an engineer?
Go deeper · 4 more questions
Check your understanding. A customer asks to expand an encouraging pilot to all branches tomorrow. What would a credible answer cover?
Compare your answer
Name which branches and workflows were represented, the expensive failures still possible, a phased expansion decision and who can pause it. Show the evidence that would change your recommendation.
Connection. Return to the technical topic where your explanation depends on an assumption you cannot yet test.
Topic notes · Step 14
14.1How do you scope an ambiguous customer request live?
Start by asking who does the work, what triggers it, what evidence is available and who owns the final decision. Ask for one routine example and one exception. Restate a small deliverable, success measure and excluded action in the customer’s own vocabulary.
Prompt: “Automate order reconciliation.” A strong first response asks the operator to walk through a real discrepancy before choosing a model or drawing a vector database.
14.2How do you approach an FDE coding exercise?
Clarify the input and output contract, implement a simple vertical slice and test the boundary cases. If an assistant is permitted, use it for bounded changes you can explain and verify. State a remaining limitation when time runs out.
Given a paginated API and duplicate records, show the normal import, a missing cursor and a replayed page. Explain the stable key and what state survives a restart.
14.3How do you run an AI system design interview?
Start with users, workload, hard constraints and a baseline. Trace one successful request end to end. Then trace a failure and a change in requirements. Show the source of truth, permission checks, observations and rollback path.
An interviewer bans off-site inference halfway through a document-search design. Revisit data movement, serving capacity, model selection and the fallback. Keep components whose assumptions still hold.
14.4How do you debug a system you did not build?
Form competing hypotheses and name the observation that would separate them. Trace a specific request through its inputs, intermediate artifacts, versions and output. Change one variable where possible. End with the evidence for your conclusion.
“Accuracy fell after Monday’s release.” Compare the old and new indexes using the same prompt and model. If the right passage disappears only under the new index, investigate ingestion or retrieval.
Answer the interviewer with one discriminating test
Hypothesis A: the passage never entered the candidate set.
Hypothesis B: the passage was present, but the answer ignored it.
Observation: list candidate IDs, then inspect the exact model input.If the passage was retrieved but trimmed before generation, both initial explanations were incomplete. The first loss happened during context assembly.
14.5How do you explain trade-offs to a sponsor and an engineer?
Use the same evidence at different levels of detail. A sponsor needs the business outcome, exposure, consequence and decision. An engineer needs the failing record, component versions, measurement method and path to reproduce it.
Tell a sponsor that two of twenty cases still required manual correction. Show the engineer which two, the observed error and the check that would detect it automatically.
14.6How do you present a portfolio that can be examined?
Include a one-page problem statement, a runnable or reproducible example, an architecture diagram, a baseline, failed cases, an evaluation and a handoff. Label simulations and estimates. Attribute what you personally implemented.
A reviewer asks to change the date or account in your demo. A portable project can predict which decision changes, show the result and explain why the rest of the workflow stays valid.
Next in this step. How do you prioritise under delivery pressure?
14.7How do you prioritise under delivery pressure?
Separate a non-negotiable boundary from a feature that can be deferred. Offer the smallest pilot still capable of testing the business hypothesis. State what evidence would justify widening the rollout and what would stop it.
A customer wants autonomous refunds by Friday. Propose a draft-only review pilot if the authorisation boundary is unresolved. Specify what review-time reduction would justify the next investment.
Next in this step. How do you convert a field lesson into product feedback?
14.8How do you convert a field lesson into product feedback?
Describe the repeated problem, affected workflow, evidence, workaround and a testable product improvement. Distinguish a one-off configuration from a broadly useful capability. Give the product team an example they can reproduce without customer secrets.
“Better search” is hard to act on. “Five searches returned superseded clauses because versions were hidden; show effective dates and filter current versions by default” gives a product owner a decision to make.
Next in this step. How do you assess an interview answer without rewarding buzzwords?
14.9How do you assess an interview answer without rewarding buzzwords?
Use observable criteria: did the candidate clarify the task, name a source of truth, define a failure boundary, test a claim and explain a trade-off? Introduce a changed constraint halfway through. Ask which earlier decision it invalidates.
Give the candidate a design that assumes access to raw customer messages. Then restrict storage to redacted metadata. Ask how they would investigate quality regressions and what evidence would now be harder to collect.
When a problem sends you back
Follow one idea across steps
These short routes are useful when a customer problem sends you back to a detail you learned earlier.
- A correct document produces the wrong answer. 2.8 → 5.3 → 5.9 → 5.12 → 8.3
- The model called a tool twice. 4.3 → 6.4 → 6.10 → 10.10 → 12.2
- An assistant feels slow. 2.10 → 10.1 → 10.3 → 10.6 → 13.6
- A model is accurate but nobody uses it. 0.5 → 3.6 → 8.7 → 8.10 → 12.10
- One customer’s evidence reaches another. 0.6 → 5.6 → 9.2 → 9.9 → 12.9
Want help along the way?
Want mentors, projects and placement support? Join the FDE course.
The free course gives you the topics. The BuildAI Careers Forward Deployed Engineer course adds live classes with mentors, reviewed customer-style projects and placement support.
- Live classes with working engineers
- Projects reviewed like a customer deployment
- Interview preparation and placement support