如何讓 AI 代理可以重用(ReAct,版本 4,一個函數,任何任務)?
上一篇筆記
建立了一個會用網上搜尋研究問題的代理 — 但問題是寫在腳本裡的,答案也只會
出現在畫面上。這篇筆記只做兩項結構上的改動,其他一概不變:迴圈搬進一個
函數,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")
與上一個腳本相比有甚麼改變
逐行來看,這是同一個代理。差別在於包裝方式:
-
迴圈現在住在
perform_task(task)裡面。 任務是一個參數,所以同一份程式碼可以研究任何問題,不必修改腳本中段。 問題搬到最後一行,那才是它該在的地方:perform_task("When did Mark launch Muse")。 -
函數會回傳答案。以往答案只會被印出來。現在
return answer把答案以文字形式交回,所以呼叫它的程式 可以儲存、電郵、顯示在網頁上,或把它交給更大程式的下一步使用。 -
其他一切都不變 — 同樣兩把金鑰、同樣一個工具、
同樣五輪的預算、同樣的
stop=["Action"]防護欄。如果你對 其中任何一項感到陌生, 上一篇筆記 有解釋。
一次真實執行
=== 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。
- 在 Visual Studio Code 開啟這個資料夾。
-
在資料夾內建立一個名為
.env的檔案,內容有兩行:
第一個金鑰從 DeepSeek 控制台取得,第二個從 Tavily取得; 兩者都有免費的起始額度。DEEPSEEK_API_KEY=your-deepseek-key TAVILY_API_KEY=your-tavily-key - 在終端機執行:
uv sync uv run ReAct04.pyuv sync只需要第一次執行;它會讀取pyproject.toml,並把openai、tavily-python和python-dotenv裝進這個專案。
現在實驗就在最後一行。把它改成
perform_task("What were the three biggest news stories in my city this week?")
— 或者任何其他問題 — 再執行一次。改一行,就是另一個研究項目。
為甚麼這個小改動重要
- 不必修改就能重用。代理的邏輯已經定下來;問題是資料。 把兩者分開,你就能用十行研究十個問題,而不是寫十個腳本。
- 答案可以去別的地方。回傳的值可以被儲存、送出或顯示在 任何地方。印出來的值,到螢幕就結束了。
- 這就是真實系統的形狀。一個每天早上檢查新聞的排程工作, 或一個回答訪客問題的網頁,兩者都是這個樣子:一個函數,用一個任務去呼叫, 回傳一個答案。這個系列正朝著這個方向走。
延伸閱讀
- ReAct: Synergizing Reasoning and Acting in Language Models — 為這個模式命名的論文,也是本系列所建立的基礎。
- Tavily 文件 — 搜尋選項、免費方案與定價。
- DeepSeek API 文件 — 模型、金鑰與定價。