DEV Community

Wei Chen
Wei Chen

Posted on

Building Reliable AI Agents with LangGraph: Human Approval Before Tool Execution

An AI agent can summarize documents, search databases, and generate reports. Those are relatively safe operations.

But what happens when you give it permission to perform actions?

Imagine an AI agent responsible for managing customer accounts.

A user asks:

Find all inactive customer accounts and disable them.

The agent searches the database, identifies inactive accounts, and prepares an update.

Technically, everything looks correct.

But should the agent immediately execute that update?

What if its definition of "inactive" is wrong? What if an important enterprise customer is included? What if the agent misunderstood the request?

This is where human-in-the-loop workflows become important.

Instead of allowing an AI agent to execute every action automatically, we can pause execution, request approval, and continue only after someone reviews the proposed operation.

LangGraph provides a practical way to build this behavior using state management, checkpoints, and interrupts.

Let's build a simple example and examine the engineering decisions that make it reliable.

1. Why a Prompt Isn't Enough

A common approach to agent safety is adding instructions like:

Never modify customer records without approval.
Always ask the user before performing a dangerous action.
Enter fullscreen mode Exit fullscreen mode

These instructions are useful, but they aren't a reliable enforcement mechanism.

The language model still decides how to interpret them.

For operations involving database updates, payments, emails, or infrastructure changes, approval should be enforced by application code.

The agent can propose an action, but the application should control whether that action is executed.

A better architecture separates three responsibilities:

Component Responsibility
AI model Understand the request and propose an action
Workflow Control execution and approval
Application tools Execute authorized operations

This separation makes the system easier to reason about, test, and audit.

2. Model the Workflow as a Graph

Consider a hypothetical customer-management assistant.

The workflow has three main steps:

User Request
     |
     v
Prepare Action
     |
     v
Human Approval
     |
     +---- Rejected ----> Stop
     |
   Approved
     |
     v
Execute Action
     |
     v
Return Result
Enter fullscreen mode Exit fullscreen mode

Each step has a clear responsibility.

The preparation node creates a proposed operation.

The approval node pauses execution.

The execution node performs the action only when approval is granted.

This is a good fit for LangGraph because the workflow contains explicit state transitions and a point where execution must wait for external input.

The important design decision is that the approval step happens before the side effect.

3. Define the Agent's State

LangGraph uses state to share information between nodes.

Let's define a small workflow state using Python's TypedDict.

from typing import TypedDict


class AgentState(TypedDict):
    request: str
    proposed_action: str
    approved: bool | None
    result: str
Enter fullscreen mode Exit fullscreen mode

For this example, we'll use a fixed action rather than an actual LLM-generated database operation.

That keeps the example focused on workflow control.

In a real application, an LLM could generate a structured action containing the operation type, target records, and parameters.

Those values should be validated against an allowlist before execution.

The model shouldn't be allowed to generate arbitrary SQL and send it directly to a production database.

4. Create the Preparation Node

The first node creates the proposed action.

def prepare_action(state: AgentState):
    return {
        "proposed_action": (
            "Disable inactive customer accounts"
        )
    }
Enter fullscreen mode Exit fullscreen mode

This example deliberately uses a static proposal.

In a real workflow, preparation might involve retrieving customer records, applying business rules, and generating an action preview.

For example, the application could display the number of affected accounts and their identifiers before requesting approval.

That matters because a reviewer cannot make an informed decision from a vague message like "Approve database update?"

Approval should be tied to a specific, reviewable operation.

5. Pause Execution with LangGraph Interrupts

Now comes the interesting part.

LangGraph provides an interrupt() function that pauses graph execution until external input is supplied.

from langgraph.types import interrupt


def review_action(state: AgentState):
    decision = interrupt({
        "question": "Approve this action?",
        "action": state["proposed_action"],
    })

    return {
        "approved": decision["approved"]
    }
Enter fullscreen mode Exit fullscreen mode

When this node executes, LangGraph interrupts the workflow and exposes the approval request to the calling application.

The application can display it in a UI or send it to an authorized reviewer.

The graph doesn't continue until a resume command is supplied.

This is different from asking the LLM whether an operation is safe.

The application controls when execution resumes.

LangGraph's interrupt behavior is documented in its official human-in-the-loop documentation.

6. Execute Only Approved Actions

Next, create the execution node.

def execute_action(state: AgentState):
    if not state["approved"]:
        return {
            "result": "Action rejected"
        }

    # Demonstration only.
    # No database operation is performed.
    return {
        "result": "Approved action simulated"
    }
Enter fullscreen mode Exit fullscreen mode

In production, this node would call a controlled application service.

That service should independently validate permissions, operation parameters, and relevant business rules.

Human approval is not a replacement for authorization.

Even an approved operation must respect tenant isolation, user permissions, and application-level constraints.

