安装openai和LangChain库。
pip -q install openai
pip install LangChain
设置谷歌搜索的API密钥,以及设置OpenAI的密钥。
os.environ["OPENAI API KEY"]="填人你的密钥"
os.environ["SERPAPI API KEY"]="填人你的谷歌搜索的API密钥"
首先,加载大语言模型。
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=lm进去。
tools load tools (["serpapi","llm-math"],llm=llm)
最后,初始化一个Agent组件。
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?")
看一看AgentExecutor链组件运行的结果,重点是观察Observation、Action、Answer及Thought的变化。这就是Agent在回答雷纳尔多(LeoDiCaprio)所经历的中间步骤。这个中间步骤执行的便是ReAct框架的策略。
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 the0.43 power is3.991298452658078.
Finished chain.
"Camila Morrone is Leo DiCaprio's girlfriend and her current age raised to
the0.43 power is3.991298452658078."
在深入了解各种具体的Agent组件之前,先看一下源代码中定义的Agent类型枚举类。这个枚举类列出了LangChain框架中所有可用的Agent组件。知道了这个概念,我们就可以更好地理解以下要介绍的各种Aget组件及它们的使用场景。
class AgentType(str,Enum):
ZERO_SHOT_REACT_DESCRIPTION ="zero-shot-react-description"
REACT_DOCSTORE ="react-docstore"
SELF_ASK_WITH_SEARCH ="self-ask-with-search"
CONVERSATIONAL_REACT_DESCRIPTION ="conversational-react-description"
CHAT_ZERO_SHOT_REACT_DESCRIPTION ="chat-zero-shot-react-description"
CHAT_CONVERSATIONAL_REACT_DESCRIPTION ="chat-conversational-react-description"
STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION =("structured-chat-zero-shot-react-description")
OPENAI_FUNCTIONS= "openai-functions"
这些Agent组件是根据不同的理论依据和实践需求创建的,并已在源代码中实现,可供直接使用。内置的Agent组件提供了丰富的工具组件集,满足了大多数使用场景。接下来,将其按原理进行分类,并介绍它们的应用场景。
了解这些分类和内置的Agent组件不仅能帮助你选择最适用于特定场景的组件,还可以作为你自定义Agent组件时的参考。在开始创建自定义Agent组件时,先确定其需要承担的任务类型,然后选择最适合完成该任务的Aget组件类型。内置的Agent组件类型,如Zero-shot ReAct组件、结构化输入反应组件、OpenAI函数组件等,都有各自的特点和应用场景。通过理解和学习这些类型,可以更有效地在LangChain框架内创建和使用Agent组件。
在LangChain框架中,Agent模块实现了多种类型的Agent组件,比如ZeroShotAgent组件和OpenAIFunctionsAgent组件。另外,LangChain框架鼓励开发者创建自己的Agent组件。理解这些Agent:组件的使用步骤,以及如何自定义Agent组件都至关重要。首先,需要明白创建和运行Agent是两个分离的步骤。创建Agent是通过实例化Agent类来完成的。在创建Agent的过程中,Tools也会被用于提示词模板,所以,无论是Agent组件还是AgentExecutor组件的初始化过程中,都需要设置tools属性。在创建好Agent组件后,需要将其放入AgentExecutor组件中进行运行。
AgentExecutor是Agent组件的运行环境,它是一个链组件。实际上运行的是这个链组件,而不是Agent组件本身。在整个LangChain框架中,所有模块的终点都是被组合到链组件上的。Agent不能脱离AgentExecutor环境,就像鱼离不开水。在运行过程中,AgentExecutor会调用Tools的方法来执行具体的任务。以下是一个使用ZeroShotAgent:组件的示例:
from langchain.agents import ZeroShotAgent,Tool,AgentExecutor
llm_chain =LLMChain (llm=OpenAI(temperature=0),prompt=prompt)
tool_names =[tool.name for tool in tools]
agent ZeroShotAgent (11m chain=11m chain,allowed tools=tool names)
agent executor AgentExecutor.from agent and tools
agent=agent,tools=tools,verbose=True
agent_executor.run("How many people live in canada as of 2023?")
在这个示例中,首先创建了一个ZeroShotAgent实例,并将其放人了AgentExecutor中。然后,调用了AgentExecutor的run方法来运行这个Agent,并获取了其运行结果。这是目前最通用的Agent组件的实现方法。无论是自定义还是内置的Agent组件,都遵循这个使用步骤。对于内置的Agent组件类型,还有一个简化方法initialize_agent,.简化之后,把原本的两个步骤合并为一个步骤,而不需要创建Agent组件实例,也不需要显式创建AgentExecutor。
agent =initialize_agent (tools,11m,agent=AgentType.ZERO SHOT REACT DESCRIPTION,verbose=True)
initialize_agent方法被广泛用于内置的Agent组件中。比如上面使用的agent=AgentType…ZERO_SHOT_REACT_DESCRIPTION,实际上它对应的是ZeroShotAgent。
值得注意的是,如果此方法并不在这个清单内,则这个方法并不适用。以下类型均可
以使用这个方法:
{
AgentType.ZERO_SHOT_REACT_DESCRIPTION:ZeroShotAgent,
AgentType.REACT_DOCSTORE:ReActDocstoreAgent,
AgentType.SELF_ASK_WITH_SEARCH:SelfAskWithSearchAgent,
AgentType.CONVERSATIONAL_REACT_DESCRIPTION:ConversationalAgent,
AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION:ChatAgent,
AgentType.CHAT_CONVERSATIONAL_REACT_DESCRIPTION:ConversationalChatAgent,
AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION:StructuredChatAgent,
AgentType.OPENAI_FUNCTIONS:OpenAIFunctionsAgent}
下面通过一个实际的应用案例代码,展示一个完整的Agent组件使用步骤。
Agent组件不仅能够完成单一任务,还能够动态选择并利用多种工具组件来应对和解决不同类型的问题和任务,这种特点被称为Agent组件的多功能性。下面通过代码示例,实现一个多功能性的Agent:组件。先安装要用到的库。
pip -q install LangChain huggingface hub openai google-search-results tiktoken wikipedia
设置所需工具的密钥和LLM模型的密钥。
import os
os.environ["OPENAI API KEY"]="填入你的密钥"
os.environ["SERPAPI API KEY"]="填人你的密钥"
设置Agent组件的过程包含两个主要步骤:加载Agent组件将使用的工具,然后用这些工具初始化Aget组件。首先初始化一些基础设置,然后加载两个工具:一个使用搜索API进行搜索的工具,以及一个可以进行数学运算的计算器工具。然后加载工具和初始化Agent组件。
from langchain.agents import load tools
from langchain.agents import initialize agent
from langchain.llms import OpenAI
llm =OpenAI(temperature=0)
每个工具都有一个名称和描述,表示它是用来做什么的。例如“serpapi’”工具用于搜索,而“1lm-math”工具则用于解决数学问题。这些工具内部有很多内容,包括模板和许多不同的chains。tools load_tools (["serpapi","llm-math"],llm=llm)
一旦设置好了工具,就可以开始初始化Agent组件。初始化Agent组件需要传人工具和语言模型,以及Agent:组件的类型或风格。下面使用了“zero-shot-react–description”的内置Agent组件,这个组件的思想是基于一篇关于让语言模型采取行动并生成操作步骤的论文。
agentinitialize_agent (tools,1lm,agent="zero-shot-react-description",verbose=True)
初始化Agent组件的重要步骤之一是设置提示词模板。这些提示词会在Agent组件开始运行时告诉大语言模型它应该做什么。agent.agent.llm_chain.prompt.template
这里,为Agent组件设置了两个工具:搜索引擎和计算器。然后,设置了Agent组件应该返回的格式,包括它需要回答的问题,以及它应该采取的行动和行动的输人。
'Answer the following questions as best you can.You have access to thefollowing tools:\n\nSearch:A search engine.Useful for when you need to answerquestions about current events.Input should be a search query.\nCalculator:Useful for when you need to answer questions about math.\n\nUse the followingformat:\n\nQuestion:the input question you must answer\nThought:you should
always think about what to do\nAction:the action to take,should be one of [Search,
Calculator]\nAction Input:the input to the action\nobservation:the result of
the action\n...(this Thought/Action/Action Input/Observation can repeat N
times)\nThought:I now know the final answer\nFinal Answer:the final answer to
the original input question\n\nBegin!\n\nQuestion:
(input)\nThought:(agent scratchpad)'
最后,运行Agent组件。需要注意的是,Agent组件并不总是需要使用工具的。例如问Agent组件:“你今天好吗?”对于这样的问题,Agent组件并不需要进行搜索或计算,而是可以直接生成回答。
agent.run ("Hi How are you today?")
这些是Agent组件的基础功能。Agent组件的数学能力。下面继续探讨如何在实际中应用Agent组件的数学能力。agent.run ("Where is DeepMind's office?")
在前面的示例中,尚未使用到math模块,下面介绍一下它的作用。让Agent组件查找Deep Mind的街道地址中的数字,然后进行平方运算。
agent.run("If I square the number for the street address of DeepMind what answer do I get?")
Agent组件首先通过搜索获取地址,然后找到数字5(假设为地址的一部分),最后进行平方运算,得出结果25。然而,如果地址中包含多个数字,则Aget组件可能会对哪个数字进行平方运算产生混淆,这就是我们可能需要考虑和解决的问题。
Entering new AgentExecutor chain...
I need to find the street address of DeepMind first.
Action:Search
Action Input:"DeepMind street address"
Observation:DeepMind Technologies Limited,is a company organised under the
laws of England and Wales,with registered office at 5 New Street Square,London,
EC4A 3TW ("DeepMind","us","we",or "our").DeepMind is a wholly owned subsidiary
of Alphabet Inc.and operates请参考本书代码仓库URL映射表,找到对应资源://deepmind.com
(the "site").
Thought:I now need to calculate the square of the street address.
Action:Calculator
Action Input:52
Observation:Answer:25
Thought:I now know the final answer.
Final Answer:25
Finished chain.
'25'
Agent组件的使用终端工具能力。在工具库中,还有一个尚未使用的工具,那就是终端工具。例如,可以问Agent组件当前目录中有哪些文件。下面继续探讨如何在实际中应用Aget组件的使用终端工具能力。agent.run ("What files are in my current directory?")
Agent组件将运行一个LS命令来查看文件夹,并返回一个文件列表。
Entering new AgentExecutor chain...
I need to find out what files are in my current directory.
Action:Terminal
Action Input:ls
Observation:sample data
Thought:I need to find out more information about this file.
Action:Terminal
Action Input:1s -1 sample data
Observation:total 55504
-rwxr-xr-x 1 root root
1697 Jan 1 2000 anscombe.json
-rw-r--r--1 rootroot
301141 Mar 10 20:51 california housing test.csv
-rw-r--r--1 rootroot 1706430 Mar 10 20:51 california housing train.csv
-rw-r--r--1 root root 18289443 Mar 10 20:51 mnist test.csv
-rw-r--r--1 rootroot 36523880 Mar 10 20:51 mnist train small.csv
-rwxr-xr-x 1 root root
930 Jan 1 2000 README.md
Thought:I now know the final answer.
Final Answer:The files in my current directory are anscombe.json,
california_housing_test.csv,california_housing_train.csv,mnist_test.csv,
mnist train small.csv,and README.md.
Finished chain.
'The files in my current directory are anscombe.json,
california_housing_test.csv,california_housing_train.csv,mnist_test.csv,
mnist_train_small.csv,and README.md.'
甚至可以问它特定的文件是否存在,比如询问当前目录中是否有一个关于“California”的文件。
agent.run ("Does my current directory have a file about California?")
Agent组件会使用grep命令进行检索,并报告结果。然而,这个过程可能需要多次调用语言模型,从而产生一定的运行成本。
Entering new AgentExecutor chain...
I need to find out what files are in my current directory.
Action:Terminal
Action Input:ls
Observation:sample data
Thought:I need to find out if there is a file about California in this
directory.
Action:Terminal
Action Input:grep California sample data
Observation:Command 'grep California sample_data'returned non-zero exit
status 2.
Thought:I need to look for a different way to search for the file.
Action:Search
Action Input:"California file in current directory"
Observation:The pwd command displays the full,absolute path of the current,
or working,directory.It's not something you'll use all the time,but it can ..
Thought:I need to use the pwd command to find the file.
Action:Terminal
Action Input:pwd
Observation:/content
Thought:I need to use the ls command to find the file.
Action:Terminal
Action Input:ls
Observation:sample data
Thought:I need to use the grep command to find the file.
Action:Terminal
Action Input:grep California sample data
Observation:Command 'grep California sample data'returned non-zero exit
status 2.
Thought:I need to look for a different way to search for the file.
Action:Search
Action Input:"California file in current directory"
Observation:The pwd command displays the full,absolute path of the current,
or working,directory.It's not something you'll use all the time,but it can ..
Thought:I need to use the find command to find the file.
Action:Terminal
Action Input:find -name "*California*"
Observation:Command 'find.-name "*California*'returned non-zero exit
status 2.
Thought:I need to use the grep command to find the file.
Action:Terminal
Action Input:grep -R California
Observation:sample_data/README.md:california_housing_data*.csv'is
California housing data from the 1990 US
Thought:I now know the final answer.
Final Answer:Yes,there is a file about California in the current directory.
Finished chain.
'Yes.there is a file about California in the current directory.'
在使用终端工具时,需要非常谨慎。如果你不希望最终用户能够通过运行终端命令来操作你的文件系统,那么在添加这个工具时,你需要确保已采取适当的安全防护措施。不过,尽管有其潜在风险,但在某些情况下,使用终端工具还是很有用的,比如当你需要设置某些功能时。以上就是Agent组件的使用示例和注意事项。