Slides · GenAI system design
Designing an agent product
1 / 31
Designing an agent product
When a wrong output is a wrong action, safety, cost control and failure handling move from the end of the design to the start.
By the end you can:
- assign an autonomy level to each action from its blast radius, and say which actions need human approval,
- estimate the cost and latency of a multi-step run, show why cost grows faster than steps, and set caps,
- design safe side effects with idempotency keys, spend limits and compensation,
- plan evaluation and the handling of tool errors, ambiguity, step limits and injected instructions.
Concept
A wrong answer versus a wrong action
- A RAG system’s worst output is a wrong answer. An agent’s worst output can be a wrong action.
- Agents can loop and burn money, repeat a payment, obey an instruction hidden in a web page, or stop halfway and leave the world broken.
- A design that treats these as afterthoughts is incomplete, however good the model is.
- The same nine-link chain applies (requirements, scale, components, data flow, failures, evaluation, cost and latency, security, rollout). The weight shifts to blast radius, budgets and side effects.
Mental model: a new assistant handed a company card and an email account. You list what they may do alone, what needs your signature, what has a spending limit, and what they must never touch. An agent design is that list written as code.
Concept
First question: do you need an agent at all?
- Anthropic’s guidance on building agents advises starting with the simplest thing that works and adding complexity only when it is justified.
- The reason it gives: agents buy better task performance with extra latency and cost, and their autonomy raises both costs and the risk of errors compounding.
- A fixed workflow is cheaper and more predictable. An agent adapts. Use the agent only where the steps cannot be known in advance.
- Say this before drawing a single box. It is also the most common way to cut a design’s risk.
Concept
The running example: a travel-booking agent
| Aspect | Requirement |
|---|---|
| Function | Search flights and hotels, hold a booking, pay, send the itinerary |
| Safety | No payment without explicit user confirmation; a hard spend limit per trip |
| Reliability | A retried or interrupted run must never double-charge |
| Quality bar | A task that cannot be finished safely stops and explains, not guesses |
| Latency | Progress visible within a few seconds; the whole task may take a minute |
First ask what the agent can change and how bad a mistake is. A read-only research agent and an agent that pays for flights are different products.
Compare
Autonomy levels: trust per tool, not per agent
OWASP names three root causes of excessive agency: excessive functionality, excessive permissions and excessive autonomy. Giving each tool the level its worst case justifies mainly limits autonomy and permissions; together with rule 1 below (fewer, narrower tools) it addresses all three.
| Level | Meaning | Travel-agent examples |
|---|---|---|
| 0. Read | Runs freely; no side effect | Search flights, read the calendar |
| 1. Reversible write | Runs, then can be undone | Hold a fare, add a calendar entry |
| 2. Approve first | Needs the user’s explicit yes to the exact action | Pay, change a booking, email a third party |
| 3. Never | No tool exists | Close the account, change the user’s card |
Level 3 means the tool is absent, not forbidden by the prompt.
Diagram
How a proposed call is routed
Process
Four rules that make the table work
- Least privilege. Offer the agent only the tools it needs, with narrow functions and minimum permissions. OWASP suggests preferring purpose-built tools over open-ended ones such as a shell.
- Approval shows the real action. Build the confirmation screen from the structured call (payee, amount, dates), not from the model’s description of it. The user approves what will happen, not what the model says will happen.
- Authorization in code. The executor takes the user id and limits from the session, never from model-written arguments. OWASP calls this complete mediation: enforce authorization downstream rather than trusting the model to decide.
- Where the line sits is judgment. A team with a strong undo path may let small holds run unattended. State the reasoning.
Concept
Why sends sit at level 2: the exfiltration path
- Simon Willison names three ingredients that together are dangerous: access to private data, exposure to untrusted content, and the ability to communicate externally.
- Combined, an instruction hidden in content the agent reads can make it send private data out.
- Willison also writes that the field still does not know how to prevent this with full reliability, so the safe move is to avoid the full combination.
- Anthropic’s documentation adds the matching practice: treat tool output as untrusted data, limit the agent’s access to sensitive data and actions, and screen tool results.
For the travel agent: it reads the user’s saved traveller profile (private data) and web pages (untrusted content). A send tool would complete the trifecta. Put sends behind approval. Caveat: booking and payment tools also pass traveller data to third parties, so the trifecta can already be nearly complete without a dedicated send tool; check every tool that talks outside.
Sources[3] The lethal trifecta for AI agents: private data, untrusted content, and external communication[4] Mitigate jailbreaks and prompt injections
Worked example
Worked example: levels for an expense assistant
Illustrative design, with the worst case driving each choice.
| Tool | Worst case | Level | Why |
|---|---|---|---|
| Read receipts and the expense policy | Reads data the user already owns | 0 | No side effect |
| Create a draft expense report | A wrong draft | 1 | Deleting the draft undoes it |
| Submit the report to finance | Starts a workflow other people act on | 2 | The user approves the exact totals |
| Email a vendor | A message that cannot be recalled | 2 | No undo; also an outbound channel |
| Change the payee bank account | Money to the wrong place | 3 | No tool exists |
If this team had a reliable withdraw-before-approval path, it could argue for submit at level 1. The point is to state the reasoning from the worst case.
Check yourself
Check: the small-refund tool
A support agent has a refund tool. The team wants refunds up to $20 to run without approval. What controls would make that defensible, and when should it stay at level 2?
Answer
It is defensible only if the executor enforces limits in code (a per-refund cap of $20, a daily cap per customer and per agent), refunds are logged for audit with a kill switch for the tool, and the cost of a wrong refund is bounded by those caps. If the refund cannot be bounded or reversed, or the limits would come from model-written arguments, keep it at level 2 so a person approves the exact amount.
Math
Why steps cost more than they seem
Every loop step is a model call that re-reads the growing history.
inputn=B+d(n−1)total input(N)=NB+d⋅2N(N−1)cost=106total input×pin+106total output×pout| Symbol | Meaning | Value in this lesson (illustrative) |
|---|---|---|
| B | Base prompt: instructions, tool definitions, task | 2,000 tokens |
| d | Tokens added per step (thought plus tool result) | 800 tokens |
| n, N | Step number, number of steps | 6 or 10 |
| o | Output tokens per step | 150 tokens |
| total output | N×o | 900 or 1,500 tokens |
| pin, pout | Hypothetical price per million input and output tokens | $3 and $15 |
The history grows linearly, so its running sum grows with N2.
Worked example
Worked: the formula on a different agent
Illustrative agent: base prompt B = 1,200 tokens, d = 400 tokens added per step, o = 100 output tokens per step, N = 6 steps.
| Step | Input tokens read | Running total |
|---|---|---|
| 1 | 1,200 | 1,200 |
| 2 | 1,600 | 2,800 |
| 3 | 2,000 | 4,800 |
| 4 | 2,400 | 7,200 |
| 5 | 2,800 | 10,000 |
| 6 | 3,200 | 13,200 |
- Formula check: 6×1,200+400×26×5=7,200+6,000=13,200.
- A naive 6×1,200=7,200 misses almost half of the true input.
- Output: 6×100=600 tokens.
- Cost at $3 and $15 per million: 1,000,00013,200×$3=$0.0396, plus 1,000,000600×$15=$0.009, so $0.0486.
Worked example
Worked: the 10-step cap, and why a step cap is a cost control
Back to the lesson’s agent (B=2,000, d=800, o=150).
- 6 steps: 6×2,000+800×15=24,000 input tokens; output 900; $0.072+$0.0135=$0.0855.
- Input: 10×2,000+800×210×9=20,000+36,000=56,000 tokens.
- Output: 10×150=1,500 tokens.
- Cost: $0.168+$0.0225=$0.1905.
| Aspect | 6 steps | 10 steps | Change |
|---|---|---|---|
| Steps | 6 | 10 | +67% |
| Input tokens | 24,000 | 56,000 | +133% |
| Cost per task | $0.0855 | $0.1905 | about +123% |
If 1,000 runs a day all hit the cap, that is 1,000×$0.1905=$190.50 a day (illustrative). Caching a repeated prompt prefix can reduce the re-read cost on some providers, but check the current provider documentation before relying on it.
Concept
Set four caps, and return something useful
- Step cap. Anthropic’s agent guidance says to build in stopping conditions, with an iteration limit as its example, so the system stays under control.
- Cost or token cap per task.
- Wall-clock limit per task.
- Daily spend cap per user.
- When a cap is hit, return a useful partial result and say why you stopped.
Latency adds up the same way. At about 2 seconds per model call (illustrative), a 6-step run is about 12 seconds of model time before any tool latency. Stream progress (“searching flights…”), and consider a smaller model for easy sub-steps.
Trade-off: a low cap cuts cost and loops but aborts legitimate long tasks.
Check yourself
Check: cost a 4-step run, then find the growth point
An agent has a 2,500-token base prompt, adds 700 tokens per step and emits 250 output tokens per step, with the history re-sent each step. At $3 and $15 per million tokens, what does a 4-step run cost? At which step does a single call first read more than 8,000 input tokens?
Answer
Input: 4×2,500+700×24×3=10,000+4,200=14,200 tokens. Output: 4×250=1,000 tokens. Cost: 1,000,00014,200×$3=$0.0426, plus 1,000,0001,000×$15=$0.015, so $0.0576. Step n reads 2,500+700×(n−1): step 8 reads 7,400 and step 9 reads 8,100, so step 9 is the first above 8,000.
Diagram
Components: the model proposes, the executor decides
Diagram
The scenario: the payment call times out
Process
Three parts of the fix
- Executor-made key. One key per user intent, such as one approved payment. A model that retries may invent a new key, and then each retry looks like a new request.
- Retry with the same key. Stripe’s API v1 documentation says it saves the response to the first request with a key and returns it on retries. It also errors if a reused key arrives with different parameters.
- Keys expire. Stripe v1 may remove keys at least 24 hours old, and a reused key after that creates a new request. For a late retry, or a provider with no idempotency support, write your own reference before calling, look the payment up by that reference before any retry, and reconcile afterwards.
AWS’s Builders’ Library makes the wider point: retrying an API with side effects is only safe when the operation is idempotent. Back off with jitter between attempts, and cap the retries.
Sources[5] Idempotent requests[6] Timeouts, retries, and backoff with jitter
Code
Code: the executor owns the key
Python
class Timeout(Exception): # raised by the provider client when the response is lost
pass
def pay(provider, amount, ref, key, attempts=3):
# key and ref are created by the executor for ONE approved payment.
for _ in range(attempts):
try:
return provider.charge(amount, key=key, ref=ref)
except Timeout:
continue # same key every time
raise RuntimeError("gave up: look up by ref before any retry")- The model never sees or supplies
key. The executor generates it when the user approves, stores it, and reuses it. - This loop has no backoff or jitter. A production version should add both.
- The provider in the tests on the next slide is a small simulation of the documented behaviour (saved first response, error on changed parameters, pruning after a period). It is not Stripe.
Source[5] Idempotent requests
Worked example
The failure cases, tested
These are results from the simulated provider described above. The ground truth is its list of charges.
| Test | Outcome | Charges made | Expected |
|---|---|---|---|
| Same key reused after a lost response | As described | 1 | 1 |
| Fresh key on each attempt (model-made key) | As described | 2 | 2 (the bug) |
| Same key, amount changed from 120 to 130 | As described: rejected | 1 | rejected |
| Late retry after the key was pruned, no lookup | As described | 2 | 2 (the gap) |
| Same late retry, with lookup by own reference first | As described | 1 | 1 |
| Charge of 780 against a 700 trip limit | As described: denied | 0 | 0 |
“As described” means the simulation behaved as the claim says. Rows 2 and 4 demonstrate the failures that the executor-made key and the lookup are there to prevent. The limit check in the last row is separate executor logic, not part of pay().
Diagram
Compensation: undo what a transaction cannot
A database transaction cannot roll back a flight hold at one company and a hotel at another. Chris Richardson’s saga pattern describes a sequence of local steps in which a failure triggers compensating transactions that undo the completed steps. They must be designed explicitly, because nothing rolls back automatically.
Source[7] Pattern: Saga
Worked example
Worked: a spend limit stops the charge before it happens
Illustrative numbers. Per-trip limit enforced in the executor: $700.
| Step | Amount | Running total | Executor decision |
|---|---|---|---|
| Hold flight | $480 | $480 | Level 1: allowed, undo kept |
| Hold hotel | $300 | $780 | Level 1: allowed, undo kept |
| Charge payment | $780 | $780 | Exceeds $700: denied before calling the provider |
- 480+300=780, which is 80 over the limit.
- The charge never reaches the provider, so there is nothing to refund. The two holds are released by their compensating actions and the user is told why.
- A stronger design checks the projected total at the hotel hold: $480+$300=$780 already exceeds $700, so the second hold would be denied and the user told earlier.
- The limit lives in the executor, so a hijacked or confused model cannot raise it.
Compare
Failure handling
| Failure | Detection | Behaviour |
|---|---|---|
| Tool error | Error code, timeout | Retry transient errors with backoff and jitter; surface a clear failure for permanent ones |
| Ambiguous request (“book the cheap one”) | Missing slots flagged | Ask the user; do not guess and act |
| Loop | Same tool, same arguments, no new information | Stop, return the partial result, escalate |
| Step or cost cap reached | Orchestrator counter | Stop with a partial result and the reason |
| Injected instruction in tool output | Output screening, red-team tests | Treat as data; deny any tool call the user did not ask for |
| Payment timeout | Timeout on a level-2 call | Retry with the same key, or look up by your own reference |
Anthropic’s guidance for injected content: put it in tool results, label what it is, limit access to sensitive data and actions, screen tool output, and red-team the agent before release.
Sources[6] Timeouts, retries, and backoff with jitter[4] Mitigate jailbreaks and prompt injections
Concept
Grade the world, not the agent’s claim
- Anthropic’s article on agent evals defines the outcome as the final state of the environment, and gives a flight-booking example: the agent may say it booked, but the check is whether the reservation exists in the database.
- Grade task success from end state: right flight, charged once, right amount. Include impossible tasks the agent should refuse.
- Track the trajectory as metrics (steps, cost, wrong tool choices, recovery from injected errors). The same article warns against requiring one exact sequence of steps, which makes tests brittle.
- Safety tests: adversarial pages and emails that try to trigger a payment. Expected result: no level-2 call without user approval.
- Release gate: write the thresholds before you see the results.
Sources[8] Demystifying evals for AI agents[9] τ-bench: A Benchmark for Tool-Agent-User Interaction in Real-World Domains
Math
Reliability: pass@k versus pass^k
Anthropic describes pass@k as the chance of at least one success in k attempts, and passk as the chance that all k trials succeed. The tau-bench paper proposes passk to measure reliability across repeated trials. In its abstract (2024), function-calling agents including GPT-4o succeed on fewer than 50% of tasks and score pass8 below 25% in the retail domain.
pass@k (one task)=1−(1−p)kpassk (one task)=pk(assuming independent trials with equal success rate p)| Per-run success p | k | pass@k | passk |
|---|---|---|---|
| 0.9 | 5 | 0.99999 | 0.590 |
| 0.8 | 8 | 0.9999974 | 0.168 |
An agent that acts once per customer needs consistency, so look at passk. The independence assumption is a simplification; real trials share causes of failure.
Sources[8] Demystifying evals for AI agents[9] τ-bench: A Benchmark for Tool-Agent-User Interaction in Real-World Domains
Check yourself
Check: a replay gate
A refund agent solves a given task 95% of the time per run. The release rule says all 10 runs of that task in a replay test must succeed. Assuming independent runs, what is the chance of passing, and what would pass@10 report?
Answer
pass10=0.9510≈0.599, so roughly 40% of the time this task would fail the gate even though each run is 95% reliable. pass@10=1−0.0510, which is essentially 1, because it only asks for one success. The gap shows why pass@k is the wrong metric for an agent that acts for a customer once.
Diagram
Rollout: expand autonomy in stages
Version prompts and tool schemas, and replay old traces against new versions before release.
Compare
Trade-offs to say aloud
| Decision | One side | Other side |
|---|---|---|
| Autonomy versus friction | More approvals: safer, slower | Fewer: faster, larger blast radius |
| Workflow versus agent | Fixed pipeline: cheaper, predictable | Agent: adapts, costs more |
| Step cap | Low: cuts cost and loops | High: allows long legitimate tasks |
| Memory | Helps personalisation | Adds privacy and staleness risk |
Interview note (common industry pattern, no company-specific claim): expect probing on the approval gate, the tool permission list and what happens on a timeout. A design that lets the model take irreversible actions with no confirmation is often treated as incomplete.
Summary
Recap
- Give each tool an autonomy level from its worst case; level 3 tools do not exist.
- Approval screens come from the structured action, and authorization lives in code.
- History is re-sent each step, so cost grows faster than the step count; cap steps, cost and time.
- The executor makes the idempotency key; after a timeout, retry with the same key, or look up by your own reference.
- Compensation handles multi-step failures; some actions have no undo and need approval.
- Evaluate final state and consistency across repeated runs, and expand autonomy in stages.
References
References & Sources (1 of 2)
Building effective agents (opens in a new tab)
Erik S., Barry Zhang2024Article
https://www.anthropic.com/engineering/building-effective-agents
Used for Start with the simplest solution; agents trade latency and cost for performance; include stopping conditions such as a maximum number of iterations.
LLM06:2025 Excessive Agency (opens in a new tab)
OWASP GenAI Security Project2025Documentation
https://genai.owasp.org/llmrisk/llm062025-excessive-agency/
Used for Excessive agency has three root causes (functionality, permissions, autonomy); mitigations include minimal tools, user approval and complete mediation.
Simon Willison2025Article
https://simonwillison.net/2025/Jun/16/the-lethal-trifecta/
Used for Private data, untrusted content and external communication together create an exfiltration risk, and the field cannot yet prevent it with full reliability.
Mitigate jailbreaks and prompt injections (opens in a new tab)
Anthropic2026Documentation
https://platform.claude.com/docs/en/test-and-evaluate/strengthen-guardrails/mitigate-jailbreaks
Used for Handling indirect injection: treat tool output as untrusted, limit access, screen tool results, and red-team the agent.
Idempotent requests (opens in a new tab)
Stripe2026Documentation
https://docs.stripe.com/api/idempotent_requests
Used for Idempotency keys in a payment API (v1): saved first response, error on changed parameters, pruning after at least 24 hours, client-generated keys.
References
References & Sources (2 of 2)
Timeouts, retries, and backoff with jitter (opens in a new tab)
Amazon Web Services (Builders' Library, AWS Builder Center)2019Article
https://builder.aws.com/content/3EumjoZascWd1oZiEgL8ORlv3qE/timeouts-retries-and-backoff-with-jitter
Used for Retries are only safe for idempotent operations; back off with jitter and cap retries.
Pattern: Saga (opens in a new tab)
Chris Richardson2026Article
https://microservices.io/patterns/data/saga.html
Used for The saga pattern: compensating transactions undo completed steps when a later step fails.
Demystifying evals for AI agents (opens in a new tab)
Mikaela Grace, Jeremy Hadfield, Rodrigo Olivares, Jiri De Jonghe2026Article
https://www.anthropic.com/engineering/demystifying-evals-for-ai-agents
Used for Grade the final environment state rather than the agent's claim; pass@k versus pass^k; avoid rigid path grading.
τ-bench: A Benchmark for Tool-Agent-User Interaction in Real-World Domains (opens in a new tab)
Shunyu Yao, Noah Shinn, Pedram Razavi, Karthik Narasimhan2024Preprint
arXiv 2406.12045 (opens in a new tab)https://arxiv.org/abs/2406.12045
Used for Proposes pass^k for reliability over repeated trials, and reports low consistency for function-calling agents in 2024.
Keys: ← → move, Home End first and last, F full screen.