mcpField
G
google-gemini-api

google-gemini-api

github.com/secondsky開発247129 回インストール6 週間前に更新
リポジトリ

google-gemini-api について

JavaScript SDK の @google/genai を使う Google Gemini API 開発者向けガイドです。生成、ストリーミング、マルチモーダル入力、関数呼び出し、モデル選択、移行、問題解決を扱います。

主な機能

  1. 01テキスト生成とストリーミング
  2. 02画像、動画、音声、PDF の入力
  3. 03関数呼び出しとチャットのパターン
  4. 04モデル選択と設定
  5. 05移行ガイドとエラーリファレンス

活用シーン

  1. 01@google/generative-ai からの移行
  2. 02Gemini モデルによるコンテンツ生成
  3. 03マルチモーダル入力の分析
  4. 04関数呼び出しワークフローの実装

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/secondsky/claude-skills --skill google-gemini-api

インストール後、Claude Code で/google-gemini-apiを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

references/
code-execution-patterns.md
context-caching-guide.md
error-catalog.md
function-calling-patterns.md
generation-config.md
grounding-guide.md
models-guide.md
multimodal-guide.md
sdk-migration-guide.md
streaming-patterns.md
thinking-mode-guide.md
top-errors.md
scripts/
check-versions.sh
templates/
basic-usage.ts
cloudflare-worker.ts
code-execution.ts
combined-advanced.ts
context-caching.ts
function-calling-basic.ts
function-calling-parallel.ts
grounding-search.ts
multimodal-image.ts
multimodal-video-audio.ts
package.json
streaming-chat.ts
streaming-fetch.ts
text-generation-basic.ts
text-generation-fetch.ts
thinking-mode.ts

詳細

Google Gemini API - 完全ガイド

パッケージ:@google/[email protected](⚠️ @google/generative-ai ではありません) 最終更新日:2025-11-21


⚠️ SDK 移行に関する重大な警告

非推奨の SDK:@google/generative-ai(2025 年 11 月 30 日に提供終了) 現在の SDK:@google/genai v1.27 以降

@google/generative-ai を使用したコードを見つけた場合、そのコードは古いものです!

完全な移行手順については、references/sdk-migration-guide.md を読み込んでください。


クイックスタート

インストール

✅ 正しい SDK:

bun add @google/[email protected]

❌ 間違い(非推奨):

bun add @google/generative-ai  # DO NOT USE!
環境設定
export GEMINI_API_KEY="your-api-key"
初めてのテキスト生成
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);

完全なテンプレート:templates/basic-usage.ts を参照してください。


現在のモデル(2025 年)

gemini-2.5-flash ⭐ 推奨
  • 最適な用途:汎用 AI、大規模な本番環境、エージェント型ワークフロー
  • 入力トークン数:1,048,576(1M。2M ではありません!)
  • 出力トークン数:65,536
  • レート制限(無料):10 RPM、250k TPM
  • 料金:入力は 1M トークンあたり $0.075、出力は 1M トークンあたり $0.30
  • 機能:思考モード、関数呼び出し、マルチモーダル、ストリーミング
gemini-2.5-pro
  • 最適な用途:複雑な推論、コード生成、数学/STEM
  • 入力トークン数:1,048,576
  • 出力トークン数:65,536
  • レート制限(無料):5 RPM、125k TPM
  • 料金:入力は 1M トークンあたり $1.25、出力は 1M トークンあたり $5
gemini-2.5-flash-lite
  • 最適な用途:大量処理、低レイテンシ、コスト重視のタスク
  • 入力トークン数:1,048,576
  • 出力トークン数:65,536
  • レート制限(無料):15 RPM、250k TPM
  • 料金:入力は 1M トークンあたり $0.01、出力は 1M トークンあたり $0.04
  • ⚠️ 制限事項:関数呼び出しとコード実行には対応していません

⚠️ よくある間違い:Gemini 2.5 のトークン数が 2M だとすること。2M ではありません。1,048,576(1M)です。

詳細なモデル比較と選択基準については、references/models-guide.md を読み込んでください。


テキスト生成

基本的な生成
const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: 'Write a haiku about programming'
});

console.log(response.text);
設定を使用する場合
const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: 'Explain AI',
  generationConfig: {
    temperature: 0.7,        // 0.0-2.0, default 1.0
    topP: 0.95,             // 0.0-1.0
    topK: 40,               // 1-100
    maxOutputTokens: 1024,
    stopSequences: ['END']
  }
});

