Before you start
4- Python 3 installed and a terminal you can run scripts in
- An agent, or any code, that chooses a tool name and arguments before acting
- A list of the tools your agent can call and which of them change something outside the agent (send, write, delete, pay)
- A named person or role who can decide for each risky tool
An agent that only answers questions can be wrong without harm. An agent that can send, change or delete things needs a gate between "the model decided" and "the action happened".
This guide builds that gate as a small approval layer in plain Python. It follows four design points that approval-checkpoint guidance repeats: place the checkpoint before the action, show the action in terms a reviewer can check, bind the decision to the exact proposal, and handle retries.
The code uses only the Python standard library and your own function names. It is not tied to any agent framework. If your framework has built-in approval or interrupt features, the exact names and settings are not given here: check that framework's official documentation and map the same four points onto it.
The layer sits between the agent and its tools, which is often called a tool broker. The agent never calls a risky tool directly. It asks the broker, and the broker decides whether a person must approve first.
Step 1 of 7: Decide which actions need approval
List every tool the agent can call. Mark each one as read-only or as an action with side effects, and name the person or role who owns the decision.
This matters because approval on everything trains reviewers to click through, and approval on nothing leaves risky actions open. Scope, risk and impact, and decision owners are the first things approval-threshold checklists ask you to define.
Start strict: any tool missing from the policy requires approval. Create approval_gate.py and add the imports and policy. You will append the later blocks to the same file, in order.
import hashlib
import json
import time
import uuid
AUDIT_FILE = "audit.jsonl"
POLICY = {
"search_docs": {"approval": False, "owner": None},
"send_email": {"approval": True, "owner": "support-lead"},
}
# Unknown tools are treated as risky.
DEFAULT_RULE = {"approval": True, "owner": None}
Step 2 of 7: Write an audit record for every event
Add one function that appends a JSON line per event. Each record gets a timestamp and a proposal id.
You do this first so that every later step can call it. An audit trail needs clear references, a rationale and timestamps to be useful when someone asks why the agent did something.
def audit(event, **fields):
record = {"event": event, "ts": time.time(), **fields}
with open(AUDIT_FILE, "a", encoding="utf-8") as f:
f.write(json.dumps(record, sort_keys=True) + "\n")
Step 3 of 7: Turn the intended action into a hashed proposal
Build a proposal that holds the tool, the exact arguments and the agent's stated reason. Compute a SHA-256 digest over those three fields.
The digest is what lets you bind the decision to the proposal. If anything changes after review, the digest no longer matches and the action does not run.
def digest_of(tool, args, reason):
body = {"tool": tool, "args": args, "reason": reason}
return hashlib.sha256(
json.dumps(body, sort_keys=True).encode("utf-8")
).hexdigest()
def propose(tool, args, reason):
proposal = {
"id": str(uuid.uuid4()),
"tool": tool,
"args": args,
"reason": reason,
"digest": digest_of(tool, args, reason),
}
audit(
"proposed",
proposal_id=proposal["id"],
digest=proposal["digest"],
tool=tool,
args=args,
reason=reason,
)
return proposal
Step 4 of 7: Show the reviewer the real action and capture a rationale
Print the tool name, the literal arguments and the agent's reason. Ask for a yes or no and a short rationale.
Show the concrete values, such as the recipient and the message body, not a summary like "send follow-up". A reviewer can only check what they can see. The default answer is no, so an empty reply never approves anything.
def review(proposal):
print("--- Approval needed ---")
print("Action :", proposal["tool"])
print("Details:", json.dumps(proposal["args"], indent=2))
print("Why :", proposal["reason"])
answer = input("Approve? [y/N] ").strip().lower()
rationale = input("Reason for your decision: ").strip()
decision = {
"proposal_id": proposal["id"],
"digest": proposal["digest"],
"approved": answer == "y",
"rationale": rationale,
}
audit("decided", **decision)
return decision
Step 5 of 7: Gate execution on a matching decision and run each proposal once
Write the broker's run function. It recomputes the digest, requires an approved decision with the same digest when the policy says so, and refuses to run a proposal id twice.
The recomputed digest stops an edited proposal from riding on an old approval. The executed set makes retries safe: if the agent or your queue repeats the call, the side effect does not happen again.
TOOLS = {
"search_docs": lambda args: "results for " + args["query"],
"send_email": lambda args: "email sent to " + args["to"],
}
EXECUTED = set()
def run(proposal, decision=None):
rule = POLICY.get(proposal["tool"], DEFAULT_RULE)
current = digest_of(proposal["tool"], proposal["args"], proposal["reason"])
if rule["approval"]:
valid = (
decision is not None
and decision["approved"]
and decision["digest"] == current
and decision["proposal_id"] == proposal["id"]
)
if not valid:
audit("blocked", proposal_id=proposal["id"], owner=rule["owner"])
return "blocked"
if proposal["id"] in EXECUTED:
audit("duplicate_ignored", proposal_id=proposal["id"])
return "already executed"
result = TOOLS[proposal["tool"]](proposal["args"])
EXECUTED.add(proposal["id"])
audit("executed", proposal_id=proposal["id"], result=result)
return result
Step 6 of 7: Route the agent's tool call through the broker and test it
Replace the direct tool call in your agent with propose, then review when the policy requires it, then run. The block below simulates one agent call and a repeated call.
Testing the retry in the same run proves the gate holds when the same proposal arrives twice. Run the file with python approval_gate.py.
if __name__ == "__main__":
proposal = propose(
"send_email",
{"to": "customer@example.com", "body": "Your refund has been issued."},
"Customer asked about a refund and the ticket is resolved.",
)
rule = POLICY.get(proposal["tool"], DEFAULT_RULE)
decision = review(proposal) if rule["approval"] else None
print("First call :", run(proposal, decision))
print("Retry :", run(proposal, decision))
python approval_gate.py
Step 7 of 7: Read the audit file to confirm the trail
Open audit.jsonl and check that each proposal shows proposed, decided and executed events with the same proposal id.
This confirms that a later reviewer can trace what was proposed, who decided and why, and what ran.
cat audit.jsonl
Expected result
When you answer y at the prompt, the terminal shows the action details and then: First call : email sent to customer@example.com Retry : already executed audit.jsonl contains these events for the proposal id, in order: proposed, decided, executed, duplicate_ignored. If you answer n or press Enter, the first call prints "blocked" and the file contains proposed, decided and blocked. Timestamps in the file are Unix seconds.
Frequently asked questions
Where should the approval checkpoint go?
Before the action, not after. Once the email is sent or the record is deleted, a review can only report the damage.
What should the reviewer see?
The action in terms they can check: the tool, the literal arguments and the agent's reason. Summaries hide the details that matter.
Why bind the decision to the proposal?
So an approval covers one specific action. If the arguments change afterwards, the digest differs and the approval no longer applies.
How do I handle retries?
Give each proposal an id and record when it has executed. A repeated call with the same id is ignored instead of running the side effect again.
What should I log?
A reference to the proposal, the decision, the rationale and timestamps, so the trail explains what happened and why.
Does every tool call need approval?
No. Set thresholds from the agent's scope, the risk and impact of each action, and the decision owner. Read-only tools can usually skip the gate.
From Grokem: https://www.grokem.com/ai-and-machine-learning/ai-agents/agent-workflows/how-to-add-a-human-approval-step-before-your-ai-agent-takes-action-in-python






