s05:TodoWrite——没有计划,做着做着就偏了
s05:TodoWrite——没有计划,做着做着就偏了
“没有计划的 agent 走哪算哪。” ——先列步骤再动手,长任务不容易漏项。
问题
给 Agent 一个复杂任务:”把所有 Python 文件改成 snake_case 命名,然后跑测试,修好失败。”
Agent 开始干活,改了 3 个文件,跑了个测试,发现 2 个失败,开始修。修着修着,它忘了最初是”改成 snake_case”——测试失败把注意力全吸走了。
对话越长越严重:工具结果不断填满上下文,系统提示的影响力被稀释。一个 10 步重构,做完 1-3 步就开始即兴发挥,因为 4-10 步已经被挤出注意力了。
解决方案
新增 todo_write 工具——它本身不做任何实际工作,不能读文件、不能跑命令,只是让 Agent 在动手之前先理清思路。
加上一个 reminder 机制:连续 3 轮没调 todo_write 就注入一条提醒。
工作原理
todo_write 工具:接收一个带状态的列表,保存在当前进程内存中,同时在终端显示进度:
CURRENT_TODOS: list[dict] = []
def run_todo_write(todos: list) -> str:
global CURRENT_TODOS
CURRENT_TODOS = todos
lines = ["\n## Current Tasks"]
for t in CURRENT_TODOS:
icon = {"pending": " ", "in_progress": "▸", "completed": "✓"}[t["status"]]
lines.append(f" [{icon}] {t['content']}")
print("\n".join(lines))
return f"Updated {len(CURRENT_TODOS)} tasks"
工具注册和其他工具一样:
TOOLS.append({
"name": "todo_write",
"description": "Create and manage a task list ...",
"input_schema": {
"type": "object",
"properties": {
"todos": {"type": "array", "items": {
"type": "object",
"properties": {
"content": {"type": "string"},
"status": {"type": "string",
"enum": ["pending", "in_progress", "completed"]},
},
}},
},
},
})
TOOL_HANDLERS["todo_write"] = run_todo_write
Nag reminder:连续 3 轮没调 todo_write 时自动注入提醒:
if rounds_since_todo >= 3:
messages.append({
"role": "user",
"content": "<reminder>Update your todos.</reminder>",
})
rounds_since_todo = 0
典型流程:Agent 先调 todo_write 列出所有步骤(全 pending)→ 做一个,改成 in_progress → 做完改 completed → 下一个 pending → 继续。
关键洞察:todo_write 不给 Agent 增加任何执行能力。它增加的是规划能力。
对比上一章
| 组件 | s04 | s05 |
|---|---|---|
| 工具数量 | 5 | 6 (+todo_write) |
| 规划能力 | 无 | 带状态的 TODO 列表 + nag reminder |
| SYSTEM 提示 | 通用 | 加入 “先计划再执行” 引导 |
| 循环 | 不变 | 新增 rounds_since_todo 计数器和 reminder 注入 |
试一下
python s05_todo_write/code.py
试试:
- 让它重构一个文件:加 type hints、docstrings、main guard
- 让它创建一个 Python package
观察:第一次工具调用是不是 todo_write?执行过程中状态有没有从 pending 变成 in_progress / completed?
接下来
Agent 能计划了。但如果一个任务太大——比如”重构整个认证模块”——光靠 TODO 列表不够。这个任务本身就是几十个小任务的集合,放在同一个对话里会被上下文淹没。
s06 Subagent → 把大任务拆成子任务,每个子任务派一个独立的 Agent。它们有自己的干净上下文,不会互相污染。