Guardrails

How permissions, argument checks, human approval and careful handling of untrusted text limit the damage when an AI agent makes a mistake.

15 minLesson 6 of 6
On this page
  1. The four places to put a limit
  2. Permissions
  3. Checking the arguments of a tool
  4. Human approval
  5. Untrusted text and prompt injection
  6. Checking what the model says
  7. Pitfalls
  8. What to do in practice
  9. What to practise next

A guardrail is a check that runs in ordinary code before an agent's action is carried out, and it applies whatever the model has written. Guardrails exist because a model can misread a request, follow reasoning that sounds right but is wrong, or be steered by text it read in a tool result, and better instructions cannot bring the chance of that to zero.

Suppose you tell a coding agent in capital letters to delete files only inside tmp/. The agent builds the path from two parts, one of them is empty, and the delete runs on the whole project folder. The instruction was clear, but it was only a request, and the delete tool accepted any path. A delete tool that refuses every path outside tmp/ would have stopped the damage, no matter what the model wrote.

The four places to put a limit

You can limit an agent at four points, and they work best together. Each one is covered in its own section below.

  1. Permissions decide which tools the agent has at all and what its credentials can reach.
  2. Argument checks decide which paths, amounts and recipients a tool will accept.
  3. Human approval holds risky actions until a person says yes.
  4. Handling of untrusted text decides how much power the agent keeps after it has read content that someone else wrote.

Permissions

The safest tool is one the agent does not have. An agent that answers questions about orders needs a tool that reads orders, and it has no need for a tool that deletes customers. If you leave the delete tool out and connect the agent to the database with a read-only account, then even an attack that completely fools the model leaves it nothing to call.

The same applies to credentials. If the agent uses an API key that can do everything your own admin account can do, then every bug in the agent becomes an admin-level bug. Give the agent its own key with only the scopes it needs. A separate key also makes the agent's actions easy to find in the logs and easy to revoke without affecting anything else.

Checking the arguments of a tool

Allowing a tool does not make every call to it safe, because the harm usually depends on the arguments. A tool that sends email is harmless with one recipient and a data leak with another. The place to enforce limits is inside the tool, the same place where Tool Use showed validation of bad input. Here the checks are aimed at dangerous input rather than malformed input. Typical checks are:

  • A file tool resolves the path, including .. segments and symbolic links, and only then checks that the result is inside the allowed folder. Checking the text of the path before resolving it can be bypassed.
  • A refund tool accepts an amount only up to the value of the order it refers to.
  • An email tool sends only to addresses that appear on the customer's record.
  • A tool that runs code does so in a sandbox with no network access and no view of your files.

Rate limits are a useful addition. A limit of ten refunds per hour will not stop a single bad refund, but it stops a confused agent from repeating the same mistake a hundred times before anyone notices.

Human approval

Some actions are too costly or too hard to undo to leave to the model, and for those the system should pause and show the request to a person. The way to decide is to sort each tool by what happens when it is used wrongly. The table summarises a common sorting.

RiskExamplesDefault
Read onlylook up an order, search documentsrun automatically
Small or easy to undoa refund under 50, a draft replyrun and log it
Costly, external or permanenta large refund, sending email, deleting, publishingask a person first
Not needed for this jobdeleting a customerno tool at all

Approval only works if the person can make a real decision. The request has to show the exact recipient, amount or list of files, and not a summary written by the model, and the default answer should be no. If the agent asks about everything, including harmless lookups, the person soon approves without reading, and then the one dangerous request is approved as well. For that reason the automatic category should be as large as safety allows.

A policy gate applies the sorting to every tool request before anything runs. The tracer below follows five requests through one.

A policy gate checks each actionUse the arrows or ← → keys
rule = policy[call.tool]if no rule: blockif rule is read: allowif money and amount <= autoLimit: allowotherwise: ask a person
  1. actions
    requestruleoutcome
    getOrder(1042)readallowed
    ran
    1
    asked a person
    0
    blocked
    0

    1Looking up order 1042 changes nothing, so it runs without asking anyone.

  2. actions
    requestruleoutcome
    getOrder(1042)readallowed
    refundOrder(1042, 30)money, 30 ≤ 50allowed
    ran
    2
    asked a person
    0
    blocked
    0

    2A refund of 30 involves money, but it is under the automatic limit of 50, so it runs and is logged.

  3. actions
    requestruleoutcome
    getOrder(1042)readallowed
    refundOrder(1042, 30)money, 30 ≤ 50allowed
    refundOrder(2210, 400)money, 400 > 50approved
    ran
    3
    asked a person
    1
    blocked
    0

    3A refund of 400 is over the limit, so a person checks the order, the amount and the payment records, and approves it.

  4. actions
    requestruleoutcome
    getOrder(1042)readallowed
    refundOrder(1042, 30)money, 30 ≤ 50allowed
    refundOrder(2210, 400)money, 400 > 50approved
    deleteCustomer(sam@…)noneblocked
    ran
    3
    asked a person
    1
    blocked
    1

    4To close an account, the agent tries deleteCustomer. That tool is not in the policy, so the call is blocked, and the agent reads the error and tells the customer that a person will handle it.

  5. actions
    requestruleoutcome
    getOrder(1042)readallowed
    refundOrder(1042, 30)money, 30 ≤ 50allowed
    refundOrder(2210, 400)money, 400 > 50approved
    deleteCustomer(sam@…)noneblocked
    sendEmail(backup@example.net)externaldeclined
    ran
    3
    asked a person
    2
    blocked
    1

    5A customer message contained a hidden line telling the agent to email the customer list to an outside address. Sending email is an external action, so a person sees the unknown recipient and declines.

  6. actions
    requestruleoutcome
    getOrder(1042)readallowed
    refundOrder(1042, 30)money, 30 ≤ 50allowed
    refundOrder(2210, 400)money, 400 > 50approved
    deleteCustomer(sam@…)noneblocked
    sendEmail(backup@example.net)externaldeclined
    ran
    3
    asked a person
    2
    blocked
    1

    6Three actions ran, one was blocked and one was declined. The person was asked only twice, and both requests deserved a look. Asking about every lookup would have taught them to click yes without reading.

