跳到内容

人机协作

要在智能体中审查、编辑和批准工具调用,您可以使用 LangGraph 内置的人机协作功能,特别是 interrupt() 原语。

LangGraph 允许您**无限期地**暂停执行——可以是几分钟、几小时,甚至几天——直到收到人工输入。

这是可能的,因为智能体状态会**检查点到数据库中**,这使得系统能够持久化执行上下文,并在稍后恢复工作流,从中断的地方继续执行。

要深入了解**人机协作**概念,请参阅概念指南

image

人工可以在继续之前审查和编辑智能体的输出。这在工具调用请求可能敏感或需要人工监督的应用程序中尤其关键。

审查工具调用

将人工审批步骤添加到工具中:

  1. 在工具中使用 interrupt() 暂停执行。
  2. 使用 Command({ resume: ... }) 恢复执行,以根据人工输入继续。
import { MemorySaver } from "@langchain/langgraph-checkpoint";
import { interrupt } from "@langchain/langgraph";
import { createReactAgent } from "@langchain/langgraph/prebuilt";
import { initChatModel } from "langchain/chat_models/universal";
import { tool } from "@langchain/core/tools";
import { z } from "zod";

// An example of a sensitive tool that requires human review / approval
const bookHotel = tool(
  async (input: { hotelName: string; }) => {
    let hotelName = input.hotelName;
    const response = interrupt(  // (1)!
      `Trying to call \`book_hotel\` with args {'hotel_name': ${hotelName}}. ` +
      `Please approve or suggest edits.`
    )
    if (response.type === "accept") {
      // proceed to execute the tool logic
    } else if (response.type === "edit") {
        hotelName = response.args["hotel_name"]
    } else {
        throw new Error(`Unknown response type: ${response.type}`)
    }
    return `Successfully booked a stay at ${hotelName}.`;
  },
  {
    name: "bookHotel",
    schema: z.object({
      hotelName: z.string().describe("Hotel to book"),
    }),
    description: "Book a hotel.",
  }
);

const checkpointer = new MemorySaver();  // (2)!

const llm = await initChatModel("anthropic:claude-3-7-sonnet-latest");
const agent = createReactAgent({
  llm,
  tools: [bookHotel],
  checkpointer  // (3)!
});
  1. interrupt 函数在特定节点暂停智能体图。在这种情况下,我们在工具函数开始时调用 interrupt(),这会在执行工具的节点处暂停图。interrupt() 中的信息(例如,工具调用)可以呈现给人工,并且图可以根据用户输入(工具调用审批、编辑或反馈)恢复。
  2. InMemorySaver 用于在工具调用循环的每一步存储智能体状态。这使得短期记忆人机协作功能成为可能。在此示例中,我们使用 InMemorySaver 将智能体状态存储在内存中。在生产应用程序中,智能体状态将存储在数据库中。
  3. 使用 checkpointer 初始化智能体。

使用 stream() 方法运行智能体,传入 config 对象以指定线程 ID。这允许智能体在未来的调用中恢复相同的对话。

const config = {
   configurable: {
      "thread_id": "1"
   }
}

for await (const chunk of await agent.stream(
  { messages: "book a stay at McKittrick hotel" },
  config
)) {
  console.log(chunk);
  console.log("\n");
};

您应该会看到智能体一直运行到达到 interrupt() 调用,此时它会暂停并等待人工输入。

使用 Command({ resume: ... }) 恢复智能体,以根据人工输入继续。

import { Command } from "@langchain/langgraph";

for await (const chunk of await agent.stream(
  new Command({ resume: { type: "accept" } }),  // (1)!
  // new Command({ resume: { type: "edit", args: { "hotel_name": "McKittrick Hotel" } } }),
  config
)) {
  console.log(chunk);
  console.log("\n");
};
  1. interrupt 函数Command 对象结合使用,以人工提供的值恢复图。

更多资源