Connect your agent
The guard must see every tool call before it runs. This page shows four ways to send calls through the guard, how to pass the conversation to it, and how to use it with OpenAI-style and Anthropic models.
Pick a way
| how your agent runs tools | use |
|---|---|
| it calls Python functions | Way 1: tools = session.tools([...]) |
| you have the function for each call | Way 2: reply = session.run(call, fn) |
| a framework, SDK or MCP client runs the tool | Way 3: reply = session.call(call, execute) |
| you need full control | Way 4: session.review(call), then session.observe(...) |
All four ways work the same inside the guard. Pick the one that fits your code.
Way 1: wrap your functions
from causalrepair import Guard, Policy, ToolCall, ToolResult, require_confirmation
def get_balance(account: str) -> str:
return "balance: $120"
def send_payment(account: str, amount: float) -> str:
return f"sent ${amount:.2f} from {account}"
policy = Policy(guarded={"send_payment"}).add(require_confirmation())
guard = Guard(policy)
session = guard.session()
tools = session.tools([get_balance, send_payment]) # or a dict: {"name": function}
session.user("Send $20 from my account, yes please.")
print(tools["send_payment"](account="main", amount=20))
It prints:
sent $20.00 from main
A wrapped tool keeps the function’s name, docstring and signature, so frameworks that read them still work. It accepts positional arguments too. If the function is async def, the wrapped tool is async as well.
A wrapped tool returns only the content: the tool’s result, or the guard’s message. To also get the status and the decision, use Way 2.
Way 2: run one call
session.run(call, fn) checks the call and, if it may run, calls fn(**arguments). It returns a Reply:
| field | meaning |
|---|---|
reply.content | what the agent should see: the result, or the guard’s message |
reply.status | "ok", "error", "unknown", or "blocked" (the guard did not run the call) |
reply.decision | the guard’s full decision (the option it picked, the broken rules, …) |
reply = session.run(ToolCall("send_payment", {"account": "main", "amount": 5}), send_payment)
print(reply.status, "|", reply.content, "|", reply.decision.intervention)
It prints:
ok | sent $5.00 from main | execute
Way 3: let your framework run the tool
Many frameworks run the tools themselves. Then give the guard a small execute(call) function that asks your framework to run the call. The guard calls it only when the call may run.
execute gets the call to run. Use its arguments: after an argument fix, they differ from what the agent proposed. Return the result. To report a failure yourself, return ToolResult(content, status) with status "error" or "unknown".
def execute(call): # how your framework runs a tool
if call.args["amount"] > 1000:
return ToolResult("the bank said no", status="error")
if call.args.get("slow"):
raise TimeoutError("the bank did not answer")
return f"sent ${call.args['amount']:.2f}"
for args in ({"amount": 20}, {"amount": 5000}, {"amount": 20, "slow": True}):
reply = session.call(ToolCall("send_payment", args), execute)
print(reply.status, "|", reply.content)
It prints:
ok | sent $20.00
error | the bank said no
unknown | Error: the request timed out. The server did not confirm whether the operation was applied.
What the guard does with errors:
- any exception counts as an
error, and the agent seesError: <the message>; - a
TimeoutErrorcounts asunknown: the call may or may not have taken effect; - with
session.call(..., raise_errors=True), the guard records the failure and then raises the exception again, so your framework’s own error handling still runs.
After an unknown result, the next call to the same tool has after_unknown in its situation label. A learned guard can treat that case in its own way (for example, check before it retries). To decide yourself what counts as unknown, pass Guard(is_unknown=...) (More options).
Way 4: review, then report
For full control, split the two steps yourself:
d = session.review(call)decides. Nothing runs.- If
d.allowedis true, rund.call(it may have fixed arguments) and report the result withsession.observe(d.call, result, status). - If not, give
d.messageto the agent in place of the result.
d = session.review(ToolCall("send_payment", {"account": "main", "amount": 7}))
if d.allowed:
result = send_payment(**d.call.args) # run it in your own way
session.observe(d.call, result, "ok")
else:
result = d.message
print(result)
It prints:
sent $7.00 from main
Always report a call that ran with observe. The guard needs the result to judge later calls.
Tell the guard what the user says
Rules such as require_confirmation read the user’s messages. Record each one:
session.user("Yes, pay the invoice.") # a user message: the guard trusts it
session.assistant("I will pay it now.") # an agent message: kept, but never taken as a fact
If your model uses a chat message list, adapters.sync(session, messages) does this for you. It adds the user and assistant turns that the session has not seen yet. It reads only text, so a tool result is never taken for something the user said.
OpenAI-style models
OpenAI, vLLM, LiteLLM and many other tools use this format. Three lines touch the guard:
from causalrepair.adapters import from_openai, sync, tool_message
session = guard.session() # 1. one session per conversation
while True:
msg = client.chat.completions.create(model=MODEL, messages=messages, tools=TOOL_SCHEMAS).choices[0].message
messages.append(msg)
sync(session, messages) # 2. the guard sees the user and agent turns
if not msg.tool_calls:
break
for tc in msg.tool_calls:
call = from_openai(tc)
reply = session.run(call, TOOLS[call.name]) # 3. every call goes through the guard
messages.append(tool_message(tc, reply))
from_openai turns a tool call (a dict or an SDK object) into a ToolCall. tool_message builds the tool message that answers it. examples/04_openai_style_agent.py runs this loop offline with a scripted model.
Anthropic models
The Anthropic Messages format uses tool_use and tool_result blocks:
from causalrepair.adapters import from_anthropic, sync, tool_result, tool_uses
session = guard.session()
while True:
response = client.messages.create(model=MODEL, max_tokens=1024, tools=TOOL_SCHEMAS, messages=messages)
messages.append({"role": "assistant", "content": response.content})
sync(session, messages)
if not tool_uses(response):
break
results = []
for block in tool_uses(response):
call = from_anthropic(block)
results.append(tool_result(block, session.run(call, TOOLS[call.name])))
messages.append({"role": "user", "content": results})
tool_result marks failed and timed-out calls with is_error. The adapters accept plain dicts and the official SDK objects. examples/05_anthropic_async_agent.py runs an async version offline.
Async tools
For async def tools, use the async forms:
| sync | async |
|---|---|
session.run(call, fn) | await session.arun(call, fn) |
session.call(call, execute) | await session.acall(call, execute) |
session.tools([...]) | the same: async functions give async wrappers |
import asyncio
async def send_payment_async(account: str, amount: float) -> str:
await asyncio.sleep(0) # a network call in a real system
return f"sent ${amount:.2f} from {account}"
async def main():
s = guard.session()
s.user("Pay $3 from main, go ahead.")
reply = await s.arun(ToolCall("send_payment", {"account": "main", "amount": 3}), send_payment_async)
print(reply.status, "|", reply.content)
asyncio.run(main())
It prints:
ok | sent $3.00 from main
Rules and trusted reads stay normal (not async) functions.
Many conversations
Make one guard and start one session for each conversation. Sessions do not share their history. Close a session with session.finish(harm=..., success=...) if you want to keep its log (Learn from logs).