API reference
Everything below can be imported from causalrepair, except where a module name is given (causalrepair.adapters, causalrepair.certify, causalrepair.interventions).
Guard
Guard(policy, mode="nearest", *, artifact=None, rule="risk", verify=None, verify_source="", domain=None,
tool_class=None, stratify=None, once=None, extra=(), options=None, design=logging_design, chooser=None,
vetoes=(), message=None, log=None, is_unknown=is_timeout, unknown_message=..., seed=None)
The settings shared by all conversations.
| argument | meaning |
|---|---|
policy | the rules (Policy) |
mode | "off", "block", "feedback", "nearest", "collect" or "learned" (Choose a mode) |
artifact | a fitted Artifact; needed for mode="learned" |
rule | how a learned guard picks: "risk" or "matched" |
verify | verify(call, session) -> str or None: a trusted read for the verify_first option |
verify_source | the name of that read, or verify_source(call) -> str |
domain | a first part of every situation label |
tool_class | tool_class(call) -> str or None: an extra part of the label |
stratify | stratify(call, violations, session) -> str: your own label |
once | options offered at most once per tool and episode (names, or one comma-separated string) |
extra | your own Intervention options |
options | the built-in options this guard may use |
design | design(menu, violations) -> {option: chance} for mode="collect" |
chooser | chooser(stratum, menu, violations, session[, call]) -> option: replaces the mode’s pick |
vetoes | your own checks: veto(call, decision, session) -> None, Veto or str |
message | message(decision, session) -> content or None: what the agent sees for a call that does not run |
log | a JSON-lines file; every finished episode is added to it |
is_unknown | is_unknown(exception_or_result) -> bool: when a result counts as unknown (default: a TimeoutError, including asyncio’s on Python 3.10). A call interrupted while it runs (cancelled, KeyboardInterrupt) is also recorded as unknown, and the interruption is raised again |
unknown_message | what the agent sees after an exception that counts as unknown |
seed | the seed of the random picks in mode="collect" |
Methods and attributes:
guard.session(episode_id=None, domain=None, **context) -> Session: start one conversation.contextholds facts from your application (rules read them astrace.context).guard.episodes: the episodes finished so far (a list of dicts).MODES: the tuple of mode names.
Session
One conversation. Get it from guard.session(...).
| method | what it does |
|---|---|
user(text) | record a user message (trusted) |
assistant(text) | record an agent message (kept, never taken as a fact) |
tools(fns) | wrap functions (a list, or a dict of name to function) so every call goes through the guard |
run(call, fn, args=None) -> Reply | check the call; if it may run, call fn(**arguments) |
await arun(call, fn, args=None) -> Reply | the same, for an async tool |
call(call, execute, args=None, *, raise_errors=False) -> Reply | check the call; if it may run, call execute(call) |
await acall(call, execute, args=None, *, raise_errors=False) -> Reply | the same, with an executor that may be async |
review(call, args=None) -> Decision | decide, without running anything |
observe(call, result, status="ok", args=None) | report a call that ran outside the session, with status "ok", "error" or "unknown" |
finish(harm, success, **info) -> dict | close the episode with its outcome (each between 0 and 1) and return its record |
call can be a ToolCall, or a tool name together with args.
Attributes: session.trace (a Trace), session.context (the facts dict), session.records (one record per checked call), session.last (the last Decision), session.id, session.domain.
Each record in session.records is a dict with: tool, args, violations, stratum, menu, target_menu (the menu after the once limit), nearest, chosen, propensity (the chance of the pick), executed, executed_args, executed_violation, reason, index.
The dict that finish returns (and writes to the log) has: id, domain, decisions (the records), harm, success, safe_completion, mode, and anything you passed as info.
Reply
What a guarded call returns: Reply(content, decision, status).
content: what the agent should see;decision: theDecision;status:"ok","error","unknown", or"blocked"(the guard did not run the call).
Decision
What the guard decided about one call.
| field | meaning |
|---|---|
intervention | the option picked |
allowed | True if the call runs |
call | the call to run (with fixed arguments after arg_repair) |
proposed | the call the agent proposed |
message | what the agent sees when the call does not run |
violations | the broken rules (Violation objects) |
stratum | the situation label |
menu | the options that were allowed |
nearest | the nearest repair |
propensity | the chance of the pick (1 outside collect) |
reason | why it was picked (for example the mode, "custom", or a veto’s reason) |
log | the decision’s record (a veto may add fields to it) |
decision.record() returns a JSON-ready record.
Policy and rules
Policy(rules=(), guarded=None, *, recheck_repairs=True)
guarded: the tool names to check (None: every tool).recheck_repairs: check a fixed call again before it runs (defaultTrue).policy.rule(tools=None, *, name=None, category="other", suggests=None): a decorator that adds a rule function.policy.add(*rules) -> Policy: addRuleobjects (it returns the policy).policy.check(call, trace) -> list[Violation]: all broken rules of a call (empty: the call is fine).policy.repair(call, violations) -> dict or None: the fixed arguments, orNone. Override it for fixes that replace the whole argument list.policy.is_guarded(call) -> bool.
Rule(name, fn, tools=None, category="other", suggests=None)
A rule object. fn(call, trace) returns None or True (pass), a string or False (broken), a Violation, or a list of these. suggests is a note that is kept in the violation record.
Violation(rule, message, category="other", repair=None, guidance="", suggests=None)
One broken rule. repair is a dict of fixed arguments, or None. guidance is an optional next step shown to the agent.
Built-in rules
| function | rule |
|---|---|
require_confirmation(tools=None, pattern=AFFIRM) | the latest user message must say “yes” and not take it back (category confirmation) |
argument_bounds(tool, arg, *, low=None, high=None, clip=False, name=None) | a number argument must lie in [low, high]; clip=True offers the clipped value as a fix |
forbid(tools, message="this tool may not be used here.", name="forbidden") | these tools are never allowed (they must also be guarded) |
must_match_request(extract, tools, keys, name="requested_only") | the call must match a request found by extract(trace) in the user’s messages, on these argument keys |
no_repeat_after_success(tools, target=<same call>, name="no_repeat") | no repeat of a call to the same target that already succeeded |
Basic types
ToolCall(name, args={}, id=None)
A proposed tool call. call.with_args(args) gives the same call with new arguments. call.key() is a stable text id of the call.
ToolResult(content, status="ok")
Return it from an executor to set the status yourself: "ok", "error" or "unknown".
Veto(message, name="veto", reason=None)
Return it from a veto to stop a call. The agent sees message. The record shows name as the chosen option.
Trace(events=(), context=None)
What the guard knows. Methods: user_texts(), last_user_text(), user_affirmed(pattern=AFFIRM), calls(name=None), results(name=None), last_status(name), guard_decisions(). Attributes: events, context.
Event(kind, content=None, call=None, status="ok")
One entry of the trace. kind is "user", "assistant", "call", "result" or "guard".
Options (causalrepair.interventions)
Intervention(name, distance, message, available=<when a rule is broken>)
Your own option. message(call, violations, session) returns the text the agent sees. available(call, violations) says when it is on the menu.
The built-in names are EXECUTE, ARG_REPAIR, CONFIRM, VERIFY, FEEDBACK and DENY ("execute", "arg_repair", "confirm_first", "verify_first", "rule_feedback", "generic_deny"). DISTANCE maps each name to its distance, and ORDER lists them in order.
| function | what it does |
|---|---|
menu(call, violations, *, can_verify=True, can_repair=None, extra=(), options=None) | the allowed options for a call |
nearest_repair(menu, vclass) | the nearest repair for a menu and a violation class |
violation_class(violations) | the violation class: none, confirm_only, repairable_arg, identity, … |
logging_design(menu, violations, no_violation=None) | the default chances of collect mode |
repaired_args(violations, args) | the arguments with every fix applied, or None |
Learning (Artifact)
Artifact.fit(episodes, *, per_domain=False, min_n=8, iters=4, pooled=None, boot=0, seed=0,
dist=DISTANCE, order=ORDER, nearest=<the nearest repair>) -> Artifact
Fit a learned guard. episodes is a list of episode dicts (such as guard.episodes), or log files and folders. dist and order give the distance and the place of each option; add your own options to both if the logs contain them. See Learn from logs.
art.save(path)andArtifact.load(path): write and read the fitted guard (JSON).art.choose(stratum, menu, rule="risk") -> (option, reason): the learned pick.art.limit_for(stratum) -> float: the harm limit used in that situation.art.table: for each situation and option,harm_hat,F_hat(predicted safe completion),n(logged decisions) andsource.art.table_matchedis the same for the matched-harm rule.art.meta: details of the fit, such aslimit,min_n,choicesandepisodes.
load_episodes(*paths) -> list[dict] reads episodes from JSON-lines files, JSON files or folders.
Chat formats (causalrepair.adapters)
| function | what it does |
|---|---|
sync(session, messages) | add the user and assistant text turns that the session has not seen yet |
from_openai(tool_call) -> ToolCall | convert an OpenAI-style tool call |
tool_message(tool_call, reply) -> dict | the tool message that answers it |
tool_uses(message) -> list | the tool_use blocks of an Anthropic message or response |
from_anthropic(block) -> ToolCall | convert a tool_use block |
tool_result(block, reply) -> dict | the tool_result block that answers it (is_error on failures and timeouts) |
text_of(content) -> str | the text of a message’s content |
They accept plain dicts and the official SDK objects.
Certified plans (causalrepair.certify)
FiniteModel(states, actions, horizon, successors, harm)
The environment: successors(t, state, action) lists the possible next states, and harm(state) is a number in [0, 1] for a final state.
Evidence.collect(model, sample, n, rng, inputs=None, beta=0.05, method="clopper_pearson")
Evidence.from_draws(model, draws, beta=0.05, method="clopper_pearson")
Bounds on every next-state chance from n draws per input (sample(t, state, action, rng) -> next state), or from draws you already have. All bounds hold together with chance at least 1 - beta. method is "clopper_pearson" or "hoeffding". ev.interval(t, state, action) gives the bounds of one input.
Plan(name, first, then=None, distance=0.0, eligible=True)
A plan: a first action and a rule then(t, state) -> action (or a dict of action to chance) for later steps.
certify(ev, plans, t, state, limit) -> Certificate
Bound every plan and pick the closest certified one. Certificate has selected, statuses (each a Verdict: CERTIFIED, EXCEEDS, UNRESOLVED, POLICY_REJECTED), bounds (each Bounds(lower, upper, supported)), true_minimum, limit, beta, reason and order.
plan_bounds(ev, plan, t, state) -> Bounds: the bounds of one plan.policy_ok(model, plan, t, state, allowed) -> bool:Trueif every action the plan can take passesallowed(t, state, action).
BudgetPlanner(ev, allowed=None)
Keep a risk budget while the agent replans. Methods: min_budget(t, state), admissible(t, state, budget), and split(t, state, action, budget) (the budget for each next state). See Certified plans.