User message/content is not changed when running thread through python class

I am creating Tea_GPT class with the help of documentation and YouTube:

from openai import OpenAI
import time as TIME
client = OpenAI()

class Tea_GPT:
  ROLE="user"
  MESSAGES=None
  CLIENT=None
  THREAD=None
  RUN=None
  def __init__(self):
    self.ASSISTANT_ID = "asst_5G****************Hr"
    if self.CLIENT is None:
      self.__client_create()
  
  def __client_create(self):
    _open_ai = OpenAI()
    self.CLIENT = _open_ai.beta.threads

  # Step 2 (Loop to add message)
  def add_message(self, message): 
    message = message or "Ask Random Question"
    self.THREAD = self.CLIENT.create(
      messages=[{
        "role": self.ROLE,
        "content": message,
      }]
    )
    self.RUN = self.CLIENT.runs.create(
      thread_id=self.THREAD.id,
      assistant_id=self.ASSISTANT_ID
    )
    self.__run_retrieve()
    return self

  # Step 3b
  def __run_retrieve(self):
    _run = self.RUN
    while _run.status != "completed":
      TIME.sleep(3)
      _run = self.CLIENT.runs.retrieve(
        run_id=_run.id,
        thread_id=self.THREAD.id
      )
      print(f"{self.THREAD.id=} {_run.id=} {_run.status=}")

    self.RUN = _run
    return self

  # Step 4
  def get_messages(self):
    self.MESSAGES = self.CLIENT.messages.list(
      thread_id=self.THREAD.id
    )

    return self
  
  def __str__(self):
    return "WIP"
    ...

  def __repr__(self):
    return "WIP"
    ...

  def print_messages(self):
    if self.MESSAGES is None:
      self.get_messages()
    for _m in reversed(self.MESSAGES.data):
      print(f"{_m.role}: {_m.content[0].text.value}")

When I initiate class to get response for a message, I get proper response.

For example I would get two different responses (contextual) for MSG1 and MSG2 from below code

_res = HIB_GPT()
_res.add_message("MSG1: Green tea recipe with Lemon.")
_res.print_messages()


_res = HIB_GPT()
_res.add_message("MSG2: Green tea recipe with Honey.")
_res.print_messages()

However if I run the following code, I would get response for MSG1 only everytime. I am getting new thread.id and run.id but getting response for the first text piece (MSG1) only. Subsequent messages provided through threads.create(user... content="MSG2") part like MSG2, MSG3 are not taken into account.

_res = HIB_GPT()

_res.add_message("MSG1: Green tea recipe with Lemon.")
_res.print_messages()

_res.add_message("MSG2: Green tea recipe with Honey.")
_res.print_messages()



Any idea if I am missing something here, like I am not overriding some variable? Or how can I update user content before run and retrieve process?

I’d suggest starting out by getting the example use case working without the added complexity of the class approach and then later you can encapsulate your code if it makes sense.

Your code is tough to read at the moment. For example:

def print_messages(self):
    if self.MESSAGES is None:
      self.get_messages()
    for _m in reversed(self.MESSAGES.data):
      print(f"{_m.role}: {_m.content[0].text.value}")

I started with individual function without class and it was working as expected. When I converted it to class to follow the workflow of add thread messagerunretrieve after initiating the class once. But I have to initiate it again and again.

Thank you for your reply.

Post a full example if possible, can try to replicate the issue.

I don’t even know what a “Tea_GPT” would be.

Probably not this one that succumbs to a one-line jailbreak where I didn’t even state “ChatGPT”…

image

That code is painful. A few runs through an AI to fix.

from openai import OpenAI

class TeaGPT:
    def __init__(self):
        self.role = "user"
        self.messages = None
        self.client = OpenAI()

        self.thread = None
        self.run = None
        self.assistant_id = None  # You might set this later when you have the assistant ID
  
    def send_message(self, message=None): 
        message = message or "Ask Random Question"
        try:
            if self.assistant_id is None:
                print("Assistant ID not set. Unable to send message.")
                return

            self.thread = self.client.beta.threads.create(
                messages=[{
                    "role": self.role,
                    "content": message,
                }]
            )
            self.run = self.client.beta.runs.create(
                thread_id=self.thread.id,
                assistant_id=self.assistant_id
            )
            self.__retrieve_run_status()
        except Exception as e:
            print(f"Error sending message: {e}")

    def __retrieve_run_status(self):
        try:
            run = self.run
            while run.status != "completed":
                time.sleep(3)
                run = self.client.beta.runs.retrieve(
                    run_id=run.id,
                    thread_id=self.thread.id
                )
                self.__log_status(run)
            self.run = run
        except Exception as e:
            print(f"Error retrieving run status: {e}")

    def __log_status(self, run):
        print(f"{self.thread.id=} {run.id=} {run.status=}")

    def get_messages(self):
        try:
            if self.thread is None:
                print("No thread available. Unable to get messages.")
                return

            self.messages = self.client.beta.messages.list(
                thread_id=self.thread.id
            )
        except Exception as e:
            print(f"Error getting messages: {e}")
  
    def print_messages(self):
        try:
            if self.messages is None:
                self.get_messages()
            for _m in reversed(self.messages.data):
                print(f"{_m.role}: {_m.content[0].text.value}")
        except Exception as e:
            print(f"Error printing messages: {e}")

You should only add a single user message to a thread at a time. Then execute a run to allow the AI assistant to answer that query. That way you have user/assistant exchanges in your thread chat.

I am testing out ChatGPT assistant API to allow users to get answers from file. This example class is just a demo before I actually implement the class.

The code I posted works fine but the problem is when I run the following quote (expecting to add_message once and retrieve the message)

_res = Tea_GPT()

_res.add_message("Green tea recipe with Honey.")
_res.print_messages()

_res.add_message("Green tea recipe with Lemon.")
_res.print_messages()

It’s response is

Here two different queries (Q1 & Q2) are being added but in the repsonse (R1 & R2) only first query is responded. Looks like first query is stored permanently somewhere.