Question reformulation with history helps make follow-up questions clearer by using past conversation context. It improves understanding in chat or assistant apps.
0
0
Question reformulation with history in LangChain
Introduction
When building a chatbot that remembers previous questions and answers.
When you want to turn short follow-up questions into full, clear questions.
When handling multi-turn conversations where context matters.
When improving user experience by avoiding repeated clarifications.
Syntax
LangChain
from langchain.chains import ConversationChain from langchain.llms import OpenAI conversation = ConversationChain(llm=OpenAI()) response = conversation.predict(input="Your question here")
Use ConversationChain to keep track of conversation history automatically.
The 'predict' method reformulates or answers questions using past context.
Examples
Asks a clear question without prior context.
LangChain
response = conversation.predict(input="Who is the president of the USA?")
Follow-up question that uses history to understand 'he' refers to the president.
LangChain
response = conversation.predict(input="Where was he born?")
Sample Program
This example shows how LangChain keeps track of conversation history. The second question 'Where was he born?' is understood using the answer to the first question.
LangChain
from langchain.chains import ConversationChain from langchain.llms import OpenAI # Initialize conversation with OpenAI model conversation = ConversationChain(llm=OpenAI()) # First question q1 = "Who is the president of the USA?" answer1 = conversation.predict(input=q1) # Follow-up question that depends on previous answer q2 = "Where was he born?" answer2 = conversation.predict(input=q2) print(f"Q1: {q1}\nA1: {answer1}\n") print(f"Q2: {q2}\nA2: {answer2}")
OutputSuccess
Important Notes
Make sure your OpenAI API key is set in your environment to use the OpenAI LLM.
ConversationChain automatically manages history, so you don't need to handle it manually.
Reformulated questions become clearer and more complete using past conversation context.
Summary
Question reformulation with history helps chatbots understand follow-up questions better.
LangChain's ConversationChain manages conversation history automatically.
This improves user experience by making conversations more natural and clear.