@@ -107,19 +107,32 @@ def prune_history(self, session_id, history):
107
107
def clear_history_but_keep_depth (self , session_id : str , depth : int , history ):
108
108
if session_id in history :
109
109
messages = history [session_id ]["messages" ]
110
- # Check if the history is already shorter than the depth
111
- if depth == 0 or len ( messages ) <= depth :
110
+ # If the depth is 0, then clear all history
111
+ if depth == 0 :
112
112
history [session_id ]["messages" ] = []
113
+ history [session_id ]["last_accessed" ] = time .time ()
114
+ return
115
+
116
+ # Check if the history is already shorter than the depth
117
+ if len (messages ) <= depth :
118
+ # Do nothing, since the history is already shorter than the depth
119
+ return
113
120
114
121
# If the message at depth is not a user message, then
115
122
# increment the depth until a user message is found
116
- else :
117
- while depth < len (messages ) and messages [- depth ]["role" ] != "user" :
118
- depth += 1
119
- history [session_id ]["messages" ] = messages [- depth :]
120
-
123
+ while depth < len (messages ) and messages [- depth ]["role" ] != "user" :
124
+ depth += 1
125
+ history [session_id ]["messages" ] = messages [- depth :]
121
126
history [session_id ]["last_accessed" ] = time .time ()
122
127
128
+ # In the unlikely case that the history starts with a non-user message,
129
+ # remove it
130
+ while (
131
+ history [session_id ]["messages" ]
132
+ and history [session_id ]["messages" ][0 ]["role" ] != "user"
133
+ ):
134
+ history [session_id ]["messages" ].pop (0 )
135
+
123
136
def handle_timer_event (self , timer_data ):
124
137
if timer_data ["timer_id" ] == "history_cleanup" :
125
138
self .history_age_out ()
0 commit comments