LangGraph Agent Memory Detailed interpretation
📚 Overview
This document explains in detail the Agent Memory mechanism in LangGraph. This is the core technology for building a multi-turn dialogue system, allowing AI agents to remember previous dialogue content and achieve true context continuity.
🎯 Core Concept
What is Agent Memory?
Agent Memory is a persistence mechanism provided by LangGraph that allows agents to maintain state between multiple interactions. Like human memory, it allows AI to:
- Remember Historical Conversations: Recall what was said before
- Understanding contextual references: Understand pronouns such as "that" and "it"
- Maintain Continuity: Continue the conversation after interruption
- Maintain Session State: Track task progress and data
Why do you need Memory?
No problem with Memory:
# 第一轮对话
user: "3 + 4 等于多少?"
agent: "等于 7"
# 第二轮对话(新的图执行)
user: "把它乘以 2"
agent: "把什么乘以 2?" ❌ 记不住 7With the effect of Memory:
# 第一轮对话
user: "3 + 4 等于多少?"
agent: "等于 7"
# 第二轮对话(继续之前的状态)
user: "把它乘以 2"
agent: "7 × 2 = 14" ✅ 记住了 7🔧 Detailed explanation of technical implementation
1. The root of the problem: the temporary nature of the state
In LangGraph, state is temporary by default and only exists during a single graph execution.
# 每次调用 invoke() 都是全新的执行
react_graph.invoke({"messages": [msg1]}) # 执行 1:有 msg1
react_graph.invoke({"messages": [msg2]}) # 执行 2:只有 msg2,忘记 msg1Problem diagram:
执行 1 执行 2
┌─────────────┐ ┌─────────────┐
│ State │ │ State │
│ msg: [msg1] │ │ msg: [msg2] │ ← 完全独立,互不相关
└─────────────┘ └─────────────┘2. Solution: Checkpointer
LangGraph provides a Checkpointer mechanism to automatically save state after each step.
Core Principles
from langgraph.checkpoint.memory import MemorySaver
# 创建内存检查点器
memory = MemorySaver()
# 编译图时注入检查点器
graph_with_memory = builder.compile(checkpointer=memory)Workflow:
用户输入 → [节点 1] → 💾 保存状态 → [节点 2] → 💾 保存状态 → 输出
↓ ↓
Checkpoint 1 Checkpoint 2After each node is executed, the current state is saved to a checkpoint.
3. Thread: session thread
To manage multiple independent conversations, LangGraph uses the Thread concept.
The role of Thread ID
# 配置:指定线程 ID
config = {"configurable": {"thread_id": "1"}}
# 第一轮对话
graph.invoke({"messages": [msg1]}, config) # 保存到 thread_id=1
# 第二轮对话(同一线程)
graph.invoke({"messages": [msg2]}, config) # 继续 thread_id=1 的状态Thread diagram:
Thread ID: 1 Thread ID: 2
┌─────────────────┐ ┌─────────────────┐
│ Checkpoint 1 │ │ Checkpoint 1 │
│ Checkpoint 2 │ │ Checkpoint 2 │
│ Checkpoint 3 │ └─────────────────┘
└─────────────────┘
↑ 用户 A 的对话 ↑ 用户 B 的对话(独立)Each thread_id maintains an independent conversation history without interfering with each other.
📖 Complete code implementation
1. Environment settings
# 安装依赖
%pip install --quiet -U langchain_openai langchain_core langgraph
# 设置 API Key
import os, getpass
def _set_env(var: str):
if not os.environ.get(var):
os.environ[var] = getpass.getpass(f"{var}: ")
_set_env("OPENAI_API_KEY")
_set_env("LANGSMITH_API_KEY")
os.environ["LANGSMITH_TRACING"] = "true"
os.environ["LANGSMITH_PROJECT"] = "langchain-academy"Description:
OPENAI_API_KEY: Call GPT modelLANGSMITH_API_KEY: Enable LangSmith tracing (visualization of execution flow)
2. Define tools
from langchain_openai import ChatOpenAI
def add(a: int, b: int) -> int:
"""Adds a and b.
Args:
a: first int
b: second int
"""
return a + b
def multiply(a: int, b: int) -> int:
"""Multiply a and b.
Args:
a: first int
b: second int
"""
return a * b
def divide(a: int, b: int) -> float:
"""Divide a and b.
Args:
a: first int
b: second int
"""
return a / b
# 工具列表
tools = [add, multiply, divide]
# 创建 LLM 并绑定工具
llm = ChatOpenAI(model="gpt-4o")
llm_with_tools = llm.bind_tools(tools)Python knowledge points: The importance of Docstring
def add(a: int, b: int) -> int:
"""Adds a and b. # ← LLM 会读取这段描述
Args:
a: first int # ← 参数说明帮助 LLM 理解如何调用
b: second int
"""
return a + b- LLM understands tool functionality through Docstring
- Clear descriptions can improve the accuracy of tool calls
- Follow Google style Docstring specification
3. Define states and nodes
from langgraph.graph import MessagesState
from langchain_core.messages import HumanMessage, SystemMessage
# 系统消息
sys_msg = SystemMessage(
content="You are a helpful assistant tasked with performing arithmetic on a set of inputs."
)
# 定义助手节点
def assistant(state: MessagesState):
return {"messages": [llm_with_tools.invoke([sys_msg] + state["messages"])]}LangGraph knowledge point: MessagesState
MessagesState is LangGraph's predefined state class, specifically used for message management:
class MessagesState(TypedDict):
messages: Annotated[list, add_messages]
# ^^^^^^^^^^^^^^^^^^^^^^^^^^
# 自动处理消息列表的追加和去重Features:
- Auto-Append: New messages are automatically added to the end of the list
- Intelligent deduplication: Messages with the same ID will be updated instead of duplicated
- Easy Access: Direct access via
state["messages"]
4. Build graph (without Memory)
from langgraph.graph import START, StateGraph
from langgraph.prebuilt import tools_condition, ToolNode
from IPython.display import Image, display
# 创建图构建器
builder = StateGraph(MessagesState)
# 添加节点
builder.add_node("assistant", assistant)
builder.add_node("tools", ToolNode(tools))
# 添加边
builder.add_edge(START, "assistant")
# 条件边:决定是否调用工具
builder.add_conditional_edges(
"assistant",
tools_condition, # 如果 assistant 返回工具调用 → tools 节点
# 否则 → END
)
builder.add_edge("tools", "assistant")
# 编译(无 Memory)
react_graph = builder.compile()
# 可视化
display(Image(react_graph.get_graph(xray=True).draw_mermaid_png()))LangGraph knowledge point: tools_condition
tools_condition is LangGraph’s predefined conditional function:
def tools_condition(state: MessagesState) -> Literal["tools", "__end__"]:
"""检查最后一条消息是否包含工具调用"""
last_message = state["messages"][-1]
if last_message.tool_calls:
return "tools" # 有工具调用 → 进入 tools 节点
return "__end__" # 无工具调用 → 结束The role of ToolNode:
ToolNode(tools)- Automate tool calls
- Wrap tool output into
ToolMessage - Add to message list
5. Test the problem without Memory
First round of dialogue
messages = [HumanMessage(content="Add 3 and 4.")]
messages = react_graph.invoke({"messages": messages})
for m in messages['messages']:
m.pretty_print()Output:
================================ Human Message =================================
Add 3 and 4.
================================== Ai Message ==================================
Tool Calls:
add (call_zZ4JPASfUinchT8wOqg9hCZO)
Args:
a: 3
b: 4
================================= Tool Message =================================
Name: add
7
================================== Ai Message ==================================
The sum of 3 and 4 is 7.Second round of dialogue (problems arise)
messages = [HumanMessage(content="Multiply that by 2.")]
messages = react_graph.invoke({"messages": messages})
for m in messages['messages']:
m.pretty_print()Output:
================================ Human Message =================================
Multiply that by 2.
================================== Ai Message ==================================
Tool Calls:
multiply (call_prnkuG7OYQtbrtVQmH2d3Nl7)
Args:
a: 2 # ❌ 错误!应该是 7
b: 2
================================= Tool Message =================================
Name: multiply
4
================================== Ai Message ==================================
The result of multiplying 2 by 2 is 4. # ❌ 应该是 14Problem Analysis:
- LLM Don't know what "that" refers to
- Because every time
invoke()is a brand new execution, there is no historical context - LLM only sees "Multiply that by 2." and cannot understand the meaning of "that"
6. Add Memory
from langgraph.checkpoint.memory import MemorySaver
# 创建内存检查点器
memory = MemorySaver()
# 重新编译图(带 Memory)
react_graph_memory = builder.compile(checkpointer=memory)MemorySaver detailed explanation:
| Features | Description |
|---|---|
| Type | In-memory key-value storage |
| Persistence | Only while the process is running |
| Purpose | Development, testing, demonstration |
| Production Alternatives | PostgresSaver, RedisSaver, etc. |
**Why not for production? **
memory = MemorySaver() # 数据存在内存中
# 问题:
# 1. 进程重启 → 数据丢失
# 2. 多进程部署 → 数据不共享
# 3. 无法持久化存储Recommended for production environment:
from langgraph.checkpoint.postgres import PostgresSaver
# 连接数据库
checkpointer = PostgresSaver.from_conn_string(
"postgresql://user:pass@localhost/db"
)
graph = builder.compile(checkpointer=checkpointer)7. Use Thread ID
# 配置线程 ID
config = {"configurable": {"thread_id": "1"}}
# 第一轮对话
messages = [HumanMessage(content="Add 3 and 4.")]
messages = react_graph_memory.invoke({"messages": messages}, config)
for m in messages['messages']:
m.pretty_print()Output:
================================ Human Message =================================
Add 3 and 4.
================================== Ai Message ==================================
Tool Calls:
add (call_MSupVAgej4PShIZs7NXOE6En)
Args:
a: 3
b: 4
================================= Tool Message =================================
Name: add
7
================================== Ai Message ==================================
The sum of 3 and 4 is 7.Checkpoint saving instructions:
Thread ID: 1
├─ Checkpoint 0: {"messages": [HumanMessage("Add 3 and 4.")]}
├─ Checkpoint 1: {"messages": [..., AIMessage(tool_calls=[...])]}
├─ Checkpoint 2: {"messages": [..., ToolMessage("7")]}
└─ Checkpoint 3: {"messages": [..., AIMessage("The sum is 7.")]}8. Continue the conversation (Memory takes effect)
# 同一线程,新消息
messages = [HumanMessage(content="Multiply that by 2.")]
messages = react_graph_memory.invoke({"messages": messages}, config)
for m in messages['messages']:
m.pretty_print()Output:
================================ Human Message =================================
Add 3 and 4.
↑ 历史消息(从检查点加载)
================================== Ai Message ==================================
Tool Calls:
add (...)
Args:
a: 3
b: 4
================================= Tool Message =================================
Name: add
7
================================== Ai Message ==================================
The sum of 3 and 4 is 7.
================================ Human Message =================================
Multiply that by 2.
↑ 新消息(追加到历史)
================================== Ai Message ==================================
Tool Calls:
multiply (call_fWN7lnSZZm82tAg7RGeuWusO)
Args:
a: 7 # ✅ 正确!记住了之前的 7
b: 2
================================= Tool Message =================================
Name: multiply
14
================================== Ai Message ==================================
The result of multiplying 7 by 2 is 14. # ✅ 正确答案Key Observations:
- Historical messages automatically loaded: The output contains all messages from the first round of dialogue
- Contextual understanding: LLM knows that "that" refers to 7
- Correct Calculation: 7 × 2 = 14
🎓 Summary of core knowledge points
LangGraph-specific concepts
1. Checkpointer
Function: Automatically save the state after each node is executed
from langgraph.checkpoint.memory import MemorySaver
memory = MemorySaver()
graph = builder.compile(checkpointer=memory)Save time:
节点执行前 节点执行 节点执行后
↓ ↓ ↓
加载状态 → 处理数据 → 💾 保存状态2. Thread
Function: Isolate the status of different users/sessions
# 用户 A
config_a = {"configurable": {"thread_id": "user_a"}}
graph.invoke(input, config_a)
# 用户 B(完全独立)
config_b = {"configurable": {"thread_id": "user_b"}}
graph.invoke(input, config_b)Thread hierarchy:
Checkpointer(全局)
├─ Thread: user_a
│ ├─ Checkpoint 1
│ ├─ Checkpoint 2
│ └─ Checkpoint 3
├─ Thread: user_b
│ ├─ Checkpoint 1
│ └─ Checkpoint 2
└─ Thread: user_c
└─ Checkpoint 13. Config
config = {
"configurable": {
"thread_id": "1", # 必需:线程标识
"checkpoint_id": "...", # 可选:特定检查点
"checkpoint_ns": "..." # 可选:检查点命名空间
}
}The role of configurable:
- Pass runtime configuration
- Does not affect the state structure
- for checkpoint management
Python-specific knowledge points
1. Type Hints
def add(a: int, b: int) -> int:
# ^^^^^ ^^^^^ ^^^
# 参数类型 返回类型
return a + bAdvantages:
- IDE support: auto-completion, type checking
- Documentation Function: Clarify function signature
- LangChain Integration: Automatically convert to tool mode
2. Docstring (documentation string)
def multiply(a: int, b: int) -> int:
"""Multiply a and b. # 功能描述
Args: # 参数说明
a: first int
b: second int
"""
return a * b**How does LangChain use Docstring? **
# LangChain 自动解析函数签名
tools = [multiply]
# 生成工具模式(OpenAI Function Calling 格式)
{
"name": "multiply",
"description": "Multiply a and b.", # ← 来自 Docstring
"parameters": {
"type": "object",
"properties": {
"a": {"type": "integer", "description": "first int"},
"b": {"type": "integer", "description": "second int"}
}
}
}3. Literal (literal type)
from typing import Literal
def route(state) -> Literal["tools", "__end__"]:
# ^^^^^^^^^^^^^^^^^^^^^^^^
# 返回值只能是这两个字符串之一
if condition:
return "tools"
return "__end__"Function:
- Limit the return value range
- IDE can check for spelling errors
- Improve code reliability
💡 Best Practices
1. When to use Memory?
✅ Applicable scenarios:
- Multi-turn dialogue system (chatbot)
- Tasks that require context ("continue", "that", etc. references)
- Long-term task tracking (task progress, user preferences)
- Debugging and auditing (view historical executions)
❌ Not applicable scenarios:
- Stateless API (each request is independent)
- Batch tasks (no memory required)
- One-time query (single Q&A of Q&A system)
2. Thread ID design principles
Principle 1: Isolate by user
# ✅ 好的设计
config = {"configurable": {"thread_id": f"user_{user_id}"}}
# ❌ 不好的设计
config = {"configurable": {"thread_id": "global"}} # 所有用户共享Principle 2: Isolate by session
# ✅ 更细粒度的隔离
import uuid
session_id = str(uuid.uuid4())
config = {"configurable": {"thread_id": f"{user_id}_{session_id}"}}Principle 3: Meaningful naming
# ✅ 清晰的命名
thread_id = f"support_ticket_{ticket_id}"
thread_id = f"order_processing_{order_id}"
# ❌ 无意义的命名
thread_id = "123"
thread_id = "abc"3. Checkpointer selection
| Scenario | Recommended Checkpointer | Reason |
|---|---|---|
| Develop/Test | MemorySaver | Simple and fast |
| Production (small scale) | SqliteSaver | Persistence, stand-alone deployment |
| Production (distributed) | PostgresSaver | Supports concurrency and scalability |
| High performance | RedisSaver | Low latency, high throughput |
Example: Production environment configuration
from langgraph.checkpoint.postgres import PostgresSaver
# 数据库连接
checkpointer = PostgresSaver.from_conn_string(
"postgresql://user:pass@localhost/langchain_db"
)
# 编译图
graph = builder.compile(checkpointer=checkpointer)
# 使用(与 MemorySaver 完全相同)
config = {"configurable": {"thread_id": "user_123"}}
graph.invoke(input, config)🚀 Advanced skills
1. Checkpoint history query
# 获取线程的所有检查点
config = {"configurable": {"thread_id": "1"}}
# 列出所有检查点
checkpoints = list(graph.checkpointer.list(config))
for checkpoint in checkpoints:
print(f"Checkpoint ID: {checkpoint.id}")
print(f"State: {checkpoint.state}")2. Backtrack to a specific checkpoint
# 获取特定检查点的状态
config = {
"configurable": {
"thread_id": "1",
"checkpoint_id": "abc123" # 指定检查点
}
}
# 从这个检查点继续执行
graph.invoke(new_input, config)3. Clean old checkpoints
# 删除线程的所有检查点
config = {"configurable": {"thread_id": "1"}}
graph.checkpointer.delete_thread(config)4. Conditional save
# 只在特定条件下保存检查点
def conditional_checkpoint(state):
if state.get("important"):
# 保存
return state
else:
# 跳过保存(通过自定义逻辑)
pass📊 Memory vs No Memory comparison
| Features | Without Memory | With Memory |
|---|---|---|
| State Persistence | ❌ | ✅ |
| Multiple rounds of dialogue | ❌ | ✅ |
| Contextual Quote | ❌ | ✅ |
| Debugging convenience | ❌ | ✅ |
| Performance Overhead | Low | Medium (depends on Checkpointer) |
| Storage Requirements | None | Yes |
| Applicable scenarios | Single query | Dialogue system |
🎯 Practical application cases
Case 1: Customer service robot
# 用户开始对话
config = {"configurable": {"thread_id": f"customer_{customer_id}"}}
# 第 1 轮
user: "我的订单号是 12345"
agent: "好的,我看到您的订单 12345 了"
# 第 2 轮(几分钟后)
user: "那个订单发货了吗?"
agent: "订单 12345 已于今天上午发货" # ✅ 记住了订单号Case 2: Multi-step task
# 数据分析任务
config = {"configurable": {"thread_id": f"analysis_{task_id}"}}
# 步骤 1
user: "加载 sales.csv"
agent: "已加载 1000 条销售记录"
# 步骤 2
user: "计算总收入"
agent: "总收入:$50,000" # ✅ 记住了加载的数据
# 步骤 3
user: "生成图表"
agent: "已生成收入趋势图" # ✅ 基于之前的计算Case 3: User preference learning
# 长期用户交互
config = {"configurable": {"thread_id": f"user_{user_id}"}}
# 第 1 次交互
user: "我喜欢简洁的回答"
agent: "好的,我会简洁回复"
# 第 100 次交互(数天后)
user: "解释量子计算"
agent: "简单说:用量子态并行计算" # ✅ 记住了用户偏好🔍 Frequently Asked Questions
Q1: What is the difference between MemorySaver and Database Checkpointer?
MemorySaver:
- Data is stored in Python process memory
- Process restart → data loss
- Suitable for development and testing
PostgresSaver:
- Data is stored in database
- Persistent storage -Support distributed deployment
- Suitable for production environment
Q2: How to achieve multi-user isolation?
Use a different thread_id:
# 用户 A
config_a = {"configurable": {"thread_id": "user_123"}}
graph.invoke(input_a, config_a)
# 用户 B(完全独立)
config_b = {"configurable": {"thread_id": "user_456"}}
graph.invoke(input_b, config_b)Q3: How much storage space will checkpoints take up?
Depends on:
- Number and size of messages
- Checkpoint retention policy
- State complexity
Optimization suggestions:
# 1. 定期清理旧线程
if thread_inactive_for_days(30):
checkpointer.delete_thread(config)
# 2. 限制消息历史长度
def trim_messages(state):
# 只保留最近 50 条消息
state["messages"] = state["messages"][-50:]
return stateQ4: Can Memory be shared between different graphs?
Yes, as long as you use the same checkpointer and thread_id:
# 共享检查点器
shared_memory = MemorySaver()
graph_1 = builder_1.compile(checkpointer=shared_memory)
graph_2 = builder_2.compile(checkpointer=shared_memory)
# 使用相同的 thread_id
config = {"configurable": {"thread_id": "shared_thread"}}
graph_1.invoke(input_1, config) # 写入状态
graph_2.invoke(input_2, config) # 读取相同状态Note: The state structures of the two graphs must be compatible!
📖 Further reading
- LangGraph Persistence official document
- Checkpointer interface detailed explanation
- Memory Management Best Practices
🎬 Summary
Agent Memory is the basic capability of LangGraph to build a multi-turn dialogue system:
- Checkpointer automatically saves the status of each step
- Thread ID isolates data from different users/sessions
- Config passes runtime configuration to control checkpoint behavior
Through these mechanisms, we can build an intelligent agent that truly has "memory" and achieve natural and coherent multiple rounds of interaction!
Core Points:
MemorySaverfor development,PostgresSaverfor production- Use unique
thread_idper user/session - Regularly clean up useless checkpoint data
- Combined with LangSmith tracing to debug Memory behavior