Agent Frameworks

Mastering Human-in-the-Loop with LangGraph: Interrupts and State Persistence

In the realm of autonomous AI agents, trust is the primary currency. While LLMs are becoming increasingly capable, deploying them in high-stakes environments—such as financial transactions, medical diagnostics, or legal compliance—requires a robust mechanism for human oversight. LangGraph, an open-source framework from LangChain, addresses this need by providing first-class support for Human-in-the-Loop (HITL) patterns. By leveraging interrupts and state persistence, developers can build agents that pause, wait for human approval, and resume seamlessly.

Why Human-in-the-Loop Matters

Traditional agent frameworks often execute tools in a single, uninterrupted chain. If an LLM decides to delete a database table or send a sensitive email, there is often no way to stop it once the process has begun. HITL patterns introduce a "circuit breaker." In LangGraph, this is achieved by breaking the agent’s execution graph into distinct nodes. When a critical node is reached, the graph can be paused, the state saved, and control handed back to the user.

Core Concepts: Checkpointers and Interrupts

To implement this, you need two main components:

  1. Checkpointers: These handle state persistence. They save the graph's state at every node execution, allowing you to reload and resume the workflow later. LangGraph supports various backends, including in-memory (for development) and Postgres/Redis (for production).
  2. Interrupts: A special command that halts execution. When the graph encounters an Interrupt object, it stops and waits for external input.

Implementation Guide

Let's look at a practical example where an agent requires approval before sending an email. We will use the SQliteSaver for simple local persistence.

import os
from typing import TypedDict, Annotated
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.sqlite import SqliteSaver
from langgraph.types import Command, Interrupt

class AgentState(TypedDict):
    messages: Annotated[list, "List of messages"]
    draft_email: str
    approval: bool

def draft_email_node(state: AgentState) -> dict:
    # Simulate LLM generating an email
    state["draft_email"] = "Dear Client, please find attached the invoice."
    return {"draft_email": state["draft_email"]}

def request_approval_node(state: AgentState) -> Command:
    # This pauses the graph
    return Command(
        update={},
        interrupt=Interrupt(
            value=state["draft_email"],
            id="approval_needed",
            resume={"approval": False} # Default resume value if not provided
        )
    )

def send_email_node(state: AgentState) -> dict:
    if not state["approval"]:
        raise ValueError("Email was not approved")
    print(f"Sending email: {state['draft_email']}")
    return {}

# Build the graph
builder = StateGraph(AgentState)
builder.add_node("draft_email", draft_email_node)
builder.add_node("request_approval", request_approval_node)
builder.add_node("send_email", send_email_node)

builder.add_edge(START, "draft_email")
builder.add_edge("draft_email", "request_approval")
builder.add_conditional_edges(
    "request_approval",
    lambda state: "send_email" if state.get("approval") else END,
    {"send_email": "send_email", "END": END}
)
builder.add_edge("send_email", END)

# Initialize with persistence
saver = SqliteSaver.from_conn_string(":memory:")
graph = builder.compile(checkpointer=saver, interrupt_before=["request_approval"])

# Run the agent
config = {"configurable": {"thread_id": "thread-1"}}
result = graph.invoke(
    {"messages": [{"role": "user", "content": "Send invoice"}]},
    config
)

Handling the Resume

After the graph pauses at request_approval, the user reviews the draft_email. Once they make a decision, you can resume the graph by passing a Command object with the updated state.

# Simulate user approval
resume_command = Command(
    resume={
        "approval": True,
        "messages": [{"role": "user", "content": "Approved."}]
    },
    id="approval_needed"
)

# Resume execution
result = graph.invoke(resume_command, config)
print(result)

Best Practices for Production

  • Thread IDs: Always use unique thread_ids in your configuration to ensure each conversation has its own isolated state history.
  • Error Handling: Define default resume values in the Interrupt object. If a user fails to provide input, the agent can gracefully terminate or take a safe action.
  • UI Integration: Use the astream_events method to stream the paused state to your frontend, displaying the pending approval prompt to the user in real-time.

Conclusion

LangGraph’s support for interrupts and state persistence transforms AI agents from reckless automations into reliable, auditable workflow participants. By carefully designing your graph to pause at critical decision points, you ensure that human intelligence remains in the loop exactly where it matters most. As agent complexity grows, these patterns will become essential for building trustworthy enterprise AI systems.

Share: