Skip to content

在你完成 LangGraph 智能体的原型后,一个自然的下一步是添加测试。本指南介绍了一些在编写单元测试时可以使用的有用模式。

请注意,本指南特定于 LangGraph,涵盖自定义结构图的相关场景——如果你才刚刚开始,请查阅使用 LangChain 内置 create_agent测试

请注意,本指南特定于 LangGraph,涵盖自定义结构图的相关场景——如果你才刚刚开始,请查阅使用 LangChain 内置 createAgent测试

先决条件

首先,请确保你已安装 pytest

bash
$ pip install -U pytest

首先,请确保你已安装 vitest

bash
$ npm install -D vitest

快速开始

由于许多 LangGraph 智能体都依赖状态,一个有用的模式是在每个使用图的测试之前创建图,然后在测试中使用新的检查点器实例编译它。

下面的示例展示了这在通过 node1node2 推进的简单线性图中如何工作。每个节点都更新单个状态键 my_key

python
import pytest

from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import MemorySaver

def create_graph() -> StateGraph:
    class MyState(TypedDict):
        my_key: str

    graph = StateGraph(MyState)
    graph.add_node("node1", lambda state: {"my_key": "hello from node1"})
    graph.add_node("node2", lambda state: {"my_key": "hello from node2"})
    graph.add_edge(START, "node1")
    graph.add_edge("node1", "node2")
    graph.add_edge("node2", END)
    return graph

def test_basic_agent_execution() -> None:
    checkpointer = MemorySaver()
    graph = create_graph()
    compiled_graph = graph.compile(checkpointer=checkpointer)
    result = compiled_graph.invoke(
        {"my_key": "initial_value"},
        config={"configurable": {"thread_id": "1"}}
    )
    assert result["my_key"] == "hello from node2"
ts
import { test, expect } from 'vitest';
import {
  StateGraph,
  StateSchema,
  START,
  END,
  MemorySaver,
} from '@langchain/langgraph';
import * as z from "zod";

const State = new StateSchema({
  my_key: z.string(),
});

const createGraph = () => {
  return new StateGraph(State)
    .addNode('node1', (state) => ({ my_key: 'hello from node1' }))
    .addNode('node2', (state) => ({ my_key: 'hello from node2' }))
    .addEdge(START, 'node1')
    .addEdge('node1', 'node2')
    .addEdge('node2', END);
};

test('basic agent execution', async () => {
  const uncompiledGraph = createGraph();
  const checkpointer = new MemorySaver();
  const compiledGraph = uncompiledGraph.compile({ checkpointer });
  const result = await compiledGraph.invoke(
    { my_key: 'initial_value' },
    { configurable: { thread_id: '1' } }
  );
  expect(result.my_key).toBe('hello from node2');
});

测试单个节点和边

编译后的 LangGraph 智能体会以 graph.nodes 的形式暴露对每个单独节点的引用。你可以利用这一点来测试智能体内的单独节点。请注意,这会绕过编译图时传入的任何检查点器:

python
import pytest

from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import MemorySaver

def create_graph() -> StateGraph:
    class MyState(TypedDict):
        my_key: str

    graph = StateGraph(MyState)
    graph.add_node("node1", lambda state: {"my_key": "hello from node1"})
    graph.add_node("node2", lambda state: {"my_key": "hello from node2"})
    graph.add_edge(START, "node1")
    graph.add_edge("node1", "node2")
    graph.add_edge("node2", END)
    return graph

def test_individual_node_execution() -> None:
    # 在此示例中会被忽略
    checkpointer = MemorySaver()
    graph = create_graph()
    compiled_graph = graph.compile(checkpointer=checkpointer)
    # 只调用 node 1
    result = compiled_graph.nodes["node1"].invoke(
        {"my_key": "initial_value"},
    )
    assert result["my_key"] == "hello from node1"
ts
import { test, expect } from 'vitest';
import {
  StateGraph,
  START,
  END,
  MemorySaver,
  StateSchema,
} from '@langchain/langgraph';
import * as z from "zod";

const State = new StateSchema({
  my_key: z.string(),
});

const createGraph = () => {
  return new StateGraph(State)
    .addNode('node1', (state) => ({ my_key: 'hello from node1' }))
    .addNode('node2', (state) => ({ my_key: 'hello from node2' }))
    .addEdge(START, 'node1')
    .addEdge('node1', 'node2')
    .addEdge('node2', END);
};

test('individual node execution', async () => {
  const uncompiledGraph = createGraph();
  // 在此示例中会被忽略
  const checkpointer = new MemorySaver();
  const compiledGraph = uncompiledGraph.compile({ checkpointer });
  // 只调用 node 1
  const result = await compiledGraph.nodes['node1'].invoke(
    { my_key: 'initial_value' },
  );
  expect(result.my_key).toBe('hello from node1');
});

