自定义Agent组件

文章目录

    • ReAct Agent的实践
    • 工具组件和工具包组件
    • 工具组件的类型

    一个Agent组件由两部分组成:tools(代理可以使用的工具)和AgentExecutor(决定采取哪种行动)。下面逐一介绍如何创建自定义Agent组件。Tool、AgentExecutor和BaseSingleActionAgent是从LangChain.agents模块中导人的类,用于创建自定义Agent组件和tools。OpenAI和SerpAPIWrapper是从LangChain模块中导人的类,用于访问OpenAI的功能和SerpAPI的包。下面先安装库。pip -q install openaipip install LangChain然后设置密钥。

#设置OpenAI的API密钥
os.environ["OPENAI API KEY"]="填入你的密钥"
#设置谷歌搜索的API密钥
os.environ["SERPAPI_API_KEY"]"填入你的密钥"
from langchain.agents import Tool,AgentExecutor,BaseSingleActionAgent
from langchain import OpenAI,SerpAPIWrapper

    接着创建一个SerpAPIWrapper实例,然后将其run方法封装到一个Tool对象中。

search SerpAPIWrapper()
tools=[Tool(name="Search",func=search.run,description="useful for when you need to answer questions about currentevents",return direct=True,)]

    这里自定义了一个Agent类FakeAgent,这个类继承自BaseSingleActionAgent。该类定义了两个方法plan和aplan,这两个方法是Agent组件根据给定的输人和中间步骤来决定下一步要做什么的核心逻辑。

from typing import List,Tuple,Any,Union
from langchain.schema import AgentAction,AgentFinish
class FakeAgent(BasesingleActionAgent):
	"""Fake Custom Agent."""
	@property
	def input_keys(self):
		return ["input"]
	def plan(
		self,intermediate steps:List [Tuple[AgentAction,str]],kwargs:Any
		)-Union[AgentAction,AgentFinish]:
		"""Given input,decided what to do.
		Args:
		intermediate steps:Steps the LLM has taken to date,
		along with observations
		kwargs:User inputs.
		Returns:
		Action specifying what tool to use.
		"""
		return AgentAction (tool="Search",tool input=kwargs ["input"],log="")
	async def aplan(
		self,intermediate steps:List [Tuple[AgentAction,str]],kwargs:Any
		)-Union[AgentAction,AgentFinish]:
		"""Given input,decided what to do.
		Args:
		intermediate steps:Steps the LLM has taken to date,
		along with observations
		kwargs:User inputs.
		Returns:
		Action specifying what tool to use.
		"""
		return AgentAction (tool="Search",tool input=kwargs ["input"],
		log="")

    下面创建一个FakeAgent的实例。agent FakeAgent ()接着创建一个AgentExecutor实例,该实例将使用前面定义的FakeAgent和tools来执行任务。from_agent_and tools是一个类方法,用于创建AgentExecutor的实例。

agent_executor_AgentExecutor.from_agent and tools:(
agent=agent,tools=tools,verbose=True
)

    下面调用AgentExecutor的run方法来执行一个任务,任务是查询“2023年加拿大有多少人口”。

agent_executor.run ("How many people live in canada as of 2023?")

    打印最终的结果。

Entering new AgentExecutor chain...
The current population of Canada is 38,669,152 as of Monday,April 24,
2023,based on Worldometer elaboration of the latest United Nations data.
Finished chain.
'The current population of Canada is 38,669,152 as of Monday,April 24,
2023,based on Worldometer elaboration of the latest United Nations data.'

ReAct Agent的实践

    由于ReAct框架的特性,目前它已经成为首选的Agent组件实现方式。Agent组件的基本理念是将大语言模型当作推理的引擎。RAct框架实际上是把推理和动作结合在一起。当Aget组件接收到用户的请求后,大语言模型就会选择使用哪个工具。接着,Aget组件会执行该工具的操作,观察生成的结果,并把这些结果反馈给大语言模型。下面演示如何使用Agent实现ReAct框架。首先,加载openai和LangChain的库。pip -q install openai langchain设置密钥。

#设置OpenAI的API密钥
os.environ["OPENAI API KEY"]="填人你的密钥"
#设置谷歌搜索的API密钥
os.environ["SERPAPI API KEY"]="填人你的密钥"
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)

    接着,需要加载一些工具。

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

    请注意,llm-math工具使用了1lm,因此需要设置llm=llm。最后,需要使用tools、Ilm和想要使用的内置Agent组件ZERO SHOT REACT_DESCRIPTION来初始化一个Agent组件。