パラメーターの完全なリファレンスと調整方法については、references/generation-config.md を読み込んでください。


ストリーミング

const stream = await ai.models.generateContentStream({
  model: 'gemini-2.5-flash',
  contents: 'Write a long story'
});

for await (const chunk of stream) {
  process.stdout.write(chunk.text);
}

Fetch/SSE の実装パターン(Cloudflare Workers)については、references/streaming-patterns.md を読み込んでください。


マルチモーダル入力

画像
const imageData = Buffer.from(imageBytes).toString('base64');

const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: [
    { text: 'What is in this image?' },
    {
      inlineData: {
        mimeType: 'image/jpeg',  // or image/png, image/webp
        data: imageData
      }
    }
  ]
});
動画、音声、PDF

同じパターンを使用し、適切な mimeType を指定します。

  • 動画:video/mp4、video/mpeg、video/mov
  • 音声:audio/wav、audio/mp3、audio/flac
  • PDF:application/pdf

形式の仕様、サイズ制限、ベストプラクティスについては、references/multimodal-guide.md を読み込んでください。


関数呼び出し

基本パターン
const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: 'What is the weather in San Francisco?',
  tools: [{
    functionDeclarations: [{
      name: 'getWeather',
      description: 'Get current weather for a location',
      parameters: {
        type: 'object',
        properties: {
          location: { type: 'string', description: 'City name' },
          unit: { type: 'string', enum: ['celsius', 'fahrenheit'] }
        },
        required: ['location']
      }
    }]
  }]
});

// Handle function call
const call = response.functionCalls?.[0];
if (call) {
  const result = await getWeather(call.args);

  // Send result back to model
  const final = await ai.models.generateContent({
    model: 'gemini-2.5-flash',
    contents: [
      ...response.contents,
      {
        functionResponse: {
          name: call.name,
          response: result
        }
      }
    ]
  });

  console.log(final.text);
}
並列関数呼び出し

Gemini は複数の関数を同時に呼び出せます。

const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: 'What is the weather in SF and NY?',
  tools: [{ functionDeclarations: [getWeatherDeclaration] }]
});

// Process all function calls in parallel
const results = await Promise.all(
  response.functionCalls.map(call =>
    getWeather(call.args).then(result => ({
      name: call.name,
      response: result
    }))
  )
);

// Send all results back
const final = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: [
    ...response.contents,
    ...results.map(r => ({ functionResponse: r }))
  ]
});

呼び出しモード(AUTO/ANY/NONE)と合成パターンについては、references/function-calling-patterns.md を読み込んでください。


マルチターンチャット

const chat = ai.models.startChat({
  model: 'gemini-2.5-flash',
  systemInstruction: 'You are a helpful programming assistant',
  history: []
});

let response = await chat.sendMessage('Hello!');
console.log(response.text);

response = await chat.sendMessage('Explain async/await');
console.log(response.text);

// Get full history
console.log(chat.getHistory());

システム指示

モデルに永続的な指示を設定します。

const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  systemInstruction: 'You are a pirate. Always respond in pirate speak.',
  contents: 'What is the weather today?'
});

思考モード

Gemini 2.5 モデルには、組み込みの思考モードが含まれています(常に有効)。複雑なタスクに合わせて思考予算を設定します。

const response = await ai.models.generateContent({
  model: 'gemini-2.5-flash',
  contents: 'Solve this math problem: If x + 2y = 10 and 3x - y = 4, what is x?',
  generationConfig: {
    thinkingConfig: {
      thinkingBudget: 8192  // Max tokens for internal reasoning
    }
  }
});

用途:複雑な数学、論理パズル、多段階の推論、コードのデバッグ

思考予算の最適化については、references/thinking-mode-guide.md を読み込んでください。


重大なエラー上位 5 件

エラー 1:非推奨の SDK を使用している

エラー:非推奨に関する警告、または古い API

解決策:@google/generative-ai ではなく、@google/genai を使用してください。

npm uninstall @google/generative-ai
bun add @google/[email protected]

エラー 2:API キーが無効(401)

エラー:API key not valid

解決策:環境変数を確認してください。

export GEMINI_API_KEY="your-key"

エラー 3:モデルが見つからない(404)

エラー:models/gemini-3.0-flash is not found

解決策:正しいモデル名(2025 年版)を使用してください。

