Node.jsからGemini APIを叩く方法について。
フォルダ・ファイル構成
test
├─ node_modules
├─ package.json
├─ package-lock.json
└─ test.mjs
※コマンドにて生成されるフォルダ・ファイルあり
手順
APIキー作成
Google AI StudioにてAPIキーを作成する。
「test」フォルダ作成
「test」フォルダを作成する。
Node.jsプロジェクト初期化及びインストール
コマンドプロンプトにて以下を実行する。
npm init
npm install @google/generative-ai
「test.mjs」ファイル作成
「test.mjs」ファイルを作成する。
import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI("xxxxxここに作成したAPIキーを貼り付けxxxxx");
// APIキーが外部に流出しないよう注意してください。
async function run() {
const model = genAI.getGenerativeModel({ model: "gemini-2.5-flash" });
const result = await model.generateContent("シベリアンハスキーの魅力を教えて。");
const response = result.response;
console.log(response.text());
}
run();
実行
コマンドプロンプトにて以下を実行する。
node test.mjs