英文:
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端点已被弃用。
<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('https://api.openai.com/v1/completions', {
  model: 'text-davinci-003',
  prompt: msg.content,
  max_tokens: 100,
}
英文:
Problem
All Engines API endpoints are deprecated.
<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('https://api.openai.com/v1/completions', {
  model: 'text-davinci-003',
  prompt: msg.content,
  max_tokens: 100,
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。



评论