AI 代理如何思考、行動與觀察(ReAct,版本 1)?
向語言模型詢問今天的氣溫,它只能靠猜 — 它的知識在訓練時就終止了。 ReAct(Reasoning and Acting 的簡稱)正是解決這個問題 的模式。代理按三個步驟的迴圈工作:先在文字中思考任務,再以 指名要呼叫的工具來行動,然後觀察真實世界的 結果,最後才給出答案。本篇建立最小的 ReAct 代理:一個任務、一個工具、 三個印出的步驟,模型採用 DeepSeek。
這個想法的來源
這個模式來自 2022 年的一篇研究論文,作者是 Google Brain 和普林斯頓大學的 研究人員: ReAct: Synergizing Reasoning and Acting in Language Models。用平白的話說,論文的重點是這樣: 在 ReAct 之前,語言模型只能推理(把問題在文字中想一遍)或 行動(在世界上做事),但不能同時做到兩者。作者讓模型輪流做這兩件事 — 先寫下思考,再採取行動,然後讀取結果再想一次。思考讓行動保持在正軌, 行動帶回真實的事實,模型於是就不再憑空編造。
程式碼
這是 ReAct01.py 目前的內容:
# Step 1: THINK -> ask the model to reason step by step (reasoning trace)
# Step 2: ACT -> append that trace to the prompt and ask "What action should be taken?"
# Step 3: OBSERVE-> run the action (a real tool), feed the result back, get the final answer
import os
import requests
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")
def ask(prompt):
"""Send one prompt to the model and return its text reply."""
response = client.chat.completions.create(
model="deepseek-flash",
messages=[{"role": "user", "content": prompt}],
)
return response.choices[0].message.content
# The only tool (action) our agent can use
def get_hk_temperature():
"""Return the current temperature in Hong Kong from open-meteo.com."""
params = {"latitude": 22.32, "longitude": 114.17,
"current": "temperature_2m", "timezone": "auto"}
data = requests.get("https://api.open-meteo.com/v1/forecast",
params=params, timeout=10).json()
return f"{data['current']['temperature_2m']}°C"
task = "What is the temperature in Hong Kong today?"
# ---- Step 1: THINK (Reasoning) ----
prompt = f"""Task: {task}
Think step-by-step about how to solve this task. Do not answer yet."""
thought = ask(prompt)
print("=== Step 1: Thought (reasoning trace) ===")
print(thought)
# ---- Step 2: ACT — append the reasoning trace to the prompt, then ask for an action ----
prompt = prompt + f"""
Thought: {thought}
You have ONE tool: get_hk_temperature. What action should be taken based on that? Reply with ONLY: get_hk_temperature or none"""
action = ask(prompt).strip()
print("=== Step 2: Action chosen by the model ===")
print(action)
# ---- Step 3: OBSERVE — our Python code (not the model) runs the tool ----
if "get_hk_temperature" in action:
observation = get_hk_temperature()
else:
observation = "No action taken."
print("=== Step 3: Observation from the real world ===")
print(observation)
# ---- Final answer: the model reasons again, now grounded in the observation ----
prompt = prompt + f"""
Action: {action}
Observation: {observation}
Now give the final answer to the task in one sentence."""
print("=== Final Answer ===")
print(ask(prompt))
每一部分的作用
-
DeepSeek 客戶端。
openai套件也可以連接 DeepSeek,因為 DeepSeek 採用相同的介面。金鑰來自.env檔案, 由load_dotenv()載入,所以機密永遠不會出現在程式碼裡。 -
ask()。一個輔助函數送出一個提示詞,回傳一個 字串。這個程式裡與模型的每次對話都經過它。 -
唯一的工具。
get_hk_temperature()向 Open-Meteo 查詢香港座標的當前氣溫,並以簡短字串回傳,例如26.8°C。 毋須金鑰。 - 第 1 步 — 思考。提示詞包含任務和一句指示: 逐步思考,暫時不要回答。回覆是一段推理軌跡 — 模型寫下來的思考過程。
-
第 2 步 — 行動。推理軌跡會附加到提示詞,並告訴模型
它只有一個工具,回覆時只可寫工具名稱或
none。模型只 選擇行動;它不會執行行動。 -
第 3 步 — 觀察。Python — 而不是模型 —
檢查所選的行動並執行工具。結果例如
26.8°C,就是觀察。 - 最終答案。提示詞現在包含任務、推理軌跡、行動和觀察。模型 寫出一句建基於真實數字的句子,而不是猜測。
在自己的電腦上執行
下載示範程式
(Folder-AI-ReAct01.zip)。zip 內有三個檔案:
ReAct01.py(上面的程式)、pyproject.toml
(套件清單)和 README.md。
- 在 Visual Studio Code 開啟這個資料夾。
-
在資料夾內建立一個名為
.env的檔案,寫入一行:
到 DeepSeek 主控台取得金鑰;新帳戶附有試用額度。DEEPSEEK_API_KEY=your-key-here - 在終端機執行:
uv sync uv run ReAct01.pyuv sync只需第一次執行;它會讀取pyproject.toml,把openai、requests和python-dotenv安裝到專案內。
你應該會看到四段依次印出:推理軌跡、所選的行動
(get_hk_temperature)、觀察到的氣溫,以及使用真實數字寫成的
最終單句答案。以下是一次真實執行:
=== Step 1: Thought (reasoning trace) ===
Let’s break this down step-by-step:
1. **Identify the goal** – The user wants the current temperature in Hong Kong today.
2. **Determine location specifics** – Hong Kong is a major city; its weather can vary slightly by district but generally a single official temperature reading is used for “Hong Kong” in weather reports.
3. **Check date/time awareness** – “Today” means the current date. My knowledge isn’t real-time, so I can’t know the live temperature without up-to-date data.
4. **Possible sources** – Could use:
- Real-time weather websites (e.g., Hong Kong Observatory).
- Weather apps or APIs.
- Search engine results for “Hong Kong temperature”.
5. **Consider limitations** – Without live access or browsing ability, I can’t retrieve the exact current temperature.
6. **Formulate approach for answer** – If I had browsing or API tools, I’d check the Hong Kong Observatory or a trusted weather source right now and report the temperature in °C (and possibly °F).
7. **Alternate if no access** – I’d explain I can’t provide real-time data and suggest how the user can check (e.g., HKO website, weather apps).
This reasoning sets up how to get the answer, but the actual temperature value would need current data.
=== Step 2: Action chosen by the model ===
get_hk_temperature
=== Step 3: Observation from the real world ===
27.1°C
=== Final Answer ===
The temperature in Hong Kong today is 27.1°C.
軌跡裡有兩點值得注意。第一,模型說得很明白: 「我的知識不是即時的」 — 只給了任務,它已經知道自己無法憑記憶 回答。第二,它的計劃(「查一個可信的天氣來源」)正是工具接下來所做的事。 迴圈把模型自己的承認,變成一個真實的答案。
為甚麼這個模式重要
- 模型決定,程式執行。模型從不接觸互聯網;實際執行甚麼, 仍由你的 Python 掌控。這正是這個模式可以安全擴展的原因。
- 每一步都看得見。推理軌跡、所選的行動和觀察都會印出, 所以當代理出錯時,你可以看到它在哪裡出錯 — 是思考錯了、 選擇錯了,還是工具出了問題。
- 更多工具,同一個迴圈。要給代理第二種能力(時間、搜尋、 檔案),只需加入函數,並在第 2 步的提示詞中提及它。三步的節奏不會改變。
延伸閱讀
- ReAct: Synergizing Reasoning and Acting in Language Models — 為這個模式命名的論文。
- DeepSeek API 文件 — 模型、金鑰與價格。
- Open-Meteo API 文件 — 天氣呼叫可以回傳的每一個欄位。