Module 4 · Human-in-the-loop
Approving sensitive actions
6 min read
Knowing how to suspend a graph isn't enough: you must do it at the right moment, ask the right question, and handle every possible answer — including bad ones. This lesson dissects Relay's refund approval circuit, which applies these principles end to end.
When to ask for approval?
Too many approvals, and humans approve them mechanically — the approval no longer protects anything. Not enough, and a costly error slips through. The decision to bother a human must be computed by code, according to the action's risk:
| Criterion | Example |
|---|---|
| Amount | Above €50: supervisor; above €500: finance too |
| Irreversibility | Deletion, external send, payment |
| Uncertainty | The model flagged a doubt, or contradictory sources |
| Novelty | A new customer's first refund, unusual amount |
| Regulation | Health data, a decision with a legal effect on a person |
In Relay, the decision is made by the decide node, from the policy in config.py:
if amount == 0:
approvals_needed = []
elif amount <= config.AUTO_APPROVE_LIMIT: # €50
approvals_needed = []
elif amount <= config.FINANCE_LIMIT: # €500
approvals_needed = ["supervisor"]
else:
approvals_needed = ["supervisor", "finance"]
Refunding a broken €24 mug goes through automatically; a chair and a desk at €848 require two approvals. Thresholds are business settings, versioned with the code and tested.
Asking the right question
The human receiving the request didn't follow the conversation. The value passed to interrupt() must give them everything needed to decide quickly and well, and nothing more:
question = {
"step": step, # who must answer: supervisor or finance
"order_id": refund["order_id"],
"amount": refund["amount"],
"lines": [{"name": l["name"], "why": l["why"], "amount": l["amount"]} for l in refund["lines"]],
"allowed": ["approve", "reject", "edit"],
}
- The decision context: the order, the amount, the per-item detail and the reason retained (
damaged,changed_mind…). The reviewer sees why each line is refunded. - The possible answers (
allowed): the interface can build its buttons from this list. - No useless data: neither the full history nor internal ids. This value will be displayed, logged, perhaps emailed.
Validating the answer: ask again while it's invalid
The human's answer comes from outside — from an interface, an API, an internal tool. It is therefore untrusted, exactly like an LLM output. Relay validates it, and asks again if it is invalid, using several interrupt() calls in the same node:
def _ask_reviewer(step: str, refund: dict) -> dict:
question = {...}
while True:
answer = interrupt(question)
if isinstance(answer, dict) and answer.get("decision") in ("approve", "reject"):
return answer
amount = answer.get("amount") if isinstance(answer, dict) else None
if isinstance(answer, dict) and answer.get("decision") == "edit" \
and isinstance(amount, (int, float)) and 0 < amount <= refund["amount"]:
return answer
question = {**question, "error": "Réponse invalide : decision ∈ approve | reject | edit "
"(avec 0 < amount ≤ montant proposé)."}
How does this loop work, when the node starts over on each resume? Thanks to matching answers by order: on the second resume, the first interrupt() receives (again) the first answer — invalid —, the loop continues, and the second interrupt() receives the new answer. The code is easy to read, and the behavior fully reproducible. The test_invalid_answer_is_asked_again test checks it: an invalid answer, then a valid one that moves on to finance.
Note the business constraint on editing: a reviewer can reduce the amount, never raise it above what the policy computed. Human approval is a brake, not a way around the policy.
Handling the decision: Command to route
Once the answer is validated, the node records the decision and chooses what comes next, with a Command (lesson 2.1):
def _review(step: str, state: RefundState, next_step: str) -> Command[...]:
refund = state["refund"]
answer = _ask_reviewer(step, refund)
approval = {"step": step, "decision": answer["decision"], "reviewer": answer.get("reviewer", "?")}
if answer["decision"] == "reject":
updated = {**refund, "approvals": [*refund["approvals"], approval], "rejected_by": step}
return Command(goto="explain", update={"refund": updated, "audit": [f"{step}: refusé par ..."]})
amount = float(answer["amount"]) if answer["decision"] == "edit" else refund["amount"]
updated = {**refund, "amount": round(amount, 2), "approvals": [*refund["approvals"], approval]}
if next_step == "finance_review" and amount <= config.FINANCE_LIMIT:
next_step = "execute" # a reduced amount may no longer need finance
return Command(goto=next_step, update={"refund": updated, "audit": [...]})
Three behaviors, each covered by a test:
| Decision | Next | Test |
|---|---|---|
approve | Next approval, or execution | test_two_level_approval |
edit (reduced amount) | Direct execution if the new amount no longer requires finance | test_edit_amount_skips_finance |
reject | Explanation to the customer, no refund | test_rejection |
Tracing who decided what
Each decision is recorded twice: in refund["approvals"] (business data, with the reviewer's name) and in the audit log. This traceability isn't a luxury: for a refund, a dispute or an audit, you must be able to say who approved, when and on what basis. The interrupt's checkpoint even contains the exact question asked to the reviewer.
The reviewer's identity must come from your authentication system, not from a free-form field: in Relay's server, the reviewer field is provided by the API caller, which must therefore be an authenticated internal interface.
After approval: act exactly once
The execute node is the only one that acts on the world. It is protected at three levels: an idempotency key (replaying doesn't refund twice), a retry policy for the payment provider's transient failures, and an error handler that escalates cleanly if everything fails (lesson 2.2). A human approval is only worth something if the action that follows is reliable.
Key takeaways
- Code decides when to bother a human, according to risk: amount, irreversibility, uncertainty, regulation.
- The
interrupt()value contains the whole decision context and the possible answers, nothing more.- The human's answer is untrusted: validate it, and ask again with successive
interrupt()calls.- The decision is recorded and the next step chosen with a
Command; each branch is tested.- Trace who decided what; the reviewer's identity comes from authentication, not a free field.
Practice
- Add an approval criterion: any refund for a
premiumcustomer above €300 goes to finance, whatever the threshold. - Add an
escalatedecision that hands the case to a manager, with a third approval level. - Write the test for an
editanswer with an amount higher than the proposed amount: what should happen?