OpenAI API调用报错TypeError: 无法读取undefined的'choices'属性求解决
解决OpenAI Node.js SDK v4.11.1的TypeError: Cannot read properties of undefined (reading 'choices')错误
核心问题修复
你遇到的错误根源是OpenAI Node.js SDK v4的响应结构与旧版本(v3及更早)不一致,代码错误使用了旧版本的res.data访问路径。
修改代码中的日志输出行:
// 错误写法 console.log(res.data.choices[0].message.content) // 正确写法 console.log(res.choices[0].message.content)
额外排查方向
- API密钥配置优化:避免硬编码密钥,改用环境变量读取,确保
.env文件中OPENAI_API_KEY配置正确:const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY, // 从环境变量读取密钥 }); - 添加错误捕获:用
try-catch包裹API请求,打印具体错误信息,排查是否存在认证失败、网络问题或API调用限制:userInterface.on("line", async input => { try { const res = await openai.chat.completions.create({ model: 'gpt-3.5-turbo', messages: [{ role: 'user', content: input}], }) console.log(res.choices[0].message.content) } catch (error) { console.error('请求错误详情:', error.response?.data || error.message) } userInterface.prompt() }) - 验证依赖版本:执行
npm list openai命令,确认实际安装的SDK版本确实是4.11.1,若版本不符,执行npm install openai@4.11.1 --force重新安装。
内容的提问来源于stack exchange,提问作者Dimitri Williams
相关产品推荐
相关产品推荐

