ngcanh commited on
Commit
c763e04
·
verified ·
1 Parent(s): 53416d2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -56
app.py CHANGED
@@ -13,25 +13,25 @@ TOKEN=os.getenv('HF_TOKEN')
13
  subprocess.run(["huggingface-cli", "login", "--token", TOKEN, "--add-to-git-credential"])
14
  st.sidebar.title("Welcome to MBAL Chatbot")
15
  class PDFChatbot:
16
- def __init__(self):
17
  self.azure_client = openai.OpenAI()
18
  self.conversation_history = []
19
  self.pdf_content = ""
20
 
21
- def get_relevant_context(self, user_question: str) -> List[str]:
22
  """Split text into smaller chunks for better processing."""
23
  db = FAISS.load_local("mbal_faiss_db", embeddings=HuggingFaceEmbeddings(model_name='bkai-foundation-models/vietnamese-bi-encoder'), allow_dangerous_deserialization=True)
24
  relevant_chunks = db.similarity_search(user_question, k=3)
25
  relevant_chunks = [chunk.page_content for chunk in relevant_chunks]
26
  return "\n\n".join(relevant_chunks)
27
- def chat_with_pdf(self, user_question: str, pdf_content: str) -> str:
28
  """Generate response using Azure OpenAI based on PDF content and user question."""
29
- try:
30
- # Split PDF content into chunks
31
- # Get relevant context for the question
32
- relevant_context = self.get_relevant_context(user_question)
33
- # Prepare messages for the chat
34
- messages = [
35
  {
36
  "role": "system",
37
  "content": """You are an experienced insurance agent assistant who helps customers understand their insurance policies and coverage details. Follow these guidelines:
@@ -53,64 +53,64 @@ class PDFChatbot:
53
  {relevant_context}
54
  Customer Question: {user_question}
55
  Please provide a helpful response based on the insurance document content above."""
56
- }
57
- ]
58
  # Add conversation history
59
- for msg in self.conversation_history[-2:]: # Keep last 6 messages for context
60
  messages.append(msg)
61
- # Get response from Azure OpenAI
62
- response = self.azure_client.chat.completions.create(
63
  model="gpt-4o-mini",
64
  messages=messages,
65
  max_tokens=300, #TODO
66
  temperature=0.7
67
- )
68
- bot_response = response.choices[0].message.content
69
- # Update conversation history
70
- self.conversation_history.append({"role": "user", "content": user_question})
71
- self.conversation_history.append({"role": "assistant", "content": bot_response})
72
- return bot_response
73
- except Exception as e:
74
- return f"Error generating response: {str(e)}"
75
  def main():
76
- # st.set_page_config(page_title="Insurance PDF Chatbot", page_icon="🛡️", layout="wide")
77
- st.title("🛡️ Insurance Policy Assistant")
78
- st.markdown("Upload your insurance policy PDF and ask questions about your coverage, claims, deductibles, and more!")
79
- # Initialize chatbot
80
- if 'chatbot' not in st.session_state:
81
- st.session_state.chatbot = PDFChatbot()
82
- st.session_state.pdf_processed = False
83
- st.session_state.chat_history = []
84
- # Sidebar for PDF upload and settings
85
 
86
- # Clear conversation
87
- if st.button("Xóa lịch sử"):
88
- st.session_state.chatbot.conversation_history = []
89
- st.session_state.chat_history = []
90
- st.rerun()
91
  # Main chat interface
92
- if st.session_state.pdf_processed:
93
- st.header("💬 Ask About Your Insurance Policy")
94
- # Display chat history
95
- for i, (question, answer) in enumerate(st.session_state.chat_history):
96
- with st.container():
97
- st.markdown(f"**You:** {question}")
98
- st.markdown(f"**Insurance Assistant:** {answer}")
99
- st.divider()
100
  # Chat input
101
- 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...")
102
- if user_question:
103
- with st.spinner("Analyzing your policy..."):
104
- # Get response from chatbot
105
- response = st.session_state.chatbot.chat_with_pdf(
106
  user_question,
107
  st.session_state.chatbot.pdf_content
108
- )
109
- # Add to chat history
110
- st.session_state.chat_history.append((user_question, response))
111
- # Display the new response
112
- st.markdown(f"**You:** {user_question}")
113
- st.markdown(f"**Insurance Assistant:** {response}")
114
  else:
115
  # Show example questions
116
  st.subheader("Các câu hỏi bạn có thể hỏi:")
