自然语言处理从入门到应用——LangChain:代理(Agents)-[基础知识]

分类目录:《自然语言处理从入门到应用》总目录


有些应用程序不仅需要预先确定的LLM或其他工具调用链,而且可能需要根据用户输入的不同而产生不同的链条。在这些类型的链条中,有一个“代理”可以访问一套工具。根据用户输入,代理可以决定是否调用其中任何一个工具。在本文中,我们首先“快速入门”代理,介绍如何以端到端的方式使用与代理相关的所有内容。

代理使用LLM来确定采取哪些行动以及顺序。 一个动作可以是使用工具并观察其输出,或返回给用户。当代理被正确使用时,它们可以非常强大。本文的目的是向您展示如何通过最简单、最高级别的API轻松使用代理。为了使用代理,我们应该搜下了解以下概念:

  • 工具(Tools):执行特定任务的功能,即有关预定义工具及其规范的列表。这可以是Google 搜索、数据库查找、 Python REPL、其他链。工具的接口目前是一个函数,预计将有一个字符串作为输入,一个字符串作为输出。
  • 大语言模型(LLM):为代理提供动力的语言模型。
  • 代理(Agents):要使用的代理,即有关受支持的Agent及其规范的列表。这应该是引用支持代理类的字符串。因为本文主要关注最简单、最高级别的API,所以它只涉及使用标准支持的代理。如果要实现自定义代理,可以参考《自然语言处理从入门到应用——LangChain:代理(Agents)》系列后续文章。
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,因此我们需要传递它:

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.

参考文献:
[1] LangChain ️ 中文网,跟着LangChain一起学LLM/GPT开发

你可能感兴趣的:(自然语言处理从入门到应用,人工智能,深度学习,自然语言处理,langchain,GPT)