Get started
This page builds a guard for a small shop agent, one step at a time. Every code block on this page is part of one program, so you can copy them in order and run them.
Install
From GitHub:
pip install git+https://github.com/vicky157/causal-repair.git
Or from a copy of the repository, if you want to change the code or run the examples:
git clone https://github.com/vicky157/causal-repair.git
cd causal-repair
pip install -e .
Check that it works:
python -c "import causalrepair; print(causalrepair.__version__)"
Step 1: list your tools
Write down the tools your agent can call. Then mark the ones that change something: they write, pay, send or delete. These are the tools the guard should check. Tools that only read can run without a check.
Our shop has one tool of each kind:
orders = {"A1": {"customer": "ann", "paid": 50.0, "refunded": 0.0}}
def lookup_order(order_id: str) -> dict:
"""Read an order. It changes nothing."""
return dict(orders[order_id])
def refund(order_id: str, amount: float) -> str:
"""Refund money. It changes the order, so the guard checks it."""
orders[order_id]["refunded"] += amount
return f"refunded ${amount:.2f} on order {order_id}"
Step 2: write the rules
A policy is the set of rules. guarded names the tools that the guard checks.
A rule is a plain function. It gets the proposed call and what the guard knows so far (the trace). It returns nothing when the call is fine. It returns a short message when the call breaks the rule.
from causalrepair import Guard, Policy, argument_bounds, require_confirmation
policy = Policy(guarded={"refund"})
policy.add(require_confirmation()) # the user must say "yes" first
policy.add(argument_bounds("refund", "amount", low=0.01)) # the amount must be positive
@policy.rule(tools={"refund"}, category="eligibility")
def not_more_than_paid(call, trace):
order = orders.get(call.args["order_id"])
if order is None:
return "there is no such order."
left = order["paid"] - order["refunded"]
if call.args["amount"] > left:
return f"only ${left:.2f} is left to refund."
The rules are hard rules. In every mode except off, the guard never runs a call that breaks one of them. (off runs everything; it is only for measuring how the agent does with no guard. A repaired call is checked again before it runs, unless you turn that off with Policy(recheck_repairs=False).) See Write a policy for all the ways to write rules.
Step 3: make a guard and a session
The guard holds the settings. A session is one conversation. Start a new session for each conversation.
session.tools(...) wraps your tool functions. A wrapped tool looks and works like the original one, but every call goes through the guard first.
guard = Guard(policy, mode="nearest") # "nearest" is the default; it needs no data
session = guard.session()
tools = session.tools([lookup_order, refund])
Step 4: tell the guard what the user says
The guard must see the user’s messages. For example, require_confirmation looks for a “yes” in the latest user message. Call session.user(text) for every user message.
session.user("Hi, order A1 came broken. Please refund it.")
print(tools["lookup_order"](order_id="A1")) # not guarded: it runs at once
print(tools["refund"](order_id="A1", amount=50.0))
It prints:
{'customer': 'ann', 'paid': 50.0, 'refunded': 0.0}
GUARD: not executed. Before calling refund, list the exact action details to the user and obtain an explicit 'yes'. Then you may call the tool again.
The refund did not run. The agent gets the message in its place and should now ask the user for a “yes”.
session.user("Yes, refund $50 please.")
print(tools["refund"](order_id="A1", amount=50.0))
print(tools["refund"](order_id="A1", amount=50.0)) # the same refund again
It prints:
refunded $50.00 on order A1
GUARD: not executed. The call violates policy:
- [not_more_than_paid] only $0.00 is left to refund.
Step 5: give the answer back to the agent
A wrapped tool returns one of two things:
- the tool’s real result, when the call ran;
- a message from the guard, when the call did not run.
In both cases, give the value back to the model as the tool’s result, in the same way you give any tool result. The model can then read the message and act on it. You do not need to handle the two cases in different ways.
Step 6: see what the guard decided
session.records keeps one record for each checked call:
for r in session.records:
print(r["tool"], r["args"], "->", r["chosen"])
It prints:
refund {'order_id': 'A1', 'amount': 50.0} -> confirm_first
refund {'order_id': 'A1', 'amount': 50.0} -> execute
refund {'order_id': 'A1', 'amount': 50.0} -> rule_feedback
confirm_first, execute and rule_feedback are the guard’s options. How it works explains each one. The read-only lookup_order call has no record, because it is not guarded.
One rule to remember
Every tool call must go through the session. A call that skips the session is not checked, and nothing the guard promises holds for it.
Next steps
- Connect your agent: use the guard with an OpenAI-style or Anthropic model, with async tools, or with a framework that runs the tools itself.
- Write a policy: more kinds of rules, and rules that fix the call for you.
- Examples: five complete programs you can run.