Assistant example not working?

Hello - i try to use the Assistant example from openAI using the following code:

from openai import OpenAI
import os
import sys
from dotenv import load_dotenv


if __name__ == '__main__':
  print(f"Program name: {os.path.basename(__file__)}") 
  path = os.path.abspath(os.path.dirname(sys.argv[0]))  

  fn = os.path.join(path, ".env")
  load_dotenv(fn) 
  client = OpenAI(api_key = os.environ.get("CHATGPT_API_KEY"))

  assistant = client.beta.assistants.create(
    name="Math Tutor",
    instructions="You are a personal math tutor. Write and run code to answer math questions.",
    tools=[{"type": "code_interpreter"}],
    model="gpt-4-1106-preview"
  )

  thread = client.beta.threads.create()

  message = client.beta.threads.messages.create(
    thread_id=thread.id,
    role="user",
    content="I need to solve the equation `3x + 11 = 14`. Can you help me?"
  )
  
  run = client.beta.threads.runs.create(
    thread_id=thread.id,
    assistant_id=assistant.id,
    instructions="Please address the user as Jane Doe. The user has a premium account."
  )

  messages = client.beta.threads.messages.list(
    thread_id=thread.id
  )

  print(messages)

But when i output the final messages i only get this output:

SyncCursorPage[ThreadMessage](data=[ThreadMessage(id='msg_RpkUIpFoNA5NYzK0PSbA9LJ6', assistant_id=None, content=[MessageContentText(text=Text(annotations=[], value='I need to solve the equation 3x + 11 = 14. Can you help me?'), type='text')], created_at=1700142149, file_ids=[], metadata={}, object='thread.message', role='user', run_id=None, thread_id='thread_oWed8asQTymdRZMl9sLzGgGR')], object='list', first_id='msg_RpkUIpFoNA5NYzK0PSbA9LJ6', last_id='msg_RpkUIpFoNA5NYzK0PSbA9LJ6', has_more=False)

Where can i find the answer to the question?

1 Like

Once the Run completes, you can list the Messages added by the Assistant to the Thread.

I might be wrong, but I believe you need to wait to receive the response first. This is what I do:

# Wait for the run to complete and get the response
while run.status not in ["completed", "failed"]:
    run = client.beta.threads.runs.retrieve(
        thread_id=thread.id,
        run_id=run.id
    )

# If the run completed successfully, get the latest messages
if run.status == "completed":
    messages = client.beta.threads.messages.list(
        thread_id=thread.id
    )

After this you should be able to print (messages)

Thx a lot - this seems to work with that

1 Like

No problem, GPT-4 wrote it for me anyways :laughing: