cryogenic22 commited on
Commit
9817125
·
verified ·
1 Parent(s): 06ff5eb

Update components/chat.py

Browse files
Files changed (1) hide show
  1. components/chat.py +68 -99
components/chat.py CHANGED
@@ -1,118 +1,87 @@
1
- # components_chat.py
2
 
3
  import streamlit as st
4
  from langchain_core.messages import HumanMessage, AIMessage
5
  from utils.database import verify_vector_store
6
  from threading import Lock
 
 
7
 
8
  # Create a lock for QA system access
9
  qa_lock = Lock()
10
 
11
  def display_chat_interface():
12
- """Display modern chat interface with clean formatting."""
13
-
14
- # Add custom CSS for modern chat styling
15
- st.markdown("""
16
- <style>
17
- /* Clean, modern chat container */
18
- .chat-container {
19
- max-width: 800px;
20
- margin: auto;
21
- }
22
-
23
- /* Message styling */
24
- .user-message {
25
- background-color: #f0f2f6;
26
- padding: 1rem;
27
- border-radius: 10px;
28
- margin: 1rem 0;
29
- }
30
-
31
- .assistant-message {
32
- background-color: #ffffff;
33
- border: 1px solid #e0e0e0;
34
- padding: 1.5rem;
35
- border-radius: 10px;
36
- margin: 1rem 0;
37
- }
38
-
39
- /* Section styling */
40
- .section-header {
41
- font-weight: bold;
42
- color: #0f52ba;
43
- margin-top: 1rem;
44
- }
45
-
46
- .source-info {
47
- background-color: #f8f9fa;
48
- padding: 0.5rem;
49
- border-left: 3px solid #0f52ba;
50
- margin-top: 1rem;
51
- font-size: 0.9rem;
52
- }
53
-
54
- /* Content sections */
55
- .content-section {
56
- margin: 0.5rem 0;
57
- }
58
-
59
- /* Clean bullets */
60
- .clean-bullet {
61
- margin: 0.3rem 0;
62
- }
63
- </style>
64
- """, unsafe_allow_html=True)
65
-
66
- # Check if QA system is initialized
67
- if 'qa_system' not in st.session_state or st.session_state.qa_system is None:
68
- st.warning("Please upload documents first to initialize the chat system.")
69
  return
70
-
71
- # Initialize chat history
72
  if 'messages' not in st.session_state:
73
  st.session_state.messages = []
74
-
75
- # Display chat history
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
  for message in st.session_state.messages:
77
  if isinstance(message, HumanMessage):
78
- st.markdown(f"""
79
- <div class="user-message">
80
- 🧑‍💼 <strong>You:</strong><br>{message.content}
81
- </div>
82
- """, unsafe_allow_html=True)
83
  elif isinstance(message, AIMessage):
84
- content = str(message.content)
85
- st.markdown(f"""
86
- <div class="assistant-message">
87
- 🤖 <strong>Assistant:</strong><br>
88
- {content}
89
- </div>
90
- """, unsafe_allow_html=True)
91
 
92
- # Chat input at the bottom
93
- if prompt := st.chat_input("Ask about your documents..."):
94
- try:
95
- with st.spinner("Analyzing..."):
96
- # Create message objects
97
- human_message = HumanMessage(content=prompt)
98
- st.session_state.messages.append(human_message)
 
 
 
 
 
 
 
 
 
 
99
 
100
- # Use lock to access QA system
101
- with qa_lock:
102
- response = st.session_state.qa_system.invoke({
103
- "input": prompt,
104
- "chat_history": st.session_state.messages
105
- })
 
 
 
 
 
106
 
107
- if response:
108
- content = str(response)
109
- ai_message = AIMessage(content=content)
110
- st.session_state.messages.append(ai_message)
111
- st.rerun()
112
- else:
113
- st.error("No valid response received")
114
-
115
- except Exception as e:
116
- st.error(f"Error: {e}")
117
- import traceback
118
- st.error(traceback.format_exc())
 
1
+ # components/chat.py
2
 
3
  import streamlit as st
4
  from langchain_core.messages import HumanMessage, AIMessage
5
  from utils.database import verify_vector_store
6
  from threading import Lock
7
+ from typing import Optional
8
+ import traceback
9
 
10
  # Create a lock for QA system access
11
  qa_lock = Lock()
12
 
13
  def display_chat_interface():
14
+ """
15
+ Display a modern chat interface with error handling and clean formatting.
16
+ Manages conversation state and handles document context.
17
+ """
18
+ # Verify QA system initialization
19
+ if not _verify_chat_ready():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  return
21
+
22
+ # Initialize chat history if needed
23
  if 'messages' not in st.session_state:
24
  st.session_state.messages = []
25
+
26
+ # Display existing chat history
27
+ _display_chat_history()
28
+
29
+ # Handle new user input
30
+ if prompt := st.chat_input("Ask about your documents..."):
31
+ _process_user_message(prompt)
32
+
33
+ def _verify_chat_ready() -> bool:
34
+ """Check if the chat system is properly initialized."""
35
+ if 'qa_system' not in st.session_state or st.session_state.qa_system is None:
36
+ st.warning("Please upload documents first to initialize the chat system.")
37
+ return False
38
+ return True
39
+
40
+ def _display_chat_history():
41
+ """Display all messages in the chat history."""
42
  for message in st.session_state.messages:
43
  if isinstance(message, HumanMessage):
44
+ with st.chat_message("user"):
45
+ st.write(message.content)
 
 
 
46
  elif isinstance(message, AIMessage):
47
+ with st.chat_message("assistant"):
48
+ st.write(message.content)
49
+
50
+ def _process_user_message(prompt: str):
51
+ """
52
+ Process a new user message and generate AI response.
 
53
 
54
+ Args:
55
+ prompt (str): User's input message
56
+ """
57
+ try:
58
+ with st.spinner("Analyzing..."):
59
+ # Create and display user message
60
+ human_message = HumanMessage(content=prompt)
61
+ st.session_state.messages.append(human_message)
62
+ with st.chat_message("user"):
63
+ st.write(prompt)
64
+
65
+ # Generate AI response with thread safety
66
+ with qa_lock:
67
+ response = st.session_state.qa_system.invoke({
68
+ "input": prompt,
69
+ "chat_history": st.session_state.messages
70
+ })
71
 
72
+ if response:
73
+ # Create and display AI message
74
+ ai_message = AIMessage(content=str(response))
75
+ st.session_state.messages.append(ai_message)
76
+ with st.chat_message("assistant"):
77
+ st.write(response)
78
+
79
+ # Rerun to update UI cleanly
80
+ st.rerun()
81
+ else:
82
+ st.error("No response received. Please try again.")
83
 
84
+ except Exception as e:
85
+ st.error(f"An error occurred while processing your message: {str(e)}")
86
+ if st.session_state.get('debug_mode'):
87
+ st.error(traceback.format_exc())