1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【備忘録】Node.jsからGemini APIを叩く

Posted at

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
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?