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,你唯一需要的就是 openai Node.js 模块。

让我们启动一个 Node.js 项目并创建此 CLI 应用程序。首先为项目创建一个目录,切换到它,然后用 npm 初始化它:

mkdir chatgpt-cli
cd chatgpt-cli
npm init --yes

将模块安装为依赖项:openai

npm install openai

打开并将密钥添加到配置中,这样我们就可以将其构建为 ES 模块,这将允许我们使用顶级 await。package.json"type": "module"

创建一个名为的文件并在编辑器中打开它。index.js

与 OpenAI API 交互

代码有两个部分:在命令行上处理输入和输出,以及处理OpenAI API。让我们先来看看 API 是如何工作的。

首先,我们从模块中导入两个对象,即 和 。该类将用于创建保存 API 密钥的配置,然后可以使用该配置创建客户端。openaiConfigurationOpenAIApiConfigurationOpenAIApi

import { env } from "node:process";
import { Configuration, OpenAIApi } from "openai";

const configuration = new Configuration({ apiKey: env.OPENAI_API_KEY });
const openai = new OpenAIApi(configuration);

在这种情况下,我们将 API 密钥存储在环境中并使用 .env.OPENAI_API_KEY

为了与 API 交互,我们现在使用 OpenAI 客户端为我们创建聊天完成。OpenAI的文本生成模型实际上并不与您交谈,而是为接受输入并提出听起来合理的文本而构建的,这些文本将遵循该输入,即完成。使用 ChatGPT,模型配置为接收消息列表,然后完成对话。此系统中的消息可以来自 3 个不同的实体之一,即“系统”、“用户”和“助手”。“助手”是 ChatGPT 本身,“用户”是交互的人,系统允许程序(或用户,如我们将在本例中看到的那样)提供定义助手行为方式的指令。更改系统提示助手的行为方式是最有趣的事情之一,它允许您创建不同类型的助手。

如上所述配置我们的对象后,我们可以创建消息以发送给助手并请求如下响应:openai

const messages = [
  { role: "system", content: "You are a helpful assistant" },
  { role: "user", content: "Can you suggest somewhere to eat in the centre of London?" }
];
const response = await openai.createChatCompletion({
  messages,
  model: "gpt-3.5-turbo",
});
console.log(response.data.choices[0].message);
// => "Of course! London is known for its diverse and delicious food scene..."

随着对话的进行,我们可以将用户的问题和助手的响应添加到消息数组中,我们在每个请求中发送这些消息数组。这为机器人提供了对话的历史记录,以及它可以建立进一步答案的上下文。

要创建 CLI,我们只需要将其连接到终端中的用户输入。

与终端交互

Node.js 提供 Readline 模块,可以轻松接收输入和将输出写入流。要使用终端,这些流将是 和 .stdinstdout

我们可以从模块导入和从模块导入,将它们重命名为并使它们更易于与 Readline 一起使用。我们还从stdinstdoutnode:processinputoutputcreateInterfacenode:readline

import { createInterface } from "node:readline/promises";
import { stdin as input, stdout as output } from "node:process";

然后我们将 and streams 传递给,这给了我们一个对象,我们可以用来写入输出并从输入中读取,所有这些都使用 question 函数:inputoutputcreateInterface

const readline = createInterface({ input, output });

const chatbotType = await readline.question(
  "What type of chatbot would you like to create? "
);

上面的代码挂接了输入和输出流。然后,该对象用于将问题发布到输出并返回承诺。当用户通过写入终端并按回车键进行回复时,承诺将使用用户编写的文本进行解析。readline

完成命令行界面

有了这两个部分,我们就可以编写所有代码。创建一个名为的新文件并输入下面的代码。index.js

我们从上面描述的导入开始:

import { createInterface } from "node:readline/promises";
import { stdin as input, stdout as output, env } from "node:process";
import { Configuration, OpenAIApi } from "openai";

然后我们初始化 API 客户端和 Readline 模块:

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 }];

然后,我们提示用户开始与聊天机器人交互并启动一个循环,该循环表示,当用户输入不等于字符串“.exit”时,继续将该输入发送到API。如果用户输入“.exit”,程序将结束,就像在 Node.js REPL 中一样。

let userInput = await readline.question("Say hello to your new assistant.\n\n");

while (userInput !== ".exit") {
  // loop
}

readline.close();

在循环中,我们将 作为“用户”消息添加到消息数组中。然后,在try/catch块中,将其发送到OpenAI API。我们将模型设置为“gpt-3.5-turbo”,这是 ChatGPT 的基础名称。userInput

当我们从 API 获得响应时,我们会从数组中获取消息。如果有消息,我们将其作为“助手”消息存储在消息数组中,并将其输出给用户,使用 readline 再次等待他们的输入。如果来自 API 的响应中没有消息,我们会提醒用户并等待进一步的用户输入。最后,如果向 API 发出请求时出错,我们会捕获错误,记录消息并告诉用户重试。response.data.choices

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"
    );
  }
}

把这些放在一起,你就有了你的助手。完整的代码在这篇文章的顶部或GitHub上。

现在,您可以通过在命令行上将 OpenAI API 密钥作为环境传递给助手来运行该助手:

OPENAI_API_KEY=YOUR_API_KEY node index.js

这将开始你与助手的互动,从询问你想要什么样的助手开始。一旦你声明了这一点,你就可以开始和它聊天了。

实验有助于我们理解

就个人而言,我实际上不确定ChatGPT有多大用处。这显然令人印象深刻;它返回文本的能力就像是人类编写的一样令人难以置信。但是,它返回的内容不一定正确,无论它呈现该内容的自信程度如何。

尝试使用 ChatGPT 是我们尝试了解它用途的唯一方法,因此构建像这样的简单聊天机器人为我们提供了该实验的基础。了解系统命令可以赋予机器人不同的个性并使其以不同的方式响应是非常有趣的。

例如,您可能听说过,您可以要求 ChatGPT 帮助您进行编程,但您也可以指定 JSON 结构并有效地将其用作 API。但是当你尝试这样做时,你可能会发现它不应该是一个信息API,而更有可能是可以用来理解你的自然文本并将其转换为JSON对象的东西。对我来说,这很令人兴奋,因为这意味着ChatGPT可以帮助创建更自然的语音助手,可以比期望以更精确的方式发出命令的现有作物更好地翻译语音的含义。我仍然在尝试这个想法,拥有这个工具给了我这个机会。

更多推荐

使用 ChatGPT API 和节点创建 CLI 聊天机器人.js