当你与那些语言模型进行交互的时候,他们不会记得你之前和他进行的交流内容,这在我们构建一些应用程序(如聊天机器人)的时候,是一个很大的问题 -- 显得不够智能!因此,在本节中我们将介绍 LangChain 中的储存模块,即如何将先前的对话嵌入到语言模型中的,使其具有连续对话的能力。
当使用 LangChain 中的储存(Memory)模块时,它可以帮助保存和管理历史聊天消息,以及构建关于特定实体的知识。这些组件可以跨多轮对话储存信息,并允许在对话期间跟踪特定信息和上下文。
LangChain 提供了多种储存类型。其中,缓冲区储存允许保留最近的聊天消息,摘要储存则提供了对整个对话的摘要。实体储存 则允许在多轮对话中保留有关特定实体的信息。这些记忆组件都是模块化的,可与其他组件组合使用,从而增强机器人的对话管理能力。储存模块可以通过简单的API调用来访问和更新,允许开发人员更轻松地实现对话历史记录的管理和维护。
此次课程主要介绍其中四种储存模块,其他模块可查看文档学习。
- 对话缓存储存 (ConversationBufferMemory)
- 对话缓存窗口储存 (ConversationBufferWindowMemory)
- 对话令牌缓存储存 (ConversationTokenBufferMemory)
- 对话摘要缓存储存 (ConversationSummaryBufferMemory)
在LangChain中,储存 指的是大语言模型(LLM)的短期记忆。为什么是短期记忆?那是因为LLM训练好之后 (获得了一些长期记忆),它的参数便不会因为用户的输入而发生改变。当用户与训练好的LLM进行对话时,LLM会暂时记住用户的输入和它已经生成的输出,以便预测之后的输出,而模型输出完毕后,它便会“遗忘”之前用户的输入和它的输出。因此,之前的这些信息只能称作为LLM的短期记忆。
为了延长LLM短期记忆的保留时间,则需要借助一些外部储存方式来进行记忆,以便在用户与LLM对话中,LLM能够尽可能的知道用户与它所进行的历史对话信息。
import os
import openai
from dotenv import find_dotenv, load_dotenv
# 读取本地/项目的环境变量。
# find_dotenv()寻找并定位.env文件的路径
# load_dotenv()读取该.env文件,并将其中的环境变量加载到当前的运行环境中
# 如果你设置的是全局的环境变量,这行代码则没有任何作用。
_ = load_dotenv(find_dotenv())
# 获取环境变量 OPENAI_API_KEY
openai.api_key = os.environ["OPENAI_API_KEY"]
二、对话缓存储存¶
2.1 英文版¶
2.1.1 初始化对话模型¶
from langchain.chains.conversation.base import ConversationChain
from langchain_community.chat_models import ChatOpenAI
from langchain.memory import ConversationBufferMemory
# 这里我们将参数temperature设置为0.0,从而减少生成答案的随机性。
# 如果你想要每次得到不一样的有新意的答案,可以尝试增大该参数。
llm = ChatOpenAI(temperature=0.0)
memory = ConversationBufferMemory()
# 新建一个 ConversationChain Class 实例
# verbose参数设置为True时,程序会输出更详细的信息,以提供更多的调试或运行时信息。
# 相反,当将verbose参数设置为False时,程序会以更简洁的方式运行,只输出关键的信息。
conversation = ConversationChain(llm=llm, memory = memory, verbose=True )
/Users/lta/anaconda3/envs/cookbook/lib/python3.10/site-packages/langchain_core/_api/deprecation.py:119: LangChainDeprecationWarning: The class `ChatOpenAI` was deprecated in LangChain 0.0.10 and will be removed in 0.3.0. An updated version of the class exists in the langchain-openai package and should be used instead. To use it run `pip install -U langchain-openai` and import as `from langchain_openai import ChatOpenAI`. warn_deprecated(
2.1.2 第一轮对话¶
当我们运行预测(predict)时,生成了一些提示,如下所见,他说“以下是人类和AI之间友好的对话,AI健谈“等等,这实际上是LangChain生成的提示,以使系统进行希望和友好的对话,并且必须保存对话,并提示了当前已完成的模型链。
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. How can I assist you today?"
2.1.3 第二轮对话¶
当我们进行第二轮对话时,它会保留上面的提示
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. How can I assist you today? Human: What is 1+1? AI: > Finished chain.
'1 + 1 equals 2. Is there anything else you would like to know?'
2.1.4 第三轮对话¶
为了验证他是否记忆了前面的对话内容,我们让他回答前面已经说过的内容(我的名字),可以看到他确实输出了正确的名字,因此这个对话链随着往下进行会越来越长
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. How can I assist you today? Human: What is 1+1? AI: 1 + 1 equals 2. Is there anything else you would like to know? Human: What is my name? AI: > Finished chain.
'Your name is Andrew.'
2.1.5 查看储存缓存¶
储存缓存(memory.buffer) 储存了当前为止所有的对话信息
print(memory.buffer)
Human: Hi, my name is Andrew AI: Hello Andrew! It's nice to meet you. How can I assist you today? Human: What is 1+1? AI: 1 + 1 equals 2. Is there anything else you would like to know? Human: What is my name? AI: Your name is Andrew.
也可以通过memory.load_memory_variables({})打印缓存中的历史消息。这里的{}是一个空字典,有一些更高级的功能,使用户可以使用更复杂的输入,但我们不会在这个短期课程中讨论它们,所以不要担心为什么这里有一个空的花括号。
print(memory.load_memory_variables({}))
{'history': "Human: Hi, my name is Andrew\nAI: Hello Andrew! It's nice to meet you. How can I assist you today?\nHuman: What is 1+1?\nAI: 1 + 1 equals 2. Is there anything else you would like to know?\nHuman: What is my name?\nAI: Your name is Andrew."}
2.1.6 直接添加内容到储存缓存¶
memory = ConversationBufferMemory() # 新建一个空的对话缓存记忆
memory.save_context({"input": "Hi"}, {"output": "What's up"}) # 向缓存区添加指定对话的输入输出
print(memory.buffer) # 查看缓存区结果
Human: Hi AI: What's up
print(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"}
2.2 中文版¶
2.1.1 初始化对话模型¶
from langchain.chains.conversation.base import ConversationChain
from langchain_community.chat_models import ChatOpenAI
from langchain.memory import ConversationBufferMemory
llm = ChatOpenAI(temperature=0.0)
memory = ConversationBufferMemory()
conversation = ConversationChain(llm=llm, memory = memory, verbose=True )
2.1.2 第一轮对话¶
conversation.predict(input="你好, 我叫皮皮鲁")
> 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: 你好, 我叫皮皮鲁 AI: > Finished chain.
' 你好皮皮鲁!我是一个人工智能助手,很高兴认识你。你有什么问题想问我吗?'
2.1.3 第二轮对话¶
conversation.predict(input="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: 你好, 我叫皮皮鲁 AI: 你好皮皮鲁!我是一个人工智能助手,很高兴认识你。你有什么问题想问我吗? Human: 1+1等于多少? AI: > Finished chain.
'1加1等于2。这是一个基本的数学问题,答案是2。你还有其他问题吗?我可以帮助你解答。'
2.1.4 第三轮对话¶
conversation.predict(input="我叫什么名字?")
> 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: 你好, 我叫皮皮鲁 AI: 你好皮皮鲁!我是一个人工智能助手,很高兴认识你。你有什么问题想问我吗? Human: 1+1等于多少? AI: 1加1等于2。这是一个基本的数学问题,答案是2。你还有其他问题吗?我可以帮助你解答。 Human: 我叫什么名字? AI: > Finished chain.
'抱歉,我不知道你的名字。你可以告诉我吗?我会记住的。'
2.1.5 查看储存缓存¶
print(memory.buffer)
Human: 你好, 我叫皮皮鲁 AI: 你好皮皮鲁!我是一个人工智能助手,很高兴认识你。你有什么问题想问我吗? Human: 1+1等于多少? AI: 1加1等于2。这是一个基本的数学问题,答案是2。你还有其他问题吗?我可以帮助你解答。 Human: 我叫什么名字? AI: 抱歉,我不知道你的名字。你可以告诉我吗?我会记住的。
print(memory.buffer)
Human: 你好, 我叫皮皮鲁 AI: 你好皮皮鲁!我是一个人工智能助手,很高兴认识你。你有什么问题想问我吗? Human: 1+1等于多少? AI: 1加1等于2。这是一个基本的数学问题,答案是2。你还有其他问题吗?我可以帮助你解答。 Human: 我叫什么名字? AI: 抱歉,我不知道你的名字。你可以告诉我吗?我会记住的。
print(memory.load_memory_variables({}))
{'history': 'Human: 你好, 我叫皮皮鲁\nAI: 你好皮皮鲁!我是一个人工智能助手,很高兴认识你。你有什么问题想问我吗?\nHuman: 1+1等于多少?\nAI: 1加1等于2。这是一个基本的数学问题,答案是2。你还有其他问题吗?我可以帮助你解答。\nHuman: 我叫什么名字?\nAI: 抱歉,我不知道你的名字。你可以告诉我吗?我会记住的。'}
memory.load_memory_variables({})
{'history': 'Human: 你好, 我叫皮皮鲁\nAI: 你好皮皮鲁!我是一个人工智能助手,很高兴认识你。你有什么问题想问我吗?\nHuman: 1+1等于多少?\nAI: 1加1等于2。这是一个基本的数学问题,答案是2。你还有其他问题吗?我可以帮助你解答。\nHuman: 我叫什么名字?\nAI: 抱歉,我不知道你的名字。你可以告诉我吗?我会记住的。'}
2.1.6 直接添加内容到储存缓存¶
memory = ConversationBufferMemory()
memory.save_context({"input": "你好,我叫皮皮鲁"}, {"output": "你好啊,我叫鲁西西"})
memory.load_memory_variables({})
{'history': 'Human: 你好,我叫皮皮鲁\nAI: 你好啊,我叫鲁西西'}
memory.save_context({"input": "Not much, just hanging"}, {"output": "Cool"})
memory.load_memory_variables({})
{'history': 'Human: 你好,我叫皮皮鲁\nAI: 你好啊,我叫鲁西西\nHuman: Not much, just hanging\nAI: Cool'}
memory.save_context({"input": "很高兴和你成为朋友!"}, {"output": "是的,让我们一起去冒险吧!"})
memory.load_memory_variables({})
{'history': 'Human: 你好,我叫皮皮鲁\nAI: 你好啊,我叫鲁西西\nHuman: Not much, just hanging\nAI: Cool\nHuman: 很高兴和你成为朋友!\nAI: 是的,让我们一起去冒险吧!'}
2.3 总结¶
当我们在使用大型语言模型进行聊天对话时,大型语言模型本身实际上是无状态的。语言模型本身并不记得到目前为止的历史对话。每次调用API结点都是独立的。储存(Memory)可以储存到目前为止的所有术语或对话,并将其输入或附加上下文到LLM中用于生成输出。如此看起来就好像它在进行下一轮对话的时候,记得之前说过什么。
三、对话缓存窗口储存¶
随着对话变得越来越长,所需的内存量也变得非常长。将大量的tokens发送到LLM的成本,也会变得更加昂贵,这也就是为什么API的调用费用,通常是基于它需要处理的tokens数量而收费的。
针对以上问题,LangChain也提供了几种方便的储存方式来保存历史对话。其中,对话缓存窗口储存只保留一个窗口大小的对话。它只使用最近的n次交互。这可以用于保持最近交互的滑动窗口,以便缓冲区不会过大
3.1 英文版¶
3.1.1 添加两轮对话到窗口储存¶
from langchain.memory import ConversationBufferWindowMemory
# k 为窗口参数,k=1表明只保留一个对话记忆
memory = ConversationBufferWindowMemory(k=1)
# 向memory添加两轮对话
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'}
3.1.2 在对话链中应用窗口储存¶
llm = ChatOpenAI(temperature=0.0)
memory = ConversationBufferWindowMemory(k=1)
conversation = ConversationChain(llm=llm, memory=memory, verbose=False )
注意此处!由于这里用的是一个窗口的记忆,因此只能保存一轮的历史消息,因此AI并不能知道你第一轮对话中提到的名字,他最多只能记住上一轮(第二轮)的对话信息
conversation.predict(input="Hi, my name is Andrew")
"Hello Andrew! It's nice to meet you. How can I assist you today?"
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 personal information such as your name. Is there anything else you would like to ask?"
3.2 中文版¶
3.1.1 添加两轮对话到窗口储存¶
from langchain.memory import ConversationBufferWindowMemory
# k=1表明只保留一个对话记忆
memory = ConversationBufferWindowMemory(k=1)
memory.save_context({"input": "你好,我叫皮皮鲁"}, {"output": "你好啊,我叫鲁西西"})
memory.save_context({"input": "很高兴和你成为朋友!"}, {"output": "是的,让我们一起去冒险吧!"})
memory.load_memory_variables({})
{'history': 'Human: 很高兴和你成为朋友!\nAI: 是的,让我们一起去冒险吧!'}
3.1.2 在对话链中应用窗口储存¶
llm = ChatOpenAI(temperature=0.0)
memory = ConversationBufferWindowMemory(k=1)
conversation = ConversationChain(llm=llm, memory=memory, verbose=False )
print(conversation.predict(input="你好, 我叫皮皮鲁"))
print(conversation.predict(input="1+1等于多少?"))
print(conversation.predict(input="我叫什么名字?"))
你好,皮皮鲁!很高兴认识你。我是一个人工智能助手,可以回答你的问题或者和你聊天。有什么我可以帮助你的吗? 1加1等于2。这是一个基本的数学问题,答案是2。如果你有任何其他数学问题,都可以问我哦! 抱歉,我不知道你的名字。我只是一个AI程序,无法获取你的个人信息。如果你有其他问题,我会尽力回答的哦!
四、对话token缓存储存¶
使用对话token缓存记忆,内存将限制保存的token数量。如果token数量超出指定数目,它会切掉这个对话的早期部分 以保留与最近的交流相对应的token数量,但不超过token限制。
from langchain.memory import ConversationTokenBufferMemory
4.1 英文版¶
添加对话到Token缓存储存,限制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!'}
可以看到前面超出的的token已经被舍弃了!!!
4.2 中文版¶
memory = ConversationTokenBufferMemory(llm=llm, max_token_limit=30)
memory.save_context({"input": "朝辞白帝彩云间,"}, {"output": "千里江陵一日还。"})
memory.save_context({"input": "两岸猿声啼不住,"}, {"output": "轻舟已过万重山。"})
memory.load_memory_variables({})
{'history': 'AI: 轻舟已过万重山。'}
4.3 补充¶
五、对话摘要缓存储存¶
对话摘要缓存储存,使用LLM编写到目前为止历史对话的摘要,并将其保存
from langchain.memory import ConversationSummaryBufferMemory
5.1 英文版¶
5.1.1 使用对话摘要缓存储存¶
创建一个长字符串,其中包含某人的日程安排
# 创建一个长字符串
schedule = "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."
# 使用对话摘要缓存记忆
llm = ChatOpenAI(temperature=0.0)
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}"}
)
print(memory.load_memory_variables({})['history'])
System: The human and AI exchange greetings and discuss the day's schedule, including a meeting with the product team, work on the LangChain project, and a lunch meeting with a customer interested in AI. The AI emphasizes the power of LangChain as a tool.
5.1.2 基于对话摘要缓存储存的对话链¶
基于上面的对话摘要缓存储存,新建一个对话链
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 exchange greetings and discuss the day's schedule, including a meeting with the product team, work on the LangChain project, and a lunch meeting with a customer interested in AI. The AI emphasizes the power of LangChain as a tool. Human: What would be a good demo to show? AI: > Finished chain.
'A good demo to show would be a live demonstration of how LangChain can accurately translate complex technical documents from one language to another in real-time. This would showcase the speed, accuracy, and efficiency of the language processing capabilities of LangChain. Additionally, demonstrating how LangChain can seamlessly integrate with other AI tools and platforms would highlight its versatility and compatibility with existing systems.'
print(memory.load_memory_variables({})['history'])
System: The human and AI exchange greetings and discuss the day's schedule, including a meeting with the product team, work on the LangChain project, and a lunch meeting with a customer interested in AI. The AI emphasizes the power of LangChain as a tool. Human: What would be a good demo to show? AI: A good demo to show would be a live demonstration of how LangChain can accurately translate complex technical documents from one language to another in real-time. This would showcase the speed, accuracy, and efficiency of the language processing capabilities of LangChain. Additionally, demonstrating how LangChain can seamlessly integrate with other AI tools and platforms would highlight its versatility and compatibility with existing systems.
5.2 中文版¶
5.2.1 使用对话摘要缓存储存¶
创建一个长字符串,其中包含某人的日程安排
# 创建一个长字符串
schedule = "在八点你和你的产品团队有一个会议。 \
你需要做一个PPT。 \
上午9点到12点你需要忙于LangChain。\
Langchain是一个有用的工具,因此你的项目进展的非常快。\
中午,在意大利餐厅与一位开车来的顾客共进午餐 \
走了一个多小时的路程与你见面,只为了解最新的 AI。 \
确保你带了笔记本电脑可以展示最新的 LLM 样例."
llm = ChatOpenAI(temperature=0.0)
memory = ConversationSummaryBufferMemory(llm=llm, max_token_limit=100)
memory.save_context({"input": "你好,我叫皮皮鲁"}, {"output": "你好啊,我叫鲁西西"})
memory.save_context({"input": "很高兴和你成为朋友!"}, {"output": "是的,让我们一起去冒险吧!"})
memory.save_context({"input": "今天的日程安排是什么?"}, {"output": f"{schedule}"})
print(memory.load_memory_variables({})['history'])
System: The human and AI introduce themselves in Chinese and become friends. They plan their schedule for the day, including a meeting with the product team, working on LangChain, and having lunch with a customer interested in AI. The AI emphasizes the importance of being prepared to showcase the latest LLM examples.
5.1.2 基于对话摘要缓存储存的对话链¶
基于上面的对话摘要缓存储存,新建一个对话链
conversation = ConversationChain(llm=llm, memory=memory, verbose=True)
conversation.predict(input="展示什么样的样例最好呢?")
> 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 introduce themselves in Chinese and become friends. They plan their schedule for the day, including a meeting with the product team, working on LangChain, and having lunch with a customer interested in AI. The AI emphasizes the importance of being prepared to showcase the latest LLM examples. Human: 展示什么样的样例最好呢? AI: > Finished chain.
'最好展示一些具有创新性和实用性的语言模型样例,比如可以展示LangChain在不同语言之间的翻译效果,或者展示其在文本生成和对话系统方面的应用。这样可以让客户更直观地了解LangChain的潜力和优势。'
memory.load_memory_variables({}) # 摘要记录更新了
{'history': 'System: The human and AI introduce themselves in Chinese and become friends. They plan their schedule for the day, including a meeting with the product team, working on LangChain, and having lunch with a customer interested in AI. The AI emphasizes the importance of being prepared to showcase the latest LLM examples. The human asks what kind of examples would be best to showcase.\nAI: 最好展示一些具有创新性和实用性的语言模型样例,比如可以展示LangChain在不同语言之间的翻译效果,或者展示其在文本生成和对话系统方面的应用。这样可以让客户更直观地了解LangChain的潜力和优势。'}