当前位置: 首页 > news >正文

LangChain学习之四种Memory模式使用

1. 学习背景

在LangChain for LLM应用程序开发中课程中,学习了LangChain框架扩展应用程序开发中语言模型的用例和功能的基本技能,遂做整理为后面的应用做准备。视频地址:基于LangChain的大语言模型应用开发+构建和评估。

2. 四种memory模式

本实验基于jupyternotebook进行。

2.1 ConversationBufferMemory

import warnings
warnings.filterwarnings('ignore')
from langchain.chat_models import ChatOpenAI
from langchain.chains import ConversationChain
from langchain.memory import ConversationBufferMemoryllm = ChatOpenAI(api_key = "XXXX",base_url = "XXXX",temperature=0.0
)memory = ConversationBufferMemory()
conversation = ConversationChain(llm=llm, memory = memory,verbose=True #设置为True可以看到模型的具体思考过程
)
conversation.predict(input="Hi, my name is Andrew")

输出如下:

> Entering new ConversationChain 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, my name is Andrew
AI:> Finished chain.
"Hello Andrew! It's nice to meet you. My name is AI and I'm here to assist you with any questions or tasks you have. How can I help you today?"

继续测试

conversation.predict(input="What is 1+1?")

输出如下:

> Entering new ConversationChain 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, my name is Andrew
AI: Hello Andrew! It's nice to meet you. My name is AI and I'm here to assist you with any questions or tasks you have. How can I help you today?
Human: What is 1+1?
AI:> Finished chain.
'1+1 equals 2. This is a basic mathematical operation that can be solved by adding the two numbers together. Is there anything else I can assist you with?'

再次输入之前的问题

conversation.predict(input="What is my name?")

输出如下:

> Entering new ConversationChain 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, my name is Andrew
AI: Hello Andrew! It's nice to meet you. My name is AI and I'm here to assist you with any questions or tasks you have. How can I help you today?
Human: What is 1+1?
AI: 1+1 equals 2. This is a basic mathematical operation that can be solved by adding the two numbers together. Is there anything else I can assist you with?
Human: What is my name?
AI:> Finished chain.
'Your name is Andrew.'

我们可以清楚的看到每次LLM所记忆的内容,看看buffer有什么

print(memory.buffer)

输出如下:

Human: Hi, my name is Andrew
AI: Hello Andrew! It's nice to meet you. My name is AI and I'm here to assist you with any questions or tasks you have. How can I help you today?
Human: What is 1+1?
AI: 1+1 equals 2. This is a basic mathematical operation that can be solved by adding the two numbers together. Is there anything else I can assist you with?
Human: What is my name?
AI: Your name is Andrew.
memory.load_memory_variables({})

输出如下:

{'history': "Human: Hi, my name is Andrew\nAI: Hello Andrew! It's nice to meet you. My name is AI and I'm here to assist you with any questions or tasks you have. How can I help you today?\nHuman: What is 1+1?\nAI: 1+1 equals 2. This is a basic mathematical operation that can be solved by adding the two numbers together. Is there anything else I can assist you with?\nHuman: What is my name?\nAI: Your name is Andrew."}

接下来,我们尝试一下对ConversationBufferMemory的操作。

# 重新初始化memory
memory = ConversationBufferMemory()
memory.save_context({"input": "Hi"}, {"output": "What's up"})
print(memory.buffer)

输出如下:

Human: Hi
AI: What's up

以变量形式读取

memory.load_memory_variables({})

输出如下:

{'history': "Human: Hi\nAI: What's up"}

再往里存入内容

memory.save_context({"input": "Not much, just hanging"}, {"output": "Cool"})
memory.load_memory_variables({})

输出如下:

{'history': "Human: Hi\nAI: What's up\nHuman: Not much, just hanging\nAI: Cool"}

可以看到把所有的变量读取出来了。一般情况下,ConversationBufferMemory会将所有的信息读出。

2.2 ConversationBufferWindowMemory

from langchain.memory import ConversationBufferWindowMemory# 设置对话缓冲窗口的轮数为1
memory = ConversationBufferWindowMemory(k = 1)
memory.save_context({"input": "Hi"},{"output": "What's up"})
memory.save_context({"input": "Not much, just hanging"},{"output": "Cool"})
memory.load_memory_variables({})

输出如下:

{'history': 'Human: Not much, just hanging\nAI: Cool'}

可以看到输出的轮次只有一次对话长度。我们尝试用人机对话进行测试。

memory = ConversationBufferWindowMemory(k = 1)
conversation = ConversationChain(llm=llm, memory = memory,verbose= False
)conversation.predict(input="Hi, my name is Andrew")

输出如下:

"Hello Andrew! It's nice to meet you. My name is AI. I have access to a vast amount of information, so feel free to ask me anything you'd like to know!"

再进行对话

conversation.predict(input="What is 1+1?")

输出如下:

'1 + 1 equals 2. Is there anything else you would like to know?'

再进行对话

conversation.predict(input="What is my name?")

输出如下:

"I'm sorry, I do not have access to that information. Is there anything else you would like to ask?"

可以看到,设置对话窗口长度为1的时候,LLM的memory中只保留最后一轮的对话。

2.3 ConversationTokenBufferMemory

首先需要安装包,因为ConversationTokenBufferMemory会调用tiktoken包相关内容。

!pip install tiktoken
from langchain.memory import ConversationTokenBufferMemory# 设置对话过程中的记忆的长度最大为30个token
memory = ConversationTokenBufferMemory(llm=llm, max_token_limit=30)
memory.save_context({"input": "AI is what?!"},{"output": "Amazing!"})
memory.save_context({"input": "Backpropagation is what?"},{"output": "Beautiful!"})
memory.save_context({"input": "Chatbots are what?"}, {"output": "Charming!"})
memory.load_memory_variables({})

输出如下:

{'history': 'AI: Beautiful!\nHuman: Chatbots are what?\nAI: Charming!'}

2.4 ConversationSummaryBufferMemory

from langchain.memory import ConversationSummaryBufferMemoryschedule = "There is a meeting at 8am with your product team. \
You will need your powerpoint presentation prepared. \
9am-12pm have time to work on your LangChain \
project which will go quickly because Langchain is such a powerful tool. \
At Noon, lunch at the italian resturant with a customer who is driving \
from over an hour away to meet you to understand the latest in AI. \
Be sure to bring your laptop to show the latest LLM demo."memory = ConversationSummaryBufferMemory(llm=llm, max_token_limit=100)
memory.save_context({"input": "Hello"}, {"output": "What's up"})
memory.save_context({"input": "Not much, just hanging"},{"output": "Cool"})
memory.save_context({"input": "What is on the schedule today?"}, {"output": f"{schedule}"})
memory.load_memory_variables({})

输出如下:

{'history': "System: The human and AI have a brief exchange of greetings, and the AI informs the human of the day's schedule, including a meeting, work time on a project, and a lunch appointment with a customer interested in AI technology."}

可以看到,由于设置了最大token的长度为100,使用的是SummaryBuffer,因此LLM会对内存中的段落信息进行摘要存储。再继续对话,打开verbose查看chain细节。

conversation = ConversationChain(llm = llm, memory = memory,verbose = True
)
conversation.predict(input="What would be a good demo to show?")

输出如下:

> Entering new ConversationChain 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:
System: The human and AI have a brief exchange of greetings, and the AI informs the human of the day's schedule, including a meeting, work time on a project, and a lunch appointment with a customer interested in AI technology.
Human: What would be a good demo to show?
AI:> Finished chain.
"I suggest showcasing our AI's natural language processing capabilities, as well as its ability to analyze and interpret large datasets for actionable insights. We could also demonstrate its real-time decision-making capabilities and its integration with various platforms and applications. Additionally, we could show its ability to automate repetitive tasks and streamline workflow processes."

尝试读取memory中的信息。

memory.load_memory_variables({})

输出如下:

