Write a policy

A policy is the set of rules that every guarded call must pass. This page shows how to write rules, how to let a rule fix a call, and the rules that come with the library.

A rule is a function

A rule gets two things: the proposed call and the trace (what the guard knows so far). It returns None when the call is fine. It returns a short message when the call breaks the rule.

from causalrepair import Guard, Policy, ToolCall, Violation, require_confirmation

orders = {"A1": {"customer": "ann", "paid": 50.0, "refunded": 10.0}}

policy = Policy(guarded={"refund"})        # the tools this policy checks

@policy.rule(tools={"refund"}, category="eligibility")
def not_more_than_paid(call, trace):
    order = orders[call.args["order_id"]]
    if order["refunded"] + call.args["amount"] > order["paid"]:
        return "the refund would be more than the customer paid."

call.name is the tool name and call.args is a dict of its arguments.

@policy.rule(...) adds the function to the policy. Its options:

  • tools: the tools the rule applies to (leave it out to apply the rule to every guarded tool);
  • category: what kind of rule it is (see Categories);
  • name: the rule’s name in messages and records (default: the function’s name).

You can also add rules with policy.add(rule1, rule2, ...). It returns the policy, so you can chain it: Policy(guarded={"refund"}).add(require_confirmation()).

What a rule can return

the rule returns meaning
None or True the call passes this rule
a string the call breaks the rule; the string is the message
False the call breaks the rule, with a default message
a Violation the call breaks the rule; you choose every detail, such as a fix
a list of the above several problems at once

A Violation that you return keeps its own rule and category (the category is other unless you set it). The name and category of @policy.rule(...) are not copied into it, so set them in the Violation itself.

If a rule raises an error (for example a missing key), the call counts as breaking the rule. The guard never lets a call through because a rule could not be checked.

Categories

The category tells the guard what kind of problem a rule finds. It changes what the nearest repair does:

category use it for the nearest repair
confirmation a missing “yes” (require_confirmation uses it) asks for a “yes”
argument a wrong argument value fixes the argument if the rule offers a fix; else tells the agent the broken rule
identity the user may not act on this record tells the agent the broken rule
eligibility the action is not allowed in this state tells the agent the broken rule
other anything else (the default) tells the agent the broken rule

The last column holds when all the broken rules have that category. When rules of different categories are broken together (for example a missing “yes” and a wrong argument), the guard tells the agent all the broken rules. Whatever the categories, when every broken rule offers a fix (see below), the nearest repair runs the fixed call.

You may use any other category name. It is also part of the situation label that a learned guard uses.

Let a rule fix the call

A rule can offer fixed arguments. Return a Violation with repair, a dict of the arguments to change. When every broken rule offers a fix, the guard can run the call with the fixed arguments (the arg_repair option).

Offer a fix only when it keeps what the user wanted. Here, giving back what is left keeps the user’s wish (a full refund):

policy = Policy(guarded={"refund"})
policy.add(require_confirmation())

@policy.rule(tools={"refund"}, category="argument")
def cap_to_what_is_left(call, trace):
    order = orders[call.args["order_id"]]
    left = order["paid"] - order["refunded"]
    if call.args["amount"] > left:
        return Violation("cap_to_what_is_left", f"only ${left:.2f} is left to refund.", "argument",
                         repair={"amount": left})

def refund(order_id, amount):
    orders[order_id]["refunded"] += amount
    return f"refunded ${amount:.2f} on order {order_id}"

session = Guard(policy).session()
tools = session.tools({"refund": refund})
session.user("Order A1 broke. Please refund all of it, yes.")
print(tools["refund"](order_id="A1", amount=50.0))
print(session.records[-1]["chosen"], session.records[-1]["executed_args"])

It prints:

refunded $40.00 on order A1
arg_repair {'order_id': 'A1', 'amount': 40.0}

Before a fixed call runs, the guard checks it against every rule again. If it still breaks a rule, the guard tells the agent the broken rules instead.

A Violation has these fields:

field meaning
rule the rule’s name
message what went wrong, in words the agent can act on
category see Categories (default other)
repair the arguments to change, or None if there is no safe fix
guidance an optional next step, shown to the agent after the message

repair is merged into the call’s arguments. If a fix must replace the whole argument list (for example, drop an argument), make your own class from Policy and override Policy.repair(call, violations).

Use facts from your application

Some rules need facts that the agent must not decide, such as who is logged in. Put them in the session when it starts. Rules read them from trace.context:

