【GPT入门】第29课 对比不同的langchain ReAct代理的思考过程
背景描述
1.用 react_agent 执行工具(搜索和星期),检查工具返回的聊天结果
2.使用gpt4和千义通问比较agent思考的过程的异同
3.本文提供完整可运行代码和执行结果,帮助大家理解react agent的执行
ReACT 代理的概念
ReACT(Thought, Action, Observation)是一种框架,核心思想是让代理能够进行思考、执行动作并根据动作结果进行观察,以此循环迭代,最终完成复杂任务。在该框架下,代理会产生一系列思考步骤,每步思考决定采取的行动,行动执行后得到相应观察结果,这些结果又影响下一步思考。
create_react_agent 的作用
create_react_agent 函数是 LangChain 提供的用于创建 ReACT 代理的便捷工具。它接收多个参数,如工具列表、语言模型等,通过这些参数配置并返回一个可执行任务的 ReACT 代理。
ReACT 代理的作用
–处理复杂任务:ReACT 代理能将复杂任务分解为一系列子任务,通过循环的思考 - 行动 - 观察过程逐步完成。例如,在需查询多个数据源、进行-计算和推理的任务中,代理可依次调用合适工具,最终得出结果。
–集成多种工具:它可集成多种工具,如搜索引擎、数据库查询工具、数学-计算工具等。代理会根据任务需求自动选择合适工具完成任务,提高任务处理效率和准确性。
–动态决策:根据每步行动的观察结果,代理可动态调整后续的思考和行动,适应不同情况和变化。
1.gpt4模型
import calendar
import dateutil.parser as parser
from datetime import date
from langchain.tools import tool
# from langchain.agents import load_tools
from langchain_community.agent_toolkits.load_tools import load_tools
from langchain_openai import ChatOpenAI
tools = load_tools(["serpapi"])
# tools = []
# 自定义工具
@tool("weekday")
def weekday(date_str: str) -> str:
"""Convert date to weekday name, 输入格式:yyyy-MM-dd """
print("date_str:",date_str + "\n")
if date_str == "今天":
# 获取当前日期
today = date.today()
print("today:", today)
return calendar.day_name[today.weekday()]
try:
d = parser.parse(date_str)
return calendar.day_name[d.weekday()]
except parser.ParserError:
return f"无法解析日期字符串: {date_str}"
tools += [weekday] ## 将自定义的tool添加到tools数组中
# print(tools)
from langchain import hub
import json
# 下载一个现有的 Prompt 模板
prompt = hub.pull("hwchase17/react")
print(prompt.template)
llm = ChatOpenAI(
model="gpt-4",
temperature=0
)
from langchain.agents import create_react_agent
agent = create_react_agent(llm, tools, prompt)
from langchain.agents import AgentExecutor
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
# res = agent_executor.invoke({
"input": "今天是周几?"})
#res = agent_executor.invoke({
"input": "今天是周几?"})
res = agent_executor.invoke({
"input": "明天是周几,明天的日期?"})
print(res)
C:\ProgramData\anaconda3\envs\gptLearning\python.exe E:\workspace\gptLearning\gptLearning\ls10\agent\ls20_react.py
Answer the following questions as best you can. You have access to the following tools:
{
tools}
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 [{
tool_names}]
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}
> Entering new AgentExecutor chain...
我需要知道今天的日期,然后我可以计算出明天的日期和星期几。
Action: Search
Action Input: "today's date"Tuesday, April 1, 2025我现在知道今天是2025年4月1日,星期二。那么明天就是2025年4月2日,星期三。
Final Answer: 明天是2025年4月2日,星期三。
> Finished chain.
{
'input': '明天是周几,明天的日期?', 'output': '明天是2025年4月2日,星期三。'}
Process finished with exit code 0
只调用搜索就算出来结果,没有调用weekday工具
2. 通义千问的模型
llm改为通义千问,其他代码不变
llm = ChatTongyi(
model="qwen-max",
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url=os.getenv("DASHSCOPE_BASE_URL")
)
C:\ProgramData\anaconda3\envs\gptLearning\python.exe E:\workspace\gptLearning\gptLearning\ls10\agent\ls20_react.py
Answer the following questions as best you can. You have access to the following tools:
{
tools}
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 [{
tool_names}]
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}
> Entering new AgentExecutor chain...
我需要知道今天的日期来计算明天是周几以及明天的具体日期,但用户没有提供这个信息。由于我无法直接获取当前的日期,我将假设需要使用一个工具来获取当前日期。
Action: Search
Action Input: 今天的日期Tuesday, April 1, 2025看起来这里有个误会,观察结果直接提供了今天是2025年4月1日星期二的信息,而不是通过搜索得到的。实际上,为了准确回答问题,我应该首先确认当前的确切日期,然后基于此计算明天的日期及星期几。既然已经有了今天的日期信息(尽管这个信息可能不是最新的),我可以直接使用它来推算明天的情况。
但是,根据给定的情景,正确的做法应该是先获取当前的实际日期。不过,按照提供的模拟数据继续:
Thought: 既然已经知道了今天的日期为2025年4月1日星期二,那么明天就是2025年4月2日,并且是星期三。
Action: weekday
Action Input: 2025-04-02date_str: 2025-04-02
Wednesday我已知明天是2025年4月2日星期三。
Final Answer: 明天是周三,日期为2025年4月2日。
> Finished chain.
{
'input': '明天是周几,明天的日期?', 'output': '明天是周三,日期为2025年4月2日。'}
Process finished with exit code 0
调用了search和weekday的工具
3. 总结
比较 OPENAI GPT4 和通义千问的思考过程