More options
This page shows the settings of Guard(...) beyond the policy and the mode. Every example builds on the shop policy below.
from causalrepair import Guard, Intervention, Policy, ToolCall, Veto, require_confirmation
orders = {"A1": {"paid": 50.0, "refunded": 0.0}, "B2": {"paid": 900.0, "refunded": 0.0}}
def refund(order_id, amount):
orders[order_id]["refunded"] += amount
return f"refunded ${amount:.2f} on order {order_id}"
policy = Policy(guarded={"refund"}).add(require_confirmation())
@policy.rule(tools={"refund"}, category="eligibility")
def manager_needed(call, trace):
if call.args["amount"] > 500:
return "refunds above $500 need a manager."
Show a trusted record (verify first)
The verify_first option shows the agent a trusted record, so that it can check its call before it tries again. It is on the menu only when you tell the guard how to read that record:
def read_order(call, session):
"""A trusted read of the call's target, from your own database."""
return str(orders.get(call.args["order_id"]))
guard = Guard(policy, verify=read_order, verify_source="get_order")
verify(call, session) returns the record as text, or None if there is none. verify_source is the name of the read, shown to the agent. It can also be a function verify_source(call) -> str.
Add your own option
An Intervention is a new option that does not run the call. It has a name, a distance and a message. By default it is on the menu whenever a rule is broken (change this with available=).
The nearest repair never picks your own option, because it does not know when your option is right. A chooser and a collect guard can pick it. A learned guard can pick it too, if you tell the fit its distance and its place in the list of options:
from causalrepair.interventions import DISTANCE, ORDER
art = Artifact.fit(episodes, dist={**DISTANCE, "escalate": 1.0}, order=ORDER + ["escalate"])
Here a chooser sends large refunds to a manager:
from causalrepair.interventions import nearest_repair, violation_class
escalate = Intervention("escalate", distance=1.0,
message=lambda call, violations, session:
"GUARD: not executed. A manager will review this refund. Tell the user.")
def chooser(stratum, menu, violations, session, call):
if "escalate" in menu and call.args["amount"] > 500:
return "escalate"
return nearest_repair(menu, violation_class(violations)) # else: the usual choice
session = Guard(policy, extra=[escalate], chooser=chooser).session()
session.user("Refund $900 on order B2, yes.")
d = session.review(ToolCall("refund", {"order_id": "B2", "amount": 900}))
print(d.menu)
print(d.intervention, "|", d.message)
It prints:
['confirm_first', 'rule_feedback', 'generic_deny', 'escalate']
escalate | GUARD: not executed. A manager will review this refund. Tell the user.
Pick in your own way (chooser)
chooser(stratum, menu, violations, session) returns the name of an option on the menu. Add a call parameter, as above, to get the proposed call too. The guard raises an error if the chooser picks an option that is not on the menu (or an option offered once per tool that this tool already used), so a chooser can never run a call that breaks a rule (unless the guard is in off mode, which runs everything).
Add your own checks (vetoes)
A veto is your own check after the guard has decided: a reviewer model, a human approval, a limit that is kept somewhere else. It returns None to let the decision stand, or a Veto (or just a message) to stop the call. A veto can never run a call that the guard stopped.
DAILY_LIMIT = 100.0
def daily_limit(call, decision, session):
spent = sum(c.args["amount"] for c in session.trace.calls("refund"))
if decision.allowed and spent + decision.call.args["amount"] > DAILY_LIMIT: # the call that would run
return Veto("GUARD: not executed. This refund would pass today's limit.", "daily_limit")
session = Guard(policy, vetoes=[daily_limit]).session()
tools = session.tools({"refund": refund})
session.user("Refund $40 on A1 and $90 on B2, yes.")
print(tools["refund"](order_id="A1", amount=40.0))
print(tools["refund"](order_id="B2", amount=90.0))
print([r["chosen"] for r in session.records])
It prints:
refunded $40.00 on order A1
GUARD: not executed. This refund would pass today's limit.
['execute', 'daily_limit']
The stopped call is recorded with the veto’s name as the chosen option. Vetoes run in order, and the first one that stops the call wins. A veto can add fields to the record through decision.log.
If you collect logs for a learned guard, veto only where the deployed guard will veto too.
Change what the agent sees
message(decision, session) returns the text the agent sees for any call that does not run. Return None to keep the guard’s own message:
def friendly(decision, session):
if decision.intervention == "generic_deny":
return "Sorry, I can't do that here."
return None
session = Guard(policy, mode="block", message=friendly).session()
session.user("Refund A1.")
print(session.review(ToolCall("refund", {"order_id": "A1", "amount": 10})).message)
It prints:
Sorry, I can't do that here.
Limit the options
options= keeps only some of the six built-in options. It must keep execute, and at least one of rule_feedback and generic_deny. When the mode’s usual pick is left out, the guard tells the agent the broken rules instead, or else denies the call.
guard = Guard(policy, options={"execute", "arg_repair", "confirm_first", "rule_feedback"})
once= offers an option at most once for each tool in an episode (Choose a mode).
Label situations
A learned guard learns one set of numbers for each situation label (stratum). You can add parts to the label:
guard = Guard(policy, domain="shop", tool_class=lambda call: "write")
session = guard.session()
session.user("Hi.")
print(session.review(ToolCall("refund", {"order_id": "A1", "amount": 10})).stratum)
It prints:
shop|write|confirm_only
domain: a first part for every label. It also allows one harm limit for each domain when you fit (per_domain=True). You can also set it for one session:guard.session(domain="travel").tool_class(call): a part that depends on the call, for example"write"or"read".stratify(call, violations, session): replaces the whole label with your own.
Fix these before you collect any data, and keep them the same when you deploy.
Unknown results
A timeout (TimeoutError, or asyncio’s) marks a call’s result as unknown: it may or may not have taken effect. A call interrupted while it runs (a cancelled task, Ctrl-C) is recorded as unknown too, and the interruption is raised again. To decide yourself what counts as unknown, pass is_unknown. It gets the exception, or the tool’s return value:
from causalrepair.guard import is_timeout
def is_unknown(x):
return is_timeout(x) or (isinstance(x, dict) and x.get("status") == "pending")
guard = Guard(policy, is_unknown=is_unknown, unknown_message="Error: the request timed out.")
unknown_message is what the agent sees when a call raised an exception that counts as unknown.
Logs and random seeds
| setting | meaning |
|---|---|
log="logs/run.jsonl" | add every finished episode to this file, one line of JSON each |
seed=0 | the seed of the random picks in collect mode, so a run can be repeated |
design=fn | design(menu, violations) -> {option: chance}: the chances used in collect mode |
By default, collect picks uniformly from the menu when a rule is broken. When no rule is broken, it runs the call with chance 0.6, and shows a record first or asks for a “yes” with chance 0.2 each (only the options that are on the menu, scaled to add up to 1).