Reviewing tool calls and escalation

Topic 3 of 4 in Human-in-the-loop24 min readIntermediateFree course

Overview

Giving an AI agent access to tools transforms it from a conversational system into a system capable of taking actions.

An agent can query databases, send emails, modify customer accounts, issue refunds, create support tickets, and interact with external APIs. Although these capabilities make agents valuable, they also introduce operational, financial, security, and reputational risks.

Consider a customer support agent connected to an order management system.

The agent might safely retrieve an order’s delivery status without supervision. However, issuing a large refund, changing a customer’s registered email address, or deleting an account requires considerably more control.

The fundamental distinction is between proposing an action and authorizing its execution.

A model-generated tool call is a proposal. It is not proof that the operation is authorized, appropriate, or correct.

In the previous lesson, you implemented approve, edit, and reject patterns using interrupt() and Command. This lesson applies those patterns specifically to tool execution and introduces escalation when an agent cannot safely resolve a situation independently.

You will learn three implementation approaches:

  • Embed approval directly inside sensitive tools.
  • Introduce a dedicated review node before tool execution.
  • Use LangChain’s built-in human-in-the-loop middleware.

You will also learn how to preserve reviewer feedback and design workflows that transfer responsibility to qualified humans.

Environment setup

Install the required packages in a Python 3.11 or newer environment.

Terminal
pip install -U "langgraph>=1,<2" "langchain>=1.5.2,<2" langchain-openai

For the model-backed example, configure your OpenAI API key.

Terminal
export OPENAI_API_KEY="your-api-key"

The graph-based examples use deterministic tool-call proposals so their approval behavior does not depend on unpredictable model output.

Note: The examples simulate external operations rather than sending real emails or modifying financial records. APIs have been checked against current documentation, but the examples have not been runtime-tested here. The model-backed example requires access to the specified model.

Classify your tools

Human approval is not something you should indiscriminately apply to every tool.

Requiring approval for every database lookup makes an agent slow and frustrating. Conversely, allowing unrestricted execution of sensitive operations creates unacceptable risks.

The objective is risk-based autonomy: allow independent execution when justified, introduce review when necessary, and prohibit operations that violate organizational policy.

Tool risk classification

A useful starting point is to classify tools into four categories.

Risk level Example tools Typical policy
Low Calculator, public documentation search Automatic execution
Moderate Customer lookup, draft creation, internal ticket creation Authorization checks and conditional review
High Send email, issue refund, update account Explicit human approval
Critical Delete production data, transfer large payments Specialist approval or prohibition

These classifications are application-specific.

For example, sending an internal notification may be low risk, while emailing confidential financial information to an external recipient may be critical.

Read-only tools are not automatically safe either. A database lookup could expose personal information, and an unrestricted search tool could retrieve documents belonging to another organization.

Classify the action, not just the tool

Consider a tool named issue_refund.

Its risk depends on the requested amount, customer eligibility, account history, and applicable business rules.

A hypothetical organization might define the following policy:

  • Refunds up to $50: automatic execution after eligibility checks.
  • Refunds above $50 and up to $500: support supervisor approval.
  • Refunds above $500: finance manager approval.
  • Refunds exceeding the original payment: prohibited.

The thresholds belong in deterministic application code or a dedicated policy service, not exclusively in the system prompt.

A prompt instructing a model to request permission is useful guidance, but it is not an enforceable security boundary.

The controlled execution lifecycle

The following diagram illustrates how policy evaluation separates tool proposals from actual execution.

Classify your tools diagram: START to Propose Tool Call; Propose Tool Call to Evaluate Risk Policy; Evaluate Risk Policy to Risk Level?; Risk Level? to Execute Tool (Low); Risk Level? to Human Review (High); Risk Level? to Specialist Review (Critical); Human Review to Approved?; Specialist Review to Approved?; Approved? to Execute Tool (Yes); Approved? to Cancel Action (No).

A review decision authorizes a specific operation. It should not automatically authorize future operations, different recipients, larger payments, or modified arguments.

