Skip to main content

ReAct 代理 ReAct

LangChain

本教程演示了使用代理实现 ReAct 逻辑。

from langchain.agents import load_tools
from langchain.agents import initialize_agent
from langchain.agents import AgentType
from langchain.llms import OpenAI

首先,让我们加载要用来控制代理的语言模型。

llm = OpenAI(temperature=0)

接下来,让我们加载一些工具来使用。请注意,llm-math 工具使用了 LLM,所以我们需要传入 LLM。

tools = load_tools(["serpapi", "llm-math"], llm=llm)

最后,让我们用这些工具、语言模型和我们想要使用的代理类型初始化一个代理。

agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)

现在让我们来测试一下!

agent.run("Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?")
    > Entering new AgentExecutor chain...
I need to find out who Leo DiCaprio's girlfriend is and then calculate her age raised to the 0.43 power.
Action: Search
Action Input: "Leo DiCaprio girlfriend"
Observation: Camila Morrone
Thought: I need to find out Camila Morrone's age
Action: Search
Action Input: "Camila Morrone age"
Observation: 25 years
Thought: I need to calculate 25 raised to the 0.43 power
Action: Calculator
Action Input: 25^0.43
Observation: Answer: 3.991298452658078

Thought: I now know the final answer
Final Answer: Camila Morrone is Leo DiCaprio's girlfriend and her current age raised to the 0.43 power is 3.991298452658078.

> Finished chain.


"Camila Morrone is Leo DiCaprio's girlfriend and her current age raised to the 0.43 power is 3.991298452658078."

使用聊天模型

您还可以创建使用聊天模型而不是 LLMs 作为代理驱动程序的 ReAct 代理。

from langchain.chat_models import ChatOpenAI

chat_model = ChatOpenAI(temperature=0)
agent = initialize_agent(tools, chat_model, agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
agent.run("Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?")