我在我的 MERN 堆栈代码文件中有如下代码,并且运行良好。
exports.chatbot = async (req, res) => { console.log("OpenAI Chatbot Post"); const { textInput } = req.body; try { const response = await openai.createCompletion({ model: "text-davinci-003", prompt: ` What is your name? My name is Chatbot. How old are you? I am 900 years old. ${textInput}`, max_tokens: 100, temperature: 0, }); if (response.data) { if (response.data.choices[0].text) { return res.status(200).json(response.data.choices[0].text); } } } catch (err) { return res.status(404).json({ message: err.message }); }};
当我更改 API 请求,使用新的 Chat Completions API 时,这个就不工作了。
exports.chatbot = async (req, res) => { console.log("OpenAI Chatbot Post"); const { textInput } = req.body; try { const completion = await openai.createChatCompletion({ model: "gpt-3.5-turbo", messages: [{ role: "user", content: textInput }], }); console.log(completion.data.choices[0].message); if (completion.data) { if (completion.data.choices[0].message) { return res.status(200).json(completion.data.choices[0].message); } } } catch (err) { return res.status(404).json({ message: err.message }); }};
我得到的错误是:
POST http://localhost:3000/api/openai/chatbot 404 (Not Found)
回答:
你需要重新安装 openai npm 包。这个包在过去两天内才刚刚更新了 createChatCompletion 功能。
当我重新安装了这个包并运行你的代码后,它成功运行了。