AI / LangGraph LangChain Interview questions
How do you implement a ConversationChain?
A ConversationChain maintains multi-turn dialogue by storing conversation history and injecting it into each new prompt invocation. The legacy approach uses ConversationChain with a memory object; the LCEL approach manages history explicitly in the chain state using MessagesPlaceholder.
LCEL approach (recommended):
from langchain_openai import ChatOpenAI from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder from langchain_core.messages import HumanMessage, AIMessage prompt = ChatPromptTemplate.from_messages([ ("system", "You are a helpful assistant."), MessagesPlaceholder(variable_name="history"), ("human", "{input}"), ]) chain = prompt | ChatOpenAI() # Manually manage history history = [] def chat(user_input): response = chain.invoke({"input": user_input, "history": history}) history.append(HumanMessage(content=user_input)) history.append(AIMessage(content=response.content)) return response.content print(chat("My name is Alice.")) print(chat("What is my name?")) # correctly recalls "Alice"
For server-side multi-user conversations, pair this with LangGraph's checkpointing or RunnableWithMessageHistory which wraps the chain and automatically loads/saves history per session ID from a configurable store.
More Related questions...