pythonintermediate
LangChain Conversation with Memory
Maintain conversation context across turns using LangChain memory modules.
pythonPress ⌘/Ctrl + Shift + C to copy
from langchain.chat_models import ChatOpenAI
from langchain.memory import ConversationBufferWindowMemory
from langchain.chains import ConversationChain
from langchain.prompts import PromptTemplate
# Setup LLM + memory
llm = ChatOpenAI(model="gpt-4o", temperature=0.7)
memory = ConversationBufferWindowMemory(
k=10, # Keep last 10 exchanges
return_messages=True
)
# Custom system prompt
template = """You are a helpful coding assistant.
Conversation history:
{history}
Human: {input}
Assistant:"""
prompt = PromptTemplate(
input_variables=["history", "input"],
template=template
)
chain = ConversationChain(
llm=llm,
memory=memory,
prompt=prompt,
verbose=True
)
# Multi-turn conversation
print(chain.predict(input="What is a Python decorator?"))
print(chain.predict(input="Can you show me an example?"))
print(chain.predict(input="How do I make it accept arguments?"))
# Check what's stored in memory
print("\nMemory contents:")
for msg in memory.chat_memory.messages:
print(f" {msg.type}: {msg.content[:80]}...")Use Cases
- Multi-turn chatbots
- Context-aware assistants
- Customer support
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
pythonintermediate
LangChain Conversation with Memory
Build a stateful chatbot that remembers conversation history using LangChain memory.
Best for: stateful chatbots
#langchain#memory
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
Build a RAG Pipeline with LangChain
Implement retrieval-augmented generation using LangChain, embeddings, and a vector store.
Best for: Knowledge base Q&A
#ai#langchain
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