MBAL_chatbot / app.py
ngcanh's picture
Update app.py
ecbb6ec verified
raw
history blame
8.19 kB
import os
import streamlit as st
import subprocess
import openai
import fitz
import PyPDF2
from langchain_community.vectorstores import FAISS
from langchain.embeddings import HuggingFaceEmbeddings
from openai import OpenAI
from langchain_openai import ChatOpenAI
from typing import List, Dict
from langchain.schema import Document
from langchain_experimental.text_splitter import SemanticChunker # module for chunking text
import os
# Load environment variables
OPENAI_API_KEY = os.getenv("OPENAI_API")
TOKEN=os.getenv('HF_TOKEN')
subprocess.run(["huggingface-cli", "login", "--token", TOKEN, "--add-to-git-credential"])
st.sidebar.title("Welcome to MBAL Chatbot")
class PDFChatbot:
def __init__(self):
self.azure_client = openai.OpenAI()
self.conversation_history = []
self.pdf_content = ""
def get_relevant_context(self, user_question: str) -> List[str]:
"""Split text into smaller chunks for better processing."""
# db = FAISS.load_local('mbaldb', HuggingFaceEmbeddings(model_name='bkai-foundation-models/vietnamese-bi-encoder'), allow_dangerous_deserialization = True )
pdf_directory = "data"
# Duyệt qua các file trong thư mục và đọc từng file PDF
pdf_reader = PyPDF2.PdfReader(pdf_file)
text = ""
for page_num in range(len(pdf_reader.pages)):
page = pdf_reader.pages[page_num]
text += page.extract_text() + "\n"
words = text.split()
chunks = []
current_chunk = []
current_length = 0
for word in words:
if current_length + len(word) + 1 > chunk_size:
if current_chunk:
chunks.append(" ".join(current_chunk))
current_chunk = [word]
current_length = len(word)
else:
current_chunk.append(word)
current_length += len(word) + 1
if current_chunk:
chunks.append(" ".join(current_chunk))
db = FAISS.from_documents(docs, HuggingFaceEmbeddings(model_name='bkai-foundation-models/vietnamese-bi-encoder'))
relevant_chunks = db.similarity_search(user_question, k=3)
relevant_chunks = [chunk.page_content for chunk in relevant_chunks]
return "\n\n".join(relevant_chunks)
def chat_with_pdf(self, user_question: str, pdf_content: str) -> str:
"""Generate response using Azure OpenAI based on PDF content and user question."""
# Split PDF content into chunks
# Get relevant context for the question
relevant_context = self.get_relevant_context(user_question)
# Prepare messages for the chat
messages = [
{
"role": "system",
"content": """You are an experienced insurance agent assistant who helps customers understand their insurance policies and coverage details. Follow these guidelines:
1. Only provide information based on the PDF content provided
2. If the answer is not in the PDF, clearly state that the information is not available in the document
3. Provide clear, concise, and helpful responses in a professional manner
4. Always respond in Vietnamese using proper grammar and formatting
5. When possible, reference specific sections or clauses from the policy
6. Use insurance terminology appropriately but explain complex terms when necessary
7. Be empathetic and patient, as insurance can be confusing for customers
8. If asked about claims, coverage limits, deductibles, or policy terms, provide accurate information from the document
9. Always prioritize customer understanding and satisfaction
10. If multiple interpretations are possible, explain the different scenarios clearly
Remember: You are here to help customers understand their insurance coverage better."""
},
{
"role": "user",
"content": f"""Insurance Document Content:
{relevant_context}
Customer Question: {user_question}
Please provide a helpful response based on the insurance document content above."""
}
]
# Add conversation history
for msg in self.conversation_history[-2:]: # Keep last 6 messages for context
messages.append(msg)
# Get response from Azure OpenAI
response = self.azure_client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
max_tokens=300, #TODO
temperature=0.7
)
bot_response = response.choices[0].message.content
# Update conversation history
self.conversation_history.append({"role": "user", "content": user_question})
self.conversation_history.append({"role": "assistant", "content": bot_response})
return bot_response
def main():
# st.set_page_config(page_title="Insurance PDF Chatbot", page_icon="🛡️", layout="wide")
st.title("🛡️ Insurance Policy Assistant")
st.markdown("Upload your insurance policy PDF and ask questions about your coverage, claims, deductibles, and more!")
# Initialize chatbot
if 'chatbot' not in st.session_state:
st.session_state.chatbot = PDFChatbot()
st.session_state.pdf_processed = False
st.session_state.chat_history = []
# Sidebar for PDF upload and settings
# Clear conversation
if st.button("Xóa lịch sử"):
st.session_state.chatbot.conversation_history = []
st.session_state.chat_history = []
st.rerun()
# Main chat interface
st.header("💬 Ask About Your Insurance Policy")
# Display chat history
for i, (question, answer) in enumerate(st.session_state.chat_history):
with st.container():
st.markdown(f"**You:** {question}")
st.markdown(f"**Insurance Assistant:** {answer}")
st.divider()
# Chat input
user_question = st.chat_input("Hãy đặt những câu hỏi về hợp đồng bảo hiểm cơ bản...")
if user_question:
with st.spinner("Analyzing your policy..."):
# Get response from chatbot
response = st.session_state.chatbot.chat_with_pdf(
user_question,
st.session_state.chatbot.pdf_content
)
# Add to chat history
st.session_state.chat_history.append((user_question, response))
# Display the new response
st.markdown(f"**You:** {user_question}")
st.markdown(f"**Insurance Assistant:** {response}")
else:
# Show example questions
st.subheader("Các câu hỏi bạn có thể hỏi:")
st.markdown("""
- Giới hạn bảo hiểm cho thiệt hại tài sản của tôi là bao nhiêu?
- Mức khấu trừ của tôi là bao nhiêu?
- Những loại sự cố nào được bảo hiểm theo hợp đồng này?
- Những gì không được bảo hiểm?
- Làm thế nào để tôi nộp đơn yêu cầu bồi thường?
- Quy trình giải quyết yêu cầu bồi thường như thế nào?
- Tôi có những lựa chọn nào để thanh toán phí bảo hiểm?
- Hợp đồng bảo hiểm của tôi hết hạn khi nào?
- Bảo hiểm có bao gồm thiệt hại do lũ lụt không?
- Tôi cần những giấy tờ gì khi nộp đơn yêu cầu bồi thường?
""")
# Thêm mẹo bảo hiểm
st.subheader("💡 Mẹo về bảo hiểm")
st.markdown("""
- Thường xuyên xem lại hợp đồng bảo hiểm để hiểu rõ quyền lợi của bạn
- Lưu giữ tài liệu bảo hiểm ở nơi an toàn
- Cập nhật quyền lợi bảo hiểm khi hoàn cảnh của bạn thay đổi
- Ghi lại mọi sự cố ngay khi xảy ra
- Liên hệ với đại lý bảo hiểm nếu bạn có bất kỳ câu hỏi nào
""")
if __name__ == "__main__":
main()