pythonintermediate

LangChain Conversation with Memory

Build a stateful chatbot that remembers conversation history using LangChain memory.

python
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langchain_community.chat_message_histories import ChatMessageHistory
from langchain_core.runnables.history import RunnableWithMessageHistory

llm = ChatOpenAI(model='gpt-4o-mini')

prompt = ChatPromptTemplate.from_messages([
    ('system', 'You are a helpful assistant.'),
    MessagesPlaceholder(variable_name='history'),
    ('human', '{input}'),
])

store: dict[str, ChatMessageHistory] = {}

def get_session_history(session_id: str) -> ChatMessageHistory:
    if session_id not in store:
        store[session_id] = ChatMessageHistory()
    return store[session_id]

chain = RunnableWithMessageHistory(prompt | llm, get_session_history, input_messages_key='input', history_messages_key='history')

for msg in ['My name is Alice.', 'What is my name?']:
    r = chain.invoke({'input': msg}, config={'configurable': {'session_id': 's1'}})
    print(r.content)

Use Cases

  • stateful chatbots
  • conversation history
  • session management

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.