skip to Main Content

I looked into various possible solutions:

Here is my code:

import { config } from "dotenv"
config()

// New
import OpenAI from 'openai';
import readline from "readline"

const openai = new OpenAI({
  apiKey: 'My Key', // defaults to process.env["OPENAI_API_KEY"]
});

const userInterface = new readline.createInterface({
    input: process.stdin,
    output: process.stdout

})

userInterface.prompt()
userInterface.on("line", async input => {
    const res = await openai.chat.completions.create({
        model: 'gpt-3.5-turbo',
        messages: [{ role: 'user', content: input}],
    })
    console.log(res.data.choices[0].message.content)
    userInterface.prompt()
})

When I run the code I get the error msg from the title of the post: "TypeError: Cannot read properties of undefined (reading ‘choices’) "

I tried the following to fix the issue:

  • Reload the Window with command:"Developer:Reload.Window"
  • Using different API keys from OpenAI
  • Update package.json OpenAi to the latest version which is 4.11.1
  • Generally a different console.log code/output & code structure to solve the issue

Can anyone pinpoint me in the right direction? Everything works, besides for the user input, as a guideline I used this video: "https://www.youtube.com/watch?v=4qNwoAAfnk4" and updated the project as far as I could, why does the user input not work?

Also, obviously the code on my PC has a functioning apiKey implemented! Thanks for reading!!

2

Answers


  1. Chosen as BEST ANSWER

    Changing console.log(res.data.choices[0].message.content) to console.log(res.choices[0]) or console.log(res.choices[0].message.content) solved the issue and fixed the proper user input feature.


  2. OpenAI NodeJS SDK v4 was released on August 16, 2023, and is a complete rewrite of the SDK. Among other things, there are changes in extracting the message content. See the v3 to v4 migration guide.

    • If you have the OpenAI NodeJS SDK v3:

    import { Configuration, OpenAIApi } from 'openai';
    
    const configuration = new Configuration({
      apiKey: process.env.OPENAI_API_KEY,
    });
    
    const openai = new OpenAIApi(configuration);
    
    const chatCompletion = await openai.createChatCompletion({
      model: 'gpt-3.5-turbo',
      messages: [{ role: 'user', content: 'Hello!' }],
    });
    
    console.log(chatCompletion.data.choices[0].message);
    

    • If you have the OpenAI NodeJS SDK v4:

    import OpenAI from 'openai';
    
    const openai = new OpenAI({
      apiKey: process.env.OPENAI_API_KEY,
    });
    
    const chatCompletion = await openai.chat.completions.create({
      model: 'gpt-3.5-turbo',
      messages: [{ role: 'user', content: 'Hello!'}],
    });
    
    console.log(chatCompletion.choices[0].message); // There's no "data" property
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search