pythonintermediate

LangChain Conversation with Memory

Maintain conversation context across turns using LangChain memory modules.

python
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.