agent=initialize_agent (tools,11m,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 DiCaprid'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:250.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 the0.43 power is3.991298452658078."

    除此之外,你还可以创建使用聊天模型包装器作为Agent驱动器的ReAct Agent,
而不是使用LLM模型包装器。

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?")

工具组件和工具包组件

    在Agent模块中,工具组件(Tools)是Agent组件用来与世界互动的接口。这些工具组件实际上就是Agent组件可以使用的函数。它们可以是通用的实用程序(例如搜索功能),也可以是其他的工具组件链,甚至是其他的Agent组件。工具组件包(Toolkits)是用于完成特定任务的工具组件的集合,它们具有方便的加载方法。工具组件包将一组具有共同目标或特性的工具组件集中在一起,提供统一而便捷的使用方式,使得用户能够更加方便地完成特定的任务。在构建自己的Agent组件时,你需要提供一个工具组件列表,其中的工具组件是Agent组件可以使用的。除实际被调用的函数外(func=search.un),工具组件中还包括一些组成部分:name(必需的,并且其在提供给Agent组件的工具组件集合中必须是唯一的);description(可选的,但建议提供,因为Agent组件会用它来判断工具组件的使用情况)。

from langchain.agents import ZeroShotAgent,Tool,AgentExecutor
from langchain import OpenAI,SerpAPIWrapper,LLMChain
search =SerpAPIWrapper()
tools =Tool(name="Search",func=search.run,
description="useful for when you need to answer questions about current events",)

    LangChain框架中封装了许多类型的工具组件和工具组件包,用户可以随时调用这些工具组件,完成各种复杂的任务。除使用LangChain框架中提供的工具组件外,用户也可以自定义工具组件,形成自己的工具组件包,以完成特殊的任务。

工具组件的类型

    LangChain框架中提供了一系列的工具组件,它们封装了各种功能,可以直接在项目中使用。这些工具组件涵盖了从数据处理到网络请求,从文件操作到数据库查询,从搜索引擎查询到大语言模型应用等。这个工具组件列表在不断地扩展和更新。以下是目前可用的工具组件:

  • AIPluginTool:个插件工具组件,允许用户将其他的人工智能模型或服务集成到系统中。
  • APIOperation:用于调用外部API的工具组件。
  • ArxivQueryRun:用于查询Axiv的工具组件。
  • AzureCogsFormRecognizerTool:利用Azure认知服务中的表单识别器的工具组件。
  • AzureCogsImageAnalysisTool:利用Azure认知服务中的图像分析的工具组件。
  • AzureCogsSpeech2 TextTool:利用Azure认知服务中的语音转文本的工具组件。
  • AzureCogsText2 SpeechTool:利用Azure认知服务中的文本转语音的工具组件。
  • BaseGraphQLTool:用于发送GraphQL查询的基础工具组件。
  • BaseRequestsTool:.用于发送HTTP请求的基础工具组件。
  • BaseSQLDatabaseTool:用于与SQL数据库交互的基础工具组件。
  • BaseSparkSQLTool:用于执行Spark SQL查询的基础工具组件。
  • BingSearchResults:用于获取Bing搜索结果的工具组件。
  • BingSearchRun:用于执行Bing搜索的工具组件。
  • BraveSearch:用于执行Brave搜索的工具组件。
  • ClickTool:模拟点击操作的工具组件。
  • CopyFileTool:用于复制文件的工具组件。
  • Current WebPageTool:用于获取当前网页信息的工具组件。
  • DeleteFileTool:用于删除文件的工具组件。
  • DuckDuckGoSearchResults:用于获取DuckDuckGo搜索结果的工具组件。
  • DuckDuckGoSearchRun:用于执行DuckDuckGo搜索的工具组件。
  • ExtractHyperlinksTool:用于从文本或网页中提取超链接的工具组件。
  • ExtractTextTool:用于从文本或其他源中提取文本的工具组件。
  • FileSearchTool::用于搜索文件的工具组件。
  • GetElementsTool:用于从网页或其他源中获取元素的工具组件。
  • GmailCreateDraft:用于创建Gmail草稿的工具组件。
  • GmailGetMessage:用于获取Gmail消息的工具组件。
  • GmailGetThread:用于获取Gmail线程的工具组件。
  • GmailSearch:用于搜索Gmail的工具组件。
  • GmailSendMessage:用于发送Gmail消息的工具组件。
  • GooglePlacesTool:用于搜索Google Places的工具组件。
  • GoogleSearchResults:用于获取Google搜索结果的工具组件。
  • GoogleSearchRun:用于执行Google搜索的工具组件。
  • GoogleSerperResults:.用于获取Google SERP(搜索引擎结果页面)的工具组件。
  • GoogleSerperRun:用于执行Google SERP查询的工具组件。
  • HumanInputRun:用于模拟人类输人的工具组件。
  • IFTTTWebhook:用于触发IFTTT(If this Then that)服务的工作流程的工具组件。
  • InfoPowerBITool:用于获取Power BI信息的工具组件。
  • InfoSQLDatabaseTool:用于获取SQL数据库信息的工具组件。
  • InfoSparkSQLTool:.用于获取Spark SQL信息的工具组件。
  • JiraAction:用于在Jira上执行操作的工具组件。
  • JsonGet ValueTool::用于从JSON数据中获取值的工具组件。
  • JsonListKeysTool:用于列出JSON数据中的键的工具组件。
  • ListDirectory Tool:用于列出目录内容的工具组件。
  • ListPowerBITool:用于列出Power BI信息的工具组件。
  • ListSQLDatabaseTool:.用于列出SQL数据库信息的工具组件。

    请注意,这些工具组件的具体实现和功能可能会根据实际的需求和环境进行调整。

你可能感兴趣的:(langchain+llm,python,开发语言,microsoft,gpt,langchain,javascript,前端)