policy = Policy(guarded={"refund"})

@policy.rule(tools={"refund"}, category="identity")
def own_orders_only(call, trace):
    if orders[call.args["order_id"]]["customer"] != trace.context["customer_id"]:
        return "this order belongs to another customer."

session = Guard(policy).session(customer_id="bob")     # set by your login code, never by the agent
print(session.review(ToolCall("refund", {"order_id": "A1", "amount": 5})).message)

It prints:

GUARD: not executed. The call violates policy:
- [own_orders_only] this order belongs to another customer.

session.context is the same dict as trace.context. If you change it later (for example after a login), the rules see the change.

Use what happened before

The trace tells a rule what happened earlier in the conversation:

method what it gives
trace.last_user_text() the latest user message
trace.user_texts() all user messages
trace.user_affirmed() True if the latest user message says “yes” (or a similar word) and does not take it back (“No, do not proceed”, “I’m not sure”)
trace.calls("refund") the calls to a tool that ran, in order
trace.results("refund") their results, each with a status and content
trace.last_status("refund") "ok", "error", "unknown", or None if the tool never ran
trace.context the facts your application set

For example, a rule that allows at most one refund for each order:

@policy.rule(tools={"refund"}, category="eligibility")
def one_refund_per_order(call, trace):
    if any(c.args["order_id"] == call.args["order_id"] for c in trace.calls("refund")):
        return "this order was already refunded once."

Built-in rules

The library has five ready-made rules.

require_confirmation

The latest user message must say “yes” (or a word like it) before a guarded call runs.

from causalrepair import require_confirmation

policy = Policy(guarded={"refund", "cancel"}).add(require_confirmation())

These words count: yes, yeah, yep, yup, sure, confirm, confirmed, go ahead, proceed, please do, do it, correct, that’s right, sounds good, absolutely, ok, okay. Only the latest user message counts. To use other words, pass your own pattern: require_confirmation(pattern=re.compile(r"\bI confirm\b", re.I)). To check only some tools, pass tools={...}.

argument_bounds

A number argument must lie between low and high.

from causalrepair import argument_bounds

policy = Policy(guarded={"refund"}).add(argument_bounds("refund", "amount", low=0.01, high=100))

With clip=True, the rule offers the nearest allowed value as a fix. Use clip only when that keeps what the user wanted.

forbid

Calls to these tools are never allowed. The tools must also be in guarded, because rules only check guarded tools.

from causalrepair import forbid

policy = Policy(guarded={"refund", "delete_account"}).add(forbid({"delete_account"}, "only a person may delete accounts."))

must_match_request

The call must match something the user asked for. This protects against prompt injection: text hidden in a web page or a tool result that tells the agent to do something else. You give a function that finds the user’s requests in the user’s own messages. A call that matches none of the requests that are still open (not done yet) breaks the rule.

import re
from causalrepair import must_match_request

def stated_trades(trace):
    """The trades the user asked for, found in the user's own messages."""
    found = []
    for text in trace.user_texts():
        for qty, symbol in re.findall(r"buy (\d+) shares of ([A-Z]+)", text):
            found.append({"symbol": symbol, "quantity": int(qty)})
    return found

def buy(symbol, quantity):
    return f"bought {quantity} {symbol}"

policy = Policy(guarded={"buy"}).add(must_match_request(stated_trades, tools={"buy"}, keys=["symbol", "quantity"]))
session = Guard(policy).session()
tools = session.tools({"buy": buy})
session.user("Please buy 15 shares of META.")
print(tools["buy"](symbol="EVIL", quantity=15))     # an injected instruction changed the symbol

It prints:

bought 15 META

When exactly one request of the user is still open, the rule offers it as a fix, so the guard ran the trade the user asked for. Text inside tool descriptions or tool results never counts as a request.

no_repeat_after_success

A call may not repeat an earlier call to the same target that already succeeded.

from causalrepair import no_repeat_after_success

policy = Policy(guarded={"send_payment"}).add(
    no_repeat_after_success({"send_payment"}, target=lambda call: call.args["invoice"]))

target says what counts as the same target. By default it is the same tool with the same arguments.

Good habits

  • Guard every tool that changes something. Reads can stay unguarded.
  • Keep each rule small and give it a clear message. The agent reads the message and must be able to act on it.
  • Take facts from your own code (trace.context, your database), never from what the agent says.
  • Offer a fix only when it keeps what the user wanted.