diff --git a/sgpt/handlers/chat_handler.py b/sgpt/handlers/chat_handler.py index a68a212..2bb7c61 100644 --- a/sgpt/handlers/chat_handler.py +++ b/sgpt/handlers/chat_handler.py @@ -71,13 +71,9 @@ class ChatSession: def _write(self, messages: List[Dict[str, str]], chat_id: str) -> None: file_path = self.storage_path / chat_id - if len(messages) > self.length: - message_role_item = messages[0] - json.dump( - [message_role_item] + messages[-self.length :], file_path.open("w") - ) - return - json.dump(messages[-self.length :], file_path.open("w")) + # Retain the first message since it defines the role + truncated_messages = messages[:1] + messages[1 + max(0, len(messages) - self.length):] + json.dump(truncated_messages, file_path.open("w")) def invalidate(self, chat_id: str) -> None: file_path = self.storage_path / chat_id