NodeJS 打开AI示例代码不工作“Await仅在异步函数和模块的顶层主体中有效”

ws51t4hk  于 2022-12-18  发布在  Node.js
关注(0)|答案(2)|浏览(209)

如果这看起来很简单,我很抱歉,我对这个相对来说是新手。
正如标题中所说,我得到了错误“等待只在异步函数和模块的顶级主体中有效”,尽管我很困惑,因为等待是在主体的顶部?

const { Configuration, OpenAIApi } = require("openai");

const configuration = new Configuration({
  apiKey: 'Api Key Go Brrrrrr',
});
const openai = new OpenAIApi(configuration);

const response = await openai.createCompletion("text-davinci-002", {
  prompt: "You: What have you been up to?\nFriend: Watching old movies.\nYou: Did you watch anything interesting?\nFriend:",
  temperature: 0.5,
  max_tokens: 60,
  top_p: 1.0,
  frequency_penalty: 0.5,
  presence_penalty: 0.0,
  stop: ["You:"],
});
00jrzges

00jrzges1#

您可以将代码 Package 在异步IIFE中:

// add ; at the start to be safe, this is one of the very few cases where semicolons matter in JS
;(async ()=>{
const response = await openai.createCompletion("text-davinci-002", {
  prompt: "You: What have you been up to?\nFriend: Watching old movies.\nYou: Did you watch anything interesting?\nFriend:",
  temperature: 0.5,
  max_tokens: 60,
  top_p: 1.0,
  frequency_penalty: 0.5,
  presence_penalty: 0.0,
  stop: ["You:"],
});
})();
62o28rlo

62o28rlo2#

如果您可以将代码更改为python,这可能会有所帮助:https://pypi.org/project/openai-async/
只要做到:

pip install openai-async

然后例如:

import openai_async

response = await openai_async.complete(
    "<API KEY>",
    timeout=2,
    payload={
        "model": "text-davinci-003",
        "prompt": "Correct this sentence: Me like you.",
        "temperature": 0.7,
    },
)
print(response.json()["choices"][0]["text"].strip()) # Output: "I like you."

相关问题