08. Add memory to LCEL Chain

LCEL (Remember Conversation): Add Memory

Shows how to add memory to any chain. You can use the current memory class, but you have to connect it manually.

Copy

from dotenv import load_dotenv

load_dotenv()

Copy

True

Copy

from operator import itemgetter
from langchain.memory import ConversationBufferMemory
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_core.runnables import RunnableLambda, RunnablePassthrough
from langchain_openai import ChatOpenAI


# ChatOpenAI Initialize the model.
model = ChatOpenAI()

# Creates an interactive prompt. This prompt includes system messages, previous conversation history, and user input.
prompt = ChatPromptTemplate.from_messages(
    [
        ("system", "You are a helpful chatbot"),
        MessagesPlaceholder(variable_name="chat_history"),
        ("human", "{input}"),
    ]
)

Memory to store conversation ConversationBufferMemory Create and return_messages parameter True By setting it to, the generated instance returns the message.

  • memory_key Settings: Chain later prompt It is the key to be brought inside. You can change it and use it.

Copy

Check the saved minutes. Since we haven't saved it yet, the dialog is empty.

Copy

Copy

RunnablePassthrough.assign Using chat_history To variable memory.load_memory_variables Assign the result of the function, and from this result chat_history Extract the value corresponding to the key.

Copy

Copy

Copy

Copy

Copy

runnable Start the first conversation on.

  • input : User input conversation is passed.

  • chat_history : Conversation records are passed.

Copy

Copy

Copy

Proceed with the first conversation.

Copy

Copy

Copy

Copy

Copy

Copy

Copy

Ask if you remember your name.

Copy

Copy

Custom ConversationChain implementation example

Copy

Copy

Copy

Copy

Copy

Copy

Copy

Copy

Copy

Copy

Copy

Copy

Copy

Last updated