English 繁體中文 简体中文

AI 代理如何思考、行動與觀察(ReAct,版本 1)?

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

向語言模型詢問今天的氣溫,它只能靠猜 — 它的知識在訓練時就終止了。 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))

每一部分的作用

在自己的電腦上執行

下載示範程式 (Folder-AI-ReAct01.zip)。zip 內有三個檔案: ReAct01.py(上面的程式)、pyproject.toml (套件清單)和 README.md。

  1. 在 Visual Studio Code 開啟這個資料夾。
  2. 在資料夾內建立一個名為 .env 的檔案,寫入一行:
    DEEPSEEK_API_KEY=your-key-here
    到 DeepSeek 主控台取得金鑰;新帳戶附有試用額度。
  3. 在終端機執行:
    uv sync
    uv run ReAct01.py
    uv 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.

軌跡裡有兩點值得注意。第一,模型說得很明白: 「我的知識不是即時的」 — 只給了任務,它已經知道自己無法憑記憶 回答。第二,它的計劃(「查一個可信的天氣來源」)正是工具接下來所做的事。 迴圈把模型自己的承認,變成一個真實的答案。

為甚麼這個模式重要

延伸閱讀