@@ -88,6 +88,14 @@ export default class EasyGpt {
8888 return this ;
8989 }
9090
91+ /**
92+ * Get all the messages in the chat.
93+ * @returns {Array } messages
94+ **/
95+ getMessages ( ) {
96+ return this . #messages. filter ( message => message . role !== "system" ) ;
97+ }
98+
9199 /**
92100 * Removes all rules and previous messages.
93101 * @returns {Object } working instance.
@@ -98,6 +106,39 @@ export default class EasyGpt {
98106 return this ;
99107 }
100108
109+ /**
110+ * Removes all the messages in the chat except for the system rules.
111+ * The below returns the instance so you can chain functions.
112+ * @returns {Object } working instance.
113+ **/
114+ clearChatButRules ( ) {
115+ this . #messages = this . #messages. filter (
116+ message => message . role === "system"
117+ ) ;
118+
119+ return this ;
120+ }
121+
122+ /**
123+ * Sends removes the chat if the max context is exceeded.
124+ * Determines the number the model will consider when generating a response.
125+ * Note that the more context you give the model, the more tokens will be used.
126+ * It will also take longer to generate a response.
127+ * @param {Number } maxContext The max context to allow (in messages).
128+ * @returns {Object } working instance.
129+ **/
130+ clearMessagesIfExceedsMaxContext ( maxContext ) {
131+ // currentContext is the number of interactions with the bot.
132+ const currentContext = Math . floor ( this . getMessages ( ) . length / 2 ) ;
133+
134+ if ( currentContext >= maxContext ) {
135+ console . log ( "Clearing messages" ) ;
136+ this . clearChatButRules ( ) ;
137+ }
138+
139+ return this ;
140+ }
141+
101142 /**
102143 * Import a previous chat.
103144 * ! If the instance has been used before importing the chat, you may want to clear the chat using ```instace.clearChat();```
0 commit comments