admin管理员组文章数量:1631723
ChatGPT风靡全球,本周,OpenAI发布了ChatGPT API。我花了一些时间在浏览器中使用 ChatGPT,但真正适应这些新功能的最好方法是尝试使用它构建一些东西。有了可用的 API,现在是时候了。
。我想我会从尝试构建相同的聊天机器人开始,但使用 JavaScript。
事实证明,Node.js 需要比 Python 更多的代码来处理命令行输入,所以 Grag 的版本是 16 行,而我的版本需要 31 行。构建了这个小机器人后,我对使用此 API 构建的潜力同样感到兴奋。
这是完整的代码。我将进一步解释它在做什么。
import { createInterface } from "node:readline/promises";
import { stdin as input, stdout as output, env } from "node:process";
import { Configuration, OpenAIApi } from "openai";
const configuration = new Configuration({ apiKey: env.OPENAI_API_KEY });
const openai = new OpenAIApi(configuration);
const readline = createInterface({ input, output });
const chatbotType = await readline.question(
"What type of chatbot would you like to create? "
);
const messages = [{ role: "system", content: chatbotType }];
let userInput = await readline.question("Say hello to your new assistant.\n\n");
while (userInput !== ".exit") {
messages.push({ role: "user", content: userInput });
try {
const response = await openai.createChatCompletion({
messages,
model: "gpt-3.5-turbo",
});
const botMessage = response.data.choices[0].message;
if (botMessage) {
messages.push(botMessage);
userInput = await readline.question("\n" + botMessage.content + "\n\n");
} else {
userInput = await readline.question("\nNo response, try asking again\n");
}
} catch (error) {
console.log(error.message);
userInput = await readline.question("\nSomething went wrong, try asking again\n");
}
}
readline.close();
构建聊天机器人
您需要一个OpenAI平台帐户才能与ChatGPT API进行交互。注册后,从您的帐户仪表板创建 API 密钥。
只要你安装了 Node.js,你唯一需要的就是 o
版权声明:本文标题:使用 ChatGPT API 和节点创建 CLI 聊天机器人.js 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dianzi/1729101769a1186672.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论