人机协作(HITL)中间件让您可以为智能体工具调用添加人工监督。 当模型提出可能需要审查的操作(例如写入文件或执行 SQL)时,中间件可以暂停执行并等待决策。 它通过根据可配置策略检查每个工具调用来实现。如果需要干预,中间件会触发一次中断以停止执行。图状态通过 LangGraph 的持久化层保存,因此执行可以安全暂停并在稍后恢复。 然后由人工决定接下来发生什么:该操作可以按原样批准( approve )、运行前修改( edit ),或拒绝并反馈( reject )。

中断决策类型

中间件定义了人类响应中断的三种内置方式:
决策类型 描述 示例用例
approve 该操作按原样批准并执行,无需更改。 发送与书面内容完全一致的电子邮件草稿
✏️ edit 工具调用经过修改后执行。 发送电子邮件之前更改收件人
reject 工具调用被拒绝,并在对话中添加了解释。 拒绝电子邮件草稿并解释如何重写它
每个工具的可用决策类型取决于您在 interrupt_on 中配置的策略。 当多个工具调用同时暂停时,每个操作都需要单独的决策。 决策必须按照中断请求中出现的操作的顺序提供。
编辑工具参数时,请保守修改。对原始参数的大幅改动可能会导致模型重新评估其方法,并可能多次执行该工具或采取意外操作。

配置中断

要使用 HITL,请在创建智能体时将中间件加入 middleware 列表。 您可以使用工具操作到每个操作允许的决策类型的映射来配置它。当工具调用与映射中的操作匹配时,中间件将中断执行。
import { createAgent, humanInTheLoopMiddleware } from "langchain"; 
import { MemorySaver } from "@langchain/langgraph"; 

const agent = createAgent({
    model: "gpt-4o",
    tools: [writeFileTool, executeSQLTool, readDataTool],
    middleware: [
        humanInTheLoopMiddleware({
            interruptOn: {
                write_file: true, // All decisions (approve, edit, reject) allowed
                execute_sql: {
                    allowedDecisions: ["approve", "reject"],
                    // No editing allowed
                    description: "🚨 SQL execution requires DBA approval",
                },
                // Safe operation, no approval needed
                read_data: false,
            },
            // Prefix for interrupt messages - combined with tool name and args to form the full message
            // e.g., "Tool execution pending approval: execute_sql with query='DELETE FROM...'"
            // Individual tools can override this by specifying a "description" in their interrupt config
            descriptionPrefix: "Tool execution pending approval",
        }),
    ],
    // Human-in-the-loop requires checkpointing to handle interrupts.
    // In production, use a persistent checkpointer like AsyncPostgresSaver.
    checkpointer: new MemorySaver(), 
});
您必须配置检查指针以跨中断保持图状态。 在生产中,使用持久检查指针,例如 AsyncPostgresSaver 。对于测试或原型设计,请使用 InMemorySaver . 调用智能体时,传递一个 config ,其中包括线程 ID以将执行与对话线程关联起来。 请参阅LangGraph 中断文档了解详情。
中断开启
目的
必需的
工具名称到批准配置的映射
工具批准配置选项:
允许接受
布尔值
默认: false
是否允许审批
允许编辑
布尔值
默认: false
是否允许编辑
允许响应
布尔值
默认: false
是否允许回复/拒绝

响应中断

当您调用智能体时,它会一直运行,直到完成或触发中断。当工具调用与您在 interrupt_on 中配置的策略匹配时,就会触发中断。在这种情况下,调用结果将包含 __interrupt__ 字段,其中包括需要审查的操作。随后,您可以将这些操作呈现给审阅者,并在做出决定后恢复执行。
import { HumanMessage } from "@langchain/core/messages";
import { Command } from "@langchain/langgraph";

// You must provide a thread ID to associate the execution with a conversation thread,
// so the conversation can be paused and resumed (as is needed for human review).
const config = { configurable: { thread_id: "some_id" } }; 

// Run the graph until the interrupt is hit.
const result = await agent.invoke(
    {
        messages: [new HumanMessage("Delete old records from the database")],
    },
    config
);


// The interrupt contains the full HITL request with action_requests and review_configs
console.log(result.__interrupt__);
// > [
// >    Interrupt(
// >       value: {
// >          action_requests: [
// >             {
// >                name: 'execute_sql',
// >                arguments: { query: 'DELETE FROM records WHERE created_at < NOW() - INTERVAL \'30 days\';' },
// >                description: 'Tool execution pending approval\n\nTool: execute_sql\nArgs: {...}'
// >             }
// >          ],
// >          review_configs: [
// >             {
// >                action_name: 'execute_sql',
// >                allowed_decisions: ['approve', 'reject']
// >             }
// >          ]
// >       }
// >    )
// > ]

// Resume with approval decision
await agent.invoke(
    new Command({ 
        resume: { decisions: [{ type: "approve" }] }, // or "reject"
    }), 
    config // Same thread ID to resume the paused conversation
);

决策类型

使用 approve 按原样批准工具调用并在不进行任何更改的情况下执行它。
await agent.invoke(
    new Command({
        // Decisions are provided as a list, one per action under review.
        // The order of decisions must match the order of actions
        // listed in the `__interrupt__` request.
        resume: {
            decisions: [
                {
                    type: "approve",
                }
            ]
        }
    }),
    config  // Same thread ID to resume the paused conversation
);

通过人机协作进行流式传输

您可以使用 stream() 而不是 invoke() 在智能体运行和处理中断时获取实时更新。使用 stream_mode=['updates', 'messages'] 流式传输智能体进度和 LLM 令牌。
import { Command } from "@langchain/langgraph";

const config = { configurable: { thread_id: "some_id" } };

// Stream agent progress and LLM tokens until interrupt
for await (const [mode, chunk] of await agent.stream(
    { messages: [{ role: "user", content: "Delete old records from the database" }] },
    { ...config, streamMode: ["updates", "messages"] }  
)) {
    if (mode === "messages") {
        // LLM token
        const [token, metadata] = chunk;
        if (token.content) {
            process.stdout.write(token.content);
        }
    } else if (mode === "updates") {
        // Check for interrupt
        if ("__interrupt__" in chunk) {
            console.log(`\n\nInterrupt: ${JSON.stringify(chunk.__interrupt__)}`);
        }
    }
}

// Resume with streaming after human decision
for await (const [mode, chunk] of await agent.stream(
    new Command({ resume: { decisions: [{ type: "approve" }] } }),
    { ...config, streamMode: ["updates", "messages"] }
)) {
    if (mode === "messages") {
        const [token, metadata] = chunk;
        if (token.content) {
            process.stdout.write(token.content);
        }
    }
}
请参阅流式传输指南,了解流式模式的更多细节。

执行生命周期

中间件定义了一个 after_model 钩子,在模型生成响应之后、执行任何工具调用之前运行:
  1. 智能体调用模型来生成响应。
  2. 中间件检查工具调用的响应。
  3. 如果任何调用需要人工输入,中间件会构建一个 HITLRequest action_requests review_configs 并调用中断 .
  4. 智能体等待人类的决定。
  5. 基于 HITLResponse 决策,中间件执行批准或编辑的调用,生成工具消息用于拒绝调用,并恢复执行。

自定义 HITL 逻辑

对于更复杂的工作流程,您可以直接使用中断 原语和中间件抽象来构建自定义 HITL 逻辑。 参见执行生命周期了解如何将中断集成到智能体操作中。
将这些文档接入 MCP,发送给 Claude、VSCode 等以获得实时答案。