Thread.id being treated as object

Hi, I’m having a bit of a nightmare. When trying to connect to the Assistants API my Thread.id is being treated as an object. I have checked and they are all String types.

I know i’m doing something stupid just not 100 what it is as I am new to the API.

Can someone give me a gentle nudge in the right way either in the docs or code example. I did ask GPT as well XD.

require('dotenv').config();
const { OpenAI } = require('openai');
const pino = require('pino');
const logger = pino({ level: 'info' });

const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });

async function interactWithAssistant(assistantId, userQuery) {
    try {
        // Throttle requests needs to be updated to dynamic throttling
        await new Promise(resolve => setTimeout(resolve, 1000));

        // Create empty Thread and get ID
        const threadResponse = await openai.beta.threads.create();
        const thread = threadResponse.id;
       

        // Add a Message to the Thread
        await openai.beta.threads.messages.create(thread, {
            role: "user",
            content: userQuery
        });

        // Run the Assistant
        const run = await openai.beta.threads.runs.create(thread, { assistant_id: assistantId });
        
        let completedRun;
        do {
            // Polling every 1 second before checking the run status again.
            await new Promise(resolve => setTimeout(resolve, 1000));
            completedRun = await openai.beta.threads.runs.retrieve(thread, run.id);
        } while (completedRun.status === 'in_progress');
        
        if (completedRun.status !== 'completed') {
            throw new Error(`Run did not complete successfully. Status: ${completedRun.status}`);
        }

        // Retrieve the Assistant's response
        const messages = await openai.beta.threads.messages.list({
            thread_id: thread
        });
        
        return messages.data.filter(msg => msg.role === 'assistant');
    } catch (error) {
        logger.error({ err: error }, 'An error occurred');
        return null;
    }
}

// Example Usage
const userQuery = "Why are you not working!"; 

interactWithAssistant(process.env.ASSISTANT_ID, userQuery)
    .then(messages => {
        if (messages) {
            messages.forEach(msg => {
                logger.info('Assistant:', msg.content.text.value);
            });
        }
    });

Error:
“error”:{“type”:“Object”,“message”:“No thread found with id ‘function toString() { [native code] }’.”,“stack”:“”,“param”:null,“code”:null},“code”:null,“param”:null},“msg”:“An error occurred”}

Not quite sure what im doing wrong. All help appreciated!

If you don’t mind, I’m going to do a comprehensive review.

  1. Don’t wrap everything in a try/catch during development. It’s common for ChatGPT to write this for you, but it’s not correct (for your situation). You want the program to crash and know the exact line and error. For production you may want to consider wrapping it so you can handle the error yourself but that’s beyond this scope.

// Create empty Thread and get ID
const threadResponse = await openai.beta.threads.create();
const thread = threadResponse.id;

Don’t do this. First of all you’ve now created a misleading variable name that can later cause confusion (threadId would be ideal). Second, you have created a separate source of truth. It’s not necessary. For the sake of ease you should always refer to the object when it is very shallow (or unless you are destructing it to pass elsewhere)

  1. You can use createAndRun to create a thread and run at the same time.

        // Run the Assistant
        const run = await openai.beta.threads.runs.create(thread, { assistant_id: assistantId });
        
        let completedRun;
        do {
            // Polling every 1 second before checking the run status again.
            await new Promise(resolve => setTimeout(resolve, 1000));
            completedRun = await openai.beta.threads.runs.retrieve(thread, run.id);
        } while (completedRun.status === 'in_progress');

There’s a couple things that can be improved here.

  1. You have created an immutable “run” object, only to create another mutable version, why? Keep it simple
  2. A do while is redundant. With a single mutable run object you can begin with a while checking the status.
  3. This is another game-breaking issue. You are only checking for “in_progress”. You should be checking for “queued” as well. If the project is still queued after one second your script will fail. There are also other pathways, but it’s not important for now.

Finally,

        // Retrieve the Assistant's response
        const messages = await openai.beta.threads.messages.list({
            thread_id: thread
        });

You have wrapped the parameters as an object, this is where I am guessing your error is occurring. The correct format is:

  const threadMessages = await openai.beta.threads.messages.list(
    "thread_abc123"
  );

Ultimately I believe you should stop relying on ChatGPT. It has created a lot of loose ends for you (documentation changes a lot and intentions can be misleading). Stick with the documentation, keep posting here and you’ll have some good code in no time

3 Likes

Ahhh! Thank you so much for the valuable feedback I will implement suggestions and repost the code! And thank you for pointing out the {}!

2 Likes

No problem. Happy coding!