本节展示如何扩展 AgentState、用工具写入 state,再通过 ToolRuntime 读取 state,让 Agent 在同一个 thread 中保留用户偏好。
Runtime context 是调用方传入的临时信息;Agent state 是 Agent 自己在运行中维护的工作记忆。只要配置了 checkpointer,同一个 thread_id 后续调用可以继续读取 state。
| 维度 | Runtime Context | Agent State |
|---|---|---|
| 谁提供 | 调用方传入 | Agent 和工具运行时更新 |
| 是否持久 | 默认不持久 | 通过 checkpointer 按 thread 保存 |
| 本课例子 | ColourContext(favourite_colour="green") | favourite_colour 写入 thread state |
Notebook 定义 CustomState,在默认 AgentState 基础上增加一个 favourite_colour 字段。
from langchain.agents import AgentState
class CustomState(AgentState):
favourite_colour: strAgentState 已经包含 Agent 必需的消息字段。继承它再加业务字段,可以避免破坏 Agent 的默认消息流。
工具不能直接随意修改外层变量,而是返回 Command(update=...)。这里同时更新 favourite_colour,并追加一条 ToolMessage 表示工具执行成功。
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,
)
],
}
)这是 LangGraph/LangChain Agent 中从 tool 返回状态更新的标准方式。它比隐藏副作用更清晰,也更容易被 checkpointer 记录。
要让 state 跨调用保存,Agent 需要 checkpointer。Notebook 使用内存版 InMemorySaver,适合课程演示。
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"}},
)checkpointer 按 thread 区分记忆。同一个 thread_id 可以读到之前写入的 state;换一个 thread 就是另一份记忆。
读取 state 的工具从 runtime.state 取值。如果当前 thread 还没有写入对应字段,就返回一个明确的 fallback 文案。
@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 记忆。
favourite_colour,不要塞一个模糊的大字典。Command(update=...),同时写必要的 ToolMessage。InMemorySaver;生产环境需要换成持久化 checkpointer。