题意:尝试在Node.js中使用OpenAI SDK时遇到错误
问题背景:
I am trying to use Openai api with nodejs, I follow the tutorial and want to add a simple gpt text completion feauture using the openai SDK, but I got an error says: /node_modules/openai/core.js:44 const isJSON = contentType?.includes('application/json') || contentType?.includes('application/vnd.api+json');
尝试在 Node.js 中使用 OpenAI API,并遵循了相关教程,希望使用 OpenAI SDK 添加一个简单的 GPT 文本补全功能。但是,我遇到了一个错误,该错误指向 node_modules/openai/core.js
文件的第 44 行,其中使用了可选链操作符(?.
),但 Node.js 环境似乎不支持它
It results in a crash of the app, I didn't find out why.
这导致应用程序崩溃,我没有找出原因。
This is the code: 这是代码:
import OpenAI from 'openai';
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
export const gptResponse = async (req, res) => {
try {
const { message } = req.body;
const getResponse = await openai.chat.completions.create({
model: 'gpt-3.5-turbo',
messages: [
{
role: 'system',
content: 'You are a helpful assistant.',
},
{
role: 'user',
content: message,
},
],
});
console.log(getResponse.data.choices[0].message.content);
return res.json(getResponse.data.choices[0].message.content);
} catch (err) {
console.log(err);
return res.status(400).send('Error. Try again.');
}
};
问题解决:
This code will work. 代码正常运行
Save as `demo.js' 另存为文件 demo.js
import OpenAI from 'openai';
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
const requestData = {
model: 'gpt-3.5-turbo',
messages: [
{
role: 'system',
content: 'You are a helpful assistant.',
},
{
role: 'user',
content: 'Hello!',
},
],
};
async function getGPTResponse() {
try {
const response = await openai.chat.completions.create(requestData);
console.log("Response from OpenAI:", response.choices[0].message.content);
} catch (error) {
console.error("Error:", error.message);
}
}
getGPTResponse();
In package.json
{
"type": "module",
"dependencies": {
"openai": "^4.28.0"
}
}
Install dependencies 安装依赖
npm install
Run it 运行
node demo.js
Result 结果
Confirm by Postman
You can see the response message's hierarchy
您可以看到响应消息的层级结构
url
POST https://api.openai.com/v1/chat/completions
In body
{
"model": "gpt-3.5-turbo",
"messages": [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "Hello!"
}
]
}
insufficient permissions cases
权限不足的情况
#1 Read Only API_KEY
Error 错误信息
Error: 401 You have insufficient permissions for this operation. Missing scopes: model.request
#2 Model capabilities Write API_KEY
#2 模型功能 写入 API_KEY
No Error 没有错误
#3 All Permissions API_KEY
#3 所有权限 API_KEY
标签:Node,use,const,tried,js,content,API,openai,OpenAI From: https://blog.csdn.net/suiusoar/article/details/141083833