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

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

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错误。

我的代码是:

  1. const { Client, GatewayIntentBits } = require('discord.js');
  2. const axios = require('axios');
  3. const client = new Client({
  4. intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages],
  5. });
  6. const BOT_TOKEN = 'token here';
  7. const OPENAI_TOKEN = 'token here';
  8. const BOT_APPLICATION_ID = 'token here';
  9. client.once('ready', () => {
  10. console.log('Bot est谩 online!');
  11. registerSlashCommand();
  12. });
  13. client.on('interactionCreate', async (interaction) => {
  14. if (!interaction.isCommand()) return;
  15. if (interaction.commandName === 'ajuda-ai') {
  16. await interaction.reply('Digite sua mensagem para o GPT-3.');
  17. const collector = interaction.channel.createMessageCollector({
  18. filter: (msg) => msg.author.id === interaction.user.id,
  19. });
  20. collector.on('collect', async (msg) => {
  21. if (msg.content.toLowerCase() === '/cancelar') {
  22. collector.stop();
  23. interaction.channel.send('A conversa foi cancelada.');
  24. return;
  25. }
  26. interaction.channel.send('Aguarde, estou consultando o GPT-3...');
  27. try {
  28. const response = await axios.post('https://api.openai.com/v1/engines/davinci-codex/completions', {
  29. prompt: msg.content,
  30. max_tokens: 100,
  31. }, {
  32. headers: {
  33. 'Authorization': `Bearer ${OPENAI_TOKEN}`,
  34. 'Content-Type': 'application/json',
  35. },
  36. });
  37. await interaction.followUp(`Resposta do GPT-3: ${response.data.choices[0].text.trim()}`);
  38. } catch (error) {
  39. console.error(error);
  40. await interaction.followUp('Desculpe, ocorreu um erro ao buscar a resposta.');
  41. }
  42. collector.stop();
  43. });
  44. }
  45. });
  46. async function registerSlashCommand() {
  47. try {
  48. const guild = client.guilds.cache.get('1116260407414374493');
  49. if (!guild) return console.error('N茫o foi poss铆vel encontrar o servidor.');
  50. await guild.commands.create({
  51. name: 'ajuda-ai',
  52. description: 'Inicia uma conversa com o GPT-3.',
  53. });
  54. console.log('Comando slash registrado.');
  55. } catch (error) {
  56. console.error('Erro ao registrar o comando slash:', error);
  57. }
  58. }
  59. 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:

  1. const { Client, GatewayIntentBits } = require('discord.js');
  2. const axios = require('axios');
  3. const client = new Client({
  4. intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages],
  5. });
  6. const BOT_TOKEN = 'token here';
  7. const OPENAI_TOKEN = 'token here';
  8. const BOT_APPLICATION_ID = 'token here';
  9. client.once('ready', () => {
  10. console.log('Bot está online!');
  11. registerSlashCommand();
  12. });
  13. client.on('interactionCreate', async (interaction) => {
  14. if (!interaction.isCommand()) return;
  15. if (interaction.commandName === 'ajuda-ai') {
  16. await interaction.reply('Digite sua mensagem para o GPT-3.');
  17. const collector = interaction.channel.createMessageCollector({
  18. filter: (msg) => msg.author.id === interaction.user.id,
  19. });
  20. collector.on('collect', async (msg) => {
  21. if (msg.content.toLowerCase() === '/cancelar') {
  22. collector.stop();
  23. interaction.channel.send('A conversa foi cancelada.');
  24. return;
  25. }
  26. interaction.channel.send('Aguarde, estou consultando o GPT-3...');
  27. try {
  28. const response = await axios.post('https://api.openai.com/v1/engines/davinci-codex/completions', {
  29. prompt: msg.content,
  30. max_tokens: 100,
  31. }, {
  32. headers: {
  33. 'Authorization': `Bearer ${OPENAI_TOKEN}`,
  34. 'Content-Type': 'application/json',
  35. },
  36. });
  37. await interaction.followUp(`Resposta do GPT-3: ${response.data.choices[0].text.trim()}`);
  38. } catch (error) {
  39. console.error(error);
  40. await interaction.followUp('Desculpe, ocorreu um erro ao buscar a resposta.');
  41. }
  42. collector.stop();
  43. });
  44. }
  45. });
  46. async function registerSlashCommand() {
  47. try {
  48. const guild = client.guilds.cache.get('1116260407414374493');
  49. if (!guild) return console.error('Não foi possível encontrar o servidor.');
  50. await guild.commands.create({
  51. name: 'ajuda-ai',
  52. description: 'Inicia uma conversa com o GPT-3.',
  53. });
  54. console.log('Comando slash registrado.');
  55. } catch (error) {
  56. console.error('Erro ao registrar o comando slash:', error);
  57. }
  58. }
  59. 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从这个...

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

...更改为这个。

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

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

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

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...

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

...to this.

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

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

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

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:

确定