rdune71 commited on
Commit
f992e80
·
1 Parent(s): cbac037

Fix chat message display issues with two-step processing

Browse files
Files changed (2) hide show
  1. app.py +22 -12
  2. src/ui/chat_handler.py +48 -11
app.py CHANGED
@@ -7,7 +7,7 @@ from datetime import datetime
7
  from pathlib import Path
8
  sys.path.append(str(Path(__file__).parent))
9
 
10
- # Import our new handler
11
  from src.ui.chat_handler import chat_handler
12
  from utils.config import config
13
  from core.session import session_manager
@@ -22,7 +22,9 @@ import logging
22
  logging.basicConfig(level=logging.INFO)
23
  logger = logging.getLogger(__name__)
24
 
25
- # Initialize session state
 
 
26
  if "messages" not in st.session_state:
27
  st.session_state.messages = []
28
  if "is_processing" not in st.session_state:
@@ -33,15 +35,16 @@ if "cosmic_mode" not in st.session_state:
33
  st.session_state.cosmic_mode = True
34
  if "show_welcome" not in st.session_state:
35
  st.session_state.show_welcome = True
36
- if "session_id" not in st.session_state:
37
- st.session_state.session_id = f"sess_{int(time.time())}_{os.urandom(4).hex()}"
38
  if "last_processed_message" not in st.session_state:
39
  st.session_state.last_processed_message = ""
 
 
40
 
41
  # Start session tracking
42
- session_analytics.start_session_tracking("default_user", st.session_state.session_id)
43
-
44
- st.set_page_config(page_title="CosmicCat AI Assistant", page_icon="🐱", layout="wide")
 
45
 
46
  # Log page view
