Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import streamlit as st
|
3 |
+
from langchain_community.vectorstores import FAISS
|
4 |
+
from langchain_huggingface import HuggingFaceEmbeddings
|
5 |
+
import subprocess
|
6 |
+
import openai
|
7 |
+
from openai import OpenAI
|
8 |
+
from langchain_openai import ChatOpenAI
|
9 |
+
from io import BytesIO
|
10 |
+
from typing import List, Dict
|
11 |
+
from dotenv import load_dotenv
|
12 |
+
# Load environment variables
|
13 |
+
OPENAI_API_KEY = os.getenv("OPENAI_API")
|
14 |
+
TOKEN=os.getenv('HF_TOKEN')
|
15 |
+
subprocess.run(["huggingface-cli", "login", "--token", TOKEN, "--add-to-git-credential"])
|
16 |
+
st.sidebar.title("Welcome to MBAL Chatbot")
|
17 |
+
class PDFChatbot:
|
18 |
+
def __init__(self):
|
19 |
+
self.azure_client = openai.OpenAI()
|
20 |
+
# Store conversation history
|
21 |
+
self.conversation_history = []
|
22 |
+
|
23 |
+
def get_relevant_context(self, user_question: str) -> List[str]:
|
24 |
+
"""Split text into smaller chunks for better processing."""
|
25 |
+
db = FAISS.load_local("mbal_faiss_db", embeddings=HuggingFaceEmbeddings(model_name='bkai-foundation-models/vietnamese-bi-encoder'), allow_dangerous_deserialization=True)
|
26 |
+
relevant_chunks = db.similarity_search(user_question, k=3)
|
27 |
+
relevant_chunks = [chunk.page_content for chunk in relevant_chunks]
|
28 |
+
return "\n\n".join(relevant_chunks)
|
29 |
+
def chat_with_pdf(self, user_question: str, pdf_content: str) -> str:
|
30 |
+
"""Generate response using Azure OpenAI based on PDF content and user question."""
|
31 |
+
try:
|
32 |
+
# Split PDF content into chunks
|
33 |
+
# Get relevant context for the question
|
34 |
+
relevant_context = self.get_relevant_context(user_question)
|
35 |
+
# Prepare messages for the chat
|
36 |
+
messages = [
|
37 |
+
{
|
38 |
+
"role": "system",
|
39 |
+
"content": """You are an experienced insurance agent assistant who helps customers understand their insurance policies and coverage details. Follow these guidelines:
|
40 |
+
1. Only provide information based on the PDF content provided
|
41 |
+
2. If the answer is not in the PDF, clearly state that the information is not available in the document
|
42 |
+
3. Provide clear, concise, and helpful responses in a professional manner
|
43 |
+
4. Always respond in Vietnamese using proper grammar and formatting
|
44 |
+
5. When possible, reference specific sections or clauses from the policy
|
45 |
+
6. Use insurance terminology appropriately but explain complex terms when necessary
|
46 |
+
7. Be empathetic and patient, as insurance can be confusing for customers
|
47 |
+
8. If asked about claims, coverage limits, deductibles, or policy terms, provide accurate information from the document
|
48 |
+
9. Always prioritize customer understanding and satisfaction
|
49 |
+
10. If multiple interpretations are possible, explain the different scenarios clearly
|
50 |
+
Remember: You are here to help customers understand their insurance coverage better."""
|
51 |
+
},
|
52 |
+
{
|
53 |
+
"role": "user",
|
54 |
+
"content": f"""Insurance Document Content:
|
55 |
+
{relevant_context}
|
56 |
+
Customer Question: {user_question}
|
57 |
+
Please provide a helpful response based on the insurance document content above."""
|
58 |
+
}
|
59 |
+
]
|
60 |
+
# Add conversation history
|
61 |
+
for msg in self.conversation_history[-2:]: # Keep last 6 messages for context
|
62 |
+
messages.append(msg)
|
63 |
+
# Get response from Azure OpenAI
|
64 |
+
response = self.azure_client.chat.completions.create(
|
65 |
+
model="gpt-4o-mini",
|
66 |
+
messages=messages,
|
67 |
+
max_tokens=1000,
|
68 |
+
temperature=0.7
|
69 |
+
)
|
70 |
+
bot_response = response.choices[0].message.content
|
71 |
+
# Update conversation history
|
72 |
+
self.conversation_history.append({"role": "user", "content": user_question})
|
73 |
+
self.conversation_history.append({"role": "assistant", "content": bot_response})
|
74 |
+
return bot_response
|
75 |
+
except Exception as e:
|
76 |
+
return f"Error generating response: {str(e)}"
|
77 |
+
def main():
|
78 |
+
# st.set_page_config(page_title="Insurance PDF Chatbot", page_icon="🛡️", layout="wide")
|
79 |
+
st.title("🛡️ Insurance Policy Assistant")
|
80 |
+
st.markdown("Upload your insurance policy PDF and ask questions about your coverage, claims, deductibles, and more!")
|
81 |
+
# Initialize chatbot
|
82 |
+
if 'chatbot' not in st.session_state:
|
83 |
+
st.session_state.chatbot = PDFChatbot()
|
84 |
+
st.session_state.pdf_processed = False
|
85 |
+
st.session_state.chat_history = []
|
86 |
+
|
87 |
+
# Clear conversation
|
88 |
+
if st.button("Xóa lịch sử chat"):
|
89 |
+
st.session_state.chatbot.conversation_history = []
|
90 |
+
st.session_state.chat_history = []
|
91 |
+
st.rerun()
|
92 |
+
# Main chat interface
|
93 |
+
if st.session_state.pdf_processed:
|
94 |
+
st.header("💬 Ask About Your Insurance Policy")
|
95 |
+
# Display chat history
|
96 |
+
for i, (question, answer) in enumerate(st.session_state.chat_history):
|
97 |
+
with st.container():
|
98 |
+
st.markdown(f"**You:** {question}")
|
99 |
+
st.markdown(f"**Insurance Assistant:** {answer}")
|
100 |
+
st.divider()
|
101 |
+
# Chat input
|
102 |
+
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...")
|
103 |
+
if user_question:
|
104 |
+
with st.spinner("Analyzing your policy..."):
|
105 |
+
# Get response from chatbot
|
106 |
+
response = st.session_state.chatbot.chat_with_pdf(
|
107 |
+
user_question,
|
108 |
+
st.session_state.chatbot.pdf_content
|
109 |
+
)
|
110 |
+
# Add to chat history
|
111 |
+
st.session_state.chat_history.append((user_question, response))
|
112 |
+
# Display the new response
|
113 |
+
st.markdown(f"**You:** {user_question}")
|
114 |
+
st.markdown(f"**Insurance Assistant:** {response}")
|
115 |
+
else:
|
116 |
+
# Show example questions
|
117 |
+
st.subheader("Các câu hỏi bạn có thể hỏi:")
|
118 |
+
st.markdown("""
|
119 |
+
- 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?
|
120 |
+
- Mức khấu trừ của tôi là bao nhiêu?
|
121 |
+
- Những loại sự cố nào được bảo hiểm theo hợp đồng này?
|
122 |
+
- Những gì không được bảo hiểm?
|
123 |
+
- Làm thế nào để tôi nộp đơn yêu cầu bồi thường?
|
124 |
+
- Quy trình giải quyết yêu cầu bồi thường như thế nào?
|
125 |
+
- Tôi có những lựa chọn nào để thanh toán phí bảo hiểm?
|
126 |
+
- Hợp đồng bảo hiểm của tôi hết hạn khi nào?
|
127 |
+
- Bảo hiểm có bao gồm thiệt hại do lũ lụt không?
|
128 |
+
- Tôi cần những giấy tờ gì khi nộp đơn yêu cầu bồi thường?
|
129 |
+
""")
|
130 |
+
|
131 |
+
# Thêm mẹo bảo hiểm
|
132 |
+
st.subheader("💡 Mẹo về bảo hiểm")
|
133 |
+
st.markdown("""
|
134 |
+
- 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
|
135 |
+
- Lưu giữ tài liệu bảo hiểm ở nơi an toàn
|
136 |
+
- Cập nhật quyền lợi bảo hiểm khi hoàn cảnh của bạn thay đổi
|
137 |
+
- Ghi lại mọi sự cố ngay khi xảy ra
|
138 |
+
- 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
|
139 |
+
""")
|
140 |
+
|
141 |
+
if __name__ == "__main__":
|
142 |
+
main()
|