Learn from logs

Sometimes several options are allowed, but one is much safer than the others. For example, after a payment times out, a retry is allowed by the rules, but it charges the customer twice if the first payment went through. Showing the agent the payment record first is safer.

The nearest repair cannot know this. A learned guard can: it learns from logs which option leads to less harm. It always picks from the menu, so it never runs a call that breaks a rule.

It takes three steps:

  1. Collect. Run your agent with mode="collect". After each checked call, the guard picks an allowed option at random and writes down the exact chance of that pick.
  2. Fit. Artifact.fit(...) reads the logs and estimates the harm and safe completion that follow each option in each situation. You save the result to a file.
  3. Deploy. Load the file into a guard with mode="learned". Test it on new tasks before you trust it.

A full example

A checkout agent takes a payment. Sometimes the payment gateway times out and does not say if the charge went through (it did, half of the time). The agent then retries. Harm means the customer was charged twice.

A small simulated agent stands in for a language model here. With a real model, keep the guard code as it is.

import json

import numpy as np

from causalrepair import Artifact, Guard, Policy, require_confirmation

rng = np.random.default_rng(0)


class Gateway:
    """The payment backend. The agent cannot see if a timed-out charge went through."""

    def __init__(self):
        self.charges = 0
        self.first = True

    def capture(self, order: str, amount: float):
        if self.first and rng.random() < 0.4:            # this attempt times out
            self.first = False
            if rng.random() < 0.5:                        # ... but the charge went through
                self.charges += 1
            raise TimeoutError
        self.first = False
        self.charges += 1
        return {"status": "captured", "order": order}

    def record(self, order: str) -> str:                  # a trusted read of the order's payments
        return json.dumps({"order": order, "captures": self.charges})


def read_record(call, session):
    """The "verify first" option shows the agent this trusted record."""
    return session.context["gateway"].record(call.args["order"])


def run_episode(guard):
    gw = Gateway()
    s = guard.session(gateway=gw)
    tools = s.tools({"capture_payment": gw.capture})
    s.user("Please place the order and charge my card, yes.")
    for _ in range(4):                                     # the agent's turns (a stand-in for a model)
        out = str(tools["capture_payment"](order="A1", amount=30.0))
        if "captured" in out or '"captures": 1' in out:    # done, or the record shows it already went through
            break
        if "explicit 'yes'" in out:
            s.user("Yes.")                                 # the user confirms again
    harm = float(gw.charges > 1)                           # charged twice
    return s.finish(harm=harm, success=float(gw.charges >= 1))


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

Step 1: collect. Each episode ends with session.finish(harm=..., success=...). You must measure harm and success yourself, for example by checking the database at the end.

collector = Guard(policy, mode="collect", verify=read_record, seed=1)
for _ in range(1500):
    run_episode(collector)
print(len(collector.episodes), "episodes collected")

It prints:

1500 episodes collected

Step 2: fit and save.

art = Artifact.fit(collector.episodes)
art.save("payment_guard.json")

cell = art.table["after_unknown|none"]                     # the situation right after a timeout
print({option: round(v["harm_hat"], 3) for option, v in cell.items()}, "limit", round(art.meta["limit"], 3))

It prints:

{'execute': 0.478, 'confirm_first': 0.436, 'verify_first': 0.215} limit 0.193

After a timeout, a plain retry (execute) is predicted to cause harm 0.478 of the time. Showing the record first (verify_first) is much safer.

Step 3: deploy and compare on new episodes:

for mode in ("nearest", "learned"):
    g = Guard(policy, mode=mode, artifact=Artifact.load("payment_guard.json"), verify=read_record)
    episodes = [run_episode(g) for _ in range(2000)]
    print(f"{mode:8s} harm {np.mean([e['harm'] for e in episodes]):.3f}   "
          f"safe completion {np.mean([e['safe_completion'] for e in episodes]):.3f}")

It prints:

nearest  harm 0.195   safe completion 0.805
learned  harm 0.000   safe completion 0.802

The learned guard shows the agent the payment record after a timeout, and the double charges stop.

Collect from many processes

Give the collecting guard a log file. Each finished episode is added to it as one line of JSON. Use one file for each process, then fit on the whole folder:

collector = Guard(policy, mode="collect", verify=read_record, seed=worker_id, log=f"logs/worker-{worker_id}.jsonl")
...
art = Artifact.fit("logs/")                    # reads every .jsonl and .json file under the folder

load_episodes(...) reads the same files if you want to look at them yourself.

How the learned guard picks

The fit gives each situation and each option two numbers: the predicted harm (harm_hat) and the predicted safe completion (F_hat). One file holds two ways to pick:

  • Risk-limited (rule="risk", the default). The limit is the harm that the nearest repair is predicted to have on average. The guard takes the closest option whose predicted harm is within the limit. If none is within the limit, it takes the option with the lowest predicted harm.
  • Matched-harm (rule="matched"). The guard stays as close as the nearest repair. Among the options at that distance that are predicted no more harmful than the nearest repair, it takes the one with the best predicted safe completion.

An option needs at least min_n logged decisions (default 8) in a situation before the guard uses its numbers; options with fewer are skipped. When no option on the menu has enough, the guard uses the nearest repair.

Options of the fit

option meaning
per_domain=True one harm limit for each domain (set Guard(domain=...) when you collect)
min_n=8 the fewest logged decisions an option needs in a situation
pooled=other_artifact a fit on a larger set of logs, used where your own logs are too thin
boot=200 also store one-sided 95% bootstrap bounds: harm_upper and F_lower

To see what the risk-limited rule will do in each situation, read art.meta["choices"]. For the matched-harm rule, read art.meta["matched"]["choices"].

Good practice

  • Collect with the settings you will deploy: the same policy, the same trusted read (verify=), the same once= and options=.
  • Fit once, then freeze the file. Never fit again on the tasks you test on.
  • Test on new tasks. The numbers are estimates over coarse situations, not a proof. Compare the learned guard with nearest on tasks the fit has not seen before you trust it.
  • Collection also tries other options when no rule is broken (most often it runs the call). This costs a little during collection, and it is what lets the fit learn about those cases.

If you need a proven risk limit instead of an estimate, and you can reset your environment, see Certified plans.