Option A: interrupt inside the tool

The simplest way to protect a sensitive operation is to place interrupt() directly inside its tool function.

This design makes approval part of the tool’s implementation.

Whenever the tool executes through a compatible LangGraph workflow, it encounters the approval requirement before reaching the sensitive operation.

How it works internally

When a model requests a tool, it produces an AIMessage containing structured tool calls.

Each call contains a tool name, arguments, and a unique call identifier. ToolNode dispatches the request to the corresponding registered tool.

If that tool calls interrupt():

  1. LangGraph suspends the interrupted task.
  2. The checkpointer preserves the execution state.
  3. The interrupt payload becomes available to the calling application.
  4. A human provides a decision.
  5. The application resumes the same thread using Command(resume=...).
  6. The interrupted node replays, and interrupt() returns the supplied decision.

The Python function is not permanently suspended on a live call stack. Its execution is reconstructed through LangGraph’s checkpoint and replay mechanisms.

Example: Protecting an email tool

This example places an approval requirement inside an email tool. It uses ToolNode and a manually constructed tool call to demonstrate the approval mechanism without an LLM.

Python
from langchain.tools import tool, ToolRuntime
from langchain.messages import AIMessage, ToolMessage
from langgraph.graph import StateGraph, MessagesState, START, END
from langgraph.prebuilt import ToolNode
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import interrupt, Command

outbox = []

@tool
def send_email(
    to: str,
    subject: str,
    body: str,
    runtime: ToolRuntime
) -> str | ToolMessage:
    """Send an email after receiving explicit human approval."""

    decision = interrupt({
        "type": "tool_approval",
        "tool": "send_email",
        "tool_call_id": runtime.tool_call_id,
        "arguments": {
            "to": to,
            "subject": subject,
            "body": body
        },
        "allowed_decisions": ["approve", "reject"]
    })

    if not isinstance(decision, dict) or \
       decision.get("decision") != "approve":

        return ToolMessage(
            content="Email rejected. Nothing was sent.",
            tool_call_id=runtime.tool_call_id,
            status="error"
        )

    # Simulated external side effect.
    outbox.append({
        "to": to,
        "subject": subject,
        "body": body
    })

    return f"Email sent to {to}"

builder = StateGraph(MessagesState)

builder.add_node("tools", ToolNode([send_email]))
builder.add_edge(START, "tools")
builder.add_edge("tools", END)

graph = builder.compile(checkpointer=InMemorySaver())

config = {
    "configurable": {"thread_id": "email-review-001"}
}

proposal = AIMessage(
    content="",
    tool_calls=[{
        "name": "send_email",
        "args": {
            "to": "customer@example.com",
            "subject": "Order update",
            "body": "Your order will arrive tomorrow."
        },
        "id": "call_email_001",
        "type": "tool_call"
    }]
)

result = graph.invoke({"messages": [proposal]}, config)

print(result["__interrupt__"][0].value)
print("Emails sent before approval:", len(outbox))

result = graph.invoke(
    Command(resume={"decision": "approve"}),
    config
)

print(result["messages"][-1].content)
print("Emails sent after approval:", len(outbox))

Expected output, excluding the displayed interrupt payload:

Text
Emails sent before approval: 0
Email sent to customer@example.com
Emails sent after approval: 1

The injected ToolRuntime supplies execution information without requiring the model to generate those arguments.

In particular, runtime.tool_call_id identifies the original request and allows the rejection message to be associated with the correct tool call.

Why placement matters

The interrupt must occur before the protected side effect.

If the email is sent before approval, rejecting the interrupt cannot undo the delivery. Furthermore, replaying the interrupted node could cause the operation to happen again.

Placing the side effect after the interrupt prevents premature execution, but it does not guarantee exactly-once execution. A crash after delivery but before checkpoint completion could still cause a duplicate during recovery.

Production tools therefore need stable idempotency keys and durable operation records.