47
  session_analytics.track_interaction("default_user", st.session_state.session_id, "page_view", {
@@ -251,12 +254,12 @@ if st.session_state.show_welcome:
251
  st.markdown(greeting)
252
  st.session_state.show_welcome = False
253
 
254
- # Display conversation history
255
- for message in st.session_state.messages:
256
  with st.chat_message(message["role"]):
257
  st.markdown(message["content"])
258
  if "timestamp" in message:
259
- provider_info = f" (via {message.get('provider', 'unknown')})" if message["role"] == "assistant" else ""
260
  st.caption(f"🕒 {message['timestamp']}{provider_info}")
261
 
262
  # Chat input with enhanced processing
@@ -264,12 +267,19 @@ user_input = st.chat_input("Type your message here...", key="chat_input")
264
 
265
  # Process message when received
266
  if user_input and user_input.strip():
267
- # Prevent processing if already processing
268
- if not getattr(chat_handler, 'is_processing', False):
269
  chat_handler.process_user_message(user_input, selected_model_name)
270
  else:
271
  st.warning("Still processing your previous request...")
272
 
 
 
 
 
 
 
 
273
  # About tab
274
  st.divider()
275
  tab1, = st.tabs(["ℹ️ About"])
 
7
  from pathlib import Path
8
  sys.path.append(str(Path(__file__).parent))
9
 
10
+ # Import modules
11
  from src.ui.chat_handler import chat_handler
12
  from utils.config import config
13
  from core.session import session_manager
 
22
  logging.basicConfig(level=logging.INFO)
23
  logger = logging.getLogger(__name__)
24
 
25
+ st.set_page_config(page_title="CosmicCat AI Assistant", page_icon="🐱", layout="wide")
26
+
27
+ # Initialize session state properly
28
  if "messages" not in st.session_state:
29
  st.session_state.messages = []
30
  if "is_processing" not in st.session_state:
 
35
  st.session_state.cosmic_mode = True
36
  if "show_welcome" not in st.session_state:
37
  st.session_state.show_welcome = True
 
 
38
  if "last_processed_message" not in st.session_state:
39
  st.session_state.last_processed_message = ""
40
+ if "session_id" not in st.session_state:
41
+ st.session_state.session_id = f"sess_{int(time.time())}_{abs(hash(str(time.time()))) % 10000}"
42
 
43
  # Start session tracking
44
+ try:
45
+ session_analytics.start_session_tracking("default_user", st.session_state.session_id)
46
+ except Exception as e:
47
+ logger.warning(f"Analytics session tracking failed: {e}")
48
 
49
  # Log page view
50
  session_analytics.track_interaction("default_user", st.session_state.session_id, "page_view", {
 
254
  st.markdown(greeting)
255
  st.session_state.show_welcome = False
256
 
257
+ # Display existing conversation history
258
+ for message in st.session_state.get("messages", []):
259
  with st.chat_message(message["role"]):
260
  st.markdown(message["content"])
261
  if "timestamp" in message:
262
+ provider_info = f" (via {message.get('provider', 'ollama')})" if message["role"] == "assistant" else ""
263
  st.caption(f"🕒 {message['timestamp']}{provider_info}")
264
 
265
  # Chat input with enhanced processing
 
267
 
268
  # Process message when received
269
  if user_input and user_input.strip():
270
+ # Handle user message display first
271
+ if not st.session_state.get('is_processing', False):
272
  chat_handler.process_user_message(user_input, selected_model_name)
273
  else:
274
  st.warning("Still processing your previous request...")
275
 
276
+ # Handle AI response processing (triggered after user message display)
277
+ if st.session_state.get('is_processing', False) and st.session_state.get('last_processed_message'):
278
+ chat_handler.process_ai_response(
279
+ st.session_state.last_processed_message,
280
+ selected_model_name
281
+ )
282
+
283
  # About tab
284
  st.divider()
285
  tab1, = st.tabs(["ℹ️ About"])
src/ui/chat_handler.py CHANGED
@@ -20,21 +20,22 @@ class ChatHandler:
20
  return
21
 
22
  # Prevent duplicate processing
23
- if hasattr(st.session_state, 'last_processed_message'):
24
- if st.session_state.last_processed_message == user_input:
25
- return
26
-
 
 
27
  st.session_state.last_processed_message = user_input
28
- self.is_processing = True
29
 
30
  try:
31
- # Show user message immediately
32
  timestamp = time.strftime("%H:%M:%S")
33
  with st.chat_message("user"):
34
  st.markdown(user_input)
35
  st.caption(f"🕒 {timestamp}")
36
 
37
- # Add to session state history
38
  if "messages" not in st.session_state:
39
  st.session_state.messages = []
40
 
@@ -44,6 +45,20 @@ class ChatHandler:
44
  "timestamp": timestamp
45
  })
46
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  # Show processing status
48
  with st.chat_message("assistant"):
49
  status_placeholder = st.empty()
@@ -67,32 +82,54 @@ class ChatHandler:
67
  response_placeholder.markdown(response)
68
 
69
  # Add to session history
 
70
  st.session_state.messages.append({
71
  "role": "assistant",
72
  "content": response,
73
- "timestamp": time.strftime("%H:%M:%S"),
74
  "provider": provider_name
75
  })
76
  else:
77
  status_placeholder.warning("⚠️ Empty response received")
78
  response_placeholder.markdown("*No response generated. Please try again.*")
 
 
 
 
 
 
 
79
 
80
  except ProviderNotAvailableError as e:
81
  status_placeholder.error("❌ No AI providers available")
82
  response_placeholder.markdown("No AI providers are configured. Please check your settings.")
 
 
 
 
 
 
83
  logger.error(f"Provider not available: {e}")
84
 
85
  except Exception as e:
86
  status_placeholder.error(f"❌ Error: {str(e)[:100]}...")
87
  response_placeholder.markdown(f"Sorry, I encountered an error: {str(e)[:100]}...")
 
 
 
 
 
 
88
  logger.error(f"Chat processing error: {e}", exc_info=True)
89
 
90
  except Exception as e:
91
- logger.error(f"Unexpected error in process_user_message: {e}", exc_info=True)
92
  st.error("An unexpected error occurred. Please try again.")
93
  finally:
94
- self.is_processing = False
95
- # Force UI refresh
 
 
96
  st.experimental_rerun()
97
 
98
  def _get_provider_for_model(self, selected_model: str) -> str:
 
20
  return
21
 
22
  # Prevent duplicate processing
23
+ if st.session_state.get('last_processed_message') == user_input:
24
+ logger.info("Preventing duplicate message processing")
25
+ return
26
+
27
+ # Set processing flag
28
+ st.session_state.is_processing = True
29
  st.session_state.last_processed_message = user_input
 
30
 
31
  try:
32
+ # Show user message immediately (this was missing!)
33
  timestamp = time.strftime("%H:%M:%S")
34
  with st.chat_message("user"):
35
  st.markdown(user_input)
36
  st.caption(f"🕒 {timestamp}")
37
 
38
+ # Add to session state history immediately
39
  if "messages" not in st.session_state:
40
  st.session_state.messages = []
41
 
 
45
  "timestamp": timestamp
46
  })
