重构 AI 智能体课程:Markdown 化,新增 ReAct 模块与案例
- 按 Python 课件的章节式结构重组为 9 个部分、24 章 - 新增 ReAct 模块:原理与手写实现、LangGraph 实现、create_agent、5 个案例 - 补齐 RAG、LangGraph 工作流、多智能体、任务调度 - 新增 3 个项目实战与部署评估章节 - 统一 '学习目标 / 概念 / 代码 / 小结 / 练习' 结构
This commit is contained in:
@@ -0,0 +1,274 @@
|
||||
# 记忆与人机协作
|
||||
|
||||
> **本章目标**:让图记住上一轮对话,并在关键动作前停下来等人点头。
|
||||
> **前置知识**:第 6.1、6.2 章。
|
||||
> **预计用时**:80 分钟。
|
||||
|
||||
## 1. 为什么图会「失忆」
|
||||
|
||||
```python
|
||||
graph.invoke({"messages": [HumanMessage("我叫小明")]})
|
||||
graph.invoke({"messages": [HumanMessage("我叫什么?")]})
|
||||
```
|
||||
|
||||
第二次调用是一个**全新的状态**,图不知道上一次发生了什么。
|
||||
|
||||
LangGraph 的解决方案是 **Checkpointer**:每执行一步,把状态快照存下来;下次用同一个 `thread_id`,就能接着用。
|
||||
|
||||
## 2. 最小记忆
|
||||
|
||||
```python
|
||||
# %%
|
||||
from typing import Annotated, TypedDict
|
||||
from langgraph.graph import StateGraph, START, END
|
||||
from langgraph.graph.message import add_messages
|
||||
from langgraph.checkpoint.memory import InMemorySaver
|
||||
from langchain_core.messages import AnyMessage, HumanMessage
|
||||
from dotenv import load_dotenv
|
||||
from langchain_openai import ChatOpenAI
|
||||
|
||||
load_dotenv()
|
||||
llm = ChatOpenAI(model="qwen3.6-35b-A3b", temperature=0.3)
|
||||
|
||||
class ChatState(TypedDict):
|
||||
messages: Annotated[list[AnyMessage], add_messages]
|
||||
|
||||
def chat(state: ChatState):
|
||||
reply = llm.invoke(state["messages"])
|
||||
return {"messages": [reply]}
|
||||
|
||||
builder = StateGraph(ChatState)
|
||||
builder.add_node("chat", chat)
|
||||
builder.add_edge(START, "chat")
|
||||
builder.add_edge("chat", END)
|
||||
|
||||
graph = builder.compile(checkpointer=InMemorySaver())
|
||||
```
|
||||
|
||||
关键就是 `compile(checkpointer=...)`。
|
||||
|
||||
```python
|
||||
# %%
|
||||
config = {"configurable": {"thread_id": "user_001"}}
|
||||
|
||||
r1 = graph.invoke({"messages": [HumanMessage("我叫小明,在做智能体课程设计")]}, config=config)
|
||||
print("AI:", r1["messages"][-1].content)
|
||||
|
||||
r2 = graph.invoke({"messages": [HumanMessage("我叫什么?在做什么?")]}, config=config)
|
||||
print("AI:", r2["messages"][-1].content)
|
||||
```
|
||||
|
||||
第二轮能答出「小明 / 智能体课程设计」,说明状态被恢复了。
|
||||
|
||||
## 3. thread_id 与多会话
|
||||
|
||||
```python
|
||||
# %%
|
||||
def ask(user_id: str, text: str):
|
||||
cfg = {"configurable": {"thread_id": user_id}}
|
||||
out = graph.invoke({"messages": [HumanMessage(text)]}, config=cfg)
|
||||
return out["messages"][-1].content
|
||||
|
||||
print(ask("alice", "我叫 Alice"))
|
||||
print(ask("bob", "我叫 Bob"))
|
||||
print(ask("alice", "我叫什么?")) # Alice
|
||||
print(ask("bob", "我叫什么?")) # Bob
|
||||
```
|
||||
|
||||
`thread_id` 就是会话主键。常见命名:
|
||||
|
||||
| 场景 | thread_id |
|
||||
| --- | --- |
|
||||
| 单用户多会话 | `{user_id}:{session_id}` |
|
||||
| 工单机器人 | `ticket:{ticket_id}` |
|
||||
| 每次任务独立 | `uuid4()` |
|
||||
|
||||
## 4. 记忆存哪儿
|
||||
|
||||
| Checkpointer | 存储 | 适用 |
|
||||
| --- | --- | --- |
|
||||
| `InMemorySaver` | 进程内存 | 教学、测试 |
|
||||
| `SqliteSaver` | 本地文件 | 单机小项目 |
|
||||
| `PostgresSaver` | 数据库 | 生产 |
|
||||
|
||||
```python
|
||||
# SQLite 示例(需 pip install langgraph-checkpoint-sqlite)
|
||||
# from langgraph.checkpoint.sqlite import SqliteSaver
|
||||
# with SqliteSaver.from_conn_string("checkpoints.db") as saver:
|
||||
# graph = builder.compile(checkpointer=saver)
|
||||
```
|
||||
|
||||
换成持久化存储后,进程重启也能接着聊。
|
||||
|
||||
## 5. 历史太长怎么办
|
||||
|
||||
消息越攒越多,token 会爆。两种处理:
|
||||
|
||||
### 5.1 滑动窗口
|
||||
|
||||
```python
|
||||
def trim(messages, max_messages=12):
|
||||
return messages[-max_messages:]
|
||||
```
|
||||
|
||||
在调用模型前裁剪,但**不要修改状态本身**(否则历史真的丢了)。
|
||||
|
||||
### 5.2 摘要压缩
|
||||
|
||||
```python
|
||||
# %%
|
||||
def summarize_old(messages, keep_last=6):
|
||||
if len(messages) <= keep_last:
|
||||
return messages
|
||||
old = messages[:-keep_last]
|
||||
summary = llm.invoke(
|
||||
"把下面这段对话压缩成 100 字以内的摘要,保留关键事实:\n" +
|
||||
"\n".join(f"{m.type}: {m.content}" for m in old)
|
||||
).content
|
||||
from langchain_core.messages import SystemMessage
|
||||
return [SystemMessage(content=f"之前对话的摘要:{summary}")] + messages[-keep_last:]
|
||||
```
|
||||
|
||||
生产里通常组合使用:**近期原文 + 远期摘要**。
|
||||
|
||||
## 6. 人工审批:interrupt
|
||||
|
||||
有些动作不能自动执行:退款、删库、发邮件、重启服务。
|
||||
|
||||
`interrupt()` 会在节点内部**暂停整个图**,把问题抛给调用方;等人回复后,用 `Command(resume=...)` 继续。
|
||||
|
||||
```text
|
||||
执行到 interrupt → 图暂停,返回 __interrupt__
|
||||
人类审批 → 调用方传入 Command(resume="yes")
|
||||
图从暂停处继续,interrupt() 返回 "yes"
|
||||
```
|
||||
|
||||
## 7. 完整审批案例
|
||||
|
||||
```python
|
||||
# %%
|
||||
from langgraph.types import interrupt, Command
|
||||
from langchain_core.messages import AIMessage
|
||||
|
||||
class ApprovalState(TypedDict):
|
||||
action: str
|
||||
amount: int
|
||||
decision: str
|
||||
result: str
|
||||
|
||||
def request_approval(state: ApprovalState):
|
||||
# 图会在这里暂停,把 value 交给外部
|
||||
decision = interrupt({
|
||||
"question": f"是否批准:{state['action']},金额 {state['amount']} 元?",
|
||||
"options": ["yes", "no"],
|
||||
})
|
||||
return {"decision": decision}
|
||||
|
||||
def execute(state: ApprovalState):
|
||||
if state["decision"] == "yes":
|
||||
return {"result": f"已执行:{state['action']} {state['amount']} 元"}
|
||||
return {"result": "已取消:人工拒绝"}
|
||||
|
||||
b = StateGraph(ApprovalState)
|
||||
b.add_node("request_approval", request_approval)
|
||||
b.add_node("execute", execute)
|
||||
b.add_edge(START, "request_approval")
|
||||
b.add_edge("request_approval", "execute")
|
||||
b.add_edge("execute", END)
|
||||
|
||||
approval_graph = b.compile(checkpointer=InMemorySaver())
|
||||
```
|
||||
|
||||
### 7.1 第一次运行:会停住
|
||||
|
||||
```python
|
||||
# %%
|
||||
config = {"configurable": {"thread_id": "refund_1001"}}
|
||||
|
||||
first = approval_graph.invoke(
|
||||
{"action": "退款", "amount": 3299, "decision": "", "result": ""},
|
||||
config=config,
|
||||
)
|
||||
|
||||
print(first)
|
||||
# {'action': '退款', ..., '__interrupt__': [Interrupt(value={'question': '是否批准:退款,金额 3299 元?'...})]}
|
||||
```
|
||||
|
||||
注意返回值里的 `__interrupt__`:这就是「等你审批」。
|
||||
|
||||
### 7.2 恢复执行
|
||||
|
||||
```python
|
||||
# %%
|
||||
second = approval_graph.invoke(Command(resume="yes"), config=config)
|
||||
print(second["result"])
|
||||
# 已执行:退款 3299 元
|
||||
```
|
||||
|
||||
`resume` 的值会成为 `interrupt()` 的返回值。所以节点里写:
|
||||
|
||||
```python
|
||||
decision = interrupt({...}) # 第一次暂停;恢复后 decision == "yes"
|
||||
```
|
||||
|
||||
**必须传同一个 `config`(同一个 thread_id)**,否则图找不到暂停点。
|
||||
|
||||
### 7.3 拒绝的情况
|
||||
|
||||
```python
|
||||
# 新的 thread
|
||||
cfg2 = {"configurable": {"thread_id": "refund_1002"}}
|
||||
approval_graph.invoke({"action": "退款", "amount": 999, "decision": "", "result": ""}, config=cfg2)
|
||||
out = approval_graph.invoke(Command(resume="no"), config=cfg2)
|
||||
print(out["result"]) # 已取消:人工拒绝
|
||||
```
|
||||
|
||||
## 8. interrupt 的三个要点
|
||||
|
||||
| 要点 | 说明 |
|
||||
| --- | --- |
|
||||
| 必须在节点内调用 | 不能写在路由函数或图外面 |
|
||||
| 必须有 checkpointer | 没有存盘点,恢复不了 |
|
||||
| 恢复要同一个 thread_id | 否则当成新会话 |
|
||||
|
||||
常见误解:以为 `interrupt` 会「阻塞程序」。实际上它**结束当前调用并返回**,等下一次 `invoke` 才继续。
|
||||
|
||||
## 9. 和 `create_agent` 结合
|
||||
|
||||
`create_agent` 也支持人工介入:
|
||||
|
||||
```python
|
||||
agent = create_agent(
|
||||
model=llm,
|
||||
tools=[...],
|
||||
checkpointer=InMemorySaver(),
|
||||
interrupt_before=["tools"], # 执行工具前暂停
|
||||
)
|
||||
```
|
||||
|
||||
执行到工具前会停下,人工检查 `tool_calls` 后再放行。这比自己包一层更省事。
|
||||
|
||||
## 10. 常见错误
|
||||
|
||||
| 现象 | 原因 | 解决 |
|
||||
| --- | --- | --- |
|
||||
| 第二轮失忆 | 没传 `checkpointer` | `compile(checkpointer=...)` |
|
||||
| 恢复了但重头开始 | `thread_id` 不一致 | 用同一个 config |
|
||||
| `interrupt` 没生效 | 没编译 checkpointer | 同上 |
|
||||
| 状态越存越大 | 没裁剪历史 | 滑动窗口 / 摘要 |
|
||||
| 并发串话 | 多人共用一个 thread | 按用户+会话隔离 |
|
||||
|
||||
## 11. 本章小结
|
||||
|
||||
- Checkpointer + thread_id 让图拥有跨调用记忆;
|
||||
- `InMemorySaver` 适合教学,生产用 SQLite/Postgres;
|
||||
- 历史要裁剪或摘要,否则 token 会失控;
|
||||
- `interrupt()` 暂停,`Command(resume=...)` 恢复;
|
||||
- 人工审批是高风险智能体的必备能力。
|
||||
|
||||
## 12. 练习
|
||||
|
||||
1. 用 `SqliteSaver` 替换内存版,重启进程后验证记忆还在;
|
||||
2. 给对话加「超过 10 条就摘要前 8 条」的逻辑;
|
||||
3. 把审批案例改成「金额 > 1000 才需要审批,否则直接执行」;
|
||||
4. 设计一个「审批被拒后让模型给出替代方案」的图。
|
||||
Reference in New Issue
Block a user