返回文章列表

对于langchain,langgraph,和deepagent的理解

2 min read

为了能更好的理解这三个的区别,用js来表达一下自己的理解并记录一下

1. langchain#

我的理解是类似promise的then调用

JAVASCRIPT
左右滑动查看完整代码

function runLangChain(input) {
  return formatPrompt(input)       // 步骤 1:组装 Prompt
    .then(callLLM)                 // 步骤 2:调用大模型
    .then(parseOutput)             // 步骤 3:解析模型输出
    .then(useTool)                 // 步骤 4:调用外部工具
    .catch(handleError);           // 出错后统一处理
}

// 输入问题 -> 组装 Prompt -> 调用 LLM -> 解析输出 -> 返回答案

2. langgraph#

LangGraph的话更像是你自己维护一个 state,然后通过编排节点执行的顺序和方向去实现一个agent

JAVASCRIPT
左右滑动查看完整代码

async function runLangGraph(initialInput) {
  let state = {
    input: initialInput,
    history: [],
    isFinished: false,
  };

  while (!state.isFinished) {
    const nextNode = await router(state);

    if (nextNode === "think") {
      state = await agentThinkNode(state);
    } else if (nextNode === "use_tool") {
      state = await toolExecutionNode(state);
    } else if (nextNode === "reflect") {
      state = await selfCorrectNode(state);
    } else {
      state.isFinished = true;
    }
  }

  return state.finalResult;
}

// 这就类似于定义好了节点,在编排graph

3. DeepAgent#

DeepAgent 看着最复杂,其实是官方写好的一套复杂的 LangGraph Agent 框架,你只需要提供这些东西

  1. system prompt
  2. tools
  3. model
  4. subagents / memory / filesystem / interrupt

你只要把这些东西提供给DeepAgent ,提示词写清楚这些东西的关系,什么时候调用谁,剩下的就交给llm自己去判断了

JAVASCRIPT
左右滑动查看完整代码

async function runDeepAgent(userInput) {
  let state = {
    messages: [{ role: "user", content: userInput }],
    todos: [],
    files: {},
    toolResults: [],
    subAgents: {},
    isFinished: false,
  };

  const systemPrompt = `
    你要先理解任务,必要时写 TODO。
    需要查本地知识库就调用 localRagTool。
    需要联网就调用 webSearchTool。
    复杂任务可以拆给 subAgent。
    最后整理答案。
  `;

  while (!state.isFinished) {
    const decision = await llmDecideNextAction({
      systemPrompt,
      messages: state.messages,
      todos: state.todos,
      files: state.files,
      tools: [
        writeTodos,
        readFile,
        writeFile,
        localRagTool,
        webSearchTool,
        taskSubAgent,
      ],
    });

    if (decision.type === "tool_call") {
      const result = await runTool(decision.toolName, decision.args);

      state.toolResults.push(result);
      state.messages.push({
        role: "tool",
        name: decision.toolName,
        content: result,
      });

      continue;
    }

    if (decision.type === "sub_agent") {
      const subResult = await runDeepAgent(decision.subTask);

      state.messages.push({
        role: "tool",
        name: "sub_agent",
        content: subResult,
      });

      continue;
    }

    if (decision.type === "final_answer") {
      state.finalResult = decision.content;
      state.isFinished = true;
    }
  }

  return state.finalResult;
}