mirror of
https://github.com/langchain-ai/langchain.git
synced 2026-10-09 19:35:20 +03:00
4.0 KiB
4.0 KiB
In [1]:
from langchain.chat_models import ChatOpenAI
from langchain.memory import ConversationBufferMemory
from langchain.schema.runnable import RunnableMap
from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder
model = ChatOpenAI()
prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful chatbot"),
MessagesPlaceholder(variable_name="history"),
("human", "{input}")
])In [2]:
memory = ConversationBufferMemory(return_messages=True)In [3]:
memory.load_memory_variables({})Out [3]:
{'history': []}In [4]:
chain = RunnableMap({
"input": lambda x: x["input"],
"memory": memory.load_memory_variables
}) | {
"input": lambda x: x["input"],
"history": lambda x: x["memory"]["history"]
} | prompt | modelIn [5]:
inputs = {"input": "hi im bob"}
response = chain.invoke(inputs)
responseOut [5]:
AIMessage(content='Hello Bob! How can I assist you today?', additional_kwargs={}, example=False)In [6]:
memory.save_context(inputs, {"output": response.content})In [7]:
memory.load_memory_variables({})Out [7]:
{'history': [HumanMessage(content='hi im bob', additional_kwargs={}, example=False),
AIMessage(content='Hello Bob! How can I assist you today?', additional_kwargs={}, example=False)]}In [8]:
inputs = {"input": "whats my name"}
response = chain.invoke(inputs)
responseOut [8]:
AIMessage(content='Your name is Bob.', additional_kwargs={}, example=False)