This approach works especially well when the same sensitive tool is shared across several graphs. Its disadvantage is that approval policies become distributed across individual tool implementations.

Option B: a review node before the tool node

A more centralized architecture separates approval from execution.

Instead of embedding an interrupt inside every sensitive tool, introduce a review node between the model and ToolNode.

The review node examines proposed calls, evaluates policies, and decides whether the tool execution node is permitted to run.

This architecture is particularly useful when several tools share organizational approval requirements.

Review and execution flow

The following diagram shows how a dedicated review node controls the agent’s execution loop.

Option B: a review node before the tool node diagram: START to Agent Model; Agent Model to Tool Requested?; Tool Requested? to END (No); Tool Requested? to Review Policy (Yes); Review Policy to Review Required?; Review Required? to Tool Node (No); Review Required? to Human Review (Yes); Human Review to Approved?; Approved? to Tool Node (Approve); Approved? to Tool Node (Edit).

Notice that rejection produces a result for the model rather than executing the rejected operation.

In a complete agent loop, the model can use this result to explain the rejection, revise its proposal, or pursue a permitted alternative.

Example: Reviewing and editing tool arguments

The following standalone graph reviews a proposed database update. The demonstration intentionally processes one tool call per turn, making argument replacement and rejection straightforward.

Python
import operator
from typing import Annotated, Literal

from langchain.tools import tool
from langchain.messages import AIMessage, ToolMessage
from langgraph.graph import StateGraph, MessagesState, START, END
from langgraph.prebuilt import ToolNode
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import interrupt, Command

database = {"ORD-101": "pending"}

class ReviewState(MessagesState):
    feedback: Annotated[list[dict], operator.add]

@tool
def update_order(order_id: str, status: str) -> str:
    """Update the status of an existing customer order."""

    if order_id not in database:
        raise ValueError("Unknown order")

    if status not in {"pending", "shipped", "cancelled"}:
        raise ValueError("Invalid order status")

    database[order_id] = status
    return f"Order {order_id} updated to {status}"

def review(
    state: ReviewState
) -> Command[Literal["tools", "__end__"]]:

    message = state["messages"][-1]

    if not isinstance(message, AIMessage):
        raise ValueError("Expected an AIMessage")

    if len(message.tool_calls) != 1:
        raise ValueError("Expected exactly one tool call")

    call = message.tool_calls[0]

    if call["name"] != "update_order":
        raise PermissionError("Unrecognized tool")

    response = interrupt({
        "type": "review_tool_call",
        "tool_call": call,
        "allowed_decisions": ["approve", "edit", "reject"]
    })

    response = response if isinstance(response, dict) else {}

    decision = response.get("decision")
    effective_args = dict(call["args"])

    if decision == "edit":
        edited_status = response.get("status")

        if edited_status in ("pending", "shipped", "cancelled"):
            effective_args["status"] = edited_status
        else:
            decision = "reject"

    if decision not in {"approve", "edit"}:
        decision = "reject"

    feedback = {
        "tool_call_id": call["id"],
        "tool": call["name"],
        "original_arguments": dict(call["args"]),
        "effective_arguments": (
            effective_args if decision != "reject" else None
        ),
        "decision": decision,
        "reason": str(response.get("reason", ""))
    }

    if decision == "reject":
        return Command(
            update={
                "feedback": [feedback],
                "messages": [ToolMessage(
                    content="Order update rejected by reviewer.",
                    tool_call_id=call["id"],
                    status="error"
                )]
            },
            goto=END
        )

    approved_call = {
        **call,
        "args": effective_args
    }

    reviewed_message = message.model_copy(
        update={"tool_calls": [approved_call]}
    )

    return Command(
        update={
            "messages": [reviewed_message],
            "feedback": [feedback]
        },
        goto="tools"
    )

builder = StateGraph(ReviewState)

builder.add_node("review", review)
builder.add_node("tools", ToolNode([update_order]))

builder.add_edge(START, "review")
builder.add_edge("tools", END)

