ChatGPT API 通过 .env 调用使用 Nodejs 编写的 Discord 聊天机器人

问题描述 投票:0回答:1

我在尝试获取此代码来调用 .env 文件中的 OPENAI_API_KEY 时遇到问题。我对 Nodejs 非常陌生,所以请像我是个白痴一样跟我说话。将错误粘贴在代码后面的底部。另外,第一次在 stackoverflow 上发帖,所以……你知道……教我如何发布不烦人的帖子。非常感谢您的任何和所有帮助,并感谢您的宝贵时间。

代码:

require('dotenv').config();
const { OpenAIApi } = require('openai');

// Initialize OpenAI API client with the API key from your .env file
const openaiClient = new OpenAIApi(process.env.OPENAI_API_KEY);


/**
 * Generates a response using ChatGPT-4 Turbo based on the provided user input.
 * @param {string} userInput - The user's message input.
 * @returns {Promise<string>} - The generated response from ChatGPT-4 Turbo.
 */
async function generateResponse(userInput) {
  try {
    console.log('Sending input to OpenAI API:', userInput);
    const response = await openaiClient.createChatCompletion({
      model: "gpt-4-turbo",
      messages: [{
        role: "user",
        content: userInput
      }],
    });

    if (response.data.choices && response.data.choices.length > 0) {
      console.log('Received response from OpenAI API');
      return response.data.choices[0].message.content;
    } else {
      console.log('No response from OpenAI API.');
      throw new Error('No response from OpenAI API');
    }
  } catch (error) {
    console.error('Failed to generate response from OpenAI API:', error.message, error.stack);
    throw error; // Rethrow to handle it in the calling function
  }
}

module.exports = { generateResponse };

错误:

L:\ai projects\gpt-pilot\workspace\JS-Rock_Bot\chatService.js:5
const openaiClient = new OpenAIApi(process.env.OPENAI_API_KEY);
                     ^

TypeError: OpenAIApi is not a constructor
    at Object.<anonymous> (L:\ai projects\gpt-pilot\workspace\JS-Rock_Bot\chatService.js:5:22)
    at Module._compile (node:internal/modules/cjs/loader:1376:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
    at Module.load (node:internal/modules/cjs/loader:1207:32)
    at Module._load (node:internal/modules/cjs/loader:1023:12)
    at Module.require (node:internal/modules/cjs/loader:1235:19)
    at require (node:internal/modules/helpers:176:18)
    at Client.<anonymous> (L:\ai projects\gpt-pilot\workspace\JS-Rock_Bot\bot.js:34:30)
    at Client.emit (node:events:518:28)
    at MessageCreateAction.handle (L:\ai projects\gpt-pilot\workspace\JS-Rock_Bot\node_modules\discord.js\src\client\actions\MessageCreate.js:28:14)

Node.js v20.11.1

尝试改变方式

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

被称为是因为我认为我的代码已经过时但不知道我在做什么。

node.js discord openai-api
1个回答
0
投票

第 1 步:安装最新的 OpenAI Node.js SDK

您在上面的评论中说您想使用最新的语法。因此,首先,请确保您安装了最新的 OpenAI Node.js SDK。运行以下命令:

npm install openai@latest

截至今天,

v4.29.0
是最新的。在继续之前,请通过运行以下命令检查版本:

npm view openai version

您应该在终端中看到

4.29.0

第 2 步:修复代码

您的代码中有多个错误,但您还不知道它们,因为初始化是引发的第一个错误。修复这个错误后,才会抛出下一个错误。

OpenAI Node.js SDK >=

v4
(即,包括最新的)有很多重大更改。其中,也是初始化导致了你的错误。但正如我所说,你的代码中有更多错误。

以下是使用 OpenAI Node.js SDK 的正确初始化 >=

v4
:

const OpenAI = require("openai");

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

以下是使用 OpenAI Node.js SDK 的正确方法名称 >=

v4
:

openai.chat.completions.create

以下是使用 OpenAI Node.js SDK 的正确消息检索 >=

v4
:

response.choices[0].message.content

完整代码

require('dotenv').config();
const OpenAI = require("openai");

// Initialization
const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

async function generateResponse(userInput) {
  try {
    console.log('Sending input to OpenAI API:', userInput);
    const response = await openai.chat.completions.create({ // Method name
      model: "gpt-4-turbo",
      messages: [{
        role: "user",
        content: userInput
      }],
    });

    if (response.choices && response.choices.length > 0) {
      console.log('Received response from OpenAI API');
      return response.choices[0].message.content; // Message retrieval
    } else {
      console.log('No response from OpenAI API.');
      throw new Error('No response from OpenAI API');
    }
  } catch (error) {
    console.error('Failed to generate response from OpenAI API:', error.message, error.stack);
    throw error;
  }
}

module.exports = { generateResponse };
© www.soinside.com 2019 - 2024. All rights reserved.