Sub topic 4
Building an approval gate
An approval gate is a piece of code that stops an agent from running a tool call until a person has decided it may run. This chapter builds one. It assumes you can read short Python programs, know that an agent proposes tool calls and your code executes them, and understand that a call's risk level is a label you can look up. Earlier chapters covered the agent loop and how to classify actions. Later chapters cover saved state, timeouts, and binding an approval to an exact action. Here the goal is the core mechanism: pause, decide, resume.
What a gate is and where it lives
In a typical agent loop, the model returns a tool call such as send_email(to="[email protected]", body="..."). Your code runs that call, adds the result to the conversation, and asks the model for its next step. The gate is a function that sits between "the model proposed a call" and "the tool runs".
You can place a gate in three places.
| Location | How it works | Problem |
|---|---|---|
| In the prompt | You tell the model "ask before sending email" | The model can forget, misread, or be talked out of it. Nothing enforces the rule. |
| Inside each tool | Every tool function asks for approval itself | Easy to forget in one tool. Approval logic is duplicated and inconsistent. |
| In the executor | One function checks every call before dispatching it | One enforcement point. The model cannot skip it. |
Use the executor. The model only proposes calls, and your code decides whether a call runs. Prompt instructions are useful for behavior, but they are not a safety control.
The three parts of a gate
A gate does three things in order.
- Pause. Decide whether the call needs a human. If so, stop before executing anything.
- Decide. Show the call to a reviewer and get a structured decision back.
- Resume. Act on the decision. Either run the call, run a modified call, or skip it and tell the agent why.
Every path ends by returning something to the agent loop. A rejected call still produces a result, so the agent can react to it instead of hanging.
Step 1: Classify the call
The gate needs a fast answer to "does this call need a human?" The simplest implementation is a lookup table keyed by tool name.
from dataclasses import dataclass
@dataclass(frozen=True)
class ToolCall:
name: str
args: dict
RISK = {
"search_docs": "low",
"send_email": "high",
"delete_record": "high",
}
def risk_of(call: ToolCall) -> str:
# Unknown tools default to high risk, so new tools need approval until classified.
return RISK.get(call.name, "high")The important line is RISK.get(call.name, "high"). When a developer adds a new tool and forgets to classify it, the system asks for approval. The mistake costs a few extra prompts, not an unreviewed deletion. This is called failing closed.
A table keyed only by name is the minimum. Real systems often look at arguments too, for example treating a payment under a small limit differently from a large one. The chapter on policy rules covers that. Start with names.
Step 2: Write the gate
The gate takes the proposed call, a dictionary of tool functions, and a callable ask_human. Passing ask_human in as a parameter keeps the gate independent of how you collect decisions. In a terminal it can call input(). In a web app it can post to a review queue. In tests it can be a stub.
def run_step(call, tools, ask_human):
if risk_of(call) == "low":
return tools[call.name](**call.args)
decision = ask_human(call) # returns a dict such as {"action": "approve"}
action = decision.get("action")
if action == "approve":
return tools[call.name](**call.args)
if action == "edit":
edited = ToolCall(call.name, decision["args"])
return tools[edited.name](**edited.args)
if action == "reject":
return {"rejected": True, "reason": decision.get("reason", "")}
# Anything unrecognized is treated as a rejection, never as permission.
return {"rejected": True, "reason": "Unrecognized decision"}Three details matter here.
- The decision is data, not a boolean. A dictionary with an
actionfield can carry edited arguments or a rejection reason. A plainTrueorFalsecannot. The next chapter covers the decision types in detail. - Rejection returns a value instead of raising. The agent loop appends this result to the conversation, and the model reads the reason and can try another approach. If you raised an exception, the whole run would usually crash.
- Unknown actions are rejected. The last two lines make sure a malformed decision, such as a typo like
"aprove", cannot run the tool. Only the exact string"approve"or a valid"edit"reaches execution.
Step 3: Run it
Here is a complete program you can run. The tools are fake, and the reviewer is a function that approves anything addressed to an internal domain and rejects the rest.
from dataclasses import dataclass
@dataclass(frozen=True)
class ToolCall:
name: str
args: dict
RISK = {"search_docs": "low", "send_email": "high"}
def risk_of(call: ToolCall) -> str:
return RISK.get(call.name, "high")
def run_step(call, tools, ask_human):
if risk_of(call) == "low":
return tools[call.name](**call.args)
decision = ask_human(call)
action = decision.get("action")
if action == "approve":
return tools[call.name](**call.args)
if action == "edit":
edited = ToolCall(call.name, decision["args"])
return tools[edited.name](**edited.args)
if action == "reject":
return {"rejected": True, "reason": decision.get("reason", "")}
return {"rejected": True, "reason": "Unrecognized decision"}
tools = {
"search_docs": lambda query: f"3 results for {query!r}",
"send_email": lambda to, body: f"sent to {to}",
}
def ask_human(call):
print(f"Review requested: {call.name} {call.args}")
if call.args.get("to", "").endswith("@example.com"):
return {"action": "approve"}
return {"action": "reject", "reason": "External recipients are not allowed."}
calls = [
ToolCall("search_docs", {"query": "refund policy"}),
ToolCall("send_email", {"to": "[email protected]", "body": "Hello"}),
ToolCall("send_email", {"to": "[email protected]", "body": "Hello"}),
]
for call in calls:
print(run_step(call, tools, ask_human))The search runs without a prompt. The first email is approved and sent. The second email is rejected, and the agent receives {'rejected': True, 'reason': ...}.
Edge cases to handle
The short gate above works for a demo. Production gates need to handle several more situations.
- The reviewer is unavailable or
ask_humanraises an error. The call must not run. Let the exception stop that step, or catch it and return a rejection. Never wrapask_humanin atryblock that falls through to execution. - Several tool calls in one model turn. Run each call through the gate separately. If you show a reviewer a batch, they must be able to decide each item on its own. Otherwise one harmless call can carry a dangerous one past review.
- An edit changes the tool. The code above keeps the tool name from the original call. If you ever let reviewers change the name, run the edited call through
risk_ofagain and back through the gate. - A tool name that is not in
tools.tools[call.name]raisesKeyError. For a model that hallucinates tool names, check membership before asking a human, so reviewers never see calls that cannot run. - A blocking wait. Here
ask_humanreturns immediately. A real person may take hours. Holding a process open that long is fragile, so later chapters replace the blocking call with saved state and a resume step.
What this gate does not yet do
This version proves the shape of the mechanism, and it has known gaps. It holds the call in memory while a person decides, so a restart loses it. It has no timeout. It does not check that the call executed is the same one the reviewer saw, because ask_human receives the call object and nothing stops a later bug from changing it. It records nothing for audit. Later chapters add saved state, expiry, action binding, and an audit trail, each on top of this same run_step structure.
Exercise
A developer adds a new tool, transfer_funds, but forgets to add it to the RISK table. What does risk_of return, and why is that a good behavior?
Show answer
It returns "high", because RISK.get(call.name, "high") falls back to "high" for unknown names. The new tool then needs human approval until someone classifies it, so a missing table entry causes extra review instead of an unreviewed money transfer.
Exercise
In run_step, a reviewer's UI has a bug and returns {"action": "approved"} (with a trailing "d"). What happens, and why is that the right outcome?
Show answer
None of the approve, edit, or reject branches match, so the final return gives {"rejected": True, "reason": "Unrecognized decision"} and the tool does not run. Failing closed means a malformed decision never grants permission. The agent receives a rejection it can report or work around.
Exercise
Why does run_step return a rejection dictionary instead of raising an exception when the reviewer says no?
Show answer
A rejection is a normal outcome, not a program error. Returning it as a result lets the agent loop add the reason to the conversation so the model can adjust, for example by drafting a different email or asking the user for guidance. An exception would typically end the whole run.