单元测试隔离地演练代理的小型、确定性部分。通过用内存假(也称为装置)替换真实 LLM,您可以编写精确的响应(文本、工具调用和错误),使测试快速、免费且可重复,无需 API 密钥。

模拟聊天模型

LangChain 提供 GenericFakeChatModel 用于模拟文本响应。它接受响应迭代器(AIMessage 对象或字符串),每次调用返回一个。它支持常规和流式使用。
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel

model = GenericFakeChatModel(messages=iter([
    AIMessage(content="", tool_calls=[ToolCall(name="foo", args={"bar": "baz"}, id="call_1")]),
    "bar"
]))

model.invoke("hello")
# AIMessage(content='', ..., tool_calls=[{'name': 'foo', 'args': {'bar': 'baz'}, 'id': 'call_1', 'type': 'tool_call'}])
如果我们再次调用模型,它将返回迭代器中的下一项:
model.invoke("hello, again!")
# AIMessage(content='bar', ...)

InMemorySaver 检查点

为了在测试期间启用持久化,您可以使用 InMemorySaver 检查点。这允许您模拟多轮对话以测试依赖于状态的行为:
from langgraph.checkpoint.memory import InMemorySaver

agent = create_agent(
    model,
    tools=[],
    checkpointer=InMemorySaver()
)

# First invocation
agent.invoke(
    {"messages": [HumanMessage(content="I live in Sydney, Australia")]},
    config={"configurable": {"thread_id": "session-1"}}
)

# Second invocation: the first message is persisted (Sydney location), so the model returns GMT+10 time
agent.invoke(
    {"messages": [HumanMessage(content="What's my local time?")]},
    config={"configurable": {"thread_id": "session-1"}}
)

下一步

了解如何在 集成测试 中使用真实模型提供商 API 测试您的代理。