I am trying to develop chatbot where user can upload a pdf and ask questions on it using llm. It is using a langchain framework and here is the code below. Review and fix it for conversation memory since I am not getting output as a chatbot:
def get_conversation_chain(vectorstore):
# Load the model name
model_name = "mistralai/Mistral-7B-Instruct-v0.3"
code
# Ensure you have the correct token set in your environment
token = os.environ['HUGGINGFACEHUB_API_TOKEN'] # Replace with a valid token having 'read' permission
# Download the model and tokenizer
# tokenizer = AutoTokenizer.from_pretrained(model_name, use_auth_token=token)
# Create the LLM instance with repo_id
llm = HuggingFaceHub(
repo_id=model_name, # Specify the repo_id here
model_kwargs={
"temperature": 0.5,
"max_new_tokens": 512
},
huggingfacehub_api_token=token # Pass the token if needed
)
memory = ConversationBufferMemory(
memory_key='chat_history',
return_messages=True
)
conversation_chain = ConversationalRetrievalChain.from_llm(
llm=llm,
retriever=vectorstore.as_retriever(),
memory=memory
)
return conversation_chain
for i, message in enumerate(st.session_state.chat_history):
if i % 2 == 0:
st.write(user_template.replace(
"{{MSG}}", message.content), unsafe_allow_html=True)
else:
st.write(bot_template.replace(
"{{MSG}}", message.content), unsafe_allow_html=True)
def main():
load_dotenv()
st.set_page_config(page_title="Chat with multiple PDFs",
page_icon=":books:")
st.write(css, unsafe_allow_html=True)
code
if "conversation" not in st.session_state:
st.session_state.conversation = None
if "chat_history" not in st.session_state:
st.session_state.chat_history = None
st.header("Chat with multiple PDFs :books:")
user_question = st.text_input("Ask a question about your documents:")
if user_question:
handle_userinput(user_question)
with st.sidebar:
st.subheader("Your documents")
pdf_docs = st.file_uploader(
"Upload your PDFs here and click on 'Process'", accept_multiple_files=True)
if st.button("Process"):
with st.spinner("Processing"):
raw_text = get_pdf_text(pdf_docs)
text_chunks = get_text_chunks(raw_text)
vectorstore = get_vectorstore(text_chunks)
st.session_state.conversation = get_conversation_chain(vectorstore)
Assistant
I've reviewed your code for the PDF chatbot with conversation memory. There are a few issues that need to be fixed to make the conversation memory work properly. Here's the corrected version:
python
User
coversation chain is showing prompt after formatting please only display question from human and answer from assistant
Assistant
To modify your code to only display the human's question and the assistant's answer (without showing the formatted prompt), you need to adjust the handle_userinput function and ensure the conversation chain is configured properly. Here's the updated code:
python
User
this great I also need history of chat
Assistant
To maintain the chat history while only displaying the human's questions and assistant's answers, I'll modify the code to properly track and display the conversation history. Here's the updated solution:
python
def get_conversation_chain(vectorstore):
# Load the model name
model_name = "mistralai/Mistral-7B-Instruct-v0.3"
# Ensure you have the correct token set in your environment
token = os.environ['HUGGINGFACEHUB_API_TOKEN'] # Replace with a valid token having 'read' permission
# Create the LLM instance with repo_id
llm = HuggingFaceHub(
repo_id=model_name,
model_kwargs={
"temperature": 0.5,
"max_new_tokens": 512
},
huggingfacehub_api_token=token
)
memory = ConversationBufferMemory(
memory_key='chat_history',
return_messages=True,
output_key='answer' # Add this to match the output key of the chain
)
conversation_chain = ConversationalRetrievalChain.from_llm(
llm=llm,
retriever=vectorstore.as_retriever(),
memory=memory,
return_source_documents=True,
return_generated_question=True,
verbose=True # Helpful for debugging
)
return conversation_chain
def handle_userinput(user_question):
if st.session_state.conversation is None:
st.warning("Please process your documents first!")
return
response = st.session_state.conversation({'question': user_question})
# Initialize chat_history if it doesn't exist
if 'chat_history' not in st.session_state:
st.session_state.chat_history = []
# Add the user question and bot response to chat history
st.session_state.chat_history.append(("user", user_question))
st.session_state.chat_history.append(("bot", response['answer']))
# Display the entire conversation history
for role, message in st.session_state.chat_history:
if role == "user":
st.write(user_template.replace("{{MSG}}", message), unsafe_allow_html=True)
else:
st.write(bot_template.replace("{{MSG}}", message), unsafe_allow_html=True)
def main():
load_dotenv()
st.set_page_config(page_title="Chat with multiple PDFs", page_icon=":books:")
st.write(css, unsafe_allow_html=True)
# Initialize session state variables
if "conversation" not in st.session_state:
st.session_state.conversation = None
if "chat_history" not in st.session_state:
st.session_state.chat_history = []
st.header("Chat with multiple PDFs :books:")
user_question = st.text_input("Ask a question about your documents:")
if user_question:
handle_userinput(user_question)
with st.sidebar:
st.subheader("Your documents")
pdf_docs = st.file_uploader(
"Upload your PDFs here and click on 'Process'",
accept_multiple_files=True
)
if st.button("Process"):
with st.spinner("Processing"):
# Get pdf text
raw_text = get_pdf_text(pdf_docs)
# Get the text chunks
text_chunks = get_text_chunks(raw_text)
# Create vector store
vectorstore = get_vectorstore(text_chunks)
# Create conversation chain
st.session_state.conversation = get_conversation_chain(vectorstore)
st.session_state.chat_history = [] # Reset chat history when new docs are processed
st.success("Documents processed successfully!")
Key fixes and improvements:
Memory Configuration: Added output_key='answer' to the memory to match the ConversationalRetrievalChain's output structure.
Conversation Chain: Added return_source_documents and return_generated_question parameters to ensure consistent response format.
Chat History Handling:
Changed the chat history storage format to store tuples of (role, message) for better tracking
Initialize chat_history as an empty list if it doesn't exist
Reset chat history when new documents are processed
Error Handling: Added a check for unprocessed documents before attempting to answer questions.
User Feedback: Added a success message when documents are processed.
Session State Initialization: Ensured chat_history is initialized as an empty list rather than None.
Make sure you also have these imports at the top of your file:
python
from langchain.memory import ConversationBufferMemory
from langchain.chains import ConversationalRetrievalChain
from langchain.llms import HuggingFaceHub
import os
from dotenv import load_dotenv
import streamlit as st
This should now properly maintain conversation history across multiple questions and display the chat in a proper conversational format.
def get_conversation_chain(vectorstore):
# Load the model name
model_name = "mistralai/Mistral-7B-Instruct-v0.3"
# Ensure you have the correct token set in your environment
token = os.environ['HUGGINGFACEHUB_API_TOKEN']
# Create the LLM instance
llm = HuggingFaceHub(
repo_id=model_name,
model_kwargs={
"temperature": 0.5,
"max_new_tokens": 512
},
huggingfacehub_api_token=token
)
memory = ConversationBufferMemory(
memory_key='chat_history',
return_messages=True,
output_key='answer'
)
conversation_chain = ConversationalRetrievalChain.from_llm(
llm=llm,
retriever=vectorstore.as_retriever(),
memory=memory,
return_source_documents=False, # Set to False to avoid extra output
verbose=False # Disable verbose to hide prompt formatting
)
return conversation_chain
def handle_userinput(user_question):
if st.session_state.conversation is None:
st.warning("Please process your documents first!")
return
# Display user question immediately
st.write(user_template.replace("{{MSG}}", user_question), unsafe_allow_html=True)
# Get the response
response = st.session_state.conversation({'question': user_question})
answer = response['answer']
# Display bot answer
st.write(bot_template.replace("{{MSG}}", answer), unsafe_allow_html=True)
# Update chat history (optional, if you want to keep track)
if 'chat_history' not in st.session_state:
st.session_state.chat_history = []
st.session_state.chat_history.append((user_question, answer))
def main():
load_dotenv()
st.set_page_config(page_title="Chat with multiple PDFs", page_icon=":books:")
st.write(css, unsafe_allow_html=True)
# Initialize session state
if "conversation" not in st.session_state:
st.session_state.conversation = None
if "chat_history" not in st.session_state:
st.session_state.chat_history = []
st.header("Chat with multiple PDFs :books:")
user_question = st.text_input("Ask a question about your documents:")
if user_question:
handle_userinput(user_question)
with st.sidebar:
st.subheader("Your documents")
pdf_docs = st.file_uploader(
"Upload your PDFs here and click on 'Process'",
accept_multiple_files=True
)
if st.button("Process"):
with st.spinner("Processing"):
raw_text = get_pdf_text(pdf_docs)
text_chunks = get_text_chunks(raw_text)
vectorstore = get_vectorstore(text_chunks)
st.session_state.conversation = get_conversation_chain(vectorstore)
st.session_state.chat_history = []
st.success("Documents processed successfully!")
Key changes made:
Disabled verbose output: Set verbose=False in the ConversationalRetrievalChain to hide prompt formatting.
Simplified response handling: Directly access the answer from the response without showing intermediate steps.
Immediate display: Show the user's question immediately when submitted, then show the bot's answer when ready.
Removed source documents: Set return_source_documents=False to avoid extra information in the output.
Streamlined chat history: Simplified the chat history storage to just store question-answer pairs.
This will now only display:
The user's question (in the user template style)
The assistant's answer (in the bot template style)
Without showing any of the intermediate prompt formatting or processing information.
def get_conversation_chain(vectorstore):
# Load the model name
model_name = "mistralai/Mistral-7B-Instruct-v0.3"
# Ensure you have the correct token set in your environment
token = os.environ['HUGGINGFACEHUB_API_TOKEN']
# Create the LLM instance
llm = HuggingFaceHub(
repo_id=model_name,
model_kwargs={
"temperature": 0.5,
"max_new_tokens": 512
},
huggingfacehub_api_token=token
)
memory = ConversationBufferMemory(
memory_key='chat_history',
return_messages=True,
output_key='answer'
)
conversation_chain = ConversationalRetrievalChain.from_llm(
llm=llm,
retriever=vectorstore.as_retriever(),
memory=memory,
return_source_documents=False,
verbose=False
)
return conversation_chain
def handle_userinput(user_question):
if st.session_state.conversation is None:
st.warning("Please process your documents first!")
return
# Display all previous chat history first
for exchange in st.session_state.chat_history:
role, message = exchange
if role == "user":
st.write(user_template.replace("{{MSG}}", message), unsafe_allow_html=True)
else:
st.write(bot_template.replace("{{MSG}}", message), unsafe_allow_html=True)
# Display the new user question immediately
st.write(user_template.replace("{{MSG}}", user_question), unsafe_allow_html=True)
# Get the response
response = st.session_state.conversation({'question': user_question})
answer = response['answer']
# Display the new bot answer
st.write(bot_template.replace("{{MSG}}", answer), unsafe_allow_html=True)
# Update chat history with the new exchange
st.session_state.chat_history.append(("user", user_question))
st.session_state.chat_history.append(("assistant", answer))
def main():
load_dotenv()
st.set_page_config(page_title="Chat with multiple PDFs", page_icon=":books:")
st.write(css, unsafe_allow_html=True)
# Initialize session state
if "conversation" not in st.session_state:
st.session_state.conversation = None
if "chat_history" not in st.session_state:
st.session_state.chat_history = []
st.header("Chat with multiple PDFs :books:")
# Container for chat history
chat_container = st.container()
# Container for new question input
with st.container():
user_question = st.text_input("Ask a question about your documents:", key="input")
if user_question:
handle_userinput(user_question)
# Clear the input box after submission
st.session_state.input = ""
with st.sidebar:
st.subheader("Your documents")
pdf_docs = st.file_uploader(
"Upload your PDFs here and click on 'Process'",
accept_multiple_files=True
)
if st.button("Process"):
with st.spinner("Processing"):
raw_text = get_pdf_text(pdf_docs)
text_chunks = get_text_chunks(raw_text)
vectorstore = get_vectorstore(text_chunks)
st.session_state.conversation = get_conversation_chain(vectorstore)
st.session_state.chat_history = []
st.success("Documents processed successfully!")
Key improvements for maintaining chat history:
Proper chat history storage: The chat history is stored as a list of tuples in the format (role, message) where role is either "user" or "assistant"
Full conversation display: The handle_userinput function now:
First displays all previous chat history
Then shows the new question and answer
Finally updates the chat history with the new exchange
Better UI organization:
Added containers to separate chat history display from input
Clears the input box after submission for better UX
Persistent memory:
The conversation chain maintains its memory through LangChain's ConversationBufferMemory
The Streamlit session state maintains the visual chat history
Reset on new documents:
When processing new documents, the chat history is properly reset
This implementation will now:
Show the complete conversation history
Only display questions and answers (no intermediate prompts)
Maintain context for follow-up questions
Provide a clean chat interface that resembles typical chat applications
The chat history will persist throughout the session and will be properly displayed in the correct order with appropriate styling for user vs assistant messages.