Sub topic 1
Where an approval step fits in the agent loop
An approval step is a point in an agent's loop where execution stops until a person decides what happens next. Before you build one, you need to know exactly where it goes. A gate in the wrong place can look like it protects you and still allow the action. This chapter walks through the agent loop, marks the one position where a gate works, and shows the smallest version in code.
Prerequisites
This chapter assumes you already have the following:
- A basic idea of how LLM agents call tools. You know that the model returns a structured request such as "call
send_emailwith these arguments," and your code runs it. - Comfort reading short Python programs, including dataclasses and dictionaries.
- Familiarity with JSON-like data structures.
- A basic idea of what a web request or background job is. This matters only in the last sections, where a pause can last longer than one process.
You do not need any framework. The examples use plain Python and a scripted stand-in for the model, so you can run them offline.
The loop in four steps
Most tool-using agents repeat the same cycle until the model decides it is done:
- Plan. Your code sends the conversation so far to the model.
- Propose. The model replies with either a final answer or a tool call. A tool call is only a request, a name plus arguments. Nothing has happened yet.
- Act. Your code looks up the tool and runs it. This is the only step with side effects in the outside world.
- Observe. Your code appends the tool result to the conversation, and the loop returns to step 1.
The distinction between propose and act is the basis for everything in this tutorial. The model never touches your systems. Your code does, and it does so only when it chooses to. That gap between a proposed call and an executed call is where a human checkpoint belongs.
Where the gate goes
The gate sits between propose and act. It receives the proposed call, decides whether a person must look at it, and either lets execution continue or substitutes some other result for the real one.
Three properties of this placement are worth stating directly.
- Before the side effect. The gate runs before the tool function is called. Anything that happens after the tool runs is logging or damage control, not approval.
- Per tool call, not per run. Each proposed call is judged separately. A run that searches ten times and sends one email should interrupt a person once.
- Both branches rejoin the loop. Whether the call ran or not, the model gets an observation and continues. A rejection is information the model can act on, for example by choosing another approach or asking the user a question.
A minimal loop with a gate
The code below is a complete, runnable agent loop. The model is a script that first searches and then tries to send an email, which lets you watch the gate behave without an API key.
from dataclasses import dataclass
@dataclass(frozen=True)
class ToolCall:
name: str
args: dict
def search_docs(query):
return {"results": [f"doc about {query}"]}
def send_email(to, body):
return {"sent": True, "to": to}
TOOLS = {"search_docs": search_docs, "send_email": send_email}
RISK = {"search_docs": "low", "send_email": "high"}
def risk_of(call):
# Unknown tools default to high risk.
return RISK.get(call.name, "high")
def fake_model(history):
# Scripted stand-in for an LLM: search, then email, then finish.
tool_results = sum(1 for m in history if m["role"] == "tool")
if tool_results == 0:
return {"call": ToolCall("search_docs", {"query": "refund policy"})}
if tool_results == 1:
return {"call": ToolCall("send_email", {"to": "[email protected]", "body": "Refund sent."})}
return {"final": "Done."}
def run_agent(task, model, tools, ask_human, max_steps=5):
history = [{"role": "user", "content": task}]
for _ in range(max_steps):
out = model(history)
if "final" in out:
return out["final"], history
call = out["call"] # propose
history.append({"role": "assistant", "call": call})
if risk_of(call) == "low": # gate
result = tools[call.name](**call.args)
else:
decision = ask_human(call)
if decision["action"] == "approve":
result = tools[call.name](**call.args) # act
else:
result = {"rejected": True, "reason": decision.get("reason", "")}
history.append({"role": "tool", "name": call.name, "result": result}) # observe
raise RuntimeError("Agent exceeded step limit")
def ask_human(call):
print(f"Approval needed: {call.name} {call.args}")
return {"action": "reject", "reason": "Customer asked not to be emailed."}
answer, history = run_agent("Handle the refund", fake_model, TOOLS, ask_human)
print(answer)
for message in history:
print(message)Run it and you will see the search execute without interruption, the email stopped at the gate, and the rejection reason appear in the history as a tool result. The model's next turn can read that reason. Change ask_human to return {"action": "approve"} and the email tool runs.
Notice what is missing. This version blocks while waiting, only supports approve and reject, and does not check that the approved action is the one that runs. Later chapters add editing, saved state, and action binding. The position of the gate does not change as you add them.
Why the position matters
Approval seems simple enough that people often place it wrongly. Each of the placements below fails in a specific way.
| Placement | What happens | Why it fails |
|---|---|---|
| Inside the prompt ("ask before sending email") | The model is told to ask for permission | The model can forget, misread, or be manipulated. It is a request, not a control. |
| After the tool runs | A person reviews the result | The side effect already happened. You can apologize but not prevent. |
| Inside each tool function | Every tool asks for itself | Works, but duplicates policy across tools and makes it hard to see what is gated. |
| Between propose and act, in the loop | One gate sees every call | Code enforces it, and policy lives in one place. |
The last row is the pattern this tutorial uses. The central idea is that approval is enforced by code that the model cannot bypass, not by instructions the model is asked to follow.
What the gate can see and decide
At the gate you have the full proposed call and the conversation up to that point. That gives you three kinds of input to the decision:
- The call itself. The tool name and arguments. This is what your risk lookup uses.
- The context. The user's task, earlier tool results, and which agent or tenant is running. Later chapters use this for policy rules, for example "refunds under $20 are fine."
- The state of the run. How many steps have run and what has already been approved.
The gate produces one of a small set of outcomes. In this chapter you saw approve and reject. The tutorial later adds edit and feedback. Every outcome must end with something appended to the conversation, so the loop never leaves the model waiting with no observation.
Edge cases at the gate
Several situations in the loop need an explicit decision from you.
Several tool calls in one turn. Many models can propose multiple calls at once. Gate each call separately and decide whether to run low-risk calls while high-risk ones wait. If calls depend on each other, such as "create record, then email the link," holding one may make the other meaningless. The simplest safe policy is to pause the whole turn if any call needs approval.
Rejected calls and retry loops. A model that sees a rejection may propose the same call again with slightly different wording. Without a limit you will ask the human the same question repeatedly. Cap the number of approval requests per run and include the rejection reason in what the model sees.
The step limit. The max_steps guard in the example stops runaway loops. Waiting on a human should not count against it, or a slow reviewer will make the run fail.
Tools you have not classified. A new tool that is not in the lookup table is treated as high risk. This fails toward asking, which is annoying but safe. The opposite default would let a new tool run unreviewed.
The model's final answer. Not every output is a tool call. Some teams also gate the final message, for example before a customer-facing reply is sent. That is the same pattern. The "act" is sending the reply.
Synchronous and long-lived pauses
The example blocks inside ask_human, so the Python process waits for a person. That works for a terminal demo. In a web service, a reviewer might respond in minutes or days, and your process may restart in between. A real gate then has to stop the loop, save enough state to continue, and resume when the decision arrives. The loop structure stays the same, with the pause turned into a stored record instead of a function call. The chapters on saving state and asynchronous approval cover how.
Common errors
- Putting the approval check in the model's prompt instead of in code.
- Running the tool first, then asking for confirmation.
- Gating by run instead of by tool call, which forces people to approve harmless steps.
- Forgetting to append a result after a rejection, so the next model call has a tool call with no matching observation. Many model APIs reject such histories with an error.
- Counting waiting time against the step limit or a request timeout.
Exercise
In the loop code, the gate checks risk_of(call) and calls ask_human before the tool runs. A teammate proposes moving the approval prompt to after tools[call.name](**call.args) so reviewers can see the actual result. What is wrong with this, and what would you offer instead?
Show answer
Once the tool has run, the side effect (for example, the sent email) has already happened, so the person can no longer prevent it. The gate must sit between proposing and acting. To show reviewers a concrete preview, have the tool offer a dry-run or preview mode that computes what would happen without committing it, and show that preview at the gate.
Exercise
The model proposes two calls in one turn: search_docs (low risk) and send_email (high risk). Name one safe policy for this case and one reason you might prefer a different one.
Show answer
A safe policy is to pause the whole turn if any call needs approval, then run all approved calls together. This avoids partial results when calls depend on each other. A different policy runs the low-risk call immediately and only holds the high-risk one, which reduces latency when the calls are independent, but you must be sure the low-risk call's result does not change what the reviewer should decide.