pythonintermediate
LangChain Conversation with Memory
Build a stateful chatbot that remembers conversation history using LangChain memory.
pythonPress ⌘/Ctrl + Shift + C to copy
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.
pythonintermediate
LangChain Conversation with Memory
Maintain conversation context across turns using LangChain memory modules.
Best for: Multi-turn chatbots
#ai#langchain
typescriptadvanced
AI Chat Conversation Memory
Manage conversation history with token limits, summarization, and sliding window for LLM chat apps.
Best for: Building chatbot applications with context
#chat#memory
pythonadvanced
LangChain Agent with Persistent Memory
Build an AI agent that persists conversation context across sessions using LangChain memory stores.
Best for: persistent agents
#langchain#agent
pythonbeginner
LangChain Prompt Chain (Python)
Build a simple LLMChain with a prompt template and ChatOpenAI in LangChain.
Best for: prompt chaining
#langchain#openai