Choices property of OpenAI is not working

The following code to extract the response is not working with node.js. Maybe the OpenAI new package has changes that I’m unable to locate. Highly appreciate it if someone could help. Please see below scenario details.

Code snippet:
const { OpenAI } = require(‘openai’);

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

async function main( ) => {
try {
const response = await openai.chat.completions.create({
model: ‘gpt-3.5-turbo’,
messages: [
{ “role”: “system”, “content”: “What is the process to test a metal?”},
{ “role”: “user”, “content”: prompt }
]
});

let content = response.data.choices[0].message.content;

return {
  status: 1,
  response: content
};

} catch (error) {
console.error('Error from OpenAI : ', error.message);
return {
status: 0,
response: ‘’
};
}
};

The error message shown in the console:

Error from OpenAI : Cannot read properties of undefined (reading ‘choices’)

Hi and welcome to the Developer Forum!

Could be that there are other errors being masked by that response, try this code to dig a little deeper, possibly the API key is not being set correctly (need to do a test with it hard coded in to test that)

const { OpenAI } = require('openai');

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

async function main(prompt) {
  try {
    const response = await openai.chat.completions.create({
      model: 'gpt-3.5-turbo',
      messages: [
        { "role": "system", "content": "What is the process to test a metal?"},
        { "role": "user", "content": prompt }
      ]
    });

    // Log the whole API response to troubleshoot the format.
    console.log('API Response: ', response);

    // Check if the expected data exists before trying to access it.
    if (response && response.data && response.data.choices && response.data.choices.length > 0) {
      let content = response.data.choices[0].message.content;

      return {
        status: 1,
        response: content
      };
    } else {
      throw new Error('Unexpected API response format.');
    }
  } catch (error) {
    console.error('Error from OpenAI : ', error.message);
    return {
      status: 0,
      response: ''
    };
  }
};

Thank you so much for the feedback. So I’ve re-written the following code as per your instructions :

const { OpenAI } = require(‘openai’);
require(‘dotenv’).config();

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

const chatCompletion = async (prompt) => {
try {
const response = await openai.chat.completions.create({
model: ‘gpt-3.5-turbo’,
messages: [
{ “role”: “user”, “content”: prompt }
]
});

// Log the whole API response to troubleshoot the format.
console.log('API Response: ', response);

// Check if the expected data exists before trying to access it.
if (response && response.data && response.data.choices && response.data.choices.length > 0) {
  let content = response.data.choices[0].message.content;
  console.log('This is the response : ', content);

  return {
    status: 1,
    response: content
  };
} else {
  throw new Error('Unexpected API response format.');
}

} catch (error) {
console.error('Error from OpenAI : ', error.message);
return {
status: 0,
response: ‘’
};
}
};
module.exports = {
chatCompletion
};

And I received the following errors:

API Response: {
id: ‘chatcmpl-85YwSetzuHIvJiqEiSGAKcmLk8yL7’,
object: ‘chat.completion’,
created: 1696336648,
model: ‘gpt-3.5-turbo-0613’,
choices: [ { index: 0, message: [Object], finish_reason: ‘stop’ } ],
usage: { prompt_tokens: 21, completion_tokens: 524, total_tokens: 545 }
}
Error from OpenAI : Unexpected API response format.

Hi,

I’m sorry. I made a slight mistake when sending the last reply. I have now edited and corrected it. Please note that I’m sending a simple ‘Hello’ as the prompt.

Thanks!

Hey there,

Please be informed that it is working again and now it’s fine. Thanks!

3 Likes