@@ -138,4 +138,4 @@ def main():
138
  """)
139
 
140
  if __name__ == "__main__":
141
- main()
 
13
  subprocess.run(["huggingface-cli", "login", "--token", TOKEN, "--add-to-git-credential"])
14
  st.sidebar.title("Welcome to MBAL Chatbot")
15
  class PDFChatbot:
16
+ def __init__(self):
17
  self.azure_client = openai.OpenAI()
18
  self.conversation_history = []
19
  self.pdf_content = ""
20
 
21
+ def get_relevant_context(self, user_question: str) -> List[str]:
22
  """Split text into smaller chunks for better processing."""
23
  db = FAISS.load_local("mbal_faiss_db", embeddings=HuggingFaceEmbeddings(model_name='bkai-foundation-models/vietnamese-bi-encoder'), allow_dangerous_deserialization=True)
24
  relevant_chunks = db.similarity_search(user_question, k=3)
25
  relevant_chunks = [chunk.page_content for chunk in relevant_chunks]
26
  return "\n\n".join(relevant_chunks)
27
+ def chat_with_pdf(self, user_question: str, pdf_content: str) -> str:
28
  """Generate response using Azure OpenAI based on PDF content and user question."""
29
+ try:
30
+ # Split PDF content into chunks
31
+ # Get relevant context for the question
32
+ relevant_context = self.get_relevant_context(user_question)
33
+ # Prepare messages for the chat
34
+ messages = [
35
  {
36
  "role": "system",
37
  "content": """You are an experienced insurance agent assistant who helps customers understand their insurance policies and coverage details. Follow these guidelines:
 
53
  {relevant_context}
54
  Customer Question: {user_question}
55
  Please provide a helpful response based on the insurance document content above."""
56
+ }
57
+ ]
58
  # Add conversation history
59
+ for msg in self.conversation_history[-2:]: # Keep last 6 messages for context
60
  messages.append(msg)
61
+ # Get response from Azure OpenAI
62
+ response = self.azure_client.chat.completions.create(
63
  model="gpt-4o-mini",
64
  messages=messages,
65
  max_tokens=300, #TODO
66
  temperature=0.7
67
+ )
68
+ bot_response = response.choices[0].message.content
69
+ # Update conversation history
70
+ self.conversation_history.append({"role": "user", "content": user_question})
71
+ self.conversation_history.append({"role": "assistant", "content": bot_response})
72
+ return bot_response
73
+ except Exception as e:
74
+ return f"Error generating response: {str(e)}"
75
  def main():
76
+ # st.set_page_config(page_title="Insurance PDF Chatbot", page_icon="🛡️", layout="wide")
77
+ st.title("🛡️ Insurance Policy Assistant")
78
+ st.markdown("Upload your insurance policy PDF and ask questions about your coverage, claims, deductibles, and more!")
79
+ # Initialize chatbot
80
+ if 'chatbot' not in st.session_state:
81
+ st.session_state.chatbot = PDFChatbot()
82
+ st.session_state.pdf_processed = False
83
+ st.session_state.chat_history = []
84
+ # Sidebar for PDF upload and settings
85
 
86
+ # Clear conversation
87
+ if st.button("Xóa lịch sử"):
88
+ st.session_state.chatbot.conversation_history = []
89
+ st.session_state.chat_history = []
90
+ st.rerun()
91
  # Main chat interface
92
+ if st.session_state.pdf_processed:
93
+ st.header("💬 Ask About Your Insurance Policy")
94
+ # Display chat history
95
+ for i, (question, answer) in enumerate(st.session_state.chat_history):
96
+ with st.container():
97
+ st.markdown(f"**You:** {question}")
98
+ st.markdown(f"**Insurance Assistant:** {answer}")
99
+ st.divider()
100
  # Chat input
101
+ 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...")
102
+ if user_question:
103
+ with st.spinner("Analyzing your policy..."):
104
+ # Get response from chatbot
105
+ response = st.session_state.chatbot.chat_with_pdf(
106
  user_question,
107
  st.session_state.chatbot.pdf_content
108
+ )
109
+ # Add to chat history
110
+ st.session_state.chat_history.append((user_question, response))
111
+ # Display the new response
112
+ st.markdown(f"**You:** {user_question}")
113
+ st.markdown(f"**Insurance Assistant:** {response}")
114
  else:
115
  # Show example questions
116
  st.subheader("Các câu hỏi bạn có thể hỏi:")
 
138
  """)
139
 
140
  if __name__ == "__main__":
141
+ main()