1 / 6

The gate in code

The gate takes the place of the direct tool call in the agent loop. In the code below, askHuman shows the request to a person and returns yes or no.

const policy = {
  getOrder: { risk: "read" },
  refundOrder: { risk: "money", autoLimit: 50 },
  sendEmail: { risk: "external" },
};
 
function checkAction(call) {
  const rule = policy[call.tool];
  if (!rule) return { decision: "block", reason: `${call.tool} is not on the allowed list` };
  if (rule.risk === "read") return { decision: "allow" };
  if (rule.risk === "money" && call.input.amount <= rule.autoLimit) {
    return { decision: "allow" };
  }
  return { decision: "ask" };
}
 
function guardedRun(call, runTool, askHuman) {
  const { decision, reason } = checkAction(call);
  if (decision === "block") return { error: `Blocked: ${reason}.` };
  if (decision === "ask" && !askHuman(call)) {
    return { error: "A person declined this action. Do not retry it." };
  }
  return runTool(call);
}
policy = {
    "get_order": {"risk": "read"},
    "refund_order": {"risk": "money", "auto_limit": 50},
    "send_email": {"risk": "external"},
}
 
def check_action(call):
    rule = policy.get(call["tool"])
    if rule is None:
        return {"decision": "block", "reason": f"{call['tool']} is not on the allowed list"}
    if rule["risk"] == "read":
        return {"decision": "allow"}
    if rule["risk"] == "money" and call["input"]["amount"] <= rule["auto_limit"]:
        return {"decision": "allow"}
    return {"decision": "ask"}
 
def guarded_run(call, run_tool, ask_human):
    check = check_action(call)
    if check["decision"] == "block":
        return {"error": f"Blocked: {check['reason']}."}
    if check["decision"] == "ask" and not ask_human(call):
        return {"error": "A person declined this action. Do not retry it."}
    return run_tool(call)

Two details of this code matter. The policy lists the tools that are allowed, so a tool nobody has classified yet is blocked until someone decides what to do with it. If the policy listed forbidden tools instead, forgetting to add one would leave it open. The second detail is that a block or a refusal comes back to the model as an error message it can read, so the agent can tell the user what happened instead of retrying the same call.

Untrusted text and prompt injection

The sendEmail request in the tracer came from text inside a customer message, not from the user. This is the attack described in Prompt Injection. When an agent reads text that you do not control, such as a web page, an incoming email or an uploaded document, whatever it does next may be steered by the author of that text, and the model cannot reliably tell the difference.

You can use the gate to react to this. After the agent has read untrusted content, require approval for any action that sends a message or touches private data, even if the same action would run automatically at the start of the session. The attack that does the most damage needs three things at once: untrusted text, access to private data, and a way to send data out. Removing or gating any one of the three makes the attack much harder.

Checking what the model says

The sections above limit what an agent can do. Many products also check what the model writes to the user, because a reply can contain private data, a link the model made up, or text that breaks your policy. These output checks usually run after generation and are either simple rules, such as a pattern that detects card numbers or a list of allowed link domains, or a second model call that classifies the reply. They help, but they are weaker than the limits on actions: a classifier can be wrong in both directions, and a rule can only catch what its author thought of. Use output checks for what the user sees, and use permissions and argument checks for anything that changes the world.

Pitfalls

What to do in practice

Start from the tool list, not from the prompt. For each tool, write down the worst thing it could do with the worst arguments the model could produce. Remove tools the job does not need, narrow the credentials of the ones that remain, and put argument checks inside the tools. Then assign each remaining tool to automatic, logged or approval according to the table above, and make approval requests show exact details.

Log every action together with the decision made, so that you can see what the agent tried and what the gate stopped. A pattern of blocked calls is often the first sign that a prompt is being attacked or that the instructions confuse the model. Finally, turn each worst case you wrote down into a test in your evals, so that a later change to a prompt or a tool cannot quietly remove a limit.

Try it: Set the policy for an assistant

An assistant manages a person's calendar and email using the tools below. For each tool, choose one of run automatically, run and log, ask first, or remove, and give one reason.

Show a sample answer
  • readCalendar: run automatically. Reading changes nothing.
  • createEvent: run and log. It only touches the user's own calendar and is easy to undo.
  • sendEmail: ask first. It reaches other people and cannot be unsent, so the request should show the recipients and the full text.
  • deleteEmail: ask first, or make it reversible by moving mail to a trash folder that is emptied after 30 days.
  • readWebPage: run automatically, but treat the rest of the session as untrusted and require approval for any send.
  • forwardAllEmail: remove. No everyday task needs it, and it gives an attacker a silent and permanent copy of everything the user receives.

The decision follows what a wrong call would cost, not how often the tool is useful.

Quick check

An agent only answers questions about orders. What most reliably prevents it from ever deleting data?

Why should the policy list the tools that are allowed instead of the tools that are forbidden?

A file tool checks that a path starts with tmp/ and then deletes it. Which input gets past the check?

An agent reads a web page and then asks to send an email. What is the safest default?

What to practise next

List your agent's tools with the worst thing each could do, add those cases to your evals, and read Privacy and Security for what to keep out of AI tools in the first place.