在 Node.js 中使用 OpenAI API 时遇到基本的 Await 错误。我该如何修复?

我直接从 OpenAI 的示例中复制了代码,结果却得到了一个初级的 Await JS 错误,但我不知道它期望我做什么。我只是想启动一个 Express.js 实例,并从 openapi(最终是 chatgpt)那里得到一个“hello world”的回应。Web 服务器本身运行正常。

这是我的代码:

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)

错误信息如下:

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

原始的 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);

回答:

如前所述,您需要将异步代码包装在一个函数中:

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)

另外,请确保您有一个包含适当依赖项的 package.json 文件:

{  "name": "sample",  "version": "1.0.0",  "description": "",  "main": "index.js",  "author": "",  "license": "ISC",  "dependencies": {    "express": "^4.18.2",    "openai": "^3.1.0"  }}

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注