graph = builder.compile(checkpointer=InMemorySaver())

config = {
    "configurable": {"thread_id": "order-review-001"}
}

proposal = AIMessage(
    id="message-001",
    content="",
    tool_calls=[{
        "name": "update_order",
        "args": {
            "order_id": "ORD-101",
            "status": "cancelled"
        },
        "id": "call_order_001",
        "type": "tool_call"
    }]
)

result = graph.invoke({
    "messages": [proposal],
    "feedback": []
}, config)

print("Before review:", database["ORD-101"])
print(result["__interrupt__"][0].value)

result = graph.invoke(
    Command(resume={
        "decision": "edit",
        "status": "shipped",
        "reason": "Warehouse confirmed dispatch."
    }),
    config
)

print("After review:", database["ORD-101"])
print(result["feedback"])

Expected output includes:

Text
Before review: pending
After review: shipped

The feedback record contains both the original proposed status and the corrected status.

Understanding message replacement

MessagesState uses the add_messages reducer for its messages field.

When an incoming message has the same message ID as an existing message, the reducer replaces the existing message rather than appending a duplicate.

The review node preserves the original AIMessage ID while replacing its structured tool arguments. It also preserves the tool-call ID so that the resulting ToolMessage remains correctly associated with the request.

For real provider-generated messages, also account for provider-specific tool-call representations in message metadata. Do not blindly modify normalized tool calls while retaining contradictory provider-specific representations.

The example avoids that complication by constructing a normalized AIMessage directly.

Handling multiple tool calls

Models can propose multiple tool calls in one response.

A production reviewer must explicitly handle every proposed call. Reviewing the first call and forwarding the entire original message to ToolNode can accidentally authorize unreviewed operations.

For mixed batches, maintain individual decisions and return a corresponding tool result for every call before continuing the model loop.

Rejecting a call must not leave its tool-call ID unanswered when that conversation is passed back to the model.

Where parallel tasks produce separate interrupts, LangGraph also supports mapping interrupt IDs to individual resume values.

Using create_agent

LangChain 1.x provides HumanInTheLoopMiddleware, which implements common tool-review workflows without requiring you to manually construct the agent’s review graph.

It integrates with create_agent, which runs on LangGraph.

Configuring approval policies

The middleware accepts an interrupt_on mapping keyed by tool name.

A value of False allows that tool to execute without this middleware’s approval interrupt.

A configuration containing allowed_decisions explicitly limits how a human may respond.

Tools omitted from the mapping are not automatically protected. Maintain a complete tool inventory and verify your policy whenever a new tool is registered.

Example: Agent with approval middleware

This agent can retrieve an order status automatically, but must request approval before sending an email.

The interactive review loop lets you approve or reject each requested sensitive action.

Python
from langchain.agents import create_agent
from langchain.agents.middleware import HumanInTheLoopMiddleware
from langchain.chat_models import init_chat_model
from langchain.tools import tool
from langchain.messages import HumanMessage
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import Command

outbox = []

@tool
def get_order_status(order_id: str) -> str:
    """Retrieve the shipping status of an order."""
    return f"Order {order_id} has shipped."

@tool
def send_email(to: str, subject: str, body: str) -> str:
    """Send an email to a customer."""
    outbox.append({
        "to": to,
        "subject": subject,
        "body": body
    })
    return f"Email sent to {to}"

model = init_chat_model("openai:gpt-5.4-mini")

agent = create_agent(
    model=model,
    tools=[get_order_status, send_email],
    system_prompt=(
        "You are a customer support agent. "
        "Use tools to perform requested operations. "
        "Never claim an email was sent if its call was rejected. "
        "Do not repeat rejected operations."
    ),
    middleware=[
        HumanInTheLoopMiddleware(
            interrupt_on={
                "get_order_status": False,
                "send_email": {
                    "allowed_decisions": [
                        "approve", "edit", "reject"
                    ]
                }
            },
            interrupt_mode="batched",
            description_prefix="Review customer communication"
        )
    ],
    checkpointer=InMemorySaver()
)

