Chapter 32
4. 协同推理和行动 ReAct
第四章 协同推理和行动 ReAct
一、引言
大语言模型(Large Language Models, LLMs),如 GPT-3.5 Turbo/GPT-4,已在语言理解和交互式决策任务上表现出强大的能力。然而,在 ReAct 出现之前,LLMs 在推理(如思维链提示)和行动(如行动计划生成)方面的能力是被孤立地研究和应用的。(但现在,LLMs 和基于 LLM 的 Agent 的研究正在迅速发展。)
ReAct 当时首次对这个问题给出了答案:当这两种基本能力结合在一起时,会产生什么效果?
上面的示意图的来源:https://react-lm.github.io/
本章将详细介绍 ReAct 框架,ReAct 是由 Reason(推理)和 Action(行动)组成的缩写,ReAct = Reason + Action = 推理 + 行动。我们通过深入阐述关键原理和提供实际代码示例,旨在帮助读者全面掌握 ReAct 的关键原理和实际应用。阅读本章后,读者将能够更专业、准确地理解并应用 ReAct 框架。
二、ReAct 框架的核心要点
2.1 ReAct 的关键原理
你知道我们人类在做事情的时候,会先想一想(推理),然后再去做(行动),对吧?比如说,你想要搭积木,你可能会先想一想,我要搭一个什么样的积木,需要什么颜色的积木块,然后你才会去找这些积木块,开始搭建。这就是我们人类的智能,我们可以把想和做紧密地结合在一起。
现在,有一种叫做 ReAct 的方法,它就是想在计算机里模拟我们人类这种把想和做结合在一起的智能。它会让计算机先想一想(生成推理文本),然后再去做(检索信息或者调用工具)。这样,计算机就可以更好地回答问题,也可以更好地适应复杂的环境。
就像你在玩一个新的游戏,你可能会先想一想规则,然后再去玩。如果游戏中出现了一些新的情况,你也可以根据你之前的想法,来调整你的行动。这就是 ReAct 方法的核心思想,它让计算机也能像我们人类一样,先想后做,从而更好地完成任务。
2.2 ReAct 的提示设计
ReAct 提示设计的一个关键点是:few-shot task-solving 轨迹,其本质在于充分利用上下文学习和提供好的演示(Demonstrations)。这些轨迹由人工编写的文本推理和操作序列以及相应操作环境的观察结果构成。下面是一个 ReAct 提示的示例(摘自论文):
问题 科罗拉多造山带东部区域延伸到的区域的海拔范围是多少?
思考 1 我需要搜索科罗拉多造山带,找到科罗拉多造山带东段延伸的区域,然后找到该区域的海拔范围。
操作 1 搜索 [科罗拉多造山带]
观察 1 科罗拉多造山带是科罗拉多及其周边地区造山运动的一段。
思考 2 它没有提到东部地区。所以我需要查一下东部地区。
操作 2 查找 [东部地区]
观察 2 (结果 1 / 1) 东部区域延伸至高平原,称为中原造山带。
思考 3 科罗拉多造山运动的东部区域延伸到高平原。所以我需要搜索高平原,找到它的海拔范围。
操作 3 搜索 [高平原]
观察 3 高平原指的是两个截然不同的陆地区域之一。
思考 4 我需要搜索高平原(美国)
操作 4 搜索 [高平原(美国)]
观察 4 高平原是大平原的一个分区。从东到西,高平原的海拔从 1800 到 7000 英尺 (550 到 2130 米) 不等。[3]
思考 5 高平原海拔高度从 1800 到 7000 英尺,所以答案是 1800 到 7000 英尺。
操作 5 结束 [1800 到 7000 英尺]
...在 LangChain 中,您可以找到封装好的 ReAct 模块的源码,其中包含更详细的 Prompt 模板和 Demonstrations:https://github.com/langchain-ai/langchain/tree/c4e9c9ca2959e2cf756fc499b7c6f35d8786e143/libs/langchain/langchain/agents/react
ReAct 的提示设计直观、灵活,并在各种任务中实现了最先进的少样本性能。研究论文表明,ReAct 的有效性在四个基准测试中进行了评估,包括问题解答和事实验证任务(如 HotpotQA 和 Fever),以及交互式决策任务(如 ALFWorld 和 WebShop)。在这些不同的领域中,ReAct 在多个方面都优于纯推理和纯行为基线方法,显示了集成推理-行动系统的潜力。
三、ReAct 应用示例
注意:我使用的测试环境是 UV + Python3.12+。Python 的版本要求 Python3.12+。
开始实验之前,我们需要安装好本次实验所需的第三方依赖库:
-
openai:OpenAI Python 库提供了一个便捷的途径,让任何 Python 3.12+ 应用程序可以访问 OpenAI REST API。 -
langchain:LangChain 是一个基于语言模型开发应用程序的框架。 -
numexpr:NumExpr 是一个高效的数值表达式计算器,用于在利用 LLM 进行数学计算时提高性能。
此外,我们还需要获取一个名为 SERPAPI_API_KEY 的 API 密钥。您可以在官方网站上获得密钥和更多信息:https://serpapi.com/dashboard
SerpApi 是一个强大且可靠的工具,用于获取搜索引擎结果。SerpApi API 可用于访问 Google 搜索结果,为开发者处理代理、解决验证码,并解析所有丰富的结构化数据。功能:快速、简单、完整的 API,可从 Google 和其他搜索引擎中获取数据;支持的搜索引擎包括 Google、Bing、Yandex 等。可以集成到主流编程语言(如 Python、Java、Go、Rust、Node.js 等)或直接在 Google Sheets 中使用。
SerpApi 特点:
(1)实时和真实的结果:每个 API 请求立即运行,无需等待结果。此外,每个 API 请求在完整的浏览器中运行,我们甚至会解决所有验证码,完全模仿人类的操作,确保您获得用户真正看到的内容。
(2)丰富的结构化数据:提供常规的有机搜索结果,以及地图、本地信息、故事、购物、直接答案和知识图谱。每个结果都有许多结构化数据,包括链接、地址、推文、价格、缩略图、评级、评论、丰富片段等。
导入此次实验所需的依赖库
import os
import warnings
from dotenv import load_dotenv, find_dotenv
from openai import OpenAI
from langchain.agents import AgentType
from langchain.agents import initialize_agent
from langchain_community.agent_toolkits.load_tools import load_tools
from langchain_community.chat_models import ChatOpenAI
warnings.filterwarnings("ignore")
loaded = load_dotenv(find_dotenv(), override=True)
# 从环境变量中获取 OpenAI API Key 或者直接赋值
API_KEY = os.getenv("API_KEY")
# 如果您使用的是官方 API,就直接用 https://api.siliconflow.cn/v1 就行。
BASE_URL = "https://api.siliconflow.cn/v1"
# 如果您使用的不是官方 API,而是通过代理进行请求,请设置您的代理 URL。
# BASE_URL = "https://api.xxx.../v1"实验 1:连接搜索引擎,对比使用和不用 ReAct 的生成结果
给定任务 1:"你的任务是列出 Datawhale 的开源项目南瓜书的核心作者的姓名。"
1. 实例化一个 LLM 对象以及设置其关键参数
-
temperature:采样温度在 0 到 2 之间,更高的值如 0.8 会使输出更随机,而更低的值如 0.2 会使其更加集中和确定性。
-
model_name:使用的模型标识,此次实验演示用的是
gpt-3.5-turbo-0125。 -
max_tokens:聊天完成时可以生成的最大 tokens 数。注意:输入 tokens 和生成 tokens 的总长度受模型上下文长度的限制。
-
openai_api_key:必需的 OpenAI API Key。登录 https://platform.openai.com/ 获取。
-
openai_api_base:非必需,如果您使用的不是官方 API,而是通过代理进行请求,请提供您的代理 URL。
-
max_retries:最大重试次数。
-
"seed=42, presence_penalty=0, frequency_penalty=0,": 这是为了促进确定性地输出。 这几个参数的含义具体可以参考:https://platform.openai.com/docs/api-reference/chat/create
2. 使用 load_tools 方法加载工具 "serpapi"
3. 传入工具和 LLM 对象,以及实例化一个基于 ReAct 的 Agent
-
verbose 参数为 True 则会打印全部的执行详情。
-
agent 参数设置为 AgentType.ZERO_SHOT_REACT_DESCRIPTION。
llm = ChatOpenAI(temperature=0.3, model_name="Qwen/Qwen3-8B", max_tokens=1024,
openai_api_key=API_KEY,
openai_api_base=BASE_URL,
max_retries=3,
model_kwargs={
"seed": 42,
"presence_penalty": 0,
"frequency_penalty": 0}
)
tools = load_tools(["serpapi"])
agent_ReAct = initialize_agent(tools, llm, verbose=True,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
handle_parsing_errors=True
)# 查看所用到的提示模板
print(agent_ReAct.agent.llm_chain.prompt.template)Output
Answer the following questions as best you can. You have access to the following tools:
Search(query: str, **kwargs: Any) -> str - A search engine. Useful for when you need to answer questions about current events. Input should be a search query.
Use the following format:
Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [Search]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question
Begin!
Question: {input}
Thought:{agent_scratchpad}
# 实例化 OpenAI 对象
# 传入参数:OpenAI API Key(必需)、Base URL 和最大重试次数
client = OpenAI(api_key=API_KEY, base_url=BASE_URL, max_retries=3)def get_completions(llm_prompt, model_endpoint):
extra_body = {}
if "Qwen3" in model_endpoint:
extra_body={
"enable_thinking": False
}
response = client.chat.completions.create(model=model_endpoint,
messages=[
{"role": "user", "content": llm_prompt}
],
n=1, temperature=0.20, seed=42,
presence_penalty=0, frequency_penalty=0,
max_tokens=1024, extra_body = extra_body
)
return response.choices[0].message.content.strip()没有使用 ReAct,直接 Prompting
prompt = "你的任务是列出 Datawhale 的开源项目南瓜书的核心作者的姓名。"
result_no_ReAct = get_completions(prompt, "Qwen/Qwen3-8B")
print(f"\n生成结果-中文:\n{result_no_ReAct}")Output
生成结果-中文: Datawhale 的开源项目 **《南瓜书》**(Pumpkin Book)是一本面向初学者的 Python 编程入门书籍,由 Datawhale 社区的成员共同编写和维护。该书以轻松幽默的方式讲解 Python 基础知识,非常适合编程新手学习。 目前,《南瓜书》的核心作者包括: 1. **李金良**(作者) 2. **王宇**(作者) 3. **张伟**(作者) 4. **李明**(作者) 5. **陈强**(作者) 6. **周杰**(作者) 7. **吴昊**(作者) 8. **赵磊**(作者) 9. **孙婷**(作者) 10. **徐浩**(作者) 这些作者是 Datawhale 社区中活跃的成员,他们共同推动了《南瓜书》的编写、更新和开源。如果你对《南瓜书》感兴趣,可以访问其 GitHub 仓库或 Datawhale 官网获取更多信息。
prompt = "Your task is to list the names of the core authors of Datawhale's open source project Pumpkin Book."
result_no_ReAct = get_completions(prompt, "Qwen/Qwen3-8B")
print(f"\n生成结果-英文:\n{result_no_ReAct}")Output
生成结果-英文: The **Pumpkin Book** is an open-source educational project by **Datawhale**, aimed at teaching machine learning and data science through a series of practical, hands-on exercises. It is part of Datawhale's mission to make machine learning more accessible and to provide learning resources for beginners and intermediate learners. The **core authors** of the Pumpkin Book are typically a group of contributors from the Datawhale community. While the exact list of core authors may vary over time, as of the latest known information, the main contributors and maintainers include: 1. **Yan Pan** (Pan Yan) – One of the primary authors and maintainers of the Pumpkin Book. 2. **Zhiyuan Liu** (Liu Zhiyuan) – A key contributor to the project. 3. **Yi Zhang** (Zhang Yi) – Another core author involved in the development of the Pumpkin Book. 4. **Jiawei Zhang** (Zhang Jiawei) – Also a core contributor to the project. 5. **Ying Zhang** (Zhang Ying) – Participates in the development and maintenance of the Pumpkin Book. 6. **Yan Li** (Li Yan) – A contributor to the project. 7. **Xiaoyu Wang** (Wang Xiaoyu) – Involved in the development of the Pumpkin Book. 8. **Yan Wang** (Wang Yan) – Another core author. 9. **Yi Liu** (Liu Yi) – A contributor to the project. 10. **Ying Liu** (Liu Ying) – Also part of the core team. These individuals are part of the **Datawhale** team and have been actively involved in creating and maintaining the Pumpkin Book. The project is collaborative, and many contributors have helped shape its content over time. If you're looking for the most up-to-date list, I recommend checking the **GitHub repository** of the Pumpkin Book directly, as the contributors section there will reflect the current team and their roles.
使用 ReAct
# 使用 ReAct 来回答 中文
question_Chinese = "你的任务是列出 Datawhale 的开源项目南瓜书的核心作者的姓名。用中文输出结果。"
result_Chinese = agent_ReAct.run(question_Chinese)
print(f"\n生成结果-中文:\n{result_Chinese}")Output
[1m> Entering new AgentExecutor chain...[0m [32;1m[1;3m Thought: 我需要先确认“南瓜书”是否为Datawhale的开源项目,并查找其核心作者的信息。由于“南瓜书”可能不是广为人知的项目,我需要通过搜索引擎获取准确信息。 Action: Search Action Input: "Datawhale 南瓜书 核心作者" [0m Observation: [36;1m[1;3m作者:Datawhale开源项目团队 作为机器学习的入门经典教材,周志华老师的《机器学习》,自2016年1月底出版以来,首印5000册一周售罄,并在8个月内重印9次。 先后登上了亚马逊,京东,当当网等的计算机类畅销书榜首,身边学习机器学习的小伙伴基本上是人手一本。[0m Thought:[32;1m[1;3m Final Answer: Datawhale的开源项目“南瓜书”的核心作者是周志华以及Datawhale开源项目团队。[0m [1m> Finished chain.[0m 生成结果-中文: Datawhale的开源项目“南瓜书”的核心作者是周志华以及Datawhale开源项目团队。
# 使用 ReAct 来回答 英文
question_English = "Your task is to list the names of the core authors of Datawhale's open source project Pumpkin Book."
result_English = agent_ReAct.run(question_English)
print(f"\n生成结果-英文:\n{result_English}")Output
[1m> Entering new AgentExecutor chain...[0m [32;1m[1;3m Thought: I now know the final answer Final Answer: The core authors of Datawhale's Pumpkin Book are Yixing Chen, Yixing Chen, and others. However, for the most accurate and up-to-date list, it's recommended to check the official Datawhale GitHub repository or their website.[0m [1m> Finished chain.[0m 生成结果-英文: The core authors of Datawhale's Pumpkin Book are Yixing Chen, Yixing Chen, and others. However, for the most accurate and up-to-date list, it's recommended to check the official Datawhale GitHub repository or their website.
分析实验结果:
-
传统的提示方法主要依靠 LLM 自身的参数化知识。然而,在上述实验中,无论是在中文还是英文输入提示的情况下,gpt-3.5-turbo-0125 都不能准确回答问题。事实上,Datawhale 开源项目《南瓜书》的核心作者是 "谢文睿",尽管 LLM 输出了内容,但存在幻觉问题。
-
相比之下,ReAct 强调了 LLM 与外部工具之间的协作(例如上述实验中使用了搜索),从而实现更精确、具有情境化的响应。当输入中文提示时,gpt-3.5-turbo-0125 给出了准确的答案:"谢文睿";然而当输入英文提示时,生成结果是:"The core authors of Datawhale's open source project Pumpkin Book are Michael and Lennon.",产生了幻觉。这可能是由于中文/英文关键词检索结果质量问题导致的,在中文场景下,《南瓜书》的信息更为丰富。
实验 2:连接搜索引擎和数学计算工具,对比使用和不用 ReAct 的生成结果。
给定任务 2:"强化学习教程(蘑菇书)现在的价格是多少?如果我在此基础上降价 15% 卖出,应该如何定价?用中文输出结果。"
# 使用 load_tools 方法加载工具 "serpapi" 和 "llm-math"
tools = load_tools(["serpapi", "llm-math"], llm=llm)
agent_ReAct = initialize_agent(tools, llm, verbose=True,
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
handle_parsing_errors=True
)# 查看所用到的提示模板
print(agent_ReAct.agent.llm_chain.prompt.template)Output
Answer the following questions as best you can. You have access to the following tools:
Search(query: str, **kwargs: Any) -> str - A search engine. Useful for when you need to answer questions about current events. Input should be a search query.
Calculator(*args: Any, callbacks: Union[list[langchain_core.callbacks.base.BaseCallbackHandler], langchain_core.callbacks.base.BaseCallbackManager, NoneType] = None, tags: Optional[list[str]] = None, metadata: Optional[dict[str, Any]] = None, **kwargs: Any) -> Any - Useful for when you need to answer questions about math.
Use the following format:
Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [Search, Calculator]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question
Begin!
Question: {input}
Thought:{agent_scratchpad}
没有使用 ReAct,直接 Prompting
prompt = "强化学习教程(蘑菇书)现在的价格是多少?如果我在此基础上降价 15% 卖出,应该如何定价?用中文输出结果。"
result_no_ReAct = get_completions(prompt, "Qwen/Qwen3-8B")
print(f"\n生成结果-中文:\n{result_no_ReAct}")Output
生成结果-中文:
目前《强化学习教程(蘑菇书)》的价格因版本、销售渠道和时间不同而有所差异。以下是大致的价格参考(以中文出版的常见版本为例):
- **原价**:通常在 **50元至100元** 之间,具体取决于出版社和版本(如第一版、第二版或电子版)。
- **折扣价**:在一些电商平台(如京东、当当、淘宝等)上,这本书有时会有折扣,价格可能在 **30元至60元** 之间。
### 如果你打算降价15%卖出,应该如何定价?
假设你以 **60元** 作为当前售价(这是一个常见的折扣价),那么降价15%后的价格为:
$$
60 \times (1 - 0.15) = 60 \times 0.85 = 51 \text{元}
$$
### 结论:
- **当前价格**:约 **60元**(仅供参考,实际以你所在平台为准)。
- **降价15%后的价格**:约 **51元**。
如果你有具体的原价或销售平台信息,我可以帮你更精确地计算。
prompt = "What is the current price of the Reinforcement Learning Tutorial (The Mushroom Book)? How should I price it if I sell it with a 15% price reduction on top of that?"
result_no_ReAct = get_completions(prompt, "Qwen/Qwen3-8B")
print(f"\n生成结果-英文:\n{result_no_ReAct}")Output
生成结果-英文: The **Reinforcement Learning Tutorial (The Mushroom Book)** is a free online resource, not a physical product or a paid book. It is created by **Alexander Rakhlin** and **Sivan Saban**, and is available on [The Mushroom Book website](https://mushroombook.com/). Since it's free, there is no "current price" in the traditional sense. However, if you are considering **selling a physical copy** of the book (if one exists) or **offering a paid version** of the tutorial (e.g., a premium version with additional content), you would need to determine the **original price** first. Once you have that, a **15% price reduction** would be calculated as follows: ### Formula: ``` Discounted Price = Original Price × (1 - 0.15) ``` ### Example: If the original price is $20: ``` Discounted Price = $20 × 0.85 = $17 ``` ### Steps to Determine Your Price: 1. **Find the original price** of the book (if it's available for purchase). 2. **Calculate the 15% discount** using the formula above. 3. **Set your price** at the discounted amount. If you're not selling a physical product but instead offering a **paid version** of the tutorial (e.g., a downloadable PDF or a course), you can set the original price based on market research, the value of the content, and your target audience. A common approach is to price it between **$10 to $30**, depending on the depth and exclusivity of the material. ### Summary: - The **Reinforcement Learning Tutorial (The Mushroom Book)** is **free**. - If you are selling a **paid version**, you can choose an original price (e.g., $20), then apply a **15% discount** to get the final price (e.g., $17). - If you're unsure about the original price, consider market trends and the perceived value of the content when setting it. Let me know if you want help determining a fair price for a paid version of the tutorial!
使用 ReAct
# 使用 ReAct 的生成结果 中文
question_Chinese = "强化学习教程(蘑菇书)现在的价格是多少?如果我在此基础上降价 15% 卖出,应该如何定价?用中文输出结果。"
result_Chinese = agent_ReAct.run(question_Chinese)
print(f"\n生成结果-中文:\n{result_Chinese}")Output
[1m> Entering new AgentExecutor chain...[0m [32;1m[1;3m Thought: 我需要先查找《强化学习教程(蘑菇书)》的当前价格,然后计算降价15%后的定价。首先使用搜索工具获取原价。 Action: Search Action Input: 强化学习教程 蘑菇书 当前价格 [0m Observation: [36;1m[1;3m['Easy RL 强化学习教程蘑菇书深度强化学习落地指南机器学习人工智能导论神经网络与深度学习编程入门电脑书籍人民邮电出版社. ¥58.40. 价格可能因优惠活动发生变化.', '《Easy RL:强化学习教程》王琦,出版于2022-03-01,中图网为您提供正版《Easy RL:强化学习教程》价格、内容简介、全书目录、读者书评等信息。', '李宏毅老师的《深度强化学习》是强化学习领域经典的中文视频之一。李老师幽默风趣的上课风格让晦涩难懂的强化学习理论变得轻松易懂,他会通过很多有趣的例子来讲解 ...', '【正版书】 蘑菇绘-30种蘑菇的色铅笔图绘飞乐鸟著水利水电出版社. ¥. 39.52. 4人付款. 北京. 孤雁直木旗舰店 · 旺旺在线 · 【新华文轩】看!蘑菇正版书籍新华书店旗舰店 ...', '苏宁易购为您提供[正版]Easy RL 强化学习教程蘑菇书深度强化学习落地指南机器学习人工智能导论神经网络与深度学习编程入门电脑价格、图片、品牌、报价等信息, ...', '蘑菇书EasyRL强化学习教程_v.1.0.2 · 总结来说,"蘑菇书EasyRL强化学习教程_v.1.0.2"是一本结合了李宏毅、周博磊、李科浇等多位专家的教学精华,旨在为 ...', '... 书生产计划与调度等相关. 正版套装. ¥109.00 · 套装[店]深度学习花书+动手学深度学习pytorch版AI人工智能基础机器强化学习 ...', '蘑菇书《Easy RL》介绍了强化学习的基础知识和Markov决策过程,以及Q网络的一些特性和优化方法。文章还讨论了延迟的策略更新和目标策略平滑等内容。', '... 书的时候,没有资源能够同时满足一些条件:(1)是最新的;(2)涵盖了现代机器学习的. 所有领域,技术深度丰富;(3)在一本引人入胜的教科书中,人们可以在实践教程 ...', '本文讲的十个应用只是对强化学习的一个简单了解,如果您想了解更多信息或者全面学习强化学习,请查看这个下面的几个GitHub仓库学习:. 强化学习蘑菇书EasyRL( ...'][0m Thought:[32;1m[1;3m Thought: 我需要先查找《强化学习教程(蘑菇书)》的当前价格,然后计算降价15%后的定价。根据搜索结果,原价为¥58.40。现在使用计算器计算降价后的价格。 Action: Calculator Action Input: 58.40 * 0.85[0m Observation: [33;1m[1;3mAnswer: 49.64[0m Thought:[32;1m[1;3m Final Answer: 《强化学习教程(蘑菇书)》当前价格为¥58.40。若降价15%出售,新的定价应为¥49.64。[0m [1m> Finished chain.[0m 生成结果-中文: 《强化学习教程(蘑菇书)》当前价格为¥58.40。若降价15%出售,新的定价应为¥49.64。
# 使用 ReAct 的生成结果 英文
question_English = "What is the current price of the Reinforcement Learning Tutorial (The Mushroom Book, By DataWhale)? How should I price it if I sell it with a 15% price reduction on top of that?"
result_English = agent_ReAct.run(question_English)
print(f"\n生成结果-英文:\n{result_English}")Output
[1m> Entering new AgentExecutor chain...[0m [32;1m[1;3m[0m Observation: Invalid Format: Missing 'Action:' after 'Thought: Thought:[32;1m[1;3m Thought: I need to find the current price of the book first. Since the user mentioned "The Mushroom Book" by DataWhale, which is a known free resource, the current price is likely $0. If that's the case, a 15% discount would not change the price. However, to confirm, I should check the availability and pricing on platforms like Amazon or the official DataWhale website. Action: Search Action Input: "The Mushroom Book by DataWhale price on Amazon" [0m Observation: [36;1m[1;3m['] on Amazon.com. *FREE* shipping on qualifying offers. THE MUSHROOM BOOK: A ... Price ($24.95x). - $24.95. Subtotal. $$24.9524.95. Subtotal ...', 'Buy New. $32.51$32.51. FREE delivery Thursday, June 12 on orders shipped by Amazon over $35 · Return this item for free · Save with Used - Good. $29.09$29.09.', 'Hikaru Kotz · 4.74.7 out of 5 stars. (556) · $9.99 ; Kytefox Publishing · 4.64.6 out of 5 stars. (3K) · $8.99 ; Maybell Eequay · 4.94.9 out of 5 stars. (758) · $6.81 ...', '"This book uses the matsutake mushroom as a lens through which to examine contemporary environmental history, global commodity production, and science. With ...', '"The Mushroom Book" is out of print. Why? It has lesser offspring with it\'s cloned paperback edition but the original is currently recycled online at over £30.', 'A veritable feast of more than 150 mushroom recipes-from classic Italian preparations to Asian-inspired creations and contemporary dishes.', "It's word and image predictive generators, basically. And it's the people putting these books out that are responsible if people get killed.", '$14.99$1499. Digital List Price:$30.00$30.00.', 'This book, with over 100 recipes that make the most of readily available mushrooms in dishes ranging from classic to contemporary via oriental and Eastern ...', 'Used book that is in excellent condition. May show signs of wear or ... Other sellers on AmazonOther sellers on Amazon. Compare Used (3) from. $22.05 ...'][0m Thought:[32;1m[1;3m Thought: I now know the final answer. Final Answer: The current price of "The Mushroom Book" by DataWhale on Amazon is $24.95 for new copies and varies for used ones (e.g., $22.05). If you sell it with a 15% price reduction, the discounted price would be $24.95 × 0.85 = **$21.21**. However, note that "The Mushroom Book" is not the official title of DataWhale's Reinforcement Learning Tutorial, which is a free resource. If you are referring to that, the price is $0, and a 15% discount would still be $0. Clarify the title for accuracy.[0m [1m> Finished chain.[0m 生成结果-英文: The current price of "The Mushroom Book" by DataWhale on Amazon is $24.95 for new copies and varies for used ones (e.g., $22.05). If you sell it with a 15% price reduction, the discounted price would be $24.95 × 0.85 = **$21.21**. However, note that "The Mushroom Book" is not the official title of DataWhale's Reinforcement Learning Tutorial, which is a free resource. If you are referring to that, the price is $0, and a 15% discount would still be $0. Clarify the title for accuracy.
需要指出的是,ReAct 并不是完美的,有时多次检索和计算可能会导致报错。在我进行调试的过程中,就遇到了以下的报错:
分析实验结果:
-
针对给定的问题:"强化学习教程(蘑菇书)现在的价格是多少?如果我在此基础上降价 15% 卖出,应该如何定价?"。推理思路应为:首先需要确定这本书的具体价格,然后才能准确地计算出基于此降价 15% 的价格。
-
在没有使用 ReAct,直接 Prompting 的情况下,无论输入提示是中文还是英文,gpt-3.5-turbo-0125 都无法准确回答问题。
-
当使用 ReAct 并输入中文提示时,gpt-3.5-turbo-0125 能够给出准确的答案:“我现在知道了强化学习教程(蘑菇书)的价格是 66.90 元,降价 15% 后的定价应为 56.865 元。”
-
当使用 ReAct 并输入英文提示时,gpt-3.5-turbo-0125 无法给出准确的答案,其生成的结果为:“The current price of the Reinforcement Learning Tutorial (The Mushroom Book, By DataWhale) is 45.99 dollar, and it should be priced at 6.90 dollar if sold with a 15% reduction.” (备注:"$" 符号在 MarkDown 中渲染存在冲突,所以使用 dollar 替代)
-
在输入中文提示时,给出的答案都是准确的。分析表明,在实际应用中,如果是中文环境,参考 ReAct 的源代码并根据特定需求定制中文的 Prompt 模板和演示是有价值的。
-
通过观察 ReAct 的执行过程,我们发现它以交错的方式生成推理轨迹和任务特定操作,这增强了 LLM 的可解释性。
前面的实验结果表明,在某些情况下,使用英文 Prompt 的效果并不理想。因此,我们再补充一个示例,给出今天的日期,让 LLM 回答:列出历史上在这一天发生的重大事件。
from datetime import datetime
# 获取当前日期
today = datetime.today()
# 格式化为 yyyy-MM-dd
formatted_date = today.strftime("%Y-%m-%d")
print(f"今天的日期是{formatted_date}")Output
今天的日期是2025-06-09
prompt = f"今天的日期是{formatted_date},列出历史上在这一天发生的重大事件。请用中文回答。"
result_no_ReAct = get_completions(prompt, "Qwen/Qwen3-8B")
print(f"\n生成结果-中文:\n{result_no_ReAct}")Output
生成结果-中文: 2025年6月9日尚未到来,因此目前没有历史上的事件发生在这一天。不过,我可以为你列出一些历史上在**6月9日**发生的重大事件,供你参考: 1. **1940年6月9日**:第二次世界大战期间,法国政府宣布巴黎进入紧急状态,标志着法国在德军进攻下开始撤退。 2. **1941年6月9日**:第二次世界大战期间,德国入侵苏联的“巴巴罗萨行动”开始,这是二战中规模最大的陆地进攻之一。 3. **1945年6月9日**:第二次世界大战接近尾声,德国在法国的占领区开始崩溃,法国抵抗运动逐渐取得优势。 4. **1967年6月9日**:以色列在六日战争中占领了约旦河西岸和加沙地带,这一事件对中东局势产生了深远影响。 5. **1975年6月9日**:美国与伊朗签署《联合公报》,标志着两国关系的正常化,结束了1953年政变后的长期对立。 6. **1990年6月9日**:美国和苏联签署《削减战略武器条约》(START I),这是冷战后期重要的军控协议。 7. **2003年6月9日**:伊拉克战争期间,美国主导的联军宣布已控制巴格达,标志着伊拉克政权更迭的开始。 如果你想知道**2025年6月9日**未来可能发生的事件,我可以帮你预测或分析当天的节日、纪念日或可能的重要活动。需要的话请告诉我!
prompt = f"Today's date is {formatted_date}. List the great events that have occurred on this day in history."
result_no_ReAct = get_completions(prompt, "Qwen/Qwen3-8B")
print(f"\n生成结果-英文:\n{result_no_ReAct}")Output
生成结果-英文: June 9 is not widely recognized as a date of major global historical events, but there are some notable occurrences that have happened on this day in history. Here are a few: 1. **1940 – World War II**: The Battle of Britain officially began. This was a pivotal aerial campaign in which the Royal Air Force (RAF) defended the United Kingdom against the German Air Force (Luftwaffe) during the summer of 1940. 2. **1944 – World War II**: The Allied invasion of Normandy, also known as D-Day, began on June 6, but June 9 saw the continuation of the landings and the establishment of a foothold in France. It was a critical phase in the liberation of Western Europe. 3. **1969 – Vietnam War**: The U.S. military began its withdrawal from Vietnam, marking a significant shift in the war's direction. This was part of the broader "Vietnamization" policy under President Richard Nixon. 4. **1975 – Vietnam War**: The Fall of Saigon occurred on April 30, but June 9 is not directly associated with a major event in this conflict. 5. **1989 – Tiananmen Square protests**: June 9 is not a date of a major event in this context. 6. **2005 – Iraq War**: The U.S. military began its withdrawal from Iraq, which was a major shift in the conflict. However, the formal withdrawal started on August 31, 2010. 7. **2011 – Libya War**: The NATO-led intervention in Libya began on March 19, 2011, but June 9 is not a major date in this conflict. If you are looking for events in a specific region or category (e.g., sports, culture, technology), please let me know, and I can provide more targeted information.
# 使用 ReAct 的生成结果(中文)
question_Chinese = f"今天的日期是{formatted_date}。列出历史上在这一天发生的重大事件。请用中文回答。"
result_Chinese = agent_ReAct.run(question_Chinese)
print(f"\n生成结果-中文:\n{result_Chinese}")Output
[1m> Entering new AgentExecutor chain...[0m [32;1m[1;3m Thought: 我需要使用搜索工具来查找历史上6月9日发生的重大事件。 Action: Search Action Input: 历史上6月9日的重大事件[0m Observation: [36;1m[1;3m1944年:第二次世界大战:为了报复法国抵抗运动的成功攻击,德国党卫队和党卫队保安处在蒂勒绞死99名男子。 1954年:日本自卫队成立。 1955年:在第二次世界大战中被俘的德国、奥地利战俘乘坐苏联专列返国。 1975年:中华人民共和国与菲律宾共和国建交。[0m Thought:[32;1m[1;3m Final Answer: 历史上6月9日发生过以下重大事件: 1. **1944年6月9日**:第二次世界大战期间,德国党卫队在法国蒂勒镇绞死99名抵抗运动成员,以报复此前的攻击。 2. **1954年6月9日**:日本自卫队正式成立,标志着日本在战后重新建立军事力量。 3. **1955年6月9日**:二战中被苏联关押的德国和奥地利战俘搭乘专列返回祖国。 4. **1975年6月9日**:中华人民共和国与菲律宾共和国正式建立外交关系。 注:部分事件的具体日期可能存在争议或不同来源的差异,建议结合权威历史资料进一步确认。[0m [1m> Finished chain.[0m 生成结果-中文: 历史上6月9日发生过以下重大事件: 1. **1944年6月9日**:第二次世界大战期间,德国党卫队在法国蒂勒镇绞死99名抵抗运动成员,以报复此前的攻击。 2. **1954年6月9日**:日本自卫队正式成立,标志着日本在战后重新建立军事力量。 3. **1955年6月9日**:二战中被苏联关押的德国和奥地利战俘搭乘专列返回祖国。 4. **1975年6月9日**:中华人民共和国与菲律宾共和国正式建立外交关系。 注:部分事件的具体日期可能存在争议或不同来源的差异,建议结合权威历史资料进一步确认。
《邦联条款与永久联盟》是美国 13 个州之间的协议,这些州曾经是美国的十三个殖民地,它们被视为国家的第一个政府框架。它在 1776 年 7 月至 1777 年 11 月间在费城的独立厅由第二次大陆会议进行了讨论,最终由大陆会议于 1777 年 11 月 15 日拟定。在经过所有 13 个殖民地州的批准后,于 1781 年 3 月 1 日生效。
维基百科 Articles of Confederation:https://en.wikipedia.org/wiki/Articles_of_Confederation
# 使用 ReAct 的生成结果(英文)
question_English = f"Today's date is {formatted_date}. List the great events that have occurred on this day in history."
result_English = agent_ReAct.run(question_English)
print(f"\n生成结果-英文:\n{result_English}")Output
[1m> Entering new AgentExecutor chain...[0m [32;1m[1;3m Thought: I need to search for historical events that occurred on June 9. Action: Search Action Input: "Great events on June 9 in history"[0m Observation: [36;1m[1;3m['Nero Commits Suicide · Battle of Langensalza · Pope and France Sign Secret Treaty · Cartier Sails the St. Lawrence · Book of Common Prayer · William Takes Gelderland.', "Serbian Prince Michael III was assassinated, derailing the Balkan League's plans for a coordinated rebellion against the Ottomans and destroying the league. How ...", '1732 – James Oglethorpe is granted a royal charter for the colony of the future U.S. state of Georgia. · 1772 – The British schooner Gaspee is burned in ...', "In Washington, DC on June 9, 1893, the interior of ramshackle Ford's Theatre collapses, causing the deaths of 22 people.", '1967 Israel captures the Golan Heights from Syria · 1957 Four Austrian climbers become the first to conquer Broad Peak · 1946 Bhumibol Adulyadej is crowned King ...', "Discover what happened on June 9 with HISTORY's summaries of major events, anniversaries, famous births and notable deaths.", 'Several World War II events took place on this day, the most gruesome being the torture and hanging of 99 residents of Tulle town in France, by the Nazi German ...', 'June 9th is National Strawberry Rhubarb Pie Day & Donald Duck Day. Today marks day 160 of the year, and we have 205 days left in 2025.', 'Major Events · 1815 End of the Congress of Vienna: New European political situation is set · 1856 500 Mormons leave Iowa City, Iowa, and head west for Salt Lake ...', '1986. NASA publishes a report on the Challenger accident. · 1972. American advisor John Paul Vann is killed in a helicopter accident in Vietnam. · 1959. The first ...'][0m Thought:[32;1m[1;3m Thought: I now know the final answer. Final Answer: Here are some significant events that occurred on June 9 in history: 1. **1815**: The Congress of Vienna concluded, reshaping European politics after the Napoleonic Wars. 2. **1327**: The Battle of Langensalza took place, a key event in the Hundred Years' War. 3. **1549**: The Book of Common Prayer was established in England, marking a major shift in religious practices. 4. **1732**: James Oglethorpe received a royal charter to found the colony of Georgia. 5. **1772**: The British schooner *Gaspee* was burned in what became a catalyst for the American Revolution. 6. **1878**: Serbian Prince Michael III was assassinated, disrupting the Balkan League's plans against the Ottomans. 7. **1893**: The interior of Ford's Theatre collapsed in Washington, DC, killing 22 people. 8. **1944**: Nazi forces tortured and hanged 99 residents of Tulle, France, during World War II. 9. **1946**: King Bhumibol Adulyadej (Rama IX) was crowned King of Thailand. 10. **1967**: Israel captured the Golan Heights from Syria during the Six-Day War. Note: Some entries in the search results may have incorrect dates (e.g., Tesla's birthday is actually December 10, 1856, and Schubert died on December 19, 1828). The above list includes verified historical events.[0m [1m> Finished chain.[0m 生成结果-英文: Here are some significant events that occurred on June 9 in history: 1. **1815**: The Congress of Vienna concluded, reshaping European politics after the Napoleonic Wars. 2. **1327**: The Battle of Langensalza took place, a key event in the Hundred Years' War. 3. **1549**: The Book of Common Prayer was established in England, marking a major shift in religious practices. 4. **1732**: James Oglethorpe received a royal charter to found the colony of Georgia. 5. **1772**: The British schooner *Gaspee* was burned in what became a catalyst for the American Revolution. 6. **1878**: Serbian Prince Michael III was assassinated, disrupting the Balkan League's plans against the Ottomans. 7. **1893**: The interior of Ford's Theatre collapsed in Washington, DC, killing 22 people. 8. **1944**: Nazi forces tortured and hanged 99 residents of Tulle, France, during World War II. 9. **1946**: King Bhumibol Adulyadej (Rama IX) was crowned King of Thailand. 10. **1967**: Israel captured the Golan Heights from Syria during the Six-Day War. Note: Some entries in the search results may have incorrect dates (e.g., Tesla's birthday is actually December 10, 1856, and Schubert died on December 19, 1828). The above list includes verified historical events.
在这个示例中,直接提示 GPT-3.5 Turbo 问答:今天的日期是什么?列出历史上在这一天发生的重大事件。结果是:模型一本正经地胡说八道。
GPT-3.5 Turbo 可以通过 ReAct 准确地回答这个问题。我们通过访问这个网站 https://www.onthisday.com/events/march/1 和使用搜索引擎进行事实检查。结果显示,使用英文 Prompt 的效果比使用中文 Prompt 更好。
四、总结与讨论
你知道我们玩乐高积木时,我们会想一想,然后拿一个积木,再想一想,再拿一个积木,直到我们建造出我们想要的东西,对吧?这就是我们思考和行动交替进行的过程。ReAct 就像一个聪明的机器人,它也会这样做。它会想一想,然后做一些事情,再想一想,再做一些事情,直到它完成了它的任务。这就是为什么我们说 ReAct 通过交替使用语言推理和可执行计划,模仿了人类解决问题的思维方式。
在这个过程中,大语言模型(LLM)就像机器人的大脑,它可以控制机器人的 “手” 和 “脚”,让机器人知道下一步应该做什么。ReAct 的优点是它很灵活,就像我们可以用乐高积木建造各种各样的东西一样。它也很容易使用,就像我们很容易地拿起和放下乐高积木一样。而且,它可以从很少的例子中学习,就像我们可以从几个乐高积木中学习如何建造一个房子一样。最后,它的行为是可以解释的,就像我们可以解释我们是如何用乐高积木建造房子的一样。
此外,ReAct 也是一种优秀的微调格式。我们可以利用推理轨迹和正确的结果数据来构建中间过程的数据集,这是一种有效的降低标注成本的方法,可以通过这种方法以较低的成本构建高质量的 Fine-tuning 数据集。研究者已经观察到,当模型大小约为 60B 时,Fine-tuning 带来的性能提升远超过 Prompt 方法,这表明 ReAct 结合 Fine-tuning 可能是提高 LLM 性能的有效方式。
最后,值得一提的是,ReAct 可以被视为当前人工智能领域中热门的 Agent 研究的开创性工作。ReAct 提出了一种基于 LLM 的 Agent 范式,并在问答和决策任务上取得了良好的结果,但其性能受到 LLM 能力的限制。对于具有大动作空间的复杂任务,需要更多的演示才能进行有效的学习。然而,这很容易超出 LLM 的上下文学习的输入长度限制。
参考资料:
-
ICLR 2023 - ReAct: Synergizing Reasoning and Acting in Language Models,https://openreview.net/forum?id=WE_vluYUL-X
-
Lilian Weng - LLM Powered Autonomous Agents,https://lilianweng.github.io/posts/2023-06-23-agent/
