Spaces:
Paused
Paused
Update components/chat.py
Browse files- components/chat.py +46 -37
components/chat.py
CHANGED
|
@@ -5,6 +5,7 @@ from langchain_core.messages import HumanMessage, AIMessage
|
|
| 5 |
from backend import get_embeddings_model, initialize_qa_system
|
| 6 |
from utils.persistence import PersistenceManager
|
| 7 |
|
|
|
|
| 8 |
def ensure_embeddings_initialized():
|
| 9 |
"""Ensure embeddings model is initialized in session state."""
|
| 10 |
if 'embeddings' not in st.session_state:
|
|
@@ -15,6 +16,7 @@ def ensure_embeddings_initialized():
|
|
| 15 |
return False
|
| 16 |
return True
|
| 17 |
|
|
|
|
| 18 |
def format_session_date(session_id: str) -> str:
|
| 19 |
"""Format session ID into readable date."""
|
| 20 |
try:
|
|
@@ -23,7 +25,7 @@ def format_session_date(session_id: str) -> str:
|
|
| 23 |
date_part = session_id.split('_')[1]
|
| 24 |
else:
|
| 25 |
date_part = session_id
|
| 26 |
-
|
| 27 |
if len(date_part) == 8: # Format: YYYYMMDD
|
| 28 |
return datetime.strptime(date_part, '%Y%m%d').strftime('%B %d, %Y')
|
| 29 |
elif len(date_part) == 14: # Format: YYYYMMDD_HHMMSS
|
|
@@ -33,34 +35,36 @@ def format_session_date(session_id: str) -> str:
|
|
| 33 |
except Exception as e:
|
| 34 |
return f"Session: {session_id}" # Fallback display
|
| 35 |
|
|
|
|
| 36 |
def clean_ai_response(content):
|
| 37 |
"""Clean up AI response content and remove technical artifacts."""
|
| 38 |
content = str(content)
|
| 39 |
-
|
| 40 |
# Remove common technical artifacts
|
| 41 |
if "content='" in content:
|
| 42 |
content = content.split("content='")[1]
|
| 43 |
if "additional_kwargs" in content:
|
| 44 |
content = content.split("additional_kwargs")[0]
|
| 45 |
-
|
| 46 |
# Clean up any remaining artifacts
|
| 47 |
content = content.strip("'")
|
| 48 |
content = content.replace('\\n', '\n')
|
| 49 |
content = content.replace('\\t', '\t')
|
| 50 |
-
|
| 51 |
return content
|
| 52 |
|
|
|
|
| 53 |
def format_assistant_response(content):
|
| 54 |
"""Format the assistant's response into a structured layout."""
|
| 55 |
try:
|
| 56 |
# Clean the content first
|
| 57 |
content = clean_ai_response(content)
|
| 58 |
-
|
| 59 |
# Identify sections and structure
|
| 60 |
lines = [line.strip() for line in content.split('\n') if line.strip()]
|
| 61 |
formatted_sections = []
|
| 62 |
current_section = []
|
| 63 |
-
|
| 64 |
for line in lines:
|
| 65 |
# Handle bullet points and lists
|
| 66 |
if line.startswith(('•', '-', '*')):
|
|
@@ -84,32 +88,33 @@ def format_assistant_response(content):
|
|
| 84 |
formatted_sections.extend(current_section)
|
| 85 |
current_section = []
|
| 86 |
formatted_sections.append(f'<p>{line}</p>')
|
| 87 |
-
|
| 88 |
# Add any remaining content
|
| 89 |
if current_section:
|
| 90 |
if current_section[0] == "<ul>":
|
| 91 |
current_section.append("</ul>")
|
| 92 |
formatted_sections.extend(current_section)
|
| 93 |
-
|
| 94 |
# Build the final HTML
|
| 95 |
formatted_html = f"""
|
| 96 |
<div class="response-content">
|
| 97 |
{''.join(formatted_sections)}
|
| 98 |
</div>
|
| 99 |
"""
|
| 100 |
-
|
| 101 |
return formatted_html
|
| 102 |
except Exception as e:
|
| 103 |
st.error(f"Error formatting response: {str(e)}")
|
| 104 |
return str(content)
|
| 105 |
|
|
|
|
| 106 |
def display_chat_interface():
|
| 107 |
"""Display modern chat interface with clean formatting."""
|
| 108 |
-
|
| 109 |
# Initialize persistence if needed
|
| 110 |
if 'persistence' not in st.session_state:
|
| 111 |
st.session_state.persistence = PersistenceManager()
|
| 112 |
-
|
| 113 |
# Add custom CSS for modern chat styling
|
| 114 |
st.markdown("""
|
| 115 |
<style>
|
|
@@ -118,7 +123,7 @@ def display_chat_interface():
|
|
| 118 |
max-width: 800px;
|
| 119 |
margin: auto;
|
| 120 |
}
|
| 121 |
-
|
| 122 |
/* User message */
|
| 123 |
.user-message {
|
| 124 |
background-color: #f0f2f6;
|
|
@@ -127,7 +132,7 @@ def display_chat_interface():
|
|
| 127 |
margin: 1rem 0;
|
| 128 |
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
|
| 129 |
}
|
| 130 |
-
|
| 131 |
/* Assistant message */
|
| 132 |
.assistant-message {
|
| 133 |
background-color: #ffffff;
|
|
@@ -137,12 +142,12 @@ def display_chat_interface():
|
|
| 137 |
margin: 1rem 0;
|
| 138 |
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
|
| 139 |
}
|
| 140 |
-
|
| 141 |
/* Response content */
|
| 142 |
.response-content {
|
| 143 |
line-height: 1.6;
|
| 144 |
}
|
| 145 |
-
|
| 146 |
/* Section headers */
|
| 147 |
.section-header {
|
| 148 |
color: #0f52ba;
|
|
@@ -152,33 +157,33 @@ def display_chat_interface():
|
|
| 152 |
border-bottom: 2px solid #e0e0e0;
|
| 153 |
padding-bottom: 0.5rem;
|
| 154 |
}
|
| 155 |
-
|
| 156 |
/* Lists */
|
| 157 |
.response-content ul {
|
| 158 |
margin: 1rem 0;
|
| 159 |
padding-left: 1.5rem;
|
| 160 |
list-style-type: none;
|
| 161 |
}
|
| 162 |
-
|
| 163 |
.response-content li {
|
| 164 |
margin: 0.5rem 0;
|
| 165 |
position: relative;
|
| 166 |
padding-left: 1rem;
|
| 167 |
}
|
| 168 |
-
|
| 169 |
.response-content li:before {
|
| 170 |
content: "•";
|
| 171 |
position: absolute;
|
| 172 |
left: -1rem;
|
| 173 |
color: #0f52ba;
|
| 174 |
}
|
| 175 |
-
|
| 176 |
/* Paragraphs */
|
| 177 |
.response-content p {
|
| 178 |
margin: 1rem 0;
|
| 179 |
color: #2c3e50;
|
| 180 |
}
|
| 181 |
-
|
| 182 |
/* Source citations */
|
| 183 |
.source-citation {
|
| 184 |
font-style: italic;
|
|
@@ -197,7 +202,7 @@ def display_chat_interface():
|
|
| 197 |
margin-bottom: 1rem;
|
| 198 |
border: 1px solid #e0e0e0;
|
| 199 |
}
|
| 200 |
-
|
| 201 |
/* Current session info */
|
| 202 |
.session-info {
|
| 203 |
margin-bottom: 1rem;
|
|
@@ -209,7 +214,7 @@ def display_chat_interface():
|
|
| 209 |
}
|
| 210 |
</style>
|
| 211 |
""", unsafe_allow_html=True)
|
| 212 |
-
|
| 213 |
try:
|
| 214 |
# Check if QA system is initialized
|
| 215 |
if 'qa_system' not in st.session_state or st.session_state.qa_system is None:
|
|
@@ -223,13 +228,13 @@ def display_chat_interface():
|
|
| 223 |
options=[s['session_id'] for s in sessions],
|
| 224 |
format_func=lambda x: f"Chat from {format_session_date(x)}"
|
| 225 |
)
|
| 226 |
-
|
| 227 |
if selected_session and st.button("Load Selected Chat"):
|
| 228 |
with st.spinner("Loading previous chat..."):
|
| 229 |
messages = st.session_state.persistence.load_chat_history(selected_session)
|
| 230 |
if messages:
|
| 231 |
st.session_state.messages = messages
|
| 232 |
-
|
| 233 |
# Load vector store
|
| 234 |
vector_store = st.session_state.persistence.load_vector_store(selected_session)
|
| 235 |
if vector_store:
|
|
@@ -238,14 +243,14 @@ def display_chat_interface():
|
|
| 238 |
st.session_state.current_session_id = selected_session
|
| 239 |
st.rerun()
|
| 240 |
st.markdown('</div>', unsafe_allow_html=True)
|
| 241 |
-
|
| 242 |
st.warning("Please upload documents or select a previous chat to begin.")
|
| 243 |
return
|
| 244 |
-
|
| 245 |
# Initialize chat history
|
| 246 |
if 'messages' not in st.session_state:
|
| 247 |
st.session_state.messages = []
|
| 248 |
-
|
| 249 |
# Display current session info if available
|
| 250 |
if 'current_session_id' in st.session_state:
|
| 251 |
session_date = format_session_date(st.session_state.current_session_id)
|
|
@@ -254,7 +259,7 @@ def display_chat_interface():
|
|
| 254 |
📅 Current Session: {session_date}
|
| 255 |
</div>
|
| 256 |
""", unsafe_allow_html=True)
|
| 257 |
-
|
| 258 |
# Display chat history
|
| 259 |
for message in st.session_state.messages:
|
| 260 |
if isinstance(message, HumanMessage):
|
|
@@ -270,8 +275,7 @@ def display_chat_interface():
|
|
| 270 |
{format_assistant_response(message.content)}
|
| 271 |
</div>
|
| 272 |
""", unsafe_allow_html=True)
|
| 273 |
-
|
| 274 |
-
# Chat input
|
| 275 |
# Chat input
|
| 276 |
if prompt := st.chat_input("Ask about your documents..."):
|
| 277 |
with st.spinner("Analyzing..."):
|
|
@@ -279,22 +283,22 @@ def display_chat_interface():
|
|
| 279 |
if not prompt.strip():
|
| 280 |
st.warning("Please enter a valid question.")
|
| 281 |
return
|
| 282 |
-
|
| 283 |
try:
|
| 284 |
# Create and append human message
|
| 285 |
human_message = HumanMessage(content=prompt)
|
| 286 |
st.session_state.messages.append(human_message)
|
| 287 |
-
|
| 288 |
# Get response from QA system
|
| 289 |
response = st.session_state.qa_system.invoke({
|
| 290 |
"input": prompt,
|
| 291 |
"chat_history": []
|
| 292 |
})
|
| 293 |
-
|
| 294 |
if response:
|
| 295 |
ai_message = AIMessage(content=str(response))
|
| 296 |
st.session_state.messages.append(ai_message)
|
| 297 |
-
|
| 298 |
# Save chat history
|
| 299 |
if 'current_session_id' in st.session_state:
|
| 300 |
st.session_state.persistence.save_chat_history(
|
|
@@ -305,15 +309,20 @@ def display_chat_interface():
|
|
| 305 |
'last_updated': datetime.now().isoformat()
|
| 306 |
}
|
| 307 |
)
|
| 308 |
-
|
| 309 |
st.rerun()
|
| 310 |
else:
|
| 311 |
st.error("No valid response received. Please try again.")
|
| 312 |
-
|
| 313 |
except Exception as e:
|
| 314 |
st.error(f"Error processing response: {str(e)}")
|
|
|
|
| 315 |
st.error(traceback.format_exc())
|
| 316 |
# Remove the failed message attempt
|
| 317 |
if st.session_state.messages:
|
| 318 |
st.session_state.messages.pop()
|
| 319 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
from backend import get_embeddings_model, initialize_qa_system
|
| 6 |
from utils.persistence import PersistenceManager
|
| 7 |
|
| 8 |
+
|
| 9 |
def ensure_embeddings_initialized():
|
| 10 |
"""Ensure embeddings model is initialized in session state."""
|
| 11 |
if 'embeddings' not in st.session_state:
|
|
|
|
| 16 |
return False
|
| 17 |
return True
|
| 18 |
|
| 19 |
+
|
| 20 |
def format_session_date(session_id: str) -> str:
|
| 21 |
"""Format session ID into readable date."""
|
| 22 |
try:
|
|
|
|
| 25 |
date_part = session_id.split('_')[1]
|
| 26 |
else:
|
| 27 |
date_part = session_id
|
| 28 |
+
|
| 29 |
if len(date_part) == 8: # Format: YYYYMMDD
|
| 30 |
return datetime.strptime(date_part, '%Y%m%d').strftime('%B %d, %Y')
|
| 31 |
elif len(date_part) == 14: # Format: YYYYMMDD_HHMMSS
|
|
|
|
| 35 |
except Exception as e:
|
| 36 |
return f"Session: {session_id}" # Fallback display
|
| 37 |
|
| 38 |
+
|
| 39 |
def clean_ai_response(content):
|
| 40 |
"""Clean up AI response content and remove technical artifacts."""
|
| 41 |
content = str(content)
|
| 42 |
+
|
| 43 |
# Remove common technical artifacts
|
| 44 |
if "content='" in content:
|
| 45 |
content = content.split("content='")[1]
|
| 46 |
if "additional_kwargs" in content:
|
| 47 |
content = content.split("additional_kwargs")[0]
|
| 48 |
+
|
| 49 |
# Clean up any remaining artifacts
|
| 50 |
content = content.strip("'")
|
| 51 |
content = content.replace('\\n', '\n')
|
| 52 |
content = content.replace('\\t', '\t')
|
| 53 |
+
|
| 54 |
return content
|
| 55 |
|
| 56 |
+
|
| 57 |
def format_assistant_response(content):
|
| 58 |
"""Format the assistant's response into a structured layout."""
|
| 59 |
try:
|
| 60 |
# Clean the content first
|
| 61 |
content = clean_ai_response(content)
|
| 62 |
+
|
| 63 |
# Identify sections and structure
|
| 64 |
lines = [line.strip() for line in content.split('\n') if line.strip()]
|
| 65 |
formatted_sections = []
|
| 66 |
current_section = []
|
| 67 |
+
|
| 68 |
for line in lines:
|
| 69 |
# Handle bullet points and lists
|
| 70 |
if line.startswith(('•', '-', '*')):
|
|
|
|
| 88 |
formatted_sections.extend(current_section)
|
| 89 |
current_section = []
|
| 90 |
formatted_sections.append(f'<p>{line}</p>')
|
| 91 |
+
|
| 92 |
# Add any remaining content
|
| 93 |
if current_section:
|
| 94 |
if current_section[0] == "<ul>":
|
| 95 |
current_section.append("</ul>")
|
| 96 |
formatted_sections.extend(current_section)
|
| 97 |
+
|
| 98 |
# Build the final HTML
|
| 99 |
formatted_html = f"""
|
| 100 |
<div class="response-content">
|
| 101 |
{''.join(formatted_sections)}
|
| 102 |
</div>
|
| 103 |
"""
|
| 104 |
+
|
| 105 |
return formatted_html
|
| 106 |
except Exception as e:
|
| 107 |
st.error(f"Error formatting response: {str(e)}")
|
| 108 |
return str(content)
|
| 109 |
|
| 110 |
+
|
| 111 |
def display_chat_interface():
|
| 112 |
"""Display modern chat interface with clean formatting."""
|
| 113 |
+
|
| 114 |
# Initialize persistence if needed
|
| 115 |
if 'persistence' not in st.session_state:
|
| 116 |
st.session_state.persistence = PersistenceManager()
|
| 117 |
+
|
| 118 |
# Add custom CSS for modern chat styling
|
| 119 |
st.markdown("""
|
| 120 |
<style>
|
|
|
|
| 123 |
max-width: 800px;
|
| 124 |
margin: auto;
|
| 125 |
}
|
| 126 |
+
|
| 127 |
/* User message */
|
| 128 |
.user-message {
|
| 129 |
background-color: #f0f2f6;
|
|
|
|
| 132 |
margin: 1rem 0;
|
| 133 |
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
|
| 134 |
}
|
| 135 |
+
|
| 136 |
/* Assistant message */
|
| 137 |
.assistant-message {
|
| 138 |
background-color: #ffffff;
|
|
|
|
| 142 |
margin: 1rem 0;
|
| 143 |
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
|
| 144 |
}
|
| 145 |
+
|
| 146 |
/* Response content */
|
| 147 |
.response-content {
|
| 148 |
line-height: 1.6;
|
| 149 |
}
|
| 150 |
+
|
| 151 |
/* Section headers */
|
| 152 |
.section-header {
|
| 153 |
color: #0f52ba;
|
|
|
|
| 157 |
border-bottom: 2px solid #e0e0e0;
|
| 158 |
padding-bottom: 0.5rem;
|
| 159 |
}
|
| 160 |
+
|
| 161 |
/* Lists */
|
| 162 |
.response-content ul {
|
| 163 |
margin: 1rem 0;
|
| 164 |
padding-left: 1.5rem;
|
| 165 |
list-style-type: none;
|
| 166 |
}
|
| 167 |
+
|
| 168 |
.response-content li {
|
| 169 |
margin: 0.5rem 0;
|
| 170 |
position: relative;
|
| 171 |
padding-left: 1rem;
|
| 172 |
}
|
| 173 |
+
|
| 174 |
.response-content li:before {
|
| 175 |
content: "•";
|
| 176 |
position: absolute;
|
| 177 |
left: -1rem;
|
| 178 |
color: #0f52ba;
|
| 179 |
}
|
| 180 |
+
|
| 181 |
/* Paragraphs */
|
| 182 |
.response-content p {
|
| 183 |
margin: 1rem 0;
|
| 184 |
color: #2c3e50;
|
| 185 |
}
|
| 186 |
+
|
| 187 |
/* Source citations */
|
| 188 |
.source-citation {
|
| 189 |
font-style: italic;
|
|
|
|
| 202 |
margin-bottom: 1rem;
|
| 203 |
border: 1px solid #e0e0e0;
|
| 204 |
}
|
| 205 |
+
|
| 206 |
/* Current session info */
|
| 207 |
.session-info {
|
| 208 |
margin-bottom: 1rem;
|
|
|
|
| 214 |
}
|
| 215 |
</style>
|
| 216 |
""", unsafe_allow_html=True)
|
| 217 |
+
|
| 218 |
try:
|
| 219 |
# Check if QA system is initialized
|
| 220 |
if 'qa_system' not in st.session_state or st.session_state.qa_system is None:
|
|
|
|
| 228 |
options=[s['session_id'] for s in sessions],
|
| 229 |
format_func=lambda x: f"Chat from {format_session_date(x)}"
|
| 230 |
)
|
| 231 |
+
|
| 232 |
if selected_session and st.button("Load Selected Chat"):
|
| 233 |
with st.spinner("Loading previous chat..."):
|
| 234 |
messages = st.session_state.persistence.load_chat_history(selected_session)
|
| 235 |
if messages:
|
| 236 |
st.session_state.messages = messages
|
| 237 |
+
|
| 238 |
# Load vector store
|
| 239 |
vector_store = st.session_state.persistence.load_vector_store(selected_session)
|
| 240 |
if vector_store:
|
|
|
|
| 243 |
st.session_state.current_session_id = selected_session
|
| 244 |
st.rerun()
|
| 245 |
st.markdown('</div>', unsafe_allow_html=True)
|
| 246 |
+
|
| 247 |
st.warning("Please upload documents or select a previous chat to begin.")
|
| 248 |
return
|
| 249 |
+
|
| 250 |
# Initialize chat history
|
| 251 |
if 'messages' not in st.session_state:
|
| 252 |
st.session_state.messages = []
|
| 253 |
+
|
| 254 |
# Display current session info if available
|
| 255 |
if 'current_session_id' in st.session_state:
|
| 256 |
session_date = format_session_date(st.session_state.current_session_id)
|
|
|
|
| 259 |
📅 Current Session: {session_date}
|
| 260 |
</div>
|
| 261 |
""", unsafe_allow_html=True)
|
| 262 |
+
|
| 263 |
# Display chat history
|
| 264 |
for message in st.session_state.messages:
|
| 265 |
if isinstance(message, HumanMessage):
|
|
|
|
| 275 |
{format_assistant_response(message.content)}
|
| 276 |
</div>
|
| 277 |
""", unsafe_allow_html=True)
|
| 278 |
+
|
|
|
|
| 279 |
# Chat input
|
| 280 |
if prompt := st.chat_input("Ask about your documents..."):
|
| 281 |
with st.spinner("Analyzing..."):
|
|
|
|
| 283 |
if not prompt.strip():
|
| 284 |
st.warning("Please enter a valid question.")
|
| 285 |
return
|
| 286 |
+
|
| 287 |
try:
|
| 288 |
# Create and append human message
|
| 289 |
human_message = HumanMessage(content=prompt)
|
| 290 |
st.session_state.messages.append(human_message)
|
| 291 |
+
|
| 292 |
# Get response from QA system
|
| 293 |
response = st.session_state.qa_system.invoke({
|
| 294 |
"input": prompt,
|
| 295 |
"chat_history": []
|
| 296 |
})
|
| 297 |
+
|
| 298 |
if response:
|
| 299 |
ai_message = AIMessage(content=str(response))
|
| 300 |
st.session_state.messages.append(ai_message)
|
| 301 |
+
|
| 302 |
# Save chat history
|
| 303 |
if 'current_session_id' in st.session_state:
|
| 304 |
st.session_state.persistence.save_chat_history(
|
|
|
|
| 309 |
'last_updated': datetime.now().isoformat()
|
| 310 |
}
|
| 311 |
)
|
| 312 |
+
|
| 313 |
st.rerun()
|
| 314 |
else:
|
| 315 |
st.error("No valid response received. Please try again.")
|
| 316 |
+
|
| 317 |
except Exception as e:
|
| 318 |
st.error(f"Error processing response: {str(e)}")
|
| 319 |
+
import traceback
|
| 320 |
st.error(traceback.format_exc())
|
| 321 |
# Remove the failed message attempt
|
| 322 |
if st.session_state.messages:
|
| 323 |
st.session_state.messages.pop()
|
| 324 |
+
except Exception as e:
|
| 325 |
+
st.error(f"An unexpected error occurred: {e}")
|
| 326 |
+
import traceback
|
| 327 |
+
st.error(traceback.format_exc())
|
| 328 |
+
|