LLM application engineering (agents, RAG, prompts)
Named in 74% of 2253 senior postings · 47 review cards
Building products on top of model APIs: agent loops and the harnesses around them, tool interfaces and MCP, retrieval-augmented generation, context construction, guardrails, and the cost, latency and reliability work that turns a demo into a production system. About three quarters of postings name something in this area, and 82% of AI-engineer postings name agents. It is tested in system design rounds, in a build-an-agent or build-a-retriever coding round, and in debugging scenarios.
What the postings ask for
Share of postings that name each skill, overall and by track.
| Skill | All postings | MLE | AI eng | Research eng | Cards |
|---|---|---|---|---|---|
| Agents and agentic systems | 37% | 75% | 51% | 7 | |
| Agent frameworks, harnesses and runtimes (LangGraph, LlamaIndex, agent SDKs) | 13% | 40% | 10% | 4 | |
| Building on model APIs (OpenAI, Anthropic, Gemini, Bedrock) | 16% | 32% | 24% | 3 | |
| Prompt and context engineering | 13% | 33% | 10% | 5 | |
| Retrieval-augmented generation | 15% | 32% | 4% | 8 | |
| Tool use, function calling, MCP | 11% | 31% | 12% | 5 | |
| Workflow automation and enterprise integration | 8% | 27% | 6% | 1 | |
| Guardrails, safety filters, hallucination control | 11% | 23% | 4% | 3 | |
| Cost, latency and model routing for LLM products | 12% | 19% | 4% | 3 | |
| Forward-deployed / customer-embedded delivery | 6% | 18% | 8% | 2 | |
| Vector search and embedding stores | 7% | 18% | 1% | 2 | |
| Structured outputs and reliability of LLM pipelines | 5% | 11% | 3% | 2 | |
| Conversational AI / voice agents | 5% | 7% | 5% | 1 | |
| Agent memory and state | 2% | 6% | 2% | 1 |
In the postings’ words
AI application integration patterns, including MCP, gateways, skills, plugins, or agent workflows. Deep ML model development is not required.
Proficiency in LangChain/LangGraph or other Orchestration and agentic workflow
Deep UXC / AI-native UX expertise - has shipped intelligent, AI-driven user experiences (not just consumed an LLM API), with strong intuition for how agent/model output should surface to real users.
Python, Java, LangGraph, RAG, prompt and context engineering, GCP Vertex AI, Bigtable, Cloud SQL, vector databases, etc.
Proficiency in building and troubleshooting modern agentic systems (prompt tuning, routing, planning, multi-agent, RAG, tool use, memory management, etc.).
Agentic Safety: Focus on LLM-level safety for autonomous systems, including multi-turn tool-calling, orchestration, and execution risks.
● Seamlessly integrate Large Language Model (LLM)-driven agent pipelines with core Electronic Design Automation (EDA) suites, custom in-house software tools, and enterprise data repositories.
Broadcom · Infrastructure AI/ML Engineer for Memory Design, Characterization, and Yield Optimization
The senior bar
What separates a senior answer from a mid-level one in this area.
- Picks the least autonomous design that solves the task (single call, workflow, agent) and justifies it with error compounding, cost per task and cost of a wrong action.
- Treats the model as an untrusted proposer, so permissions, argument validation, budgets, idempotency and approvals are enforced in code outside the model and never only in the prompt.
- Reasons about context as a budgeted, cache-sensitive compiled state and can say what goes in, in what order, what is compacted and what is fetched on demand.
- Separates retrieval failures from generation failures in RAG, measures each stage, and knows hybrid retrieval, reranking and permission filtering concretely.
- Changes prompts, tools and models as versioned changes gated by a regression eval, and debugs incidents from traces rather than from guesses.
- Quantifies cost and latency per completed task (input and output tokens, cache hit rate, time to first token, steps per task) and knows which lever moves which number.
- Can scope work with a customer down to one measurable workflow, define acceptance criteria and carry it from demo to production.
Skills, checklists and questions
Tick an item when you can explain it without notes; ticks are saved in this browser. Open a question to see the answer.
Agents and agentic systems 57% of postings
- Draw the agent loop and name the four parts (model, tools, state, stop condition) and which decisions belong to code
- Decide between a single call, a fixed workflow and an agent, using error compounding and cost of error
- Explain router, prompt chain, parallel fan-out, orchestrator-workers and evaluator-optimizer, with a failure mode for each
- Say when sub-agents with isolated context help and what they cost in tokens and lost context
- Debug a non-terminating agent from its trace and add the budgets and loop detection that prevent it
- Write a minimal tool-calling loop from memory
coreconceptMLE AI REasked at Google What is an agent, concretely? Walk me through the loop and tell me which parts belong to the model and which to your code.
An agent is a model run in a loop where the model, not the code, picks the next action from what it has observed so far. It has four parts:
- Model: proposes either a final answer or one or more tool calls.
- Tools: typed functions the harness can execute (search, read, write, run code).
- State: the message history plus anything kept outside the window (plan, files, event log).
- Stop condition: the model answers without a tool call and the completion check passes, or a budget (steps, tokens, wall-clock, money) runs out, or the run needs a human, or a fatal error occurs.
One iteration: compile context from state, call the model, and if it requested tools then validate the arguments, check permissions, execute, append the bounded result as an observation and repeat.
The split that matters: the model owns judgment under ambiguity (which hypothesis to test, what is missing, how to read an unfamiliar error). Code owns invariants (step limits, schema validation, timeouts, permission checks, approval for destructive actions). A model proposal is not a side effect until the harness has parsed, authorised and executed it. If the control flow is fixed in code and the model only fills in steps, it is a workflow, not an agent.
Follow-ups
- Which stop conditions would you enforce in code even if the prompt already states them?
- What does the model see when a tool call fails?
Reported in interviews (candidate reports on third-party sites, not verified)
- Google, Software Engineer, Jul 2026: Scalable and safe agentic system with deterministic controls (PracHub)
coretrade-offMLE AI REasked at Anthropic When does a fixed workflow beat an agent, and when is an agent worth it?
Use the least autonomy that solves the task. A single call for classification, extraction or Q&A; a workflow (code-defined steps, model fills each one) when the steps are known in advance; an agent only when the path depends on what is discovered along the way.
Why not default to an agent:
- Compounding error. If each step succeeds independently with probability \(p\), an \(n\)-step run succeeds with about \(p^n\): \(0.95^{20} \approx 0.36\), \(0.99^{20} \approx 0.82\). This is a pessimistic bound only when the environment gives feedback the agent can use to recover (tests, error messages); silent errors compound fully.
- Cost and latency. Every step re-sends the growing history, so uncached input tokens grow roughly quadratically in the number of steps.
- Predictability. A workflow has enumerable paths that can be tested and audited.
An agent earns its cost when four things hold: the task is open-ended and hard to specify as steps; the outcome is valuable enough to pay for many calls; the model is actually good at the task; and errors are cheap to detect and undo (tests, review, rollback).
The common production shape is a hybrid: code fixes the outer stages and the invariants, and the model makes local decisions or runs a bounded loop inside one stage.
Follow-ups
- Give an example you would build as a workflow that a team wanted to build as an agent.
- How does a verifier change the \(p^n\) argument?
Reported in interviews (candidate reports on third-party sites, not verified)
- Anthropic, Machine Learning Engineer, undated: Design an agentic system that adapts to new tasks (Aced (formerly Exponent))
seniortrade-offAI RE Single agent or multiple agents? When do sub-agents help and what do they cost?
Start with one agent. Add sub-agents for a specific reason, not to mirror an org chart.
What sub-agents buy:
- Context isolation. A sub-agent can read 100k tokens of search results or files in its own window and return a 1-2k token finding, keeping the lead’s context clean.
- Parallelism. Independent sub-tasks run concurrently and cut wall-clock time.
- Specialisation. Different tool sets, prompts or cheaper models per role.
- Independent checking. A reviewer that has not seen the author’s reasoning is less anchored on it.
What they cost:
- Tokens. Each sub-agent pays for its own context; total usage is typically several times a single agent’s.
- Lossy hand-offs. The sub-agent knows only the brief, and the lead sees only the summary. Errors come back in the same confident tone as findings.
- Coordination. Parallel agents that make interdependent decisions produce conflicts (two agents editing the same file, incompatible assumptions).
Good fit: breadth-first, read-heavy, separable work (research across sources, codebase search, per-document extraction). Poor fit: tightly coupled writing where every decision depends on shared context.
Rules that make it work: give each sub-agent an explicit brief (goal, what is already ruled out, output format, tool and scope limits); have it return compact, checkable results or pointers to artefacts; keep writes single-threaded; cap depth and fan-out.
Follow-ups
- How would you measure whether a multi-agent version is worth its token cost?
- What goes wrong if the lead forwards its own hypothesis in the brief?
seniorconceptAI RE Name the common orchestration patterns for LLM systems and say when each fits and how it fails.
| Pattern | Shape | Fits when | Typical failure |
|---|---|---|---|
| Prompt chain | fixed sequence, each call consumes the previous output, with code checks between | task decomposes into known steps | an early error propagates; latency adds up |
| Router | classify the input, dispatch to a specialised prompt, tool set or model | distinct request types with different handling | misroutes fail silently; needs per-route evals |
| Parallel fan-out | split into independent parts, or run the same task several times and vote | separable sub-tasks, or a need for higher confidence | merge step loses or duplicates content; cost multiplies |
| Orchestrator-workers (planner-executor) | a lead model decomposes at run time and delegates to workers | sub-tasks are not known in advance | bad decomposition; plan not revised when evidence changes |
| Evaluator-optimizer | a generator proposes, an evaluator critiques against criteria, loop until pass or budget | clear criteria and measurable gain from revision | evaluator is too lenient or the loop never converges |
| Autonomous loop | model chooses tools until done | open-ended tasks with good environment feedback | wandering, loops, runaway cost |
Two points interviewers look for. First, these compose: a router in front of a chain, with one stage being a bounded agent loop. Second, plans should be mutable: plan, act briefly, observe, replan beats executing a long fixed plan, because later steps depend on observations the planner did not have. An evaluator should check the artefact or the environment (tests, schema, citations), not just ask the same model whether it is happy.
Follow-ups
- Where would you put deterministic checks in a prompt chain?
- When does voting across samples actually improve accuracy?
seniordebuggingAI RE Your agent sometimes runs until it hits the step limit without finishing. How do you investigate and what do you change?
Read the traces of the runs that ended on the budget and classify them before changing anything. The usual causes:
- Repeated identical call. The tool returns an error the model cannot act on (“failed”), or the result never reaches the model (tool result not paired with its call id, or truncated to nothing), so it retries the same thing.
- Oscillation. Two fixes that undo each other, common when a verifier reports failure without saying what failed.
- No reachable stop. The definition of done is missing or the completion check can never pass (flaky test, impossible requirement).
- Lost state. Compaction dropped the fact that an approach was tried and failed.
- Unbounded exploration. Pagination or search with no convergence criterion.
Changes, in order:
- Make errors actionable: what failed, why, and what input would be valid.
- Detect loops in code: hash (tool, normalised arguments); after k repeats inject a notice, force a replan, or stop.
- Hard budgets on steps, tokens and wall-clock, with a graceful exit that reports partial progress instead of an exception.
- Give the model an explicit way out: “cannot complete, here is why” or ask the user.
- Keep failed attempts and unresolved errors verbatim through compaction.
Then monitor the termination-reason histogram and the steps-per-task distribution (p50, p95), and add the looping cases to the regression set.
Follow-ups
- How do you tell a legitimate long task from a loop?
- The loop detector fires on a polling tool. What do you do?
seniordesignAI Design a customer-support agent for an e-commerce company that can answer questions and perform actions such as refunds.
Clarify first. Channels (chat, email, voice), volume, top intents, which actions are in scope, policy sources, the target (resolution rate at equal or better CSAT) and the cost of a wrong action.
Architecture.
- Intake: authenticate the customer, attach account context, run input checks.
- Routing: a small model classifies intent and risk; out-of-scope or sensitive intents go straight to a human.
- Knowledge: RAG over help-centre and policy documents, with document versions and effective dates, so policy answers are grounded and cited.
- Agent loop with tools: read tools (order status, shipment, account) run freely; write tools (refund, cancel, address change) are gated.
- Escalation: hand off with a structured summary (issue, steps taken, customer data gathered) so the human does not start over.
Controls outside the model. Tools take the authenticated customer id from the session, never from model arguments, and the backend re-checks ownership. Refunds carry an idempotency key; amounts above a limit, or repeated refunds, require human approval. Policy limits live in code. Customer messages and ticket text are untrusted input. PII is redacted in logs.
Evaluation. Offline: a golden set of conversations per intent, simulated multi-turn users, graders for policy adherence, correct tool use and groundedness. Online: resolution rate, reopen rate within 7 days, CSAT, escalation rate and its precision, cost per resolved conversation.
Rollout. Shadow mode, then draft-for-human, then autonomous on low-risk intents, then expand intent by intent.
Failure modes to name. Inventing policy, premature “resolved” to hit the metric, social-engineering for refunds, loops with frustrated users (cap turns and escalate).
Follow-ups
- How do you stop the agent from promising something the policy does not allow?
- Which metric would the team game first, and what counter-metric do you add?
- What changes for the voice channel?
corecodingMLE AI RE Write a minimal agent loop with tool calling against a generic chat-completions-style client. Then tell me what is missing for production.
Assume client.chat(messages, tools) returns {"content": str | None, "tool_calls": [{"id", "name", "arguments": <JSON string>}], "finish_reason": str}.
import json
import jsonschema
def run_agent(client, system, user_msg, tools, max_steps=20):
"""tools: {name: {"description": str, "parameters": <JSON Schema>, "fn": callable}}"""
specs = [{"name": n, "description": t["description"], "parameters": t["parameters"]}
for n, t in sorted(tools.items())] # stable order keeps the prefix cacheable
messages = [{"role": "system", "content": system},
{"role": "user", "content": user_msg}]
for _ in range(max_steps):
reply = client.chat(messages=messages, tools=specs)
messages.append({"role": "assistant", "content": reply["content"],
"tool_calls": reply["tool_calls"]})
if reply["finish_reason"] == "length":
raise RuntimeError("output truncated; tool arguments may be incomplete")
if not reply["tool_calls"]:
return reply["content"] # stop: answer without a tool call
for call in reply["tool_calls"]: # one result per call, same id
messages.append({"role": "tool", "tool_call_id": call["id"],
"content": execute(tools, call)})
raise RuntimeError("step budget exhausted")
def execute(tools, call, max_chars=8000):
try:
tool = tools[call["name"]] # KeyError: hallucinated tool
args = json.loads(call["arguments"])
jsonschema.validate(args, tool["parameters"])
out = tool["fn"](**args)
text = out if isinstance(out, str) else json.dumps(out, default=str)
except Exception as e: # errors are observations
text = f"ERROR {type(e).__name__}: {e}"
return text[:max_chars]Pitfalls an interviewer checks:
- The assistant message with its tool calls must be appended before the results, and every call needs exactly one result with the matching id, or the next request is rejected.
- Tool errors go back to the model as results; only harness faults raise.
- A hard step limit and bounded tool output.
Missing for production: permission and approval checks before side-effecting tools, per-tool timeouts, retry with backoff on API errors, token and cost budgets, context compaction, concurrency for parallel-safe calls, an event log for resume, tracing, and a completion verifier.
Follow-ups
- Where would you add human approval, and what is persisted while waiting?
- How would you run the tool calls in parallel safely?
Agent frameworks, harnesses and runtimes (LangGraph, LlamaIndex, agent SDKs) 26% of postings
- Name the components of a harness (context compiler, tool executor, state, controller, verifiers, permissions, observability)
- Design sandboxing and a permission policy for an agent that can run shell commands
- Make a long-running agent resumable with an event log, checkpoints and durable human approval
- Say what LangGraph, LlamaIndex, DSPy and vendor agent SDKs each provide
- Argue when to write the loop yourself and what you would then have to rebuild
coreconceptMLE AI RE What is an agent harness, and what are its components?
The harness is everything around the model that turns a next-token predictor into a closed-loop system: it decides what the model sees, executes what the model proposes, and enforces what the model must not decide. The same model can score very differently under different harnesses, which is why postings ask for it by name.
Components:
- Context compiler: assembles rules, task, tool definitions, working state, selected evidence and recent history for each call; handles ordering, truncation and compaction.
- Tool registry and executor: schemas, argument validation, timeouts, output normalisation, side-effect class, retry semantics.
- State and memory: append-only event log, working state (plan, budgets), artefacts on disk, long-term memory.
- Controller: the loop itself, with termination conditions, budgets, retries, escalation, sub-agent and background-job lifecycles, resume after interruption.
- Verifiers: tests, schema checks, citation checks; they turn “I think I am done” into evidence.
- Permission layer: least privilege, sandboxing, approval for consequential actions; outside the model’s control.
- Observability: traces of every decision, call, result, token count and termination reason.
The design rule: deterministic invariants belong in code. Writing “never call more than 20 tools” in a prompt makes a hard rule probabilistic and wastes context.
Follow-ups
- Which component would you build first for a new agent, and why?
- What does the harness do that a stronger model will not make unnecessary?
staffdesignAI REasked at OpenAI Design the harness for a coding agent that works in a developer’s repository and can run shell commands.
Tools. Search (grep, glob), read with line ranges, edit by exact string replacement or patch (cheaper and safer than whole-file rewrites), shell, and a way to run tests. Tool output is bounded; large output goes to a file the agent can page through.
Sandbox. Run commands in a container, VM or OS-level sandbox: file writes limited to the workspace, network denied by default with an allowlist (package registries), no ambient credentials in the environment. State which capability sits inside which boundary; an external MCP tool is not covered by the shell sandbox.
Permissions. Rules evaluated in code per action: reads allowed; workspace edits allowed or ask-once; shell commands matched against allow, ask and deny patterns; pushing, deploying, deleting outside the workspace and anything touching secrets needs explicit approval. The effective action set is the intersection of sandbox, rules and approval policy.
Context. Load a repository instruction file and a compact environment description; never load the repo wholesale, search on demand. Keep the prefix stable for caching (fixed tool order, append-only history). Compact when near the limit, preserving the task, user constraints, files touched, failing tests and attempted fixes.
Feedback and verification. Compilers, type checkers, linters and tests are the dense signal that makes coding agents work; run them after edits and before claiming done. Show the diff to the user.
State. Append-only event log to replay or resume a session; file snapshots or commits as checkpoints so any step can be rolled back; explicit interrupt semantics (what happens to an in-flight command).
Extras. Read-only sub-agents for wide searches; hooks before and after tool calls for policy and formatting; full traces with token and cost accounting.
Evaluation. Repository tasks graded by hidden tests in fresh containers, plus tasks from your own codebase; report resolve rate, cost and time per task, and human intervention rate.
Threats. Injection via repository files, issue text, web pages and dependency docs; data exfiltration through the network; destructive commands. The sandbox bounds the blast radius when the prompt-level defences fail.
Follow-ups
- Why edit by string replacement instead of rewriting files?
- How would you let the agent work unattended overnight without widening the risk?
- A post-tool hook finds a secret in the diff. What can it still prevent?
Reported in interviews (candidate reports on third-party sites, not verified)
- OpenAI, Machine Learning Engineer, Apr 2026: Agent harness and evaluation system for a tool-using agent (PracHub)
seniortrade-offAI What do LangGraph, LlamaIndex, DSPy and vendor agent SDKs actually give you, and when would you write the loop yourself?
What each provides (APIs change quickly, so treat details as version-specific):
- LangGraph: a graph or state-machine runtime. Nodes are steps, edges are transitions, a typed shared state flows through; checkpointing gives persistence, resume and human-in-the-loop interrupts.
- LlamaIndex: a data framework for RAG: loaders, parsers and chunkers, indices, retrievers, rerankers and query engines, plus agent and workflow abstractions on top.
- DSPy: programs written as typed signatures and modules instead of prompt strings; optimizers search instructions and few-shot demonstrations against a metric and a training set. It needs a metric and data to be useful.
- Vendor agent SDKs (OpenAI Agents SDK, Claude Agent SDK, Google ADK and similar): a maintained loop with tool definitions, hand-offs or sub-agents, guardrail hooks, sessions and tracing, tuned for that vendor’s models.
The core loop is about 50 lines. The hard parts are tool design, context assembly, evals and permissions, and no framework does those for you.
Write it yourself when you need full control of the exact request sent to the model, when the abstraction hides prompts or token usage, or when the control flow is unusual. Use a framework for the commodity runtime you would otherwise rebuild: durable state and resume, streaming, tracing, connectors.
A practical test: can you print the exact messages and tool definitions for any call, and can you swap one component without rewriting the rest? If not, the framework will cost more in debugging than it saves.
Follow-ups
- What breaks first when a prototype built on a framework goes to production?
- How would you evaluate a DSPy-optimised prompt against your hand-written one?
staffconceptAI An agent run can take hours and includes a step that needs human approval. How do you make it survive crashes, restarts and a two-day wait?
Model the run as a resumable state machine, not a blocking function call.
Event log as source of truth. Append every model response, tool call, tool result, approval and error to durable storage. State is rebuilt by replaying the log; derived UI state is a projection, not a second source of truth.
Checkpoint boundaries. Persist the model’s response before executing its tool calls, and each tool result as soon as it returns. On restart, completed steps are read from the log and not re-executed.
The ambiguous step. A crash between “tool started” and “result recorded” leaves a side effect in an unknown state. Handle it with an idempotency key derived from (run id, step, call id) that the downstream system deduplicates on, or by querying the target’s state before retrying. Without one of these, at-least-once execution means duplicate refunds.
Durable approval. A pending approval is a persisted record, not a waiting process: store the exact proposed action, release compute, resume on an external signal. Bind the approval to a hash of the arguments so any change needs re-approval; give it an expiry and a defined behaviour on timeout and on rejection (the model is told and can replan).
Interruption. Define what cancel means for the model stream, the in-flight tool, effects already applied and the next resume. Killing the process is not a design.
Implementation. A durable-execution engine (Temporal-style) fits: orchestration code is deterministic and replayable, while model calls and tools are activities whose recorded results are replayed rather than recomputed. LangGraph-style checkpointers give a lighter version of the same idea.
Follow-ups
- Why can you not simply re-run the model call during replay?
- The context has been compacted since the checkpoint. What do you restore?
Building on model APIs (OpenAI, Anthropic, Gemini, Bedrock) 25% of postings
- Handle rate limits, retries with backoff and jitter, timeouts and streaming errors
- Check finish reasons (length, tool call, refusal or content filter) before using a response
- Design provider or model fallback and say why prompts are not portable across models
- Explain sources of non-determinism and how tests and evals account for it
- Plan a model version migration with pinned snapshots and a re-qualification eval
coreconceptMLE AI What does a production-grade client for a hosted model API need to handle?
- Rate limits. Providers limit requests and tokens per minute, often separately for input and output. Handle 429 with the
retry-afterheader; add a client-side token bucket and a queue with backpressure so bursts wait instead of failing; give interactive traffic priority over batch. - Retries. Exponential backoff with jitter for 429, 5xx, timeouts and overload errors, with a cap on attempts and total time. Do not retry 4xx validation errors. A retried request may be billed twice and returns a different sample.
- Timeouts and streaming. Long generations need streaming to avoid idle-connection timeouts. Handle errors that arrive mid-stream and decide what to do with partial output.
- Finish reasons. Check why generation stopped before using the output: natural end, token limit (truncated), tool call, or refusal or content filter.
- Fallbacks. A secondary model, region or provider behind a circuit breaker. Prompts and tool-call behaviour are not portable across models, so the fallback path needs its own prompt tuning and its own eval results.
- Capacity. Know your quota against peak tokens per minute; consider provisioned throughput for latency-sensitive paths; hedge requests only where tail latency justifies the cost.
- Observability. Log request id, model version, token counts including cached tokens, latency, finish reason and retries for every call.
- Data terms. Retention, training use, residency, and what may be sent at all.
- Versioning. Pin dated model versions and track deprecation dates.
Follow-ups
- You are at the token-per-minute limit at peak. What are your options?
- What can go wrong when failing over to another provider mid-conversation?
seniortrade-offMLE AI RE LLM outputs are non-deterministic and the models behind an API change. How do you build a reliable system on that?
Where the variance comes from. Sampling (temperature, top-p). Even at temperature 0, outputs can differ between calls: floating-point results depend on batching and hardware, requests land on different replicas, and providers update serving stacks. Seed parameters are best effort. Some reasoning models do not expose sampling parameters at all.
Consequences for testing.
- Assert properties, not exact strings: schema validity, required facts present, a grader’s verdict.
- Run each eval case several times and report a pass rate with a confidence interval; a case that passes four times in five is a finding in itself.
- Use record-and-replay of model responses for unit tests of the surrounding code.
Consequences for design.
- Put anything that must be exact in code: arithmetic, lookups, permission checks.
- Validate outputs and retry within bounds; make downstream actions idempotent.
- Use multiple samples with voting only where the accuracy gain justifies the cost.
Model changes.
- Pin dated snapshots; moving aliases change behaviour without a deploy on your side.
- Snapshots are deprecated on a schedule, so migration is recurring work. Keep an eval suite that re-qualifies a new model, and expect to re-tune prompts: instructions that compensated for the old model can hurt the new one.
- Roll out with shadow traffic or a canary, comparing quality, latency and cost.
- Keep periodic canary prompts in production to detect upstream drift.
The goal is system-level reliability from an unreliable component, the same way distributed systems treat networks.
Follow-ups
- A test passes locally and fails in CI one time in ten. What do you do?
- How do you decide the number of trials per eval case?
seniordesignAI MLE REasked at Anthropic You have one helper, logprob(prompt, continuation), which returns the log-probability a language model assigns to a continuation. Build a binary text classifier from it, with a calibrated probability and a threshold you can defend.
Score by comparing label continuations. Put the input in a template that ends where the answer starts, and compare the log-probabilities of the two answers:
import numpy as np
YES, NO = [" Yes", " yes"], [" No", " no"]
TEMPLATE = "Review: {text}\nIs this review positive? Answer Yes or No.\nAnswer:"
def logsumexp(v):
v = np.asarray(v); m = v.max()
return m + np.log(np.exp(v - m).sum())
def score(text, logprob):
p = TEMPLATE.format(text=text)
return logsumexp([logprob(p, v) for v in YES]) - logsumexp([logprob(p, v) for v in NO])The difference is a log-odds restricted to the two labels, so probability mass on anything else cancels.
What goes wrong, and the fix for each.
- Surface forms. “Yes”, “yes” and “Y” split the mass. Sum over the verbalisers of each class (the
logsumexpabove). - Tokenisation. The leading space and the casing change the tokens. A multi-token label has a lower log-probability only because it is longer, so choose single-token labels of similar frequency, or normalise.
- Prior bias. The model prefers one answer regardless of input, and few-shot examples add a bias toward the majority and the most recent label. Correct it by subtracting the score of a content-free input (“N/A”), or better, by fitting a calibration map on labelled data.
- Prompt sensitivity. Average the score over a few paraphrased templates.
Calibrate on a small labelled set. Fit \(p = \sigma(a s + b)\) (Platt scaling) on a few hundred examples:
def fit_platt(s, y, steps=2000, lr=0.1):
a, b = 1.0, 0.0
for _ in range(steps):
p = 1 / (1 + np.exp(-(a * s + b)))
a -= lr * np.mean((p - y) * s); b -= lr * np.mean(p - y)
return a, bIn a simulation with a helper that is overconfident by a factor of 3 and biased toward “Yes”, fitting on 500 examples cut log loss from 0.59 to 0.35 and barely changed accuracy: calibration fixes the probabilities, not the ranking.
Threshold. Choose it on held-out data from the cost of each error, or to hit a target precision, and report the confidence interval: with 500 examples a precision estimate is loose. Add an abstain band around the threshold if a human can take the uncertain cases.
Evaluation. AUROC and PR-AUC for ranking, log loss and a reliability diagram for calibration, both by slice (length, language, source). Keep the calibration set, the threshold set and the test set separate.
Cost. One call per label per template. Cache the shared prompt prefix, batch, and if the helper can return the next-token distribution, read both labels from one call.
Limits to state. Calibration is specific to the model version and the template, so refit after either changes. And a zero-shot score is a baseline: with a few thousand labels, a small classifier on the model’s embeddings is usually cheaper and better.
Follow-ups
- Extend this to 50 classes with multi-token names. What breaks first?
- The calibrated classifier drifts after a model upgrade. How do you detect it without new labels?
- Why can few-shot examples make the classifier worse on the minority class?
Reported in interviews (candidate reports on third-party sites, not verified)
- Anthropic, Software Engineer, Sep 2025: Binary text classifier using only an LLM log-probability helper (PracHub)
Prompt and context engineering 22% of postings
- List what goes into the context window and order it for both quality and cache reuse
- Describe compaction strategies and what must survive a summary verbatim
- Decide between long-context stuffing, one-shot retrieval and agentic retrieval
- Explain prompt caching as a prefix match and name the common silent invalidators
- Run prompts as versioned artefacts with a regression suite and pinned model versions
- Choose few-shot examples and say when they hurt
coreconceptMLE AI RE What goes into the context window of a production LLM feature, and how do you order it?
Context engineering is choosing the smallest set of high-signal tokens that makes the next output correct. The layers:
- Rules: role, policies, output contract. Stable and authoritative.
- Tool definitions.
- Reference material: retrieved documents, few-shot examples.
- State: plan, progress, known constraints, open errors.
- History: recent turns and tool results.
- The current request.
Ordering principles:
- Stable first, volatile last. Prompt caches match on the prefix, so tools, system prompt and fixed documents go first; timestamps, user-specific data and the question go last.
- Long documents before the question, with the instruction restated at the end. Models attend best to the start and end of long inputs (“lost in the middle”), so do not bury the key instruction or the key passage mid-context.
- Delimit data from instructions (tags or fenced sections) and label untrusted content as data to be analysed, not obeyed.
- Say why, not just what. A short reason for a rule generalises better than emphasis.
Few-shot examples: three to five, diverse, covering edge cases, in exactly the output format you want. For heterogeneous inputs, select examples per request by similarity. Models copy surface features of examples, so near-identical examples narrow the output.
Failure modes: contradictory instructions accumulated over time, stale retrieved content, tool outputs that swamp the window, and treating a transcript dump as state.
Follow-ups
- How would you test whether an instruction in the prompt is still doing anything?
- When do few-shot examples make outputs worse?
seniorconceptAI RE Your agent’s context fills up on long tasks. What are the compaction strategies and what can go wrong?
Quality degrades before the hard limit: long, noisy contexts make models miss instructions and reuse stale information. So manage context continuously, not only at overflow.
Strategies, cheapest first.
- Bound tool output at the source: return the relevant slice, store the full output as an artefact with a pointer.
- Clear old tool results: keep the record that the call happened, drop the bulky payload that can be re-fetched.
- Summarise history into structured state: goal, user constraints, decisions and their reasons, files or entities touched, open errors, failed attempts, next steps.
- Externalise: write notes or plans to files or a memory store and re-read on demand.
- Isolate: push exploration into a sub-agent that returns only its conclusion.
What must survive verbatim. User constraints, the definition of done, unresolved errors, the reasons earlier approaches failed, and source attributions.
Costs. Summaries are lossy, and rewriting history invalidates the prompt cache from that point, so compaction trades a one-time cache miss for a smaller context. Trigger at a threshold well below the limit so the summary itself has room.
Failure modes. The agent repeats an approach whose failure was summarised away; a user constraint disappears; the summary states a guess as a fact.
How to test. Evals that interrupt a run, compact, and resume; compare task success and repeated-action rate with and without compaction.
Follow-ups
- How do you choose between clearing tool results and summarising?
- What is the compaction analogue of a regression test?
seniortrade-offMLE AIasked at OpenAI Context windows now reach a million tokens. Why still build retrieval, and when would you just put everything in the prompt?
Put it all in the prompt when the corpus is small enough to fit comfortably, changes rarely, and every user may see all of it. With prompt caching the repeated prefix is cheap on later requests, there is no retrieval miss, and the model can reason across documents. This is the right first version for a knowledge base of tens to a few hundred pages.
Build retrieval when any of these holds:
- Size: the corpus exceeds the window, or will.
- Cost and latency: input cost and time to first token scale with prompt length on every request; at high QPS a long prompt per request dominates the bill even with caching.
- Access control: different users may see different documents, which breaks a shared cached prefix and makes “put everything in” a leak.
- Freshness: documents change; re-indexing a changed document is cheaper than invalidating a huge cached prompt.
- Accuracy: irrelevant material acts as distractors, and recall of a specific fact drops as context grows.
- Attribution: retrieval gives a natural unit for citations.
Retrieval’s weakness is that a one-shot miss is unrecoverable: if the passage is not in the top k, the model cannot answer. Global questions (“summarise the themes across all contracts”) also do badly with top-k chunks.
The middle option is agentic retrieval: give the model search and read tools and let it iterate. It recovers from misses and handles multi-hop questions, at the price of more calls and latency.
Decide from corpus size against window, update rate, QPS times tokens, permission model, and question types, and confirm with an eval rather than by argument.
Follow-ups
- How would you measure the distractor effect on your own data?
- What does per-user access control do to your cache hit rate?
Reported in interviews (candidate reports on third-party sites, not verified)
- OpenAI, Product Manager, Apr 2026: How context window length affects quality, cost and latency (PracHub)
- OpenAI, Machine Learning Engineer, undated: Effect of adjusting an LLM’s context window size (Aced (formerly Exponent))
seniorconceptMLE AI How does prompt caching work, and how does it change the way you lay out a prompt?
The provider stores the model’s computed state for a prompt prefix. A later request whose prompt starts with exactly the same tokens reuses it, so those input tokens are billed at a discount and time to first token drops.
It is a prefix match. A change at any position invalidates everything after it. So the layout is: tool definitions, then system prompt, then fixed reference material, then conversation history, then the volatile part (current question, timestamps, per-request data).
Silent invalidators.
- A timestamp, request id or user name near the top of the system prompt.
- Non-deterministic serialisation: unsorted JSON keys, tools listed in varying order.
- Adding or removing a tool mid-conversation.
- Rewriting earlier history (compaction, trimming, editing a message).
- Switching models; caches are per model.
Provider differences (check current documentation). Some cache automatically above a minimum prefix length; others need explicit cache breakpoints. Lifetimes are short, typically minutes, extended on use. Discounts vary: on Anthropic’s API reads cost about a tenth of the base input price and writes carry a premium of about 25%, so a cached prefix pays off from the second request.
Why it matters most for agents. Each step re-sends the whole history. With an append-only history, each step pays full price only for the new tokens.
Operate it. Log cached versus uncached input tokens per request, track the hit rate, and alert when it falls; a prompt edit that drops the hit rate to zero can multiply cost with no visible behaviour change.
Follow-ups
- You need the current date in the prompt. Where do you put it?
- How would you inject a new operator instruction mid-conversation without losing the cache?
seniorconceptAIasked at OpenAI, Anthropic How do you run prompt engineering as an engineering discipline rather than trial and error?
Treat prompts, tool descriptions and model settings as code with tests.
- Version control. Prompts live in the repository as templates, separate from the data interpolated into them. Every production trace records the prompt version and the model version.
- Regression suite. A golden set of inputs with graders (code checks where possible, validated LLM judges otherwise) runs on every change. The pull request shows per-slice scores and the individual examples that flipped, not only the average.
- Held-out data. Tune against a development split and confirm on a held-out split. Editing a prompt until five hand-picked examples pass is overfitting.
- Pinned models. Use dated model snapshots, not moving aliases. A model upgrade is a change like any other: re-run the suite and expect to re-tune, because instructions written to compensate for an older model’s weaknesses can hurt a newer one.
- Staged rollout. Shadow or canary, then A/B on online metrics.
- Root cause before patching. When an output is wrong, find out whether it is missing context, a conflicting instruction, a retrieval miss or a tool problem. Appending “IMPORTANT: never do X” for each incident produces a long, contradictory prompt.
- Injection surface. Keep an inventory of every place where user, document or tool text is interpolated into the prompt; each is an attack surface and needs delimiting and downstream controls.
Automated prompt optimisation (DSPy-style) fits the same frame: it needs a metric and a dataset, and its output is reviewed and tested like a human-written prompt.
Follow-ups
- A prompt change fixes one customer’s issue and lowers the suite score by a point. Ship?
- How large does the golden set need to be to detect a 3-point regression?
Reported in interviews (candidate reports on third-party sites, not verified)
- OpenAI / Anthropic, Machine Learning Engineer, undated: Your approach to prompt engineering (Aced (formerly Exponent))
Retrieval-augmented generation 22% of postings
- Walk through ingestion, chunking, embedding, hybrid retrieval, reranking, generation and citation
- Explain how chunk size trades retrieval precision against context and name three chunking strategies
- Implement reciprocal rank fusion and say why hybrid beats dense-only on identifiers and rare terms
- Triage a wrong answer into index, retrieval, context assembly or generation failure
- Enforce document permissions at retrieval time and explain why post-generation filtering is unsafe
- Evaluate retrieval (recall@k, nDCG) separately from generation (faithfulness, correctness, abstention)
coreconceptMLE AIasked at OpenAI, Amazon Walk me through a RAG system end to end, offline and online, and say where it usually breaks.
Offline (ingestion).
- Parse: PDFs, HTML, slides, tables, scans (OCR). Layout and table extraction quality bounds everything downstream.
- Chunk: split into retrievable units, keeping structure (headings, tables, code).
- Enrich: metadata per chunk (source, title, section path, date, version, permissions).
- Embed and index: a vector index plus a lexical (BM25) index.
- Keep fresh: incremental updates from change events, deletions, periodic reconciliation.
Online (query).
- Query processing: rewrite a conversational turn into a standalone query; optionally decompose or expand.
- Retrieve: top 50-100 candidates from dense and lexical retrieval, with metadata and permission filters applied in the retriever.
- Rerank: a cross-encoder or LLM reranker cuts to the best 5-10.
- Assemble: passages with source ids, ordered and deduplicated, within a token budget.
- Generate: answer only from the passages, cite ids, abstain if unsupported.
- Check: citation and groundedness verification before returning.
Where it breaks. Most failures are upstream of the model: a table parsed into noise, a chunk boundary that separates a number from its meaning, a query whose exact identifier dense retrieval misses, a stale version of a document outranking the current one. Fewer are generation failures: the model ignores the passage, blends in prior knowledge, or answers when it should abstain.
Changing the embedding model means re-embedding the whole corpus, so version the index.
Follow-ups
- Which stage would you instrument first, and with what metric?
- How do you handle a question the corpus cannot answer?
Reported in interviews (candidate reports on third-party sites, not verified)
- OpenAI, Machine Learning Engineer, Dec 2025: Design and optimise a RAG system over a private corpus (PracHub)
- OpenAI, Machine Learning Engineer, Aug 2025: Production RAG for enterprise document question answering (PracHub)
- OpenAI, Machine Learning Engineer, Jul 2025: Enterprise search using RAG (PracHub)
- OpenAI, Machine Learning Engineer, Jul 2025: Low-latency RAG for customer support (PracHub)
- Amazon, Data Scientist, Jan 2026: Design and evaluate a RAG system for internal Q&A (PracHub)
coretrade-offMLE AI How do you choose a chunking strategy and chunk size?
Chunk size trades retrieval precision against context. Small chunks give a focused embedding and precise matches but lose the surrounding meaning (“it increased 12%” with no subject). Large chunks keep context but dilute the embedding across several topics and spend prompt tokens on irrelevant text.
A reasonable starting point is a few hundred tokens with 10-20% overlap; treat it as a hyperparameter and tune on a retrieval eval.
Strategies:
- Fixed size with overlap: simple baseline; splits mid-sentence and mid-table.
- Structure-aware / recursive: split on headings, then paragraphs, then sentences; keep tables, lists and code blocks whole.
- Semantic: split where the similarity between adjacent sentences drops.
- Small-to-big (parent-child): index small chunks for matching, return the enclosing section to the model.
- Contextual chunks: prepend the document title and section path, or a short model-written sentence situating the chunk, before embedding. This repairs lost referents.
Choose by document type: structured manuals and code favour structure-aware splitting; transcripts and prose favour semantic or sliding windows; FAQs are one chunk per question.
Evaluate with recall@k and nDCG on labelled queries, and end-to-end answer correctness. Looking at a few chunks is not an evaluation.
Failure modes: answers that span a boundary, split tables, overlap that returns the same text twice, and chunks so short that everything matches weakly.
Follow-ups
- Recall@10 is fine but answers lack context. What do you change?
- How does the embedding model’s maximum input length constrain your choice?
seniorconceptMLE AI Why use hybrid retrieval and a reranker, and when does query rewriting help?
Hybrid. Dense retrieval matches meaning and paraphrase but is weak on exact tokens it did not learn well: product codes, error strings, rare names, new jargon. Lexical retrieval (BM25) is the opposite: exact on tokens, blind to synonyms. Their errors are complementary, so fusing them raises recall. Fuse with reciprocal rank fusion (rank-based, no score calibration needed) or a weighted sum of normalised scores.
Reranking. First-stage retrieval encodes query and document separately (a bi-encoder), which is fast but coarse. A cross-encoder reads the query and passage together and scores relevance much more accurately, at one forward pass per candidate. So retrieve 50-200 candidates cheaply and rerank to 5-10. Cost: tens to a few hundred milliseconds, depending on model size and candidate count.
Query rewriting.
- Standalone rewrite: resolve “what about the second one?” into a self-contained query. Close to mandatory for multi-turn chat.
- Decomposition: split a multi-hop question into sub-queries.
- Expansion: add synonyms or generate several paraphrases and fuse the results.
- HyDE: embed a hypothetical answer instead of the question, which moves the query closer to document space.
Rewriting costs an extra model call and can drift from the user’s intent, so keep the original query in the fusion.
Add each stage only if it moves recall@k or nDCG on a labelled set; a reranker on top of a retriever that misses the document fixes nothing.
Follow-ups
- How do you set the candidate depth before reranking?
- When does dense-only retrieval beat hybrid?
seniorcodingMLE AI Implement hybrid retrieval with reciprocal rank fusion.
RRF scores a document by its ranks across retrievers: \(\mathrm{RRF}(d) = \sum_{r} \frac{w_r}{k + \mathrm{rank}_r(d)}\), with \(k = 60\) by convention and ranks starting at 1. A document absent from a list contributes nothing for that list.
from collections import defaultdict
def rrf(rankings, k=60, weights=None):
"""rankings: list of ranked lists of doc ids, best first. Returns [(doc_id, score)]."""
weights = weights or [1.0] * len(rankings)
scores = defaultdict(float)
for w, ranking in zip(weights, rankings):
seen = set()
for rank, doc_id in enumerate(ranking, start=1):
if doc_id in seen: # count each doc once per list
continue
seen.add(doc_id)
scores[doc_id] += w / (k + rank)
return sorted(scores.items(), key=lambda x: (-x[1], str(x[0]))) # deterministic ties
def hybrid_search(query, bm25, embed, ann, top_k=10, depth=100, flt=None):
lexical = bm25.search(query, depth, filter=flt) # -> [doc_id, ...]
dense = ann.search(embed(query), depth, filter=flt) # -> [doc_id, ...]
return rrf([lexical, dense])[:top_k]Pitfalls:
- RRF uses ranks only, so it needs no score normalisation but ignores how confident each retriever was. A weighted sum of normalised scores can do better if scores are calibrated.
- Fuse at one granularity. If one retriever returns chunks and the other documents, map both to the same id first.
- Retrieve deeper than
top_kfrom each list, or fusion has nothing to add. - Apply permission and metadata filters inside each retriever. Filtering after fusion can leave fewer than
top_kresults, and for permissions it is the wrong place. - \(k\) damps the influence of top ranks; small \(k\) makes rank 1 dominate.
- Tune weights and depth on a labelled set; follow with a reranker if latency allows.
Follow-ups
- Why is k around 60 and what happens at k = 0?
- How would you add a third retriever that is much noisier than the other two?
seniorcodingMLE AI Implement semantic chunking: split a document where the topic changes, with size limits.
Embed sentences, measure the cosine distance between neighbours, and cut at the largest jumps, subject to minimum and maximum chunk sizes.
import re
import numpy as np
def semantic_chunks(text, embed, max_tokens=400, min_tokens=80, pct=90,
n_tokens=lambda s: len(s.split())):
sents = [s.strip() for s in re.split(r"(?<=[.!?])\s+", text) if s.strip()]
if len(sents) < 2:
return sents
E = np.asarray(embed(sents), dtype=np.float32) # (n, d)
E /= np.linalg.norm(E, axis=1, keepdims=True) + 1e-12
dist = 1.0 - np.sum(E[:-1] * E[1:], axis=1) # (n-1,) neighbour distance
thresh = np.percentile(dist, pct) # cut at the largest jumps
chunks, cur, cur_len = [], [sents[0]], n_tokens(sents[0])
for i in range(1, len(sents)):
n = n_tokens(sents[i])
topic_shift = dist[i - 1] > thresh and cur_len >= min_tokens
if topic_shift or cur_len + n > max_tokens:
chunks.append(" ".join(cur))
cur, cur_len = [], 0
cur.append(sents[i])
cur_len += n
chunks.append(" ".join(cur))
return chunksPitfalls:
- Single-sentence embeddings are noisy. Embedding a sliding window of two or three sentences around each position gives steadier boundaries.
- The percentile threshold is relative to the document, so a single-topic document is still cut at its top 10% of jumps; the minimum size limits the damage.
- A single sentence longer than
max_tokensstill needs a hard split. - The regex splitter breaks on abbreviations, decimals, code and tables. Split on structure (headings, tables, code blocks) first and apply this within sections.
- Count tokens with the embedding model’s tokenizer, not whitespace.
- Ingestion cost is one embedding per sentence.
- Semantic chunking does not always beat structure-aware fixed-size chunking. Compare recall@k on labelled queries before adopting it.
Follow-ups
- How would you add overlap or parent-child retrieval to this?
- What is the time complexity, and where is the cost in practice?
seniordebuggingMLE AIasked at OpenAI, Anthropic, Google Users report that your RAG assistant gives confidently wrong answers. How do you find the cause and fix it?
Take a sample of wrong answers with their traces and assign each to the first stage that failed:
- Not in the index: the document was never ingested, was parsed badly (tables, scans), or is stale.
- Indexed but not retrieved: not in the top k. Vocabulary mismatch, an exact identifier dense retrieval missed, a bad chunk boundary, an over-restrictive filter.
- Retrieved but not in the prompt: dropped by the reranker or the token budget.
- In the prompt but answered wrongly: the model ignored it, blended in prior knowledge, or picked one of two conflicting or outdated passages.
- Unanswerable: the corpus has no answer and the model produced one anyway.
The distribution across buckets tells you where to work. Prompt edits only help buckets 4 and 5.
Fixes by bucket: better parsing and freshness monitoring (1); hybrid retrieval, query rewriting, chunking changes (2); deeper candidates, reranker tuning, larger budget (3); instructions to answer only from sources, recency and authority metadata, deduplication of versions (4); explicit abstention plus an answerability check (5).
For the “confidently” part:
- Require a citation per claim and verify after generation that each cited passage supports its claim (entailment model or LLM judge); block or flag unsupported claims.
- Abstain when retrieval scores are low or passages disagree.
- Show sources to the user.
Then keep it fixed: put the failures into the regression set, and track retrieval recall and groundedness on sampled production traffic.
Follow-ups
- Two retrieved documents contradict each other. What should the system do?
- How do you measure abstention quality without making the system refuse everything?
Reported in interviews (candidate reports on third-party sites, not verified)
- OpenAI / Anthropic, Machine Learning Engineer, undated: Handle hallucinations in a generative model deployed to users (Aced (formerly Exponent))
- Anthropic, Machine Learning Engineer, undated: Fix a conversational model that is confidently wrong in high-risk contexts (Aced (formerly Exponent))
- Google, Product Manager, Oct 2026: Detect and contain confident false outputs in a customer-facing product (PracHub)
staffdesignMLE AIasked at OpenAI, Google Design enterprise RAG over documents with access controls (SharePoint, Drive, Confluence, Slack) for a company with tens of thousands of employees.
Requirements to pin down. Sources and volume, freshness target for content and for permission changes, the non-negotiable (a user never sees content they cannot open at source), citations, audit, tenancy and data residency.
Ingestion. One connector per source with incremental sync (change feeds or webhooks) and a periodic full reconcile to catch missed events and deletions. Each document is stored with its ACL: users, groups, inheritance and link-sharing rules. Source principals are mapped to one company identity; group membership is synced separately because it changes without the document changing.
Enforcing permissions. Filter at retrieval, before anything reaches the model. Content the user may not see must never enter the context window; a model cannot be trusted to withhold what it has read.
- Index-time ACLs: store allowed principals on each chunk and filter by the user’s expanded principal set. Fast, but stale until the next sync.
- Query-time check: confirm the top results against the source system. Always current, but slower.
- Use both: filter in the index, then verify the final few results at source.
Revocation latency is a stated SLO. Response caches and semantic caches are keyed by permission scope or disabled.
Retrieval and generation. Structure-aware chunking with title and path context; hybrid retrieval with filter-aware ANN, falling back to exact search when a user’s permitted set is small; reranking; generation with citations that link to the source, which re-checks access.
Security. Documents are untrusted input (indirect injection), so the answering model gets no write tools. Per-tenant isolation. Audit log of who queried and which documents were retrieved. PII handling and retention.
Evaluation. Per-source retrieval sets; a permission test suite with canary documents that specific test users must never retrieve, run continuously; groundedness and citation accuracy; freshness lag dashboards.
Scale risks. Group fan-out for users in thousands of groups, very selective filters degrading ANN recall, and re-embedding the corpus on a model change.
Follow-ups
- A user is removed from a group. Walk me through what must happen and how fast.
- Why is filtering the generated answer not sufficient?
- How would you test for a permission leak before launch?
Reported in interviews (candidate reports on third-party sites, not verified)
- OpenAI, Machine Learning Engineer, Sep 2026: Multi-tenant enterprise RAG assistant with hybrid retrieval, reranking and access controls (PracHub)
- OpenAI, Machine Learning Engineer, Sep 2025: Multi-tenant enterprise document search with ML ranking (PracHub)
- Google, Software Engineer, Aug 2026: Internal document-search agent with permissions and citations (PracHub)
seniorconceptMLE AIasked at Amazon How do you evaluate a RAG system? Be specific about retrieval versus generation.
Evaluate the stages separately, then end to end, because an end-to-end score cannot tell you which stage to fix.
Retrieval. Labelled pairs of query and relevant chunk or document ids.
- recall@k: is the needed passage among the k passed on? This caps answer quality.
- MRR or nDCG@k: is it ranked high enough to survive truncation?
- Report by query type (lookup, multi-hop, identifier, conversational).
Generation, given the retrieved context.
- Faithfulness / groundedness: is every claim supported by the provided passages?
- Answer correctness against a reference answer.
- Citation precision and recall: do citations support the claims, and are claims cited?
- Abstention: on unanswerable questions, does it decline; on answerable ones, does it not?
Diagnostic matrix. Cross retrieval hit or miss with answer right or wrong. A hit with a wrong answer is a generation problem; a miss with a right answer means the model used prior knowledge, which is a risk; a miss with a wrong answer is a retrieval problem.
Building the set. Sample real queries and have experts label; include unanswerable, multi-hop and ambiguous queries. Synthetic questions generated from chunks are useful for volume but are lexically close to their source and overstate retrieval quality.
Graders. Retrieval metrics are computed in code. Faithfulness and correctness usually need an LLM judge, validated against human labels before it is trusted.
Online. Citation click-through, reformulation rate, thumbs, escalation to a human, and sampled traces scored by the same graders.
Follow-ups
- Your labelled set only marks one relevant chunk per query but several exist. What happens to your metrics?
- How would you get retrieval labels cheaply?
Reported in interviews (candidate reports on third-party sites, not verified)
- Amazon, Data Scientist, Jan 2026: Design and evaluate a RAG system for internal Q&A (PracHub)
Tool use, function calling, MCP 21% of postings
- Explain the function-calling protocol end to end, including how tool results are paired with calls
- Design a tool schema that is hard to misuse (enums, required fields, non-overlapping tools, compact results)
- Classify tools by side effect and make retried writes idempotent
- Decide which parallel tool calls may run concurrently and how partial failures are reported
- Describe what MCP standardises (tools, resources, prompts, transports, authorization) and its security concerns
- Say when computer or browser use is justified over an API tool and how to contain it
coreconceptMLE AI RE How does function calling work, and what makes a tool definition good?
Mechanism. You send tool definitions (name, description, JSON Schema for parameters) with the request; they are rendered into the model’s context. The model either answers in text or emits a structured call (tool name plus JSON arguments). The model executes nothing: your code parses the call, runs the function and sends the result back as a tool message tied to the call id, and the model continues. Tool definitions cost input tokens on every request.
What makes a definition good.
- Few, non-overlapping tools. Two tools that could both apply create selection errors. Prefer one task-shaped tool (
get_order_status) over thin wrappers around three endpoints. - Descriptions written for a newcomer: what it does, when to use it, when not to, what it returns, with an example for tricky arguments.
- Tight schemas: enums instead of free strings, required fields, explicit formats (ISO dates, ids), flat rather than deeply nested. Make invalid states hard to express.
- Results designed for the model: compact, stable field names, ids that can be passed to the next call, pagination or truncation with a note that more exists.
- Declared side-effect class: read, reversible write, irreversible action.
Schema-constrained (“strict”) tool calling, where the provider supports it, guarantees arguments parse and match the schema. It does not guarantee they are correct, so validate semantics and authorisation server-side.
With dozens of tools, selection accuracy drops and definitions crowd the context: namespace them, load definitions on demand through a tool-search step, or route to a subset.
Follow-ups
- How would you find out that two tool descriptions are confusing the model?
- Why return ids rather than names in tool results?
seniortrade-offAI Talk me through error handling, parallel tool calls and idempotency in a tool executor.
Validation before execution. Check arguments against the schema, then semantics (ranges, existence) and authorisation (does this user own this resource). The model’s arguments are untrusted input.
Three error classes.
- Transient (timeout, 429, 5xx): the harness retries with backoff; the model need not know unless retries are exhausted.
- Model-fixable (bad argument, not found, precondition failed): return as a tool result saying what failed and what a valid call looks like, so the model can correct itself.
- Fatal (auth revoked, invariant violated, policy denial): stop or escalate; do not let the model work around it.
Parallel calls. Models often emit several calls in one turn. Run them concurrently only when their effects commute: reads in parallel, writes serialised. Whether a tool is parallel-safe is metadata on the tool, decided in code. Return a result for every call, including failures, each tied to its call id.
Idempotency. A timed-out write may have succeeded. Retrying a payment, an email or a deploy can duplicate it. Options: an idempotency key per logical action that the downstream system deduplicates on; check-then-act (read current state before retrying); or a two-phase prepare-and-confirm for irreversible actions. Retried model turns can also re-propose the same action, so dedupe at the action level, not only the HTTP level.
Bounds. Per-tool timeouts, output size caps, and rate limits per run.
Follow-ups
- The downstream API has no idempotency support. What do you do?
- One of four parallel calls fails. What does the model see?
coreconceptAI What is the Model Context Protocol, what does it standardise, and what are its security concerns?
MCP is an open protocol, introduced by Anthropic in late 2024 and since adopted by other vendors, for connecting LLM applications to external tools and data. It turns the M x N integration problem (every app times every system) into M + N: a system exposes one MCP server, and any MCP-capable host can use it.
Architecture. A host application (IDE, chat app, agent runtime) runs MCP clients, each holding a connection to one server. Messages are JSON-RPC 2.0, with capability negotiation at initialisation.
Server primitives.
- Tools: functions the model can call, with a name, description and JSON Schema input.
- Resources: data the application can read into context (files, records), addressed by URI.
- Prompts: reusable templates the user can invoke.
Clients can offer features back to servers, such as sampling (the server asks the host’s model for a completion) and roots (which directories are in scope).
Transports. stdio for local servers started as subprocesses, and Streamable HTTP for remote servers (it replaced the earlier HTTP+SSE transport). Remote authorization is based on OAuth 2.1. The specification is still evolving, so check the current revision.
Security concerns.
- Tool descriptions and tool results are untrusted text that enters the model’s context: a malicious or compromised server can inject instructions (“tool poisoning”).
- A server holds real credentials; over-broad scopes and token pass-through create confused-deputy problems.
- A local stdio server runs with the user’s privileges.
- The host’s sandbox does not automatically cover what an MCP server does.
Mitigations: allowlist servers, pin versions, least-privilege scopes, per-tool approval for writes, and treat everything returned as data.
Follow-ups
- How is an MCP tool different from a function you define in the request?
- Fifty MCP servers are connected and tool definitions fill the context. What do you do?
seniordebuggingAI Two percent of your agent’s tool calls are malformed. How do you investigate and fix it?
Two percent per call is not small: over a 20-call trajectory the chance of at least one malformed call is \(1 - 0.98^{20} \approx 33\%\).
Classify the failures from logs first.
- Invalid JSON: usually truncation (finish reason is
length), or unescaped quotes and newlines inside long string arguments such as code or documents. - Schema-invalid: missing required field, wrong type, invented enum value.
- Unknown tool name: hallucinated or from a stale tool list.
- Client bug: streamed argument deltas concatenated in the wrong order or across calls.
Look for what the failures correlate with. One tool, long arguments, long context, parallel calls, a model version, streaming versus non-streaming.
Fixes, most effective first.
- Turn on schema-constrained (strict) tool calling if the provider offers it; this removes syntax and schema errors, except truncation.
- Raise the output token limit, and treat
lengthas an error rather than parsing a partial call. - Simplify the schema: flatten nesting, fewer optional fields, enums, and move large payloads out of JSON (write to a file, pass a reference).
- Validate before execution and return the validation error to the model for one bounded repair attempt.
- Fix the streaming accumulator (key deltas by call index).
- Tighten the description, add one example of a correct call.
Then make the malformed-call rate a tracked metric per tool and per model version, alert on it, and add the failing inputs to the regression suite so a model or prompt change that brings it back is caught.
Follow-ups
- Constrained decoding is on and you still see failures. What are they?
- Why not just retry the whole request?
seniortrade-offAI RE When would you give an agent computer or browser use instead of API tools, and how do you contain it?
Computer use means the model perceives a screen (screenshots, sometimes with a DOM or accessibility tree) and emits mouse and keyboard actions in a perceive-act loop. It is the tool of last resort: use it when the target has no API (legacy desktop software, third-party sites, UI testing).
Order of preference. A structured API tool; then browser automation over the DOM or accessibility tree (text is cheaper and more reliable to ground than pixels); then pixel-level control.
Why it is last.
- Slow: every step is a screenshot plus a model call, so seconds per action and minutes per task.
- Expensive: image tokens on every step.
- Brittle: layout changes, pop-ups, loading states, mis-grounded click coordinates.
- Hard to verify: success must be checked from the resulting state, not from the model’s claim.
- Large attack surface: any text on any page is a potential injected instruction, and the agent may hold a logged-in session.
Containment. Run in an isolated VM or a dedicated browser profile with no ambient credentials; allowlist domains; require human confirmation for logins, purchases, sending messages and anything irreversible; cap steps and time; record the session; verify the end state with an independent check.
Evaluation. Task success on sandboxed, resettable sites or VMs, with steps and cost per task; expect high run-to-run variance, so run each task several times.
Follow-ups
- How do you check that a form was actually submitted?
- What would you do about a page that tells the agent to email its cookies somewhere?
Workflow automation and enterprise integration 17% of postings
- Split a business process into deterministic steps and model steps
- Choose between delegated user credentials and a service account and keep credentials away from the model
- Make writes to systems of record idempotent and auditable
- Place human review using confidence and impact thresholds and feed corrections back into evals
seniordesignAI A finance team wants to automate invoice processing into their ERP with an LLM. How do you design the integration?
Map the process first. Receive, extract fields, match to purchase order, validate, approve, post to the ERP, handle exceptions. Use the model where judgment or unstructured input is involved (reading the document, classifying exceptions, drafting a query to the vendor). Keep matching rules, tolerances, approval limits and posting in code.
Architecture. An event (new email or upload) starts a durable workflow. Each model step returns schema-constrained output with supporting quotes; code validates it (totals add up, vendor exists, PO matches within tolerance). Passing items post through the ERP API; failing or low-confidence items go to a review queue with the evidence shown.
Auth and permissions. The workflow, not the model, holds credentials. Use delegated user tokens (OAuth, least scopes) when acting for a person, or a service account with narrowly scoped rights for back-office automation. The ERP still enforces its own authorisation; the model never sees secrets.
Idempotency. Every write carries a key derived from the business object (invoice id plus action), with a dedupe check, so retries and replays cannot double-post. Multi-step updates need compensation steps.
Audit. Record for each item: inputs, extracted values and quotes, model and prompt versions, validation results, who approved, and what was written. Auditors must be able to reconstruct why an invoice was paid.
Human review. Thresholds on confidence and amount; reviewer corrections are captured as labelled data for evals and prompt improvement.
Integration realities. API rate limits, pagination, schema changes, duplicate documents, and documents in formats the parser has not seen.
Rollout and metrics. Shadow mode against human decisions, then auto-post the high-confidence segment. Track straight-through rate, error rate from sampled audits, cycle time and cost per invoice.
Follow-ups
- How do you set the confidence threshold for auto-posting?
- The ERP API times out after you send a post request. What happens next?
Guardrails, safety filters, hallucination control 16% of postings
- Define direct and indirect prompt injection and explain why prompting alone cannot prevent it
- State the combination of capabilities that makes exfiltration possible and how to break it
- Lay out input, tool-boundary, output and system-level controls and the latency each adds
- Describe hallucination controls (grounding, citations, abstention, verification)
- Measure a guardrail with both attack success rate and false positive rate on benign traffic
coreconceptMLE AI REasked at Anthropic What is prompt injection, what is indirect prompt injection, and why can you not fix it with a better system prompt?
A language model receives instructions and data in one token stream and has no reliable way to tell them apart. Prompt injection exploits this.
- Direct injection: the user writes text that overrides the application’s instructions (“ignore the above and…”). A jailbreak is the related attack on the model’s own safety policy rather than the application’s instructions.
- Indirect injection: the instructions are planted in content the system reads on the user’s behalf: a web page, email, document, code comment, tool result or tool description. The user is the victim, not the attacker.
A stronger system prompt or delimiters around untrusted text lowers the success rate but does not make it zero, and an attacker can retry. So assume some injections succeed and limit what a successful one can do.
The dangerous combination is an agent that has all three of: access to private data, exposure to untrusted content, and a way to send data out (web requests, email, rendering a URL or image). Remove one and exfiltration is blocked.
Defence in depth:
- Least-privilege tools; read-only where possible.
- Human approval for consequential or outbound actions.
- Egress control: allowlisted domains, no auto-rendering of model-produced links or images.
- Isolation: a quarantined model reads untrusted content and returns constrained data to a privileged one that never sees the raw text.
- Taint tracking: once untrusted content is in context, restrict the tools available.
- Injection classifiers on inputs and tool results, as one layer.
- Logging and a red-team suite that measures attack success rate.
Follow-ups
- Your agent summarises a web page and can send email. What is the attack and what do you remove?
- Why does markdown image rendering matter?
Reported in interviews (candidate reports on third-party sites, not verified)
- Anthropic, Product Manager, Apr 2026: Dual-use requests, jailbreaks and layered defences (PracHub)
staffdesignAI Design the guardrails for an LLM assistant that answers from company data and can take actions. What are the layers and how do you know they work?
No single filter is sufficient; each layer covers failures the others miss.
| Layer | Controls | Catches |
|---|---|---|
| Input | abuse and rate limits, moderation classifier, PII detection, injection classifier | abusive or policy-violating requests, bulk probing |
| Model | system policy, a model version with tested refusal behaviour | most ordinary misuse |
| Data and tool boundary | permission-filtered retrieval, tool allowlists, argument validation, sandbox, approval for writes | injection consequences, data leaks, wrong actions |
| Output | schema validation, groundedness check against sources, PII and secret scan, moderation | hallucinated claims, leaked data, harmful text |
| System | audit log, monitoring, kill switch, incident process | what slipped through |
Hallucination control sits mainly at the output and data layers: answer only from retrieved sources with citations, abstain when support is missing, verify claims against their cited passages, choose from enumerated values instead of free text, and compute numbers in code.
PII. Redact in logs and traces by default, minimise what is sent to the model, and respect retention and residency terms.
Latency and UX trade-offs. Run input checks in parallel with generation and cancel on a hit. Output checks conflict with streaming: check per sentence or buffer, or accept a delayed first token on sensitive routes. Every block is a possible false positive, and over-blocking drives users away.
Knowing they work.
- A red-team suite per threat (injection, jailbreak, exfiltration, policy violations) reporting attack success rate, re-run on every model, prompt or tool change.
- A benign set to measure the false positive rate of each filter.
- Online: block rate, user override or appeal rate, sampled human review of both blocked and allowed traffic.
- Test the code-level controls directly: can the tool layer be made to act outside permissions regardless of what the model says?
The principle: prompts and classifiers reduce frequency; permissions, validation and approvals in code bound the damage.
Follow-ups
- Which layer would you cut first under a latency budget, and what risk do you accept?
- How do you run an output check on a streamed answer?
seniordesignAI MLEasked at Meta Your company runs coding agents on private repositories. How can private code or secrets leak, and what do you build to prevent it? How would you test that the controls work?
Enumerate the exits first. Code can leave by five routes, and each needs its own control:
- To the model provider, in prompts: retention, logging, use for training.
- Through the agent’s own actions: a shell command that makes a network request, a package install, a web fetch with code in the URL, a push to the wrong remote, a comment on a public issue.
- Through prompt injection: text in a dependency’s README, an issue or a web page tells the agent to send data somewhere. This needs three things together: access to private data, exposure to untrusted content, and a channel out. Remove one and it fails.
- Across tenants or users: a shared retrieval index, cache or agent memory without access control; a model fine-tuned on one customer’s code that reproduces it for another.
- Through side stores: traces, logs, analytics and crash reports that capture prompts.
Controls, by route.
- Provider: contractual zero retention and no training, or a model hosted inside the trust boundary for the most sensitive repositories. A policy map of which repositories may use which endpoint, enforced in a gateway, not left to each developer.
- Actions: run the agent in a sandbox with network egress denied by default and an allowlist through a proxy (package mirror, internal services). Short-lived credentials scoped to one repository, read-only unless the task needs a write. Outbound actions that publish (push, open a pull request, post) need approval or are restricted to internal targets.
- Injection: treat fetched and third-party content as data. After the agent has read untrusted content, restrict the tools it may call, or require approval for anything with a destination. Prompting the model to ignore instructions is not a control.
- Tenancy: retrieval filtered by the caller’s permissions at query time, caches and memory keyed by tenant, no training on customer code without consent.
- Secrets: scan before content enters the context and scan outputs; keep
.envfiles and key stores out of the agent’s reach; prefer a secrets broker that injects credentials into tools without the model seeing them. - Side stores: redact and set retention on traces; restrict who can read them.
Testing. Plant unique canary strings and canary credentials in test repositories, and plant instructions in dependencies, issues and web pages that try to exfiltrate them. Run the suite on every agent and tool change and report the exfiltration rate, which must be zero for the blocked channels. Canary credentials that alert when used catch what the suite misses. Track the cost too: blocked legitimate requests and approval prompts per task, because controls that annoy developers get bypassed.
What the senior answer gets right. Egress control and credential scope are the hard guarantees; model-level defences are probabilistic and count only as a second layer. And the provider question is a data-governance decision, made per repository class, before any engineering.
Follow-ups
- The agent needs internet access to read documentation. How do you allow that without opening an exfiltration channel?
- A developer pastes a stack trace containing a customer token into the chat. Which control catches it?
- How would you detect, after the fact, that code from one tenant was shown to another?
Reported in interviews (candidate reports on third-party sites, not verified)
- Meta, Machine Learning Engineer, Apr 2026: Prevent private code leakage in coding agents (PracHub)
Cost, latency and model routing for LLM products 14% of postings
- Write the cost and latency formulas in terms of input, cached and output tokens
- Rank cost levers (caching, context trimming, output limits, smaller models, batch, response caching)
- Design a model router or cascade and state when it loses money or quality
- Diagnose a cost regression by decomposing it into tokens, cache hit rate, steps and model mix
- Explain time to first token versus total latency and what streaming does and does not fix
coreconceptMLE AIasked at Google What determines the cost and latency of an LLM feature, and which levers do you pull first?
Cost per request is \(\text{uncached input} \times p_{in} + \text{cached input} \times p_{cache} + \text{output} \times p_{out}\). Output tokens (including reasoning tokens) are priced several times higher than input tokens on most APIs. An agent multiplies this by the number of steps, and each step re-sends the history.
Latency is roughly time to first token plus output tokens divided by generation speed. Time to first token grows with queueing and with uncached prompt length; total latency is dominated by output length.
Levers, in the order I would try them:
- Prompt caching: stable prefix, check the hit rate. No quality cost.
- Trim input: fewer and shorter retrieved passages, bounded tool outputs, compaction.
- Trim output: concise formats, no restating of the input, appropriate token limit, lower reasoning effort where it does not change results.
- Smaller model for easy steps (routing, extraction), kept honest by an eval.
- Batch API for offline work: asynchronous, typically about half price.
- Response caching for repeated queries: exact-match is safe; semantic caching risks wrong hits, staleness and leaking across users.
- Parallelise independent calls; stream to improve perceived latency (it does not shorten total time).
Measure cost per completed task, not per call. A cheaper model that needs more steps or more retries can cost more per task. Track tokens in and out, cached fraction, steps per task and latency percentiles per route.
Follow-ups
- Streaming is on and users still complain it is slow. What do you look at?
- When is a semantic cache a bad idea?
Reported in interviews (candidate reports on third-party sites, not verified)
- Google, Software Engineer, Jan 2026: Choose between fast and cheap model options (PracHub)
stafftrade-offMLE AI Design model routing for an LLM product. When does a router or a cascade save money, and when does it backfire?
Two designs.
- Router: a cheap classifier (or small LLM) predicts difficulty or intent and picks a model up front. One model call per request.
- Cascade: call the small model first, and escalate to the large one when a check fails (schema or business validation, a verifier, low self-consistency, a learned confidence score).
Economics. With escalation rate \(e\), expected cascade cost is \(c_s + e \cdot c_l\) against \(c_l\) for always-large. It saves money only if \(c_s + e \cdot c_l < c_l\), that is \(e < 1 - c_s / c_l\), and the escalated requests pay both latencies. A router avoids the double call but its mistakes are silent: a hard query sent to the small model simply gets a worse answer.
How to set it up. Label a traffic sample with both models’ outputs and quality grades. Sweep the threshold and plot quality against cost; choose the operating point, and check quality per slice, not only on average, because routing errors concentrate in the hard tail that matters most.
Where it backfires.
- LLM self-reported confidence is poorly calibrated; prefer external checks.
- Two models means two prompts, two eval suites and two cache namespaces.
- A provider upgrade to either model shifts the optimal threshold.
- On multi-step agent tasks, a weaker model that takes more steps can cost more per task.
Alternatives to test first. The large model at lower reasoning effort; prompt caching; a fine-tuned or distilled small model for one narrow, high-volume task with a fallback to the large model on validation failure.
Monitor the route mix, escalation rate, per-route quality and cost per completed task.
Follow-ups
- How would you train the router, and what is its label?
- The escalation rate doubles overnight. What happened?
seniordebuggingAI Your LLM bill tripled the week after a prompt change, with flat traffic. How do you find the cause?
Decompose spend from usage logs, before and after, per route and model:
\[ \text{cost} = \text{tasks} \times \text{calls per task} \times (\text{uncached in} \cdot p_{in} + \text{cached in} \cdot p_{cache} + \text{out} \cdot p_{out}) \]
Then check each factor.
- Cache hit rate collapsed. The most likely cause of a step change with a small edit: the change put something dynamic (date, user name, request id) near the top of the prompt, or reordered tools, so every request misses the cache. Compare cached-token fractions; diff the rendered prompt of two consecutive requests.
- Input grew. New examples or documents in the prompt, multiplied by every step of every agent run.
- Output grew. The new instruction elicits longer answers, more reasoning tokens, or restated context.
- More calls per task. The change causes more tool calls, validation failures and retries, or loops. Compare the steps-per-task distribution and the retry rate.
- Model mix changed. A routing or fallback rule now sends more traffic to the expensive model.
- Not the prompt at all. A retry storm from rate limits, a batch job, or a new caller, coinciding with the change.
Fix the specific cause, then prevent recurrence: report tokens, cache hit rate, steps and cost per task in the regression suite next to quality, alert on cost per task, and set budget caps per run.
Follow-ups
- How would you detect a cache-breaking change in CI?
- Quality improved with the new prompt. How do you decide whether to keep it?
Forward-deployed / customer-embedded delivery 12% of postings
- Run a scoping conversation that ends in one workflow, a success metric and acceptance criteria
- List what separates a demo from production for an LLM system
- Measure delivered value against a baseline and track adoption
- Handle a customer request that is technically wrong or out of scope
seniorbehaviouralAI A customer says “we want an AI agent for our operations team”. How do you scope the engagement?
What the interviewer is testing. Whether you can turn a vague ask into a deliverable with a measurable outcome, push back constructively, and avoid building a demo nobody uses.
Structure of a strong answer.
- Find the workflow, not the technology. Ask who does what today, how often, how long it takes, where errors and delays are, and what a mistake costs. Watch someone do the task if possible.
- Pick one narrow, high-volume, measurable workflow where errors are detectable and recoverable. Decline the “do everything” agent for the first phase and say why.
- Define success with the customer. A baseline, a target metric (handle time, error rate, throughput), and acceptance criteria on a test set they help label. Agree who signs off.
- Check feasibility early. Data access, APIs and permissions, security and compliance review, the human fallback path, and who owns the system after hand-off.
- Plan in thin slices. A working end-to-end version on real data in the first weeks, then widen. Write down what is out of scope.
- Communicate in their terms. Risks, cost per task and expected accuracy with examples of failures, not architecture diagrams.
Mistakes that sink the answer. Starting with model or framework choices; accepting the customer’s proposed solution without understanding the problem; no baseline, so value cannot be shown; promising accuracy before seeing data; ignoring the people whose work changes; treating security review as a late step.
Follow-ups
- The executive sponsor wants full autonomy on day one. What do you say?
- How do you handle a request you believe will not work?
staffdesignAI Your demo impressed the customer’s executives. What stands between that demo and production, and how will you prove the system delivers value?
A demo shows that the system can work on chosen inputs. Production requires that it works on their inputs, inside their systems, with known failure behaviour.
The gaps.
- Distribution. Real inputs are messier than demo inputs. Build an eval set from their data, with their experts defining what correct means, and report results by slice. This is usually the largest piece of work and the one that reveals whether the project is viable.
- Integration. Their identity provider, permissions, data sources, rate limits and network constraints.
- Reliability. Retries, timeouts, idempotent writes, a fallback path to a human, and defined behaviour when the model is unavailable or wrong.
- Security and compliance. Data residency, retention, PII handling, vendor review, audit logs. Start this early; it sets the timeline.
- Cost and latency at their volume, not at demo volume.
- Operations. Monitoring, alerting, a feedback channel, a process for prompt and model updates, and a named owner after hand-off.
- Adoption. Training, changes to how people work, and trust built through visible sources and easy correction.
Proving value.
- Agree the primary metric and measure the baseline before launch.
- Pilot with a comparison: randomised by user or team if possible; otherwise a staggered rollout, with before-and-after as the weakest option because other things change too.
- Track adoption and acceptance: usage, how often outputs are accepted, edited or overridden. A tool that is not used delivers nothing.
- Report cost per task next to the outcome metric, and audit a sample for errors the metric does not capture.
Risks to name. The last 20% of cases taking most of the effort, undefined success criteria, scope growth, and a pilot group that is not representative.
Follow-ups
- The pilot shows no improvement in handle time but users like it. What do you conclude?
- Which gap would you close first if you had two weeks?
Vector search and embedding stores 12% of postings
- Explain HNSW, IVF and product quantization and the knob each exposes for recall versus latency
- Compute the memory footprint of N vectors of dimension d with and without PQ
- Compare pre-filtering, post-filtering and filter-aware graph search under selective filters
- Say when brute force or pgvector is enough and when a dedicated vector store is needed
- Measure ANN recall against exact search and plan a re-embedding migration
coreconceptMLE AI Explain HNSW, IVF and product quantization, and the recall-latency-memory trade-off each one exposes.
Exact nearest-neighbour search is \(O(Nd)\) per query. Below roughly \(10^5\) vectors that is a few milliseconds and brute force is the right answer. Beyond that, approximate indexes trade recall for speed and memory.
HNSW (graph). A multi-layer proximity graph; search starts at the sparse top layer and greedily descends. Parameters: M (links per node, typically 16-64), efConstruction (build quality), efSearch (query-time beam: higher means better recall and slower). High recall at low latency, roughly logarithmic query scaling in practice. Costs: full vectors plus links in RAM, slow builds, deletes handled by tombstones.
IVF (partitioning). k-means splits the space into nlist cells (on the order of \(\sqrt{N}\)); a query scans the nprobe closest cells. nprobe is the recall-latency knob. Less memory overhead than a graph, needs training, and degrades when the data drifts from the trained centroids.
Product quantization (compression). Split each vector into \(m\) sub-vectors and replace each with the id of its nearest of 256 centroids: \(m\) bytes per vector. A 768-dimension float32 vector is 3,072 bytes; with \(m = 96\) it is 96 bytes, 32 times smaller. Distances come from lookup tables. It is lossy, so re-score the top candidates with full vectors.
Typical combinations. HNSW when the data fits in RAM; IVF-PQ at the billion scale; disk-based graphs (DiskANN-style) when RAM is the constraint. Scalar or binary quantization with re-scoring is a simpler alternative to PQ.
Always measure. Compute recall@k against exact search on a query sample and plot it against latency; ANN recall is a property of your data and parameters, not of the library.
Follow-ups
- How much RAM do 100 million 1,024-dimension vectors need in HNSW, roughly?
- What happens to an IVF index as new data arrives over months?
seniortrade-offMLE AI How does metadata filtering interact with ANN search, and when is pgvector enough versus a dedicated vector database?
Filtering. Three approaches:
- Post-filter: run ANN, then drop non-matching results. With a selective filter (1% of rows match) a top-100 search returns about one usable result.
- Pre-filter: select matching rows, then search exactly within them. Exact and cheap when the subset is small, linear in subset size when it is not.
- Filter-aware index traversal: skip non-matching nodes during graph search. Good at moderate selectivity; at very low selectivity the graph of matching nodes is disconnected and recall collapses unless the engine falls back to brute force.
Good engines choose by estimated selectivity. If the filter is always a tenant id, use a partition or namespace per tenant instead of a filter.
pgvector is enough when the corpus is in the millions to low tens of millions of vectors, the index fits in memory, QPS is moderate, and you benefit from one system: joins with relational data, transactions, row-level security for permissions, existing backups and operations. These thresholds are rules of thumb and depend on dimension and hardware. Filtered ANN behaviour in pgvector is version-dependent, so test it with your real filters.
A dedicated store earns its place at hundreds of millions of vectors or more, with strict p99 latency at high QPS, heavy filtered or hybrid search, many tenants, or a need for built-in quantization, disk-based indexes and sharding.
Either way, plan for the operational events: a new embedding model means re-embedding everything and a dual-index migration; shorter dimensions (Matryoshka-style embeddings) and quantization cut memory at some recall cost.
Follow-ups
- Your filter matches 0.1% of rows. Which strategy and why?
- How would you migrate to a new embedding model with no downtime?
Structured outputs and reliability of LLM pipelines 8% of postings
- Distinguish prompt-only JSON, JSON mode and schema-constrained decoding and what each guarantees
- Design a schema that does not force the model to invent values (nullable fields, enums, reasoning before answer)
- Implement a bounded retry loop that feeds validation errors back to the model
- Explain why valid JSON can still be truncated or semantically wrong and how to catch it
coreconceptMLE AI How do you get reliable structured output from an LLM? What do JSON mode and schema-constrained decoding guarantee, and what do they not?
Three levels of guarantee:
- Prompt only (“reply in JSON with these fields”). Works most of the time; failures include prose around the JSON, trailing commas, missing fields.
- JSON mode. The output is syntactically valid JSON, with no guarantee about fields or types.
- Schema-constrained decoding (structured outputs, strict tool calling). The schema is compiled to a grammar, and at each step tokens that would violate it are masked. Output that completes always parses and matches the schema.
What constrained decoding does not guarantee:
- Completion. Hitting the output token limit leaves truncated JSON; check the finish reason.
- Correct values. A date field holds a valid date, not necessarily the right one.
- Full JSON Schema. Providers support a subset (limits on recursion, numeric and string constraints, optional fields); check the documentation.
- No refusal. The model may still decline.
Schema design matters as much as the mechanism:
- Generation is left to right, so put reasoning or evidence fields before the verdict; forcing the answer first removes the model’s chance to think.
- Allow null or “unknown” so the model is not forced to invent a value.
- Use enums for categories; keep nesting shallow; describe each field.
- For extraction, ask for the supporting quote alongside the value so it can be verified.
Then validate anyway (types with Pydantic or JSON Schema, plus business rules such as totals that must add up), and retry with the validation error on failure.
Follow-ups
- Why can constraining the output format reduce answer quality?
- How would you extract fields from a scanned invoice and know which ones to trust?
seniorcodingMLE AI Write a retry-with-validation wrapper for structured output from an LLM.
from pydantic import BaseModel, ValidationError
def extract_json(text: str) -> str:
start, end = text.find("{"), text.rfind("}")
if start == -1 or end <= start:
raise ValueError("no JSON object found in output")
return text[start:end + 1]
def structured_call(llm, messages, schema: type[BaseModel], max_attempts=3, check=None):
"""llm(messages) -> str. Returns a validated `schema` instance or raises."""
msgs, last_err = list(messages), None
for attempt in range(1, max_attempts + 1):
raw = llm(msgs)
try:
obj = schema.model_validate_json(extract_json(raw))
if check is not None:
check(obj) # business rules; raises ValueError
return obj
except (ValidationError, ValueError) as e:
last_err = e
msgs = list(messages) + [ # keep only the latest failed attempt
{"role": "assistant", "content": raw},
{"role": "user", "content":
f"That output was invalid:\n{e}\n"
"Return only a corrected JSON object that matches the schema."},
]
raise RuntimeError(f"no valid output after {max_attempts} attempts: {last_err}")Pitfalls an interviewer checks:
- Bounded attempts. Each retry is a full paid call; two or three is the usual cap.
- Feed back the specific error, not “try again”. The validator’s message tells the model which field to fix.
- Do not accumulate every failed attempt in the history; it grows cost and anchors the model on its mistakes.
- Separate transport errors (429, 5xx, timeouts) from validation errors; they need backoff, not a repair prompt.
- Semantic checks belong in
check: cross-field consistency, values present in the source text. - No side effects before validation succeeds.
- Log the attempt count. A rising retry rate is an early signal of a prompt or model regression.
- With schema-constrained decoding the wrapper is still needed for truncation, refusals and business rules.
Extensions: escalate to a stronger model on the last attempt; return a typed failure instead of raising so the caller can route to human review.
Follow-ups
- How would you handle a response truncated by the token limit?
- What would you alert on in production?
Conversational AI / voice agents 6% of postings
- Break a voice-to-voice latency budget into endpointing, ASR, LLM time to first token and TTS
- Explain turn detection and barge-in, including truncating history to what was actually spoken
- Compare a cascaded ASR-LLM-TTS pipeline with a speech-to-speech model
- Design escalation to a human with a usable handoff summary
seniordesignAI RE Design a real-time voice agent. Where does the latency go, and how do you handle turn-taking and interruptions?
Pipeline. The cascaded design is voice activity and turn detection, streaming speech recognition, the LLM, then streaming text-to-speech. The alternative is a speech-to-speech model that consumes and emits audio directly.
Latency budget. People expect a reply within a few hundred milliseconds of finishing; beyond about a second the conversation feels broken. Typical contributions (approximate, system-dependent): end-of-turn detection 200-500 ms, final transcript 100-300 ms with streaming ASR, LLM time to first token 200-500 ms, TTS time to first audio 100-300 ms, plus network. What matters is time to first audio, not total generation time.
Reducing it. Stream every stage; start TTS on the first clause rather than the full reply; use a fast model and a short, cached prompt; co-locate services; replace a fixed silence timeout with a turn-detection model that uses what was said; speak a short acknowledgement before slow tool calls.
Turn-taking and barge-in. When the user starts speaking during playback: stop audio immediately, cancel the in-flight LLM and TTS, and truncate the stored assistant turn to what was actually spoken (this needs TTS timing information), otherwise the model believes it said things the user never heard. Echo cancellation stops the agent from interrupting itself. Short back-channels (“mm-hm”) should not count as interruptions.
Cascaded versus speech-to-speech. Cascaded gives text at every stage, so guardrails, tool calling, logging and model choice are straightforward, but it loses prosody and adds latency. Speech-to-speech is faster and more natural, and harder to inspect and control.
Evaluation. p50 and p95 voice-to-voice latency, word error rate on names, numbers and domain terms, interruption handling, task completion, and escalation rate.
Follow-ups
- The user gives a 16-digit number. What goes wrong and how do you make it robust?
- How would you test barge-in automatically?
Agent memory and state 4% of postings
- Distinguish working context, session state and long-term memory (semantic, episodic, procedural)
- Design the write path (what, when, dedupe, conflict resolution, expiry) and the read path (always loaded versus retrieved)
- Explain memory poisoning and stale-memory failure modes and their mitigations
- Scope memory by user and tenant and support inspection and deletion
seniorconceptAI RE How would you design memory for an agent that works with the same user across many sessions?
Separate three things:
- Working context: what is in the window now.
- Session state: the conversation, plan, scratchpad and checkpoints for one task.
- Long-term memory: what persists across sessions. Useful sub-types are semantic (facts and preferences), episodic (what happened in past sessions) and procedural (instructions and learned ways of working).
Write path. Decide who writes (the agent through an explicit tool, or a background extraction job after the session), what is written (distilled statements with a timestamp and provenance, not raw transcripts), and how conflicts resolve (a new fact supersedes or updates the old one rather than accumulating). Add expiry for things that go stale.
Read path. A small, always-loaded profile for things that matter every time; everything else retrieved on demand by search, or kept as files the agent lists and reads. Always-loaded memory costs tokens on every request and can break prompt caching if it changes often.
Failure modes.
- Stale or wrong memory: an error written once is replayed forever. Keep provenance, let the agent verify against the current state, and prefer current observations over memory.
- Poisoning: injected content written to memory persists across sessions and survives the end of the attack. Do not write memory from untrusted content without review.
- Bloat: retrieval returns marginally relevant memories that distract.
- Privacy: scope strictly by user and tenant; let users inspect and delete.
Evaluate with multi-session tasks where the answer depends on an earlier session, and measure both recall of needed memories and the rate of wrong-memory use.
Start simple: a structured profile plus notes files beats a vector store until volume demands one.
Follow-ups
- The user says “I moved to Berlin” and memory says Paris. What happens on write and on read?
- When is memory better implemented as fine-tuning? When is it worse?