config = {
    "configurable": {"thread_id": "support-agent-001"},
    "recursion_limit": 20
}

result = agent.invoke({
    "messages": [HumanMessage(
        content=(
            "Check order ORD-101 and email "
            "customer@example.com with its shipping status."
        )
    )]
}, config)

review_rounds = 0

while result.get("__interrupt__"):
    review_rounds += 1

    if review_rounds > 5:
        raise RuntimeError("Review limit reached; escalate the run")

    pending = result["__interrupt__"][0]
    request = pending.value
    decisions = []

    for action in request["action_requests"]:
        print("Tool:", action["name"])
        print("Arguments:", action["args"])

        choice = input("Approve this exact action? [y/N]: ")

        if choice.strip().lower() == "y":
            decisions.append({"type": "approve"})
        else:
            decisions.append({
                "type": "reject",
                "message": "Reviewer did not authorize this email."
            })

    result = agent.invoke(
        Command(resume={"decisions": decisions}),
        config
    )

print(result["messages"][-1].content)
print("Emails sent:", len(outbox))

The expected sequence is an automatic order lookup, followed by an email approval request. Approving permits the simulated delivery; rejecting prevents that particular call from executing. The model determines its actual tool proposals and final wording.

Editing calls through middleware

Although the interactive example offers only approval and rejection, the configured policy also permits editing.

For a single pending email action, the application could submit this alternative decision:

Python
Command(resume={
    "decisions": [{
        "type": "edit",
        "edited_action": {
            "name": "send_email",
            "args": {
                "to": "customer@example.com",
                "subject": "Shipping confirmation",
                "body": "Your order has been dispatched."
            }
        }
    }]
})

In batched mode, supply one decision for every requested review action, preserving their order.

Recent LangChain 1.x versions also support interrupt_mode="per_call", where gated calls receive individual interrupts and decisions are associated with interrupt IDs.

Another available middleware decision is respond, which substitutes a human-provided tool result without executing the tool. It is appropriate for clarification tools, not for denying sensitive operations; use reject for denial.

See the current LangChain human-in-the-loop documentation for the middleware’s decision schemas.

Choosing an implementation approach

Consideration Interrupt inside tool Dedicated review node Agent middleware
Policy location Tool implementation Graph layer Agent configuration
Reusability Tool-level Workflow-level Agent-level
Custom routing Limited without additional logic Excellent Configurable
Implementation effort Low Higher Low
Best use case Independently protected tools Complex business workflows Conventional tool-calling agents

For standard approval workflows, middleware reduces development effort. Dedicated review nodes are particularly useful when authorization depends on complex state, business thresholds, or specialist routing.

Collecting human feedback

Human review should produce more information than a Boolean approval flag.

A reviewer might identify an incorrect recipient, discover a missing customer consent record, or explain that the proposed operation violates company policy.

Structured feedback makes these decisions useful for both immediate execution and subsequent quality improvement.

Designing feedback records

A useful feedback record contains the following information:

Field Purpose
tool_call_id Identifies the reviewed operation
original_arguments Preserves the model’s proposal
effective_arguments Records the authorized operation
decision Approval, edit, rejection, or escalation
reason Explains the review outcome
reviewer_id Identifies the authenticated reviewer
policy_version Identifies the applicable approval policy
reviewed_at Records the decision timestamp

The review-node example uses an append reducer to preserve feedback across state updates.

Without a reducer, subsequent updates to the feedback field would normally replace its previous value.

Feedback storage and learning

Distinguish between three destinations for human feedback:

  • Graph state: Information needed during the current workflow.
  • Durable audit storage: Evidence required for accountability, compliance, and incident investigation.
  • Evaluation datasets: Reviewed examples used to measure agent performance and improve prompts, policies, or future model training.

Human corrections do not automatically update the underlying model’s weights.

Improvement requires an explicit mechanism, such as retrieving validated preferences, modifying policies, adding evaluation cases, or conducting a separate training process.

