- HumanInTheLoopMiddleware / humanInTheLoopMiddleware: Pause before dangerous tool calls for human approval
- Custom middleware: Intercept tool calls for error handling, logging, retry logic
- Command resume: Continue execution after human decisions (approve, edit, reject)
Requirements: Checkpointer + thread_id config for all HITL workflows.
Human-in-the-Loop
@tool
def send_email(to: str, subject: str, body: str) -> str:
"""Send an email."""
return f"Email sent to {to}"
agent = create_agent(
model="gpt-4.1",
tools=[send_email],
checkpointer=MemorySaver(), # Required for HITL
middleware=[
HumanInTheLoopMiddleware(
interrupt_on={
"send_email": {"allowed_decisions": ["approve", "edit", "reject"]},
}
)
],
)
</python>
<typescript>
Set up an agent with HITL that pauses before sending emails for human approval.
```typescript
import { createAgent, humanInTheLoopMiddleware } from "langchain";
import { MemorySaver } from "@langchain/langgraph";
import { tool } from "@langchain/core/tools";
import { z } from "zod";
const sendEmail = tool(
async ({ to, subject, body }) => `Email sent to ${to}`,
{
name: "send_email",
description: "Send an email",
schema: z.object({ to: z.string(), subject: z.string(), body: z.string() }),
}
);
const agent = createAgent({
model: "anthropic:claude-sonnet-4-5",
tools: [sendEmail],
checkpointer: new MemorySaver(),
middleware: [
humanInTheLoopMiddleware({
interruptOn: { send_email: { allowedDecisions: ["approve", "edit", "reject"] } },
}),
],
});
config = {"configurable": {"thread_id": "session-1"}}
Step 1: Agent runs until it needs to call tool
result1 = agent.invoke({
"messages": [{"role": "user", "content": "Send email to john@example.com"}]
}, config=config)
Check for interrupt
if "interrupt" in result1:
print(f"Waiting for approval: {result1['interrupt']}")
Step 2: Human approves
result2 = agent.invoke(
Command(resume={"decisions": [{"type": "approve"}]}),
config=config
)
</python>
<typescript>
Run the agent, detect an interrupt, then resume execution after human approval.
```typescript
import { Command } from "@langchain/langgraph";
const config = { configurable: { thread_id: "session-1" } };
// Step 1: Agent runs until it needs to call tool
const result1 = await agent.invoke({
messages: [{ role: "user", content: "Send email to john@example.com" }]
}, config);
// Check for interrupt
if (result1.__interrupt__) {
console.log(`Waiting for approval: ${result1.__interrupt__}`);
}
// Step 2: Human approves
const result2 = await agent.invoke(
new Command({ resume: { decisions: [{ type: "approve" }] } }),
config
);
- Which tools require approval (per-tool policies)
- Allowed decisions per tool (approve, edit, reject)
- Custom middleware hooks:
before_model, after_model, wrap_tool_call, before_agent, after_agent
- Tool-specific middleware (apply only to certain tools)
What You CANNOT Configure
- Interrupt after tool execution (must be before)
- Skip checkpointer requirement for HITL
CORRECT
agent = create_agent(
model="gpt-4.1", tools=[send_email],
checkpointer=MemorySaver(), # Required
middleware=[HumanInTheLoopMiddleware({...})]
)
</python>
<typescript>
HITL requires a checkpointer to persist state.
```typescript
// WRONG: No checkpointer
const agent = createAgent({
model: "anthropic:claude-sonnet-4-5", tools: [sendEmail],
middleware: [humanInTheLoopMiddleware({ interruptOn: { send_email: true } })],
});
// CORRECT: Add checkpointer
const agent = createAgent({
model: "anthropic:claude-sonnet-4-5", tools: [sendEmail],
checkpointer: new MemorySaver(),
middleware: [humanInTheLoopMiddleware({ interruptOn: { send_email: true } })],
});
CORRECT
agent.invoke(input, config={"configurable": {"thread_id": "user-123"}})
</python>
</fix-no-thread-id>
<fix-wrong-resume-syntax>
<python>
Use Command class to resume execution after an interrupt.
```python
# WRONG
agent.invoke({"resume": {"decisions": [...]}})
# CORRECT
from langgraph.types import Command
agent.invoke(Command(resume={"decisions": [{"type": "approve"}]}), config=config)
// CORRECT
import { Command } from "@langchain/langgraph";
await agent.invoke(new Command({ resume: { decisions: [{ type: "approve" }] } }), config);
</typescript>
</fix-wrong-resume-syntax>
1---2name: langchain-middleware3description: "INVOKE THIS SKILL when you need human-in-the-loop approval, custom middleware, or structured output. Covers HumanInTheLoopMiddleware for human approval of dangerous tool calls, creating custom middleware with hooks, Command resume patterns, and structured output with Pydantic/Zod."4metadata:5 source: https://skillmd.com/skills/harmeet10000/langchain-middleware6---78<overview>9Middleware patterns for production LangChain agents:1011- **HumanInTheLoopMiddleware** / **humanInTheLoopMiddleware**: Pause before dangerous tool calls for human approval12- **Custom middleware**: Intercept tool calls for error handling, logging, retry logic13- **Command resume**: Continue execution after human decisions (approve, edit, reject)1415**Requirements:** Checkpointer + thread_id config for all HITL workflows.16</overview>1718---1920## Human-in-the-Loop2122<ex-basic-hitl-setup>23<python>24Set up an agent with HITL middleware that pauses before sending emails for approval.25```python26from langchain.agents import create_agent27from langchain.agents.middleware import HumanInTheLoopMiddleware28from langgraph.checkpoint.memory import MemorySaver29from langchain.tools import tool3031@tool32def send_email(to: str, subject: str, body: str) -> str:33 """Send an email."""34 return f"Email sent to {to}"3536agent = create_agent(37 model="gpt-4.1",38 tools=[send_email],39 checkpointer=MemorySaver(), # Required for HITL40 middleware=[41 HumanInTheLoopMiddleware(42 interrupt_on={43 "send_email": {"allowed_decisions": ["approve", "edit", "reject"]},44 }45 )46 ],47)48```49</python>50<typescript>51Set up an agent with HITL that pauses before sending emails for human approval.52```typescript53import { createAgent, humanInTheLoopMiddleware } from "langchain";54import { MemorySaver } from "@langchain/langgraph";55import { tool } from "@langchain/core/tools";56import { z } from "zod";5758const sendEmail = tool(59 async ({ to, subject, body }) => `Email sent to ${to}`,60 {61 name: "send_email",62 description: "Send an email",63 schema: z.object({ to: z.string(), subject: z.string(), body: z.string() }),64 }65);6667const agent = createAgent({68 model: "anthropic:claude-sonnet-4-5",69 tools: [sendEmail],70 checkpointer: new MemorySaver(),71 middleware: [72 humanInTheLoopMiddleware({73 interruptOn: { send_email: { allowedDecisions: ["approve", "edit", "reject"] } },74 }),75 ],76});77```78</typescript>79</ex-basic-hitl-setup>8081<ex-running-with-interrupts>82<python>83Run the agent, detect an interrupt, then resume execution after human approval.84```python85from langgraph.types import Command8687config = {"configurable": {"thread_id": "session-1"}}8889# Step 1: Agent runs until it needs to call tool90result1 = agent.invoke({91 "messages": [{"role": "user", "content": "Send email to john@example.com"}]92}, config=config)9394# Check for interrupt95if "__interrupt__" in result1:96 print(f"Waiting for approval: {result1['__interrupt__']}")9798# Step 2: Human approves99result2 = agent.invoke(100 Command(resume={"decisions": [{"type": "approve"}]}),101 config=config102)103```104</python>105<typescript>106Run the agent, detect an interrupt, then resume execution after human approval.107```typescript108import { Command } from "@langchain/langgraph";109110const config = { configurable: { thread_id: "session-1" } };111112// Step 1: Agent runs until it needs to call tool113const result1 = await agent.invoke({114 messages: [{ role: "user", content: "Send email to john@example.com" }]115}, config);116117// Check for interrupt118if (result1.__interrupt__) {119 console.log(`Waiting for approval: ${result1.__interrupt__}`);120}121122// Step 2: Human approves123const result2 = await agent.invoke(124 new Command({ resume: { decisions: [{ type: "approve" }] } }),125 config126);127```128</typescript>129</ex-running-with-interrupts>130131<ex-editing-tool-arguments>132<python>133Edit the tool arguments before approving when the original values need correction.134```python135# Human edits the arguments — edited_action must include name + args136result2 = agent.invoke(137 Command(resume={138 "decisions": [{139 "type": "edit",140 "edited_action": {141 "name": "send_email",142 "args": {143 "to": "alice@company.com", # Fixed email144 "subject": "Project Meeting - Updated",145 "body": "...",146 },147 },148 }]149 }),150 config=config151)152```153</python>154<typescript>155Edit the tool arguments before approving when the original values need correction.156```typescript157// Human edits the arguments — editedAction must include name + args158const result2 = await agent.invoke(159 new Command({160 resume: {161 decisions: [{162 type: "edit",163 editedAction: {164 name: "send_email",165 args: {166 to: "alice@company.com", // Fixed email167 subject: "Project Meeting - Updated",168 body: "...",169 },170 },171 }]172 }173 }),174 config175);176```177</typescript>178</ex-editing-tool-arguments>179180<ex-rejecting-with-feedback>181<python>182Reject a tool call and provide feedback explaining why it was rejected.183```python184# Human rejects185result2 = agent.invoke(186 Command(resume={187 "decisions": [{188 "type": "reject",189 "feedback": "Cannot delete customer data without manager approval",190 }]191 }),192 config=config193)194```195</python>196</ex-rejecting-with-feedback>197198<ex-multiple-tools-different-policies>199<python>200Configure different HITL policies for each tool based on risk level.201```python202agent = create_agent(203 model="gpt-4.1",204 tools=[send_email, read_email, delete_email],205 checkpointer=MemorySaver(),206 middleware=[207 HumanInTheLoopMiddleware(208 interrupt_on={209 "send_email": {"allowed_decisions": ["approve", "edit", "reject"]},210 "delete_email": {"allowed_decisions": ["approve", "reject"]}, # No edit211 "read_email": False, # No HITL for reading212 }213 )214 ],215)216```217</python>218</ex-multiple-tools-different-policies>219220<boundaries>221### What You CAN Configure222223- Which tools require approval (per-tool policies)224- Allowed decisions per tool (approve, edit, reject)225- Custom middleware hooks: `before_model`, `after_model`, `wrap_tool_call`, `before_agent`, `after_agent`226- Tool-specific middleware (apply only to certain tools)227228### What You CANNOT Configure229230- Interrupt after tool execution (must be before)231- Skip checkpointer requirement for HITL232</boundaries>233234<fix-missing-checkpointer>235<python>236HITL middleware requires a checkpointer to persist state.237```python238# WRONG239agent = create_agent(model="gpt-4.1", tools=[send_email], middleware=[HumanInTheLoopMiddleware({...})])240241# CORRECT242agent = create_agent(243 model="gpt-4.1", tools=[send_email],244 checkpointer=MemorySaver(), # Required245 middleware=[HumanInTheLoopMiddleware({...})]246)247```248</python>249<typescript>250HITL requires a checkpointer to persist state.251```typescript252// WRONG: No checkpointer253const agent = createAgent({254 model: "anthropic:claude-sonnet-4-5", tools: [sendEmail],255 middleware: [humanInTheLoopMiddleware({ interruptOn: { send_email: true } })],256});257258// CORRECT: Add checkpointer259const agent = createAgent({260 model: "anthropic:claude-sonnet-4-5", tools: [sendEmail],261 checkpointer: new MemorySaver(),262 middleware: [humanInTheLoopMiddleware({ interruptOn: { send_email: true } })],263});264```265</typescript>266</fix-missing-checkpointer>267268<fix-no-thread-id>269<python>270Always provide thread_id when using HITL to track conversation state.271```python272# WRONG273agent.invoke(input) # No config!274275# CORRECT276agent.invoke(input, config={"configurable": {"thread_id": "user-123"}})277```278</python>279</fix-no-thread-id>280281<fix-wrong-resume-syntax>282<python>283Use Command class to resume execution after an interrupt.284```python285# WRONG286agent.invoke({"resume": {"decisions": [...]}})287288# CORRECT289from langgraph.types import Command290agent.invoke(Command(resume={"decisions": [{"type": "approve"}]}), config=config)291```292</python>293<typescript>294Use Command class to resume execution after an interrupt.295```typescript296// WRONG297await agent.invoke({ resume: { decisions: [...] } });298299// CORRECT300import { Command } from "@langchain/langgraph";301await agent.invoke(new Command({ resume: { decisions: [{ type: "approve" }] } }), config);302```303</typescript>304</fix-wrong-resume-syntax>