使用OpenAI API时遇TypeError: Configuration不是构造函数问题求助
解决OpenAI API调用中
Configuration is not a constructor错误 这个错误是由于OpenAI Node.js SDK版本不兼容导致的:你代码里用的是v3版本的写法,但实际安装的是v4版本的SDK(v4已移除Configuration类)。下面提供两种解决方式:
方式一:降级到OpenAI SDK v3
如果想保留现有代码结构,执行以下命令安装v3版本:
npm install openai@^3
同时注意修正代码里的模型ID错误:gpt-4.0不是有效模型名,改为gpt-4或者gpt-3.5-turbo(根据你有权限使用的模型)。
方式二:升级代码适配SDK v4(推荐)
v4是OpenAI的最新SDK,功能更完善,修改代码如下:
require('dotenv').config(); const OpenAI = require('openai'); const openai = new OpenAI({ apiKey: process.env.OpenAIApi || 'Mykey', }); const createChatCompletion = async () => { try { const response = await openai.chat.completions.create({ model: 'gpt-4', // 修正为有效模型ID messages: [ { role: 'system', content: 'You are a helpful assistant.' }, { role: 'user', content: 'Who won the world series in 2020?' }, { role: 'assistant', content: 'The Los Angeles Dodgers won the World Series in 2020.' }, { role: 'user', content: 'Where was it played?' }, { role: 'assistant', content: 'The World Series was played in Arlington, Texas at the Globe Life Field.' }, ], }); console.log(response.choices[0].message.content); } catch (error) { console.error('Error creating chat completion:', error); } }; createChatCompletion();
关键修改点:
- 移除
Configuration,直接导入OpenAI类并初始化 - 将
openai.createChatCompletion改为openai.chat.completions.create - 修正模型ID为合法值(如
gpt-4、gpt-3.5-turbo)
内容的提问来源于stack exchange,提问作者james_66
相关产品推荐
相关产品推荐

