Discord机器人集成OpenAI gpt-3.5-turbo遇400错误求助
问题:Discord机器人集成OpenAI无法获取ChatGPT响应
已完成的排查步骤:
- 确认API密钥正确
- 确认组织ID正确
- 确认用户交互的prompt可正常获取
- OpenAI账号拥有截至6月1日的18美元试用余额,且无消费记录
相关代码:
//ChatGPT Config const { Configuration, OpenAIApi } = require("openai"); const configuration = new Configuration({ organization: "org-MyORGID", apiKey: process.env.GPT_KEY, }); const openai = new OpenAIApi(configuration); //discord interaction async execute(interaction) { try { console.log(process.env.GPT_KEY); //确认API密钥并打印到控制台 const prompt = interaction.options.getString('prompt'); //获取用户输入的prompt console.log(prompt); //记录用户的prompt const response = await openai.createCompletion({ model: 'gpt-3.5-turbo', prompt: prompt, maxTokens: 1000, n: 1, stop: ['\n'] }); await interaction.deferReply({ ephemeral: false }); await wait(6000); const message = response.choices[0].text.trim(); console.log(message); //应该记录GPT生成的内容 await interaction.editReply({ content: `你输入的内容是:${prompt} \n\nChatGPT回复:${message}`}); } catch (error) { console.error(error); await interaction.deferReply({ ephemeral: false }); await interaction.editReply({ content: `错误:OpenAI API当前无响应,请稍后重试`}); } } };
错误信息:
0|Bot | Error: Request failed with status code 400 0|Bot | at createError (/dev/Bot/node_modules/axios/lib/core/createError.js:16:15)
怀疑问题出在这段代码:
const response = await openai.createCompletion({ model: 'gpt-3.5-turbo', prompt: prompt, maxTokens: 1000, n: 1, stop: ['\n'] });
解决方案
核心问题是调用了错误的API方法:gpt-3.5-turbo属于Chat系列模型,必须使用createChatCompletion方法,而非针对文本补全模型的createCompletion,同时参数结构也有区别。
1. 修改API调用代码
将原有的createCompletion替换为createChatCompletion,并把prompt参数改为messages数组(定义对话角色和内容):
const response = await openai.createChatCompletion({ model: 'gpt-3.5-turbo', messages: [ { role: 'user', content: prompt } ], max_tokens: 1000, //注意参数名是下划线分隔的max_tokens,不是驼峰式的maxTokens n: 1, stop: ['\n'] });
2. 修改响应内容的获取方式
Chat模型的响应结构和文本补全模型不同,需要调整取值路径:
const message = response.data.choices[0].message.content.trim();
3. 优化交互时序
建议在发起API请求前就调用deferReply,避免Discord因交互超时判定失败:
async execute(interaction) { try { await interaction.deferReply({ ephemeral: false }); //提前发送延迟回复 console.log(process.env.GPT_KEY); const prompt = interaction.options.getString('prompt'); console.log(prompt); // 后续API调用和回复逻辑... } catch (error) { // 错误处理... } }
内容的提问来源于stack exchange,提问作者RasmonT
相关产品推荐
相关产品推荐

