Node.js API Call Error: Cannot read properties of undefined (reading 'chat')

Below is the code I currently have. Note that I set the API key in the environment variables. I verified that i’m on v4.28

The error suggests that the chat property is being called on an undefined object within thesendToGPT function

What’s strange is that the code syntax runs fine by itself in a separate directory. But it has issues when integrated into the taskpane.js file in the excel plugin codebase.

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

async function sendToGPT(formula) {
  try {
    const completion = await openai.chat.completions.create({
      messages: [
        { role: "system", content: "You are an assistant." },
        { role: "user", content: `Explain the following excel formula ${formula}.` }],
      model: "gpt-3.5-turbo",
    });
    // displayGPTResponse(responseText); // Function to display the response in your application's UI
    if (completion && completion.data && completion.data.choices && completion.data.choices.length > 0) {
      const responseText = completion.data.choices[0].message.content;
      console.log(responseText);
      displayGPTResponse(responseText); // Function to display the response in your application's UI
    } else {
      console.log('No completion found.');
      displayGPTResponse('No completion found.'); // Handle no completion case
    }
  } catch (error) {
    console.error('Error sending data to GPT:', error);
    displayGPTResponse(`Error: ${error.message}`); // Function to display errors in your application's UI
  }
}

The python library is only at 1.13.x, I believe…

https://platform.openai.com/docs/libraries

Is the 4.28 your python?

This is the OpenAI Node.js package version per openai - npm

1 Like

Ack. Sorry. Drive-By help attempt.

Hopefully someone sees this and can give you a better answer.

We’ve got a lot of great threads here too.

1 Like