OpenAI API in node gives basic Await error. How do I fix?
题意:OpenAI API 在 Node 中出现基本的 Await 错误。我该如何修复?
问题背景:
I literally copied the code from the openAI example and it gives me a remedial Await JS error but I am unsure what it expects me to do. I just want to spin up an Express.js instance and get a hello world from openapi (eventually chatgpt). The web server works fine.
我照搬了 OpenAI 示例中的代码,但出现了基本的 Await JS 错误,我不确定它希望我怎么做。我只是想启动一个 Express.js 实例,并从 OpenAI(最终是 ChatGPT)获取一个 Hello World。网络服务器运行正常
Here is my code: 以下是我的代码
const express = require('express')
const app = express()
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
apiKey: "my key is here"
});
const openai = new OpenAIApi(configuration);
const completion = await openai.createCompletion({
model: "text-davinci-002",
prompt: "Hello world",
});
console.log(completion.data.choices[0].text);
app.get('/', function (req, res) {
res.send('Hello World')
})
app.listen(3000)
Error: 以下是错误信息
SyntaxError: await is only valid in async functions and the top level bodies of modules
at Object.compileFunction (node:vm:360:18)
at wrapSafe (node:internal/modules/cjs/loader:1088:15)
at Module._compile (node:internal/modules/cjs/loader:1123:27)
at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
at Module.load (node:internal/modules/cjs/loader:1037:32)
at Module._load (node:internal/modules/cjs/loader:878:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:23:47
The original OpenAI example code is the same. Why the hell is this the example code?
原始的 OpenAI 示例代码是一样的。这为什么还是示例代码
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
const completion = await openai.createCompletion({
model: "text-davinci-002",
prompt: "Hello world",
});
console.log(completion.data.choices[0].text);
问题解决:
As already mentioned, you need to wrap your async code in a function:
如前所述,你需要将异步代码封装在一个函数中
const express = require('express')
const app = express()
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
apiKey: "my key is here"
});
const openai = new OpenAIApi(configuration);
const completionFunction = async () => {
const completion = await openai.createCompletion({
model: "text-davinci-002",
prompt: "Hello world",
});
console.log(completion.data.choices[0].text);
};
completionFunction();
app.get('/', function (req, res) {
res.send('Hello World')
})
app.listen(3000)
Also, make sure you have a package.json
file with the appropriate dependencies:
此外,请确保你有一个包含适当依赖项的 package.json
文件
{
"name": "sample",
"version": "1.0.0",
"description": "",
"main": "index.js",
"author": "",
"license": "ISC",
"dependencies": {
"express": "^4.18.2",
"openai": "^3.1.0"
}
}