如何向LLMChain添加内存
本笔记本介绍了如何在LLMChain中使用Memory类。在本教程中,我们将添加ConversationBufferMemory类,但实际上可以是任何内存类。
from langchain.chains import LLMChain
from langchain.llms import OpenAI
from langchain.memory import ConversationBufferMemory
from langchain.prompts import PromptTemplate
API参考:
- LLMChain 来自
langchain.chains
- OpenAI 来自
langchain.llms
- ConversationBufferMemory 来自
langchain.memory
- PromptTemplate 来自
langchain.prompts
最重要的一步是正确设置提示。在下面的提示中,我们有两个输入键:一个用于实际输入,另一个用于来自Memory类的输入。重要的是,确保PromptTemplate和ConversationBufferMemory中的键匹配(chat_history
)。
template = """You are a chatbot having a conversation with a human.
{chat_history}
Human: {human_input}
Chatbot:"""
prompt = PromptTemplate(
input_variables=["chat_history", "human_input"], template=template
)
memory = ConversationBufferMemory(memory_key="chat_history")
llm = OpenAI()
llm_chain = LLMChain(
llm=llm,
prompt=prompt,
verbose=True,
memory=memory,
)
llm_chain.predict(human_input="Hi there my friend")
> 进入新的LLMChain链...
> 格式化后的提示:
> 你是一个与人类对话的聊天机器人。
> 人类:嗨,朋友
> 聊天机器人:
> 完成链。
'嗨,你好!我今天能帮你什么忙吗?'
llm_chain.predict(human_input="Not too bad - how are you?")
> 进入新的LLMChain链...
> 格式化后的提示:
> 你是一个与人类对话的聊天机器人。
> 人类:嗨,朋友
> AI:嗨,你好!我今天能帮你什么忙吗?
> 人类:还好,你呢?
> 聊天机器人:
> 完成链。
'我过得很好,谢谢你的关心!你过得怎么样?'
向基于聊天模型的LLMChain添加内存
上述方法适用于完成式的LLM,但如果您使用的是聊天模型,使用结构化的聊天消息可能会获得更好的性能。以下是一个示例。
from langchain.chat_models import ChatOpenAI
from langchain.schema import SystemMessage
from langchain.prompts import ChatPromptTemplate, HumanMessagePromptTemplate, MessagesPlaceholder
API参考:
- ChatOpenAI 来自
langchain.chat_models
- SystemMessage 来自
langchain.schema
- ChatPromptTemplate 来自
langchain.prompts
- HumanMessagePromptTemplate 来自
langchain.prompts
- MessagesPlaceholder 来自
langchain.prompts
我们将使用ChatPromptTemplate类来设置聊天提示。
from_messages方法从消息列表(例如SystemMessage、HumanMessage、AIMessage、ChatMessage等)或消息模板(如下面的MessagesPlaceholder)创建ChatPromptTemplate。
以下配置使得内存将被注入到聊天提示的中间位置,即“chat_history”键,并且用户的输入将作为人类/用户消息添加到聊天提示的末尾。
prompt = ChatPromptTemplate.from_messages([
SystemMessage(content="You are a chatbot having a conversation with a human."), # The persistent system prompt
MessagesPlaceholder(variable_name="chat_history"), # Where the memory will be stored.
HumanMessagePromptTemplate.from_template("{human_input}"), # Where the human input will injectd
])
memory = ConversationBufferMemory(memory_key="chat_history", return_messages=True)
llm = ChatOpenAI()
chat_llm_chain = LLMChain(
llm=llm,
prompt=prompt,
verbose=True,
memory=memory,
)
chat_llm_chain.predict(human_input="Hi there my friend")
> 进入新的LLMChain链...
> 格式化后的提示:
> 系统:你是一个与人类对话的聊天机器人。
> 人类:嗨,朋友
> 完成链。
'你好!我今天能帮你什么忙吗,朋友?'
chat_llm_chain.predict(human_input="Not too bad - how are you?")
> 进入新的LLMChain链...
> 格式化后的提示:
> 系统:你是一个与人类对话的聊天机器人。
> 人类:嗨,朋友
> AI:你好!我今天能帮你什么忙吗,朋友?
> 人类:还好,你呢?
> 完成链。
'我是一个AI聊天机器人,所以我没有感觉,但我在这里帮助和与你聊天!你有什么特别想聊的或者我能帮你解答的问题吗?'