diff --git a/MAVProxy/modules/mavproxy_chat/chat_openai.py b/MAVProxy/modules/mavproxy_chat/chat_openai.py index 0fd5d3bd3c..50e5d02c45 100644 --- a/MAVProxy/modules/mavproxy_chat/chat_openai.py +++ b/MAVProxy/modules/mavproxy_chat/chat_openai.py @@ -84,6 +84,12 @@ def check_connection(self): print("chat: failed to connect to OpenAI assistant") return False + # To initialize existing thread id + assistant_thread_id_existing = None + + # Check for existing thread + if assistant_thread_id_existing is not None : + self.assistant_thread = self.client.beta.threads.retrieve(assistant_thread_id_existing) # create new thread if self.assistant_thread is None: self.assistant_thread = self.client.beta.threads.create() @@ -99,6 +105,32 @@ def set_api_key(self, api_key_str): self.assistant = None self.assistant_thread = None + # get the old thread and messages + def get_old_msg(self): + with self.send_lock: + + # check connection + if not self.check_connection(): + return "chat: failed to connect to OpenAI" + + # retrieve messages on the thread + reply = "" + reply_messages = self.client.beta.threads.messages.list(self.assistant_thread.id, + order="asc", + limit=20) + + if reply_messages is None: + return "chat: failed to retrieve messages" + + need_newline = False + for message in reply_messages.data: + reply = reply + message.content[0].text.value + if need_newline: + reply = reply + "\n" + need_newline = True + + return reply + # send text to assistant def send_to_assistant(self, text): # get lock diff --git a/MAVProxy/modules/mavproxy_chat/chat_window.py b/MAVProxy/modules/mavproxy_chat/chat_window.py index 23e273bbef..8a9c87058e 100644 --- a/MAVProxy/modules/mavproxy_chat/chat_window.py +++ b/MAVProxy/modules/mavproxy_chat/chat_window.py @@ -107,6 +107,13 @@ def apikey_set_button_click(self, event): self.chat_voice_to_text.set_api_key(self.apikey_text_input.GetValue()) self.apikey_frame.Hide() + # initially place all old messages + orig_text_attr = self.text_reply.GetDefaultStyle() + old_msgs = self.chat_openai.get_old_msg() + if old_msgs : + wx.CallAfter(self.text_reply.SetDefaultStyle, orig_text_attr) + wx.CallAfter(self.text_reply.AppendText, old_msgs + "\n\n") + # API key close button clicked def apikey_close_button_click(self, event): self.apikey_frame.Hide()