Approve, edit and reject patterns
Overview
In the previous lesson, you learned how LangGraph suspends execution using interrupt() and continues execution using Command(resume=...).
Knowing how to pause a graph is only the beginning. In production agentic systems, you must also determine what humans can decide, what information they can modify, how their responses affect execution, and when an action is authorized.
Consider an AI-powered customer support agent capable of drafting emails, updating customer records, issuing refunds, and closing support tickets.
These operations do not have the same risk. Generating a draft is usually reversible, whereas issuing a refund or sending confidential information to an external recipient may have significant consequences.
Human-in-the-loop (HITL) patterns introduce controlled decision points between an agent’s recommendations and their real-world consequences.
A well-designed review workflow distinguishes three responsibilities:
- Proposal: The agent determines what it recommends doing.
- Decision: An authorized human reviews the proposal.
- Execution: The system performs the authorized action.
The model proposes. The human decides. Deterministic application logic enforces the decision.
The five standard review patterns
| Pattern | Human provides | Workflow behavior | Typical use case |
|---|---|---|---|
| Approve or reject | Binary decision | Execute or terminate | Publishing content |
| Approve, edit or reject | Decision and optional changes | Execute original or modified proposal | Email approval |
| Feedback and revise | Improvement instructions | Generate another proposal | Document drafting |
| Review and edit state | Corrected field values | Persist corrections and continue | Customer data verification |
| Validate human input | Required structured information | Accept or request correction | Collecting transaction details |
These are application design patterns rather than five separate LangGraph APIs. They all build upon interrupts, checkpointed state, conditional execution, and validated state updates.
Environment setup
Install LangGraph 1.x and the typing utilities:
pip install "langgraph>=1.0,<2.0" typing-extensionsThe examples in this lesson intentionally use deterministic functions and simulated external actions. You do not need an LLM API key, email account, or payment service.
Each Python example is designed as a standalone script.
Note:
InMemorySaveris appropriate for learning and local testing, but its checkpoints disappear when the process exits. Production workflows require durable persistence, such as PostgreSQL-backed checkpointing.
How human review works internally
When a review node calls interrupt(payload), LangGraph suspends the current execution and records the necessary continuation information through its checkpointer.
The calling application receives the review request through result["__interrupt__"].
After the human responds, the application invokes the graph again using the same thread ID and a resume command.
LangGraph re-enters the interrupted node from its beginning. Previously supplied resume values are made available to the corresponding interrupt calls, allowing execution to continue.
The following diagram illustrates the review lifecycle.
The checkpoint is not itself an approval. It records workflow progress. Your application must explicitly interpret the response and decide which graph transition is permitted.
Pattern 1: Approve or reject
The simplest review pattern is a binary approval gate. The human either authorizes the proposed operation or refuses permission.
This pattern is suitable when the proposed action is already complete and does not require modification.
Examples include:
- Publishing an article.
- Submitting a purchase order.
- Deleting an archived record.
- Sending a notification.
- Executing a proposed database modification.
Implementing a binary approval gate
The following example pauses before publishing an announcement. The publication node is reachable only through explicit approval.
from typing import Literal
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.types import Command, interrupt
from langgraph.checkpoint.memory import InMemorySaver
class State(TypedDict, total=False):
content: str
status: str
def review(
state: State,
) -> Command[Literal["publish", "__end__"]]:
approved = interrupt({
"type": "approval",
"question": "Publish this announcement?",
"content": state["content"],
})
if approved is True:
return Command(
update={"status": "approved"},
goto="publish",
)
return Command(
update={
"status": "rejected" if approved is False
else "invalid_response"
},
goto=END,
)
def publish(state: State) -> dict:
if state["status"] != "approved":
raise RuntimeError("Approval required.")
print("Publishing:", state["content"])
return {"status": "published"}
builder = StateGraph(State)
builder.add_node("review", review)
builder.add_node("publish", publish)
builder.add_edge(START, "review")
builder.add_edge("publish", END)
graph = builder.compile(checkpointer=InMemorySaver())
config = {"configurable": {"thread_id": "announcement-1"}}
result = graph.invoke(
{"content": "Our new product launches on Monday."},
config,
)
print(result["__interrupt__"][0].value)
result = graph.invoke(Command(resume=True), config)
print("Final status:", result["status"])Expected output:
{'type': 'approval', 'question': 'Publish this announcement?', 'content': 'Our new product launches on Monday.'}
Publishing: Our new product launches on Monday.
Final status: publishedTo test rejection, start another execution with a different thread ID and resume using Command(resume=False).
The final status becomes rejected, and the publication node never executes.
Understanding the routing decision
The review node returns a Command containing two important properties:
update: The state changes that record the decision.goto: The destination selected by that decision.
This combines a state transition with a control-flow transition.
Notice that there is no unconditional edge from review to publish. Adding such an edge could cause publication to be scheduled independently of the decision returned by Command.
Also notice the use of approved is True rather than if approved.
Python considers nonempty strings truthy. Consequently, a response containing the string "false" could accidentally authorize an action if you use ordinary truthiness checks.
Approval gates should follow a fail-closed policy: execution is permitted only when the expected authorization is explicitly present.
Pattern 2: Approve, edit or reject
Binary decisions are sometimes too restrictive. A reviewer might agree with an agent’s proposed action but disagree with part of its content.
For example, an AI-generated customer email might contain the correct information but use inappropriate wording.
Instead of rejecting the entire draft and restarting the workflow, the reviewer should be able to modify it directly.
This pattern introduces three decisions:
| Decision | State update | Next operation |
|---|---|---|
| Approve | Preserve proposal | Execute original |
| Edit | Replace permitted fields | Execute modified proposal |
| Reject | Record rejection | Terminate safely |
In this example, edit means edit and approve. In other applications, editing may require another independent approval.
Your interface must communicate that distinction clearly.
Implementing an editable email approval gate
The following example allows a reviewer to modify an email body before simulated delivery.
from typing import Literal
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.types import Command, interrupt
from langgraph.checkpoint.memory import InMemorySaver
class State(TypedDict, total=False):
recipient: str
draft: str
status: str
def review(
state: State,
) -> Command[Literal["send_email", "__end__"]]:
response = interrupt({
"type": "email_review",
"recipient": state["recipient"],
"draft": state["draft"],
"allowed_decisions": ["approve", "edit", "reject"],
"editable_fields": ["draft"],
})
if isinstance(response, dict):
decision = response.get("decision")
if decision == "approve" and state["draft"].strip():
return Command(
update={"status": "approved"},
goto="send_email",
)
if decision == "edit":
edited = response.get("draft")
if isinstance(edited, str) and 0 < len(edited.strip()) <= 5000:
return Command(
update={
"draft": edited.strip(),
"status": "approved",
},
goto="send_email",
)
if decision == "reject":
return Command(
update={"status": "rejected"},
goto=END,
)
return Command(
update={"status": "invalid_response"},
goto=END,
)
def send_email(state: State) -> dict:
if state["status"] != "approved":
raise RuntimeError("Email is not approved.")
print("SIMULATED SEND")
print("To:", state["recipient"])
print("Body:", state["draft"])
return {"status": "sent"}
builder = StateGraph(State)
builder.add_node("review", review)
builder.add_node("send_email", send_email)
builder.add_edge(START, "review")
builder.add_edge("send_email", END)
graph = builder.compile(checkpointer=InMemorySaver())
config = {"configurable": {"thread_id": "email-001"}}
result = graph.invoke({
"recipient": "customer@example.com",
"draft": "Your complaint has been received.",
"status": "pending",
}, config)
print(result["__interrupt__"][0].value)
result = graph.invoke(
Command(resume={
"decision": "edit",
"draft": "Thank you for contacting us. We are reviewing your concern.",
}),
config,
)
print("Final status:", result["status"])Expected output after the reviewer responds:
SIMULATED SEND
To: customer@example.com
Body: Thank you for contacting us. We are reviewing your concern.
Final status: sentThe important detail is that the execution node reads the updated draft from graph state, not the original proposal.
Restricting editable fields
The example permits editing the message body but not the recipient.
This is intentional. A poorly designed implementation might return the entire human response as a state update. That could allow callers to change protected fields, including transaction identifiers, permissions, recipients, or approval status.
Construct state updates explicitly using an allowlist of permitted fields.
For sensitive workflows, material changes should invalidate existing approvals. Changing a payment destination, for example, may require a new review rather than automatic execution.
An approved proposal should be treated as a specific version of an action, not unrestricted permission to perform similar actions later.
Pattern 3: Feedback and revise
Sometimes the reviewer knows what is wrong but does not want to rewrite the entire proposal.
Instead of supplying replacement content, the reviewer provides feedback such as:
- Make the response more empathetic.
- Explain the refund policy.
- Remove unsupported promises.
- Include the customer’s ticket number.
The agent then generates another version for review.
Unlike the previous pattern, feedback does not authorize execution. It initiates another generation cycle.
The following diagram shows this iterative workflow.
Implementing a bounded revision loop
This example uses a deterministic drafting function to demonstrate the workflow without introducing LLM variability.
from typing import Literal
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.types import Command, interrupt
from langgraph.checkpoint.memory import InMemorySaver
class State(TypedDict, total=False):
draft: str
feedback: str
revisions: int
status: str
MAX_REVISIONS = 2
def generate_draft(state: State) -> dict:
if state["revisions"] == 0:
draft = "Your support ticket is under review."
else:
draft = (
"Thank you for your patience. "
+ state["feedback"]
)
return {"draft": draft, "status": "pending"}
def review(
state: State,
) -> Command[Literal["generate_draft", "__end__"]]:
response = interrupt({
"type": "draft_feedback",
"draft": state["draft"],
"revision": state["revisions"],
"allowed_decisions": ["approve", "revise", "reject"],
})
if isinstance(response, dict):
decision = response.get("decision")
if decision == "approve":
return Command(
update={"status": "approved"},
goto=END,
)
if decision == "reject":
return Command(
update={"status": "rejected"},
goto=END,
)
if decision == "revise":
feedback = response.get("feedback")
if isinstance(feedback, str) and feedback.strip():
if state["revisions"] < MAX_REVISIONS:
return Command(
update={
"feedback": feedback.strip(),
"revisions": state["revisions"] + 1,
},
goto="generate_draft",
)
return Command(
update={"status": "revision_limit_reached"},
goto=END,
)
return Command(
update={"status": "invalid_response"},
goto=END,
)
builder = StateGraph(State)
builder.add_node("generate_draft", generate_draft)
builder.add_node("review", review)
builder.add_edge(START, "generate_draft")
builder.add_edge("generate_draft", "review")
graph = builder.compile(checkpointer=InMemorySaver())
config = {
"configurable": {"thread_id": "feedback-001"},
"recursion_limit": 20,
}
result = graph.invoke(
{"revisions": 0, "feedback": ""},
config,
)
print("Original:", result["draft"])
result = graph.invoke(
Command(resume={
"decision": "revise",
"feedback": "Your ticket is being reviewed by our support team.",
}),
config,
)
print("Revised:", result["draft"])
assert result["__interrupt__"]
result = graph.invoke(
Command(resume={"decision": "approve"}),
config,
)
print("Status:", result["status"])
print("Revisions:", result["revisions"])Expected output:
Original: Your support ticket is under review.
Revised: Thank you for your patience. Your ticket is being reviewed by our support team.
Status: approved
Revisions: 1Integrating feedback with an LLM
In a real agent, the drafting node would invoke a language model using the original requirements, previous draft, human feedback, and relevant business policies.
The generation node should remain separate from the review node. This avoids unnecessarily repeating model calls when a human resumes an interrupted review.
Keep the original requirements available throughout the revision process. Otherwise, repeated modifications can gradually remove important constraints, a problem known as revision drift.
A revision limit controls the application’s business behavior. The graph’s recursion_limit provides an additional safeguard against excessive execution steps.
Neither reaching a revision limit nor receiving positive feedback should automatically authorize an external action.
Pattern 4: Review and edit state
Human review is not limited to generated documents or proposed actions. Humans can also correct information that the agent has extracted, classified, or inferred.
Imagine an agent that extracts customer information from a support ticket:
- Customer name.
- Department.
- Priority.
- Ticket category.
Incorrect information could cause the workflow to route the ticket to the wrong department.
A state-review node allows humans to correct these fields before downstream processing.
Implementing structured state correction
The following example allows a reviewer to correct a ticket’s department and priority while preserving its identifier.
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.types import interrupt, Command
from langgraph.checkpoint.memory import InMemorySaver
class State(TypedDict, total=False):
ticket_id: str
department: str
priority: str
verified: bool
assigned_queue: str
def review_ticket(state: State) -> dict:
corrections = interrupt({
"type": "state_review",
"ticket_id": state["ticket_id"],
"fields": {
"department": state["department"],
"priority": state["priority"],
},
"allowed_departments": ["billing", "technical"],
"allowed_priorities": ["low", "normal", "high"],
})
if not isinstance(corrections, dict):
return {"verified": False}
department = corrections.get("department", state["department"])
priority = corrections.get("priority", state["priority"])
if department not in ("billing", "technical"):
return {"verified": False}
if priority not in ("low", "normal", "high"):
return {"verified": False}
return {
"department": department,
"priority": priority,
"verified": True,
}
def assign_ticket(state: State) -> dict:
return {
"assigned_queue": f"{state['department']}-{state['priority']}"
}
builder = StateGraph(State)
builder.add_node("review_ticket", review_ticket)
builder.add_node("assign_ticket", assign_ticket)
builder.add_edge(START, "review_ticket")
builder.add_conditional_edges(
"review_ticket",
lambda state: "assign_ticket" if state["verified"] else END,
)
builder.add_edge("assign_ticket", END)
graph = builder.compile(checkpointer=InMemorySaver())
config = {"configurable": {"thread_id": "ticket-001"}}
graph.invoke({
"ticket_id": "T1001",
"department": "technical",
"priority": "normal",
"verified": False,
}, config)
result = graph.invoke(
Command(resume={
"department": "billing",
"priority": "high",
}),
config,
)
print(result["ticket_id"])
print(result["assigned_queue"])Expected output:
T1001
billing-highThe reviewer corrected the classification without changing the ticket’s identity.
Returning updates versus modifying checkpoints
LangGraph also provides checkpoint inspection and external state modification APIs:
graph.get_state(config)retrieves a state snapshot.graph.update_state(config, values, as_node=...)applies an external state update.graph.get_state_history(config)exposes historical snapshots.
However, update_state() is not equivalent to answering an interrupt. It can change checkpoint history and affect subsequent node scheduling through the specified as_node.
For ordinary human corrections, prefer returning validated updates from a review node. Reserve external checkpoint editing for controlled administrative, debugging, or recovery workflows.
Remember that updates follow the state schema’s reducers. A normal scalar field is replaced, whereas an append-style reducer may accumulate additional values instead of replacing existing ones.
See the official Graph API documentation for reducer and routing semantics.
Pattern 5: Validate human input
A human response is not automatically correct simply because it originated from a human.
Review interfaces may submit malformed JSON, missing fields, unsupported decisions, incorrect data types, or values that violate business constraints.
Validation must happen on the backend, even when the frontend already validates its forms.
Re-prompting after invalid input
Consider a workflow that requires a reviewer to enter a refund percentage between 1 and 100.
Instead of terminating immediately when the input is invalid, the graph can present another interrupt containing an error message.
The following implementation stores validation errors in state and routes back to the input node.
from typing import Literal
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.types import Command, interrupt
from langgraph.checkpoint.memory import InMemorySaver
class State(TypedDict, total=False):
percentage: int
attempts: int
error: str
status: str
def collect_percentage(
state: State,
) -> Command[Literal["collect_percentage", "__end__"]]:
response = interrupt({
"type": "numeric_input",
"question": "Enter a refund percentage from 1 to 100.",
"error": state.get("error", ""),
"attempts": state["attempts"],
})
if type(response) is int and 1 <= response <= 100:
return Command(
update={
"percentage": response,
"error": "",
"status": "validated",
},
goto=END,
)
attempts = state["attempts"] + 1
return Command(
update={
"attempts": attempts,
"error": "Enter an integer between 1 and 100.",
"status": (
"validation_failed" if attempts >= 3
else "waiting_for_input"
),
},
goto=END if attempts >= 3 else "collect_percentage",
)
builder = StateGraph(State)
builder.add_node("collect_percentage", collect_percentage)
builder.add_edge(START, "collect_percentage")
graph = builder.compile(checkpointer=InMemorySaver())
config = {
"configurable": {"thread_id": "percentage-001"},
"recursion_limit": 20,
}
result = graph.invoke({"attempts": 0}, config)
result = graph.invoke(Command(resume=150), config)
print(result["__interrupt__"][0].value["error"])
result = graph.invoke(Command(resume=25), config)
print(result["percentage"])
print(result["status"])Expected output:
Enter an integer between 1 and 100.
25
validatedValidation and interrupt replay
The self-routing node creates a fresh review task after each unsuccessful attempt. This makes validation progress visible in checkpoints.
Multiple deterministic interrupt calls inside a node are also possible. However, repeatedly interrupting within a local loop causes previous iterations to be replayed on resume. A short bounded loop can work, but checkpointed graph-level loops are preferable for production validation.
Recent LangGraph 1.x releases also support typed interrupt responses through response_schema, introduced in version 1.2.12. This is useful for form generation and type validation, but business-specific checks remain necessary.
Tip: Validate data types, permitted values, business rules, and reviewer permissions separately. A structurally valid response can still authorize an invalid operation.
Refer to the official Interrupts documentation for response schemas and replay behavior.
Designing the payload
An interrupt payload is a communication contract between your graph and the application responsible for human review.
LangGraph transports the payload, but your application defines its meaning and determines how to render it.
A production-oriented email review payload might look like this:
{
"schema_version": 1,
"type": "email_review",
"review_id": "REV-1042",
"proposal_version": 3,
"action": "send_email",
"risk": "external_communication",
"proposal": {
"recipient": "customer@example.com",
"subject": "Support update",
"body": "We are reviewing your request."
},
"allowed_decisions": ["approve", "edit", "reject"],
"editable_fields": ["body"],
"error": null
}A corresponding response could be:
{
"review_id": "REV-1042",
"proposal_version": 3,
"decision": "edit",
"changes": {
"body": "Thank you for your patience. Our team is reviewing your request."
}
}Payload design principles
Include sufficient context for informed authorization. A reviewer should understand what will happen, which resources will be affected, and whether the operation is reversible.
Use stable machine-readable decision values rather than interpreting natural-language responses with an LLM.
A robust payload should include:
- A review type and schema version for frontend compatibility.
- A unique review identifier and proposal version.
- The proposed action and relevant parameters.
- Permitted decisions and editable fields.
- Validation errors and applicable constraints.
- Relevant risks and supporting evidence.
Keep identifiers stable across resume operations. Generate and persist them before entering the interrupted review node.
Avoid exposing access tokens, credentials, unnecessary personal information, or unrestricted internal state through interrupt payloads.
Security and stale approvals
The thread_id identifies execution state; it does not authenticate a reviewer.
The application handling resume requests must verify the reviewer’s identity, permissions, tenant ownership, and access to the relevant thread.
It should also confirm that the response refers to the currently pending review and the correct proposal version.
Suppose one reviewer approves an email while another simultaneously changes its contents. Without version checks, the system might execute content that was never actually approved.
Use concurrency controls and atomic review-status transitions to prevent duplicate decisions and stale approvals.
Store trusted reviewer identity separately from client-submitted response fields. Never accept an arbitrary reviewer_id supplied by the browser as proof of authorization.
Separate approval from action
One of the most important architectural principles in human-reviewed agentic systems is separating the review decision from the operation it authorizes.
A review node should interpret human input, validate the decision, update state, and determine routing. The action node should perform the approved operation.
This separation provides a useful checkpoint boundary between authorization and execution.
Why execution boundaries matter
Consider an email-sending node that successfully calls an external email provider but crashes before LangGraph records its completion.
When the node is retried, the email might be sent again.
Separating approval from execution reduces replay-related risks, but it does not guarantee exactly-once external operations.
Production action nodes should therefore use stable operation identifiers, provider-supported idempotency keys, deduplicated database writes, or transactional outbox patterns where appropriate.
An idempotency key must identify the logical operation and remain unchanged across retries.
For consequential workflows, synchronous checkpoint durability can be requested using:
result = graph.invoke(
Command(resume={"decision": "approve"}),
config,
durability="sync",
)Synchronous durability persists checkpoints before proceeding to subsequent execution steps. It does not make external API calls and checkpoint writes part of one atomic transaction.
Consult the Persistence documentation when selecting a production checkpointer.
Production readiness checklist
Before deploying a human-reviewed workflow, verify that:
- Rejected and malformed responses cannot reach action nodes.
- The executed parameters match the authorized proposal.
- Editing protected fields is prohibited.
- Expired approvals require renewed authorization.
- External conditions and business constraints are rechecked before execution.
- Duplicate submissions and execution retries cannot duplicate consequential actions.
- Reviewer identity, proposal versions, decisions, timestamps, and outcomes are auditable.
- Pending reviews can survive application restarts.
Do not perform irreversible operations before an interrupt. Because the review node can restart, even seemingly harmless operations such as inserting audit records may produce duplicates unless those operations are idempotent.
Testing review workflows
Test approval, editing, rejection, invalid input, repeated invalid input, revision limits, and attempted unauthorized modifications independently.
Use separate thread IDs for independent test scenarios. Verify not only the final status but also whether the action node executed, which parameters it received, and whether any simulated external effects occurred.
The examples in this lesson use simulated operations, simple validation, and in-memory checkpointing to isolate the review patterns. Their API usage follows the current LangGraph 1.x documentation; the scripts have not been runtime-tested in an installed LangGraph environment.
Connecting to the next lesson
This lesson establishes the decision-making layer of human-in-the-loop workflows. You can now design explicit review gates around proposals, collect corrective feedback, validate human responses, and control when execution is permitted.
In the next lesson, Reviewing tool calls and escalation, you will apply these patterns to agent-generated tool calls, inspect proposed tool arguments before execution, and route high-risk or uncertain operations to appropriate human reviewers.
These capabilities will come together in the chapter project: an email drafting agent that generates a response, presents it for human review, accepts authorized modifications, and sends it only after explicit approval.
Build a human-reviewed refund workflow
Build a LangGraph workflow that pauses before processing a proposed customer refund. Allow the reviewer to approve the original amount, edit the amount and approve it, or reject the refund entirely. Validate the edited amount and request corrected input whenever the review response is invalid. Ensure that refund processing occurs only after a valid approval and test all three decision paths using simulated transactions.
from typing import Literal
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.types import Command, interrupt
from langgraph.checkpoint.memory import InMemorySaver
class RefundState(TypedDict, total=False):
customer_id: str
amount_cents: int
max_amount_cents: int
status: str
receipt: str
def review_refund(
state: RefundState,
) -> Command[Literal["process_refund", "__end__"]]:
# TODO: Present the proposed refund using interrupt().
# TODO: Support approve, edit, and reject decisions.
# TODO: Validate edited amounts and request corrections.
# TODO: Return a Command with state updates and routing.
raise NotImplementedError
def process_refund(state: RefundState) -> dict:
# TODO: Verify approval before simulating the refund.
# TODO: Return a receipt and the final status.
raise NotImplementedError
builder = StateGraph(RefundState)
builder.add_node("review_refund", review_refund)
builder.add_node("process_refund", process_refund)
builder.add_edge(START, "review_refund")
builder.add_edge("process_refund", END)
graph = builder.compile(checkpointer=InMemorySaver())
config = {"configurable": {"thread_id": "refund-001"}}
result = graph.invoke(
{
"customer_id": "C101",
"amount_cents": 7500,
"max_amount_cents": 10000,
"status": "pending",
},
config,
)
# TODO: Inspect the interrupt payload.
# TODO: Resume with a human decision using Command.
# TODO: Test approval, editing, rejection, and invalid input.from typing import Literal
from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.types import Command, interrupt
from langgraph.checkpoint.memory import InMemorySaver
class RefundState(TypedDict, total=False):
customer_id: str
amount_cents: int
max_amount_cents: int
status: str
receipt: str
def review_refund(
state: RefundState,
) -> Command[Literal["process_refund", "__end__"]]:
error = None
for _ in range(3):
response = interrupt(
{
"type": "refund_review",
"customer_id": state["customer_id"],
"amount_cents": state["amount_cents"],
"max_amount_cents": state["max_amount_cents"],
"allowed_decisions": ["approve", "edit", "reject"],
"error": error,
}
)
if not isinstance(response, dict):
error = "Response must be an object."
continue
decision = response.get("decision")
if decision == "reject":
return Command(
update={"status": "rejected"},
goto=END,
)
if decision not in ("approve", "edit"):
error = "Choose approve, edit, or reject."
continue
if decision == "approve":
amount = state["amount_cents"]
else:
amount = response.get("amount_cents")
if (
type(amount) is not int
or not 0 < amount <= state["max_amount_cents"]
):
error = "Amount must be positive integer cents within the limit."
continue
return Command(
update={
"amount_cents": amount,
"status": "approved",
},
goto="process_refund",
)
return Command(
update={"status": "validation_failed"},
goto=END,
)
def process_refund(state: RefundState) -> dict:
if state.get("status") != "approved":
raise RuntimeError("Refund has not been approved.")
amount = state["amount_cents"]
if type(amount) is not int or not 0 < amount <= state["max_amount_cents"]:
raise ValueError("Invalid refund amount.")
# Simulation only. No real financial transaction.
receipt = f"SIM-{state['customer_id']}-{amount}"
return {
"status": "processed",
"receipt": receipt,
}
builder = StateGraph(RefundState)
builder.add_node("review_refund", review_refund)
builder.add_node("process_refund", process_refund)
builder.add_edge(START, "review_refund")
builder.add_edge("process_refund", END)
graph = builder.compile(checkpointer=InMemorySaver())
def start_review(thread_id: str):
config = {"configurable": {"thread_id": thread_id}}
result = graph.invoke(
{
"customer_id": "C101",
"amount_cents": 7500,
"max_amount_cents": 10000,
"status": "pending",
},
config,
)
assert result["__interrupt__"]
return config
# Test 1: Approve the original refund.
config = start_review("approve-test")
result = graph.invoke(
Command(resume={"decision": "approve"}),
config,
)
assert result["status"] == "processed"
assert result["amount_cents"] == 7500
print("Approved:", result["receipt"])
# Test 2: Edit and approve.
config = start_review("edit-test")
result = graph.invoke(
Command(
resume={"decision": "edit", "amount_cents": 5000}
),
config,
)
assert result["status"] == "processed"
assert result["amount_cents"] == 5000
print("Edited:", result["receipt"])
# Test 3: Reject.
config = start_review("reject-test")
result = graph.invoke(
Command(resume={"decision": "reject"}),
config,
)
assert result["status"] == "rejected"
assert "receipt" not in result
print("Rejected:", result["status"])
# Test 4: Invalid input followed by a valid correction.
config = start_review("validation-test")
result = graph.invoke(
Command(
resume={"decision": "edit", "amount_cents": 20000}
),
config,
)
assert result["__interrupt__"]
assert "receipt" not in result
print("Validation error:", result["__interrupt__"][0].value["error"])
result = graph.invoke(
Command(
resume={"decision": "edit", "amount_cents": 3000}
),
config,
)
assert result["status"] == "processed"
assert result["amount_cents"] == 3000
print("Corrected:", result["receipt"])
# Test 5: Exhaust the validation attempts.
config = start_review("invalid-test")
for _ in range(3):
result = graph.invoke(
Command(resume={"decision": "unknown"}),
config,
)
assert result["status"] == "validation_failed"
assert "receipt" not in result
print("Invalid review:", result["status"])Summary
- Human approval gates prevent consequential actions from executing without explicit authorization.
- The approve-edit-reject pattern allows reviewers to authorize either the original proposal or a validated modification.
- Human feedback can drive iterative revisions without granting permission to execute an action.
- Review nodes should return explicit state updates instead of directly mutating graph state.
- Human responses must be treated as untrusted input and validated before influencing execution.
- Structured interrupt payloads establish a clear communication contract between the graph and its review interface.
- Separating approval from execution improves auditability and supports reliable recovery when combined with durable checkpointing and idempotency.