Avoid placing unrestricted reviewer comments directly into privileged instructions. Feedback may contain mistakes, confidential information, or malicious instructions. Validate and sanitize it according to its destination.

Escalation mechanisms

Approval answers the question: May this proposed action execute?

Escalation answers a different question: Who should take responsibility for this situation when the agent cannot handle it safely?

An agent should escalate when it encounters insufficient information, conflicting policies, repeated failures, missing permissions, unsupported requests, or decisions outside its authorized scope.

Establish objective escalation triggers

Do not rely exclusively on the model declaring that it lacks confidence.

An LLM’s self-reported confidence is not necessarily a calibrated probability of correctness.

Use measurable signals wherever possible.

For example, escalate when required evidence is missing, a financial threshold is exceeded, two authoritative records disagree, or a bounded retry policy is exhausted.

Different failures require different destinations. A customer may supply missing information, while a finance manager must authorize a payment exception.

Example: Routing uncertain cases to specialists

This example uses deterministic routing to transfer unresolved customer support cases to the appropriate specialist.

Python
from typing import TypedDict, Literal

from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import interrupt, Command

class SupportState(TypedDict):
    case_id: str
    issue: str
    failed_attempts: int
    evidence_verified: bool
    resolution: str

def route_case(state: SupportState) -> Literal[
    "resolve", "escalate"
]:
    if (
        state["issue"] == "billing_dispute"
        or state["failed_attempts"] >= 3
        or not state["evidence_verified"]
    ):
        return "escalate"

    return "resolve"

def resolve(state: SupportState) -> dict:
    return {
        "resolution": "Resolved using verified support policy."
    }

def escalate(state: SupportState) -> dict:
    queue = (
        "billing_specialist"
        if state["issue"] == "billing_dispute"
        else "support_supervisor"
    )

    response = interrupt({
        "type": "escalation",
        "case_id": state["case_id"],
        "assigned_queue": queue,
        "issue": state["issue"],
        "failed_attempts": state["failed_attempts"],
        "evidence_verified": state["evidence_verified"],
        "allowed_decisions": ["resolve", "handoff"]
    })

    if isinstance(response, dict):
        resolution = response.get("resolution")

        if (
            response.get("decision") == "resolve"
            and isinstance(resolution, str)
            and resolution.strip()
        ):
            return {"resolution": resolution}

    return {
        "resolution": "Transferred to human ownership."
    }

builder = StateGraph(SupportState)

builder.add_node("resolve", resolve)
builder.add_node("escalate", escalate)

builder.add_conditional_edges(START, route_case)

builder.add_edge("resolve", END)
builder.add_edge("escalate", END)

graph = builder.compile(checkpointer=InMemorySaver())

config = {
    "configurable": {"thread_id": "case-901"}
}

result = graph.invoke({
    "case_id": "CASE-901",
    "issue": "billing_dispute",
    "failed_attempts": 3,
    "evidence_verified": False,
    "resolution": "pending"
}, config)

print(result["__interrupt__"][0].value)

result = graph.invoke(
    Command(resume={
        "decision": "resolve",
        "resolution": (
            "Billing specialist verified the invoice. "
            "Duplicate charge requires reversal."
        )
    }),
    config
)

print(result["resolution"])

The interrupt identifies billing_specialist as the required queue.

After resumption, the specialist’s resolution becomes part of the graph state.

This example records a simulated handoff or resolution. It does not actually notify a specialist or reverse a payment. A real deployment must integrate those operations separately.

Designing production escalation workflows

An interrupt pauses execution; it does not automatically create a support ticket, send a notification, authenticate a reviewer, or enforce an approval deadline.

A production application must implement these responsibilities around the graph.

The application should create an escalation record, notify the appropriate queue, associate the request with its thread and interrupt IDs, and accept a response only from an authorized reviewer.

It should also support escalation deadlines, reassignment, cancellation, and permanent human ownership.

An expired approval must not silently become an approval.

Production best practices and common mistakes

