开发聊天摘要应用遇TypeError: Cannot read properties of undefined (reading 'create')错误求助
解决OpenAI API调用中的TypeError: Cannot read properties of undefined (reading 'create')错误
你遇到的错误核心原因是OpenAI SDK版本不兼容:你使用的是v4版本的OpenAI SDK,但代码里沿用了v3版本的API调用写法,导致openai.ChatCompletion不存在,进而触发create属性读取失败的错误。
关键修复点:
- 移除冗余的旧版SDK引入代码
- 替换API调用方法为v4版本的正确路径
- 调整请求参数格式(gpt-3.5-turbo要求用
messages数组而非prompt) - 修改响应结果的解析逻辑
修复后的完整代码:
require('dotenv').config(); const express = require('express'); const multer = require('multer'); const ExcelJS = require('exceljs'); const fs = require('fs'); const { OpenAI } = require('openai'); // Initialize express app const app = express(); // Configure multer for file uploads const upload = multer({ dest: 'uploads/' }); // Initialize OpenAI API with configuration const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY }); app.post('/upload', upload.single('file'), async (req, res) => { try { const workbook = new ExcelJS.Workbook(); await workbook.xlsx.readFile(req.file.path); console.log(`File uploaded to: ${req.file.path}`); const worksheet = workbook.getWorksheet(1); // Convert worksheet rows to an array for easier iteration let rows = []; worksheet.eachRow((row, rowNumber) => { rows.push({ row, rowNumber }); }); // Iterate over rows array using a for...of loop to maintain async/await context for (let { row, rowNumber } of rows) { let chatText = row.getCell(1).value; if (chatText) { // Ensure there's text to summarize try { const response = await openai.chat.completions.create({ model: "gpt-3.5-turbo", messages: [ { role: "user", content: `Summarize this chat: ${chatText}` } ], max_tokens: 100, }); let summary = response.choices[0].message.content.trim(); row.getCell(2).value = summary; // Assign the summary to the next column } catch (apiError) { console.error(`Error processing row ${rowNumber}:`, apiError); } } } // Save the workbook with summaries to a new file await workbook.xlsx.writeFile('/Users/ravikumar/ClarabridgeOutput/output.xlsx'); res.send('File processed and summaries added.'); } catch (error) { console.error(error); res.status(500).send('An error occurred while processing the file.'); fs.unlinkSync(req.file.path); // Clean up uploaded file even on error } }); // Choose a port for the server to listen on const PORT = 3000; // Start the server app.listen(PORT, () => { console.log(`Server running on port ${PORT}`); });
额外说明:
- OpenAI v4 SDK将原
ChatCompletion.create改为chat.completions.create,同时响应结构也发生了变化,不再需要.data层级,直接从response.choices中读取结果。 - gpt-3.5-turbo及以上模型要求使用
messages数组传递对话内容,而非单独的prompt参数,这是符合模型设计的标准调用方式。
内容的提问来源于stack exchange,提问作者Ravi Kumar
相关产品推荐
相关产品推荐

