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.

轨迹里有两点值得注意。第一,模型说得很明白: “我的知识不是实时的” — 只给了任务,它就已经知道自己无法凭记忆 回答。第二,它的计划(“查一个可信的天气来源”)正是工具接下来所做的事。 循环把模型自己的承认,变成一个真实的答案。

为什么这个模式重要

延伸阅读