Skip to content

Human-in-the-Loop

RestrictTools can hold a tool call until someone approves it. List the tools in require_approval and pass an approval callback. The callback receives the tool name and its arguments, can be sync or async, and returns True to allow the call.

from pydantic_ai import Agent
from pydantic_ai_guardrails import RestrictTools
def approve_in_terminal(tool_name: str, args: dict) -> bool:
print(f'The agent wants to call {tool_name} with {args}')
return input('Approve? [y/N] ').strip().lower() == 'y'
agent = Agent(
'openai:gpt-4o',
capabilities=[
RestrictTools(require_approval=['send_email', 'refund_*'], approval=approve_in_terminal),
],
)
@agent.tool_plain
def send_email(to: str, subject: str, body: str) -> str:
return f'Email sent to {to}'
@agent.tool_plain
def refund_order(order_id: str, amount: float) -> str:
return f'Refunded {amount} on {order_id}'
result = agent.run_sync('Refund order 1234 for 20 dollars and email the customer at a@b.com')
print(result.output)
Decision Result
approval returns True The tool runs with the original arguments
approval returns False ModelRetry: the model is told the call was not approved and can try another approach or explain to the user
No approval callback configured ToolDenied stops the run, so a gated tool only ever runs with approval

The callback can be async, so it can wait on Slack, a web UI or a ticket queue:

import asyncio
from pydantic_ai_guardrails import RestrictTools
pending: dict[str, asyncio.Future[bool]] = {}
async def notify_reviewers(request_id: str, tool_name: str, args: dict) -> None:
"""Post the request to Slack, email or your review UI."""
print(f'[{request_id}] approval needed for {tool_name}({args})')
async def approve_via_queue(tool_name: str, args: dict) -> bool:
request_id = f'{tool_name}-{id(args)}'
future: asyncio.Future[bool] = asyncio.get_running_loop().create_future()
pending[request_id] = future
await notify_reviewers(request_id, tool_name, args)
try:
return await asyncio.wait_for(future, timeout=300)
except asyncio.TimeoutError:
return False # no answer in 5 minutes = denied
finally:
pending.pop(request_id, None)
def on_reviewer_decision(request_id: str, approved: bool) -> None:
if future := pending.get(request_id):
future.set_result(approved)
guard = RestrictTools(require_approval=['deploy_*'], approval=approve_via_queue)

Keep long waits in mind: the agent run stays open while the callback waits.

from pydantic_ai_guardrails import RestrictTools
RestrictTools(
allowed=['search_*', 'send_email', 'refund_*'], # hide everything else
blocked=['refund_all'], # never, even if allowed matches
require_approval=['refund_*'],
approval=lambda name, args: args['amount'] < 100, # auto-approve small refunds only
)

approval and other callables cannot go in a config file, so a RestrictTools with approval is built in code.

See RestrictTools for the full parameter list.