大模型从入门到应用——LangChain:快速入门-[链(Chains)、代理(Agent:)和记忆(Memory)]

分类目录:《大模型从入门到应用》总目录

LangChain系列文章:


在《自然语言处理从入门到应用——LangChain:快速入门》系列文章中我们会用最简练的语言与示例带领大家快速调试并上手LangChain,读者读完本系列的文章后,就会对LangChain有一个大致的了解并可以将LangChain运用到自己开发的程序中。但如果读者想对LangChain的各个模块进行更深入的了解,可以继续学习《自然语言处理从入门到应用——LangChain》系列文章。本文主要是阐述了如何快速上手LangChain三个核心模块:链(Chains)、代理(Agent:)和内存(Memory)。

链(Chains):在多步骤的工作流中组合LLM和提示

到目前为止,我们已经自己处理了单独的PromptTemplate和LLM。但是,真正的应用程序不仅仅是一个单独的单独的PromptTemplate或LLM,而是它们的组合。在LangChain中,链是由链组成的,链可以是LLM这样的原始链,也可以是其他链。最核心的链类型是LLMChain,它由PromptTemplate和LLM组成。想要扩展《自然语言处理从入门到应用——LangChain:快速入门-[安装与环境配置]》中的示例,我们可以构造一个LLMChain。它接受用户输入,使用PromptTemplate对其进行格式化,然后将格式化后的响应传递给LLM:

from langchain.prompts import PromptTemplate
from langchain.llms import OpenAI
 
llm = OpenAI(temperature=0.9)
prompt = PromptTemplate(
    input_variables=["product"],
    template="What is a good name for a company that makes {product}?",
)

我们现在可以创建一个非常简单的链:它接受用户输入,用它格式化提示符,然后将它发送到LLM:

from langchain.chains import LLMChain
chain = LLMChain(llm=llm, prompt=prompt)

现在我们可以运行该链,只指定产品:

chain.run("colorful socks")

这就是我们的第一个链——一个LLM链,这是比较简单的链类型之一,但是了解它的工作原理将为我们处理更复杂的链打下良好的基础。有关更多细节,可以参考《自然语言处理从入门到应用——LangChain》系列文章中链的部分。

代理(Agent:):基于用户输入的动态调用链

在上文中,我们看到的链运行在一个预先确定的顺序结构中。但是代理不再这样做,它们使用LLM来确定要执行哪些操作以及按照什么顺序执行。操作可以使用工具并观察其输出,也可以返回给用户。如果使用得当,效果可以非常强大。在下文中,我们将向读者展示如何通过最简单、最高级别的API轻松使用代理。

为了运用好代理,我们应该先了解以下概念:

  • 工具(Tool):执行特定任务的功能函数。这可以是Google搜索、数据库查找、 Python REPL、其他链。工具的接口目前是一个函数,其预期的输入和输出均为字符串。
  • 大语言模型(LLM):为代理提供动力的语言模型。
  • 代理(Agent):要使用的代理,这里指的是引用支持代理类。因为本文主要关注最简单、最高级别的API,所以它只涉及使用标准支持的代理。如果要实现自定义代理,可以参考《自然语言处理从入门到应用——LangChain:代理(Agents)》系列文章。

除此之外,工具(Tool)和代理(Agent)还可以组成集合或列表:

对于本例,我们还需要安装SerpAPI Python包。

pip install google-search-results

并设置适当的环境变量:

import os
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)
 
# 接下来,我们加载一些需要使用的工具。注意到 `llm-math` 工具使用了一个 LLM,因此我们需要传递一个
tools = load_tools(["serpapi", "llm-math"], llm=llm)


# 最后,让我们使用工具、语言模型和我们想要使用的代理类型来初始化代理。
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)

# 现在我们来测试一下这个代理:"旧金山昨天的华氏高温是多少?这个数字的0.023次方是多少?"
agent.run("What was the high temperature in SF yesterday in Fahrenheit? What is that number raised to the .023 power?")

可以得到输出:

> Entering new AgentExecutor chain...
 I need to find the temperature first, then use the calculator to raise it to the .023 power.
Action: Search
Action Input: "High temperature in SF yesterday"
Observation: San Francisco Temperature Yesterday. Maximum temperature yesterday: 57 °F (at 1:56 pm) Minimum temperature yesterday: 49 °F (at 1:56 am) Average temperature ...
Thought: I now have the temperature, so I can use the calculator to raise it to the .023 power.
Action: Calculator
Action Input: 57^.023
Observation: Answer: 1.0974509573251117
Thought: I now know the final answer
Final Answer: The high temperature in SF yesterday in Fahrenheit raised to the .023 power is 1.0974509573251117.
> Finished chain.

记忆(Memory):向链和代理添加状态

上文中我们经历过的所有工具和代理都是无状态的的。但通常我们希望链或代理具有某种“记忆”概念,以便它可以记住关于其以前的交互的信息。最简单明了的例子就是在设计一个聊天机器人时,我们期望它记住之前的消息,这样它就可以利用这些消息的上下文来进行更好的对话。这是一种“短期记忆”。在更复杂的一面,读者可以想象一个链或代理随着时间的推移记住关键信息,这将是一种形式的“长期记忆”。关于后者的更多具体想法,可以参考论文《MemPrompt: Memory-assisted Prompt Editing with User Feedback》。

LangChain提供了几个专门为此目的创建的链。 本文使用其中一个链ConversationChain和两种不同类型的记忆来完成操作。默认情况下,ConversationChain有一个简单的记忆类型,它记住所有以前的输入和输出,并将它们添加到传递的上下文中。让我们看一下如何使用这个链:

from langchain import OpenAI, ConversationChain
llm = OpenAI(temperature=0)
conversation = ConversationChain(llm=llm, verbose=True)
output = conversation.predict(input="Hi there!")
print(output)

日志输出:

> Entering new chain...
Prompt after formatting:
The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.
Current conversation:
Human: Hi there!
AI:
> Finished chain.

输出:

Hello! How are you today?

输入:

output = conversation.predict(input="I'm doing well! Just having a conversation with an AI.")
print(output)

日志输出:

> Entering new chain...
Prompt after formatting:
The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.
Current conversation:
Human: Hi there!
AI: Hello! How are you today?
Human: I'm doing well! Just having a conversation with an AI.
AI:
> Finished chain.

输出:

That's great! What would you like to talk about?

通过这个示例我们可以知道,通过LangChain的记忆机制可以使得LLM记住前序对话的内容。

参考文献:
[1] LangChain 🦜️🔗 中文网,跟着LangChain一起学LLM/GPT开发:https://www.langchain.com.cn/
[2] LangChain中文网 - LangChain 是一个用于开发由语言模型驱动的应用程序的框架:http://www.cnlangchain.com/

  • 4
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

von Neumann

您的赞赏是我创作最大的动力~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值