English 繁體中文 简体中文

AI 代理如何處理追問(ReAct,版本 5,無記憶)?

林邦源博士 · AI 筆記 · 2026 年 11 月 9 日 · 約 3 分鐘閱讀

版本 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?")

檔案頂部的 import、兩個 API 客戶端、ask() 和 search_tavily() 都與 版本 3相同,所以這裡 省略。

程式碼中唯一要留意的地方

看 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。

  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 ReAct05.py
    然後試試上面兩種補救方法,比較任務 2 的回答有何不同。

為甚麼這個實驗值得留意

延伸閱讀