漂亮的命令行交互工具 clack 与 ChatGPT 集成

3,622 阅读2分钟

clack 被设计成一个类似于时间线的漂亮的 cli 交互工具。

地址:www.clack.cc/

本文介绍: clack 的基本用法,以及集成 ChatGPT 的聊天工程

image.png

clack 工程化分析

  • 整体上,使用 pnpm workspace 管理 clack 项目,
  • 以下是依赖:

@clack/core

// @clack/core
"dependencies": {
    "picocolors": "^1.0.0",
    "sisteransi": "^1.0.5"
},

代码层面使用 class 来管理 prompt 代码。

@clack/prompts

// @clack/prompts
"dependencies": {
    "@clack/core": "^0.3.2",
    "picocolors": "^1.0.0",
    "sisteransi": "^1.0.5"
},

构建工具: unbuild, 底层使用 rollup 作为打包工具。使用 build.config.ts 做配置文件。

示例

demo-in-stackblitz.png

官方示例

  • basic 一个简单关于 npm 相关的示例。
  • changesets 一个使用包版本管理示例。

项目推荐

  • itpls 一个 基于 git/degit 的github clone 库,可以方便的从 github 下载,使用 clack 进行交互。

clack prompt 与 ChatGPT api 进行交互对话

注意指定 dotenv 的命令:需要 OPENAI_API_KEY 的 key。

#!/usr/bin/env node

import { Command } from "commander";

import {clackChat} from './main.js'

const program = new Command();

program
  .command("start")
  .option("-r --role <role>", "输入角色", "")
  .action(async () => {
    clackChat()
  });

program.parse(process.argv);

聊天

import * as p from "@clack/prompts";
import chalk from "chalk";
import { runCompletion } from './runCompletion.js'
import {config} from 'dotenv'

config()

export async function clackChat() {
  console.clear();

  p.intro(chalk.bgCyan(chalk.black("聊天已经开始了")));

  const createInput = async (placeholder = "") => {
    const inputText = await p.text({
      message: "提示:请输入...",
      placeholder,
      initialValue: "",
      validate(value) {
        if (value.length === 0) return `Value is required!`;
      },
    });

    const s = p.spinner();
    s.start('思考中...');

    if (p.isCancel(inputText)) {
      p.cancel('Operation cancelled');
      s.stop('');
      return process.exit(0);
    }

    const resText = await runCompletion(inputText)
    s.stop('');
    console.log()
    console.log(resText)
    console.log()
    createInput()
  };

  createInput("对什么感兴趣呢?")
}

runCompletion 发送请求获取响应数据

import fetch from "node-fetch";

export async function runCompletion(messages) {
  const response = await fetch(
    "https://api.openai-proxy.com/v1/chat/completions",
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: "Bearer " + process.env.OPENAI_API_KEY,
      },
      body: JSON.stringify({
        model: "gpt-3.5-turbo",
        messages: [{ role: "user", content: messages }],
      }),
    }
  ).then((res) => res.json())
  return await response.choices[0].message.content;
}

package.json 指定命令配合 npm link 启动

"bin": {
    "clack-chat": "./src/index.js"
  },

项目地址

clack-chat: clack prompt with chat gpt (github.com)

创建 env 环境变量,添加 OPENAI_API_KEY, 然后通过 node.js 启动 或者 npm unlink 之后再启动。以下是效果(timeline 的效果类似):

clack-chat.png

小结

clack 主打 timeline 风格的样式,支持不同风格的 prompts。然后使用 命令 commander + - @clack/prompts 实现一个在 terminal 中简单对话的应用。

更多

微信搜索并关注公踪号 进二开物,更多技术 JS/TS/CSS/Rust 文章...