google-gemini-api について
google-gemini-api は、現行の @google/genai SDK と Gemini への REST リクエストを解説する開発者向けスキルです。テキスト生成、マルチモーダル入力、関数呼び出しなどを扱います。
主な機能
- 01テキスト生成とストリーミング
- 02画像、動画、音声、PDFの入力
- 03並列実行に対応した関数呼び出し
- 04システム指示と複数ターンのチャット
- 05コンテキストキャッシュ、コード実行、Google 検索による grounding
活用シーン
- 01Node.js アプリでのテキスト生成
- 02Gemini リクエストでのメディアや文書の処理
- 03モデルの応答と外部関数の連携
- 04エッジランタイムでの REST リクエスト利用
インストール
コマンドをコピーしてターミナルで実行します。
npx skills add https:/ / github.com/ jackspace/ claudeskillz --skill google-gemini-apiインストール後、Claude Code で/google-gemini-apiを入力して読み込まれたか確認します。
同梱ファイルREADME.mdSKILL.json
詳細
Google Gemini API - 完全ガイド
バージョン:Phase 2 完了 ✅ パッケージ:@google/[email protected] (⚠️ @google/generative-ai ではありません) 最終更新日:2025-10-25
⚠️ SDK の重大な移行に関する警告
非推奨の SDK:@google/generative-ai (2025 年 11 月 30 日に提供終了)
現在の SDK:@google/genai v1.27+
@google/generative-ai を使用するコードを見つけた場合、そのコードは古くなっています!
このスキルでは、現在の正しい SDK を使用し、完全な移行ガイドを提供します。
ステータス
✅ Phase 1 完了:
- ✅ テキスト生成(基本およびストリーミング)
- ✅ マルチモーダル入力(画像、動画、音声、PDF)
- ✅ 関数呼び出し(基本および並列実行)
- ✅ システム指示と複数ターンのチャット
- ✅ 思考モードの設定
- ✅ 生成パラメーター(temperature、top-p、top-k、停止シーケンス)
- ✅ Node.js SDK (@google/genai) と fetch の両方の方法
✅ Phase 2 完了:
- ✅ コンテキストキャッシュ(TTL ベースのキャッシュによるコスト最適化)
- ✅ コード実行(組み込みの Python インタープリターとサンドボックス)
- ✅ Google 検索によるグラウンディング(リアルタイムのウェブ情報と引用)
📦 個別のスキル:
- 埋め込み:text-embedding-004 については
google-gemini-embeddingsスキルを参照してください
目次
Phase 1 - コア機能:
Phase 2 - 高度な機能: 12. コンテキストキャッシュ 13. コード実行 14. Google 検索によるグラウンディング
共通リファレンス: 15. エラー処理 16. レート制限 17. SDK 移行ガイド 18. 本番環境でのベストプラクティス
クイックスタート
インストール
正しい SDK:
npm install @google/[email protected]
❌ 間違い(非推奨):
npm install @google/generative-ai # DO NOT USE!
環境設定
export GEMINI_API_KEY="..."
または .env ファイルを作成します:
GEMINI_API_KEY=...
最初のテキスト生成(Node.js SDK)
import { GoogleGenAI } from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: 'Explain quantum computing in simple terms'
});
console.log(response.text);
最初のテキスト生成(fetch - Cloudflare Workers)
const response = await fetch(
`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-goog-api-key': env.GEMINI_API_KEY,
},
body: JSON.stringify({
contents: [{ parts: [{ text: 'Explain quantum computing in simple terms' }] }]
}),
}
);
const data = await response.json();
console.log(data.candidates[0].content.parts[0].text);
現在のモデル(2025)
Gemini 2.5 シリーズ(一般提供)
gemini-2.5-pro
- コンテキスト:入力トークン 1,048,576 個 / 出力トークン 65,536 個
- 説明:複雑な推論に対応する最先端の思考モデル
- 最適な用途:コード、数学、STEM、複雑な問題解決
- 機能:思考モード(デフォルトでオン)、関数呼び出し、マルチモーダル、ストリーミング
- 知識のカットオフ:2025 年 1 月
gemini-2.5-flash
- コンテキスト:入力トークン 1,048,576 個 / 出力トークン 65,536 個
- 説明:価格と性能のバランスに優れた主力モデル
- 最適な用途:大規模処理、低レイテンシ、高ボリューム、エージェント型のユースケース
- 機能:思考モード(デフォルトでオン)、関数呼び出し、マルチモーダル、ストリーミング
- 知識のカットオフ:2025 年 1 月
gemini-2.5-flash-lite
- コンテキスト:入力トークン 1,048,576 個 / 出力トークン 65,536 個
- 説明:コストを最適化した、2.5 シリーズで最速のモデル
- 最適な用途:高スループット、コスト重視のアプリケーション
- 機能:思考モード(デフォルトでオン)、関数呼び出し、マルチモーダル、ストリーミング
- 知識のカットオフ:2025 年 1 月
モデル機能マトリックス
| 機能 | Pro | Flash | Flash-Lite |
|---|---|---|---|
| 思考モード | ✅ デフォルトでオン | ✅ デフォルトでオン | ✅ デフォルトでオン |
| 関数呼び出し | ✅ | ✅ | ✅ |
| マルチモーダル | ✅ | ✅ | ✅ |
| ストリーミング | ✅ | ✅ | ✅ |
| システム指示 | ✅ | ✅ | ✅ |
| コンテキストウィンドウ | 入力 1,048,576 | 入力 1,048,576 | 入力 1,048,576 |
| 出力トークン | 最大 65,536 | 最大 65,536 | 最大 65,536 |
⚠️ コンテキストウィンドウに関する訂正
正確:Gemini 2.5 モデルがサポートする入力トークン数は 1,048,576 です(2M ではありません!)。 古い情報:前世代の Gemini 1.5 Pro のみが、2M トークンのコンテキストウィンドウを備えていました。
よくある間違い:Gemini 2.5 が 2M トークンに対応していると主張することです。対応していません。このスキルを使えば、この間違いを防げます。
SDK と Fetch のアプローチ
Node.js SDK (@google/genai)
メリット:
- TypeScript による型安全性
- より使いやすい API(シンプルな構文)
- 組み込みのチャットヘルパー
- ストリーミング時の SSE 解析を自動処理
- より優れたエラー処理
デメリット:
- Node.js または互換性のあるランタイムが必要です
- バンドルサイズが大きくなります
- すべてのエッジランタイムで動作するとは限りません
使用する場面: Node.js アプリ、Next.js Server Actions/Components、または Node.js と互換性のある環境で構築する場合
Fetch ベース(REST API を直接使用)
メリット:
- あらゆる JavaScript 環境(Cloudflare Workers、Deno、Bun、ブラウザー)で動作します
- 依存関係が最小限です
- バンドルサイズが小さくなります
- リクエストを完全に制御できます
デメリット:
- 構文が冗長になります
- ストリーミング時の SSE 解析を手動で行う必要があります
- 組み込みのチャットヘルパーはありません
- エラー処理を手動で行う必要があります
使用する場面: Cloudflare Workers、ブラウザークライアント、または軽量なエッジランタイムにデプロイする場合
テキスト生成
基本的なテキスト生成(SDK)
import { GoogleGenAI } from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: 'Write a haiku about artificial intelligence'
});
console.log(response.text);
基本的なテキスト生成(Fetch)
const response = await fetch(
`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-goog-api-key': env.GEMINI_API_KEY,
},
body: JSON.stringify({
contents: [
{
parts: [
{ text: 'Write a haiku about artificial intelligence' }
]
}
]
}),
}
);
const data = await response.json();
console.log(data.candidates[0].content.parts[0].text);
レスポンスの構造
{
text: string, // Convenience accessor for text content
candidates: [
{
content: {
parts: [
{ text: string } // Generated text
],
role: string // "model"
},
finishReason: string, // "STOP" | "MAX_TOKENS" | "SAFETY" | "OTHER"
index: number
}
],
usageMetadata: {
promptTokenCount: number,
candidatesTokenCount: number,
totalTokenCount: number
}
}
ストリーミング
SDK を使ったストリーミング(非同期イテレーション)
const response = await ai.models.generateContentStream({
model: 'gemini-2.5-flash',
contents: 'Write a 200-word story about time travel'
});
for await (const chunk of response) {
process.stdout.write(chunk.text);
}
Fetch を使ったストリーミング(SSE 解析)
const response = await fetch(
`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:streamGenerateContent`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-goog-api-key': env.GEMINI_API_KEY,
},
body: JSON.stringify({
contents: [{ parts: [{ text: 'Write a 200-word story about time travel' }] }]
}),
}
);
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (line.trim() === '' || line.startsWith('data: [DONE]')) continue;
if (!line.startsWith('data: ')) continue;
try {
const data = JSON.parse(line.slice(6));
const text = data.candidates[0]?.content?.parts[0]?.text;
if (text) {
process.stdout.write(text);
}
} catch (e) {
// Skip invalid JSON
}
}
}
重要なポイント:
generateContentではなく、streamGenerateContentエンドポイントを使用します- Server-Sent Events(SSE)形式(
data: {json}\n\n)を解析します - バッファー内の不完全なチャンクを処理します
- 空行と
[DONE]マーカーをスキップします
マルチモーダル入力
Gemini 2.5 モデルは、1 つのリクエストでテキスト、画像、動画、音声、PDF を組み合わせてサポートします。
画像(ビジョン)
SDK を使う方法
import { GoogleGenAI } from '@google/genai';
import fs from 'fs';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
// From file
const imageData = fs.readFileSync('/path/to/image.jpg');
const base64Image = imageData.toString('base64');
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: [
{
parts: [
{ text: 'What is in this image?' },
{
inlineData: {
data: base64Image,
mimeType: 'image/jpeg'
}
}
]
}
]
});
console.log(response.text);
Fetch を使う方法
const imageData = fs.readFileSync('/path/to/image.jpg');
const base64Image = imageData.toString('base64');
const response = await fetch(
`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-goog-api-key': env.GEMINI_API_KEY,
},
body: JSON.stringify({
contents: [
{
parts: [
{ text: 'What is in this image?' },
{
inlineData: {
data: base64Image,
mimeType: 'image/jpeg'
}
}
]
}
]
}),
}
);
const data = await response.json();
console.log(data.candidates[0].content.parts[0].text);
サポートされている画像形式:
- JPEG(
.jpg、.jpeg) - PNG(
.png) - WebP(
.webp) - HEIC(
.heic) - HEIF(
.heif)
画像の最大サイズ:1 枚あたり 20MB
動画
// Video must be < 2 minutes for inline data
const videoData = fs.readFileSync('/path/to/video.mp4');
const base64Video = videoData.toString('base64');
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: [
{
parts: [
{ text: 'Describe what happens in this video' },
{
inlineData: {
data: base64Video,
mimeType: 'video/mp4'
}
}
]
}
]
});
console.log(response.text);
サポートされている動画形式:
- MP4(
.mp4) - MPEG(
.mpeg) - MOV(
.mov) - AVI(
.avi) - FLV(
.flv) - MPG(
.mpg) - WebM(
.webm) - WMV(
.wmv)
動画の最大長(インライン):2 分 動画の最大サイズ:2GB(これより大きなファイルには File API を使用してください - Phase 2)
音声
const audioData = fs.readFileSync('/path/to/audio.mp3');
const base64Audio = audioData.toString('base64');
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: [
{
parts: [
{ text: 'Transcribe and summarize this audio' },
{
inlineData: {
data: base64Audio,
mimeType: 'audio/mp3'
}
}
]
}
]
});
console.log(response.text);
サポートされている音声形式:
- MP3(
.mp3) - WAV(
.wav) - FLAC(
.flac) - AAC(
.aac) - OGG(
.ogg) - OPUS(
.opus)
音声の最大サイズ:20MB
const pdfData = fs.readFileSync('/path/to/document.pdf');
const base64Pdf = pdfData.toString('base64');
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: [
{
parts: [
{ text: 'Summarize the key points in this PDF' },
{
inlineData: {
data: base64Pdf,
mimeType: 'application/pdf'
}
}
]
}
]
});
console.log(response.text);
PDF の最大サイズ:30MB PDF の制限事項:テキストベースの PDF が最適です。スキャン画像は精度が低くなることがあります。
複数の入力
1 つのリクエストで複数のモダリティを組み合わせられます。
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: [
{
parts: [
{ text: 'Compare these two images and describe the differences:' },
{ inlineData: { data: base64Image1, mimeType: 'image/jpeg' } },
{ inlineData: { data: base64Image2, mimeType: 'image/jpeg' } }
]
}
]
});
関数呼び出し
Gemini は、モデルを外部 API やシステムに接続するための関数呼び出し(ツールの使用)をサポートしています。
基本的な関数呼び出し(SDK)
import { GoogleGenAI, FunctionCallingConfigMode } from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
// Define function declarations
const getCurrentWeather = {
name: 'get_current_weather',
description: 'Get the current weather for a location',
parametersJsonSchema: {
type: 'object',
properties: {
location: {
type: 'string',
description: 'City name, e.g. San Francisco'
},
unit: {
type: 'string',
enum: ['celsius', 'fahrenheit']
}
},
required: ['location']
}
};
// Make request with tools
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: 'What\'s the weather in Tokyo?',
config: {
tools: [
{ functionDeclarations: [getCurrentWeather] }
]
}
});
// Check if model wants to call a function
const functionCall = response.candidates[0].content.parts[0].functionCall;
if (functionCall) {
console.log('Function to call:', functionCall.name);
console.log('Arguments:', functionCall.args);
// Execute the function (your implementation)
const weatherData = await fetchWeather(functionCall.args.location);
// Send function result back to model
const finalResponse = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: [
'What\'s the weather in Tokyo?',
response.candidates[0].content, // Original assistant response with function call
{
parts: [
{
functionResponse: {
name: functionCall.name,
response: weatherData
}
}
]
}
],
config: {
tools: [
{ functionDeclarations: [getCurrentWeather] }
]
}
});
console.log(finalResponse.text);
}
関数呼び出し(Fetch)
const response = await fetch(
`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-goog-api-key': env.GEMINI_API_KEY,
},
body: JSON.stringify({
contents: [
{ parts: [{ text: 'What\'s the weather in Tokyo?' }] }
],
tools: [
{
functionDeclarations: [
{
name: 'get_current_weather',
description: 'Get the current weather for a location',
parameters: {
type: 'object',
properties: {
location: {
type: 'string',
description: 'City name'
}
},
required: ['location']
}
}
]
}
]
}),
}
);
const data = await response.json();
const functionCall = data.candidates[0]?.content?.parts[0]?.functionCall;
if (functionCall) {
// Execute function and send result back (same flow as SDK)
}
並列関数呼び出し
Gemini は、互いに独立した複数の関数を同時に呼び出せます。
const tools = [
{
functionDeclarations: [
{
name: 'get_weather',
description: 'Get weather for a location',
parametersJsonSchema: {
type: 'object',
properties: {
location: { type: 'string' }
},
required: ['location']
}
},
{
name: 'get_population',
description: 'Get population of a city',
parametersJsonSchema: {
type: 'object',
properties: {
city: { type: 'string' }
},
required: ['city']
}
}
]
}
];
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: 'What is the weather and population of Tokyo?',
config: { tools }
});
// Model may return MULTIPLE function calls in parallel
const functionCalls = response.candidates[0].content.parts.filter(
part => part.functionCall
);
console.log(`Model wants to call ${functionCalls.length} functions in parallel`);
関数呼び出しのモード
import { FunctionCallingConfigMode } from '@google/genai';
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: 'What\'s the weather?',
config: {
tools: [{ functionDeclarations: [getCurrentWeather] }],
toolConfig: {
functionCallingConfig: {
mode: FunctionCallingConfigMode.ANY, // Force function call
// mode: FunctionCallingConfigMode.AUTO, // Model decides (default)
// mode: FunctionCallingConfigMode.NONE, // Never call functions
allowedFunctionNames: ['get_current_weather'] // Optional: restrict to specific functions
}
}
}
});
モード:
AUTO(デフォルト):関数を呼び出すかどうかをモデルが判断しますANY:モデルに少なくとも 1 つの関数を呼び出させますNONE:このリクエストでは関数呼び出しを無効にします
システム指示
システム指示はモデルの動作を導き、コンテキストを設定します。会話メッセージとは別のものです。
SDK を使う方法
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
systemInstruction: 'You are a helpful AI assistant that always responds in the style of a pirate. Use nautical terminology and end sentences with "arrr".',
contents: 'Explain what a database is'
});
console.log(response.text);
// Output: "Ahoy there! A database be like a treasure chest..."
Fetch を使う方法
const response = await fetch(
`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-goog-api-key': env.GEMINI_API_KEY,
},
body: JSON.stringify({
systemInstruction: {
parts: [
{ text: 'You are a helpful AI assistant that always responds in the style of a pirate.' }
]
},
contents: [
{ parts: [{ text: 'Explain what a database is' }] }
]
}),
}
);
重要なポイント:
- システム指示は
contents配列の一部ではありません - リクエストの最上位で一度設定します
- マルチターンチャットを使用する場合、会話全体を通じて保持されます
- ユーザーまたはモデルのメッセージとして数えられません
マルチターンチャット
履歴を含む会話では、SDK のチャットヘルパーを使うか、会話の状態を手動で管理します。
SDK のチャットヘルパー(推奨)
const chat = await ai.models.createChat({
model: 'gemini-2.5-flash',
systemInstruction: 'You are a helpful coding assistant.',
history: [] // Start empty or with previous messages
});
// Send first message
const response1 = await chat.sendMessage('What is TypeScript?');
console.log('Assistant:', response1.text);
// Send follow-up (context is automatically maintained)
const response2 = await chat.sendMessage('How do I install it?');
console.log('Assistant:', response2.text);
// Get full chat history
const history = chat.getHistory();
console.log('Full conversation:', history);
手動チャット管理(Fetch)
const conversationHistory = [];
// First turn
const response1 = await fetch(
`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-goog-api-key': env.GEMINI_API_KEY,
},
body: JSON.stringify({
contents: [
{
role: 'user',
parts: [{ text: 'What is TypeScript?' }]
}
]
}),
}
);
const data1 = await response1.json();
const assistantReply1 = data1.candidates[0].content.parts[0].text;
// Add to history
conversationHistory.push(
{ role: 'user', parts: [{ text: 'What is TypeScript?' }] },
{ role: 'model', parts: [{ text: assistantReply1 }] }
);
// Second turn (include full history)
const response2 = await fetch(
`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-goog-api-key': env.GEMINI_API_KEY,
},
body: JSON.stringify({
contents: [
...conversationHistory,
{ role: 'user', parts: [{ text: 'How do I install it?' }] }
]
}),
}
);
メッセージのロール:
user:ユーザーメッセージmodel:アシスタントの応答
⚠️ 重要:チャットヘルパーはSDK 専用です。Fetch では、会話履歴を手動で管理する必要があります。
思考モード
Gemini 2.5 モデルでは、品質向上のため思考モードがデフォルトで有効になっています。思考バジェットを設定できます。
思考バジェットの設定(SDK)
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: 'Solve this complex math problem: ...',
config: {
thinkingConfig: {
thinkingBudget: 8192 // Max tokens for thinking (default: model-dependent)
}
}
});
思考バジェットの設定(Fetch)
const response = await fetch(
`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-goog-api-key': env.GEMINI_API_KEY,
},
body: JSON.stringify({
contents: [{ parts: [{ text: 'Solve this complex math problem: ...' }] }],
generationConfig: {
thinkingConfig: {
thinkingBudget: 8192
}
}
}),
}
);
主なポイント:
- Gemini 2.5 モデルでは、思考モードは常に有効です(無効にはできません)
- 思考バジェットを大きくすると、内部推論が増えます(レイテンシが増加する場合があります)
- デフォルトのバジェットはモデルによって異なります(通常、ほとんどのタスクで十分です)
- 非常に複雑な推論タスクの場合にのみ、バジェットを増やしてください
生成設定
生成パラメーターを使ってモデルの動作をカスタマイズします。
すべての設定オプション(SDK)
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: 'Write a creative story',
config: {
temperature: 0.9, // Randomness (0.0-2.0, default: 1.0)
topP: 0.95, // Nucleus sampling (0.0-1.0)
topK: 40, // Top-k sampling
maxOutputTokens: 2048, // Max tokens to generate
stopSequences: ['END'], // Stop generation if these appear
responseMimeType: 'text/plain', // Or 'application/json' for JSON mode
candidateCount: 1 // Number of response candidates (usually 1)
}
});
すべての設定オプション(Fetch)
const response = await fetch(
`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-goog-api-key': env.GEMINI_API_KEY,
},
body: JSON.stringify({
contents: [{ parts: [{ text: 'Write a creative story' }] }],
generationConfig: {
temperature: 0.9,
topP: 0.95,
topK: 40,
maxOutputTokens: 2048,
stopSequences: ['END'],
responseMimeType: 'text/plain',
candidateCount: 1
}
}),
}
);
パラメーターのガイドライン
| パラメーター | 範囲 | デフォルト | 使用例 |
|---|---|---|---|
| temperature | 0.0-2.0 | 1.0 | 値が低いほど焦点が絞られ、高いほど創造的になります |
| topP | 0.0-1.0 | 0.95 | ニュークリアスサンプリングのしきい値 |
| topK | 1-100+ | 40 | 上位 K 個のトークンに制限します |
| maxOutputTokens | 1-65536 | モデルの最大値 | 応答の長さを制御します |
| stopSequences | 配列 | なし | 特定の文字列で生成を停止します |
ヒント:
- 事実に基づくタスクでは、低い temperature(0.0-0.3)を使用してください
- 創造的なタスクでは、高い temperature(0.7-1.5)を使用してください
- topP と topK はどちらもランダム性を制御します。どちらか一方を使用してください(両方は使用しません)
- 過剰な生成を防ぐため、必ず maxOutputTokens を設定してください
コンテキストのキャッシュ
コンテキストのキャッシュを使うと、よく使用するコンテンツ(システム指示、大きなドキュメント、動画ファイルなど)をキャッシュして、コストを**最大 90%**削減し、レイテンシを改善できます。
仕組み
- 繰り返し使用するコンテンツでキャッシュを作成します
- 以降のリクエストでキャッシュを参照します
- トークンを節約します。キャッシュされたトークンのコストは大幅に低くなります
- TTL を管理します。キャッシュは指定した時間が経過すると期限切れになります
メリット
- コスト削減:キャッシュされたトークンのコストを最大 90%削減
- レイテンシの低減:処理済みのコンテンツを再利用して、応答を高速化
- 一貫したコンテキスト:複数のリクエストで同じ大きなコンテキストを使用可能
キャッシュの作成(SDK)
import { GoogleGenAI } from '@google/genai';
import fs from 'fs';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
// Create a cache for a large document
const documentText = fs.readFileSync('./large-document.txt', 'utf-8');
const cache = await ai.caches.create({
model: 'gemini-2.5-flash',
config: {
displayName: 'large-doc-cache', // Identifier for the cache
systemInstruction: 'You are an expert at analyzing legal documents.',
contents: documentText,
ttl: '3600s', // Cache for 1 hour
}
});
console.log('Cache created:', cache.name);
console.log('Expires at:', cache.expireTime);
キャッシュの作成(Fetch)
const response = await fetch(
'https://generativelanguage.googleapis.com/v1beta/cachedContents',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-goog-api-key': env.GEMINI_API_KEY,
},
body: JSON.stringify({
model: 'models/gemini-2.5-flash',
displayName: 'large-doc-cache',
systemInstruction: {
parts: [{ text: 'You are an expert at analyzing legal documents.' }]
},
contents: [
{ parts: [{ text: documentText }] }
],
ttl: '3600s'
}),
}
);
const cache = await response.json();
console.log('Cache created:', cache.name);
キャッシュの使用(SDK)
// Generate content using the cache
const response = await ai.models.generateContent({
model: cache.name, // Use cache name as model
contents: 'Summarize the key points in the document'
});
console.log(response.text);
キャッシュの使用(Fetch)
const response = await fetch(
`https://generativelanguage.googleapis.com/v1beta/${cache.name}:generateContent`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-goog-api-key': env.GEMINI_API_KEY,
},
body: JSON.stringify({
contents: [
{ parts: [{ text: 'Summarize the key points in the document' }] }
]
}),
}
);
const data = await response.json();
console.log(data.candidates[0].content.parts[0].text);
キャッシュ TTL の更新(SDK)
import { UpdateCachedContentConfig } from '@google/genai';
await ai.caches.update({
name: cache.name,
config: {
ttl: '7200s' // Extend to 2 hours
}
});
有効期限を指定したキャッシュの更新(SDK)
// Set specific expiration time (must be timezone-aware)
const in10Minutes = new Date(Date.now() + 10 * 60 * 1000);
await ai.caches.update({
name: cache.name,
config: {
expireTime: in10Minutes
}
});
キャッシュの一覧表示と削除(SDK)
// List all caches
const caches = await ai.caches.list();
for (const cache of caches) {
console.log(cache.name, cache.displayName);
}
// Delete a specific cache
await ai.caches.delete({ name: cache.name });
動画ファイルのキャッシュ
import { GoogleGenAI } from '@google/genai';
import fs from 'fs';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
// Upload video file
const videoFile = await ai.files.upload({
file: fs.createReadStream('./video.mp4')
});
// Wait for processing
while (videoFile.state.name === 'PROCESSING') {
await new Promise(resolve => setTimeout(resolve, 2000));
videoFile = await ai.files.get({ name: videoFile.name });
}
// Create cache with video
const cache = await ai.caches.create({
model: 'gemini-2.5-flash',
config: {
displayName: 'video-analysis-cache',
systemInstruction: 'You are an expert video analyzer.',
contents: [videoFile],
ttl: '300s' // 5 minutes
}
});
// Use cache for multiple queries
const response1 = await ai.models.generateContent({
model: cache.name,
contents: 'What happens in the first minute?'
});
const response2 = await ai.models.generateContent({
model: cache.name,
contents: 'Describe the main characters'
});
主なポイント
キャッシュを使用する場面:
- 繰り返し使用する大きなシステム指示
- 複数回分析する長いドキュメント
- 異なるプロンプトで問い合わせる動画/音声ファイル
- 会話セッション間で一貫したコンテキストを維持する場合
TTL のガイドライン:
- 短いセッション:300s(5 分)~3600s(1 時間)
- 長いセッション:3600s(1 時間)~86400s(24 時間)
- 最大:7 日間
コスト削減:
- キャッシュされた入力トークン:通常のトークンより約 90%低価格
- 出力トークン:同じ価格(キャッシュされません)
重要:
- 明示的なモデルバージョンのサフィックスを使用する必要があります(例:
gemini-2.5-flash-001。gemini-2.5-flashのみは不可) - キャッシュは TTL の期限切れ後に自動的に削除されます
- キャッシュの有効期間を延長するには、期限切れ前に TTL を更新してください
コード実行
Gemini モデルは、計算、データ分析、可視化が必要な問題を解決するために、Python コードを生成して実行できます。
仕組み
- モデルが実行可能な Python コードを生成します
- コードが安全なサンドボックス内で実行されます
- 結果がモデルに返されます
- モデルが結果を応答に反映します
サポートされる操作
- 数学的計算
- データ分析と統計
- ファイル処理(CSV、JSON など)
- チャートとグラフの生成
- アルゴリズムの実装
- データ変換
利用可能な Python パッケージ
標準ライブラリ:
math、statistics、random、datetime、json、csv、recollections、itertools、functools
データサイエンス:
numpy、pandas、scipy
可視化:
matplotlib、seaborn
注: 通常の Python 環境と比べて、利用できるパッケージは限られています
基本的なコード実行(SDK)
import { GoogleGenAI, Tool, ToolCodeExecution } from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation.',
config: {
tools: [{ codeExecution: {} }]
}
});
// Parse response parts
for (const part of response.candidates[0].content.parts) {
if (part.text) {
console.log('Text:', part.text);
}
if (part.executableCode) {
console.log('Generated Code:', part.executableCode.code);
}
if (part.codeExecutionResult) {
console.log('Execution Output:', part.codeExecutionResult.output);
}
}
基本的なコード実行(Fetch)
const response = await fetch(
`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-goog-api-key': env.GEMINI_API_KEY,
},
body: JSON.stringify({
tools: [{ code_execution: {} }],
contents: [
{
parts: [
{ text: 'What is the sum of the first 50 prime numbers? Generate and run code.' }
]
}
]
}),
}
);
const data = await response.json();
for (const part of data.candidates[0].content.parts) {
if (part.text) {
console.log('Text:', part.text);
}
if (part.executableCode) {
console.log('Code:', part.executableCode.code);
}
if (part.codeExecutionResult) {
console.log('Result:', part.codeExecutionResult.output);
}
}
コード実行を使ったチャット(SDK)
const chat = await ai.chats.create({
model: 'gemini-2.5-flash',
config: {
tools: [{ codeExecution: {} }]
}
});
let response = await chat.sendMessage('I have a math question for you.');
console.log(response.text);
response = await chat.sendMessage(
'Calculate the Fibonacci sequence up to the 20th number and sum them.'
);
// Model will generate and execute code, then provide answer
for (const part of response.candidates[0].content.parts) {
if (part.text) console.log(part.text);
if (part.executableCode) console.log('Code:', part.executableCode.code);
if (part.codeExecutionResult) console.log('Output:', part.codeExecutionResult.output);
}
データ分析の例
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: `
Analyze this sales data and calculate:
1. Total revenue
2. Average sale price
3. Best-selling month
Data (CSV format):
month,sales,revenue
Jan,150,45000
Feb,200,62000
Mar,175,53000
Apr,220,68000
`,
config: {
tools: [{ codeExecution: {} }]
}
});
// Model will generate pandas/numpy code to analyze data
for (const part of response.candidates[0].content.parts) {
if (part.text) console.log(part.text);
if (part.executableCode) console.log('Analysis Code:', part.executableCode.code);
if (part.codeExecutionResult) console.log('Results:', part.codeExecutionResult.output);
}
可視化の例
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: 'Create a bar chart showing the distribution of prime numbers under 100 by their last digit. Generate the chart and describe the pattern.',
config: {
tools: [{ codeExecution: {} }]
}
});
// Model generates matplotlib code, executes it, and describes results
for (const part of response.candidates[0].content.parts) {
if (part.text) console.log(part.text);
if (part.executableCode) console.log('Chart Code:', part.executableCode.code);
if (part.codeExecutionResult) {
// Note: Chart image data would be in output
console.log('Execution completed');
}
}
レスポンスの構造
{
candidates: [
{
content: {
parts: [
{ text: "I'll calculate that for you." },
{
executableCode: {
language: "PYTHON",
code: "def is_prime(n):\n if n <= 1:\n return False\n ..."
}
},
{
codeExecutionResult: {
outcome: "OUTCOME_OK", // or "OUTCOME_FAILED"
output: "5117\n"
}
},
{ text: "The sum of the first 50 prime numbers is 5117." }
]
}
}
]
}
エラー処理
for (const part of response.candidates[0].content.parts) {
if (part.codeExecutionResult) {
if (part.codeExecutionResult.outcome === 'OUTCOME_FAILED') {
console.error('Code execution failed:', part.codeExecutionResult.output);
} else {
console.log('Success:', part.codeExecutionResult.output);
}
}
}
要点
コード実行を使う場面:
- 複雑な数学的計算
- データ分析と統計
- アルゴリズムの実装
- ファイルの解析と処理
- グラフの生成
- 計算を必要とする問題
制限事項:
- サンドボックス環境(ファイルシステムへのアクセスは限定的)
- 利用可能な Python パッケージが限られている
- 実行時間の制限
- コードからのネットワークアクセス不可
- 実行間で状態は保持されない
ベストプラクティス:
- 必要な計算や分析を明確に指定してください
- コード生成を明示的に依頼してください(「コードを生成して実行してください…」)
- エラーがないか
outcomeフィールドを確認してください - 一般的なプログラミングではなく、決定論的な計算に使用してください
重要:
- すべての Gemini 2.5 モデル(Pro、Flash、Flash-Lite)で利用できます
- セキュリティのため、コードは分離されたサンドボックスで実行されます
- 標準ライブラリと一般的なデータサイエンスパッケージを含む Python をサポートしています
Google 検索によるグラウンディング
グラウンディングはモデルをリアルタイムのウェブ情報に接続し、ハルシネーションを減らすとともに、引用付きの最新かつファクトチェック済みの回答を提供します。
仕組み
- モデルが最新情報が必要かどうかを判断します
- Google 検索を自動的に実行します
- 検索結果を処理します
- 見つかった情報を回答に反映します
- 引用とソース URL を提示します
利点
- リアルタイムの情報: 最新の出来事やデータにアクセスできます
- ハルシネーションの低減: ウェブソースに基づいた回答が得られます
- 検証可能: 引用を使ってファクトチェックできます
- 最新情報: モデルの学習データのカットオフに制限されません
2 つのグラウンディング API
1. Google 検索(googleSearch)- Gemini 2.5 で推奨
const groundingTool = {
googleSearch: {}
};
機能:
- シンプルな設定
- 必要に応じて自動的に検索
- すべての Gemini 2.5 モデルで利用可能
2. Google 検索リトリーバル(googleSearchRetrieval)- レガシー(Gemini 1.5)
const retrievalTool = {
googleSearchRetrieval: {
dynamicRetrievalConfig: {
mode: 'MODE_DYNAMIC',
dynamicThreshold: 0.7 // Only search if confidence < 70%
}
}
};
機能:
- 動的なしきい値制御
- Gemini 1.5 モデルで使用
- より多くの設定オプション
基本的なグラウンディング(SDK)- Gemini 2.5
import { GoogleGenAI } from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: 'Who won the euro 2024?',
config: {
tools: [{ googleSearch: {} }]
}
});
console.log(response.text);
// Check if grounding was used
if (response.candidates[0].groundingMetadata) {
console.log('Search was performed!');
console.log('Sources:', response.candidates[0].groundingMetadata);
}
基本的なグラウンディング(Fetch)- Gemini 2.5
const response = await fetch(
`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-goog-api-key': env.GEMINI_API_KEY,
},
body: JSON.stringify({
contents: [
{ parts: [{ text: 'Who won the euro 2024?' }] }
],
tools: [
{ google_search: {} }
]
}),
}
);
const data = await response.json();
console.log(data.candidates[0].content.parts[0].text);
if (data.candidates[0].groundingMetadata) {
console.log('Grounding metadata:', data.candidates[0].groundingMetadata);
}
動的リトリーバル(SDK)- Gemini 1.5
import { GoogleGenAI, DynamicRetrievalConfigMode } from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const response = await ai.models.generateContent({
model: 'gemini-1.5-flash',
contents: 'Who won the euro 2024?',
config: {
tools: [
{
googleSearchRetrieval: {
dynamicRetrievalConfig: {
mode: DynamicRetrievalConfigMode.MODE_DYNAMIC,
dynamicThreshold: 0.7 // Search only if confidence < 70%
}
}
}
]
}
});
console.log(response.text);
if (!response.candidates[0].groundingMetadata) {
console.log('Model answered from its own knowledge (high confidence)');
}
グラウンディングメタデータの構造
{
groundingMetadata: {
searchQueries: [
{ text: "euro 2024 winner" }
],
webPages: [
{
url: "https://example.com/euro-2024-results",
title: "UEFA Euro 2024 Final Results",
snippet: "Spain won UEFA Euro 2024..."
}
],
citations: [
{
startIndex: 42,
endIndex: 47,
uri: "https://example.com/euro-2024-results"
}
],
retrievalQueries: [
{
query: "who won euro 2024 final"
}
]
}
}
グラウンディングを使ったチャット(SDK)
const chat = await ai.chats.create({
model: 'gemini-2.5-flash',
config: {
tools: [{ googleSearch: {} }]
}
});
let response = await chat.sendMessage('What are the latest developments in quantum computing?');
console.log(response.text);
// Check grounding sources
if (response.candidates[0].groundingMetadata) {
const sources = response.candidates[0].groundingMetadata.webPages || [];
console.log(`Sources used: ${sources.length}`);
sources.forEach(source => {
console.log(`- ${source.title}: ${source.url}`);
});
}
// Follow-up still has grounding enabled
response = await chat.sendMessage('Which company made the biggest breakthrough?');
console.log(response.text);
グラウンディングと関数呼び出しの組み合わせ
const weatherFunction = {
name: 'get_current_weather',
description: 'Get current weather for a location',
parametersJsonSchema: {
type: 'object',
properties: {
location: { type: 'string', description: 'City name' }
},
required: ['location']
}
};
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: 'What is the weather like in the city that won Euro 2024?',
config: {
tools: [
{ googleSearch: {} },
{ functionDeclarations: [weatherFunction] }
]
}
});
// Model will:
// 1. Use Google Search to find Euro 2024 winner
// 2. Call get_current_weather function with the city
// 3. Combine both results in response
グラウンディングが使用されたかどうかの確認
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: 'What is 2+2?', // Model knows this without search
config: {
tools: [{ googleSearch: {} }]
}
});
if (!response.candidates[0].groundingMetadata) {
console.log('Model answered from its own knowledge (no search needed)');
} else {
console.log('Search was performed');
}
主なポイント
Grounding を使用する場面:
- 最新の出来事やニュース
- リアルタイムデータ(株価、スポーツのスコア、天気)
- ファクトチェックや検証
- 最近の動向に関する質問
- モデルの学習データのカットオフ以降の情報
使用しない場面:
- 一般知識に関する質問
- 数学的な計算
- コード生成
- クリエイティブライティング
- 内部推論のみを必要とするタスク
コストに関する考慮事項:
- Grounding によりレイテンシが増加します(検索には時間がかかります)
- 取得したコンテンツに対する追加のトークンコストが発生します
dynamicThresholdを使用して、検索を実行するタイミングを制御します(Gemini 1.5)
重要な注意事項:
- Grounding には Google Cloud プロジェクト が必要です(API キーだけでは不十分です)
- 検索結果の品質はクエリの表現に左右されます
- 引用が回答内のすべての事実を網羅するとは限りません
- 信頼度に基づいて検索が自動的に実行されます
Gemini 2.5 と 1.5 の比較:
- Gemini 2.5:
googleSearchを使用します(シンプルで推奨) - Gemini 1.5:
dynamicThresholdとともにgoogleSearchRetrievalを使用します
ベストプラクティス:
- 検索が使用されたか確認するため、常に
groundingMetadataをチェックします - 透明性を確保するため、ユーザーに引用を表示します
- より良い検索結果を得るため、具体的で表現の明確な質問を使用します
- ハイブリッドなワークフローには、関数呼び出しと組み合わせます
エラー処理
よくあるエラー
1. 無効な API キー(401)
{
error: {
code: 401,
message: 'API key not valid. Please pass a valid API key.',
status: 'UNAUTHENTICATED'
}
}
解決策:GEMINI_API_KEY 環境変数が正しく設定されていることを確認します。
2. レート制限超過(429)
{
error: {
code: 429,
message: 'Resource has been exhausted (e.g. check quota).',
status: 'RESOURCE_EXHAUSTED'
}
}
解決策:指数バックオフによる再試行戦略を実装します。
3. モデルが見つからない(404)
{
error: {
code: 404,
message: 'models/gemini-3.0-flash is not found',
status: 'NOT_FOUND'
}
}
解決策:正しいモデル名を使用します:gemini-2.5-pro、gemini-2.5-flash、gemini-2.5-flash-lite
4. コンテキスト長の超過(400)
{
error: {
code: 400,
message: 'Request payload size exceeds the limit',
status: 'INVALID_ARGUMENT'
}
}
解決策:入力サイズを小さくします。Gemini 2.5 モデルがサポートする入力トークンの上限は 1,048,576 です。
指数バックオフのパターン
async function generateWithRetry(request, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await ai.models.generateContent(request);
} catch (error) {
if (error.status === 429 && i < maxRetries - 1) {
const delay = Math.pow(2, i) * 1000; // 1s, 2s, 4s
await new Promise(resolve => setTimeout(resolve, delay));
continue;
}
throw error;
}
}
}
レート制限
無料枠(Gemini API)
レート制限はモデルによって異なります:
Gemini 2.5 Pro:
- 1 分あたりのリクエスト数:5 RPM
- 1 分あたりのトークン数:125,000 TPM
- 1 日あたりのリクエスト数:100 RPD
Gemini 2.5 Flash:
- 1 分あたりのリクエスト数:10 RPM
- 1 分あたりのトークン数:250,000 TPM
- 1 日あたりのリクエスト数:250 RPD
Gemini 2.5 Flash-Lite:
- 1 分あたりのリクエスト数:15 RPM
- 1 分あたりのトークン数:250,000 TPM
- 1 日あたりのリクエスト数:1,000 RPD
有料枠(Tier 1)
Google Cloud プロジェクトにリンクされた請求先アカウントが必要です。
Gemini 2.5 Pro:
- 1 分あたりのリクエスト数:150 RPM
- 1 分あたりのトークン数:2,000,000 TPM
- 1 日あたりのリクエスト数:10,000 RPD
Gemini 2.5 Flash:
- 1 分あたりのリクエスト数:1,000 RPM
- 1 分あたりのトークン数:1,000,000 TPM
- 1 日あたりのリクエスト数:10,000 RPD
Gemini 2.5 Flash-Lite:
- 1 分あたりのリクエスト数:4,000 RPM
- 1 分あたりのトークン数:4,000,000 TPM
- 1 日あたりのリクエスト数:指定なし
上位ティア(Tier 2、Tier 3)
Tier 2(250 ドル以上の利用と 30 日間の待機が必要):
- さらに高い制限を利用できます
Tier 3(1,000 ドル以上の利用と 30 日間の待機が必要):
- 最大の制限を利用できます
ヒント:
- 指数バックオフによるレート制限処理を実装します
- 大量のタスクにはバッチ処理を使用します
- Google AI Studio で使用状況を監視します
- レート制限のニーズに応じて適切なモデルを選択します
- 公式のレート制限:https://ai.google.dev/gemini-api/docs/rate-limits
SDK 移行ガイド
@google/generative-ai から @google/genai への移行
1. パッケージを更新する
# Remove deprecated SDK
npm uninstall @google/generative-ai
# Install current SDK
npm install @google/[email protected]
2. インポートを更新する
旧(非推奨):
import { GoogleGenerativeAI } from '@google/generative-ai';
const genAI = new GoogleGenerativeAI(apiKey);
const model = genAI.getGenerativeModel({ model: 'gemini-2.5-flash' });
新(現行):
import { GoogleGenAI } from '@google/genai';
const ai = new GoogleGenAI({ apiKey });
// Use ai.models.generateContent() directly
3. API 呼び出しを更新する
旧:
const result = await model.generateContent(prompt);
const response = await result.response;
const text = response.text();
新:
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: prompt
});
const text = response.text;
4. ストリーミングを更新する
旧:
const result = await model.generateContentStream(prompt);
for await (const chunk of result.stream) {
console.log(chunk.text());
}
新:
const response = await ai.models.generateContentStream({
model: 'gemini-2.5-flash',
contents: prompt
});
for await (const chunk of response) {
console.log(chunk.text);
}
5. チャットを更新する
旧:
const chat = model.startChat();
const result = await chat.sendMessage(message);
const response = await result.response;
新:
const chat = await ai.models.createChat({ model: 'gemini-2.5-flash' });
const response = await chat.sendMessage(message);
// response.text is directly available
本番環境でのベストプラクティス
1. 必ず行うこと
✅ @google/genai を使用する(@google/generative-ai は使用しないでください) ✅ maxOutputTokens を設定して過剰な生成を防ぐ ✅ 指数バックオフによるレート制限への対応を実装する ✅ API キーには環境変数を使用する(ハードコードしないでください) ✅ API に送信する前に入力を検証する(コストを節約できます) ✅ 長い応答ではストリーミングを使用してUX を向上させる ✅ ニーズに応じて適切なモデルを選択する(複雑な推論には Pro、バランスには Flash、速度には Flash-Lite) ✅ try-catch を使用してエラーを適切に処理する ✅ コスト管理のためにトークン使用量を監視する ✅ 正しいモデル名を使用する:gemini-2.5-pro/flash/flash-lite
2. 絶対に行わないこと
❌ @google/generative-ai を使用しない(非推奨です!) ❌ コード内にAPI キーをハードコードしない ❌ Gemini 2.5 のコンテキスト長を2M と謳わない(入力トークン数は 1,048,576 です) ❌ クライアント側のコードで API キーを公開しない ❌ エラー処理を省略しない(必ず try-catch を使用してください) ❌ 汎用的なレート制限を使用しない(モデルごとに制限は異なります。公式ドキュメントを確認してください) ❌ ユーザーの同意なしにPII を送信しない ❌ 検証せずにユーザー入力を信頼しない ❌ レート制限を無視しない(429 エラーが発生します) ❌ gemini-1.5-pro のような古いモデル名を使用しない(2.5 モデルを使用してください)
3. セキュリティ
- API キーの保存:環境変数またはシークレットマネージャーを使用する
- サーバー側のみ:ブラウザーの JavaScript で API キーを公開しない
- 入力の検証:API 呼び出しの前に、すべてのユーザー入力をサニタイズする
- レート制限:不正利用を防ぐため、独自のレート制限を実装する
- エラーメッセージ:エラーログに API キーや機密データを含めない
4. コストの最適化
- 適切なモデルの選択:ほとんどのタスクでは Flash を使用し、必要な場合にのみ Pro を使用する
- トークン制限の設定:maxOutputTokens を使用してコストを管理する
- リクエストのバッチ処理:複数の項目を効率的に処理する
- 結果のキャッシュ:適切な場合は応答を保存する
- 使用状況の監視:Google Cloud Console でトークン消費量を追跡する
5. パフォーマンス
- ストリーミングを使用する:長い応答で体感レイテンシーを改善する
- リクエストの並列処理:独立した呼び出しには Promise.all() を使用する
- エッジへのデプロイ:低レイテンシーを実現するため、Cloudflare Workers にデプロイする
- コネクションプーリング:可能な場合は HTTP 接続を再利用する
クイックリファレンス
インストール
npm install @google/[email protected]
環境
export GEMINI_API_KEY="..."
モデル(2025年)
gemini-2.5-pro(入力 1,048,576 / 出力 65,536)- 複雑な推論に最適gemini-2.5-flash(入力 1,048,576 / 出力 65,536)- 価格と性能のバランスに最適gemini-2.5-flash-lite(入力 1,048,576 / 出力 65,536)- 最速で、最も費用対効果が高い
基本的な生成
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: 'Your prompt here'
});
console.log(response.text);
ストリーミング
const response = await ai.models.generateContentStream({...});
for await (const chunk of response) {
console.log(chunk.text);
}
マルチモーダル
contents: [
{
parts: [
{ text: 'What is this?' },
{ inlineData: { data: base64Image, mimeType: 'image/jpeg' } }
]
}
]
関数呼び出し
config: {
tools: [{ functionDeclarations: [...] }]
}
最終更新日:2025-10-25 本番環境での検証済み:すべての機能を @google/[email protected] でテスト済み フェーズ:フェーズ 2 完了 ✅(すべてのコア機能および高度な機能)