记忆
使用的工具是COnversation Chain,其使用方式很简单
from langchain.openai import OpenAI
from langchain.chats import ConversationChain
llm = OpenAI(
temperature = .8,
model_name = ...,
)
conv_chain = Conversation_Chain(llm = llm)
print(conv_chain.prompt.template)
# 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:
# {history}
# Human: {input}
# AI:
复制代码
通过这个方法,就为chat构建了基本的环境框架,同时,这个prompt设置了两个参数,一个是过去的历史聊天,另一个是本轮的输入
memory通过ConversationBufferMemory实现
from langchain.openai import OpenAI
from langchan.chains import ConversationChain
from langchain.chains.conversation.memory import ConversationBufferMemory
llm = OpenAI(
temperature = .8,
model_name = ...,
)
conversation = Conversation_Chain(
llm = llm,
memory = ConversationBufferMemory()
)
# 第一天的对话 # 回合1
conversation("我姐姐明天要过生日,我需要一束生日花束。")
print("第一次对话后的记忆:", conversation.memory.buffer)
# 第一次对话后的记忆:
# Human: 我姐姐明天要过生日,我需要一束生日花束。
# AI: 哦,你姐姐明天要过生日,那太棒了!我可以帮你推荐一些生日花束,你想要什么样的?我知道有很多种,比如玫瑰、康乃馨、郁金香等等。
# 回合2
conversation("她喜欢粉色玫瑰,颜色是粉色的。")
print("第二次对话后的记忆:", conversation.memory.buffer)
# 第二次对话后的记忆:
# Human: 我姐姐明天要过生日,我需要一束生日花束。
# AI: 哦,你姐姐明天要过生日,那太棒了!我可以帮你推荐一些生日花束,你想要什么样的?我知道有很多种,比如玫瑰、康乃馨、郁金香等等。
# Human: 她喜欢粉色玫瑰,颜色是粉色的。
# AI: 好的,那我可以推荐一束粉色玫瑰的生日花束给你。你想要多少朵?我可以帮你定制一束,比如说十朵、二十朵或者更多?
复制代码
通过直接存储,可以让llm方便的查找信息,但是输入也会相应变长,且太长的对话会超过模型的token限制而无法被记住。
如果要限制记忆长度,使用ConversationBufferWindowMemory(k = )
conv_chain = Conversation_Chain(
llm = llm,
memory = ConversationBufferWindowMemory(k = 1)
)
复制代码
另一种思路是使用ConversationSummaryMemory,通过将过往信息进行汇总,从而节约长对话时history占用的token
from langchain.chains.conversation.memory import ConversationSummaryMemory
# 初始化对话链
conversation = ConversationChain(
llm=llm,
memory=ConversationSummaryMemory(llm=llm)
)
# {'input': '我姐姐明天要过生日,我需要一束生日花束。',
# 'history': '',
# 'response': ' 我明白,你需要一束生日花束。我可以为你提供一些建议吗?我可以推荐一些花束给你,比如玫瑰,康乃馨,百合,仙客来,郁金香,满天星等等。挑选一束最适合你姐姐的生日花束吧!'}
{'input': '她喜欢粉色玫瑰,颜色是粉色的。',
'history': "\nThe human asked what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good because it will help humans reach their full potential. The human then asked the AI for advice on what type of flower bouquet to get for their sister's birthday, to which the AI provided a variety of suggestions.",
'response': ' 为了为你的姐姐的生日准备一束花,我建议你搭配粉色玫瑰和白色康乃馨。你可以在玫瑰花束中添加一些紫色的满天星,或者添加一些绿叶以增加颜色对比。这将是一束可爱的花束,让你姐姐的生日更加特别。'}
复制代码
缺点是在短对话时,该方法会消耗较多的token
自然而然可以想到将两种进行组合,即ConversationSummaryBufferMemory
from langchain.chains.conversation.memory import ConversationSummaryBufferMemory
# 初始化对话链
conversation = ConversationChain(
llm=llm,
memory=ConversationSummaryBufferMemory(
llm=llm,
max_token_limit=300))
复制代码
当小于这个值,即使用window,否则使用summary