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 文档 — 天气调用可以返回的每一个字段。