Lesson 7.4: Reliability and guardrails
Make agents safe and dependable: how they fail, layered guardrails, approval points, consistency testing, sandboxes and a staged path to more autonomy.
An agent that can act can also act wrongly. It can send an email to the wrong person, refund the wrong order, delete a file it should have kept, run up a bill in a loop or be talked into leaking information by a cleverly worded web page. These are not exotic risks. They follow directly from giving a system that sometimes makes mistakes the power to do things. The aim of this lesson is not to make agents perfect, which is not possible, but to make them dependable enough for the job and safe to fail: when they go wrong, the harm is small, caught early and reversible. The tools for this are guardrails, which are checks and limits placed around the agent, approvals that put people at the right points, measurements that show how consistent the agent really is and a gradual path from supervised to more independent operation. By the end you will be able to list the main ways agents fail, design guardrails in layers at the input, tool, output, process and system levels, work out how stacking independent checks reduces the chance that a bad action gets through, decide where human approval is worth its cost and estimate the workload, measure consistency across repeated runs, apply the principle of least privilege and sandboxing, and plan a staged rollout of autonomy. You should have read Lessons 7.1 to 7.3 and Lesson 6.4. No programming is needed, and the arithmetic is multiplication and percentages.
How agents fail
It helps to name the failures, since each calls for a different defence.
Failure · What it looks likeWrong tool or wrong arguments · Refunds the wrong transaction, searches the wrong customer, uses a date in the wrong format
Misreading a result · Treats an error message as success, or misreads a number
Invented results · Says it did something it did not, or reports a tool result that was never returned
Loops and waste · Repeats a call, retries without change, burns tokens and time
Goal drift · Slides from the task given to a related one, or over-reaches by doing more than asked
Cascading errors · One early mistake carried through all later steps
Over-permission · Acts in ways the user never intended because the tools let it
Prompt injection · Follows instructions hidden in a web page, email or document it read
Data leakage · Reveals private information in an answer or sends it to a tool
Silent failure · Gives up or fails without telling anyone, and looks as if it succeeded
Cost runaway · Many steps or retries in a short time
Most of these have been met in earlier lessons. The point of this lesson is to put the defences together.
Guardrails in layers
A guardrail is any check or limit that stops or corrects bad behaviour. No single guardrail is enough, so you stack them in layers, each catching what the others miss. This is called defence in depth.
1. Input guardrails. Check what comes in before the agent acts.
Validate user input for length, format and obviously unsafe content.
Screen for attempts to override instructions or extract the system prompt.
Detect personal data that should not be sent to a model or stored.
Check that the request is in scope, so that a billing assistant declines to write a poem.
2. Tool guardrails. Constrain what each tool can do. These are the strongest, because they are enforced by your code and not by the model's judgment.
Give each tool the least privilege it needs: read-only where possible, access to one table, one folder or one customer's records.
Validate arguments against a strict schema and reject anything out of range.
Set limits: a maximum refund, a maximum number of emails a day, a list of allowed domains.
Use allow lists and not block lists: define what is permitted rather than trying to list everything that is not.
Make write actions idempotent and reversible where you can, with undo or a delay before they take effect.
3. Output guardrails. Check what goes out.
Validate format and check citations and numbers against sources, as in Lesson 5.3.
Screen for policy violations, unsafe content and leaked personal data.
Check that the answer matches the task and does not promise what the system cannot deliver.
4. Process guardrails. Control how the agent runs.
Step, time and cost caps, as in Lesson 7.2.
Repetition detection and stuck-run handling.
Approval points for risky actions.
Checkpoints that verify intermediate results, as in Lesson 7.3.
5. System guardrails. Protect everything around the agent.
Sandboxing. Run code and risky tools in an isolated environment with no access to secrets or production systems.
Secrets handling. Keep keys and passwords out of the prompt and out of the model's reach, so that tools use them but the model never sees them.
Rate limits and quotas per user and overall.
A kill switch, a way to stop the agent or one of its tools at once.
Audit logs of every action, so that you can investigate.
An important rule runs through all of these: put hard limits in code, not in the prompt. A prompt saying "never refund more than ₹5,000" is a request that the model may fail to follow. A check in the refund tool that rejects any amount above ₹5,000 is a guarantee. Use prompts to guide behaviour and code to enforce it.
Why layers help, and their limit
Suppose each guardrail layer independently catches 70% of bad actions that reach it. One layer lets 30% through. Two layers let through 0.3 × 0.3 = 9%. Three let through 0.3 to the power 3 = 2.7%. Four, 0.8%.
Layers · Share of bad actions that get through · Share caught1 · 30% · 70%
2 · 9% · 91%
3 · 2.7% · 97.3%
4 · 0.8% · 99.2%
Each added layer cuts the leak by 70% of what remains, and three or four layers bring a mediocre check up to something dependable. If 1,000 bad actions are attempted in a month, one layer lets 300 through and three layers let 27 through.
There is an important caution. The calculation assumes the layers fail independently. Layers that use the same method, such as three prompts to the same model asking whether an action is safe, tend to fail on the same cases, and stacking them adds far less than the arithmetic suggests. Real defence in depth uses different kinds of check: a schema validator, a permission rule in code, a limit on amounts, a second model with a different prompt and a human approval. Diversity is what makes the layers independent.
Human approval: where it is worth its cost
Some actions should not be taken without a person's agreement. Ask of each action: how bad is the worst case, can it be undone, how often does it happen, and how well can a person judge it from what they are shown?
Always require approval for actions that are irreversible, costly, public or legally significant: paying money, deleting data, sending messages to customers, signing, publishing.
Require approval above a threshold, such as refunds over ₹5,000, or emails to more than 20 people.
Require approval when the agent is unsure, or when the request is unusual or outside tested cases.
Do not require approval for low-risk, reversible, frequent actions, such as reading a document or drafting a reply that a person will send.
Approval has a cost, in people's time, and a risk of its own, since reviewers who approve hundreds of requests a day stop reading them. Show the reviewer what matters: the proposed action, the reason, the key numbers and what will change. Make approving and rejecting equally easy, and measure how often reviewers reject or edit. A rejection rate near zero over a long time may mean the checks are unnecessary, or that nobody is looking.
Take a workload example. An agent proposes 10,000 actions a month, and 8% of them, those above a risk threshold, need approval. That is 800 approvals. If each takes 2 minutes, the work is 1,600 minutes, about 26.7 hours a month. At ₹300 an hour, the cost is ₹8,000, which may be a small price for avoiding a large loss. If the threshold were lowered so that 30% needed approval, the work would rise to 100 hours and ₹30,000, and queues would build.
Testing for reliability
Agents are not deterministic, so one successful run proves little. Measure how they behave across many runs.
Success rate. Run each test task several times and record the share of runs that reach the right outcome.
Consistency. A user relies on the agent working every time, not on average. If the success rate per run is 85%, the chance of succeeding on all of 5 runs of the same task is 0.85 to the power 5 = 44%, and on all of 8 runs 27%. A measure sometimes called pass to the power k, the chance of succeeding k times in a row, shows how fragile a good-looking average can be. Choose k to match the number of times a user would depend on it.
Trajectory checks. Besides the outcome, look at the route: did it use the right tools, avoid forbidden ones, stay within the step cap and avoid unnecessary calls?
Safety tests. A set of adversarial cases, such as requests to exceed limits, instructions hidden in documents, attempts to extract secrets and requests outside scope. The agent should refuse or escalate. Run them on every release.
Mock tools. Test with stand-in versions of tools that return scripted results, including errors, empty results and malicious text, so that runs are repeatable and nothing real is touched.
Failure injection. Make a tool time out or return garbage, and check that the agent copes: retries sensibly, tells the user and does not claim success.
Cost and delay. Record tokens, steps and time per run, and look at the tail.
Least privilege and sandboxes
Give the agent only the access it needs, for only as long as it needs it.
Narrow credentials. A read-only database user for lookups, a separate account with strict limits for writes. Never give an agent an administrator key.
Scoped by user. The agent acts with the rights of the person it serves, not with a master key. A customer's session cannot reach another customer's data.
Time-limited tokens that expire, so a leaked one is not useful for long.
Sandboxes for code and files. If the agent can run code, run it in an isolated container with no network or limited network, no secrets and a limit on time and memory. If it can edit files, give it a copy or a limited folder.
Separate environments. Test with fake data and mock services, and move to production in steps.
Handling failure well
Because failures will happen, design for them.
Fail safe. When unsure or stuck, stop and hand over to a person, with a clear note of what was tried. Do not guess on irreversible actions.
Fail loudly. Never pretend an action worked. Report errors honestly to the user and to your logs.
Undo. Where possible, make actions reversible or delayed, such as holding an email for a minute or marking records for deletion before removing them.
Degrade gracefully. If a tool is down, offer what can still be done, or a manual route.
Respond to incidents with a runbook: contain, diagnose, fix, learn, as in Lesson 6.4, and add every failure to the test set.
A staged path to autonomy
Do not start by letting the agent act alone. Move in stages, and advance only when the evidence supports it.
1. Suggest only. The agent proposes actions and drafts, and a person does everything. You collect data on how often the suggestions are right.
2. Act with approval. The agent prepares the action and a person approves each one. Measure approval and edit rates.
3. Act on low-risk actions, with approval for the rest. Define clearly what low risk means, and set limits in code.
4. Act broadly, with monitoring. Wide autonomy within limits, with sampling of actions, alerts, a kill switch and regular review.
At each stage, set the criteria for moving on, such as "at least 95% of suggestions accepted without edit over 500 cases", and for moving back, such as "any serious incident returns the agent to the previous stage". Autonomy is earned by evidence and can be withdrawn.
Three worked examples
Example 1: a refund agent. A retailer's agent can issue refunds. The team stacks five layers of different kinds. The input is screened for requests that are out of scope. The refund tool takes the customer's identity from the session and only offers orders belonging to that customer. A limit in code rejects any refund above ₹3,000, and refunds between ₹1,000 and ₹3,000 go to a human. A second model with a separate prompt checks the stated reason against the policy text. Every action is logged. In a test with 400 adversarial cases, each layer alone misses between 20% and 35% of them, and together they miss 2, which is 0.5%. The team notes that the layers are of different kinds, which is why the combined figure is better than any single one.
Example 2: a coding agent in a sandbox. An agent fixes failing tests. It runs in a container with a copy of the repository, no network access except to the package mirror, no secrets and a 10-minute time limit. It cannot push to the main branch, so its work appears as a proposed change for a developer to review. A step cap of 15 and a repetition check stop loops. When it deleted a configuration file in one run, the damage was confined to the copy.
Example 3: staged autonomy. A finance team's assistant drafts payment instructions. In month one it only suggests, and humans accept 82% without edits. In month two, with approval for each, the acceptance reaches 94%. After the team fixes two recurring errors, with a limit in code of ₹50,000 a payment and a rule that a new payee always needs a person, acceptance reaches 97% over 600 cases. The assistant is allowed to execute payments under ₹10,000 to known payees on its own, with a daily sample of 5% reviewed and a rule that two wrong payments in a week return it to approval mode.
A guardrail worksheet
1. The actions. What can the agent do? List each, with its worst case and whether it can be undone.
2. The layers. Input, tool, output, process and system guardrails, and the kind of each.
3. The hard limits. What is enforced in code?
4. The privileges. What access does each tool have, and is it the least needed?
5. The approvals. Which actions need a person, with thresholds, and the expected workload.
6. The failure behaviour. Fail safe, fail loudly, undo, degrade.
7. The tests. Success rate, consistency over k runs, safety cases, failure injection.
8. The sandbox. Where risky actions run, and what is out of reach.
9. The stages. The path from suggest-only to autonomy, with criteria to advance and retreat.
10. The incident plan. Who is called, how to stop the agent and how failures become tests.
Common mistakes
Relying on the prompt for limits that code should enforce.
Stacking checks of the same kind and counting them as independent.
Giving broad credentials for convenience.
No approval where actions are irreversible, or approval for everything so that reviewers stop reading.
Judging an agent by one successful run.
No adversarial tests.
Silent failures that look like success.
Granting autonomy all at once.
No kill switch.
Key takeaways
Agents fail by choosing wrong tools or arguments, misreading results, inventing results, looping, drifting, cascading errors, over-reaching, being injected, leaking data, failing silently and running up costs.
Defend in layers at input, tool, output, process and system levels, and put hard limits in code, not in the prompt.
Independent layers multiply: if each catches 70%, three layers let through 2.7% and four 0.8%. Layers of the same kind fail together, so use different kinds of checks.
Use human approval for irreversible, costly or unusual actions, and count the workload. In the example, 800 approvals a month take about 27 hours.
Measure consistency. If a run succeeds 85% of the time, the chance of five successes in a row is 44%.
Apply least privilege, scope by user, expire tokens and run risky code in a sandbox.
Fail safe and loudly, make actions reversible and move autonomy forward in stages with criteria to advance and to retreat.
Check yourself
1. Why is "never refund more than ₹5,000" better enforced in the refund tool than in the prompt?
A prompt is a request the model may not follow, while a check in the tool is enforced by code and cannot be argued around.
2. Each of 4 independent layers catches 60% of bad actions. What share gets through?
0.4 to the power 4 = 0.0256, or 2.6%.
3. Why may three prompts to the same model be a weak set of layers?
They share the same blind spots, so they tend to miss the same cases, and the layers are not independent.
4. An agent succeeds on 90% of runs. What is the chance it succeeds on all of 4 runs?
0.9 to the power 4 = 0.656, or about 66%.
5. What is least privilege?
Giving a tool or agent only the access it needs, such as read-only access to one table, and no more.
6. What should move an agent from one stage of autonomy to the next?
Evidence against criteria set in advance, such as an acceptance rate over a large number of cases, with a rule for retreating after a serious incident.
Try this
Design guardrails for a real agent. Set aside 60 minutes.
1. Choose an agent you use or would build, and list five actions it could take, with the worst case of each.
2. Mark each action as reversible or not and low, medium or high risk.
3. For each medium or high-risk action, write a guardrail at the tool level in code terms, such as a limit or a permission rule, and one at another level.
4. Use the first simulator with an honest catch rate and the number of layers to estimate how many bad actions a month would get through, and note whether the layers are of different kinds.
5. Decide which actions need approval, and use the second simulator to estimate the monthly workload.
6. Write five adversarial test cases and the expected behaviour for each.
7. Write the stages from suggest-only to autonomy, and the evidence needed to advance from the first to the second.
A good result is a risk table of actions, a layered set of guardrails with limits in code, a leak estimate and an approval workload, five adversarial tests and a staged plan with criteria.
Tags: AI Engineering Agents Guardrails Reliability Safety