LangChain Human-in-the-Loop - Human-in-the-Loop (HITL)
In real AI Agent applications, not all operations are suitable for automatic execution by the model.
For example, operations such as sending emails, deleting data, modifying databases, and executing payments may affect real business, so they usually require human confirmation.
LangChain provides the Human-in-the-Loop (HITL) mechanism, which lets the Agent pause before executing critical operations, wait for human approval, and then decide whether to continue, modify, or cancel.
This chapter is based on LangChain 1.x and LangGraph, introducing interrupt()、Command(resume=...)、HumanInTheLoopMiddleware, static breakpoints, and a web approval architecture.
I. What is Human-in-the-Loop HITL?
Human-in-the-Loop refers to retaining a human decision step in an AI automation flow.
For example, an administrator asks the Agent to delete a course:
管理员:删除《过时的 Java 教程》
↓
Agent 理解任务
↓
准备执行删除工具
↓
暂停执行
↓
人工查看操作内容
↓
┌───────────────┐
│ │
批准 拒绝
│ │
执行删除 取消删除
│ │
└───────┬───────┘
↓
返回最终结果
The role of HITL is not to let the model judge "whether authorization has been granted" itself, but to let an external trusted system truly participate in the decision.
Common scenarios include:
| Scenario | Operation requiring approval | Main risk |
|---|---|---|
| Email assistant | Send email | Accidental sending, sensitive information leakage |
| Course management | Delete or publish courses | Accidental deletion, erroneous publishing |
| Database assistant | Execute UPDATE, DELETE | Data corruption |
| Financial system | Payments, refunds, transfers | Financial loss |
| Operations Agent | Modify configurations, execute commands | Service interruption |
II. LangChain's Three Interrupt Mechanisms
LangChain and LangGraph mainly provide three human-in-the-loop approaches.
| Method | How It Works | Applicable scenarios |
|---|---|---|
interrupt() |
Dynamically pause inside the code | Custom approvals, form input |
HumanInTheLoopMiddleware |
Intercept specific tool calls and request approval | General Agent tool review |
interrupt_before / interrupt_after |
Pause before and after graph nodes | Debugging, execution checkpoints |
For most Agents that need to review tool calls, it is recommended to prefer HumanInTheLoopMiddleware。
If you need more complex custom business flows, you can directly use interrupt()。
III. interrupt(): Dynamically Pause Execution
interrupt() is a dynamic interrupt function provided by LangGraph.
When execution reaches this function, the graph pauses and returns an approval or input request to the external caller.
Basic usage:
from langgraph.types import interrupt
decision = interrupt({
"action": "delete_course",
"message": "确认删除课程?"
})
After the external system receives the interrupt information, a human makes the decision.
Then, through:
Command(resume={"approved": True})
resume execution.
Prerequisites for interrupt()
Normal use requires three key elements:
- A Checkpointer to save the execution state when paused.
- A stable
thread_id, used to resume the correct conversation. - A serializable interrupt payload used to display approval content externally.
**Important:** On resume, the node containing interrupt() is re-executed; only when the corresponding interrupt() is reached again will it receive the value previously passed via resume.
Therefore, you should not perform operations with non-repeatable side effects before interrupt().
IV. Using interrupt() Inside a Tool
Below, we create a mock course deletion tool.
The tool first pauses and requests approval, and only executes the mock deletion logic if approval is granted.
Example: Approval for mock course deletion
Example
from
langchain.
tools
import
tool
from
langgraph.
types
import
interrupt
@
tool
def
delete_course
(
course_name:
str
)
str
:
"""Mock deletion of a specified course; human approval must be obtained before execution."""
decision
=
interrupt
(
{
"action"
:
"delete_course"
,
"course"
: course_name
,
"message"
: f
"Confirm deletion of '{course_name}'?"
}
)
if
not
isinstance
(
decision
,
dict
)
or
decision.
get
(
"approved"
)
is
not
True
:
return
f
"Deletion of '{course_name}' cancelled"
For teaching demonstration; does not perform real database deletion
return
f
"Mock deletion successful: '{course_name}'"
The interrupt request here contains the operation type, course name, and prompt information.
When resuming, pass in:
{"approved": True}
to indicate human approval.
Pass in:
{"approved": False}
to cancel the operation.
**Note:** The above is only a teaching simulation. A real deletion tool must re-check the operator's permissions at execution time and use a trusted backend to perform the database operation.
V. Complete Example: Pause, Approve, Resume
Next, we connect the tool to the Agent to complete a full HITL flow.
Install dependencies:
pip install -U langchain langgraph langchain-deepseek python-dotenv
Configure .env:
DEEPSEEK_API_KEY=your_deepseek_api_key
Filename:hitl_interrupt_demo.py
Complete example
from
dotenv
import
load_dotenv
from
langchain.
agents
import
create_agent
from
langchain.
tools
import
tool
from
langgraph.
types
import
interrupt
,
Command
from
langgraph.
checkpoint
.
memory
import
InMemorySaver
load_dotenv
(
)
@
tool
def
delete_course
(
course_name:
str
)
str
:
"""Mock course deletion; approval must be obtained first."""
decision
=
interrupt
(
{
"action"
:
"delete_course"
,
"course"
: course_name
,
"message"
: f
"Delete '{course_name}'?"
}
)
if
not
isinstance
(
decision
,
dict
)
or
decision.
get
(
"approved"
)
is
not
True
:
return
"Administrator refused deletion; no operation performed"
return
f
"Mock-deleted '{course_name}'"
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
delete_course
]
,
checkpointer
=
InMemorySaver
(
)
,
system_prompt
=
"You are a course management assistant. When the user asks to delete a course, use delete_course; do not claim that a real database operation was performed."
)
config
=
{
"configurable"
:
{
"thread_id"
:
"approval-001"
}
}
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Please use the tool to mock-delete the 'Outdated Java Tutorial'."
}
]
}
,
config
=
config
)
pending
=
result.
get
(
"interrupt"
,
(
)
)
if
pending:
(
"Waiting for human approval:"
,
pending
[
0
]
.
value
)
Demonstrating human approval; a real application must obtain the decision from an authenticated approval interface
result
=
agent.
invoke
(
Command
(
resume
=
{
"approved"
:
True
}
)
,
config
=
config
)
if
result.
get
(
"interrupt"
)
:
(
"Approval still pending"
)
else
:
(
"Execution result:"
,
result
[
"messages"
]
[
1
]
.
content
)
Possible run results
等待人工审批: {'action': 'delete_course', 'course': '过时的 Java 教程', ...}
执行结果: 已模拟删除《过时的 Java 教程》。
This is divided into two phases:
**Phase 1:** The Agent reaches interrupt() and returns the pending approval information.
**Phase 2:** The external program uses the same thread_id and, through Command(resume=...) resume execution.
Example usage result["__interrupt__"] checks the interrupt; this is a common pattern in an ordinary invoke() return structure.
Note that whether the tool is called is decided by the model. Even if the user explicitly requests deletion, the actual run may not trigger the tool.
VI. Viewing the Agent's Interrupt State
After the Agent pauses, you can use get_state() to view the thread's current state.
Example
Example
state
=
agent.
get_state
(
config
)
(
"Pending nodes: "
,
state.
next
)
for
task
in
state.
tasks
:
for
item
in
task.
interrupts
:
(
"Interrupt ID:"
,
item.
id
)
(
"Approval content:"
,
item.
value
)
If the tool node triggered an interrupt,state.next may contain:
('tools',)
indicating that the graph still has a tool node pending execution.
**Note:** You should not assume state.tasks[0] necessarily corresponds to the current approval, nor should you treat all pauses as tool approvals.
Real applications should iterate over pending tasks and manage approval state using the interrupt ID, thread, and business records.
VII. HumanInTheLoopMiddleware: Built-in Tool Approval
LangChain 1.x provides HumanInTheLoopMiddleware, which can automatically pause when the model requests to execute a sensitive tool and wait for human review.
It is more convenient than manually calling interrupt() in every tool, and is especially suitable for unified approval management of a large number of tools.
It mainly supports four decisions:
| Decision | Description |
|---|---|
approve |
Approve execution with original arguments |
edit |
Execute after modifying tool arguments |
reject |
Reject the tool call |
respond |
Human directly provides the tool return content without executing the tool |
where respond Mainly suitable for tools that wait for user answers, such as ask_user。
**Note:** Do not use respond to reject deletion or payment tools, because it generates a successful tool result, which may make the model mistakenly believe the operation has completed.
VIII. Complete Example: HumanInTheLoopMiddleware
Below, we create a mock course deletion Agent with approval through the built-in Middleware.
Complete example
from
dotenv
import
load_dotenv
from
langchain.
agents
import
create_agent
from
langchain.
agents
.
middleware
import
HumanInTheLoopMiddleware
from
langchain.
tools
import
tool
from
langgraph.
checkpoint
.
memory
import
InMemorySaver
from
langgraph.
types
import
Command
load_dotenv
(
)
@
tool
def
delete_course
(
course_name:
str
)
str
:
"""Mock course deletion."""
return
f
"Mock-deleted '{course_name}'"
@
tool
def
search_course
(
keyword
:
str
)
str
:
"""Query mock courses."""
return
"Python3 Basic Tutorial, Java Basic Tutorial"
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
delete_course
,
search_course
]
,
middleware
=
[
HumanInTheLoopMiddleware
(
interrupt_on
=
{
"delete_course"
:
{
"allowed_decisions"
:
[
"approve"
,
"reject"
]
}
,
"search_course"
:
False
}
)
]
,
checkpointer
=
InMemorySaver
(
)
,
system_prompt
=
"You are a course management assistant. When deleting a course, call delete_course; the tool only simulates execution."
)
config
=
{
"configurable"
:
{
"thread_id"
:
"hitl-002"
}
}
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
:
"Please call the tool to mock-delete the 'Old Java Tutorial'."
}
]
}
,
config
=
config
,
version
=
"v2"
)
if
result.
interrupts
:
(
"Pending approval:"
,
result.
interrupts
[
0
]
.
value
)
result
=
agent.
invoke
(
Command
(
resume
=
{
"decisions"
:
[
{
"type"
:
"approve"
}
]
}
)
,
config
=
config
,
version
=
"v2"
)
if
result.
interrupts
:
(
"Operations still pending approval"
)
else
:
(
"Final reply:"
,
result.
value
[
"messages"
]
[
1
]
.
content
)
Here, the following is used version="v2", so it returns an execution result object containing value and interrupts the interrupt information.
It differs from reading interrupt information via result["__interrupt__"] when v2 is not specified.
In this example:
delete_course: approval is required.search_course: no approval is needed.approve: approve execution of the original tool call.reject: reject execution and pass the rejection feedback to the Agent.
The example simplifies the demonstration by assuming only one pending approval action. If multiple actions exist at the same time, you need to provide a decision for each one separately.
IX. Approve, Reject, and Modify Tool Arguments
The approval result of HumanInTheLoopMiddleware is passed through the Command(resume=...) decisions field.
1. Approve
Command(resume={
"decisions": [{"type": "approve"}]
})
Indicates executing the tool with the original arguments.
2. Reject
Command(resume={
"decisions": [{
"type": "reject",
"message": "管理员不同意删除该课程,请勿再次尝试。"
}]
})
A rejected tool will not be executed, and the Agent will receive the corresponding rejection feedback.
3. Edit Arguments
If humans are allowed to modify tool calls, you can configure:
"delete_course": {
"allowed_decisions": ["approve", "edit", "reject"]
}
When resuming:
Command(resume={
"decisions": [{
"type": "edit",
"edited_action": {
"name": "delete_course",
"args": {"course_name": "指定的新课程名称"}
}
}]
})
This allows the approver to modify tool arguments.
**Note:** Modifying the tool name or arguments may change the actual business operation; a trusted backend should re-check the edited tool, target object, and approver's permissions.
For high-risk operations such as deletion and payment, it is generally not recommended to allow the approver to switch tool types arbitrarily.
X. Multiple Tools Requiring Approval at the Same Time
The Agent may request to call multiple tools in a single model response.
For example:
delete_course("旧版 Java 教程")
delete_course("旧版 PHP 教程")
If two tool calls both require approval, the HITL Middleware can return multiple pending review actions.
In this case, you must provide a corresponding decision for each action.
Example: Batch Approval
Example
decision
=
Command
(
resume
=
{
"decisions"
:
[
{
"type"
:
"approve"
}
,
{
"type"
:
"reject"
,
"message"
:
"The second course needs to be retained."
}
]
}
)
result
=
agent.
invoke
(
decision
,
config
=
config
,
version
=
"v2"
)
The order of the decisions must match the order of the action_requests in the interrupt information.
You cannot assume there is only one request requiring approval based solely on the tool name.
A real web system should also record a unique ID for each approval action to ensure the approver does not mistakenly approve other tool calls.
XI. interrupt_before and interrupt_after
In addition to dynamic interrupts, you can also use the create_agent() parameter to set static breakpoints before and after specified graph nodes.
For example:
Example
from
langchain.
agents
import
create_agent
from
langgraph.
checkpoint
.
memory
import
InMemorySaver
agent
=
create_agent
(
model
=
"deepseek:deepseek-flash"
,
tools
=
[
search_course
]
,
checkpointer
=
InMemorySaver
(
)
,
interrupt_before
=
[
"tools"
]
)
This means the graph pauses before executing the tool node.
| Settings | Pause timing | Typical use |
|---|---|---|
interrupt_before=["model"] |
Before the model node executes | Debug input state |
interrupt_after=["model"] |
After the model node executes | Check model output |
interrupt_before=["tools"] |
Before the tool node executes | View tool call requests |
interrupt_after=["tools"] |
After the tool node executes | Inspect tool results |
Note that static breakpoints differ from interrupt() in important ways.
A static breakpoint merely pauses the graph before and after the specified node; it does not automatically construct a tool approval request with approve, edit, and reject options.
If you need to review tools individually, HumanInTheLoopMiddleware is recommended.
How does a static breakpoint resume execution?
After inspecting the state, you can use:
result = agent.invoke(None, config=config)
to continue executing the paused graph.
If it is a static tool-node breakpoint, you should first inspect the tool to be executed and its arguments, and confirm authorization in the business backend.
**Note:** Directly resuming execution does not mean approval is complete; whether to allow continuation is something the application layer must guarantee itself.
XII. Differences Between Dynamic and Static Interrupts
| Comparison Item | Dynamic interrupt() | Static interrupt_before/after |
|---|---|---|
| Interrupt location | Any appropriate location in the code | Before and after specified graph nodes |
| Whether it can carry approval content | You can | Must be read from the graph state yourself |
| Resume method | Command(resume=...) | Usually continues via invoke(None, config=...) |
| Whether human decisions can be input | You can | The application must manage decisions and state itself |
| Typical use | Approval, human-filled data | Node debugging, execution pause |
For scenarios that require users to fill in forms, supplement arguments, or perform approval operations, dynamic interrupts are usually more suitable.
XIII. Important Notes When Resuming Execution
One of the most common HITL problems is mistakenly thinking that after interrupt() pauses, execution resumes in place from the next line of the Python function.
In fact, when LangGraph resumes an interrupted node, it re-executes the code from the beginning of that node.
Incorrect Example
def delete_data():
database.delete("course-001")
approved = interrupt("确认删除?")
return approved
Here, the deletion is performed before human confirmation.
Moreover, when resuming, the previous code may be executed again.
The correct approach
def delete_data():
approved = interrupt("确认删除?")
if approved:
database.delete("course-001")
return approved
For real business, you also need to ensure database operations are idempotent, to avoid duplicate operations caused by network retries, concurrent approvals, or execution resumes.
**Note:** Placing side effects after interrupt() can avoid "executing before approval," but it cannot alone guarantee that the entire business implementation executes strictly only once.
XIV. HITL Architecture in Web Applications
Real web applications usually split HITL into two types of APIs:
- The user submits a task, and the Agent executes up to the pending approval node.
- An authorized approver submits a decision, and the backend resumes the corresponding Agent thread.
Typical flow:
浏览器
↓ 提交任务
应用后端
↓
Agent 执行
↓
触发 interrupt
↓
Checkpointer 保存状态
↓
后端创建待审批记录
↓
审批界面展示操作详情
↓
管理员登录并批准或拒绝
↓
后端验证权限与审批状态
↓
Command(resume=...)
↓
Agent 恢复执行
↓
返回完成状态或新的审批请求
Below is simple backend logic to accompany the previous custom interrupt() example.
Example: Submitting a Task and Reading Approval Status
Example
def
handle_user_message
(
thread_id:
str
,
message:
str
)
:
config
=
{
"configurable"
:
{
"thread_id"
: thread_id
}
}
result
=
agent.
invoke
(
{
"messages"
:
[
{
"role"
:
"user"
,
"content"
: message
}
]
}
,
config
=
config
)
pending
=
result.
get
(
"interrupt"
,
(
)
)
if
pending:
return
{
"status"
:
"pending_approval"
,
"actions"
:
[
item.
value
for
item
in
pending
]
,
"thread_id"
: thread_id
}
return
{
"status"
:
"completed"
,
"reply"
: result
[
"messages"
]
[
1
]
.
content
}
Here, the pending approval content is returned rather than automatically performing approval.
Example: Resume After Approval
Example
from
langgraph.
types
import
Command
def
handle_approval
(
thread_id:
str
,
approved:
bool
,
reason:
str
=
""
)
:
Before calling this function, the backend must complete verification of identity, permissions, conversation ownership, and approval status
config
=
{
"configurable"
:
{
"thread_id"
: thread_id
}
}
result
=
agent.
invoke
(
Command
(
resume
=
{
"approved"
: approved
,
"reason"
: reason
}
)
,
config
=
config
)
pending
=
result.
get
(
"interrupt"
,
(
)
)
if
pending:
return
{
"status"
:
"pending_approval"
,
"actions"
:
[
i.
value
for
i
in
pending
]
}
return
{
"status"
:
"completed"
,
"reply"
: result
[
"messages"
]
[
1
]
.
content
}
These two functions show the core execution logic, not a complete HTTP API ready for public deployment.
A real backend must also handle authentication, authorization, approval logs, state locking, timeout handling, and exception recovery.
**Important:** This custom approval flow uses the interrupt() resume data structure. If you use HumanInTheLoopMiddleware instead, you must resume in that Middleware's decisions format; the two cannot be mixed.
XV. HITL and Checkpointer
HITL requires a Checkpointer to save the interrupt state so that execution can resume after external approval completes.
Development environments usually use:
from langgraph.checkpoint.memory import InMemorySaver
checkpointer = InMemorySaver()
It is simple and easy to use, but data is only kept in the current process's memory.
Once the program restarts, the execution state of pending approval tasks may be lost.
For production, it is recommended to use a Checkpointer that supports persistence, such as PostgreSQL:
PostgresSaver
AsyncPostgresSaver
For asynchronous web services, an asynchronous Checkpointer is usually used, with database connections managed throughout the application lifecycle.
Note:
- Resume must use the original thread_id.
- A Checkpointer stores graph execution state, not a complete approval business database.
- Approval records usually need separate storage for auditing and permission management.
- Concurrent resume requests for the same thread need to be coordinated to prevent duplicate processing.
XVI. Production Safety Design for HITL
1. Approval operations must be completed by a trusted backend
Do not assume an operation has been approved by an administrator merely because the request contains
{"approved": true}
such a field.
The backend must confirm the approver's identity, permissions, and corresponding business object.
2. The approval object must be bound to a specific operation
Approval records should contain:
审批 ID
thread_id
工具名称
工具参数摘要
操作对象
审批人
审批状态
创建时间
处理时间
Avoid the problem of "the user approved operation A, but the Agent ultimately executed operation B."
3. Permissions must still be re-verified after approval
A user's permissions may change while waiting for approval.
Therefore, when actually performing sensitive operations such as deletion or payment, the backend still needs to re-verify permissions and business rules.
4. Ensure operation idempotency
For operations such as payment, sending emails, and creating orders, use idempotency keys or unique business request IDs to prevent duplicate execution.
5. Approval needs timeout and cancellation mechanisms
Users may leave approval requests unhandled for a long time.
Production environments should define clear waiting deadlines, cancellation methods, and handling rules after a timeout.
6. Do not treat interrupt information directly as trusted instructions
Interrupt details may contain model-generated arguments; the approval UI should escape them properly for display, and the backend should validate the arguments.
7. Audit the actual execution results
Human approval does not mean the business operation will necessarily succeed.
You should separately record states such as "approval granted," "tool execution started," and "business operation completed."
17. Frequently Asked Questions
1. What is HITL?
HITL is Human-in-the-Loop, which lets humans participate in the key decisions and execution flow of an AI Agent.
2. Does interrupt() block the entire Python service?
It does not work by continuously blocking to wait for user input. Through graph interruption and state persistence, it lets the current execution return pending information and resume later.
3. Can HITL be used without a Checkpointer?
Normal persistent interrupt resumption requires a Checkpointer and a stable thread_id.
4. Why must the same thread_id be used when resuming?
Because the Checkpointer needs the thread identifier to find the previously saved execution state.
5. What is the role of Command(resume=...)?
It passes external input to the paused interrupt(), letting the graph continue executing.
6. Does execution continue from the interrupt point after resuming?
Resuming re-executes the node containing interrupt() and receives the resume data at the corresponding interrupt call.
7. Is interrupt_before=["tools"] equivalent to tool approval?
No. It is only a tool-node-level static breakpoint and does not automatically provide per-tool approve, edit, and reject mechanisms.
8. When should HumanInTheLoopMiddleware be used?
When the main need is to review tool calls proposed by the Agent, the built-in Middleware is usually preferred.
9. Can HITL modify tool parameters?
Yes. HumanInTheLoopMiddleware supports the edit decision, but editing must be explicitly configured as allowed.
10. What if multiple tools require approval at the same time?
You need to provide a decision for each pending review action, and ensure the order of decisions matches the order of actions in the interrupt request.
11. What is the difference between reject and respond?
reject means rejecting the tool call; respond means the human directly provides the tool response without executing the tool. respond cannot be used in place of a rejection for sensitive operations.
12. Does approval by a human guarantee successful execution?
Not necessarily. Subsequent tools may still fail due to permission changes, service failures, or business validation failures.
13. Can approval be resumed after a program restart?
If you use a persistent Checkpointer and properly save the thread and approval information, cross-process recovery can be supported.
14. Can HITL be used in FastAPI?
Yes. Typically one endpoint starts the task, another authorized endpoint submits the approval decision, and then the corresponding thread is resumed.
Summary
Human-in-the-Loop is an important capability for LangChain Agents to achieve safe and controllable automation.
This chapter covers:
interrupt(): dynamically pausing execution.Command(resume=...): resuming paused execution.HumanInTheLoopMiddleware: human review of tool calls.approve: approving operations.edit: modifying tool parameters.reject: rejecting operations.respond: humans directly providing tool results.interrupt_before / interrupt_after: static graph node interrupts.Checkpointer: saving interrupt state.- Approval permissions, state management, and idempotency control in web applications.
The most basic way to write a dynamic interrupt:
decision = interrupt({"message": "请确认操作"})
if decision.get("approved"):
# Operations allowed after execution
pass
Resuming execution:
agent.invoke(
Command(resume={"approved": True}),
config={"configurable": {"thread_id": "approval-001"}}
)
For common tool approval, the recommendation is:
HumanInTheLoopMiddleware(
interrupt_on={
"delete_course": {"allowed_decisions": ["approve", "reject"]}
}
)
Core principles:An Agent can propose actions, but high-risk operations should be validated by a trusted system, approved by an authorized person, and actually executed by the business backend. Human approval, successful tool execution, and completion of the business result are three states that need to be confirmed separately.