GPT4AllをNode.jsから使ってみる

料金を気にしながら、遊び目的でChatGPTを使うのが微妙にストレスだったので、無料&ローカルでも動くGPT4Allを使ってみた。

グラボ非搭載の低スペックPCでも使える軽量チャットAI「GPT4ALL」の使い方まとめ

基本的にこの記事の通りやればサクッと動いた。2017年のインテルiMacでやり取りに数十秒かかるけど、とりあえず遊ぶ分には十分使えそう。

…ならば、Node.jsでも使いたい。

本サイトにTypeScriptから叩くやり方は書いてあったので、それを参考にやってみたら、簡単にできた!

作業環境

macOS Monterey(12.6.5)
Node.js v18.2

Node.jsの設定

  1. npmでGPT4Allをインストール
    npm install gpt4all
  2. とりあえず、簡単なサンプルスクリプトを実行。
    import { GPT4All } from 'gpt4all';
    
    let gpt4all = null;
    const _model = 'gpt4all-lora-quantized';
    
    /*GPT4ALL初期化*/
    const initGPT = async () => {
        gpt4all = new GPT4All(_model, true);
        await gpt4all.init();
        await gpt4all.open();
        console.log(">> GPT Opened");
        askGPT("Hello GPT!")
    }
    
    /*問い合せ実行*/
    const askGPT = async(xQstr) =>{
      console.log(xQstr);
      const xResponse = await gpt4all.prompt(xQstr);
      console.log(">>" + xResponse);
    }
    
    initGPT();

    初回はgpt4allの本体と学習済みモデル(gpt4all-lora-quantized)データがダウンロードされる。4G位あるので恐ろしく時間がかかけど、のんびり待つ。

  3. スクリプトがエラーになる場合、モジュールのimportが機能してない場合が多い。その場合は「package.json」に以下の一行を追加。
    "type":"module"
  4. こんな感じになれば、成功!
     % node sample.js
    >> GPT Opened
    Hello GPT!
    >>Thank you for your input, GPT!
  5. 別の学習済みモデルを利用したければ、ダウンロードして下記ディレクトリに入れ、newする時にモデル名を指定すれば使える。
    /Users/<ユーザー名>/.nomic/

これで、心置きなく、遊べる!!

ラズパイ4 + Node.jsで OLEDディプレイを使う

OLEDモジュールをラズパイ4+Node.js環境で使うための覚え書。

作業環境

作業手順

1.OLEDディプレイを繋ぐ
2.Config画面を開いて、I2Cデバイスとの通信を有効化
$ sudo raspi-config

Interfacing Options -> P5 I2C -> YES

3.ラズパイをリブート
$ sudo reboot
4.I2Cデバイスのアドレスを確認
$ i2cdetect -y 1

     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f
00:          -- -- -- -- -- -- -- -- -- -- -- -- --
10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
30: -- -- -- -- -- -- -- -- -- -- -- -- 3c -- -- --
40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
70: -- -- -- -- -- -- -- --
5.モジュールをインストール

$ npm install raspi-io
$ npm install johnny-five
$ npm install oled-js
$ npm install pngparse png-to-lcd oled-font-5x7
6.スクリプトを作成
const five = require('johnny-five');
const raspi = require('raspi-io').RaspiIO;
const board = new five.Board({
	io: new raspi()
});

const Oled = require('oled-js');
const font = require('oled-font-5x7');

board.on('ready',() => {
	console.log('Connected to OLED, ready.');
	const opts = {
		width: 128,
	    height: 64, 
	    address: 0x3C
	};
	oled = new Oled(board, five, opts);
	oled.clearDisplay();
	oled.setCursor(1, 1);
	oled.writeString(font, 1,"Hello World!", 1, true, 2);
	oled.update();
});
7.スクリプトを実行
$ node ./index.js

おしまい!

参考サイト