Module 'openai' has no attribute 'Thread'

Hey guys, new coder here.

My python openai sdk is completely up to date but i cant understanding why im still having this issue, im trying to make a thread with the new Assistants API but it keeps telling me thread attribute dosent exist, is there something fundamentally wrong im missing?

Have uninstalled and reinstalled openai, still nothing.

Any ideas what could be going wrong here?

At the moment it is all under the beta namespace. Try:

client = openai.OpenAI()

assistant = client.beta.assistants.create(
...

thread = client.beta.threads.create(
...

Still getting the same issue, just for context here is the updated code. I am making a flask app so that may be part of the issue?


from flask import Flask, request
from twilio.twiml.messaging_response import MessagingResponse
import openai
from dotenv import load_dotenv
import os
import time

# Load environment variables
load_dotenv()

app = Flask(__name__)

# Retrieve environment variables
openai.api_key = os.getenv('OPENAI_API_KEY')

@app.route("/whatsapp", methods=['POST'])
def whatsapp_reply():
    body = request.values.get('Body', None)
    response = MessagingResponse()
    assistant_response = get_assistant_response(body)
    response.message(assistant_response)
    return str(response)

def get_assistant_response(user_message):
    try:
        # Initialize the client
        client = openai.OpenAI(api_key=openai.api_key)

        # Step 1: Create an Assistant using the beta namespace
        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"
        )

        # Step 2: Create a Thread using the beta namespace
        thread = client.beta.threads.create(assistant_id=assistant.id)

        # Step 3: Add a Message to a Thread using the beta namespace
        message = client.beta.threads.messages.create(
            thread_id=thread.id,
            role="user",
            content=user_message
        )

        # Step 4: Run the Assistant using the beta namespace
        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."
        )

        # Blocking call to wait for the run to complete; not recommended for production environments
        while True:
            run_status = client.beta.threads.runs.retrieve(
                thread_id=thread.id,
                run_id=run.id
            )
            if run_status.status == 'completed':
                break
            time.sleep(0.5)  # Adjust the timing as needed for your use case

        # Retrieve all messages from the thread using the beta namespace
        messages = client.beta.threads.messages.list(thread_id=thread.id)
        assistant_messages = [msg.content for msg in messages.data if msg.role == 'assistant']

        return assistant_messages[-1] if assistant_messages else "No response from the assistant."

    except Exception as e:
        print(f"An error occurred: {e}")
        return "I am unable to process your request at the moment."

if __name__ == "__main__":
    app.run(debug=True)

Thx for your reply btw.

Got the exact same issue, can’t get it to work without that error

You shoudld in general try to post your error mesages. Otherwhise is more dificult figure out the solution :slight_smile:

I think in your get_assistant_response function you ned to change this:

  # Step 2: Create a Thread using the beta namespace
  # thread = client.beta.threads.create(assistant_id=assistant.id)
 thread = client.beta.threads.create()

The trhead is (as far as I understand) independent of the assistant. It wors for me with that change.

One more note in case it helps. Usually I load dot env as:

from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())

just to give it more chances to find the env file.

What version of the Openai python sdk do you have? I may have identified the issue, im stuck on v1.3.5. when I should be on v 1.2.3. Even hard uninstalling isnt working and --upgrade openai isnt making any changes, it keeps 1.3.5…

Idk Ill try dmontaners changes and see if it works.

Great idea, didnt think of posting in general I probably should :slight_smile:

Ill try make some changes based on that feedback, and let you know what happens.

Really appreciate your response, thanks a million!

I was on openai==‘1.3.4’ but just upgraded to ‘1.3.6’ and your function sill works fine with that minor chage.

I am on pythton 3.11 and ubunu 22.04… but probably this does not matter.

If you do

pip install -U openai

And it does not upgrade your version it seems that your pip is running under a different version of python or you have some mess in your paths…

Try first:

pip install -UI openai  # Notice the I

and if you are still not upgraded you will have to double check your python and pip setup.

1 Like

These days ago I was trying a web wrapper as you… (but with streamlit not flask)

You can see my backend logic here in case it helps: https://github.com/dmontaner/coach_assistant/blob/main/coach_assistant.py