🙌

Gemini API を node で使うときには @google/generative-ai がよい。

2024/12/28に公開

TL;DR;

パッケージ名にGeminiがついていないが、@google/generative-ai を選んでおけばよいと思う。

Gemini

LLMには色々出ていますが、Geminiにも良いところがたくさんあります。他LLMとの比較は他に譲りますが、GoogleのLLMであるGeminiを使うことも選択肢に入れてみてはいかがでしょう?

@google/generative-ai の利用方法

ほぼ、リポジトリに説明が書いてありますが、日本語の情報も役に立つ事があると考えるため、記載していきます。

鍵の取得

Google AI Studioの「Get API Key」から鍵を取得します。

Httpによる実行方式もCURLを使った例として表示されています。簡単に使うのであれば、ライブラリ無しでGeminiを使うのも良いと考えます。

Code作成。

プロジェクトを初期化して、

mkdir geminiInspect && cd $_
npm init -y
npm i @google/generative-ai
npm i ts-node

コードを作成します。

index.ts
import { GoogleGenerativeAI } from "@google/generative-ai";
(async() => {
const genAI = new GoogleGenerativeAI(process.env.API_KEY!);
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });

const prompt = "Gemini をTypeScriptで使うのも簡単ですか?";

const result = await model.generateContent([prompt]);
console.log(result.response.text());
})();

環境によっては、tsconfig.json が必要です。念の為おいておきます。

tsconfig.json
{
  "compilerOptions": {
    "target": "es2016",
    "module": "commonjs",
    "types": ["node"],
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  }
}

これで、コマンド実行すれば、Geminiを呼ぶことができます。簡単ですね。

API_KEY=Google AI Studioで取得したAPIキー npx ts-node index.ts

Discussion