メインコンテンツへスキップ

概要

Google は @google/genai(JavaScript / TypeScript)と google-genai(Python)の 2 つの公式 SDK を提供しており、Gemini API のすべてのエンドポイントをカバーしています。baseUrl を AIHubMix ゲートウェイに向け、プラットフォームの API Key に置き換えるだけで、ネイティブ SDK を通じて Interactions、Embeddings、Context Caching など OpenAI 互換レイヤーではカバーされない機能を呼び出すことができます。ビジネスコードの変更は一切不要です。

クイックスタート

インストール

npm install @google/genai
# >= 2.0.0 が必要です。latest のインストールを推奨
Interactions API は @google/genai >= 2.0.0 または google-genai >= 2.0.0 が必要です。古いバージョンの SDK からのリクエストは Google バックエンドに拒否されます(legacy Interactions schema no longer supported)。

クライアントの初期化

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({
  apiKey: "sk-***", // AIHubMix で生成した API Key に置き換えてください
  httpOptions: {
    baseUrl: "https://aihubmix.com/gemini",
  },
});
baseUrlhttps://aihubmix.com/gemini に固定されており、OpenAI 互換エンドポイント https://aihubmix.com/v1 とは異なります。

Interactions API

Interactions は Gemini の新世代推論インターフェースで、構造化された Interaction オブジェクトを返し、テキスト生成、ネイティブ画像生成(Nano Banana)、マルチステップ推論をサポートします。現在は同期モードinteractions.create())をサポートしています。非同期モード(Background Interactions:get / cancel / delete)は近日公開予定です。

テキスト生成

interactions.create() を呼び出して推論を開始します。返される Interaction オブジェクトは output_text 便利プロパティを提供し、モデルの最後のテキスト出力を直接取得できます。
const interaction = await ai.interactions.create({
  model: "gemini-3.5-flash",
  input: "用一句话解释量子计算",
});

console.log(interaction.output_text);
console.log(interaction.usage);
// { total_tokens, total_input_tokens, total_output_tokens, ... }

ネイティブ画像生成

response_format を設定して出力モダリティを画像に構成します。返される Interaction オブジェクトは output_image 便利プロパティを提供し、その data フィールドには Base64 エンコードされた画像データが含まれます。
  • 推奨モデル gemini-3.1-flash-image(Nano Banana 2、汎用画像生成モデル)。
  • response_modalities の値は小文字['text', 'image'] でなければなりません。大文字は generateContent API の書き方であり、Interactions API では 400 が返されます。
  • delivery: 'inline' を渡さないでください(400 Image delivery mode is not supported)。Interactions API はデフォルトで inline 方式で画像データを返します。
response_format パラメータ:
フィールド説明使用可能な値
type出力タイプ"image"
aspect_ratioアスペクト比"1:1" "3:4" "4:3" "9:16" "16:9"
image_size出力解像度"1K" "2K" "4K"
mime_type画像フォーマット"image/png" "image/jpeg"
import fs from "node:fs";

const interaction = await ai.interactions.create({
  model: "gemini-3.1-flash-image",
  input: "A translucent banana-shaped glass lamp on a white desk, soft studio lighting.",
  response_modalities: ["text", "image"],
  response_format: { type: "image", aspect_ratio: "1:1", image_size: "1K" },
});

// 方法 1:output_image 便利プロパティ(最後に生成された画像を取得)
if (interaction.output_image?.data) {
  fs.writeFileSync("output.png", Buffer.from(interaction.output_image.data, "base64"));
}

// 方法 2:steps を反復処理、マルチステップ混合出力に適用
for (const step of interaction.steps ?? []) {
  for (const block of step.content ?? []) {
    if (block.type === "image" && block.data) {
      fs.writeFileSync("output.png", Buffer.from(block.data, "base64"));
    }
  }
}

ストリーミング出力

stream: true を渡して Server-Sent Events(SSE)ストリーミング転送を有効にします。イベントは以下の順序で到着します:
interaction.created → status_update → step.start → step.delta → step.stop → interaction.completed
増分テキストは event.delta.text から取得され、イベントタイプフィールドは event_type です。
JavaScript
const stream = await ai.interactions.create({
  model: "gemini-3.5-flash",
  input: "写一首关于月亮的俳句",
  stream: true,
});

for await (const event of stream) {
  if (event.event_type === "step.delta" && event.delta?.type === "text") {
    process.stdout.write(event.delta.text);
  }
  if (event.event_type === "interaction.completed") {
    console.log("\nUsage:", JSON.stringify(event.interaction?.usage));
  }
}

Embeddings

embedContent エンドポイントを通じて、テキストまたはマルチモーダルコンテンツのベクトル表現(embedding)を取得します。
OpenAI 互換の /v1/embeddings エンドポイントが必要な場合は、ベクトル埋め込み を参照してください。

embedContent

const response = await ai.models.embedContent({
  model: "gemini-embedding-2-preview",
  contents: "What is the meaning of life?",
  config: {
    outputDimensionality: 768, // オプション:出力次元を指定(128-3072)、デフォルト 3072
  },
});

console.log("dimensions:", response.embeddings[0].values.length); // 768

バッチ Embeddings 取得

embedContentcontents パラメータに Content 配列を渡すことで、1 回の呼び出しで複数のテキストの embedding を取得できます:
JavaScript
const response = await ai.models.embedContent({
  model: "gemini-embedding-2-preview",
  contents: [
    { parts: [{ text: "第一段文本" }] },
    { parts: [{ text: "第二段文本" }] },
  ],
});

