English 繁體中文 简体中文

如何让 AI 代理拥有记忆(ReAct,版本 6,memory.json)?

林邦源博士 · AI 笔记 · 2026 年 11 月 9 日 · 约 4 分钟阅读

版本 5留下一个承诺。 追问“香港现在能用了吗?”失败了,因为代理对第一个任务毫无记忆,而正确 的补救方法是给它自己的记忆。版本 6 就做到了这一点,只靠一个小文件: memory.json。(JSON 是纯文本,把数据存成有标签的值,例如 {"question": "...", "answer": "..."},所以程序可以逐个字段读取。)

脚本

这是 ReAct06.py。 版本 4的 ReAct 循环 没有改动,所有新增的东西都关于记忆。三个小函数负责读写一个 JSON 文件:

MEMORY_FILE = "memory.json"    # long-term memory lives in this file

def load_memory():
    """Return the list of saved facts (empty if there is no file yet)."""
    if not os.path.exists(MEMORY_FILE):
        return []
    with open(MEMORY_FILE, encoding="utf-8") as f:
        return json.load(f)

def save_memory(question, answer):
    """Add one question + answer (with today's date) to memory.json."""
    memory = load_memory()
    memory.append({"date": today, "question": question, "answer": answer})
    with open(MEMORY_FILE, "w", encoding="utf-8") as f:
        json.dump(memory, f, indent=2, ensure_ascii=False)

def memory_text():
    """Turn the saved facts into text we can put in the prompt."""
    memory = load_memory()
    if not memory:
        return "(empty)"
    return "\n".join(f"- [{m['date']}] Q: {m['question']} A: {m['answer']}"
                     for m in memory)

perform_task 内的提示词多了一个新段落:

prompt = f"""Task: {task}
Today is {today}.
Memory (what you learned before, with the date you learned it):
{memory_text()}

You can use ONE tool: search[query] searches the web (Tavily) and returns the top results.
If your memory already answers the task, you may finish without searching.
Work in steps. Each step has a Thought, an Action, and an Observation."""

而当代理完成一个任务,答案会在函数返回之前先保存起来。脚本也会在每次运行开始时 清空 memory.json,所以每次运行都从一张白纸开始:

        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)
            save_memory(task, answer)   # long-term memory: keep it for next time
            return answer
# Start each run with an EMPTY long-term memory (overwrites any old memory.json)
with open(MEMORY_FILE, "w", encoding="utf-8") as f:
    json.dump([], f)

perform_task("When did Mark launch Muse")
perform_task("Is it available in Hong Kong yet?")

import、两个 API 客户端、ask() 和 search_tavily() 都与 版本 3相同,所以这里 省略。

代码中唯一要看的地方

这个脚本有两种记忆,值得分辨清楚:

这里没有魔法。“记忆”仍然只是文字:答案被附加到一个文件,那个文件再被贴进下一个 提示词。模型本身在两次调用之间,依然什么都不记得。

一次真实运行

--- Task 1: "When did Mark launch Muse" ---
=== Memory loaded into the prompt ===
(empty)
...three rounds of searching...
=== Final Answer ===
Muse (Meta's personal AI agent) launched in early September 2026; Mark Zuckerberg's Sept 20, 2026 post said it had "been out for a little over a week," pointing to a launch around early September 2026.

--- Task 2: "Is it available in Hong Kong yet?" ---
=== Memory loaded into the prompt ===
- [2026-10-09] Q: When did Mark launch Muse A: Muse (Meta's personal AI agent) launched in early September 2026; Mark Zuckerberg's Sept 20, 2026 post said it had "been out for a little over a week," pointing to a launch around early September 2026.
=== Round 1 - Thought ===
Thought 1: The task asks whether something is available in Hong Kong yet, but the memory only tells me about Muse's launch timing... I need to search for current information about Muse availability in Hong Kong.
=== Round 1 - Action chosen by the model ===
search[Muse Meta personal AI agent available in Hong Kong]
...launched September 8; 2.5 million downloads in two weeks...
=== Round 2 - Action chosen by the model ===
search[Muse Meta AI agent Hong Kong availability rollout regions]
...available in the United States and Canada only; no launch announced for Hong Kong, Taiwan, Singapore or any Asia-Pacific market...
=== Final Answer ===
No, Muse is not available in Hong Kong yet. As of October 2026, Meta Muse is only available in the United States (and possibly Canada), and no launch has been announced for Hong Kong or any other Asia-Pacific market.

节选已缩短(…);完整运行会打印出两个任务的全部内容。

把这次与版本 5 比较:同样两次调用、同一个循环、同一个模型 —— 但这次任务 2 一开口就读到任务 1 的记忆。“它”不再是谜:提示词的第一行清楚写出之前问过什么、 答过什么。代理免费解决了这个指代,然后把两次搜索用在真正的问题上,并正确回答: 还没有,也没有公布日期。

这是真实运行后的 memory.json —— 代理全部的长期记忆,一眼看完:

[
  {
    "date": "2026-11-09",
    "question": "When did Mark launch Muse",
    "answer": "September 8, 2026"
  },
  {
    "date": "2026-11-09",
    "question": "Is it available in Hong Kong yet?",
    "answer": "No — as of 2026-11-09, Muse does not appear to be available in Hong Kong yet. It launched on September 8, 2026 and was reported as US-only; Meta AI becoming available in Hong Kong on October 29, 2026 is separate from Muse."
  }
]

两条记录,各自标上学到的日期。留意第二个答案:代理甚至把两件关于香港的事分开 —— Meta AI(聊天机器人)进入香港,与 Muse(代理)在香港可用,并不是同一件事。

在自己的电脑上运行

下载演示程序 (Folder-AI-ReAct06.zip)。zip 内有三个文件: ReAct06.py(完整脚本)、pyproject.toml 和 README.md。

  1. 在 Visual Studio Code 打开这个文件夹。
  2. 在文件夹内创建一个名为 .env 的文件,写上两行:
    DEEPSEEK_API_KEY=your-deepseek-key
    TAVILY_API_KEY=your-tavily-key
    密钥:DeepSeek 控制台和 Tavily (两者都有免费的起始额度)。
  3. 在终端运行:
    uv sync
    uv run ReAct06.py
    运行之后,在文件夹内打开 memory.json —— 你会看到两个答案都已 保存,并附有日期。

为什么这个实验值得关注

延伸阅读