如何给 LLM Chain(大语言模型链)添加 Memeory(记忆)#
本章介绍了如何将Memory类与LLMChain一起使用。在本指南的示例中,我们将添加 ConversationBufferMemory 类,当然也可以是任何其他 Memory(记忆)类。
from langchain.memory import ConversationBufferMemory
from langchain import OpenAI, LLMChain, PromptTemplate
最重要的一步是正确设置提示。在下面的提示中,我们有两个输入键:一个是实际输入的键,另一个是来自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_chain = LLMChain(
llm=OpenAI(),
prompt=prompt,
verbose=True,
memory=memory,
)
llm_chain.predict(human_input="Hi there my friend")
> Entering new LLMChain chain...
Prompt after formatting:
You are a chatbot having a conversation with a human.
Human: Hi there my friend
Chatbot:
> Finished LLMChain chain.
' Hi there, how are you doing today?'
llm_chain.predict(human_input="Not too bad - how are you?")
> Entering new LLMChain chain...
Prompt after formatting:
You are a chatbot having a conversation with a human.
Human: Hi there my friend
AI: Hi there, how are you doing today?
Human: Not to bad - how are you?
Chatbot:
> Finished LLMChain chain.
" I'm doing great, thank you for asking!"