部分执行

对于由较大图构成的智能体,你可能希望测试智能体内的部分执行路径,而不是整个端到端流程。在某些情况下,将这些部分重构为子图在语义上可能更有意义,你可以像往常一样单独调用它们。

然而,如果你不想更改智能体图的整体结构,你可以使用 LangGraph 的持久化机制来模拟一种状态:智能体在所需部分开始之前恰好暂停,并在所需部分结束时再次暂停。步骤如下:

  1. 使用检查点器编译你的智能体(内存检查点器 InMemorySaver 足以用于测试)。
  2. 调用智能体的 update_state 方法,并将 as_node 参数设置为你想要开始测试的节点之前的那个节点的名称。
  3. 使用与更新状态时相同的 thread_id 以及设置为你想停止的节点名称的 interrupt_after 参数调用你的智能体。
  4. 使用检查点器编译你的智能体(内存检查点器 MemorySaver 足以用于测试)。
  5. 调用智能体的 update_state 方法,并将 asNode 参数设置为你想要开始测试的节点之前的那个节点的名称。
  6. 使用与更新状态时相同的 thread_id 以及设置为你想停止的节点名称的 interruptBefore 参数调用你的智能体。

下面是一个仅在线性图中执行第二个和第三个节点的示例:

python
import pytest

from typing_extensions import TypedDict
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import MemorySaver

def create_graph() -> StateGraph:
    class MyState(TypedDict):
        my_key: str

    graph = StateGraph(MyState)
    graph.add_node("node1", lambda state: {"my_key": "hello from node1"})
    graph.add_node("node2", lambda state: {"my_key": "hello from node2"})
    graph.add_node("node3", lambda state: {"my_key": "hello from node3"})
    graph.add_node("node4", lambda state: {"my_key": "hello from node4"})
    graph.add_edge(START, "node1")
    graph.add_edge("node1", "node2")
    graph.add_edge("node2", "node3")
    graph.add_edge("node3", "node4")
    graph.add_edge("node4", END)
    return graph

def test_partial_execution_from_node2_to_node3() -> None:
    checkpointer = MemorySaver()
    graph = create_graph()
    compiled_graph = graph.compile(checkpointer=checkpointer)
    compiled_graph.update_state(
        config={
          "configurable": {
            "thread_id": "1"
          }
        },
        # 传入 node 2 的状态——模拟 node 1 结束时的
        # 状态
        values={"my_key": "initial_value"},
        # 更新保存的状态,就好像它来自 node 1
        # 执行将从 node 2 恢复
        as_node="node1",
    )
    result = compiled_graph.invoke(
        # 通过传入 None 恢复执行
        None,
        config={"configurable": {"thread_id": "1"}},
        # 在 node 3 之后停止,这样 node 4 就不会运行
        interrupt_after="node3",
    )
    assert result["my_key"] == "hello from node3"
ts
import { test, expect } from 'vitest';
import {
  StateGraph,
  StateSchema,
  START,
  END,
  MemorySaver,
} from '@langchain/langgraph';
import * as z from "zod";

const State = new StateSchema({
  my_key: z.string(),
});

const createGraph = () => {
  return new StateGraph(State)
    .addNode('node1', (state) => ({ my_key: 'hello from node1' }))
    .addNode('node2', (state) => ({ my_key: 'hello from node2' }))
    .addNode('node3', (state) => ({ my_key: 'hello from node3' }))
    .addNode('node4', (state) => ({ my_key: 'hello from node4' }))
    .addEdge(START, 'node1')
    .addEdge('node1', 'node2')
    .addEdge('node2', 'node3')
    .addEdge('node3', 'node4')
    .addEdge('node4', END);
};

test('partial execution from node2 to node3', async () => {
  const uncompiledGraph = createGraph();
  const checkpointer = new MemorySaver();
  const compiledGraph = uncompiledGraph.compile({ checkpointer });
  await compiledGraph.updateState(
    { configurable: { thread_id: '1' } },
    // 传入 node 2 的状态——模拟 node 1 结束时的
    // 状态
    { my_key: 'initial_value' },
    // 更新保存的状态,就好像它来自 node 1
    // 执行将从 node 2 恢复
    'node1',
  );
  const result = await compiledGraph.invoke(
    // 通过传入 null 恢复执行
    null,
    {
      configurable: { thread_id: '1' },
      // 在 node 3 之后停止,这样 node 4 就不会运行
      interruptAfter: ['node3']
    },
  );
  expect(result.my_key).toBe('hello from node3');
});