OpenAI Assistants API error: "'Thread' object is not subscriptable"

334 Views Asked by At

I am trying to connect to an existing chat thread with a thread id I have stored in a json file, but I am getting an error using the retrieve command. I am doing this so that it doesn't spam and create threads every time I run my code.

This is the error message produced: Failed to connect to the GPT thread: 'Thread' object is not subscriptable

Here is the relevant function:

def connect_helmsman_gpt():
    config = load_config()
    api_key = config.get("api_key")
    thread_id = config.get("thread_id")
    if thread_id is None:
        print("No thread ID found in config")
        return None, None, None
    
    try:
        client = OpenAI(api_key=api_key)
        thread = client.beta.threads.retrieve(thread_id)
        assistant = client.beta.assistants.retrieve(thread["assistant"])
        return assistant, client, thread
    except Exception as e:
        print(f"Failed to connect to the GPT thread: {e}")
        return None, None, None
1

There are 1 best solutions below

0
Rok Benko On

Problem

The following line caused the 'Thread' object is not subscriptable error:

assistant = client.beta.assistants.retrieve(thread["asst_xxxxxxxxxxxxxxxxxxxxxxxx"])

Solution

Change this...

assistant = client.beta.assistants.retrieve(thread["asst_xxxxxxxxxxxxxxxxxxxxxxxx"])

...to this.

assistant = client.beta.assistants.retrieve("asst_xxxxxxxxxxxxxxxxxxxxxxxx")

Note: That will solve the error, but you want to use the same assistant and the same thread every time you run the code, right? Well, you "merge" the assistant and thread when you run the assistant by passing the thread_id and assistant_id parameters. I suggest you take a look at my YouTube tutorial and code on my GitHub profile regarding this step.


Full code

If you run test.py, the OpenAI API will return the following:

API calls successful.
Thread: Thread(id='thread_xxxxxxxxxxxxxxxxxxxxxxxx', created_at=xxxxxxxxxx, metadata={}, object='thread')
Assistant: Assistant(id='asst_xxxxxxxxxxxxxxxxxxxxxxxx', created_at=xxxxxxxxxx, description=None, file_ids=[], instructions='xxxxx', metadata={}, model='gpt-xxxxx', name='xxxxx', object='assistant', tools=[xxxxx])

test.py

import os
from openai import OpenAI
client = OpenAI()
OpenAI.api_key = os.getenv('OPENAI_API_KEY')

def function():
    thread = client.beta.threads.retrieve("thread_xxxxxxxxxxxxxxxxxxxxxxxx")
    assistant = client.beta.assistants.retrieve("asst_xxxxxxxxxxxxxxxxxxxxxxxx")
    return thread, assistant

result = function()

if result[0] is not None and result[1] is not None:
    print("API calls successful.")
    print("Thread:", result[0])
    print("Assistant:", result[1])
else:
    print("API calls failed.")