OpenAI GPT-3 API错误:为什么NodeJS上的Discord机器人与OpenAI API连接返回404错误?

huangapple go评论72阅读模式
英文:

OpenAI GPT-3 API error: Why does the Discord bot on NodeJS return a 404 error in connection with the OpenAI API?

问题

我正在为Discord创建一个集成了OpenAI模型的机器人,但在发出请求时出现404错误。

我的代码是:

const { Client, GatewayIntentBits } = require('discord.js');
const axios = require('axios');

const client = new Client({
  intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages],
});

const BOT_TOKEN = 'token here';
const OPENAI_TOKEN = 'token here';
const BOT_APPLICATION_ID = 'token here';

client.once('ready', () => {
  console.log('Bot est谩 online!');
  registerSlashCommand();
});

client.on('interactionCreate', async (interaction) => {
  if (!interaction.isCommand()) return;

  if (interaction.commandName === 'ajuda-ai') {
    await interaction.reply('Digite sua mensagem para o GPT-3.');

    const collector = interaction.channel.createMessageCollector({
      filter: (msg) => msg.author.id === interaction.user.id,
    });

    collector.on('collect', async (msg) => {
      if (msg.content.toLowerCase() === '/cancelar') {
        collector.stop();
        interaction.channel.send('A conversa foi cancelada.');
        return;
      }

      interaction.channel.send('Aguarde, estou consultando o GPT-3...');

      try {
        const response = await axios.post('https://api.openai.com/v1/engines/davinci-codex/completions', {
          prompt: msg.content,
          max_tokens: 100,
        }, {
          headers: {
            'Authorization': `Bearer ${OPENAI_TOKEN}`,
            'Content-Type': 'application/json',
          },
        });

        await interaction.followUp(`Resposta do GPT-3: ${response.data.choices[0].text.trim()}`);
      } catch (error) {
        console.error(error);
        await interaction.followUp('Desculpe, ocorreu um erro ao buscar a resposta.');
      }

      collector.stop();
    });
  }
});

async function registerSlashCommand() {
  try {
    const guild = client.guilds.cache.get('1116260407414374493');
    if (!guild) return console.error('N茫o foi poss铆vel encontrar o servidor.');

    await guild.commands.create({
      name: 'ajuda-ai',
      description: 'Inicia uma conversa com o GPT-3.',
    });
    console.log('Comando slash registrado.');
  } catch (error) {
    console.error('Erro ao registrar o comando slash:', error);
  }
}

client.login(BOT_TOKEN);

使用OpenAI API对我来说是新鲜事物,我还在适应中。它不断变化。我测试了一些东西,但没有成功。

在寻求帮助之前,我已经检查了令牌和其他所有内容,以确保没有遗漏任何内容。

英文:

I'm creating a bot for Discord that has integrated the OpenAI model, but it generates a 404 error when making requests.

My code is:

const { Client, GatewayIntentBits } = require('discord.js');
const axios = require('axios');

const client = new Client({
  intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages],
});

const BOT_TOKEN = 'token here';
const OPENAI_TOKEN = 'token here';
const BOT_APPLICATION_ID = 'token here';

client.once('ready', () => {
  console.log('Bot está online!');
  registerSlashCommand();
});

client.on('interactionCreate', async (interaction) => {
  if (!interaction.isCommand()) return;

  if (interaction.commandName === 'ajuda-ai') {
    await interaction.reply('Digite sua mensagem para o GPT-3.');

    const collector = interaction.channel.createMessageCollector({
      filter: (msg) => msg.author.id === interaction.user.id,
    });

    collector.on('collect', async (msg) => {
      if (msg.content.toLowerCase() === '/cancelar') {
        collector.stop();
        interaction.channel.send('A conversa foi cancelada.');
        return;
      }

      interaction.channel.send('Aguarde, estou consultando o GPT-3...');

      try {
        const response = await axios.post('https://api.openai.com/v1/engines/davinci-codex/completions', {
          prompt: msg.content,
          max_tokens: 100,
        }, {
          headers: {
            'Authorization': `Bearer ${OPENAI_TOKEN}`,
            'Content-Type': 'application/json',
          },
        });

        await interaction.followUp(`Resposta do GPT-3: ${response.data.choices[0].text.trim()}`);
      } catch (error) {
        console.error(error);
        await interaction.followUp('Desculpe, ocorreu um erro ao buscar a resposta.');
      }

      collector.stop();
    });
  }
});

async function registerSlashCommand() {
  try {
    const guild = client.guilds.cache.get('1116260407414374493');
    if (!guild) return console.error('Não foi possível encontrar o servidor.');

    await guild.commands.create({
      name: 'ajuda-ai',
      description: 'Inicia uma conversa com o GPT-3.',
    });
    console.log('Comando slash registrado.');
  } catch (error) {
    console.error('Erro ao registrar o comando slash:', error);
  }
}

client.login(BOT_TOKEN);

Working with the OpenAI API is new to me. I'm still adapting. It changes all the time. I've tested some things, but without success.

I checked the tokens and everything before asking for help here to make sure I didn't forget anything.

答案1

得分: 1

问题

所有Engines API端点已被弃用。

OpenAI GPT-3 API错误:为什么NodeJS上的Discord机器人与OpenAI API连接返回404错误?

<br>

解决方案

使用Completions API端点。

将URL从这个...

https://api.openai.com/v1/engines/davinci-codex/completions

...更改为这个。

https://api.openai.com/v1/completions

此外,设置所需的model参数(请参阅官方OpenAI文档):

const response = await axios.post(&#39;https://api.openai.com/v1/completions&#39;, {
  model: &#39;text-davinci-003&#39;,
  prompt: msg.content,
  max_tokens: 100,
}
英文:

Problem

All Engines API endpoints are deprecated.

OpenAI GPT-3 API错误:为什么NodeJS上的Discord机器人与OpenAI API连接返回404错误?

<br>

Solution

Use the Completions API endpoint.

Change the URL from this...

https://api.openai.com/v1/engines/davinci-codex/completions

...to this.

https://api.openai.com/v1/completions

Also, set the model parameter that is required (see the official OpenAI documentation):

const response = await axios.post(&#39;https://api.openai.com/v1/completions&#39;, {
  model: &#39;text-davinci-003&#39;,
  prompt: msg.content,
  max_tokens: 100,
}

huangapple
  • 本文由 发表于 2023年7月6日 13:24:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76625732.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定