47
 
48
+ # Force immediate UI update
49
+ st.experimental_rerun()
50
+
51
+ except Exception as e:
52
+ logger.error(f"Error in initial message display: {e}", exc_info=True)
53
+ st.session_state.is_processing = False
54
+ st.session_state.last_processed_message = ""
55
+
56
+ def process_ai_response(self, user_input: str, selected_model: str):
57
+ """Process AI response after user message is displayed"""
58
+ if not user_input or not user_input.strip():
59
+ return
60
+
61
+ try:
62
  # Show processing status
63
  with st.chat_message("assistant"):
64
  status_placeholder = st.empty()
 
82
  response_placeholder.markdown(response)
83
 
84
  # Add to session history
85
+ timestamp = time.strftime("%H:%M:%S")
86
  st.session_state.messages.append({
87
  "role": "assistant",
88
  "content": response,
89
+ "timestamp": timestamp,
90
  "provider": provider_name
91
  })
92
  else:
93
  status_placeholder.warning("⚠️ Empty response received")
94
  response_placeholder.markdown("*No response generated. Please try again.*")
95
+ timestamp = time.strftime("%H:%M:%S")
96
+ st.session_state.messages.append({
97
+ "role": "assistant",
98
+ "content": "*No response generated. Please try again.*",
99
+ "timestamp": timestamp,
100
+ "provider": provider_name
101
+ })
102
 
103
  except ProviderNotAvailableError as e:
104
  status_placeholder.error("❌ No AI providers available")
105
  response_placeholder.markdown("No AI providers are configured. Please check your settings.")
106
+ timestamp = time.strftime("%H:%M:%S")
107
+ st.session_state.messages.append({
108
+ "role": "assistant",
109
+ "content": "No AI providers are configured. Please check your settings.",
110
+ "timestamp": timestamp
111
+ })
112
  logger.error(f"Provider not available: {e}")
113
 
114
  except Exception as e:
115
  status_placeholder.error(f"❌ Error: {str(e)[:100]}...")
116
  response_placeholder.markdown(f"Sorry, I encountered an error: {str(e)[:100]}...")
117
+ timestamp = time.strftime("%H:%M:%S")
118
+ st.session_state.messages.append({
119
+ "role": "assistant",
120
+ "content": f"Sorry, I encountered an error: {str(e)[:100]}...",
121
+ "timestamp": timestamp
122
+ })
123
  logger.error(f"Chat processing error: {e}", exc_info=True)
124
 
125
  except Exception as e:
126
+ logger.error(f"Unexpected error in process_ai_response: {e}", exc_info=True)
127
  st.error("An unexpected error occurred. Please try again.")
128
  finally:
129
+ # Clear processing flags
130
+ st.session_state.is_processing = False
131
+ st.session_state.last_processed_message = ""
132
+ time.sleep(0.1)
133
  st.experimental_rerun()
134
 
135
  def _get_provider_for_model(self, selected_model: str) -> str: