Slides · GenAI system design

Designing an agent product

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.

Source1 Building effective agents

Concept

The running example: a travel-booking agent

AspectRequirement
FunctionSearch flights and hotels, hold a booking, pay, send the itinerary
SafetyNo payment without explicit user confirmation; a hard spend limit per trip
ReliabilityA retried or interrupted run must never double-charge
Quality barA task that cannot be finished safely stops and explains, not guesses
LatencyProgress 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.

LevelMeaningTravel-agent examples
0. ReadRuns freely; no side effectSearch flights, read the calendar
1. Reversible writeRuns, then can be undoneHold a fare, add a calendar entry
2. Approve firstNeeds the user’s explicit yes to the exact actionPay, change a booking, email a third party
3. NeverNo tool existsClose the account, change the user’s card

Level 3 means the tool is absent, not forbidden by the prompt.

Source2 LLM06:2025 Excessive Agency

Diagram

How a proposed call is routed

Diagram: Each proposed call is routed by its tool’s level (0 read, 1 reversible write, 2 approve first, 3 never).

0

1

2

3

Tool call proposed

Tool's level

Run freely

Run, keep undo

Ask user first

No such tool

Diagram summary: Each proposed call is routed by its tool’s level (0 read, 1 reversible write, 2 approve first, 3 never). Reads run freely, reversible writes run with an undo kept, irreversible or external actions wait for the user’s approval of the exact action, and the most dangerous actions are not available to the agent at all.

Process

Four rules that make the table work

  1. 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.
  2. 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.
  3. 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.
  4. Where the line sits is judgment. A team with a strong undo path may let small holds run unattended. State the reasoning.

Source2 LLM06:2025 Excessive Agency

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.

Sources3 The lethal trifecta for AI agents: private data, untrusted content, and external communication4 Mitigate jailbreaks and prompt injections

Worked example

Worked example: levels for an expense assistant

Illustrative design, with the worst case driving each choice.

ToolWorst caseLevelWhy
Read receipts and the expense policyReads data the user already owns0No side effect
Create a draft expense reportA wrong draft1Deleting the draft undoes it
Submit the report to financeStarts a workflow other people act on2The user approves the exact totals
Email a vendorA message that cannot be recalled2No undo; also an outbound channel
Change the payee bank accountMoney to the wrong place3No 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)input_n = B + d\,(n - 1)total input(N)=NB+d⋅N(N−1)2\text{total input}(N) = N B + d \cdot \frac{N(N - 1)}{2}cost=total input×pin106+total output×pout106\text{cost} = \frac{\text{total input} \times p_{\text{in}}}{10^{6}} + \frac{\text{total output} \times p_{\text{out}}}{10^{6}}
SymbolMeaningValue in this lesson (illustrative)
BBBase prompt: instructions, tool definitions, task2,000 tokens
ddTokens added per step (thought plus tool result)800 tokens
nn, NNStep number, number of steps6 or 10
ooOutput tokens per step150 tokens
total output\text{total output}N×oN \times o900 or 1,500 tokens
pinp_{\text{in}}, poutp_{\text{out}}Hypothetical price per million input and output tokens$3 and $15

The history grows linearly, so its running sum grows with N2N^2.

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.

StepInput tokens readRunning total
11,2001,200
21,6002,800
32,0004,800
42,4007,200
52,80010,000
63,20013,200
  • Formula check: 6×1,200+400×6×52=7,200+6,000=13,2006 \times 1{,}200 + 400 \times \dfrac{6 \times 5}{2} = 7{,}200 + 6{,}000 = 13{,}200.
  • A naive 6×1,200=7,2006 \times 1{,}200 = 7{,}200 misses almost half of the true input.
  • Output: 6×100=6006 \times 100 = 600 tokens.
  • Cost at $3 and $15 per million: 13,200×$31,000,000=$0.0396\dfrac{13{,}200 \times \$3}{1{,}000{,}000} = \$0.0396, plus 600×$151,000,000=$0.009\dfrac{600 \times \$15}{1{,}000{,}000} = \$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,000B = 2{,}000, d=800d = 800, o=150o = 150).

  • 6 steps: 6×2,000+800×15=24,0006 \times 2{,}000 + 800 \times 15 = 24{,}000 input tokens; output 900; $0.072+$0.0135=$0.0855\$0.072 + \$0.0135 = \$0.0855.
  • Input: 10×2,000+800×10×92=20,000+36,000=56,00010 \times 2{,}000 + 800 \times \dfrac{10 \times 9}{2} = 20{,}000 + 36{,}000 = 56{,}000 tokens.
  • Output: 10×150=1,50010 \times 150 = 1{,}500 tokens.
  • Cost: $0.168+$0.0225=$0.1905\$0.168 + \$0.0225 = \$0.1905.
Aspect6 steps10 stepsChange
Steps610+67%
Input tokens24,00056,000+133%
Cost per task$0.0855$0.1905about +123%

If 1,000 runs a day all hit the cap, that is 1,000×$0.1905=$190.501{,}000 \times \$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.

Source1 Building effective agents

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×4×32=10,000+4,200=14,2004 \times 2{,}500 + 700 \times \dfrac{4 \times 3}{2} = 10{,}000 + 4{,}200 = 14{,}200 tokens. Output: 4×250=1,0004 \times 250 = 1{,}000 tokens. Cost: 14,200×$31,000,000=$0.0426\dfrac{14{,}200 \times \$3}{1{,}000{,}000} = \$0.0426, plus 1,000×$151,000,000=$0.015\dfrac{1{,}000 \times \$15}{1{,}000{,}000} = \$0.015, so $0.0576. Step nn reads 2,500+700×(n−1)2{,}500 + 700 \times (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 orchestrator asks the model for the next action, and the executor validates it against schema, authorization and limits.

task done

denied

level 0-1

level 2

approved

declined

User request

Orchestrator
budget + trace log

Model proposes
next action

Final answer

Executor checks
schema, auth, limits

Run tool; result is
untrusted data

Approval screen from
the structured call

Diagram summary: The orchestrator asks the model for the next action, and the executor validates it against schema, authorization and limits. Low-risk tools run directly, level-2 tools go to an approval screen built from the structured call, and tool results return as untrusted observations. When the model decides the task is done, the final answer is returned. The orchestrator writes every step to a trace log.

Diagram

The scenario: the payment call times out

Diagram: The executor creates one idempotency key for the approved payment and sends it with every attempt.
Payment providerExecutorPayment providerExecutorcharge succeedscreate key K for this approved paymentcharge 120, key Kresponse lost (timeout)retry: charge 120, same key Koriginal result, no second charge
Diagram summary: The executor creates one idempotency key for the approved payment and sends it with every attempt. When the first response is lost, the retry carries the same key, and the provider returns the original result instead of charging again. The key comes from the executor, not from the model.

Process

Three parts of the fix

  1. 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.
  2. 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.
  3. 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.

Sources5 Idempotent requests6 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.

Source5 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.

TestOutcomeCharges madeExpected
Same key reused after a lost responseAs described11
Fresh key on each attempt (model-made key)As described22 (the bug)
Same key, amount changed from 120 to 130As described: rejected1rejected
Late retry after the key was pruned, no lookupAs described22 (the gap)
Same late retry, with lookup by own reference firstAs described11
Charge of 780 against a 700 trip limitAs described: denied00

“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.

Diagram: Each side-effecting step has an undo.

fails

Hold flight

Hold hotel

Charge payment

Compensate: release hotel

Compensate: cancel flight hold

Stop and explain to the user

Diagram summary: Each side-effecting step has an undo. When the payment fails, the compensations run in reverse order: release the hotel, then cancel the flight hold, and the agent tells the user why. An action with no clean undo, such as a sent email, belongs behind approval.

Source7 Pattern: Saga

Worked example

Worked: a spend limit stops the charge before it happens

Illustrative numbers. Per-trip limit enforced in the executor: $700.

StepAmountRunning totalExecutor decision
Hold flight$480$480Level 1: allowed, undo kept
Hold hotel$300$780Level 1: allowed, undo kept
Charge payment$780$780Exceeds $700: denied before calling the provider
  • 480+300=780480 + 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\$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

FailureDetectionBehaviour
Tool errorError code, timeoutRetry transient errors with backoff and jitter; surface a clear failure for permanent ones
Ambiguous request (“book the cheap one”)Missing slots flaggedAsk the user; do not guess and act
LoopSame tool, same arguments, no new informationStop, return the partial result, escalate
Step or cost cap reachedOrchestrator counterStop with a partial result and the reason
Injected instruction in tool outputOutput screening, red-team testsTreat as data; deny any tool call the user did not ask for
Payment timeoutTimeout on a level-2 callRetry 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.

Sources6 Timeouts, retries, and backoff with jitter4 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.

Sources8 Demystifying evals for AI agents9 τ-bench: A Benchmark for Tool-Agent-User Interaction in Real-World Domains

Math

Reliability: pass@k versus pass^k

Anthropic describes pass@k\text{pass@}k as the chance of at least one success in kk attempts, and passk\text{pass}^k as the chance that all kk trials succeed. The tau-bench paper proposes passk\text{pass}^k 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\text{pass}^8 below 25% in the retail domain.

pass@k (one task)=1−(1−p)k\text{pass@}k \text{ (one task)} = 1 - (1 - p)^kpassk (one task)=pk(assuming independent trials with equal success rate p)\text{pass}^k \text{ (one task)} = p^k \qquad \text{(assuming independent trials with equal success rate } p\text{)}
Per-run success ppkkpass@k\text{pass@}kpassk\text{pass}^k
0.950.999990.590
0.880.99999740.168

An agent that acts once per customer needs consistency, so look at passk\text{pass}^k. The independence assumption is a simplification; real trials share causes of failure.

Sources8 Demystifying evals for AI agents9 τ-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\text{pass@}10 report?

Answer

pass10=0.9510≈0.599\text{pass}^{10} = 0.95^{10} \approx 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\text{pass@}10 = 1 - 0.05^{10}, which is essentially 1, because it only asks for one success. The gap shows why pass@k\text{pass@}k is the wrong metric for an agent that acts for a customer once.

Diagram

Rollout: expand autonomy in stages

Diagram: Autonomy is expanded in stages, going down the diagram.

Suggestion mode
agent proposes, user clicks

Level 1 actions
run on their own

Level 2 actions run
with user approval

More autonomy only if logs
show low error rates

Kill switch per tool

Diagram summary: Autonomy is expanded in stages, going down the diagram. The agent first only suggests, then runs reversible actions, then runs irreversible ones with approval, and gets more freedom only when logs show low error rates. A kill switch per tool stays available at every stage.

Version prompts and tool schemas, and replay old traces against new versions before release.

Compare

Trade-offs to say aloud

DecisionOne sideOther side
Autonomy versus frictionMore approvals: safer, slowerFewer: faster, larger blast radius
Workflow versus agentFixed pipeline: cheaper, predictableAgent: adapts, costs more
Step capLow: cuts cost and loopsHigh: allows long legitimate tasks
MemoryHelps personalisationAdds 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)

  1. Building effective agents (opens in a new tab)

    Erik S., Barry Zhang2024Article

    Used for Start with the simplest solution; agents trade latency and cost for performance; include stopping conditions such as a maximum number of iterations.

  2. LLM06:2025 Excessive Agency (opens in a new tab)

    OWASP GenAI Security Project2025Documentation

    Used for Excessive agency has three root causes (functionality, permissions, autonomy); mitigations include minimal tools, user approval and complete mediation.

  3. The lethal trifecta for AI agents: private data, untrusted content, and external communication (opens in a new tab)

    Simon Willison2025Article

    Used for Private data, untrusted content and external communication together create an exfiltration risk, and the field cannot yet prevent it with full reliability.

  4. Mitigate jailbreaks and prompt injections (opens in a new tab)

    Anthropic2026Documentation

    Used for Handling indirect injection: treat tool output as untrusted, limit access, screen tool results, and red-team the agent.

  5. Idempotent requests (opens in a new tab)

    Stripe2026Documentation

    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)

  1. Timeouts, retries, and backoff with jitter (opens in a new tab)

    Amazon Web Services (Builders' Library, AWS Builder Center)2019Article

    Used for Retries are only safe for idempotent operations; back off with jitter and cap retries.

  2. Pattern: Saga (opens in a new tab)

    Chris Richardson2026Article

    Used for The saga pattern: compensating transactions undo completed steps when a later step fails.

  3. Demystifying evals for AI agents (opens in a new tab)

    Mikaela Grace, Jeremy Hadfield, Rodrigo Olivares, Jiri De Jonghe2026Article

    Used for Grade the final environment state rather than the agent's claim; pass@k versus pass^k; avoid rigid path grading.

  4. τ-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

    Used for Proposes pass^k for reliability over repeated trials, and reports low consistency for function-calling agents in 2024.