File size: 8,188 Bytes
d863a8a
 
 
 
4606c08
ecbb6ec
30f8dbf
 
d863a8a
 
 
7164d53
 
 
 
d863a8a
 
 
 
 
 
c763e04
d863a8a
 
30f8dbf
d863a8a
c763e04
d863a8a
7164d53
 
 
 
 
 
ecbb6ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7164d53
 
 
d863a8a
 
 
c763e04
d685d1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d863a8a
 
 
d685d1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d863a8a
c763e04
 
 
 
 
 
 
 
 
53416d2
c763e04
 
 
 
 
d685d1d
08fa6fe
 
 
 
 
 
 
d685d1d
08fa6fe
 
 
 
 
 
 
 
 
 
 
 
 
d863a8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c763e04
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
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()