如果没有记忆,Agent 每一轮都是孤立的。用户说“那上海呢?”时,模型可能根本不知道你还在问天气。
1. 为什么需要记忆
没有记忆时:
```text 用户:北京天气怎么样? Agent:北京:晴,温度 2°C
用户:那上海呢? Agent:我不知道你在问什么 ```
有记忆时:
```text 用户:北京天气怎么样? Agent:北京:晴,温度 2°C
用户:那上海呢? Agent:上海:多云,温度 8°C ```
2. 使用 LangGraph Checkpointer
```python from langgraph.checkpoint.memory import InMemorySaver
memory = InMemorySaver() agent = create_agent(llm, tools, checkpointer=memory) ```
`InMemorySaver` 会把会话上下文保存在内存里,适合本地演示和开发阶段。
3. 使用 `thread_id` 区分会话
```python config = {"configurable": {"thread_id": "user-001"}}
agent.invoke( {"messages": [{"role": "user", "content": "北京天气怎么样?"}]}, config, )
agent.invoke( {"messages": [{"role": "user", "content": "那上海呢?"}]}, config, ) ```
只要两次调用使用同一个 `thread_id`,模型就会把它们视为同一段连续对话。
4. 多轮对话示例
```python if name == "main": print("=" * 60) print("第三课:Agent 记忆与多轮对话") print("=" * 60)
config = {"configurable": {"thread_id": "demo-conversation"}}
conversations = [
"北京天气怎么样?",
"那上海呢?",
"哪个城市更冷?",
]
for i, question in enumerate(conversations, 1):
print(f"\n第 {i} 轮对话")
print(f"用户: {question}\n")
result = agent.invoke(
{"messages": [{"role": "user", "content": question}]},
config,
)
for msg in result["messages"]:
if type(msg).__name__ == "ToolMessage":
print(f"工具 [{msg.name}] 返回: {msg.content}")
print(f"\nAgent: {result['messages'][-1].content}")
```
5. 持久化记忆
`InMemorySaver` 重启程序后会丢失数据。生产环境一般会换成数据库检查点,例如 PostgreSQL:
```python from langgraph.checkpoint.postgres import PostgresSaver
DB_URI = "postgresql://postgres:postgres@localhost:5442/postgres?sslmode=disable"
with PostgresSaver.from_conn_string(DB_URI) as checkpointer: checkpointer.setup() agent = create_agent( llm, tools=tools, checkpointer=checkpointer, ) ```
6. 这一课的重点
- 记忆不是“模型自动会记住”,而是靠外部 checkpointer 管理
- `thread_id` 是多轮对话的关键
- 做聊天产品时,会话隔离和持久化要尽早设计