Files
langchain/docs/modules/memory/examples/adding_memory.ipynb
T
Harrison Chase 7bec461782 Harrison/memory refactor (#1478)
moves memory to own module, factors out common stuff
2023-03-07 07:59:37 -08:00

4.1 KiB

Adding Memory To an LLMChain

This notebook goes over how to use the Memory class with an LLMChain. For the purposes of this walkthrough, we will add the ConversationBufferMemory class, although this can be any memory class.

In [1]:
from langchain.memory import ConversationBufferMemory
from langchain import OpenAI, LLMChain, PromptTemplate

The most important step is setting up the prompt correctly. In the below prompt, we have two input keys: one for the actual input, another for the input from the Memory class. Importantly, we make sure the keys in the PromptTemplate and the ConversationBufferMemory match up (chat_history).

In [2]:
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")
In [3]:
llm_chain = LLMChain(
    llm=OpenAI(), 
    prompt=prompt, 
    verbose=True, 
    memory=memory,
)
In [4]:
llm_chain.predict(human_input="Hi there my friend")
Out [4]:

> 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?'
In [5]:
llm_chain.predict(human_input="Not to bad - how are you?")
Out [5]:

> 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!"
In [ ]: