NodeJS OpenAI GPT-3 API错误:“找不到模块'@openai/api'”

yxyvkwin  于 2023-04-20  发布在  Node.js
关注(0)|答案(2)|浏览(454)

我在使用Node.js的OpenAI API时遇到了问题。具体来说,我试图使用openai.Completion对象,但我一直收到Cannot find module '@openai/api'错误。
我已经尝试使用npm install @openai/api安装@openai/API包,但我得到一个404错误,表明无法找到该包。我也删除了它并重新安装,但没有运气。
我还尝试升级到Node.js的最新版本,目前是19.1.0,但问题仍然存在。我创建了一个测试脚本(test.js),代码如下:

const openai = require('openai');

openai.apiKey = 'sk-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';

async function runTest() {
    try {
        const gpt3Response = await openai.Completion.create({
            engine: 'davinci-codex',
            prompt: `Create a simple conversational response for beginners, with an easy question at the end, based on the input: "Hello, how are you?"`,
            max_tokens: 50,
            n: 1,
            stop: null,
            temperature: 0.5,
        });
        console.log(gpt3Response.choices[0].text.trim());
    } catch (error) {
        console.error(error);
    }
}

runTest();

当我用node test.js运行这个脚本时,我得到以下错误:

Error: Cannot find module '@openai/api'
Require stack:
- C:\Users\User\Documents\Coding\folders\test.js

我还使用VSC Thunder Client测试了OpenAI API,它似乎可以工作。下面是我使用的POST请求:

POST https://api.openai.com/v1/engines/davinci/completions
{
    "prompt": "do you like soccer",
    "max_tokens": 50,
    "n": 1,
    "stop": null,
    "temperature": 0.5,
    "top_p": 1,
    "echo": false
}

我收到了以下回复:

{
    "id": "cmpl-75BDDTIZ2Q1yodctHcEohCIsA1f46",
    "object": "text_completion",
    "created": 1681469095,
    "model": "davinci",
    "choices": [{
        "text": "?”\n\n“I’m not sure. I’ve never been to a game.”\n\n“I’m going to the game on Saturday. Would you like to go with me?",
        "index": 0,
        "logprobs": null,
        "finish_reason": "length"
    }],
    "usage": {
        "prompt_tokens": 4,
        "completion_tokens": 49,
        "total_tokens": 53
    }
}

您能帮助我了解导致Cannot find module '@openai/api'错误的原因吗?
为我提供了下一个步骤,试图弄清楚为什么这个API不工作。无论是解决方案或进一步的测试,我可以尝试。
谢谢大家!

7nbnzgx9

7nbnzgx91#

您可能安装了openai-api库。这不是正确的库。您可以使用以下命令卸载它:

npm uninstall openai-api

This ↓是正确的库,使用以下命令安装:

npm install openai

你现在会得到额外的错误,因为你的代码中有很多错误。为了帮助你,这是正确的代码:

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

const configuration = new Configuration({
    apiKey: 'sk-xxxxxxxxxxxxxxxxxxxx',
});

const openai = new OpenAIApi(configuration);

async function runTest() {
    try {
        const gpt3Response = await openai.createCompletion({
            model: 'text-davinci-003',
            prompt: `Create a simple conversational response for beginners, with an easy question at the end, based on the input: "Hello, how are you?"`,
            max_tokens: 50,
            n: 1,
            stop: null,
            temperature: 0.5,
        });
        console.log(gpt3Response.data.choices[0].text.trim());
    } catch (error) {
        console.error(error);
    }
}

runTest();
iih3973s

iih3973s2#

你必须在本地安装它

npm i openai

因为Node.js不会在全局文件夹中搜索本地项目的依赖项。全局安装是针对全局可执行文件及其依赖项。

相关问题