Dhruv-Ty commited on
Commit
e5c3d7b
·
verified ·
1 Parent(s): f3742d0

Update src/session_state.py

Browse files
Files changed (1) hide show
  1. src/session_state.py +59 -29
src/session_state.py CHANGED
@@ -35,10 +35,11 @@ def initialize_session_state():
35
  # Try to load from database if consultation_id exists
36
  if hasattr(st.session_state, 'consultation_id') and st.session_state.db_client:
37
  try:
38
- db_history = st.session_state.db_client.get_conversation_history(st.session_state.consultation_id)
39
- st.session_state.history = db_history
40
  except Exception as e:
41
  # Silently continue with empty history if database fetch fails
 
42
  pass
43
 
44
  # RAG feature toggle
@@ -70,16 +71,20 @@ def initialize_session_state():
70
 
71
  def add_message_to_history(message):
72
  """
73
- Add a message to the conversation history and persist it to database.
74
 
75
  Args:
76
  message (dict): The message to add to history
77
  """
 
 
 
 
78
  # Add to local history
79
  st.session_state.history.append(message)
80
 
81
  # Persist to database if available
82
- if hasattr(st.session_state, 'db_client') and st.session_state.db_client:
83
  try:
84
  st.session_state.db_client.save_message(
85
  st.session_state.consultation_id,
@@ -88,55 +93,80 @@ def add_message_to_history(message):
88
  except Exception as e:
89
  st.error(f"Failed to save message to database: {str(e)}")
90
 
91
- def get_full_history():
92
  """
93
- Get the complete conversation history from the database.
94
 
 
 
 
95
  Returns:
96
- list: Full conversation history
97
  """
98
- if not hasattr(st.session_state, 'consultation_id'):
99
- print("No consultation_id in session state")
100
  return []
101
 
102
  if not hasattr(st.session_state, 'db_client') or not st.session_state.db_client:
103
- print("No database client available")
104
- return st.session_state.history if hasattr(st.session_state, 'history') else []
105
 
106
  try:
107
  db_history = st.session_state.db_client.get_conversation_history(
108
- st.session_state.consultation_id
109
  )
110
-
111
- # Update the local cache with the database results
112
- st.session_state.history = db_history
113
-
114
- # For debugging
115
- print(f"Retrieved {len(db_history)} messages from database for consultation {st.session_state.consultation_id}")
116
-
117
  return db_history
118
  except Exception as e:
119
  print(f"Failed to retrieve history from database: {str(e)}")
120
-
121
- # Fallback to session state history if database retrieval fails
122
- return st.session_state.history if hasattr(st.session_state, 'history') else []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
 
124
  def end_conversation():
125
  """
126
  End the current conversation and clean up resources.
127
  """
128
- if hasattr(st.session_state, 'db_client') and st.session_state.db_client:
129
  try:
130
- st.session_state.db_client.delete_conversation(
131
- st.session_state.consultation_id
132
- )
133
  except Exception as e:
134
- st.error(f"Failed to delete conversation from database: {str(e)}")
135
 
136
- # Reset session state
137
  st.session_state.history = []
 
138
  st.session_state.consultation_id = str(uuid.uuid4())[:8]
139
-
 
140
  # Create new conversation in database
141
  if hasattr(st.session_state, 'db_client') and st.session_state.db_client:
142
  try:
 
35
  # Try to load from database if consultation_id exists
36
  if hasattr(st.session_state, 'consultation_id') and st.session_state.db_client:
37
  try:
38
+ # Load initial history from DB
39
+ st.session_state.history = load_history_from_db(st.session_state.consultation_id)
40
  except Exception as e:
41
  # Silently continue with empty history if database fetch fails
42
+ print(f"Initial history load failed: {str(e)}")
43
  pass
44
 
45
  # RAG feature toggle
 
71
 
72
  def add_message_to_history(message):
73
  """
74
+ Add a message to the local conversation history and persist it to database.
75
 
76
  Args:
77
  message (dict): The message to add to history
78
  """
79
+ # Ensure history list exists
80
+ if 'history' not in st.session_state:
81
+ st.session_state.history = []
82
+
83
  # Add to local history
84
  st.session_state.history.append(message)
85
 
86
  # Persist to database if available
87
+ if hasattr(st.session_state, 'db_client') and st.session_state.db_client and hasattr(st.session_state, 'consultation_id'):
88
  try:
89
  st.session_state.db_client.save_message(
90
  st.session_state.consultation_id,
 
93
  except Exception as e:
94
  st.error(f"Failed to save message to database: {str(e)}")
95
 
96
+ def load_history_from_db(consultation_id):
97
  """
98
+ Load the complete conversation history from the database for a given consultation_id.
99
 
100
+ Args:
101
+ consultation_id (str): The ID of the consultation to load.
102
+
103
  Returns:
104
+ list: Conversation history from the database, or an empty list on failure.
105
  """
106
+ if not consultation_id:
107
+ print("No consultation_id provided for loading history")
108
  return []
109
 
110
  if not hasattr(st.session_state, 'db_client') or not st.session_state.db_client:
111
+ print("No database client available for loading history")
112
+ return [] # Cannot load from DB, return empty
113
 
114
  try:
115
  db_history = st.session_state.db_client.get_conversation_history(
116
+ consultation_id
117
  )
118
+ print(f"Retrieved {len(db_history)} messages from database for consultation {consultation_id}")
 
 
 
 
 
 
119
  return db_history
120
  except Exception as e:
121
  print(f"Failed to retrieve history from database: {str(e)}")
122
+ return [] # Return empty list on failure
123
+
124
+ # Renamed get_full_history to reflect its purpose (it's now primarily for external use if needed)
125
+ # The main way to get history for display is directly from st.session_state.history
126
+ def get_synced_history_from_db():
127
+ """
128
+ Gets the history from the database and updates the local cache.
129
+ This is for ensuring sync if other processes might have updated the DB.
130
+ For most UI purposes, st.session_state.history should be used directly.
131
+ """
132
+ if not hasattr(st.session_state, 'consultation_id'):
133
+ print("No consultation_id in session state for sync")
134
+ return st.session_state.get('history', [])
135
+
136
+ if not hasattr(st.session_state, 'db_client') or not st.session_state.db_client:
137
+ print("No database client available for sync")
138
+ return st.session_state.get('history', [])
139
+
140
+ try:
141
+ db_history = st.session_state.db_client.get_conversation_history(
142
+ st.session_state.consultation_id
143
+ )
144
+ st.session_state.history = db_history # Sync local cache
145
+ print(f"Synced history: Retrieved {len(db_history)} messages from database for consultation {st.session_state.consultation_id}")
146
+ return db_history
147
+ except Exception as e:
148
+ print(f"Failed to sync history from database: {str(e)}")
149
+ return st.session_state.get('history', [])
150
+
151
 
152
  def end_conversation():
153
  """
154
  End the current conversation and clean up resources.
155
  """
156
+ if hasattr(st.session_state, 'db_client') and st.session_state.db_client and hasattr(st.session_state, 'consultation_id'):
157
  try:
158
+ # Potentially mark conversation as inactive instead of deleting
159
+ # st.session_state.db_client.delete_conversation(st.session_state.consultation_id)
160
+ pass # Placeholder if we decide not to delete immediately
161
  except Exception as e:
162
+ st.error(f"Failed to update conversation status in database: {str(e)}")
163
 
164
+ # Reset session state for a new conversation
165
  st.session_state.history = []
166
+ old_consultation_id = st.session_state.get('consultation_id', 'N/A')
167
  st.session_state.consultation_id = str(uuid.uuid4())[:8]
168
+ print(f"Ended consultation {old_consultation_id}. Starting new consultation: {st.session_state.consultation_id}")
169
+
170
  # Create new conversation in database
171
  if hasattr(st.session_state, 'db_client') and st.session_state.db_client:
172
  try: