LangChain LangGraph
Module 1 Module 2 Module 3
Module 2 · 工具、状态与多 Agent
1 2.1 MCP
2 2.1 Travel Agent
3 2.2 Runtime Context
4 2.2 State
5 2.3 Multi Agent
6 2.4 Wedding Planners
7 Bonus: RAG
8 Bonus: SQL
SUM Module Summary
HomeLangChainModule 2 · 工具、状态与多 Agent2.2 State
📓 Notebook 📖 Explained
LANGCHAIN MODULE 2 · LESSON 2.2b

Agent State:跨步骤保存和读取信息
AgentState · Command · Checkpointer

本节展示如何扩展 AgentState、用工具写入 state,再通过 ToolRuntime 读取 state,让 Agent 在同一个 thread 中保留用户偏好。

1 State 和 Context 的区别

Runtime context 是调用方传入的临时信息;Agent state 是 Agent 自己在运行中维护的工作记忆。只要配置了 checkpointer,同一个 thread_id 后续调用可以继续读取 state。

维度Runtime ContextAgent State
谁提供调用方传入Agent 和工具运行时更新
是否持久默认不持久通过 checkpointer 按 thread 保存
本课例子ColourContext(favourite_colour="green")favourite_colour 写入 thread state

2 扩展 AgentState

Notebook 定义 CustomState,在默认 AgentState 基础上增加一个 favourite_colour 字段。

Python
from langchain.agents import AgentState

class CustomState(AgentState):
    favourite_colour: str
为什么继承 AgentState

AgentState 已经包含 Agent 必需的消息字段。继承它再加业务字段,可以避免破坏 Agent 的默认消息流。

3 用工具写入 state

工具不能直接随意修改外层变量,而是返回 Command(update=...)。这里同时更新 favourite_colour,并追加一条 ToolMessage 表示工具执行成功。

Python
from langchain.tools import tool, ToolRuntime
from langgraph.types import Command
from langchain.messages import ToolMessage

@tool
def update_favourite_colour(favourite_colour: str, runtime: ToolRuntime) -> Command:
    """Update the favourite colour of the user in the state once they've revealed it."""
    return Command(
        update={
            "favourite_colour": favourite_colour,
            "messages": [
                ToolMessage(
                    "Successfully updated favourite colour",
                    tool_call_id=runtime.tool_call_id,
                )
            ],
        }
    )
Command(update=...)

这是 LangGraph/LangChain Agent 中从 tool 返回状态更新的标准方式。它比隐藏副作用更清晰,也更容易被 checkpointer 记录。

4 配置 checkpointer 和 state_schema

要让 state 跨调用保存,Agent 需要 checkpointer。Notebook 使用内存版 InMemorySaver,适合课程演示。

Python
from langgraph.checkpoint.memory import InMemorySaver

agent = create_agent(
    deepseek_model(),
    tools=[update_favourite_colour],
    checkpointer=InMemorySaver(),
    state_schema=CustomState,
)

response = agent.invoke(
    {"messages": [HumanMessage(content="My favourite colour is green")]},
    {"configurable": {"thread_id": "1"}},
)
thread_id 很重要

checkpointer 按 thread 区分记忆。同一个 thread_id 可以读到之前写入的 state;换一个 thread 就是另一份记忆。

5 通过 ToolRuntime 读取 state

读取 state 的工具从 runtime.state 取值。如果当前 thread 还没有写入对应字段,就返回一个明确的 fallback 文案。

Python
@tool
def read_favourite_colour(runtime: ToolRuntime) -> str:
    """Read the favourite colour of the user from the state."""
    try:
        return runtime.state["favourite_colour"]
    except KeyError:
        return "No favourite colour found in state"

agent = create_agent(
    deepseek_model(),
    tools=[update_favourite_colour, read_favourite_colour],
    checkpointer=InMemorySaver(),
    state_schema=CustomState,
)
读写闭环

用户说出偏好时,模型调用写入工具;后续用户询问偏好时,模型调用读取工具。同一个 thread 中这就是可持续的 Agent 记忆。

6 State 设计建议