console.log("count:", response.embeddings.length); // 2
for (const emb of response.embeddings) {
  console.log("dimensions:", emb.values.length);
}

利用可能なモデルとパラメータ

モデル入力トークン上限デフォルト出力次元入力モダリティ説明
gemini-embedding-2-preview8,1923,072(推奨 768)テキスト、画像、動画、音声、PDF最新のマルチモーダル埋め込みモデル、outputDimensionality サポート
gemini-embedding-0012,0483,072テキストのみ前世代のテキスト埋め込みモデル、taskType サポート
gemini-embedding-001config.taskType を通じて埋め込みの用途を指定し、特定のダウンストリームタスクのベクトル品質を最適化できます:
taskType用途
SEMANTIC_SIMILARITYセマンティック類似度計算
RETRIEVAL_DOCUMENTドキュメントインデックス(検索対象側)
RETRIEVAL_QUERY検索クエリ(検索側)
CLASSIFICATIONテキスト分類
CLUSTERINGテキストクラスタリング
gemini-embedding-2-previewtaskType パラメータをサポートしていません。代わりにプロンプト内のプレフィックスでタスクタイプを指定します(例:search_query: ... または search_document: ...)。

Context Caching(明示的キャッシュ)

明示的キャッシュ(Explicit Caching)により、開発者は CachedContent オブジェクトを手動で作成、照会、参照、削除でき、複数のリクエスト間で同じ長いコンテキストを再利用するシナリオに適しています。暗黙的キャッシュとは異なり、明示的キャッシュはアプリケーション側がライフサイクルを主体的に管理します。
明示的キャッシュは generateContent API にのみ適用されます。Interactions API は暗黙的キャッシュのみをサポートしています。
ストレージ価格が設定されていないモデルは、ゲートウェイがキャッシュ作成リクエストをブロックします(context caching is not available for model)。これはストレージ料金の漏れを防ぐためです。主要モデル(gemini-2.5-flash、gemini-2.5-pro など)はすべて設定済みです。

CachedContent の作成

caches.create() を通じてキャッシュを作成します。ttl(Time-To-Live)でキャッシュの有効期間を制御し、期限切れ後は自動的にクリアされます。
const longDocument = "需要反復引用的長文本内容...".repeat(500);

const cache = await ai.caches.create({
  model: "gemini-3.5-flash",
  config: {
    contents: longDocument,
    ttl: "300s",
  },
});

console.log("CachedContent name:", cache.name);
// 形式:cachedContents/xxx

generateContent でキャッシュを参照

cache.namecachedContent(JS)または cached_content(Python)パラメータに渡すことで、推論時にキャッシュをヒットさせることができます。ヒットしたトークン数は usageMetadata.cachedContentTokenCount に反映されます。
const response = await ai.models.generateContent({
  model: "gemini-3.5-flash",
  contents: "请总结上述文档的核心观点",
  config: { cachedContent: cache.name },
});

console.log(response.text);
console.log("cached tokens:", response.usageMetadata?.cachedContentTokenCount);

照会と削除

// CachedContent メタデータの照会
const info = await ai.caches.get({ name: cache.name });
console.log("model:", info.model, "expireTime:", info.expireTime);

// キャッシュの削除
await ai.caches.delete({ name: cache.name });

サポート済み機能マトリックス

機能ステータス説明
generateContent非ストリーミング + ストリーミング
systemInstruction / generationConfigtemperature、maxOutputTokens など
Structured Output(responseSchemaJSON mode
Function CallingfunctionDeclarations ツール宣言
thinkingConfig思考チェーン出力
マルチモーダル入力画像 / 音声 / 動画 / PDF via inlineData + Files API
Google Search Grounding検索拡張
countTokensトークンカウント
Imagen(generateImagesImagen 3 画像生成
Veo(generateVideos動画生成
TTS音声合成出力
Files API大容量ファイルのアップロードと参照
Interactions API新世代推論インターフェース(テキスト + Nano Banana 画像生成)
Embeddings(embedContentネイティブベクトル埋め込み
Context Caching CRUD明示的キャッシュ管理
Live API(WebSocket)未対応

よくある質問

SDK バージョンが低すぎます。@google/genai は >= 2.0.0、google-genai は >= 2.0.0 が必要です。npm install @google/genai@latest または pip install -U google-genai を実行して最新バージョンにアップグレードしてください。
一部の初期モデル名(gemini-2.5-flash-image-preview など)は Interactions API ではすでに廃止されています。gemini-3.1-flash-image(Nano Banana 2)など、現在利用可能なモデル識別子を使用してください。generateContent API は影響を受けません。
Interactions API の response_modalities の値は小文字("text""image")でなければなりません。大文字の "TEXT" / "IMAGE"generateContent API の書き方であり、Interactions API では受け付けられません。
使用できません。SDK の vertexai: true モードは GCP OAuth + project / location パラメータを必要とし、apiKey とは相互排他的です(SDK が Project/location and API key are mutually exclusive をスローします)。AIHubMix 経由で接続する場合は Gemini Developer API 形式を使用するだけで十分です。バックエンドが自動的にルーティングします。
ゲートウェイは、ストレージ価格が設定されていないモデルの caches.create() リクエストをブロックし、ストレージ料金の漏れを防ぎます。主要モデル(gemini-2.5-flash、gemini-2.5-pro など)はすべて設定済みです。このエラーが発生した場合は、そのモデルが明示的キャッシュをサポートしているか確認してください。

最終更新日:2026-07-07