English 繁體中文 简体中文

如何讓 AI 代理可以重用(ReAct,版本 4,一個函數,任何任務)?

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

上一篇筆記 建立了一個會用網上搜尋研究問題的代理 — 但問題是寫在腳本裡的,答案也只會 出現在畫面上。這篇筆記只做兩項結構上的改動,其他一概不變:迴圈搬進一個 函數,perform_task(task),它接受任何問題;而函數會把 答案以文字形式回傳。代理於是變成你的程式可以呼叫的東西, 而不是你只能讀一次的東西。

腳本

這是 ReAct04.py 目前的內容:

# Same ReAct idea as react01.py, but this task needs MORE THAN ONE action,
# so we repeat Think -> Act -> Observe in a loop until the model says "finish".
# Step 1: THINK  -> ask the model to reason about what to do next
# Step 2: ACT    -> ask for ONE action: search[...] or finish[...]
# Step 3: OBSERVE-> run the Tavily web search (a real tool), add the result to the prompt, loop again
import os
import re
from datetime import datetime
from tavily import TavilyClient
from openai import OpenAI
from dotenv import load_dotenv
load_dotenv()

client = OpenAI(
    api_key=os.environ.get('DEEPSEEK_API_KEY'),
    base_url="https://api.deepseek.com")
tavily = TavilyClient(api_key=os.environ.get('TAVILY_API_KEY'))

def ask(prompt, stop=None):
    """Send one prompt to the model and return its text reply."""
    response = client.chat.completions.create(
        model="deepseek-flash",
        messages=[{"role": "user", "content": prompt}],
        stop=stop,   # stop writing when this text appears
    )
    return response.choices[0].message.content

# The only tool (action) our agent can use
def search_tavily(query):
    """Return the top web results from Tavily (title, url, short content)."""
    results = tavily.search(query=query, max_results=3)["results"]
    if not results:
        return f"No web results found for '{query}'."
    return "\n".join(f"[{r['title']}] ({r['url']}) {r['content'][:400]}"
                     for r in results)

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
        # ---- Step 1: THINK (Reasoning) ----
        thought = ask(prompt + f"\n\nThought {step}: (reason briefly about what to do next; do not act yet)",
                      stop=["Action"])   # stop the model inventing its own Action/Observation
        print(f"=== Round {step} - Thought ===")
        print(thought)

        # ---- Step 2: ACT — append the reasoning trace, then ask for an action ----
        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

        # ---- Step 3: OBSERVE — our Python code (not the model) runs the tool ----
        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")

與上一個腳本相比有甚麼改變

逐行來看,這是同一個代理。差別在於包裝方式:

一次真實執行

=== Round 1 - Thought ===
Thought 1: I need to find out when Mark (likely Mark Zuckerberg) launched Muse. I should search the web for this information, but I need to be careful because "Muse" could refer to different things...
=== Round 1 - Action chosen by the model ===
search[Mark launch Muse date]
=== Round 1 - Observation from Tavily web search ===
[Mark Zuckerberg announces Muse Spark, a new Meta AI model ... | Mashable] ...after Meta launched Muse, an autonomous personal artificial intelligence agent.
[Muse Spark - Wikipedia] ...Muse Spark ... introduced in April 2026 and launched as Muse Spark 1.1 on July 9, 2026...
[Everything new coming to Meta's AI agent Muse | TechCrunch] Muse, which launched in early September...
=== Round 2 - Thought ===
Thought 2: The search results give conflicting dates depending on what "Muse" refers to. I need to distinguish between the Muse AI agent and the underlying Muse Spark model...
=== Round 2 - Action chosen by the model ===
search[Mark Zuckerberg Meta launched Muse AI agent exact date September 2026]
...two more rounds of searching...
=== Round 4 - Action chosen by the model ===
finish[Mark Zuckerberg/Meta launched **Muse**, the personal AI agent, on **September 8, 2026**. If the question refers to **Muse Spark**, that model was introduced in **April 2026** and launched as **Muse Spark 1.1 on July 9, 2026**.]
=== Final Answer ===
Mark Zuckerberg/Meta launched **Muse**, the personal AI agent, on **September 8, 2026**. If the question refers to **Muse Spark**, that model was introduced in **April 2026** and launched as **Muse Spark 1.1 on July 9, 2026**.

摘錄為求易讀而經過縮短(…);完整執行會把每一輪完整印出。

有兩點值得注意。第一,第 2 輪做了一件之前那次執行沒有做的事:它把代理 Muse 與背後的模型 Muse Spark 分開,因為搜尋結果把兩者混在 一起。最後的答案同時報告兩個日期,並說明哪個是哪個 — 問題中的含糊之處 是公開解決的,而不是靜靜帶過。第二,答案文字裡有 ** 符號: 模型寫的是 markdown 粗體。你把它印出來時,看到的是符號;當另一個程式以 markdown 顯示它時,它們就會變成真正的粗體文字。這是回傳答案為何重要的一個 小預覽 — 同一段文字現在有兩種可能的生命。

在自己的電腦上執行

下載示範程式 (Folder-AI-ReAct04.zip)。zip 內有三個檔案: ReAct04.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 ReAct04.py
    uv sync 只需要第一次執行;它會讀取 pyproject.toml,並把 openai、 tavily-python 和 python-dotenv 裝進這個專案。

現在實驗就在最後一行。把它改成 perform_task("What were the three biggest news stories in my city this week?") — 或者任何其他問題 — 再執行一次。改一行,就是另一個研究項目。

為甚麼這個小改動重要

延伸閱讀