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 — 你會看到兩個答案都 已儲存,並附有日期。

為甚麼這個實驗值得留意

延伸閱讀