AI 代理如何处理追问(ReAct,版本 5,无记忆)?
版本 4把代理变成了一 个可以重复使用的函数。版本 5 连续调用它两次:先问“Mark 何时推出 Muse?”, 然后是一个自然的追问,“香港现在能用了吗?”。人类读者一听就知“它”指 什么,代理却不知道 —— 而看着它发现这一点,正是这一课。
脚本
这是 ReAct05.py。除了最后两行,每一行都与版本 4 完全相同
—— 现在有两次调用:
def perform_task(task):
"""Run the Think -> Act -> Observe loop for one task and return the answer."""
prompt = f"""Task: {task}
You can use ONE tool: search[query] searches the web (Tavily) and returns the top results.
Today is {datetime.now().strftime('%Y-%m-%d')}.
Work in steps. Each step has a Thought, an Action, and an Observation."""
for step in range(1, 6): # at most 5 rounds, so it cannot loop forever
thought = ask(prompt + f"\n\nThought {step}: (reason briefly about what to do next; do not act yet)",
stop=["Action"])
print(f"=== Round {step} - Thought ===")
print(thought)
prompt = prompt + f"\n\nThought {step}: {thought}"
action = ask(prompt + "\n\nWhat action should be taken based on that? "
"Reply with ONLY: search[query] or finish[answer]").strip()
print(f"=== Round {step} - Action chosen by the model ===")
print(action)
if action.startswith("finish"):
found = re.search(r"finish\[(.*)\]", action, re.S)
answer = found.group(1) if found else action
print("=== Final Answer ===")
print(answer)
return answer
query = re.search(r"search\[(.*)\]", action, re.S)
observation = search_tavily(query.group(1)) if query else "Invalid action."
print(f"=== Round {step} - Observation from Tavily web search ===")
print(observation)
prompt = prompt + f"\nAction {step}: {action}\nObservation {step}: {observation}"
else:
print("=== Stopped: no answer after 5 rounds ===")
perform_task("When did Mark launch Muse")
perform_task("Is it available in Hong Kong yet?")
代码中唯一要看的地方
看 perform_task 内的第一行:每次调用这个函数,提示词都是
从零开始建立的。第一次调用的任何东西 —— 问题、搜索、答案
—— 都不会留到第二次。函数可以重复使用,但同时也是无状态的:
两次调用就是两个陌生人。
一次真实运行
--- Task 1: "When did Mark launch Muse" ---
...four rounds of searching; sources disagree by one day...
=== Final Answer ===
Meta (Mark Zuckerberg) launched Muse, its personal AI agent, on September 8, 2026 (with some outlets citing September 9, 2026).
--- Task 2: "Is it available in Hong Kong yet?" ---
=== Round 1 - Thought ===
Thought 1: The query is ambiguous because "it" isn't specified. I need to figure out what product or service the user is asking about. Since the user only wrote "Is it available in Hong Kong yet?" with no prior context, I don't know the referent... The correct move in a real scenario is to ask the user. But the format forces me to do a search. I'll do a broad search on "available in Hong Kong 2026"...
=== Round 1 - Action chosen by the model ===
search[available in Hong Kong 2026]
=== Round 1 - Observation from Tavily web search ===
[Hong Kong 2026 | CanJam] ...headphone festival, tickets...
[Hong Kong Eats 2026 - Hungry Onion] ...restaurant chat...
[Hong Kong Conditions Report 2026 - US Department of State] ...policy report...
=== Round 2 - Thought ===
Thought 2: The search results ... don't reveal what product or service the user is asking about... I cannot determine the answer. I should state that clarification is needed...
=== Round 2 - Action chosen by the model ===
finish[I can't determine whether "it" is available in Hong Kong because the item/service isn't specified. Please tell me what "it" refers to (e.g., a product, app, game, streaming service, payment feature), and I'll check availability in Hong Kong.]
任务 1 一如以往运行正常。任务 2 才是有趣的失败:模型立刻察觉到含糊之处,用一次
搜索证明盲目查询只会换来耳机节和签证报告,然后用 finish[] 做唯一
诚实的事 —— 要求澄清。这个行为值得欣赏,但设计上的缺陷在我们身上:我们向一个
记不起第一个问题的代理,问了一个追问。
补救方法:把上下文交给代理
有两种做法。
做法一:自己带着上下文
在这个层次,“记忆”只是你一路传递的文字。你可以把两个问题合并成一个任务:
perform_task("When did Mark launch Muse, and is it available in Hong Kong yet?")
或者把第一个答案喂回第二个任务:
answer1 = perform_task("When did Mark launch Muse")
perform_task(f"Context: {answer1} Is it available in Hong Kong yet?")
第二种写法就是聊天机器人运行的雏形:它们好像记得整段对话,其实只是应用程序 每收到一条消息,都悄悄地把整段历史重新发送出去。
做法二:给代理记忆
手动传递文字,应付两个问题还可以,但应付不了一场真实对话。正确的补救方法是让 代理拥有自己的记忆,这样每次调用都能看到之前发生过什么。这就是这个系列下一篇 AI 笔记的主题。
在自己的电脑上运行
下载演示程序
(Folder-AI-ReAct05.zip)。zip 内有三个文件:
ReAct05.py(完整脚本)、pyproject.toml 和
README.md。
- 在 Visual Studio Code 打开这个文件夹。
-
在文件夹内创建一个名为
.env的文件,写上两行:
密钥:DeepSeek 控制台和 Tavily (两者都有免费的起始额度)。DEEPSEEK_API_KEY=your-deepseek-key TAVILY_API_KEY=your-tavily-key - 在终端运行:
然后试试上面两种补救方法,比较任务 2 的回答有何不同。uv sync uv run ReAct05.py
为什么这个实验值得关注
- 遗忘是默认状态。调用模型的函数,在两次调用之间什么都不记得。 如果你的代理需要记忆,就要自己建立 —— 以文字向前传递的方式。
- 追问是一场记忆测试。“它”、“那一个”、“第二个选择”这类字眼, 只有在上下文与问题同行时才安全。
- 宁可说“我不知道”,也不要凭空编造。面对一个不可能完成的任务, 代理承认自己不知道,而不是自信地编出一个错误答案。当我们要求 AI 做更多事情时, 这种行为值得保护。
延伸阅读
- ReAct: Synergizing Reasoning and Acting in Language Models —— 就是为这个系列所建立的模式命名的论文。
- Tavily 文档 —— 搜索选项、免费额度与价格。
- DeepSeek API 文档 —— 模型、密钥与价格。