1. Architectural Purpose & Mental Model
In enterprise systems, granting autonomous agents unchecked execution permissions is hazardous. High-stakes actions (publishing content to corporate social channels, executing database migrations, sending client emails, transferring funds) require Human-in-the-Loop (HITL) governance.
How HITL Works in LangGraph:
- Dynamic Pause (
interrupt()): The graph runs autonomously until it reaches an approval gate. It pauses mid-execution, freezing the state snapshot in the checkpointer. - Out-of-Band Human Review: A human manager reviews the drafted content via a web UI or CLI at their own pace (seconds, hours, or days later).
- Resumption via
Command: The human submits feedback ("Approve"or"Make it shorter"). LangGraph unfreezes the graph and injects the human's response directly into the waiting node.
2. Architecture Diagram
flowchart LR
START(["START"]) --> W["Writer node"] --> H["Human node<br/><small>interrupt() · pauses here<br/>waits for Command(resume=...)</small>"] --> G{"Gate"}
G -- "feedback given" --> W
G -- "approved" --> END(["END"])
classDef term fill:#0e3b3a,stroke:#0e3b3a,color:#ffffff,font-weight:bold
classDef gate fill:#fdf1ec,stroke:#c9583a,color:#7a2e1a
classDef store fill:#f5f5f4,stroke:#57534e,color:#292524
classDef c0 fill:#d4ecea,stroke:#2a7a79,color:#0e3b3a
classDef c1 fill:#fbe5dc,stroke:#c9583a,color:#7a2e1a
classDef c2 fill:#e3f5ee,stroke:#4aa58a,color:#14463a
classDef c3 fill:#f6f4f0,stroke:#a7a29a,color:#3f3b35
classDef c4 fill:#eef7f7,stroke:#1a5c5b,color:#0e3b3a
class START term
class W c0
class H c1
class G gate
class END term+-----------------------------------------------------------------------------------------+
| HUMAN-IN-THE-LOOP APPROVAL WORKFLOW |
+-----------------------------------------------------------------------------------------+
| |
| ┌──────────────────────────────────────────────┐ |
| │ │ |
| ▼ │ (Feedback provided) |
| [START] ───> [Writer Node] ───> [Human Node (interrupt)] ───> [Gate] |
| │ │ |
| ▼ └───> [END] (Approved) |
| (Execution Pauses) |
| (Awaits Command(resume=...)) |
+-----------------------------------------------------------------------------------------+
3. The Modern LangGraph HITL Primitives
Unlike older callback systems, modern LangGraph uses native, functional primitives:
interrupt(value): Halts node execution and serializesvalueinto the state checkpoint for the caller to inspect.Command(resume=input_data): When callingapp.invoke()to resume a paused thread,Command(resume=...)provides the human input to the exact line whereinterrupt()was called.
4. Production Python Implementation (human_in_loop.py)
Code · 109 lines03_human_in_loop.pyShow here
from dotenv import load_dotenv
load_dotenv()
from typing import TypedDict
from langchain.chat_models import init_chat_model
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import MemorySaver
from langgraph.types import interrupt, Command
model = init_chat_model("mistralai:mistral-small-2603", temperature=0.7)
parser = StrOutputParser()
# 1. State Schema
class State(TypedDict):
topic: str
draft: str
human_feedback: str
is_approved: bool
# 2. Prompts
writer_prompt = ChatPromptTemplate.from_messages([
("system", "You are an expert LinkedIn copywriter. Write a high-engagement post under 100 words. Strong hook, no hashtags."),
("human", """Topic: {topic}
Previous Draft: {draft}
Human Feedback to incorporate: {feedback}
If no feedback is provided, write a great initial post.
If human feedback is provided, revise the draft precisely as requested!""")
])
# 3. Worker Node: Writer
def writer_node(state: State) -> dict:
chain = writer_prompt | model | parser
new_draft = chain.invoke({
"topic": state["topic"],
"draft": state.get("draft", ""),
"feedback": state.get("human_feedback", "")
})
return {"draft": new_draft}
# 4. Human Approval Node (Dynamic Breakpoint)
def human_node(state: State) -> dict:
# Execution halts here! The dict is sent to the client.
human_input = interrupt({
"instruction": "Please review the draft below and reply 'approve' or provide revision feedback.",
"draft": state["draft"]
})
# When resumed via Command(resume=...), human_input receives the response
is_approved = human_input.strip().lower() in ["approve", "approved", "yes", "y", "ok"]
return {
"human_feedback": human_input,
"is_approved": is_approved
}
# 5. Routing Function
def human_decision_gate(state: State) -> str:
if state["is_approved"]:
return "approved_exit"
return "revise_draft"
# 6. Graph Construction
builder = StateGraph(State)
builder.add_node("writer", writer_node)
builder.add_node("human", human_node)
builder.add_edge(START, "writer")
builder.add_edge("writer", "human")
builder.add_conditional_edges(
"human",
human_decision_gate,
{
"approved_exit": END,
"revise_draft": "writer"
}
)
# HITL strictly requires a checkpointer to preserve state across interrupts
memory = MemorySaver()
app = builder.compile(checkpointer=memory)
# 7. Execution Simulation
config = {"configurable": {"thread_id": "review_session_101"}}
print("=== STEP 1: INITIAL GENERATION (Will halt at Human Node) ===")
app.invoke({"topic": "Why AI Agents require human oversight in production"}, config=config)
# Inspect the state while paused
state_snapshot = app.get_state(config)
print("\n[PAUSED EXECUTION STATE]")
print("Next Node Scheduled:", state_snapshot.next)
print("Draft to Review:\n", state_snapshot.values.get("draft"))
# Resume execution with human feedback
print("\n=== STEP 2: RESUMING WITH HUMAN FEEDBACK ===")
app.invoke(Command(resume="Make the opening hook more controversial and shorter."), config=config)
# Inspect revised draft (will pause again for final sign-off!)
revised_snapshot = app.get_state(config)
print("\n[REVISED DRAFT AFTER FEEDBACK]:\n", revised_snapshot.values.get("draft"))
# Final sign-off
print("\n=== STEP 3: FINAL APPROVAL ===")
app.invoke(Command(resume="Approve"), config=config)
final_state = app.get_state(config)
print("\nWorkflow Finished! Final Approval Status:", final_state.values.get("is_approved"))
5. Key Takeaways
- Mandatory Checkpointer:
interrupt()will fail at runtime if the graph is compiled without a checkpointer. The checkpointer is what preserves thread state during the pause. - Asynchronous Execution: In production web applications (FastAPI/Django), Step 1 is executed by a background job, the draft is displayed on a frontend dashboard, and Step 2 is called via an HTTP POST endpoint when the user clicks "Approve".
- Time Travel & Auditing: Every human revision is logged as a distinct checkpoint, providing an audit trail of changes before publishing.
Code
03_human_in_loop.py03_human_in_loop.py · 105 linesShow code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 | from dotenv import load_dotenv load_dotenv() from typing import TypedDict from langchain.chat_models import init_chat_model from langchain_core.prompts import ChatPromptTemplate from langchain_core.output_parsers import StrOutputParser from langgraph.graph import StateGraph, START, END from langgraph.checkpoint.memory import MemorySaver from langgraph.types import interrupt , Command load_dotenv() model = init_chat_model("mistralai:open-mistral-nemo", temperature=0.7) parser = StrOutputParser() class State(TypedDict): topic:str draft:str human_feedback:str is_approved:bool writer_prompt = ChatPromptTemplate.from_messages([ ("system", """You are an expert LinkedIn copywriter. Write a high-engagement post. Rules: Strong hook in line 1, short paragraphs, under 150 words, ends with a question, no hashtags."""), ("human", """Topic: {topic} Previous Draft: {draft} Human Feedback to incorporate: {feedback} If no feedback is provided, write a great initial post. If human feedback is provided, revise the draft precisely as requested by the human!""") ]) def writer_node(state:State)->dict: chain = writer_prompt | model | parser new_draft = chain.invoke({ "topic":state["topic"], "draft":state["draft"], "feedback":state["human_feedback"] }) return {"draft":new_draft} """interrupt() pauses the graph here and waits for a human""" def human_node(state:State)->dict: human_input= interrupt({ "message":"please review the draft below", "draft":state["draft"] }) is_approved=human_input.strip().lower() in ["approve","approved","yes","y","ok"] return { "human_feedback":human_input, "is_approved":is_approved } def human_decision_gate(state:State)->str: if state["is_approved"]: return END else: print(f"\n Human requested changes: '{state['human_feedback']}'. Sending back to AI Writer...") return "writer" workflow = StateGraph(State) workflow.add_node("writer",writer_node) workflow.add_node("human_review",human_node) workflow.add_edge(START,"writer") workflow.add_edge("writer","human_review") workflow.add_conditional_edges("human_review",human_decision_gate) memory = MemorySaver() app = workflow.compile(checkpointer=memory) topic = input("\nEnter LinkedIn Topic: ").strip() config= {"configurable":{"thread_id":"session_001"}} # Step 1: Initial Run (Runs writer -> pauses at human_review) initial_state = { "topic": topic, "draft": "", "human_feedback": "", "is_approved": False } result = app.invoke(initial_state , config=config) """Command(resume=...) sends the human answer back and the graph continues""" while True: state_snapshot = app.get_state(config) if not state_snapshot.next: break; current_draft = state_snapshot.values.get("draft") print(f"[AI GENERATED DRAFT]:\n\n{current_draft}") feedback = input("\nType 'approve' to publish, OR type your feedback/changes:\n> ").strip() result = app.invoke(Command(resume=feedback),config=config) |