The problem, stated properly
An LLM call answers one question. An agent pursues a goal: "research these five vendors and produce a comparison", "find the bug and fix it", "monitor this inbox and file invoices." The difference is a loop: the model plans, calls a tool, reads the result, plans again, repeating until the goal is met or it gives up. The system-design question is not "how smart is the model" but how you build a reliable system around an unreliable component: state, tools, guardrails, memory, evaluation, and cost control. That framing is the entire lesson.
The agent loop, precisely
- Observe: assemble context: the goal, conversation history, tool results so far, relevant memory.
- Reason: the LLM decides the next action, given available tools and their schemas (ReAct-style: interleaved reasoning traces and actions work better than plan-once-execute, because plans built before seeing the world break on contact with it).
- Act: emit a structured tool call. The runtime validates it (schema, permissions) and executes: search, code execution, API call, browser action.
- Persist: append the result to the trajectory. This running transcript is the agent's working memory.
- Loop or stop: the model decides "done" and produces the final answer, or hits a budget (max steps, max time, max dollars) and must stop and report partial progress.
Everything else in agent engineering is hardening this loop.
Why agents fail: error compounding is the boss fight
If each step is 90% reliable (optimistic for hard tasks), a 20-step task succeeds 0.9^20 which is about 12% of the time. This one equation drives every architectural decision in the field:
- Decompose: split the big goal into sub-tasks, each with its own short loop and a verifiable output. Five 4-step tasks at 65% each beats one 20-step task at 12%, and failures localize instead of poisoning the whole run.
- Verify at each step: cheap deterministic checks (did the API return 200? does the code compile? does the file exist?) catch errors before they compound. LLM-as-judge adds a second, semantic layer for outputs with no deterministic check.
- Ground every load-bearing step: the model's plan says "email the receipt to finance." A hard gate checks the address against a directory before the send tool will fire. Models propose, deterministic code disposes.
- Keep trajectories short: context pollution is real; a 50-step transcript full of dead ends degrades the model's next decisions. Summarize or restart with a clean context carrying only what was learned.
Memory: the three kinds, and their failure modes
- Working memory (the context window): the trajectory itself. Failure mode: overflow and pollution, handled by summarization and sub-task isolation.
- Episodic memory (what happened before): past runs, retrieved when relevant (often RAG over past trajectories). Failure mode: retrieving a past mistake and faithfully repeating it.
- Semantic memory (facts and preferences): a curated store the agent reads and writes ("user prefers morning meetings"). Failure mode: unreviewed writes, where one bad inference becomes a permanent false belief, so writes need confidence gates or human review.
Tools and guardrails
Tool design makes or breaks agents more than prompt engineering does. Rules that survive production: tools should be narrow and semantic (one create_calendar_event, not raw API access), arguments validated strictly, every tool documented for a non-human reader, and permissions tiered: read-only tools run free; writes and external sends require policy gates or human approval. The security model from the MCP lesson applies verbatim: the agent is a caller that must never be trusted by the executor, and prompt injection through tool-read content (a poisoned email, a web page) is the primary attack path.
Multi-agent: when it helps and when it is resume decoration
Splitting work across specialized agents (researcher, coder, reviewer) helps when sub-tasks are genuinely independent, benefit from separate clean contexts, or need different tools and permissions. It hurts when agents must share fine-grained state (coordination cost exceeds the benefit) and it multiplies cost and latency by the agent count. The orchestrator-worker pattern (one planner decomposes, workers execute in parallel, results merge) is the shape that has earned production use; chatty agent societies mostly have not.
Real numbers
- Latency: each loop iteration is one LLM call (2-10 s with thinking) plus tool time. A 15-step task is 1-5 minutes. Async operation with progress updates is not optional; nobody stares at a spinner for 3 minutes.
- Cost: each step re-sends the growing context: a 20-step run can spend 100K-1M tokens. Budgets (max steps, max dollars per run) are a reliability feature, not just finance.
- Reliability math in practice: well-engineered agents on bounded tasks (form filling, research summaries, code fixes with tests) reach 70-95% task completion; open-ended multi-hour tasks remain research territory. Design the product for the 5-30% that fail: checkpoints, human handoff, resumability.
Evaluation: the part everyone skips
You cannot improve what you do not measure, and agent quality is invisible in single demos. Production agent systems keep golden task suites (50-500 representative tasks with known-good outcomes), run them on every prompt/model/tool change, and track task completion rate, cost per success, and failure taxonomy (tool misuse vs bad plan vs bad retrieval vs premature stop). Trajectory review, reading full transcripts of failures, is the debugging tool; there is no stack trace for "the model decided to give up."
Common interview traps
- Describing the loop and stopping there. The question is always really about reliability engineering.
- No answer for error compounding. If you have not said 0.9^20, you have not designed the system yet.
- Tools as raw API passthrough. Wide tools produce wide failure surfaces.
- Claiming more agents automatically means more capability. Coordination is a cost you must justify.
- No evaluation story. "It worked in the demo" is not a design.
Interview Q&A
Q: Your agent succeeds 40% of the time on a 15-step task. What do you do first?
A: Read trajectories and classify failures before touching anything. The fix depends entirely on the distribution: if one tool causes half the failures, fix that tool's schema and docs; if failures cluster at steps 10+, it is context pollution, so decompose or summarize; if the model plans badly from step 1, give it worked examples in the prompt or a planning sub-step. The universal mistake is tweaking the prompt against vibes instead of a failure taxonomy. Measure, classify, then fix the biggest bucket.
Q: How do you let an agent send emails on a user's behalf without disasters?
A: Layered gates, because the model will eventually be manipulated or wrong: (1) tool tiering: draft-creation runs free, send is a separate privileged tool; (2) deterministic policy checks in the send path: recipient in approved domain list, no attachments unless declared, rate limits; (3) human approval for anything outside the policy, with the full draft shown; (4) content inspection: block sends triggered by instructions found inside tool-read content (the prompt-injection path), which means tracking which text came from the user vs from the outside world; (5) full audit log of every send. The principle: the model proposes, policy disposes, and no single layer is trusted to catch everything.
Problem ko sahi se samjho
Ek LLM call ek sawaal ka jawab deta hai. Ek agent goal pursue karta hai: "in 5 vendors ko research karke comparison banao", "bug dhoondo aur fix karo", "is inbox ko monitor karo aur invoices file karo." Farak ek loop ka hai: model plan karta hai, tool call karta hai, result padhta hai, phir plan karta hai, jab tak goal mile ya haar maane. System-design sawaal ye nahi ki "model kitna smart hai" balki unreliable component ke around reliable system kaise banate ho: state, tools, guardrails, memory, evaluation, cost control. Yehi framing poora lesson hai.
Agent loop, precisely
- Observe: context assemble karo: goal, conversation history, ab tak ke tool results, relevant memory.
- Reason: LLM agla action decide karta hai, available tools aur unke schemas dekh ke (ReAct-style: interleaved reasoning traces aur actions plan-once-execute se better kaam karte hain, kyunki duniya dekhe bina bane plans contact pe toot jaate hain).
- Act: structured tool call emit karo. Runtime validate karta hai (schema, permissions) aur execute: search, code execution, API call, browser action.
- Persist: result trajectory mein append karo. Ye running transcript agent ki working memory hai.
- Loop ya stop: model decide karta hai "done" aur final answer deta hai, ya budget lagta hai (max steps, max time, max dollars) aur use ruk ke partial progress report karni padti hai.
Agent engineering mein baaki sab is loop ki hardening hai.
Agents fail kyun karte hain: error compounding hi boss fight hai
Agar har step 90% reliable hai (hard tasks ke liye optimistic), to 20-step task 0.9^20 matlab ~12% baar succeed karta hai. Ye ek equation field ke har architectural decision ko chalati hai:
- Decompose: bade goal ko sub-tasks mein baanto, har ek ka apna chhota loop aur verifiable output. 65% wale paanch 4-step tasks 12% wale ek 20-step task ko harate hain, aur failures poison karne ke bajaye localize hote hain.
- Har step pe verify: saste deterministic checks (API ne 200 return kiya? code compile hua? file exist karti hai?) errors ko compound hone se pehle pakadte hain. LLM-as-judge un outputs ke liye doosra, semantic layer jodata hai jinka deterministic check nahi hota.
- Har load-bearing step ground karo: model ka plan kehta hai "receipt finance ko email karo." Ek hard gate send tool fire hone se pehle address ko directory se check karta hai. Models propose karte hain, deterministic code dispose karta hai.
- Trajectories chhoti rakho: context pollution real hai; dead ends se bhara 50-step transcript model ke agle decisions degrade karta hai. Summarize karo ya clean context ke saath restart karo, sirf wahi saath le jaate hue jo seekha.
Memory: teen types, aur unke failure modes
- Working memory (context window): trajectory khud. Failure mode: overflow aur pollution, summarization aur sub-task isolation se handle.
- Episodic memory (pehle kya hua): past runs, relevant hone pe retrieved (aksar past trajectories pe RAG). Failure mode: past mistake retrieve karke faithfully repeat karna.
- Semantic memory (facts aur preferences): curated store jo agent padhta aur likhta hai ("user morning meetings prefer karta hai"). Failure mode: unreviewed writes, jahan ek bura inference permanent false belief ban jaata hai, isliye writes ko confidence gates ya human review chahiye.
Tools aur guardrails
Tool design prompt engineering se zyada agents banata ya bigaadta hai. Production mein survive karne wale rules: tools narrow aur semantic hone chahiye (raw API access nahi, ek create_calendar_event), arguments strictly validated, har tool non-human reader ke liye documented, aur permissions tiered: read-only tools free chalte hain; writes aur external sends policy gates ya human approval maangte hain. MCP lesson ka security model verbatim apply hota hai: agent ek caller hai jispe executor kabhi trust nahi karega, aur tool-read content ke through prompt injection (zehreela email, web page) primary attack path hai.
Multi-agent: kab madad karta hai aur kab resume decoration hai
Specialized agents mein kaam baantna (researcher, coder, reviewer) tab madad karta hai jab sub-tasks genuinely independent hon, alag clean contexts se fayda ho, ya alag tools aur permissions chahiye hon. Tab nuksaan karta hai jab agents ko fine-grained state share karni ho (coordination cost benefit se zyada) aur ye cost aur latency ko agent count se multiply karta hai. Orchestrator-worker pattern (ek planner decompose karta hai, workers parallel execute karte hain, results merge) wo shape hai jisne production use kamaya hai; chatty agent societies mostly nahi kar payi hain.
Real numbers
- Latency: har loop iteration ek LLM call (thinking ke saath 2-10 s) plus tool time. 15-step task 1-5 minute. Progress updates ke saath async operation optional nahi hai; koi 3 minute spinner nahi dekhta.
- Cost: har step badhta context dobara bhejta hai: 20-step run 100K-1M tokens kha sakta hai. Budgets (max steps, max dollars per run) reliability feature hain, sirf finance nahi.
- Reliability math practice mein: bounded tasks pe well-engineered agents (form filling, research summaries, tests wale code fixes) 70-95% task completion tak pahunchte hain; open-ended multi-hour tasks abhi research territory hain. Product ko un 5-30% ke liye design karo jo fail hote hain: checkpoints, human handoff, resumability.
Evaluation: wo part jo sab skip karte hain
Jo measure nahi karte use improve nahi kar sakte, aur agent quality single demos mein invisible hai. Production agent systems golden task suites rakhte hain (50-500 representative tasks known-good outcomes ke saath), har prompt/model/tool change pe chalate hain, aur track karte hain task completion rate, cost per success, aur failure taxonomy (tool misuse vs bad plan vs bad retrieval vs premature stop). Trajectory review, failures ke poore transcripts padhna, debugging tool hai; "model ne haar maan li" ka koi stack trace nahi hota.
Common interview traps
- Loop describe karke ruk jaana. Sawaal hamesha asal mein reliability engineering ka hota hai.
- Error compounding ka koi jawab na hona. Agar 0.9^20 nahi bola, to system abhi design hua hi nahi.
- Raw API passthrough ke roop mein tools. Wide tools wide failure surfaces dete hain.
- Kehna ki zyada agents automatically zyada capability. Coordination ek cost hai jo justify karni padti hai.
- Evaluation story na hona. "Demo mein chala" design nahi hai.
Interview Q&A
Q: Tumhara agent 15-step task pe 40% baar succeed karta hai. Pehle kya karoge?
A: Kuch chhedne se pehle trajectories padho aur failures classify karo. Fix poori tarah distribution pe depend karta hai: agar ek tool aadhe failures karta hai, us tool ke schema aur docs fix karo; agar failures step 10+ pe cluster karte hain, ye context pollution hai, to decompose ya summarize karo; agar model step 1 se bura plan karta hai, prompt mein worked examples do ya planning sub-step. Universal mistake failure taxonomy ke bajaye vibes ke against prompt tweak karna hai. Measure, classify, phir sabse bada bucket fix karo.
Q: Agent ko user ki taraf se emails bhejne doge, bina disasters ke kaise?
A: Layered gates, kyunki model kabhi na kabhi manipulated ya wrong hoga hi: (1) tool tiering: draft-creation free chalta hai, send alag privileged tool hai; (2) send path mein deterministic policy checks: recipient approved domain list mein, declared ke bina koi attachment nahi, rate limits; (3) policy ke bahar kuch bhi ho to human approval, poora draft dikhake; (4) content inspection: un sends ko block karo jo tool-read content ke andar mili instructions se trigger hue (prompt-injection path), matlab track karo kaunsa text user se aaya aur kaunsa bahari duniya se; (5) har send ka full audit log. Principle: model propose karta hai, policy dispose karti hai, aur koi ek layer sab kuch pakadne ke liye trusted nahi hai.