Skip to content

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

Agent WorkflowsHow-to guideIntermediate level

How to Add a Human Approval Step Before Your AI Agent Takes Action in Python

Put a checkpoint in front of every risky tool call so a person approves the exact action before it runs. You build it in plain Python with a policy, a hashed proposal, a reviewer prompt, a one-time executor and an audit log.

Pankaj Nigam

Technical Writer

Published
  • 25 min to complete
  • 0 sec

Tested with
  • Python
Your progress
  1. How to Add a Human Approval Step Before Your AI Agent Takes Action in Python6 min(finished)
    0%

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.

Agent proposesactionTool broker:policy checkReviewer seesaction anddecidesDigest matches?Tool runsTool runs onceNeeds approvalRead-onlyAudit log
The broker gates risky actions and records every stage.

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.

python
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.

python
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.

python
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.

python
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.

python
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.

python
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))
bash
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.

bash
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

Finished this article?

How did this strike you?

Be the first to react – it is anonymous.

Community

Questions about this?

Ask in Questions and help and get help from other readers.

Ask a questionBrowse Questions and help

Comments

No comments yet. Share what worked for you, or ask a question.

Keep learning

Picked for this article

Related reading, discussions and learning paths on the same subject.

All in Agent Workflows

Learning paths

Learning pathBeginner

From numbers to decisions

Read an experiment honestly, judge a classifier fairly and show the result clearly: p-values, an A/B test worked end to end, classification metrics, chart choice and dashboards.

5 lessonsabout 25 minStart

Choose what we may use. You can change this at any time with “Privacy choices” at the foot of every page. Details are in the Cookie policy and the Privacy policy.

Strictly necessary

Remembers your theme, the lessons you marked as done and this choice. It stays on your device, tracks nothing and cannot be switched off.

Always on
What exactly is collected, and why

Google Analytics

Collects
The pages you view, your device and browser type, your language, how you reached the site and your approximate location (country and city, worked out from your IP address).
Why
To understand which pages and lessons are used, so we can improve them.
Stored
Two cookies, _ga and _ga_<id>, for up to 2 years. Google acts for us; the data is processed by Google, including outside your country.

Grokem’s own counts

Collects
The pages you open and how long you stay, how far you scroll, where you came from, your device type, browser, screen size, language and time zone. Your IP address is turned into a code that changes every day; it is never stored as it is.
Why
To see how long lessons are read and where readers leave. Not shared with anyone.
Stored
A random visitor ID, a visit ID and the time of your last page view in your browser’s storage (gr_vid, gr_sid, gr_last). No name or email is attached.