Skip to content

Commit 202eddf

Browse files
committed
chore: Add some protection around clearing the history to make sure the first message is never a non-user message.
1 parent 09bacb7 commit 202eddf

File tree

1 file changed

+20
-7
lines changed

1 file changed

+20
-7
lines changed

src/solace_ai_connector/components/general/openai/openai_chat_model_with_history.py

+20-7
Original file line numberDiff line numberDiff line change
@@ -107,19 +107,32 @@ def prune_history(self, session_id, history):
107107
def clear_history_but_keep_depth(self, session_id: str, depth: int, history):
108108
if session_id in history:
109109
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:
112112
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
113120

114121
# If the message at depth is not a user message, then
115122
# 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:]
121126
history[session_id]["last_accessed"] = time.time()
122127

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+
123136
def handle_timer_event(self, timer_data):
124137
if timer_data["timer_id"] == "history_cleanup":
125138
self.history_age_out()

0 commit comments

Comments
 (0)