'gemini-2.5-pro'
'gemini-2.5-flash'
'gemini-2.5-flash-lite'

エラー 4:コンテキスト長の超過(400)

エラー:Request payload size exceeds the limit

解決策:入力上限は 1,048,576 トークン(1M。2M ではありません) です。大きな入力にはコンテキストキャッシュを使用してください。

キャッシュの実装については、references/context-caching-guide.md を読み込んでください。


エラー 5:レート制限超過(429)

エラー:Resource has been exhausted

解決策:指数バックオフを実装します

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;
    }
  }
}

22 件すべてのエラーを見る:完全なエラーカタログと解決策を確認するには、references/error-catalog.md を読み込みます。

迅速なデバッグ:デバッグチェックリストを確認するには、references/top-errors.md を読み込みます。


リファレンスを読み込むタイミング

特定の機能について詳細なガイダンスが必要な場合は、リファレンスファイルを読み込みます。

コア機能(必要に応じて読み込み)
  • SDK の移行:@google/generative-ai から移行する場合は、references/sdk-migration-guide.md を読み込みます
  • モデルの選択:Pro/Flash/Flash-Lite のいずれかを選ぶ場合は、references/models-guide.md を読み込みます
  • エラーのデバッグ:エラーが発生した場合は、references/error-catalog.md または references/top-errors.md を読み込みます
高度な機能(実装時に読み込み)
  • コンテキストのキャッシュ:大容量または繰り返し入力するデータのコストを最適化する場合は、references/context-caching-guide.md を読み込みます
  • コード実行:計算や分析のために Python コードの実行を有効にする場合は、references/code-execution-patterns.md を読み込みます
  • グラウンディング(Google Search):モデルをリアルタイムのウェブ情報に接続する場合は、references/grounding-guide.md を読み込みます
  • ストリーミングの実装:Cloudflare Workers 向けに SSE パーサーを実装する場合は、references/streaming-patterns.md を読み込みます
  • 関数呼び出しモード:AUTO/ANY/NONE モードまたは合成パターンを使用する場合は、references/function-calling-patterns.md を読み込みます
  • マルチモーダル形式:画像/動画/音声/PDF を扱う場合は、references/multimodal-guide.md を読み込みます(形式仕様、サイズ制限)
  • 生成設定の調整:temperature/topP/topK パラメーターを微調整する場合は、references/generation-config.md を読み込みます
  • Thinking モードの設定:複雑な推論に向けて Thinking の予算を最適化する場合は、references/thinking-mode-guide.md を読み込みます

一般的なルール:SKILL.md にはクイックスタートと主なエラーが記載されています。詳細な解説、詳しいパターン、特定機能のトラブルシューティングが必要な場合は、リファレンスを読み込みます。


同梱リソース

テンプレート(templates/):

  • basic-usage.ts - すべての機能を網羅した完全な例(133 行)

リファレンス(references/):

  • error-catalog.md - 解決策付きの、文書化された 7 件すべてのエラー(231 行)
  • top-errors.md - よくある 22 件のエラー向けの迅速なデバッグチェックリスト(305 行)
  • sdk-migration-guide.md - 非推奨の SDK からの完全な移行ガイド(236 行)
  • models-guide.md - 詳細なモデル比較と選択ガイド(247 行)
  • context-caching-guide.md - キャッシュによるコスト最適化(374 行)
  • code-execution-patterns.md - Python コード実行ガイド(482 行)
  • grounding-guide.md - Google Search との統合(603 行)
  • streaming-patterns.md - Cloudflare Workers 向け SSE の実装(82 行)
  • function-calling-patterns.md - 高度な関数呼び出しパターン(60 行)
  • multimodal-guide.md - 形式仕様と制限(59 行)
  • generation-config.md - パラメーター調整のリファレンス(58 行)
  • thinking-mode-guide.md - Thinking の予算最適化(60 行)

他のスキルとの統合

このスキルは、次のスキルと組み合わせて使用できます。

  • cloudflare-worker-base → Cloudflare Workers にデプロイ
  • ai-sdk-core → Vercel AI SDK との統合
  • openai-api → マルチプロバイダーの AI セットアップ
  • google-gemini-embeddings → テキスト埋め込み

追加リソース

公式ドキュメント:


本番環境でのテスト済み用途:AI チャットボット、コンテンツ生成、マルチモーダル分析 最終更新日:2025-10-25 トークン削減量:約 65%(API ドキュメントと例を削減)

コメント