I looked into various possible solutions:
- OpenAI and Javascript error : Getting 'TypeError: Cannot read properties of undefined (reading 'create') at Object.<anonymous>"
- https://github.com/davila7/code-gpt-docs/issues/57
- https://www.npmjs.com/package/openai
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 message 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 OpenAI API keys
- Update
package.json
OpenAI to the latest version which is4.11.1
- Generally a different console.log code/output & code structure to solve the issue
Can anyone point me in the right direction? Everything works, besides the user input. As a guideline I used this video: https://www.youtube.com/watch?v=4qNwoAAfnk4. I updated the project as far as I could. Why does the user input not work?
Also, the code on my PC has a functioning apiKey
implemented. Thanks for reading!
Changing
console.log(res.data.choices[0].message.content)
toconsole.log(res.choices[0])
orconsole.log(res.choices[0].message.content)
solved the issue and fixed the proper user input feature.