For high-impact changes, the reviewed action should be an immutable structured payload. The execution service should verify that it matches what was approved.

7. Connect the Nodes

We can now assemble the workflow.

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


builder = StateGraph(AgentState)

builder.add_node("prepare", prepare_action)
builder.add_node("review", review_action)
builder.add_node("execute", execute_action)

builder.add_edge(START, "prepare")
builder.add_edge("prepare", "review")
builder.add_edge("review", "execute")
builder.add_edge("execute", END)

graph = builder.compile(
    checkpointer=InMemorySaver()
)
Enter fullscreen mode Exit fullscreen mode

The checkpointer is essential.

It stores the workflow state so LangGraph can resume execution after an interruption.

InMemorySaver is suitable for demonstrations and local development. For production, use a persistent checkpointer backed by durable storage.

Otherwise, restarting the application could lose pending approvals.

8. Run, Approve, and Resume

Start the workflow using a unique thread ID.

config = {
    "configurable": {
        "thread_id": "approval-demo-001"
    }
}

initial_state = {
    "request": "Disable inactive accounts",
    "proposed_action": "",
    "approved": None,
    "result": "",
}

response = graph.invoke(
    initial_state,
    config=config,
)

print(response["__interrupt__"])
Enter fullscreen mode Exit fullscreen mode

The workflow pauses in the review node.

At this point, the execution node hasn't run.

After a reviewer makes a decision, resume the same thread:

response = graph.invoke(
    Command(
        resume={"approved": True}
    ),
    config=config,
)

print(response["result"])
Enter fullscreen mode Exit fullscreen mode

The example returns:

Approved action simulated
Enter fullscreen mode Exit fullscreen mode

If the reviewer sends approved: False, the execution node returns "Action rejected" without performing the simulated action.

Notice that the same thread_id is used for both calls.

LangGraph uses it to locate the saved workflow state.

9. Understand the Restart Behavior

There's a subtle detail that can cause problems in real systems.

When an interrupted node resumes, LangGraph restarts execution from the beginning of that node.

Code before interrupt() may run again.

Consider this dangerous pattern:

def review_action(state):
    charge_customer()

    approved = interrupt(
        "Approve this payment?"
    )

    return {"approved": approved}
Enter fullscreen mode Exit fullscreen mode

This is incorrect for two reasons.

First, the payment happens before approval.

Second, the payment function may execute again when the node resumes.

A safer design puts external side effects in a separate execution node after approval.

For operations that must survive failures and retries, use idempotency keys and an appropriate durable operation record.

LangGraph checkpointing does not automatically guarantee exactly-once execution of external API calls.

This distinction is particularly important for payments, customer updates, and infrastructure operations.

10. What I Would Add Before Production

The example demonstrates the core workflow, but a production approval system needs additional safeguards.

I'd focus on these areas:

Authorization: Verify that the reviewer has permission to approve the specific operation. Don't trust a client-supplied approved value without authentication and authorization.

Action integrity: Store the exact structured action being approved. If its targets or parameters change, require another review.

Timeouts and cancellation: Define what happens when nobody responds. Some actions should expire rather than remain executable indefinitely.

Idempotency: Prevent repeated execution if a worker crashes or an external API times out.

Audit logging: Record who approved the action, what was approved, and the execution result.

Testing: Test rejection, restart recovery, concurrent approval attempts, and external tool failures.

There is also a practical cost trade-off.

Human approval increases latency and operational workload. Requiring approval for every harmless read operation would make the agent frustrating to use.

A better design classifies actions by risk.

Read-only searches can usually execute automatically. Sensitive writes, destructive operations, and high-impact external actions should pass through stronger controls.

The approval policy should reflect the consequences of an incorrect action, not simply whether an LLM is involved.

11. When LangGraph Is Worth Using

You don't need LangGraph for every AI application.

If your application performs one LLM call and returns a response, a straightforward function may be simpler.

LangGraph becomes more useful when your workflow includes multiple steps, conditional routing, tool execution, persistent state, or human intervention.

Its persistence layer also distinguishes thread-scoped checkpoints from longer-term application memory, which is useful when workflows need to resume or share information across interactions. See the LangGraph persistence documentation.

The main benefit isn't making the agent more autonomous.

It's making its behavior more predictable and controllable.

Final Thoughts

AI agents become more useful when they can take actions. They also become more risky.

For sensitive operations, relying on prompts alone isn't enough.

Three principles are worth remembering:

  1. Separate decisions from execution. Let the model propose actions while application code enforces approval.
  2. Design for interruption and recovery. Persist state and account for nodes that may execute again.
  3. Keep authorization and idempotency outside the model. Approval doesn't replace traditional backend safeguards.

LangGraph provides useful building blocks for these workflows, but reliability still depends on how we design the surrounding application.

Top comments (0)