Enforce authorization outside the model

Never treat a reviewer role supplied through Command(resume=...) as verified identity.

Authenticate the reviewer through your application’s identity system and validate their permissions before resuming the workflow.

Use trusted runtime context when graph nodes require authenticated identity or authorization information. Reconstruct that context from trusted application services on every invocation or resumption.

The thread_id identifies execution state; it is not an authentication credential.

Protect persistence and external operations

InMemorySaver is convenient for development but loses its checkpoints when the process terminates.

Use a durable checkpointer such as PostgresSaver or AsyncPostgresSaver in production, with appropriate database initialization and access controls.

Bind approval to the exact action, effective arguments, policy version, and relevant resource version. Recheck execution-time prerequisites because external state may change while the workflow waits for review.

Tip: Use a stable operation identifier as an idempotency key when calling external services. Do not generate a new identifier during every replay of an interrupted node.

Avoid approval bypasses

Common implementation errors include:

  • Performing irreversible operations before calling interrupt().
  • Catching the interrupt’s internal control-flow exception with broad exception handlers.
  • Routing directly to ToolNode through an unprotected alternative path.
  • Applying both tool-level and middleware approval unintentionally.
  • Allowing edited arguments to bypass validation or authorization.
  • Assuming approval of one operation authorizes all future operations.
  • Allowing unlimited retries or repeated approval requests after rejection.

Explicitly test these failure paths. A rejected request should produce zero protected side effects, and an edited request should execute only its validated, authorized arguments.

For runtime behavior and replay constraints, consult the LangGraph interrupts documentation and the Graph API overview.

Connecting to the next lesson

The next lesson combines these mechanisms into a practical project: an email drafting agent that requires human approval before sending.

You will separate draft generation from delivery, present the recipient and message contents for review, support human corrections, and ensure that rejection prevents transmission.

The architectural principle throughout that project is controlled autonomy: the model may propose an action, but application policy and authorized humans determine whether the action is permitted to execute.

Exercise

Build a refund approval and escalation workflow

Build a customer support workflow that automatically processes refunds of $50 or less, requires human approval for refunds above $50, and escalates refunds above $500 to a finance manager. Use interrupt() to collect the appropriate reviewer's decision and Command to resume execution. Record the decision in graph state and ensure rejected refunds are never processed.

Python
from typing import TypedDict, Literal
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import interrupt, Command

class RefundState(TypedDict):
    order_id: str
    amount_cents: int
    decision: str
    reviewer_role: str
    status: str

def classify(state: RefundState) -> str:
    # TODO: Return automatic, review, or escalate.
    pass

def automatic(state: RefundState) -> dict:
    # TODO: Record automatic approval.
    pass

def review(state: RefundState) -> dict:
    # TODO: Request approval from customer support.
    pass

def escalate(state: RefundState) -> dict:
    # TODO: Request approval from a finance manager.
    pass

def process_refund(state: RefundState) -> dict:
    # TODO: Simulate processing an approved refund.
    pass

def cancel_refund(state: RefundState) -> dict:
    return {"status": "cancelled"}

# TODO: Build the graph, configure conditional edges,
# and compile it with InMemorySaver.

# TODO: Test automatic approval, human approval,
# rejection, and finance escalation.

Summary

  • Classify tools by sensitivity, side effects, reversibility, and business risk before deciding which actions require human approval.
  • Placing interrupt() inside a tool creates a reusable approval mechanism close to the sensitive operation.
  • A dedicated review node centralizes authorization policies and allows proposed tool calls to be inspected before ToolNode executes them.
  • HumanInTheLoopMiddleware provides configurable tool approval workflows for agents constructed with create_agent.
  • Human feedback should be structured, validated, persisted, and communicated appropriately to the agent.
  • Escalation transfers uncertain or unauthorized decisions to an appropriately qualified human rather than allowing the agent to guess.
  • Production approval systems require durable checkpointing, authenticated reviewers, idempotent execution, and enforceable authorization policies.