{'history': "System: The human and AI have a brief exchange of greetings, and the AI informs the human of the day's schedule, including a meeting, work time on a project, and a lunch appointment with a customer interested in AI technology.\nHuman: What would be a good demo to show?\nAI: I suggest showcasing our AI's natural language processing capabilities, as well as its ability to analyze and interpret large datasets for actionable insights. We could also demonstrate its real-time decision-making capabilities and its integration with various platforms and applications. Additionally, we could show its ability to automate repetitive tasks and streamline workflow processes."}

3. 思考

在构建应用时,如果token开销比较花钱,可以选择合适的对话memory进行存储关键信息。

相关文章:

  • 基于springboot+vue的医院信息管理系统
  • 计算机毕业设计 | 基于Koa+vue的高校宿舍管理系统宿舍可视化系统
  • Github上一款开源、简洁、强大的任务管理工具:Condution
  • 谨以此文章记录我的蓝桥杯备赛过程
  • Python与Scratch:深入探索两者之间的区别
  • 媳妇面试了一家公司,期望月薪20K,对方没多问就答应了,只要求3天内到岗,可我总觉得哪里不对劲。
  • 【数据库系统概论】函数依赖与范式
  • Jetpack架构组件_4. 数据绑定库页面传递数据
  • ChatGPT成知名度最高生成式AI产品,使用频率却不高
  • Java项目:94 springboot大学城水电管理系统
  • (7)svelte 教程: Props(属性)
  • 【Linux系统编程】冯诺依曼体系、操作系统、进程的认识
  • 视频汇聚EasyCVR视频监控云平台对接GA/T 1400视图库对象和对象集合XMLSchema描述
  • selenium中, quit 和close的区别
  • 前端作用域冲突之快照沙箱和代理沙箱
  • 时间复杂度分析经典问题——最大子序列和
  • 【面试系列】之二:关于js原型
  • export和import的用法总结
  • Java方法详解
  • nodejs:开发并发布一个nodejs包
  • node和express搭建代理服务器(源码)
  • node学习系列之简单文件上传
  • Spring核心 Bean的高级装配
  • SSH 免密登录
  • STAR法则
  • Webpack4 学习笔记 - 01:webpack的安装和简单配置
  • yii2权限控制rbac之rule详细讲解
  • 初探 Vue 生命周期和钩子函数
  • 回流、重绘及其优化
  • 基于Android乐音识别(2)
  • 基于游标的分页接口实现
  • 警报:线上事故之CountDownLatch的威力
  • 聊聊hikari连接池的leakDetectionThreshold
  • 排序算法学习笔记
  • 时间复杂度与空间复杂度分析
  • 手机端车牌号码键盘的vue组件
  • 微信端页面使用-webkit-box和绝对定位时,元素上移的问题
  • 3月27日云栖精选夜读 | 从 “城市大脑”实践,瞭望未来城市源起 ...
  • linux 淘宝开源监控工具tsar
  • 回归生活:清理微信公众号
  • (4) PIVOT 和 UPIVOT 的使用
  • (6)设计一个TimeMap
  • (CVPRW,2024)可学习的提示:遥感领域小样本语义分割
  • (苍穹外卖)day03菜品管理
  • (带教程)商业版SEO关键词按天计费系统:关键词排名优化、代理服务、手机自适应及搭建教程
  • (二)学习JVM —— 垃圾回收机制
  • (附源码)ssm航空客运订票系统 毕业设计 141612
  • (六)库存超卖案例实战——使用mysql分布式锁解决“超卖”问题
  • (排序详解之 堆排序)
  • (转)德国人的记事本
  • .Family_物联网
  • .L0CK3D来袭:如何保护您的数据免受致命攻击
  • .net 4.0 A potentially dangerous Request.Form value was detected from the client 的解决方案
  • .Net 6.0 Windows平台如何判断当前电脑是否联网
  • .NET/C# 异常处理:写一个空的 try 块代码,而把重要代码写到 finally 中(Constrained Execution Regions)